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