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