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