Path: blob/main/contrib/llvm-project/clang/lib/Lex/PPLexerChange.cpp
35233 views
//===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements pieces of the Preprocessor interface that manage the9// current lexer stack.10//11//===----------------------------------------------------------------------===//1213#include "clang/Basic/FileManager.h"14#include "clang/Basic/SourceManager.h"15#include "clang/Lex/HeaderSearch.h"16#include "clang/Lex/LexDiagnostic.h"17#include "clang/Lex/MacroInfo.h"18#include "clang/Lex/Preprocessor.h"19#include "clang/Lex/PreprocessorOptions.h"20#include "llvm/ADT/StringSwitch.h"21#include "llvm/Support/FileSystem.h"22#include "llvm/Support/MemoryBufferRef.h"23#include "llvm/Support/Path.h"24#include <optional>2526using namespace clang;2728//===----------------------------------------------------------------------===//29// Miscellaneous Methods.30//===----------------------------------------------------------------------===//3132/// isInPrimaryFile - Return true if we're in the top-level file, not in a33/// \#include. This looks through macro expansions and active _Pragma lexers.34bool Preprocessor::isInPrimaryFile() const {35if (IsFileLexer())36return IncludeMacroStack.empty();3738// If there are any stacked lexers, we're in a #include.39assert(IsFileLexer(IncludeMacroStack[0]) &&40"Top level include stack isn't our primary lexer?");41return llvm::none_of(42llvm::drop_begin(IncludeMacroStack),43[&](const IncludeStackInfo &ISI) -> bool { return IsFileLexer(ISI); });44}4546/// getCurrentLexer - Return the current file lexer being lexed from. Note47/// that this ignores any potentially active macro expansions and _Pragma48/// expansions going on at the time.49PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {50if (IsFileLexer())51return CurPPLexer;5253// Look for a stacked lexer.54for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {55if (IsFileLexer(ISI))56return ISI.ThePPLexer;57}58return nullptr;59}606162//===----------------------------------------------------------------------===//63// Methods for Entering and Callbacks for leaving various contexts64//===----------------------------------------------------------------------===//6566/// EnterSourceFile - Add a source file to the top of the include stack and67/// start lexing tokens from it instead of the current buffer.68bool Preprocessor::EnterSourceFile(FileID FID, ConstSearchDirIterator CurDir,69SourceLocation Loc,70bool IsFirstIncludeOfFile) {71assert(!CurTokenLexer && "Cannot #include a file inside a macro!");72++NumEnteredSourceFiles;7374if (MaxIncludeStackDepth < IncludeMacroStack.size())75MaxIncludeStackDepth = IncludeMacroStack.size();7677// Get the MemoryBuffer for this FID, if it fails, we fail.78std::optional<llvm::MemoryBufferRef> InputFile =79getSourceManager().getBufferOrNone(FID, Loc);80if (!InputFile) {81SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);82Diag(Loc, diag::err_pp_error_opening_file)83<< std::string(SourceMgr.getBufferName(FileStart)) << "";84return true;85}8687if (isCodeCompletionEnabled() &&88SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) {89CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID);90CodeCompletionLoc =91CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset);92}9394Lexer *TheLexer = new Lexer(FID, *InputFile, *this, IsFirstIncludeOfFile);95if (getPreprocessorOpts().DependencyDirectivesForFile &&96FID != PredefinesFileID) {97if (OptionalFileEntryRef File = SourceMgr.getFileEntryRefForID(FID)) {98if (std::optional<ArrayRef<dependency_directives_scan::Directive>>99DepDirectives =100getPreprocessorOpts().DependencyDirectivesForFile(*File)) {101TheLexer->DepDirectives = *DepDirectives;102}103}104}105106EnterSourceFileWithLexer(TheLexer, CurDir);107return false;108}109110/// EnterSourceFileWithLexer - Add a source file to the top of the include stack111/// and start lexing tokens from it instead of the current buffer.112void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,113ConstSearchDirIterator CurDir) {114PreprocessorLexer *PrevPPLexer = CurPPLexer;115116// Add the current lexer to the include stack.117if (CurPPLexer || CurTokenLexer)118PushIncludeMacroStack();119120CurLexer.reset(TheLexer);121CurPPLexer = TheLexer;122CurDirLookup = CurDir;123CurLexerSubmodule = nullptr;124if (CurLexerCallback != CLK_LexAfterModuleImport)125CurLexerCallback = TheLexer->isDependencyDirectivesLexer()126? CLK_DependencyDirectivesLexer127: CLK_Lexer;128129// Notify the client, if desired, that we are in a new source file.130if (Callbacks && !CurLexer->Is_PragmaLexer) {131SrcMgr::CharacteristicKind FileType =132SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());133134FileID PrevFID;135SourceLocation EnterLoc;136if (PrevPPLexer) {137PrevFID = PrevPPLexer->getFileID();138EnterLoc = PrevPPLexer->getSourceLocation();139}140Callbacks->FileChanged(CurLexer->getFileLoc(), PPCallbacks::EnterFile,141FileType, PrevFID);142Callbacks->LexedFileChanged(CurLexer->getFileID(),143PPCallbacks::LexedFileChangeReason::EnterFile,144FileType, PrevFID, EnterLoc);145}146}147148/// EnterMacro - Add a Macro to the top of the include stack and start lexing149/// tokens from it instead of the current buffer.150void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,151MacroInfo *Macro, MacroArgs *Args) {152std::unique_ptr<TokenLexer> TokLexer;153if (NumCachedTokenLexers == 0) {154TokLexer = std::make_unique<TokenLexer>(Tok, ILEnd, Macro, Args, *this);155} else {156TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);157TokLexer->Init(Tok, ILEnd, Macro, Args);158}159160PushIncludeMacroStack();161CurDirLookup = nullptr;162CurTokenLexer = std::move(TokLexer);163if (CurLexerCallback != CLK_LexAfterModuleImport)164CurLexerCallback = CLK_TokenLexer;165}166167/// EnterTokenStream - Add a "macro" context to the top of the include stack,168/// which will cause the lexer to start returning the specified tokens.169///170/// If DisableMacroExpansion is true, tokens lexed from the token stream will171/// not be subject to further macro expansion. Otherwise, these tokens will172/// be re-macro-expanded when/if expansion is enabled.173///174/// If OwnsTokens is false, this method assumes that the specified stream of175/// tokens has a permanent owner somewhere, so they do not need to be copied.176/// If it is true, it assumes the array of tokens is allocated with new[] and177/// must be freed.178///179void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,180bool DisableMacroExpansion, bool OwnsTokens,181bool IsReinject) {182if (CurLexerCallback == CLK_CachingLexer) {183if (CachedLexPos < CachedTokens.size()) {184assert(IsReinject && "new tokens in the middle of cached stream");185// We're entering tokens into the middle of our cached token stream. We186// can't represent that, so just insert the tokens into the buffer.187CachedTokens.insert(CachedTokens.begin() + CachedLexPos,188Toks, Toks + NumToks);189if (OwnsTokens)190delete [] Toks;191return;192}193194// New tokens are at the end of the cached token sequnece; insert the195// token stream underneath the caching lexer.196ExitCachingLexMode();197EnterTokenStream(Toks, NumToks, DisableMacroExpansion, OwnsTokens,198IsReinject);199EnterCachingLexMode();200return;201}202203// Create a macro expander to expand from the specified token stream.204std::unique_ptr<TokenLexer> TokLexer;205if (NumCachedTokenLexers == 0) {206TokLexer = std::make_unique<TokenLexer>(207Toks, NumToks, DisableMacroExpansion, OwnsTokens, IsReinject, *this);208} else {209TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);210TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens,211IsReinject);212}213214// Save our current state.215PushIncludeMacroStack();216CurDirLookup = nullptr;217CurTokenLexer = std::move(TokLexer);218if (CurLexerCallback != CLK_LexAfterModuleImport)219CurLexerCallback = CLK_TokenLexer;220}221222/// Compute the relative path that names the given file relative to223/// the given directory.224static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir,225FileEntryRef File, SmallString<128> &Result) {226Result.clear();227228StringRef FilePath = File.getDir().getName();229StringRef Path = FilePath;230while (!Path.empty()) {231if (auto CurDir = FM.getDirectory(Path)) {232if (*CurDir == Dir) {233Result = FilePath.substr(Path.size());234llvm::sys::path::append(Result,235llvm::sys::path::filename(File.getName()));236return;237}238}239240Path = llvm::sys::path::parent_path(Path);241}242243Result = File.getName();244}245246void Preprocessor::PropagateLineStartLeadingSpaceInfo(Token &Result) {247if (CurTokenLexer) {248CurTokenLexer->PropagateLineStartLeadingSpaceInfo(Result);249return;250}251if (CurLexer) {252CurLexer->PropagateLineStartLeadingSpaceInfo(Result);253return;254}255// FIXME: Handle other kinds of lexers? It generally shouldn't matter,256// but it might if they're empty?257}258259/// Determine the location to use as the end of the buffer for a lexer.260///261/// If the file ends with a newline, form the EOF token on the newline itself,262/// rather than "on the line following it", which doesn't exist. This makes263/// diagnostics relating to the end of file include the last file that the user264/// actually typed, which is goodness.265const char *Preprocessor::getCurLexerEndPos() {266const char *EndPos = CurLexer->BufferEnd;267if (EndPos != CurLexer->BufferStart &&268(EndPos[-1] == '\n' || EndPos[-1] == '\r')) {269--EndPos;270271// Handle \n\r and \r\n:272if (EndPos != CurLexer->BufferStart &&273(EndPos[-1] == '\n' || EndPos[-1] == '\r') &&274EndPos[-1] != EndPos[0])275--EndPos;276}277278return EndPos;279}280281static void collectAllSubModulesWithUmbrellaHeader(282const Module &Mod, SmallVectorImpl<const Module *> &SubMods) {283if (Mod.getUmbrellaHeaderAsWritten())284SubMods.push_back(&Mod);285for (auto *M : Mod.submodules())286collectAllSubModulesWithUmbrellaHeader(*M, SubMods);287}288289void Preprocessor::diagnoseMissingHeaderInUmbrellaDir(const Module &Mod) {290std::optional<Module::Header> UmbrellaHeader =291Mod.getUmbrellaHeaderAsWritten();292assert(UmbrellaHeader && "Module must use umbrella header");293const FileID &File = SourceMgr.translateFile(UmbrellaHeader->Entry);294SourceLocation ExpectedHeadersLoc = SourceMgr.getLocForEndOfFile(File);295if (getDiagnostics().isIgnored(diag::warn_uncovered_module_header,296ExpectedHeadersLoc))297return;298299ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();300OptionalDirectoryEntryRef Dir = Mod.getEffectiveUmbrellaDir();301llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();302std::error_code EC;303for (llvm::vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC),304End;305Entry != End && !EC; Entry.increment(EC)) {306using llvm::StringSwitch;307308// Check whether this entry has an extension typically associated with309// headers.310if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->path()))311.Cases(".h", ".H", ".hh", ".hpp", true)312.Default(false))313continue;314315if (auto Header = getFileManager().getOptionalFileRef(Entry->path()))316if (!getSourceManager().hasFileInfo(*Header)) {317if (!ModMap.isHeaderInUnavailableModule(*Header)) {318// Find the relative path that would access this header.319SmallString<128> RelativePath;320computeRelativePath(FileMgr, *Dir, *Header, RelativePath);321Diag(ExpectedHeadersLoc, diag::warn_uncovered_module_header)322<< Mod.getFullModuleName() << RelativePath;323}324}325}326}327328/// HandleEndOfFile - This callback is invoked when the lexer hits the end of329/// the current file. This either returns the EOF token or pops a level off330/// the include stack and keeps going.331bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {332assert(!CurTokenLexer &&333"Ending a file when currently in a macro!");334335SourceLocation UnclosedSafeBufferOptOutLoc;336337if (IncludeMacroStack.empty() &&338isPPInSafeBufferOptOutRegion(UnclosedSafeBufferOptOutLoc)) {339// To warn if a "-Wunsafe-buffer-usage" opt-out region is still open by the340// end of a file.341Diag(UnclosedSafeBufferOptOutLoc,342diag::err_pp_unclosed_pragma_unsafe_buffer_usage);343}344// If we have an unclosed module region from a pragma at the end of a345// module, complain and close it now.346const bool LeavingSubmodule = CurLexer && CurLexerSubmodule;347if ((LeavingSubmodule || IncludeMacroStack.empty()) &&348!BuildingSubmoduleStack.empty() &&349BuildingSubmoduleStack.back().IsPragma) {350Diag(BuildingSubmoduleStack.back().ImportLoc,351diag::err_pp_module_begin_without_module_end);352Module *M = LeaveSubmodule(/*ForPragma*/true);353354Result.startToken();355const char *EndPos = getCurLexerEndPos();356CurLexer->BufferPtr = EndPos;357CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);358Result.setAnnotationEndLoc(Result.getLocation());359Result.setAnnotationValue(M);360return true;361}362363// See if this file had a controlling macro.364if (CurPPLexer) { // Not ending a macro, ignore it.365if (const IdentifierInfo *ControllingMacro =366CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {367// Okay, this has a controlling macro, remember in HeaderFileInfo.368if (OptionalFileEntryRef FE = CurPPLexer->getFileEntry()) {369HeaderInfo.SetFileControllingMacro(*FE, ControllingMacro);370if (MacroInfo *MI = getMacroInfo(ControllingMacro))371MI->setUsedForHeaderGuard(true);372if (const IdentifierInfo *DefinedMacro =373CurPPLexer->MIOpt.GetDefinedMacro()) {374if (!isMacroDefined(ControllingMacro) &&375DefinedMacro != ControllingMacro &&376CurLexer->isFirstTimeLexingFile()) {377378// If the edit distance between the two macros is more than 50%,379// DefinedMacro may not be header guard, or can be header guard of380// another header file. Therefore, it maybe defining something381// completely different. This can be observed in the wild when382// handling feature macros or header guards in different files.383384const StringRef ControllingMacroName = ControllingMacro->getName();385const StringRef DefinedMacroName = DefinedMacro->getName();386const size_t MaxHalfLength = std::max(ControllingMacroName.size(),387DefinedMacroName.size()) / 2;388const unsigned ED = ControllingMacroName.edit_distance(389DefinedMacroName, true, MaxHalfLength);390if (ED <= MaxHalfLength) {391// Emit a warning for a bad header guard.392Diag(CurPPLexer->MIOpt.GetMacroLocation(),393diag::warn_header_guard)394<< CurPPLexer->MIOpt.GetMacroLocation() << ControllingMacro;395Diag(CurPPLexer->MIOpt.GetDefinedLocation(),396diag::note_header_guard)397<< CurPPLexer->MIOpt.GetDefinedLocation() << DefinedMacro398<< ControllingMacro399<< FixItHint::CreateReplacement(400CurPPLexer->MIOpt.GetDefinedLocation(),401ControllingMacro->getName());402}403}404}405}406}407}408409// Complain about reaching a true EOF within arc_cf_code_audited.410// We don't want to complain about reaching the end of a macro411// instantiation or a _Pragma.412if (PragmaARCCFCodeAuditedInfo.second.isValid() && !isEndOfMacro &&413!(CurLexer && CurLexer->Is_PragmaLexer)) {414Diag(PragmaARCCFCodeAuditedInfo.second,415diag::err_pp_eof_in_arc_cf_code_audited);416417// Recover by leaving immediately.418PragmaARCCFCodeAuditedInfo = {nullptr, SourceLocation()};419}420421// Complain about reaching a true EOF within assume_nonnull.422// We don't want to complain about reaching the end of a macro423// instantiation or a _Pragma.424if (PragmaAssumeNonNullLoc.isValid() &&425!isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {426// If we're at the end of generating a preamble, we should record the427// unterminated \#pragma clang assume_nonnull so we can restore it later428// when the preamble is loaded into the main file.429if (isRecordingPreamble() && isInPrimaryFile())430PreambleRecordedPragmaAssumeNonNullLoc = PragmaAssumeNonNullLoc;431else432Diag(PragmaAssumeNonNullLoc, diag::err_pp_eof_in_assume_nonnull);433// Recover by leaving immediately.434PragmaAssumeNonNullLoc = SourceLocation();435}436437bool LeavingPCHThroughHeader = false;438439// If this is a #include'd file, pop it off the include stack and continue440// lexing the #includer file.441if (!IncludeMacroStack.empty()) {442443// If we lexed the code-completion file, act as if we reached EOF.444if (isCodeCompletionEnabled() && CurPPLexer &&445SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==446CodeCompletionFileLoc) {447assert(CurLexer && "Got EOF but no current lexer set!");448Result.startToken();449CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);450CurLexer.reset();451452CurPPLexer = nullptr;453recomputeCurLexerKind();454return true;455}456457if (!isEndOfMacro && CurPPLexer &&458(SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid() ||459// Predefines file doesn't have a valid include location.460(PredefinesFileID.isValid() &&461CurPPLexer->getFileID() == PredefinesFileID))) {462// Notify SourceManager to record the number of FileIDs that were created463// during lexing of the #include'd file.464unsigned NumFIDs =465SourceMgr.local_sloc_entry_size() -466CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/;467SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);468}469470bool ExitedFromPredefinesFile = false;471FileID ExitedFID;472if (!isEndOfMacro && CurPPLexer) {473ExitedFID = CurPPLexer->getFileID();474475assert(PredefinesFileID.isValid() &&476"HandleEndOfFile is called before PredefinesFileId is set");477ExitedFromPredefinesFile = (PredefinesFileID == ExitedFID);478}479480if (LeavingSubmodule) {481// We're done with this submodule.482Module *M = LeaveSubmodule(/*ForPragma*/false);483484// Notify the parser that we've left the module.485const char *EndPos = getCurLexerEndPos();486Result.startToken();487CurLexer->BufferPtr = EndPos;488CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);489Result.setAnnotationEndLoc(Result.getLocation());490Result.setAnnotationValue(M);491}492493bool FoundPCHThroughHeader = false;494if (CurPPLexer && creatingPCHWithThroughHeader() &&495isPCHThroughHeader(496SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))497FoundPCHThroughHeader = true;498499// We're done with the #included file.500RemoveTopOfLexerStack();501502// Propagate info about start-of-line/leading white-space/etc.503PropagateLineStartLeadingSpaceInfo(Result);504505// Notify the client, if desired, that we are in a new source file.506if (Callbacks && !isEndOfMacro && CurPPLexer) {507SourceLocation Loc = CurPPLexer->getSourceLocation();508SrcMgr::CharacteristicKind FileType =509SourceMgr.getFileCharacteristic(Loc);510Callbacks->FileChanged(Loc, PPCallbacks::ExitFile, FileType, ExitedFID);511Callbacks->LexedFileChanged(CurPPLexer->getFileID(),512PPCallbacks::LexedFileChangeReason::ExitFile,513FileType, ExitedFID, Loc);514}515516// Restore conditional stack as well as the recorded517// \#pragma clang assume_nonnull from the preamble right after exiting518// from the predefines file.519if (ExitedFromPredefinesFile) {520replayPreambleConditionalStack();521if (PreambleRecordedPragmaAssumeNonNullLoc.isValid())522PragmaAssumeNonNullLoc = PreambleRecordedPragmaAssumeNonNullLoc;523}524525if (!isEndOfMacro && CurPPLexer && FoundPCHThroughHeader &&526(isInPrimaryFile() ||527CurPPLexer->getFileID() == getPredefinesFileID())) {528// Leaving the through header. Continue directly to end of main file529// processing.530LeavingPCHThroughHeader = true;531} else {532// Client should lex another token unless we generated an EOM.533return LeavingSubmodule;534}535}536// If this is the end of the main file, form an EOF token.537assert(CurLexer && "Got EOF but no current lexer set!");538const char *EndPos = getCurLexerEndPos();539Result.startToken();540CurLexer->BufferPtr = EndPos;541542if (getLangOpts().IncrementalExtensions) {543CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_repl_input_end);544Result.setAnnotationEndLoc(Result.getLocation());545Result.setAnnotationValue(nullptr);546} else {547CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);548}549550if (isCodeCompletionEnabled()) {551// Inserting the code-completion point increases the source buffer by 1,552// but the main FileID was created before inserting the point.553// Compensate by reducing the EOF location by 1, otherwise the location554// will point to the next FileID.555// FIXME: This is hacky, the code-completion point should probably be556// inserted before the main FileID is created.557if (CurLexer->getFileLoc() == CodeCompletionFileLoc)558Result.setLocation(Result.getLocation().getLocWithOffset(-1));559}560561if (creatingPCHWithThroughHeader() && !LeavingPCHThroughHeader) {562// Reached the end of the compilation without finding the through header.563Diag(CurLexer->getFileLoc(), diag::err_pp_through_header_not_seen)564<< PPOpts->PCHThroughHeader << 0;565}566567if (!isIncrementalProcessingEnabled())568// We're done with lexing.569CurLexer.reset();570571if (!isIncrementalProcessingEnabled())572CurPPLexer = nullptr;573574if (TUKind == TU_Complete) {575// This is the end of the top-level file. 'WarnUnusedMacroLocs' has576// collected all macro locations that we need to warn because they are not577// used.578for (WarnUnusedMacroLocsTy::iterator579I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end();580I!=E; ++I)581Diag(*I, diag::pp_macro_not_used);582}583584// If we are building a module that has an umbrella header, make sure that585// each of the headers within the directory, including all submodules, is586// covered by the umbrella header was actually included by the umbrella587// header.588if (Module *Mod = getCurrentModule()) {589llvm::SmallVector<const Module *, 4> AllMods;590collectAllSubModulesWithUmbrellaHeader(*Mod, AllMods);591for (auto *M : AllMods)592diagnoseMissingHeaderInUmbrellaDir(*M);593}594595return true;596}597598/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer599/// hits the end of its token stream.600bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {601assert(CurTokenLexer && !CurPPLexer &&602"Ending a macro when currently in a #include file!");603604if (!MacroExpandingLexersStack.empty() &&605MacroExpandingLexersStack.back().first == CurTokenLexer.get())606removeCachedMacroExpandedTokensOfLastLexer();607608// Delete or cache the now-dead macro expander.609if (NumCachedTokenLexers == TokenLexerCacheSize)610CurTokenLexer.reset();611else612TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);613614// Handle this like a #include file being popped off the stack.615return HandleEndOfFile(Result, true);616}617618/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the619/// lexer stack. This should only be used in situations where the current620/// state of the top-of-stack lexer is unknown.621void Preprocessor::RemoveTopOfLexerStack() {622assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");623624if (CurTokenLexer) {625// Delete or cache the now-dead macro expander.626if (NumCachedTokenLexers == TokenLexerCacheSize)627CurTokenLexer.reset();628else629TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);630}631632PopIncludeMacroStack();633}634635/// HandleMicrosoftCommentPaste - When the macro expander pastes together a636/// comment (/##/) in microsoft mode, this method handles updating the current637/// state, returning the token on the next source line.638void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {639assert(CurTokenLexer && !CurPPLexer &&640"Pasted comment can only be formed from macro");641// We handle this by scanning for the closest real lexer, switching it to642// raw mode and preprocessor mode. This will cause it to return \n as an643// explicit EOD token.644PreprocessorLexer *FoundLexer = nullptr;645bool LexerWasInPPMode = false;646for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {647if (ISI.ThePPLexer == nullptr) continue; // Scan for a real lexer.648649// Once we find a real lexer, mark it as raw mode (disabling macro650// expansions) and preprocessor mode (return EOD). We know that the lexer651// was *not* in raw mode before, because the macro that the comment came652// from was expanded. However, it could have already been in preprocessor653// mode (#if COMMENT) in which case we have to return it to that mode and654// return EOD.655FoundLexer = ISI.ThePPLexer;656FoundLexer->LexingRawMode = true;657LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;658FoundLexer->ParsingPreprocessorDirective = true;659break;660}661662// Okay, we either found and switched over the lexer, or we didn't find a663// lexer. In either case, finish off the macro the comment came from, getting664// the next token.665if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);666667// Discarding comments as long as we don't have EOF or EOD. This 'comments668// out' the rest of the line, including any tokens that came from other macros669// that were active, as in:670// #define submacro a COMMENT b671// submacro c672// which should lex to 'a' only: 'b' and 'c' should be removed.673while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof))674Lex(Tok);675676// If we got an eod token, then we successfully found the end of the line.677if (Tok.is(tok::eod)) {678assert(FoundLexer && "Can't get end of line without an active lexer");679// Restore the lexer back to normal mode instead of raw mode.680FoundLexer->LexingRawMode = false;681682// If the lexer was already in preprocessor mode, just return the EOD token683// to finish the preprocessor line.684if (LexerWasInPPMode) return;685686// Otherwise, switch out of PP mode and return the next lexed token.687FoundLexer->ParsingPreprocessorDirective = false;688return Lex(Tok);689}690691// If we got an EOF token, then we reached the end of the token stream but692// didn't find an explicit \n. This can only happen if there was no lexer693// active (an active lexer would return EOD at EOF if there was no \n in694// preprocessor directive mode), so just return EOF as our token.695assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");696}697698void Preprocessor::EnterSubmodule(Module *M, SourceLocation ImportLoc,699bool ForPragma) {700if (!getLangOpts().ModulesLocalVisibility) {701// Just track that we entered this submodule.702BuildingSubmoduleStack.push_back(703BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,704PendingModuleMacroNames.size()));705if (Callbacks)706Callbacks->EnteredSubmodule(M, ImportLoc, ForPragma);707return;708}709710// Resolve as much of the module definition as we can now, before we enter711// one of its headers.712// FIXME: Can we enable Complain here?713// FIXME: Can we do this when local visibility is disabled?714ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();715ModMap.resolveExports(M, /*Complain=*/false);716ModMap.resolveUses(M, /*Complain=*/false);717ModMap.resolveConflicts(M, /*Complain=*/false);718719// If this is the first time we've entered this module, set up its state.720auto R = Submodules.insert(std::make_pair(M, SubmoduleState()));721auto &State = R.first->second;722bool FirstTime = R.second;723if (FirstTime) {724// Determine the set of starting macros for this submodule; take these725// from the "null" module (the predefines buffer).726//727// FIXME: If we have local visibility but not modules enabled, the728// NullSubmoduleState is polluted by #defines in the top-level source729// file.730auto &StartingMacros = NullSubmoduleState.Macros;731732// Restore to the starting state.733// FIXME: Do this lazily, when each macro name is first referenced.734for (auto &Macro : StartingMacros) {735// Skip uninteresting macros.736if (!Macro.second.getLatest() &&737Macro.second.getOverriddenMacros().empty())738continue;739740MacroState MS(Macro.second.getLatest());741MS.setOverriddenMacros(*this, Macro.second.getOverriddenMacros());742State.Macros.insert(std::make_pair(Macro.first, std::move(MS)));743}744}745746// Track that we entered this module.747BuildingSubmoduleStack.push_back(748BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,749PendingModuleMacroNames.size()));750751if (Callbacks)752Callbacks->EnteredSubmodule(M, ImportLoc, ForPragma);753754// Switch to this submodule as the current submodule.755CurSubmoduleState = &State;756757// This module is visible to itself.758if (FirstTime)759makeModuleVisible(M, ImportLoc);760}761762bool Preprocessor::needModuleMacros() const {763// If we're not within a submodule, we never need to create ModuleMacros.764if (BuildingSubmoduleStack.empty())765return false;766// If we are tracking module macro visibility even for textually-included767// headers, we need ModuleMacros.768if (getLangOpts().ModulesLocalVisibility)769return true;770// Otherwise, we only need module macros if we're actually compiling a module771// interface.772return getLangOpts().isCompilingModule();773}774775Module *Preprocessor::LeaveSubmodule(bool ForPragma) {776if (BuildingSubmoduleStack.empty() ||777BuildingSubmoduleStack.back().IsPragma != ForPragma) {778assert(ForPragma && "non-pragma module enter/leave mismatch");779return nullptr;780}781782auto &Info = BuildingSubmoduleStack.back();783784Module *LeavingMod = Info.M;785SourceLocation ImportLoc = Info.ImportLoc;786787if (!needModuleMacros() ||788(!getLangOpts().ModulesLocalVisibility &&789LeavingMod->getTopLevelModuleName() != getLangOpts().CurrentModule)) {790// If we don't need module macros, or this is not a module for which we791// are tracking macro visibility, don't build any, and preserve the list792// of pending names for the surrounding submodule.793BuildingSubmoduleStack.pop_back();794795if (Callbacks)796Callbacks->LeftSubmodule(LeavingMod, ImportLoc, ForPragma);797798makeModuleVisible(LeavingMod, ImportLoc);799return LeavingMod;800}801802// Create ModuleMacros for any macros defined in this submodule.803llvm::SmallPtrSet<const IdentifierInfo*, 8> VisitedMacros;804for (unsigned I = Info.OuterPendingModuleMacroNames;805I != PendingModuleMacroNames.size(); ++I) {806auto *II = PendingModuleMacroNames[I];807if (!VisitedMacros.insert(II).second)808continue;809810auto MacroIt = CurSubmoduleState->Macros.find(II);811if (MacroIt == CurSubmoduleState->Macros.end())812continue;813auto &Macro = MacroIt->second;814815// Find the starting point for the MacroDirective chain in this submodule.816MacroDirective *OldMD = nullptr;817auto *OldState = Info.OuterSubmoduleState;818if (getLangOpts().ModulesLocalVisibility)819OldState = &NullSubmoduleState;820if (OldState && OldState != CurSubmoduleState) {821// FIXME: It'd be better to start at the state from when we most recently822// entered this submodule, but it doesn't really matter.823auto &OldMacros = OldState->Macros;824auto OldMacroIt = OldMacros.find(II);825if (OldMacroIt == OldMacros.end())826OldMD = nullptr;827else828OldMD = OldMacroIt->second.getLatest();829}830831// This module may have exported a new macro. If so, create a ModuleMacro832// representing that fact.833bool ExplicitlyPublic = false;834for (auto *MD = Macro.getLatest(); MD != OldMD; MD = MD->getPrevious()) {835assert(MD && "broken macro directive chain");836837if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {838// The latest visibility directive for a name in a submodule affects839// all the directives that come before it.840if (VisMD->isPublic())841ExplicitlyPublic = true;842else if (!ExplicitlyPublic)843// Private with no following public directive: not exported.844break;845} else {846MacroInfo *Def = nullptr;847if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))848Def = DefMD->getInfo();849850// FIXME: Issue a warning if multiple headers for the same submodule851// define a macro, rather than silently ignoring all but the first.852bool IsNew;853// Don't bother creating a module macro if it would represent a #undef854// that doesn't override anything.855if (Def || !Macro.getOverriddenMacros().empty())856addModuleMacro(LeavingMod, II, Def, Macro.getOverriddenMacros(),857IsNew);858859if (!getLangOpts().ModulesLocalVisibility) {860// This macro is exposed to the rest of this compilation as a861// ModuleMacro; we don't need to track its MacroDirective any more.862Macro.setLatest(nullptr);863Macro.setOverriddenMacros(*this, {});864}865break;866}867}868}869PendingModuleMacroNames.resize(Info.OuterPendingModuleMacroNames);870871// FIXME: Before we leave this submodule, we should parse all the other872// headers within it. Otherwise, we're left with an inconsistent state873// where we've made the module visible but don't yet have its complete874// contents.875876// Put back the outer module's state, if we're tracking it.877if (getLangOpts().ModulesLocalVisibility)878CurSubmoduleState = Info.OuterSubmoduleState;879880BuildingSubmoduleStack.pop_back();881882if (Callbacks)883Callbacks->LeftSubmodule(LeavingMod, ImportLoc, ForPragma);884885// A nested #include makes the included submodule visible.886makeModuleVisible(LeavingMod, ImportLoc);887return LeavingMod;888}889890891