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