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