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