1 //===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements pieces of the Preprocessor interface that manage the
10 // current lexer stack.
12 //===----------------------------------------------------------------------===//
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;
27 PPCallbacks::~PPCallbacks() {}
29 //===----------------------------------------------------------------------===//
30 // Miscellaneous Methods.
31 //===----------------------------------------------------------------------===//
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 {
37 return IncludeMacroStack.empty();
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?");
43 IncludeMacroStack.begin() + 1, IncludeMacroStack.end(),
44 [&](const IncludeStackInfo &ISI) -> bool { return IsFileLexer(ISI); });
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 {
54 // Look for a stacked lexer.
55 for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
57 return ISI.ThePPLexer;
63 //===----------------------------------------------------------------------===//
64 // Methods for Entering and Callbacks for leaving various contexts
65 //===----------------------------------------------------------------------===//
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,
71 assert(!CurTokenLexer && "Cannot #include a file inside a macro!");
72 ++NumEnteredSourceFiles;
74 if (MaxIncludeStackDepth < IncludeMacroStack.size())
75 MaxIncludeStackDepth = IncludeMacroStack.size();
77 // Get the MemoryBuffer for this FID, if it fails, we fail.
79 const llvm::MemoryBuffer *InputFile =
80 getSourceManager().getBuffer(FID, Loc, &Invalid);
82 SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
83 Diag(Loc, diag::err_pp_error_opening_file)
84 << std::string(SourceMgr.getBufferName(FileStart)) << "";
88 if (isCodeCompletionEnabled() &&
89 SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) {
90 CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID);
92 CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset);
95 EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir);
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) {
104 // Add the current lexer to the include stack.
105 if (CurPPLexer || CurTokenLexer)
106 PushIncludeMacroStack();
108 CurLexer.reset(TheLexer);
109 CurPPLexer = TheLexer;
110 CurDirLookup = CurDir;
111 CurLexerSubmodule = nullptr;
112 if (CurLexerKind != CLK_LexAfterModuleImport)
113 CurLexerKind = CLK_Lexer;
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());
120 Callbacks->FileChanged(CurLexer->getFileLoc(),
121 PPCallbacks::EnterFile, FileType);
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);
133 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
134 TokLexer->Init(Tok, ILEnd, Macro, Args);
137 PushIncludeMacroStack();
138 CurDirLookup = nullptr;
139 CurTokenLexer = std::move(TokLexer);
140 if (CurLexerKind != CLK_LexAfterModuleImport)
141 CurLexerKind = CLK_TokenLexer;
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.
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.
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
156 void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
157 bool DisableMacroExpansion, bool OwnsTokens,
159 if (CurLexerKind == CLK_CachingLexer) {
160 if (CachedLexPos < CachedTokens.size()) {
161 assert(IsReinject && "new tokens in the middle of cached stream");
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);
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,
176 EnterCachingLexMode();
180 // Create a macro expander to expand from the specified token stream.
181 std::unique_ptr<TokenLexer> TokLexer;
182 if (NumCachedTokenLexers == 0) {
183 TokLexer = llvm::make_unique<TokenLexer>(
184 Toks, NumToks, DisableMacroExpansion, OwnsTokens, IsReinject, *this);
186 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
187 TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens,
191 // Save our current state.
192 PushIncludeMacroStack();
193 CurDirLookup = nullptr;
194 CurTokenLexer = std::move(TokLexer);
195 if (CurLexerKind != CLK_LexAfterModuleImport)
196 CurLexerKind = CLK_TokenLexer;
199 /// Compute the relative path that names the given file relative to
200 /// the given directory.
201 static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir,
202 const FileEntry *File,
203 SmallString<128> &Result) {
206 StringRef FilePath = File->getDir()->getName();
207 StringRef Path = FilePath;
208 while (!Path.empty()) {
209 if (const DirectoryEntry *CurDir = FM.getDirectory(Path)) {
211 Result = FilePath.substr(Path.size());
212 llvm::sys::path::append(Result,
213 llvm::sys::path::filename(File->getName()));
218 Path = llvm::sys::path::parent_path(Path);
221 Result = File->getName();
224 void Preprocessor::PropagateLineStartLeadingSpaceInfo(Token &Result) {
226 CurTokenLexer->PropagateLineStartLeadingSpaceInfo(Result);
230 CurLexer->PropagateLineStartLeadingSpaceInfo(Result);
233 // FIXME: Handle other kinds of lexers? It generally shouldn't matter,
234 // but it might if they're empty?
237 /// Determine the location to use as the end of the buffer for a lexer.
239 /// If the file ends with a newline, form the EOF token on the newline itself,
240 /// rather than "on the line following it", which doesn't exist. This makes
241 /// diagnostics relating to the end of file include the last file that the user
242 /// actually typed, which is goodness.
243 const char *Preprocessor::getCurLexerEndPos() {
244 const char *EndPos = CurLexer->BufferEnd;
245 if (EndPos != CurLexer->BufferStart &&
246 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
249 // Handle \n\r and \r\n:
250 if (EndPos != CurLexer->BufferStart &&
251 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
252 EndPos[-1] != EndPos[0])
259 static void collectAllSubModulesWithUmbrellaHeader(
260 const Module &Mod, SmallVectorImpl<const Module *> &SubMods) {
261 if (Mod.getUmbrellaHeader())
262 SubMods.push_back(&Mod);
263 for (auto *M : Mod.submodules())
264 collectAllSubModulesWithUmbrellaHeader(*M, SubMods);
267 void Preprocessor::diagnoseMissingHeaderInUmbrellaDir(const Module &Mod) {
268 assert(Mod.getUmbrellaHeader() && "Module must use umbrella header");
269 SourceLocation StartLoc =
270 SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
271 if (getDiagnostics().isIgnored(diag::warn_uncovered_module_header, StartLoc))
274 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
275 const DirectoryEntry *Dir = Mod.getUmbrellaDir().Entry;
276 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
278 for (llvm::vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC),
280 Entry != End && !EC; Entry.increment(EC)) {
281 using llvm::StringSwitch;
283 // Check whether this entry has an extension typically associated with
285 if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->path()))
286 .Cases(".h", ".H", ".hh", ".hpp", true)
290 if (const FileEntry *Header = getFileManager().getFile(Entry->path()))
291 if (!getSourceManager().hasFileInfo(Header)) {
292 if (!ModMap.isHeaderInUnavailableModule(Header)) {
293 // Find the relative path that would access this header.
294 SmallString<128> RelativePath;
295 computeRelativePath(FileMgr, Dir, Header, RelativePath);
296 Diag(StartLoc, diag::warn_uncovered_module_header)
297 << Mod.getFullModuleName() << RelativePath;
303 /// HandleEndOfFile - This callback is invoked when the lexer hits the end of
304 /// the current file. This either returns the EOF token or pops a level off
305 /// the include stack and keeps going.
306 bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
307 assert(!CurTokenLexer &&
308 "Ending a file when currently in a macro!");
310 // If we have an unclosed module region from a pragma at the end of a
311 // module, complain and close it now.
312 const bool LeavingSubmodule = CurLexer && CurLexerSubmodule;
313 if ((LeavingSubmodule || IncludeMacroStack.empty()) &&
314 !BuildingSubmoduleStack.empty() &&
315 BuildingSubmoduleStack.back().IsPragma) {
316 Diag(BuildingSubmoduleStack.back().ImportLoc,
317 diag::err_pp_module_begin_without_module_end);
318 Module *M = LeaveSubmodule(/*ForPragma*/true);
321 const char *EndPos = getCurLexerEndPos();
322 CurLexer->BufferPtr = EndPos;
323 CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
324 Result.setAnnotationEndLoc(Result.getLocation());
325 Result.setAnnotationValue(M);
329 // See if this file had a controlling macro.
330 if (CurPPLexer) { // Not ending a macro, ignore it.
331 if (const IdentifierInfo *ControllingMacro =
332 CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
333 // Okay, this has a controlling macro, remember in HeaderFileInfo.
334 if (const FileEntry *FE = CurPPLexer->getFileEntry()) {
335 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
337 getMacroInfo(const_cast<IdentifierInfo*>(ControllingMacro)))
338 MI->setUsedForHeaderGuard(true);
339 if (const IdentifierInfo *DefinedMacro =
340 CurPPLexer->MIOpt.GetDefinedMacro()) {
341 if (!isMacroDefined(ControllingMacro) &&
342 DefinedMacro != ControllingMacro &&
343 HeaderInfo.FirstTimeLexingFile(FE)) {
345 // If the edit distance between the two macros is more than 50%,
346 // DefinedMacro may not be header guard, or can be header guard of
347 // another header file. Therefore, it maybe defining something
348 // completely different. This can be observed in the wild when
349 // handling feature macros or header guards in different files.
351 const StringRef ControllingMacroName = ControllingMacro->getName();
352 const StringRef DefinedMacroName = DefinedMacro->getName();
353 const size_t MaxHalfLength = std::max(ControllingMacroName.size(),
354 DefinedMacroName.size()) / 2;
355 const unsigned ED = ControllingMacroName.edit_distance(
356 DefinedMacroName, true, MaxHalfLength);
357 if (ED <= MaxHalfLength) {
358 // Emit a warning for a bad header guard.
359 Diag(CurPPLexer->MIOpt.GetMacroLocation(),
360 diag::warn_header_guard)
361 << CurPPLexer->MIOpt.GetMacroLocation() << ControllingMacro;
362 Diag(CurPPLexer->MIOpt.GetDefinedLocation(),
363 diag::note_header_guard)
364 << CurPPLexer->MIOpt.GetDefinedLocation() << DefinedMacro
366 << FixItHint::CreateReplacement(
367 CurPPLexer->MIOpt.GetDefinedLocation(),
368 ControllingMacro->getName());
376 // Complain about reaching a true EOF within arc_cf_code_audited.
377 // We don't want to complain about reaching the end of a macro
378 // instantiation or a _Pragma.
379 if (PragmaARCCFCodeAuditedLoc.isValid() &&
380 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
381 Diag(PragmaARCCFCodeAuditedLoc, diag::err_pp_eof_in_arc_cf_code_audited);
383 // Recover by leaving immediately.
384 PragmaARCCFCodeAuditedLoc = SourceLocation();
387 // Complain about reaching a true EOF within assume_nonnull.
388 // We don't want to complain about reaching the end of a macro
389 // instantiation or a _Pragma.
390 if (PragmaAssumeNonNullLoc.isValid() &&
391 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
392 Diag(PragmaAssumeNonNullLoc, diag::err_pp_eof_in_assume_nonnull);
394 // Recover by leaving immediately.
395 PragmaAssumeNonNullLoc = SourceLocation();
398 bool LeavingPCHThroughHeader = false;
400 // If this is a #include'd file, pop it off the include stack and continue
401 // lexing the #includer file.
402 if (!IncludeMacroStack.empty()) {
404 // If we lexed the code-completion file, act as if we reached EOF.
405 if (isCodeCompletionEnabled() && CurPPLexer &&
406 SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==
407 CodeCompletionFileLoc) {
408 assert(CurLexer && "Got EOF but no current lexer set!");
410 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
413 CurPPLexer = nullptr;
414 recomputeCurLexerKind();
418 if (!isEndOfMacro && CurPPLexer &&
419 SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid()) {
420 // Notify SourceManager to record the number of FileIDs that were created
421 // during lexing of the #include'd file.
423 SourceMgr.local_sloc_entry_size() -
424 CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/;
425 SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);
428 bool ExitedFromPredefinesFile = false;
430 if (!isEndOfMacro && CurPPLexer) {
431 ExitedFID = CurPPLexer->getFileID();
433 assert(PredefinesFileID.isValid() &&
434 "HandleEndOfFile is called before PredefinesFileId is set");
435 ExitedFromPredefinesFile = (PredefinesFileID == ExitedFID);
438 if (LeavingSubmodule) {
439 // We're done with this submodule.
440 Module *M = LeaveSubmodule(/*ForPragma*/false);
442 // Notify the parser that we've left the module.
443 const char *EndPos = getCurLexerEndPos();
445 CurLexer->BufferPtr = EndPos;
446 CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
447 Result.setAnnotationEndLoc(Result.getLocation());
448 Result.setAnnotationValue(M);
451 bool FoundPCHThroughHeader = false;
452 if (CurPPLexer && creatingPCHWithThroughHeader() &&
454 SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
455 FoundPCHThroughHeader = true;
457 // We're done with the #included file.
458 RemoveTopOfLexerStack();
460 // Propagate info about start-of-line/leading white-space/etc.
461 PropagateLineStartLeadingSpaceInfo(Result);
463 // Notify the client, if desired, that we are in a new source file.
464 if (Callbacks && !isEndOfMacro && CurPPLexer) {
465 SrcMgr::CharacteristicKind FileType =
466 SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
467 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
468 PPCallbacks::ExitFile, FileType, ExitedFID);
471 // Restore conditional stack from the preamble right after exiting from the
473 if (ExitedFromPredefinesFile)
474 replayPreambleConditionalStack();
476 if (!isEndOfMacro && CurPPLexer && FoundPCHThroughHeader &&
477 (isInPrimaryFile() ||
478 CurPPLexer->getFileID() == getPredefinesFileID())) {
479 // Leaving the through header. Continue directly to end of main file
481 LeavingPCHThroughHeader = true;
483 // Client should lex another token unless we generated an EOM.
484 return LeavingSubmodule;
488 // If this is the end of the main file, form an EOF token.
489 assert(CurLexer && "Got EOF but no current lexer set!");
490 const char *EndPos = getCurLexerEndPos();
492 CurLexer->BufferPtr = EndPos;
493 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
495 if (isCodeCompletionEnabled()) {
496 // Inserting the code-completion point increases the source buffer by 1,
497 // but the main FileID was created before inserting the point.
498 // Compensate by reducing the EOF location by 1, otherwise the location
499 // will point to the next FileID.
500 // FIXME: This is hacky, the code-completion point should probably be
501 // inserted before the main FileID is created.
502 if (CurLexer->getFileLoc() == CodeCompletionFileLoc)
503 Result.setLocation(Result.getLocation().getLocWithOffset(-1));
506 if (creatingPCHWithThroughHeader() && !LeavingPCHThroughHeader) {
507 // Reached the end of the compilation without finding the through header.
508 Diag(CurLexer->getFileLoc(), diag::err_pp_through_header_not_seen)
509 << PPOpts->PCHThroughHeader << 0;
512 if (!isIncrementalProcessingEnabled())
513 // We're done with lexing.
516 if (!isIncrementalProcessingEnabled())
517 CurPPLexer = nullptr;
519 if (TUKind == TU_Complete) {
520 // This is the end of the top-level file. 'WarnUnusedMacroLocs' has
521 // collected all macro locations that we need to warn because they are not
523 for (WarnUnusedMacroLocsTy::iterator
524 I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end();
526 Diag(*I, diag::pp_macro_not_used);
529 // If we are building a module that has an umbrella header, make sure that
530 // each of the headers within the directory, including all submodules, is
531 // covered by the umbrella header was actually included by the umbrella
533 if (Module *Mod = getCurrentModule()) {
534 llvm::SmallVector<const Module *, 4> AllMods;
535 collectAllSubModulesWithUmbrellaHeader(*Mod, AllMods);
536 for (auto *M : AllMods)
537 diagnoseMissingHeaderInUmbrellaDir(*M);
543 /// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
544 /// hits the end of its token stream.
545 bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
546 assert(CurTokenLexer && !CurPPLexer &&
547 "Ending a macro when currently in a #include file!");
549 if (!MacroExpandingLexersStack.empty() &&
550 MacroExpandingLexersStack.back().first == CurTokenLexer.get())
551 removeCachedMacroExpandedTokensOfLastLexer();
553 // Delete or cache the now-dead macro expander.
554 if (NumCachedTokenLexers == TokenLexerCacheSize)
555 CurTokenLexer.reset();
557 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
559 // Handle this like a #include file being popped off the stack.
560 return HandleEndOfFile(Result, true);
563 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
564 /// lexer stack. This should only be used in situations where the current
565 /// state of the top-of-stack lexer is unknown.
566 void Preprocessor::RemoveTopOfLexerStack() {
567 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
570 // Delete or cache the now-dead macro expander.
571 if (NumCachedTokenLexers == TokenLexerCacheSize)
572 CurTokenLexer.reset();
574 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
577 PopIncludeMacroStack();
580 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a
581 /// comment (/##/) in microsoft mode, this method handles updating the current
582 /// state, returning the token on the next source line.
583 void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
584 assert(CurTokenLexer && !CurPPLexer &&
585 "Pasted comment can only be formed from macro");
586 // We handle this by scanning for the closest real lexer, switching it to
587 // raw mode and preprocessor mode. This will cause it to return \n as an
588 // explicit EOD token.
589 PreprocessorLexer *FoundLexer = nullptr;
590 bool LexerWasInPPMode = false;
591 for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
592 if (ISI.ThePPLexer == nullptr) continue; // Scan for a real lexer.
594 // Once we find a real lexer, mark it as raw mode (disabling macro
595 // expansions) and preprocessor mode (return EOD). We know that the lexer
596 // was *not* in raw mode before, because the macro that the comment came
597 // from was expanded. However, it could have already been in preprocessor
598 // mode (#if COMMENT) in which case we have to return it to that mode and
600 FoundLexer = ISI.ThePPLexer;
601 FoundLexer->LexingRawMode = true;
602 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
603 FoundLexer->ParsingPreprocessorDirective = true;
607 // Okay, we either found and switched over the lexer, or we didn't find a
608 // lexer. In either case, finish off the macro the comment came from, getting
610 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
612 // Discarding comments as long as we don't have EOF or EOD. This 'comments
613 // out' the rest of the line, including any tokens that came from other macros
614 // that were active, as in:
615 // #define submacro a COMMENT b
617 // which should lex to 'a' only: 'b' and 'c' should be removed.
618 while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof))
621 // If we got an eod token, then we successfully found the end of the line.
622 if (Tok.is(tok::eod)) {
623 assert(FoundLexer && "Can't get end of line without an active lexer");
624 // Restore the lexer back to normal mode instead of raw mode.
625 FoundLexer->LexingRawMode = false;
627 // If the lexer was already in preprocessor mode, just return the EOD token
628 // to finish the preprocessor line.
629 if (LexerWasInPPMode) return;
631 // Otherwise, switch out of PP mode and return the next lexed token.
632 FoundLexer->ParsingPreprocessorDirective = false;
636 // If we got an EOF token, then we reached the end of the token stream but
637 // didn't find an explicit \n. This can only happen if there was no lexer
638 // active (an active lexer would return EOD at EOF if there was no \n in
639 // preprocessor directive mode), so just return EOF as our token.
640 assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");
643 void Preprocessor::EnterSubmodule(Module *M, SourceLocation ImportLoc,
645 if (!getLangOpts().ModulesLocalVisibility) {
646 // Just track that we entered this submodule.
647 BuildingSubmoduleStack.push_back(
648 BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
649 PendingModuleMacroNames.size()));
651 Callbacks->EnteredSubmodule(M, ImportLoc, ForPragma);
655 // Resolve as much of the module definition as we can now, before we enter
656 // one of its headers.
657 // FIXME: Can we enable Complain here?
658 // FIXME: Can we do this when local visibility is disabled?
659 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
660 ModMap.resolveExports(M, /*Complain=*/false);
661 ModMap.resolveUses(M, /*Complain=*/false);
662 ModMap.resolveConflicts(M, /*Complain=*/false);
664 // If this is the first time we've entered this module, set up its state.
665 auto R = Submodules.insert(std::make_pair(M, SubmoduleState()));
666 auto &State = R.first->second;
667 bool FirstTime = R.second;
669 // Determine the set of starting macros for this submodule; take these
670 // from the "null" module (the predefines buffer).
672 // FIXME: If we have local visibility but not modules enabled, the
673 // NullSubmoduleState is polluted by #defines in the top-level source
675 auto &StartingMacros = NullSubmoduleState.Macros;
677 // Restore to the starting state.
678 // FIXME: Do this lazily, when each macro name is first referenced.
679 for (auto &Macro : StartingMacros) {
680 // Skip uninteresting macros.
681 if (!Macro.second.getLatest() &&
682 Macro.second.getOverriddenMacros().empty())
685 MacroState MS(Macro.second.getLatest());
686 MS.setOverriddenMacros(*this, Macro.second.getOverriddenMacros());
687 State.Macros.insert(std::make_pair(Macro.first, std::move(MS)));
691 // Track that we entered this module.
692 BuildingSubmoduleStack.push_back(
693 BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
694 PendingModuleMacroNames.size()));
697 Callbacks->EnteredSubmodule(M, ImportLoc, ForPragma);
699 // Switch to this submodule as the current submodule.
700 CurSubmoduleState = &State;
702 // This module is visible to itself.
704 makeModuleVisible(M, ImportLoc);
707 bool Preprocessor::needModuleMacros() const {
708 // If we're not within a submodule, we never need to create ModuleMacros.
709 if (BuildingSubmoduleStack.empty())
711 // If we are tracking module macro visibility even for textually-included
712 // headers, we need ModuleMacros.
713 if (getLangOpts().ModulesLocalVisibility)
715 // Otherwise, we only need module macros if we're actually compiling a module
717 return getLangOpts().isCompilingModule();
720 Module *Preprocessor::LeaveSubmodule(bool ForPragma) {
721 if (BuildingSubmoduleStack.empty() ||
722 BuildingSubmoduleStack.back().IsPragma != ForPragma) {
723 assert(ForPragma && "non-pragma module enter/leave mismatch");
727 auto &Info = BuildingSubmoduleStack.back();
729 Module *LeavingMod = Info.M;
730 SourceLocation ImportLoc = Info.ImportLoc;
732 if (!needModuleMacros() ||
733 (!getLangOpts().ModulesLocalVisibility &&
734 LeavingMod->getTopLevelModuleName() != getLangOpts().CurrentModule)) {
735 // If we don't need module macros, or this is not a module for which we
736 // are tracking macro visibility, don't build any, and preserve the list
737 // of pending names for the surrounding submodule.
738 BuildingSubmoduleStack.pop_back();
741 Callbacks->LeftSubmodule(LeavingMod, ImportLoc, ForPragma);
743 makeModuleVisible(LeavingMod, ImportLoc);
747 // Create ModuleMacros for any macros defined in this submodule.
748 llvm::SmallPtrSet<const IdentifierInfo*, 8> VisitedMacros;
749 for (unsigned I = Info.OuterPendingModuleMacroNames;
750 I != PendingModuleMacroNames.size(); ++I) {
751 auto *II = const_cast<IdentifierInfo*>(PendingModuleMacroNames[I]);
752 if (!VisitedMacros.insert(II).second)
755 auto MacroIt = CurSubmoduleState->Macros.find(II);
756 if (MacroIt == CurSubmoduleState->Macros.end())
758 auto &Macro = MacroIt->second;
760 // Find the starting point for the MacroDirective chain in this submodule.
761 MacroDirective *OldMD = nullptr;
762 auto *OldState = Info.OuterSubmoduleState;
763 if (getLangOpts().ModulesLocalVisibility)
764 OldState = &NullSubmoduleState;
765 if (OldState && OldState != CurSubmoduleState) {
766 // FIXME: It'd be better to start at the state from when we most recently
767 // entered this submodule, but it doesn't really matter.
768 auto &OldMacros = OldState->Macros;
769 auto OldMacroIt = OldMacros.find(II);
770 if (OldMacroIt == OldMacros.end())
773 OldMD = OldMacroIt->second.getLatest();
776 // This module may have exported a new macro. If so, create a ModuleMacro
777 // representing that fact.
778 bool ExplicitlyPublic = false;
779 for (auto *MD = Macro.getLatest(); MD != OldMD; MD = MD->getPrevious()) {
780 assert(MD && "broken macro directive chain");
782 if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
783 // The latest visibility directive for a name in a submodule affects
784 // all the directives that come before it.
785 if (VisMD->isPublic())
786 ExplicitlyPublic = true;
787 else if (!ExplicitlyPublic)
788 // Private with no following public directive: not exported.
791 MacroInfo *Def = nullptr;
792 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
793 Def = DefMD->getInfo();
795 // FIXME: Issue a warning if multiple headers for the same submodule
796 // define a macro, rather than silently ignoring all but the first.
798 // Don't bother creating a module macro if it would represent a #undef
799 // that doesn't override anything.
800 if (Def || !Macro.getOverriddenMacros().empty())
801 addModuleMacro(LeavingMod, II, Def,
802 Macro.getOverriddenMacros(), IsNew);
804 if (!getLangOpts().ModulesLocalVisibility) {
805 // This macro is exposed to the rest of this compilation as a
806 // ModuleMacro; we don't need to track its MacroDirective any more.
807 Macro.setLatest(nullptr);
808 Macro.setOverriddenMacros(*this, {});
814 PendingModuleMacroNames.resize(Info.OuterPendingModuleMacroNames);
816 // FIXME: Before we leave this submodule, we should parse all the other
817 // headers within it. Otherwise, we're left with an inconsistent state
818 // where we've made the module visible but don't yet have its complete
821 // Put back the outer module's state, if we're tracking it.
822 if (getLangOpts().ModulesLocalVisibility)
823 CurSubmoduleState = Info.OuterSubmoduleState;
825 BuildingSubmoduleStack.pop_back();
828 Callbacks->LeftSubmodule(LeavingMod, ImportLoc, ForPragma);
830 // A nested #include makes the included submodule visible.
831 makeModuleVisible(LeavingMod, ImportLoc);