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