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