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, ConstSearchDirIterator 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                                             ConstSearchDirIterator 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     // If we're at the end of generating a preamble, we should record the
436     // unterminated \#pragma clang assume_nonnull so we can restore it later
437     // when the preamble is loaded into the main file.
438     if (isRecordingPreamble() && isInPrimaryFile())
439       PreambleRecordedPragmaAssumeNonNullLoc = PragmaAssumeNonNullLoc;
440     else
441       Diag(PragmaAssumeNonNullLoc, diag::err_pp_eof_in_assume_nonnull);
442     // Recover by leaving immediately.
443     PragmaAssumeNonNullLoc = SourceLocation();
444   }
445 
446   bool LeavingPCHThroughHeader = false;
447 
448   // If this is a #include'd file, pop it off the include stack and continue
449   // lexing the #includer file.
450   if (!IncludeMacroStack.empty()) {
451 
452     // If we lexed the code-completion file, act as if we reached EOF.
453     if (isCodeCompletionEnabled() && CurPPLexer &&
454         SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==
455             CodeCompletionFileLoc) {
456       assert(CurLexer && "Got EOF but no current lexer set!");
457       Result.startToken();
458       CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
459       CurLexer.reset();
460 
461       CurPPLexer = nullptr;
462       recomputeCurLexerKind();
463       return true;
464     }
465 
466     if (!isEndOfMacro && CurPPLexer &&
467         (SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid() ||
468          // Predefines file doesn't have a valid include location.
469          (PredefinesFileID.isValid() &&
470           CurPPLexer->getFileID() == PredefinesFileID))) {
471       // Notify SourceManager to record the number of FileIDs that were created
472       // during lexing of the #include'd file.
473       unsigned NumFIDs =
474           SourceMgr.local_sloc_entry_size() -
475           CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/;
476       SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);
477     }
478 
479     bool ExitedFromPredefinesFile = false;
480     FileID ExitedFID;
481     if (!isEndOfMacro && CurPPLexer) {
482       ExitedFID = CurPPLexer->getFileID();
483 
484       assert(PredefinesFileID.isValid() &&
485              "HandleEndOfFile is called before PredefinesFileId is set");
486       ExitedFromPredefinesFile = (PredefinesFileID == ExitedFID);
487     }
488 
489     if (LeavingSubmodule) {
490       // We're done with this submodule.
491       Module *M = LeaveSubmodule(/*ForPragma*/false);
492 
493       // Notify the parser that we've left the module.
494       const char *EndPos = getCurLexerEndPos();
495       Result.startToken();
496       CurLexer->BufferPtr = EndPos;
497       CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
498       Result.setAnnotationEndLoc(Result.getLocation());
499       Result.setAnnotationValue(M);
500     }
501 
502     bool FoundPCHThroughHeader = false;
503     if (CurPPLexer && creatingPCHWithThroughHeader() &&
504         isPCHThroughHeader(
505             SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
506       FoundPCHThroughHeader = true;
507 
508     // We're done with the #included file.
509     RemoveTopOfLexerStack();
510 
511     // Propagate info about start-of-line/leading white-space/etc.
512     PropagateLineStartLeadingSpaceInfo(Result);
513 
514     // Notify the client, if desired, that we are in a new source file.
515     if (Callbacks && !isEndOfMacro && CurPPLexer) {
516       SrcMgr::CharacteristicKind FileType =
517         SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
518       Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
519                              PPCallbacks::ExitFile, FileType, ExitedFID);
520     }
521 
522     // Restore conditional stack as well as the recorded
523     // \#pragma clang assume_nonnull from the preamble right after exiting
524     // from the predefines file.
525     if (ExitedFromPredefinesFile) {
526       replayPreambleConditionalStack();
527       if (PreambleRecordedPragmaAssumeNonNullLoc.isValid())
528         PragmaAssumeNonNullLoc = PreambleRecordedPragmaAssumeNonNullLoc;
529     }
530 
531     if (!isEndOfMacro && CurPPLexer && FoundPCHThroughHeader &&
532         (isInPrimaryFile() ||
533          CurPPLexer->getFileID() == getPredefinesFileID())) {
534       // Leaving the through header. Continue directly to end of main file
535       // processing.
536       LeavingPCHThroughHeader = true;
537     } else {
538       // Client should lex another token unless we generated an EOM.
539       return LeavingSubmodule;
540     }
541   }
542 
543   // If this is the end of the main file, form an EOF token.
544   assert(CurLexer && "Got EOF but no current lexer set!");
545   const char *EndPos = getCurLexerEndPos();
546   Result.startToken();
547   CurLexer->BufferPtr = EndPos;
548   CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
549 
550   if (isCodeCompletionEnabled()) {
551     // Inserting the code-completion point increases the source buffer by 1,
552     // but the main FileID was created before inserting the point.
553     // Compensate by reducing the EOF location by 1, otherwise the location
554     // will point to the next FileID.
555     // FIXME: This is hacky, the code-completion point should probably be
556     // inserted before the main FileID is created.
557     if (CurLexer->getFileLoc() == CodeCompletionFileLoc)
558       Result.setLocation(Result.getLocation().getLocWithOffset(-1));
559   }
560 
561   if (creatingPCHWithThroughHeader() && !LeavingPCHThroughHeader) {
562     // Reached the end of the compilation without finding the through header.
563     Diag(CurLexer->getFileLoc(), diag::err_pp_through_header_not_seen)
564         << PPOpts->PCHThroughHeader << 0;
565   }
566 
567   if (!isIncrementalProcessingEnabled())
568     // We're done with lexing.
569     CurLexer.reset();
570 
571   if (!isIncrementalProcessingEnabled())
572     CurPPLexer = nullptr;
573 
574   if (TUKind == TU_Complete) {
575     // This is the end of the top-level file. 'WarnUnusedMacroLocs' has
576     // collected all macro locations that we need to warn because they are not
577     // used.
578     for (WarnUnusedMacroLocsTy::iterator
579            I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end();
580            I!=E; ++I)
581       Diag(*I, diag::pp_macro_not_used);
582   }
583 
584   // If we are building a module that has an umbrella header, make sure that
585   // each of the headers within the directory, including all submodules, is
586   // covered by the umbrella header was actually included by the umbrella
587   // header.
588   if (Module *Mod = getCurrentModule()) {
589     llvm::SmallVector<const Module *, 4> AllMods;
590     collectAllSubModulesWithUmbrellaHeader(*Mod, AllMods);
591     for (auto *M : AllMods)
592       diagnoseMissingHeaderInUmbrellaDir(*M);
593   }
594 
595   return true;
596 }
597 
598 /// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
599 /// hits the end of its token stream.
600 bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
601   assert(CurTokenLexer && !CurPPLexer &&
602          "Ending a macro when currently in a #include file!");
603 
604   if (!MacroExpandingLexersStack.empty() &&
605       MacroExpandingLexersStack.back().first == CurTokenLexer.get())
606     removeCachedMacroExpandedTokensOfLastLexer();
607 
608   // Delete or cache the now-dead macro expander.
609   if (NumCachedTokenLexers == TokenLexerCacheSize)
610     CurTokenLexer.reset();
611   else
612     TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
613 
614   // Handle this like a #include file being popped off the stack.
615   return HandleEndOfFile(Result, {}, true);
616 }
617 
618 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
619 /// lexer stack.  This should only be used in situations where the current
620 /// state of the top-of-stack lexer is unknown.
621 void Preprocessor::RemoveTopOfLexerStack() {
622   assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
623 
624   if (CurTokenLexer) {
625     // Delete or cache the now-dead macro expander.
626     if (NumCachedTokenLexers == TokenLexerCacheSize)
627       CurTokenLexer.reset();
628     else
629       TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
630   }
631 
632   PopIncludeMacroStack();
633 }
634 
635 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a
636 /// comment (/##/) in microsoft mode, this method handles updating the current
637 /// state, returning the token on the next source line.
638 void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
639   assert(CurTokenLexer && !CurPPLexer &&
640          "Pasted comment can only be formed from macro");
641   // We handle this by scanning for the closest real lexer, switching it to
642   // raw mode and preprocessor mode.  This will cause it to return \n as an
643   // explicit EOD token.
644   PreprocessorLexer *FoundLexer = nullptr;
645   bool LexerWasInPPMode = false;
646   for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
647     if (ISI.ThePPLexer == nullptr) continue;  // Scan for a real lexer.
648 
649     // Once we find a real lexer, mark it as raw mode (disabling macro
650     // expansions) and preprocessor mode (return EOD).  We know that the lexer
651     // was *not* in raw mode before, because the macro that the comment came
652     // from was expanded.  However, it could have already been in preprocessor
653     // mode (#if COMMENT) in which case we have to return it to that mode and
654     // return EOD.
655     FoundLexer = ISI.ThePPLexer;
656     FoundLexer->LexingRawMode = true;
657     LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
658     FoundLexer->ParsingPreprocessorDirective = true;
659     break;
660   }
661 
662   // Okay, we either found and switched over the lexer, or we didn't find a
663   // lexer.  In either case, finish off the macro the comment came from, getting
664   // the next token.
665   if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
666 
667   // Discarding comments as long as we don't have EOF or EOD.  This 'comments
668   // out' the rest of the line, including any tokens that came from other macros
669   // that were active, as in:
670   //  #define submacro a COMMENT b
671   //    submacro c
672   // which should lex to 'a' only: 'b' and 'c' should be removed.
673   while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof))
674     Lex(Tok);
675 
676   // If we got an eod token, then we successfully found the end of the line.
677   if (Tok.is(tok::eod)) {
678     assert(FoundLexer && "Can't get end of line without an active lexer");
679     // Restore the lexer back to normal mode instead of raw mode.
680     FoundLexer->LexingRawMode = false;
681 
682     // If the lexer was already in preprocessor mode, just return the EOD token
683     // to finish the preprocessor line.
684     if (LexerWasInPPMode) return;
685 
686     // Otherwise, switch out of PP mode and return the next lexed token.
687     FoundLexer->ParsingPreprocessorDirective = false;
688     return Lex(Tok);
689   }
690 
691   // If we got an EOF token, then we reached the end of the token stream but
692   // didn't find an explicit \n.  This can only happen if there was no lexer
693   // active (an active lexer would return EOD at EOF if there was no \n in
694   // preprocessor directive mode), so just return EOF as our token.
695   assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");
696 }
697 
698 void Preprocessor::EnterSubmodule(Module *M, SourceLocation ImportLoc,
699                                   bool ForPragma) {
700   if (!getLangOpts().ModulesLocalVisibility) {
701     // Just track that we entered this submodule.
702     BuildingSubmoduleStack.push_back(
703         BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
704                               PendingModuleMacroNames.size()));
705     if (Callbacks)
706       Callbacks->EnteredSubmodule(M, ImportLoc, ForPragma);
707     return;
708   }
709 
710   // Resolve as much of the module definition as we can now, before we enter
711   // one of its headers.
712   // FIXME: Can we enable Complain here?
713   // FIXME: Can we do this when local visibility is disabled?
714   ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
715   ModMap.resolveExports(M, /*Complain=*/false);
716   ModMap.resolveUses(M, /*Complain=*/false);
717   ModMap.resolveConflicts(M, /*Complain=*/false);
718 
719   // If this is the first time we've entered this module, set up its state.
720   auto R = Submodules.insert(std::make_pair(M, SubmoduleState()));
721   auto &State = R.first->second;
722   bool FirstTime = R.second;
723   if (FirstTime) {
724     // Determine the set of starting macros for this submodule; take these
725     // from the "null" module (the predefines buffer).
726     //
727     // FIXME: If we have local visibility but not modules enabled, the
728     // NullSubmoduleState is polluted by #defines in the top-level source
729     // file.
730     auto &StartingMacros = NullSubmoduleState.Macros;
731 
732     // Restore to the starting state.
733     // FIXME: Do this lazily, when each macro name is first referenced.
734     for (auto &Macro : StartingMacros) {
735       // Skip uninteresting macros.
736       if (!Macro.second.getLatest() &&
737           Macro.second.getOverriddenMacros().empty())
738         continue;
739 
740       MacroState MS(Macro.second.getLatest());
741       MS.setOverriddenMacros(*this, Macro.second.getOverriddenMacros());
742       State.Macros.insert(std::make_pair(Macro.first, std::move(MS)));
743     }
744   }
745 
746   // Track that we entered this module.
747   BuildingSubmoduleStack.push_back(
748       BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
749                             PendingModuleMacroNames.size()));
750 
751   if (Callbacks)
752     Callbacks->EnteredSubmodule(M, ImportLoc, ForPragma);
753 
754   // Switch to this submodule as the current submodule.
755   CurSubmoduleState = &State;
756 
757   // This module is visible to itself.
758   if (FirstTime)
759     makeModuleVisible(M, ImportLoc);
760 }
761 
762 bool Preprocessor::needModuleMacros() const {
763   // If we're not within a submodule, we never need to create ModuleMacros.
764   if (BuildingSubmoduleStack.empty())
765     return false;
766   // If we are tracking module macro visibility even for textually-included
767   // headers, we need ModuleMacros.
768   if (getLangOpts().ModulesLocalVisibility)
769     return true;
770   // Otherwise, we only need module macros if we're actually compiling a module
771   // interface.
772   return getLangOpts().isCompilingModule();
773 }
774 
775 Module *Preprocessor::LeaveSubmodule(bool ForPragma) {
776   if (BuildingSubmoduleStack.empty() ||
777       BuildingSubmoduleStack.back().IsPragma != ForPragma) {
778     assert(ForPragma && "non-pragma module enter/leave mismatch");
779     return nullptr;
780   }
781 
782   auto &Info = BuildingSubmoduleStack.back();
783 
784   Module *LeavingMod = Info.M;
785   SourceLocation ImportLoc = Info.ImportLoc;
786 
787   if (!needModuleMacros() ||
788       (!getLangOpts().ModulesLocalVisibility &&
789        LeavingMod->getTopLevelModuleName() != getLangOpts().CurrentModule)) {
790     // If we don't need module macros, or this is not a module for which we
791     // are tracking macro visibility, don't build any, and preserve the list
792     // of pending names for the surrounding submodule.
793     BuildingSubmoduleStack.pop_back();
794 
795     if (Callbacks)
796       Callbacks->LeftSubmodule(LeavingMod, ImportLoc, ForPragma);
797 
798     makeModuleVisible(LeavingMod, ImportLoc);
799     return LeavingMod;
800   }
801 
802   // Create ModuleMacros for any macros defined in this submodule.
803   llvm::SmallPtrSet<const IdentifierInfo*, 8> VisitedMacros;
804   for (unsigned I = Info.OuterPendingModuleMacroNames;
805        I != PendingModuleMacroNames.size(); ++I) {
806     auto *II = const_cast<IdentifierInfo*>(PendingModuleMacroNames[I]);
807     if (!VisitedMacros.insert(II).second)
808       continue;
809 
810     auto MacroIt = CurSubmoduleState->Macros.find(II);
811     if (MacroIt == CurSubmoduleState->Macros.end())
812       continue;
813     auto &Macro = MacroIt->second;
814 
815     // Find the starting point for the MacroDirective chain in this submodule.
816     MacroDirective *OldMD = nullptr;
817     auto *OldState = Info.OuterSubmoduleState;
818     if (getLangOpts().ModulesLocalVisibility)
819       OldState = &NullSubmoduleState;
820     if (OldState && OldState != CurSubmoduleState) {
821       // FIXME: It'd be better to start at the state from when we most recently
822       // entered this submodule, but it doesn't really matter.
823       auto &OldMacros = OldState->Macros;
824       auto OldMacroIt = OldMacros.find(II);
825       if (OldMacroIt == OldMacros.end())
826         OldMD = nullptr;
827       else
828         OldMD = OldMacroIt->second.getLatest();
829     }
830 
831     // This module may have exported a new macro. If so, create a ModuleMacro
832     // representing that fact.
833     bool ExplicitlyPublic = false;
834     for (auto *MD = Macro.getLatest(); MD != OldMD; MD = MD->getPrevious()) {
835       assert(MD && "broken macro directive chain");
836 
837       if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
838         // The latest visibility directive for a name in a submodule affects
839         // all the directives that come before it.
840         if (VisMD->isPublic())
841           ExplicitlyPublic = true;
842         else if (!ExplicitlyPublic)
843           // Private with no following public directive: not exported.
844           break;
845       } else {
846         MacroInfo *Def = nullptr;
847         if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
848           Def = DefMD->getInfo();
849 
850         // FIXME: Issue a warning if multiple headers for the same submodule
851         // define a macro, rather than silently ignoring all but the first.
852         bool IsNew;
853         // Don't bother creating a module macro if it would represent a #undef
854         // that doesn't override anything.
855         if (Def || !Macro.getOverriddenMacros().empty())
856           addModuleMacro(LeavingMod, II, Def,
857                          Macro.getOverriddenMacros(), IsNew);
858 
859         if (!getLangOpts().ModulesLocalVisibility) {
860           // This macro is exposed to the rest of this compilation as a
861           // ModuleMacro; we don't need to track its MacroDirective any more.
862           Macro.setLatest(nullptr);
863           Macro.setOverriddenMacros(*this, {});
864         }
865         break;
866       }
867     }
868   }
869   PendingModuleMacroNames.resize(Info.OuterPendingModuleMacroNames);
870 
871   // FIXME: Before we leave this submodule, we should parse all the other
872   // headers within it. Otherwise, we're left with an inconsistent state
873   // where we've made the module visible but don't yet have its complete
874   // contents.
875 
876   // Put back the outer module's state, if we're tracking it.
877   if (getLangOpts().ModulesLocalVisibility)
878     CurSubmoduleState = Info.OuterSubmoduleState;
879 
880   BuildingSubmoduleStack.pop_back();
881 
882   if (Callbacks)
883     Callbacks->LeftSubmodule(LeavingMod, ImportLoc, ForPragma);
884 
885   // A nested #include makes the included submodule visible.
886   makeModuleVisible(LeavingMod, ImportLoc);
887   return LeavingMod;
888 }
889