]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Lex/PPLexerChange.cpp
MFV r331708:
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Lex / PPLexerChange.cpp
1 //===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements pieces of the Preprocessor interface that manage the
11 // current lexer stack.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "clang/Lex/Preprocessor.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "clang/Lex/HeaderSearch.h"
19 #include "clang/Lex/LexDiagnostic.h"
20 #include "clang/Lex/MacroInfo.h"
21 #include "clang/Lex/PTHManager.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/Path.h"
26 using namespace clang;
27
28 PPCallbacks::~PPCallbacks() {}
29
30 //===----------------------------------------------------------------------===//
31 // Miscellaneous Methods.
32 //===----------------------------------------------------------------------===//
33
34 /// isInPrimaryFile - Return true if we're in the top-level file, not in a
35 /// \#include.  This looks through macro expansions and active _Pragma lexers.
36 bool Preprocessor::isInPrimaryFile() const {
37   if (IsFileLexer())
38     return IncludeMacroStack.empty();
39
40   // If there are any stacked lexers, we're in a #include.
41   assert(IsFileLexer(IncludeMacroStack[0]) &&
42          "Top level include stack isn't our primary lexer?");
43   return std::none_of(
44       IncludeMacroStack.begin() + 1, IncludeMacroStack.end(),
45       [&](const IncludeStackInfo &ISI) -> bool { return IsFileLexer(ISI); });
46 }
47
48 /// getCurrentLexer - Return the current file lexer being lexed from.  Note
49 /// that this ignores any potentially active macro expansions and _Pragma
50 /// expansions going on at the time.
51 PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
52   if (IsFileLexer())
53     return CurPPLexer;
54
55   // Look for a stacked lexer.
56   for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
57     if (IsFileLexer(ISI))
58       return ISI.ThePPLexer;
59   }
60   return nullptr;
61 }
62
63
64 //===----------------------------------------------------------------------===//
65 // Methods for Entering and Callbacks for leaving various contexts
66 //===----------------------------------------------------------------------===//
67
68 /// EnterSourceFile - Add a source file to the top of the include stack and
69 /// start lexing tokens from it instead of the current buffer.
70 bool Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir,
71                                    SourceLocation Loc) {
72   assert(!CurTokenLexer && "Cannot #include a file inside a macro!");
73   ++NumEnteredSourceFiles;
74
75   if (MaxIncludeStackDepth < IncludeMacroStack.size())
76     MaxIncludeStackDepth = IncludeMacroStack.size();
77
78   if (PTH) {
79     if (PTHLexer *PL = PTH->CreateLexer(FID)) {
80       EnterSourceFileWithPTH(PL, CurDir);
81       return false;
82     }
83   }
84   
85   // Get the MemoryBuffer for this FID, if it fails, we fail.
86   bool Invalid = false;
87   const llvm::MemoryBuffer *InputFile = 
88     getSourceManager().getBuffer(FID, Loc, &Invalid);
89   if (Invalid) {
90     SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
91     Diag(Loc, diag::err_pp_error_opening_file)
92       << std::string(SourceMgr.getBufferName(FileStart)) << "";
93     return true;
94   }
95
96   if (isCodeCompletionEnabled() &&
97       SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) {
98     CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID);
99     CodeCompletionLoc =
100         CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset);
101   }
102
103   EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir);
104   return false;
105 }
106
107 /// EnterSourceFileWithLexer - Add a source file to the top of the include stack
108 ///  and start lexing tokens from it instead of the current buffer.
109 void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
110                                             const DirectoryLookup *CurDir) {
111
112   // Add the current lexer to the include stack.
113   if (CurPPLexer || CurTokenLexer)
114     PushIncludeMacroStack();
115
116   CurLexer.reset(TheLexer);
117   CurPPLexer = TheLexer;
118   CurDirLookup = CurDir;
119   CurLexerSubmodule = nullptr;
120   if (CurLexerKind != CLK_LexAfterModuleImport)
121     CurLexerKind = CLK_Lexer;
122
123   // Notify the client, if desired, that we are in a new source file.
124   if (Callbacks && !CurLexer->Is_PragmaLexer) {
125     SrcMgr::CharacteristicKind FileType =
126        SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
127
128     Callbacks->FileChanged(CurLexer->getFileLoc(),
129                            PPCallbacks::EnterFile, FileType);
130   }
131 }
132
133 /// EnterSourceFileWithPTH - Add a source file to the top of the include stack
134 /// and start getting tokens from it using the PTH cache.
135 void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL,
136                                           const DirectoryLookup *CurDir) {
137
138   if (CurPPLexer || CurTokenLexer)
139     PushIncludeMacroStack();
140
141   CurDirLookup = CurDir;
142   CurPTHLexer.reset(PL);
143   CurPPLexer = CurPTHLexer.get();
144   CurLexerSubmodule = nullptr;
145   if (CurLexerKind != CLK_LexAfterModuleImport)
146     CurLexerKind = CLK_PTHLexer;
147   
148   // Notify the client, if desired, that we are in a new source file.
149   if (Callbacks) {
150     FileID FID = CurPPLexer->getFileID();
151     SourceLocation EnterLoc = SourceMgr.getLocForStartOfFile(FID);
152     SrcMgr::CharacteristicKind FileType =
153       SourceMgr.getFileCharacteristic(EnterLoc);
154     Callbacks->FileChanged(EnterLoc, PPCallbacks::EnterFile, FileType);
155   }
156 }
157
158 /// EnterMacro - Add a Macro to the top of the include stack and start lexing
159 /// tokens from it instead of the current buffer.
160 void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
161                               MacroInfo *Macro, MacroArgs *Args) {
162   std::unique_ptr<TokenLexer> TokLexer;
163   if (NumCachedTokenLexers == 0) {
164     TokLexer = llvm::make_unique<TokenLexer>(Tok, ILEnd, Macro, Args, *this);
165   } else {
166     TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
167     TokLexer->Init(Tok, ILEnd, Macro, Args);
168   }
169
170   PushIncludeMacroStack();
171   CurDirLookup = nullptr;
172   CurTokenLexer = std::move(TokLexer);
173   if (CurLexerKind != CLK_LexAfterModuleImport)
174     CurLexerKind = CLK_TokenLexer;
175 }
176
177 /// EnterTokenStream - Add a "macro" context to the top of the include stack,
178 /// which will cause the lexer to start returning the specified tokens.
179 ///
180 /// If DisableMacroExpansion is true, tokens lexed from the token stream will
181 /// not be subject to further macro expansion.  Otherwise, these tokens will
182 /// be re-macro-expanded when/if expansion is enabled.
183 ///
184 /// If OwnsTokens is false, this method assumes that the specified stream of
185 /// tokens has a permanent owner somewhere, so they do not need to be copied.
186 /// If it is true, it assumes the array of tokens is allocated with new[] and
187 /// must be freed.
188 ///
189 void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
190                                     bool DisableMacroExpansion,
191                                     bool OwnsTokens) {
192   if (CurLexerKind == CLK_CachingLexer) {
193     if (CachedLexPos < CachedTokens.size()) {
194       // We're entering tokens into the middle of our cached token stream. We
195       // can't represent that, so just insert the tokens into the buffer.
196       CachedTokens.insert(CachedTokens.begin() + CachedLexPos,
197                           Toks, Toks + NumToks);
198       if (OwnsTokens)
199         delete [] Toks;
200       return;
201     }
202
203     // New tokens are at the end of the cached token sequnece; insert the
204     // token stream underneath the caching lexer.
205     ExitCachingLexMode();
206     EnterTokenStream(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
207     EnterCachingLexMode();
208     return;
209   }
210
211   // Create a macro expander to expand from the specified token stream.
212   std::unique_ptr<TokenLexer> TokLexer;
213   if (NumCachedTokenLexers == 0) {
214     TokLexer = llvm::make_unique<TokenLexer>(
215         Toks, NumToks, DisableMacroExpansion, OwnsTokens, *this);
216   } else {
217     TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
218     TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
219   }
220
221   // Save our current state.
222   PushIncludeMacroStack();
223   CurDirLookup = nullptr;
224   CurTokenLexer = std::move(TokLexer);
225   if (CurLexerKind != CLK_LexAfterModuleImport)
226     CurLexerKind = CLK_TokenLexer;
227 }
228
229 /// \brief Compute the relative path that names the given file relative to
230 /// the given directory.
231 static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir,
232                                 const FileEntry *File,
233                                 SmallString<128> &Result) {
234   Result.clear();
235
236   StringRef FilePath = File->getDir()->getName();
237   StringRef Path = FilePath;
238   while (!Path.empty()) {
239     if (const DirectoryEntry *CurDir = FM.getDirectory(Path)) {
240       if (CurDir == Dir) {
241         Result = FilePath.substr(Path.size());
242         llvm::sys::path::append(Result, 
243                                 llvm::sys::path::filename(File->getName()));
244         return;
245       }
246     }
247     
248     Path = llvm::sys::path::parent_path(Path);
249   }
250   
251   Result = File->getName();
252 }
253
254 void Preprocessor::PropagateLineStartLeadingSpaceInfo(Token &Result) {
255   if (CurTokenLexer) {
256     CurTokenLexer->PropagateLineStartLeadingSpaceInfo(Result);
257     return;
258   }
259   if (CurLexer) {
260     CurLexer->PropagateLineStartLeadingSpaceInfo(Result);
261     return;
262   }
263   // FIXME: Handle other kinds of lexers?  It generally shouldn't matter,
264   // but it might if they're empty?
265 }
266
267 /// \brief Determine the location to use as the end of the buffer for a lexer.
268 ///
269 /// If the file ends with a newline, form the EOF token on the newline itself,
270 /// rather than "on the line following it", which doesn't exist.  This makes
271 /// diagnostics relating to the end of file include the last file that the user
272 /// actually typed, which is goodness.
273 const char *Preprocessor::getCurLexerEndPos() {
274   const char *EndPos = CurLexer->BufferEnd;
275   if (EndPos != CurLexer->BufferStart &&
276       (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
277     --EndPos;
278
279     // Handle \n\r and \r\n:
280     if (EndPos != CurLexer->BufferStart &&
281         (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
282         EndPos[-1] != EndPos[0])
283       --EndPos;
284   }
285
286   return EndPos;
287 }
288
289 static void collectAllSubModulesWithUmbrellaHeader(
290     const Module &Mod, SmallVectorImpl<const Module *> &SubMods) {
291   if (Mod.getUmbrellaHeader())
292     SubMods.push_back(&Mod);
293   for (auto *M : Mod.submodules())
294     collectAllSubModulesWithUmbrellaHeader(*M, SubMods);
295 }
296
297 void Preprocessor::diagnoseMissingHeaderInUmbrellaDir(const Module &Mod) {
298   assert(Mod.getUmbrellaHeader() && "Module must use umbrella header");
299   SourceLocation StartLoc =
300       SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
301   if (getDiagnostics().isIgnored(diag::warn_uncovered_module_header, StartLoc))
302     return;
303
304   ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
305   const DirectoryEntry *Dir = Mod.getUmbrellaDir().Entry;
306   vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
307   std::error_code EC;
308   for (vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC), End;
309        Entry != End && !EC; Entry.increment(EC)) {
310     using llvm::StringSwitch;
311
312     // Check whether this entry has an extension typically associated with
313     // headers.
314     if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->getName()))
315              .Cases(".h", ".H", ".hh", ".hpp", true)
316              .Default(false))
317       continue;
318
319     if (const FileEntry *Header = getFileManager().getFile(Entry->getName()))
320       if (!getSourceManager().hasFileInfo(Header)) {
321         if (!ModMap.isHeaderInUnavailableModule(Header)) {
322           // Find the relative path that would access this header.
323           SmallString<128> RelativePath;
324           computeRelativePath(FileMgr, Dir, Header, RelativePath);
325           Diag(StartLoc, diag::warn_uncovered_module_header)
326               << Mod.getFullModuleName() << RelativePath;
327         }
328       }
329   }
330 }
331
332 /// HandleEndOfFile - This callback is invoked when the lexer hits the end of
333 /// the current file.  This either returns the EOF token or pops a level off
334 /// the include stack and keeps going.
335 bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
336   assert(!CurTokenLexer &&
337          "Ending a file when currently in a macro!");
338
339   // If we have an unclosed module region from a pragma at the end of a
340   // module, complain and close it now.
341   // FIXME: This is not correct if we are building a module from PTH.
342   const bool LeavingSubmodule = CurLexer && CurLexerSubmodule;
343   if ((LeavingSubmodule || IncludeMacroStack.empty()) &&
344       !BuildingSubmoduleStack.empty() &&
345       BuildingSubmoduleStack.back().IsPragma) {
346     Diag(BuildingSubmoduleStack.back().ImportLoc,
347          diag::err_pp_module_begin_without_module_end);
348     Module *M = LeaveSubmodule(/*ForPragma*/true);
349
350     Result.startToken();
351     const char *EndPos = getCurLexerEndPos();
352     CurLexer->BufferPtr = EndPos;
353     CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
354     Result.setAnnotationEndLoc(Result.getLocation());
355     Result.setAnnotationValue(M);
356     return true;
357   }
358
359   // See if this file had a controlling macro.
360   if (CurPPLexer) {  // Not ending a macro, ignore it.
361     if (const IdentifierInfo *ControllingMacro =
362           CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
363       // Okay, this has a controlling macro, remember in HeaderFileInfo.
364       if (const FileEntry *FE = CurPPLexer->getFileEntry()) {
365         HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
366         if (MacroInfo *MI =
367               getMacroInfo(const_cast<IdentifierInfo*>(ControllingMacro)))
368           MI->setUsedForHeaderGuard(true);
369         if (const IdentifierInfo *DefinedMacro =
370               CurPPLexer->MIOpt.GetDefinedMacro()) {
371           if (!isMacroDefined(ControllingMacro) &&
372               DefinedMacro != ControllingMacro &&
373               HeaderInfo.FirstTimeLexingFile(FE)) {
374
375             // If the edit distance between the two macros is more than 50%,
376             // DefinedMacro may not be header guard, or can be header guard of
377             // another header file. Therefore, it maybe defining something
378             // completely different. This can be observed in the wild when
379             // handling feature macros or header guards in different files.
380
381             const StringRef ControllingMacroName = ControllingMacro->getName();
382             const StringRef DefinedMacroName = DefinedMacro->getName();
383             const size_t MaxHalfLength = std::max(ControllingMacroName.size(),
384                                                   DefinedMacroName.size()) / 2;
385             const unsigned ED = ControllingMacroName.edit_distance(
386                 DefinedMacroName, true, MaxHalfLength);
387             if (ED <= MaxHalfLength) {
388               // Emit a warning for a bad header guard.
389               Diag(CurPPLexer->MIOpt.GetMacroLocation(),
390                    diag::warn_header_guard)
391                   << CurPPLexer->MIOpt.GetMacroLocation() << ControllingMacro;
392               Diag(CurPPLexer->MIOpt.GetDefinedLocation(),
393                    diag::note_header_guard)
394                   << CurPPLexer->MIOpt.GetDefinedLocation() << DefinedMacro
395                   << ControllingMacro
396                   << FixItHint::CreateReplacement(
397                          CurPPLexer->MIOpt.GetDefinedLocation(),
398                          ControllingMacro->getName());
399             }
400           }
401         }
402       }
403     }
404   }
405
406   // Complain about reaching a true EOF within arc_cf_code_audited.
407   // We don't want to complain about reaching the end of a macro
408   // instantiation or a _Pragma.
409   if (PragmaARCCFCodeAuditedLoc.isValid() &&
410       !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
411     Diag(PragmaARCCFCodeAuditedLoc, diag::err_pp_eof_in_arc_cf_code_audited);
412
413     // Recover by leaving immediately.
414     PragmaARCCFCodeAuditedLoc = SourceLocation();
415   }
416
417   // Complain about reaching a true EOF within assume_nonnull.
418   // We don't want to complain about reaching the end of a macro
419   // instantiation or a _Pragma.
420   if (PragmaAssumeNonNullLoc.isValid() &&
421       !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
422     Diag(PragmaAssumeNonNullLoc, diag::err_pp_eof_in_assume_nonnull);
423
424     // Recover by leaving immediately.
425     PragmaAssumeNonNullLoc = SourceLocation();
426   }
427
428   // If this is a #include'd file, pop it off the include stack and continue
429   // lexing the #includer file.
430   if (!IncludeMacroStack.empty()) {
431
432     // If we lexed the code-completion file, act as if we reached EOF.
433     if (isCodeCompletionEnabled() && CurPPLexer &&
434         SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==
435             CodeCompletionFileLoc) {
436       if (CurLexer) {
437         Result.startToken();
438         CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
439         CurLexer.reset();
440       } else {
441         assert(CurPTHLexer && "Got EOF but no current lexer set!");
442         CurPTHLexer->getEOF(Result);
443         CurPTHLexer.reset();
444       }
445
446       CurPPLexer = nullptr;
447       recomputeCurLexerKind();
448       return true;
449     }
450
451     if (!isEndOfMacro && CurPPLexer &&
452         SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid()) {
453       // Notify SourceManager to record the number of FileIDs that were created
454       // during lexing of the #include'd file.
455       unsigned NumFIDs =
456           SourceMgr.local_sloc_entry_size() -
457           CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/;
458       SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);
459     }
460
461     bool ExitedFromPredefinesFile = false;
462     FileID ExitedFID;
463     if (!isEndOfMacro && CurPPLexer) {
464       ExitedFID = CurPPLexer->getFileID();
465
466       assert(PredefinesFileID.isValid() &&
467              "HandleEndOfFile is called before PredefinesFileId is set");
468       ExitedFromPredefinesFile = (PredefinesFileID == ExitedFID);
469     }
470
471     if (LeavingSubmodule) {
472       // We're done with this submodule.
473       Module *M = LeaveSubmodule(/*ForPragma*/false);
474
475       // Notify the parser that we've left the module.
476       const char *EndPos = getCurLexerEndPos();
477       Result.startToken();
478       CurLexer->BufferPtr = EndPos;
479       CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
480       Result.setAnnotationEndLoc(Result.getLocation());
481       Result.setAnnotationValue(M);
482     }
483
484     // We're done with the #included file.
485     RemoveTopOfLexerStack();
486
487     // Propagate info about start-of-line/leading white-space/etc.
488     PropagateLineStartLeadingSpaceInfo(Result);
489
490     // Notify the client, if desired, that we are in a new source file.
491     if (Callbacks && !isEndOfMacro && CurPPLexer) {
492       SrcMgr::CharacteristicKind FileType =
493         SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
494       Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
495                              PPCallbacks::ExitFile, FileType, ExitedFID);
496     }
497
498     // Restore conditional stack from the preamble right after exiting from the
499     // predefines file.
500     if (ExitedFromPredefinesFile)
501       replayPreambleConditionalStack();
502
503     // Client should lex another token unless we generated an EOM.
504     return LeavingSubmodule;
505   }
506
507   // If this is the end of the main file, form an EOF token.
508   if (CurLexer) {
509     const char *EndPos = getCurLexerEndPos();
510     Result.startToken();
511     CurLexer->BufferPtr = EndPos;
512     CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
513
514     if (isCodeCompletionEnabled()) {
515       // Inserting the code-completion point increases the source buffer by 1,
516       // but the main FileID was created before inserting the point.
517       // Compensate by reducing the EOF location by 1, otherwise the location
518       // will point to the next FileID.
519       // FIXME: This is hacky, the code-completion point should probably be
520       // inserted before the main FileID is created.
521       if (CurLexer->getFileLoc() == CodeCompletionFileLoc)
522         Result.setLocation(Result.getLocation().getLocWithOffset(-1));
523     }
524
525     if (!isIncrementalProcessingEnabled())
526       // We're done with lexing.
527       CurLexer.reset();
528   } else {
529     assert(CurPTHLexer && "Got EOF but no current lexer set!");
530     CurPTHLexer->getEOF(Result);
531     CurPTHLexer.reset();
532   }
533   
534   if (!isIncrementalProcessingEnabled())
535     CurPPLexer = nullptr;
536
537   if (TUKind == TU_Complete) {
538     // This is the end of the top-level file. 'WarnUnusedMacroLocs' has
539     // collected all macro locations that we need to warn because they are not
540     // used.
541     for (WarnUnusedMacroLocsTy::iterator
542            I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end();
543            I!=E; ++I)
544       Diag(*I, diag::pp_macro_not_used);
545   }
546
547   // If we are building a module that has an umbrella header, make sure that
548   // each of the headers within the directory, including all submodules, is
549   // covered by the umbrella header was actually included by the umbrella
550   // header.
551   if (Module *Mod = getCurrentModule()) {
552     llvm::SmallVector<const Module *, 4> AllMods;
553     collectAllSubModulesWithUmbrellaHeader(*Mod, AllMods);
554     for (auto *M : AllMods)
555       diagnoseMissingHeaderInUmbrellaDir(*M);
556   }
557
558   return true;
559 }
560
561 /// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
562 /// hits the end of its token stream.
563 bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
564   assert(CurTokenLexer && !CurPPLexer &&
565          "Ending a macro when currently in a #include file!");
566
567   if (!MacroExpandingLexersStack.empty() &&
568       MacroExpandingLexersStack.back().first == CurTokenLexer.get())
569     removeCachedMacroExpandedTokensOfLastLexer();
570
571   // Delete or cache the now-dead macro expander.
572   if (NumCachedTokenLexers == TokenLexerCacheSize)
573     CurTokenLexer.reset();
574   else
575     TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
576
577   // Handle this like a #include file being popped off the stack.
578   return HandleEndOfFile(Result, true);
579 }
580
581 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
582 /// lexer stack.  This should only be used in situations where the current
583 /// state of the top-of-stack lexer is unknown.
584 void Preprocessor::RemoveTopOfLexerStack() {
585   assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
586
587   if (CurTokenLexer) {
588     // Delete or cache the now-dead macro expander.
589     if (NumCachedTokenLexers == TokenLexerCacheSize)
590       CurTokenLexer.reset();
591     else
592       TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
593   }
594
595   PopIncludeMacroStack();
596 }
597
598 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a
599 /// comment (/##/) in microsoft mode, this method handles updating the current
600 /// state, returning the token on the next source line.
601 void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
602   assert(CurTokenLexer && !CurPPLexer &&
603          "Pasted comment can only be formed from macro");
604   // We handle this by scanning for the closest real lexer, switching it to
605   // raw mode and preprocessor mode.  This will cause it to return \n as an
606   // explicit EOD token.
607   PreprocessorLexer *FoundLexer = nullptr;
608   bool LexerWasInPPMode = false;
609   for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
610     if (ISI.ThePPLexer == nullptr) continue;  // Scan for a real lexer.
611
612     // Once we find a real lexer, mark it as raw mode (disabling macro
613     // expansions) and preprocessor mode (return EOD).  We know that the lexer
614     // was *not* in raw mode before, because the macro that the comment came
615     // from was expanded.  However, it could have already been in preprocessor
616     // mode (#if COMMENT) in which case we have to return it to that mode and
617     // return EOD.
618     FoundLexer = ISI.ThePPLexer;
619     FoundLexer->LexingRawMode = true;
620     LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
621     FoundLexer->ParsingPreprocessorDirective = true;
622     break;
623   }
624
625   // Okay, we either found and switched over the lexer, or we didn't find a
626   // lexer.  In either case, finish off the macro the comment came from, getting
627   // the next token.
628   if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
629
630   // Discarding comments as long as we don't have EOF or EOD.  This 'comments
631   // out' the rest of the line, including any tokens that came from other macros
632   // that were active, as in:
633   //  #define submacro a COMMENT b
634   //    submacro c
635   // which should lex to 'a' only: 'b' and 'c' should be removed.
636   while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof))
637     Lex(Tok);
638
639   // If we got an eod token, then we successfully found the end of the line.
640   if (Tok.is(tok::eod)) {
641     assert(FoundLexer && "Can't get end of line without an active lexer");
642     // Restore the lexer back to normal mode instead of raw mode.
643     FoundLexer->LexingRawMode = false;
644
645     // If the lexer was already in preprocessor mode, just return the EOD token
646     // to finish the preprocessor line.
647     if (LexerWasInPPMode) return;
648
649     // Otherwise, switch out of PP mode and return the next lexed token.
650     FoundLexer->ParsingPreprocessorDirective = false;
651     return Lex(Tok);
652   }
653
654   // If we got an EOF token, then we reached the end of the token stream but
655   // didn't find an explicit \n.  This can only happen if there was no lexer
656   // active (an active lexer would return EOD at EOF if there was no \n in
657   // preprocessor directive mode), so just return EOF as our token.
658   assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");
659 }
660
661 void Preprocessor::EnterSubmodule(Module *M, SourceLocation ImportLoc,
662                                   bool ForPragma) {
663   if (!getLangOpts().ModulesLocalVisibility) {
664     // Just track that we entered this submodule.
665     BuildingSubmoduleStack.push_back(
666         BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
667                               PendingModuleMacroNames.size()));
668     return;
669   }
670
671   // Resolve as much of the module definition as we can now, before we enter
672   // one of its headers.
673   // FIXME: Can we enable Complain here?
674   // FIXME: Can we do this when local visibility is disabled?
675   ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
676   ModMap.resolveExports(M, /*Complain=*/false);
677   ModMap.resolveUses(M, /*Complain=*/false);
678   ModMap.resolveConflicts(M, /*Complain=*/false);
679
680   // If this is the first time we've entered this module, set up its state.
681   auto R = Submodules.insert(std::make_pair(M, SubmoduleState()));
682   auto &State = R.first->second;
683   bool FirstTime = R.second;
684   if (FirstTime) {
685     // Determine the set of starting macros for this submodule; take these
686     // from the "null" module (the predefines buffer).
687     //
688     // FIXME: If we have local visibility but not modules enabled, the
689     // NullSubmoduleState is polluted by #defines in the top-level source
690     // file.
691     auto &StartingMacros = NullSubmoduleState.Macros;
692
693     // Restore to the starting state.
694     // FIXME: Do this lazily, when each macro name is first referenced.
695     for (auto &Macro : StartingMacros) {
696       // Skip uninteresting macros.
697       if (!Macro.second.getLatest() &&
698           Macro.second.getOverriddenMacros().empty())
699         continue;
700
701       MacroState MS(Macro.second.getLatest());
702       MS.setOverriddenMacros(*this, Macro.second.getOverriddenMacros());
703       State.Macros.insert(std::make_pair(Macro.first, std::move(MS)));
704     }
705   }
706
707   // Track that we entered this module.
708   BuildingSubmoduleStack.push_back(
709       BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
710                             PendingModuleMacroNames.size()));
711
712   // Switch to this submodule as the current submodule.
713   CurSubmoduleState = &State;
714
715   // This module is visible to itself.
716   if (FirstTime)
717     makeModuleVisible(M, ImportLoc);
718 }
719
720 bool Preprocessor::needModuleMacros() const {
721   // If we're not within a submodule, we never need to create ModuleMacros.
722   if (BuildingSubmoduleStack.empty())
723     return false;
724   // If we are tracking module macro visibility even for textually-included
725   // headers, we need ModuleMacros.
726   if (getLangOpts().ModulesLocalVisibility)
727     return true;
728   // Otherwise, we only need module macros if we're actually compiling a module
729   // interface.
730   return getLangOpts().isCompilingModule();
731 }
732
733 Module *Preprocessor::LeaveSubmodule(bool ForPragma) {
734   if (BuildingSubmoduleStack.empty() ||
735       BuildingSubmoduleStack.back().IsPragma != ForPragma) {
736     assert(ForPragma && "non-pragma module enter/leave mismatch");
737     return nullptr;
738   }
739
740   auto &Info = BuildingSubmoduleStack.back();
741
742   Module *LeavingMod = Info.M;
743   SourceLocation ImportLoc = Info.ImportLoc;
744
745   if (!needModuleMacros() ||
746       (!getLangOpts().ModulesLocalVisibility &&
747        LeavingMod->getTopLevelModuleName() != getLangOpts().CurrentModule)) {
748     // If we don't need module macros, or this is not a module for which we
749     // are tracking macro visibility, don't build any, and preserve the list
750     // of pending names for the surrounding submodule.
751     BuildingSubmoduleStack.pop_back();
752     makeModuleVisible(LeavingMod, ImportLoc);
753     return LeavingMod;
754   }
755
756   // Create ModuleMacros for any macros defined in this submodule.
757   llvm::SmallPtrSet<const IdentifierInfo*, 8> VisitedMacros;
758   for (unsigned I = Info.OuterPendingModuleMacroNames;
759        I != PendingModuleMacroNames.size(); ++I) {
760     auto *II = const_cast<IdentifierInfo*>(PendingModuleMacroNames[I]);
761     if (!VisitedMacros.insert(II).second)
762       continue;
763
764     auto MacroIt = CurSubmoduleState->Macros.find(II);
765     if (MacroIt == CurSubmoduleState->Macros.end())
766       continue;
767     auto &Macro = MacroIt->second;
768
769     // Find the starting point for the MacroDirective chain in this submodule.
770     MacroDirective *OldMD = nullptr;
771     auto *OldState = Info.OuterSubmoduleState;
772     if (getLangOpts().ModulesLocalVisibility)
773       OldState = &NullSubmoduleState;
774     if (OldState && OldState != CurSubmoduleState) {
775       // FIXME: It'd be better to start at the state from when we most recently
776       // entered this submodule, but it doesn't really matter.
777       auto &OldMacros = OldState->Macros;
778       auto OldMacroIt = OldMacros.find(II);
779       if (OldMacroIt == OldMacros.end())
780         OldMD = nullptr;
781       else
782         OldMD = OldMacroIt->second.getLatest();
783     }
784
785     // This module may have exported a new macro. If so, create a ModuleMacro
786     // representing that fact.
787     bool ExplicitlyPublic = false;
788     for (auto *MD = Macro.getLatest(); MD != OldMD; MD = MD->getPrevious()) {
789       assert(MD && "broken macro directive chain");
790
791       if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
792         // The latest visibility directive for a name in a submodule affects
793         // all the directives that come before it.
794         if (VisMD->isPublic())
795           ExplicitlyPublic = true;
796         else if (!ExplicitlyPublic)
797           // Private with no following public directive: not exported.
798           break;
799       } else {
800         MacroInfo *Def = nullptr;
801         if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
802           Def = DefMD->getInfo();
803
804         // FIXME: Issue a warning if multiple headers for the same submodule
805         // define a macro, rather than silently ignoring all but the first.
806         bool IsNew;
807         // Don't bother creating a module macro if it would represent a #undef
808         // that doesn't override anything.
809         if (Def || !Macro.getOverriddenMacros().empty())
810           addModuleMacro(LeavingMod, II, Def,
811                          Macro.getOverriddenMacros(), IsNew);
812
813         if (!getLangOpts().ModulesLocalVisibility) {
814           // This macro is exposed to the rest of this compilation as a
815           // ModuleMacro; we don't need to track its MacroDirective any more.
816           Macro.setLatest(nullptr);
817           Macro.setOverriddenMacros(*this, {});
818         }
819         break;
820       }
821     }
822   }
823   PendingModuleMacroNames.resize(Info.OuterPendingModuleMacroNames);
824
825   // FIXME: Before we leave this submodule, we should parse all the other
826   // headers within it. Otherwise, we're left with an inconsistent state
827   // where we've made the module visible but don't yet have its complete
828   // contents.
829
830   // Put back the outer module's state, if we're tracking it.
831   if (getLangOpts().ModulesLocalVisibility)
832     CurSubmoduleState = Info.OuterSubmoduleState;
833
834   BuildingSubmoduleStack.pop_back();
835
836   // A nested #include makes the included submodule visible.
837   makeModuleVisible(LeavingMod, ImportLoc);
838   return LeavingMod;
839 }