Path: blob/main/contrib/llvm-project/clang/lib/Lex/Preprocessor.cpp
35232 views
//===- Preprocessor.cpp - C Language Family Preprocessor Implementation ---===//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 the Preprocessor interface.9//10//===----------------------------------------------------------------------===//11//12// Options to support:13// -H - Print the name of each header file used.14// -d[DNI] - Dump various things.15// -fworking-directory - #line's with preprocessor's working dir.16// -fpreprocessed17// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD18// -W*19// -w20//21// Messages to emit:22// "Multiple include guards may be useful for:\n"23//24//===----------------------------------------------------------------------===//2526#include "clang/Lex/Preprocessor.h"27#include "clang/Basic/Builtins.h"28#include "clang/Basic/FileManager.h"29#include "clang/Basic/FileSystemStatCache.h"30#include "clang/Basic/IdentifierTable.h"31#include "clang/Basic/LLVM.h"32#include "clang/Basic/LangOptions.h"33#include "clang/Basic/Module.h"34#include "clang/Basic/SourceLocation.h"35#include "clang/Basic/SourceManager.h"36#include "clang/Basic/TargetInfo.h"37#include "clang/Lex/CodeCompletionHandler.h"38#include "clang/Lex/ExternalPreprocessorSource.h"39#include "clang/Lex/HeaderSearch.h"40#include "clang/Lex/LexDiagnostic.h"41#include "clang/Lex/Lexer.h"42#include "clang/Lex/LiteralSupport.h"43#include "clang/Lex/MacroArgs.h"44#include "clang/Lex/MacroInfo.h"45#include "clang/Lex/ModuleLoader.h"46#include "clang/Lex/Pragma.h"47#include "clang/Lex/PreprocessingRecord.h"48#include "clang/Lex/PreprocessorLexer.h"49#include "clang/Lex/PreprocessorOptions.h"50#include "clang/Lex/ScratchBuffer.h"51#include "clang/Lex/Token.h"52#include "clang/Lex/TokenLexer.h"53#include "llvm/ADT/APInt.h"54#include "llvm/ADT/ArrayRef.h"55#include "llvm/ADT/DenseMap.h"56#include "llvm/ADT/STLExtras.h"57#include "llvm/ADT/SmallString.h"58#include "llvm/ADT/SmallVector.h"59#include "llvm/ADT/StringRef.h"60#include "llvm/ADT/iterator_range.h"61#include "llvm/Support/Capacity.h"62#include "llvm/Support/ErrorHandling.h"63#include "llvm/Support/MemoryBuffer.h"64#include "llvm/Support/raw_ostream.h"65#include <algorithm>66#include <cassert>67#include <memory>68#include <optional>69#include <string>70#include <utility>71#include <vector>7273using namespace clang;7475/// Minimum distance between two check points, in tokens.76static constexpr unsigned CheckPointStepSize = 1024;7778LLVM_INSTANTIATE_REGISTRY(PragmaHandlerRegistry)7980ExternalPreprocessorSource::~ExternalPreprocessorSource() = default;8182Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts,83DiagnosticsEngine &diags, const LangOptions &opts,84SourceManager &SM, HeaderSearch &Headers,85ModuleLoader &TheModuleLoader,86IdentifierInfoLookup *IILookup, bool OwnsHeaders,87TranslationUnitKind TUKind)88: PPOpts(std::move(PPOpts)), Diags(&diags), LangOpts(opts),89FileMgr(Headers.getFileMgr()), SourceMgr(SM),90ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers),91TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),92// As the language options may have not been loaded yet (when93// deserializing an ASTUnit), adding keywords to the identifier table is94// deferred to Preprocessor::Initialize().95Identifiers(IILookup), PragmaHandlers(new PragmaNamespace(StringRef())),96TUKind(TUKind), SkipMainFilePreamble(0, true),97CurSubmoduleState(&NullSubmoduleState) {98OwnsHeaderSearch = OwnsHeaders;99100// Default to discarding comments.101KeepComments = false;102KeepMacroComments = false;103SuppressIncludeNotFoundError = false;104105// Macro expansion is enabled.106DisableMacroExpansion = false;107MacroExpansionInDirectivesOverride = false;108InMacroArgs = false;109ArgMacro = nullptr;110InMacroArgPreExpansion = false;111NumCachedTokenLexers = 0;112PragmasEnabled = true;113ParsingIfOrElifDirective = false;114PreprocessedOutput = false;115116// We haven't read anything from the external source.117ReadMacrosFromExternalSource = false;118119BuiltinInfo = std::make_unique<Builtin::Context>();120121// "Poison" __VA_ARGS__, __VA_OPT__ which can only appear in the expansion of122// a macro. They get unpoisoned where it is allowed.123(Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();124SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);125(Ident__VA_OPT__ = getIdentifierInfo("__VA_OPT__"))->setIsPoisoned();126SetPoisonReason(Ident__VA_OPT__,diag::ext_pp_bad_vaopt_use);127128// Initialize the pragma handlers.129RegisterBuiltinPragmas();130131// Initialize builtin macros like __LINE__ and friends.132RegisterBuiltinMacros();133134if(LangOpts.Borland) {135Ident__exception_info = getIdentifierInfo("_exception_info");136Ident___exception_info = getIdentifierInfo("__exception_info");137Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");138Ident__exception_code = getIdentifierInfo("_exception_code");139Ident___exception_code = getIdentifierInfo("__exception_code");140Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");141Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");142Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");143Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");144} else {145Ident__exception_info = Ident__exception_code = nullptr;146Ident__abnormal_termination = Ident___exception_info = nullptr;147Ident___exception_code = Ident___abnormal_termination = nullptr;148Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;149Ident_AbnormalTermination = nullptr;150}151152// Default incremental processing to -fincremental-extensions, clients can153// override with `enableIncrementalProcessing` if desired.154IncrementalProcessing = LangOpts.IncrementalExtensions;155156// If using a PCH where a #pragma hdrstop is expected, start skipping tokens.157if (usingPCHWithPragmaHdrStop())158SkippingUntilPragmaHdrStop = true;159160// If using a PCH with a through header, start skipping tokens.161if (!this->PPOpts->PCHThroughHeader.empty() &&162!this->PPOpts->ImplicitPCHInclude.empty())163SkippingUntilPCHThroughHeader = true;164165if (this->PPOpts->GeneratePreamble)166PreambleConditionalStack.startRecording();167168MaxTokens = LangOpts.MaxTokens;169}170171Preprocessor::~Preprocessor() {172assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");173174IncludeMacroStack.clear();175176// Free any cached macro expanders.177// This populates MacroArgCache, so all TokenLexers need to be destroyed178// before the code below that frees up the MacroArgCache list.179std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);180CurTokenLexer.reset();181182// Free any cached MacroArgs.183for (MacroArgs *ArgList = MacroArgCache; ArgList;)184ArgList = ArgList->deallocate();185186// Delete the header search info, if we own it.187if (OwnsHeaderSearch)188delete &HeaderInfo;189}190191void Preprocessor::Initialize(const TargetInfo &Target,192const TargetInfo *AuxTarget) {193assert((!this->Target || this->Target == &Target) &&194"Invalid override of target information");195this->Target = &Target;196197assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&198"Invalid override of aux target information.");199this->AuxTarget = AuxTarget;200201// Initialize information about built-ins.202BuiltinInfo->InitializeTarget(Target, AuxTarget);203HeaderInfo.setTarget(Target);204205// Populate the identifier table with info about keywords for the current language.206Identifiers.AddKeywords(LangOpts);207208// Initialize the __FTL_EVAL_METHOD__ macro to the TargetInfo.209setTUFPEvalMethod(getTargetInfo().getFPEvalMethod());210211if (getLangOpts().getFPEvalMethod() == LangOptions::FEM_UnsetOnCommandLine)212// Use setting from TargetInfo.213setCurrentFPEvalMethod(SourceLocation(), Target.getFPEvalMethod());214else215// Set initial value of __FLT_EVAL_METHOD__ from the command line.216setCurrentFPEvalMethod(SourceLocation(), getLangOpts().getFPEvalMethod());217}218219void Preprocessor::InitializeForModelFile() {220NumEnteredSourceFiles = 0;221222// Reset pragmas223PragmaHandlersBackup = std::move(PragmaHandlers);224PragmaHandlers = std::make_unique<PragmaNamespace>(StringRef());225RegisterBuiltinPragmas();226227// Reset PredefinesFileID228PredefinesFileID = FileID();229}230231void Preprocessor::FinalizeForModelFile() {232NumEnteredSourceFiles = 1;233234PragmaHandlers = std::move(PragmaHandlersBackup);235}236237void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {238llvm::errs() << tok::getTokenName(Tok.getKind());239240if (!Tok.isAnnotation())241llvm::errs() << " '" << getSpelling(Tok) << "'";242243if (!DumpFlags) return;244245llvm::errs() << "\t";246if (Tok.isAtStartOfLine())247llvm::errs() << " [StartOfLine]";248if (Tok.hasLeadingSpace())249llvm::errs() << " [LeadingSpace]";250if (Tok.isExpandDisabled())251llvm::errs() << " [ExpandDisabled]";252if (Tok.needsCleaning()) {253const char *Start = SourceMgr.getCharacterData(Tok.getLocation());254llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())255<< "']";256}257258llvm::errs() << "\tLoc=<";259DumpLocation(Tok.getLocation());260llvm::errs() << ">";261}262263void Preprocessor::DumpLocation(SourceLocation Loc) const {264Loc.print(llvm::errs(), SourceMgr);265}266267void Preprocessor::DumpMacro(const MacroInfo &MI) const {268llvm::errs() << "MACRO: ";269for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {270DumpToken(MI.getReplacementToken(i));271llvm::errs() << " ";272}273llvm::errs() << "\n";274}275276void Preprocessor::PrintStats() {277llvm::errs() << "\n*** Preprocessor Stats:\n";278llvm::errs() << NumDirectives << " directives found:\n";279llvm::errs() << " " << NumDefined << " #define.\n";280llvm::errs() << " " << NumUndefined << " #undef.\n";281llvm::errs() << " #include/#include_next/#import:\n";282llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";283llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";284llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";285llvm::errs() << " " << NumElse << " #else/#elif/#elifdef/#elifndef.\n";286llvm::errs() << " " << NumEndif << " #endif.\n";287llvm::errs() << " " << NumPragma << " #pragma.\n";288llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";289290llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"291<< NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "292<< NumFastMacroExpanded << " on the fast path.\n";293llvm::errs() << (NumFastTokenPaste+NumTokenPaste)294<< " token paste (##) operations performed, "295<< NumFastTokenPaste << " on the fast path.\n";296297llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";298299llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();300llvm::errs() << "\n Macro Expanded Tokens: "301<< llvm::capacity_in_bytes(MacroExpandedTokens);302llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();303// FIXME: List information for all submodules.304llvm::errs() << "\n Macros: "305<< llvm::capacity_in_bytes(CurSubmoduleState->Macros);306llvm::errs() << "\n #pragma push_macro Info: "307<< llvm::capacity_in_bytes(PragmaPushMacroInfo);308llvm::errs() << "\n Poison Reasons: "309<< llvm::capacity_in_bytes(PoisonReasons);310llvm::errs() << "\n Comment Handlers: "311<< llvm::capacity_in_bytes(CommentHandlers) << "\n";312}313314Preprocessor::macro_iterator315Preprocessor::macro_begin(bool IncludeExternalMacros) const {316if (IncludeExternalMacros && ExternalSource &&317!ReadMacrosFromExternalSource) {318ReadMacrosFromExternalSource = true;319ExternalSource->ReadDefinedMacros();320}321322// Make sure we cover all macros in visible modules.323for (const ModuleMacro &Macro : ModuleMacros)324CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState()));325326return CurSubmoduleState->Macros.begin();327}328329size_t Preprocessor::getTotalMemory() const {330return BP.getTotalMemory()331+ llvm::capacity_in_bytes(MacroExpandedTokens)332+ Predefines.capacity() /* Predefines buffer. */333// FIXME: Include sizes from all submodules, and include MacroInfo sizes,334// and ModuleMacros.335+ llvm::capacity_in_bytes(CurSubmoduleState->Macros)336+ llvm::capacity_in_bytes(PragmaPushMacroInfo)337+ llvm::capacity_in_bytes(PoisonReasons)338+ llvm::capacity_in_bytes(CommentHandlers);339}340341Preprocessor::macro_iterator342Preprocessor::macro_end(bool IncludeExternalMacros) const {343if (IncludeExternalMacros && ExternalSource &&344!ReadMacrosFromExternalSource) {345ReadMacrosFromExternalSource = true;346ExternalSource->ReadDefinedMacros();347}348349return CurSubmoduleState->Macros.end();350}351352/// Compares macro tokens with a specified token value sequence.353static bool MacroDefinitionEquals(const MacroInfo *MI,354ArrayRef<TokenValue> Tokens) {355return Tokens.size() == MI->getNumTokens() &&356std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());357}358359StringRef Preprocessor::getLastMacroWithSpelling(360SourceLocation Loc,361ArrayRef<TokenValue> Tokens) const {362SourceLocation BestLocation;363StringRef BestSpelling;364for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();365I != E; ++I) {366const MacroDirective::DefInfo367Def = I->second.findDirectiveAtLoc(Loc, SourceMgr);368if (!Def || !Def.getMacroInfo())369continue;370if (!Def.getMacroInfo()->isObjectLike())371continue;372if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))373continue;374SourceLocation Location = Def.getLocation();375// Choose the macro defined latest.376if (BestLocation.isInvalid() ||377(Location.isValid() &&378SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {379BestLocation = Location;380BestSpelling = I->first->getName();381}382}383return BestSpelling;384}385386void Preprocessor::recomputeCurLexerKind() {387if (CurLexer)388CurLexerCallback = CurLexer->isDependencyDirectivesLexer()389? CLK_DependencyDirectivesLexer390: CLK_Lexer;391else if (CurTokenLexer)392CurLexerCallback = CLK_TokenLexer;393else394CurLexerCallback = CLK_CachingLexer;395}396397bool Preprocessor::SetCodeCompletionPoint(FileEntryRef File,398unsigned CompleteLine,399unsigned CompleteColumn) {400assert(CompleteLine && CompleteColumn && "Starts from 1:1");401assert(!CodeCompletionFile && "Already set");402403// Load the actual file's contents.404std::optional<llvm::MemoryBufferRef> Buffer =405SourceMgr.getMemoryBufferForFileOrNone(File);406if (!Buffer)407return true;408409// Find the byte position of the truncation point.410const char *Position = Buffer->getBufferStart();411for (unsigned Line = 1; Line < CompleteLine; ++Line) {412for (; *Position; ++Position) {413if (*Position != '\r' && *Position != '\n')414continue;415416// Eat \r\n or \n\r as a single line.417if ((Position[1] == '\r' || Position[1] == '\n') &&418Position[0] != Position[1])419++Position;420++Position;421break;422}423}424425Position += CompleteColumn - 1;426427// If pointing inside the preamble, adjust the position at the beginning of428// the file after the preamble.429if (SkipMainFilePreamble.first &&430SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {431if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)432Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;433}434435if (Position > Buffer->getBufferEnd())436Position = Buffer->getBufferEnd();437438CodeCompletionFile = File;439CodeCompletionOffset = Position - Buffer->getBufferStart();440441auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(442Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier());443char *NewBuf = NewBuffer->getBufferStart();444char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);445*NewPos = '\0';446std::copy(Position, Buffer->getBufferEnd(), NewPos+1);447SourceMgr.overrideFileContents(File, std::move(NewBuffer));448449return false;450}451452void Preprocessor::CodeCompleteIncludedFile(llvm::StringRef Dir,453bool IsAngled) {454setCodeCompletionReached();455if (CodeComplete)456CodeComplete->CodeCompleteIncludedFile(Dir, IsAngled);457}458459void Preprocessor::CodeCompleteNaturalLanguage() {460setCodeCompletionReached();461if (CodeComplete)462CodeComplete->CodeCompleteNaturalLanguage();463}464465/// getSpelling - This method is used to get the spelling of a token into a466/// SmallVector. Note that the returned StringRef may not point to the467/// supplied buffer if a copy can be avoided.468StringRef Preprocessor::getSpelling(const Token &Tok,469SmallVectorImpl<char> &Buffer,470bool *Invalid) const {471// NOTE: this has to be checked *before* testing for an IdentifierInfo.472if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {473// Try the fast path.474if (const IdentifierInfo *II = Tok.getIdentifierInfo())475return II->getName();476}477478// Resize the buffer if we need to copy into it.479if (Tok.needsCleaning())480Buffer.resize(Tok.getLength());481482const char *Ptr = Buffer.data();483unsigned Len = getSpelling(Tok, Ptr, Invalid);484return StringRef(Ptr, Len);485}486487/// CreateString - Plop the specified string into a scratch buffer and return a488/// location for it. If specified, the source location provides a source489/// location for the token.490void Preprocessor::CreateString(StringRef Str, Token &Tok,491SourceLocation ExpansionLocStart,492SourceLocation ExpansionLocEnd) {493Tok.setLength(Str.size());494495const char *DestPtr;496SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);497498if (ExpansionLocStart.isValid())499Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,500ExpansionLocEnd, Str.size());501Tok.setLocation(Loc);502503// If this is a raw identifier or a literal token, set the pointer data.504if (Tok.is(tok::raw_identifier))505Tok.setRawIdentifierData(DestPtr);506else if (Tok.isLiteral())507Tok.setLiteralData(DestPtr);508}509510SourceLocation Preprocessor::SplitToken(SourceLocation Loc, unsigned Length) {511auto &SM = getSourceManager();512SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);513std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellingLoc);514bool Invalid = false;515StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);516if (Invalid)517return SourceLocation();518519// FIXME: We could consider re-using spelling for tokens we see repeatedly.520const char *DestPtr;521SourceLocation Spelling =522ScratchBuf->getToken(Buffer.data() + LocInfo.second, Length, DestPtr);523return SM.createTokenSplitLoc(Spelling, Loc, Loc.getLocWithOffset(Length));524}525526Module *Preprocessor::getCurrentModule() {527if (!getLangOpts().isCompilingModule())528return nullptr;529530return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);531}532533Module *Preprocessor::getCurrentModuleImplementation() {534if (!getLangOpts().isCompilingModuleImplementation())535return nullptr;536537return getHeaderSearchInfo().lookupModule(getLangOpts().ModuleName);538}539540//===----------------------------------------------------------------------===//541// Preprocessor Initialization Methods542//===----------------------------------------------------------------------===//543544/// EnterMainSourceFile - Enter the specified FileID as the main source file,545/// which implicitly adds the builtin defines etc.546void Preprocessor::EnterMainSourceFile() {547// We do not allow the preprocessor to reenter the main file. Doing so will548// cause FileID's to accumulate information from both runs (e.g. #line549// information) and predefined macros aren't guaranteed to be set properly.550assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");551FileID MainFileID = SourceMgr.getMainFileID();552553// If MainFileID is loaded it means we loaded an AST file, no need to enter554// a main file.555if (!SourceMgr.isLoadedFileID(MainFileID)) {556// Enter the main file source buffer.557EnterSourceFile(MainFileID, nullptr, SourceLocation());558559// If we've been asked to skip bytes in the main file (e.g., as part of a560// precompiled preamble), do so now.561if (SkipMainFilePreamble.first > 0)562CurLexer->SetByteOffset(SkipMainFilePreamble.first,563SkipMainFilePreamble.second);564565// Tell the header info that the main file was entered. If the file is later566// #imported, it won't be re-entered.567if (OptionalFileEntryRef FE = SourceMgr.getFileEntryRefForID(MainFileID))568markIncluded(*FE);569}570571// Preprocess Predefines to populate the initial preprocessor state.572std::unique_ptr<llvm::MemoryBuffer> SB =573llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");574assert(SB && "Cannot create predefined source buffer");575FileID FID = SourceMgr.createFileID(std::move(SB));576assert(FID.isValid() && "Could not create FileID for predefines?");577setPredefinesFileID(FID);578579// Start parsing the predefines.580EnterSourceFile(FID, nullptr, SourceLocation());581582if (!PPOpts->PCHThroughHeader.empty()) {583// Lookup and save the FileID for the through header. If it isn't found584// in the search path, it's a fatal error.585OptionalFileEntryRef File = LookupFile(586SourceLocation(), PPOpts->PCHThroughHeader,587/*isAngled=*/false, /*FromDir=*/nullptr, /*FromFile=*/nullptr,588/*CurDir=*/nullptr, /*SearchPath=*/nullptr, /*RelativePath=*/nullptr,589/*SuggestedModule=*/nullptr, /*IsMapped=*/nullptr,590/*IsFrameworkFound=*/nullptr);591if (!File) {592Diag(SourceLocation(), diag::err_pp_through_header_not_found)593<< PPOpts->PCHThroughHeader;594return;595}596setPCHThroughHeaderFileID(597SourceMgr.createFileID(*File, SourceLocation(), SrcMgr::C_User));598}599600// Skip tokens from the Predefines and if needed the main file.601if ((usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) ||602(usingPCHWithPragmaHdrStop() && SkippingUntilPragmaHdrStop))603SkipTokensWhileUsingPCH();604}605606void Preprocessor::setPCHThroughHeaderFileID(FileID FID) {607assert(PCHThroughHeaderFileID.isInvalid() &&608"PCHThroughHeaderFileID already set!");609PCHThroughHeaderFileID = FID;610}611612bool Preprocessor::isPCHThroughHeader(const FileEntry *FE) {613assert(PCHThroughHeaderFileID.isValid() &&614"Invalid PCH through header FileID");615return FE == SourceMgr.getFileEntryForID(PCHThroughHeaderFileID);616}617618bool Preprocessor::creatingPCHWithThroughHeader() {619return TUKind == TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&620PCHThroughHeaderFileID.isValid();621}622623bool Preprocessor::usingPCHWithThroughHeader() {624return TUKind != TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&625PCHThroughHeaderFileID.isValid();626}627628bool Preprocessor::creatingPCHWithPragmaHdrStop() {629return TUKind == TU_Prefix && PPOpts->PCHWithHdrStop;630}631632bool Preprocessor::usingPCHWithPragmaHdrStop() {633return TUKind != TU_Prefix && PPOpts->PCHWithHdrStop;634}635636/// Skip tokens until after the #include of the through header or637/// until after a #pragma hdrstop is seen. Tokens in the predefines file638/// and the main file may be skipped. If the end of the predefines file639/// is reached, skipping continues into the main file. If the end of the640/// main file is reached, it's a fatal error.641void Preprocessor::SkipTokensWhileUsingPCH() {642bool ReachedMainFileEOF = false;643bool UsingPCHThroughHeader = SkippingUntilPCHThroughHeader;644bool UsingPragmaHdrStop = SkippingUntilPragmaHdrStop;645Token Tok;646while (true) {647bool InPredefines =648(CurLexer && CurLexer->getFileID() == getPredefinesFileID());649CurLexerCallback(*this, Tok);650if (Tok.is(tok::eof) && !InPredefines) {651ReachedMainFileEOF = true;652break;653}654if (UsingPCHThroughHeader && !SkippingUntilPCHThroughHeader)655break;656if (UsingPragmaHdrStop && !SkippingUntilPragmaHdrStop)657break;658}659if (ReachedMainFileEOF) {660if (UsingPCHThroughHeader)661Diag(SourceLocation(), diag::err_pp_through_header_not_seen)662<< PPOpts->PCHThroughHeader << 1;663else if (!PPOpts->PCHWithHdrStopCreate)664Diag(SourceLocation(), diag::err_pp_pragma_hdrstop_not_seen);665}666}667668void Preprocessor::replayPreambleConditionalStack() {669// Restore the conditional stack from the preamble, if there is one.670if (PreambleConditionalStack.isReplaying()) {671assert(CurPPLexer &&672"CurPPLexer is null when calling replayPreambleConditionalStack.");673CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack());674PreambleConditionalStack.doneReplaying();675if (PreambleConditionalStack.reachedEOFWhileSkipping())676SkipExcludedConditionalBlock(677PreambleConditionalStack.SkipInfo->HashTokenLoc,678PreambleConditionalStack.SkipInfo->IfTokenLoc,679PreambleConditionalStack.SkipInfo->FoundNonSkipPortion,680PreambleConditionalStack.SkipInfo->FoundElse,681PreambleConditionalStack.SkipInfo->ElseLoc);682}683}684685void Preprocessor::EndSourceFile() {686// Notify the client that we reached the end of the source file.687if (Callbacks)688Callbacks->EndOfMainFile();689}690691//===----------------------------------------------------------------------===//692// Lexer Event Handling.693//===----------------------------------------------------------------------===//694695/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the696/// identifier information for the token and install it into the token,697/// updating the token kind accordingly.698IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {699assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");700701// Look up this token, see if it is a macro, or if it is a language keyword.702IdentifierInfo *II;703if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {704// No cleaning needed, just use the characters from the lexed buffer.705II = getIdentifierInfo(Identifier.getRawIdentifier());706} else {707// Cleaning needed, alloca a buffer, clean into it, then use the buffer.708SmallString<64> IdentifierBuffer;709StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);710711if (Identifier.hasUCN()) {712SmallString<64> UCNIdentifierBuffer;713expandUCNs(UCNIdentifierBuffer, CleanedStr);714II = getIdentifierInfo(UCNIdentifierBuffer);715} else {716II = getIdentifierInfo(CleanedStr);717}718}719720// Update the token info (identifier info and appropriate token kind).721// FIXME: the raw_identifier may contain leading whitespace which is removed722// from the cleaned identifier token. The SourceLocation should be updated to723// refer to the non-whitespace character. For instance, the text "\\\nB" (a724// line continuation before 'B') is parsed as a single tok::raw_identifier and725// is cleaned to tok::identifier "B". After cleaning the token's length is726// still 3 and the SourceLocation refers to the location of the backslash.727Identifier.setIdentifierInfo(II);728Identifier.setKind(II->getTokenID());729730return II;731}732733void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {734PoisonReasons[II] = DiagID;735}736737void Preprocessor::PoisonSEHIdentifiers(bool Poison) {738assert(Ident__exception_code && Ident__exception_info);739assert(Ident___exception_code && Ident___exception_info);740Ident__exception_code->setIsPoisoned(Poison);741Ident___exception_code->setIsPoisoned(Poison);742Ident_GetExceptionCode->setIsPoisoned(Poison);743Ident__exception_info->setIsPoisoned(Poison);744Ident___exception_info->setIsPoisoned(Poison);745Ident_GetExceptionInfo->setIsPoisoned(Poison);746Ident__abnormal_termination->setIsPoisoned(Poison);747Ident___abnormal_termination->setIsPoisoned(Poison);748Ident_AbnormalTermination->setIsPoisoned(Poison);749}750751void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {752assert(Identifier.getIdentifierInfo() &&753"Can't handle identifiers without identifier info!");754llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =755PoisonReasons.find(Identifier.getIdentifierInfo());756if(it == PoisonReasons.end())757Diag(Identifier, diag::err_pp_used_poisoned_id);758else759Diag(Identifier,it->second) << Identifier.getIdentifierInfo();760}761762void Preprocessor::updateOutOfDateIdentifier(const IdentifierInfo &II) const {763assert(II.isOutOfDate() && "not out of date");764getExternalSource()->updateOutOfDateIdentifier(II);765}766767/// HandleIdentifier - This callback is invoked when the lexer reads an768/// identifier. This callback looks up the identifier in the map and/or769/// potentially macro expands it or turns it into a named token (like 'for').770///771/// Note that callers of this method are guarded by checking the772/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the773/// IdentifierInfo methods that compute these properties will need to change to774/// match.775bool Preprocessor::HandleIdentifier(Token &Identifier) {776assert(Identifier.getIdentifierInfo() &&777"Can't handle identifiers without identifier info!");778779IdentifierInfo &II = *Identifier.getIdentifierInfo();780781// If the information about this identifier is out of date, update it from782// the external source.783// We have to treat __VA_ARGS__ in a special way, since it gets784// serialized with isPoisoned = true, but our preprocessor may have785// unpoisoned it if we're defining a C99 macro.786if (II.isOutOfDate()) {787bool CurrentIsPoisoned = false;788const bool IsSpecialVariadicMacro =789&II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__;790if (IsSpecialVariadicMacro)791CurrentIsPoisoned = II.isPoisoned();792793updateOutOfDateIdentifier(II);794Identifier.setKind(II.getTokenID());795796if (IsSpecialVariadicMacro)797II.setIsPoisoned(CurrentIsPoisoned);798}799800// If this identifier was poisoned, and if it was not produced from a macro801// expansion, emit an error.802if (II.isPoisoned() && CurPPLexer) {803HandlePoisonedIdentifier(Identifier);804}805806// If this is a macro to be expanded, do it.807if (const MacroDefinition MD = getMacroDefinition(&II)) {808const auto *MI = MD.getMacroInfo();809assert(MI && "macro definition with no macro info?");810if (!DisableMacroExpansion) {811if (!Identifier.isExpandDisabled() && MI->isEnabled()) {812// C99 6.10.3p10: If the preprocessing token immediately after the813// macro name isn't a '(', this macro should not be expanded.814if (!MI->isFunctionLike() || isNextPPTokenLParen())815return HandleMacroExpandedIdentifier(Identifier, MD);816} else {817// C99 6.10.3.4p2 says that a disabled macro may never again be818// expanded, even if it's in a context where it could be expanded in the819// future.820Identifier.setFlag(Token::DisableExpand);821if (MI->isObjectLike() || isNextPPTokenLParen())822Diag(Identifier, diag::pp_disabled_macro_expansion);823}824}825}826827// If this identifier is a keyword in a newer Standard or proposed Standard,828// produce a warning. Don't warn if we're not considering macro expansion,829// since this identifier might be the name of a macro.830// FIXME: This warning is disabled in cases where it shouldn't be, like831// "#define constexpr constexpr", "int constexpr;"832if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {833Diag(Identifier, getIdentifierTable().getFutureCompatDiagKind(II, getLangOpts()))834<< II.getName();835// Don't diagnose this keyword again in this translation unit.836II.setIsFutureCompatKeyword(false);837}838839// If this is an extension token, diagnose its use.840// We avoid diagnosing tokens that originate from macro definitions.841// FIXME: This warning is disabled in cases where it shouldn't be,842// like "#define TY typeof", "TY(1) x".843if (II.isExtensionToken() && !DisableMacroExpansion)844Diag(Identifier, diag::ext_token_used);845846// If this is the 'import' contextual keyword following an '@', note847// that the next token indicates a module name.848//849// Note that we do not treat 'import' as a contextual850// keyword when we're in a caching lexer, because caching lexers only get851// used in contexts where import declarations are disallowed.852//853// Likewise if this is the standard C++ import keyword.854if (((LastTokenWasAt && II.isModulesImport()) ||855Identifier.is(tok::kw_import)) &&856!InMacroArgs && !DisableMacroExpansion &&857(getLangOpts().Modules || getLangOpts().DebuggerSupport) &&858CurLexerCallback != CLK_CachingLexer) {859ModuleImportLoc = Identifier.getLocation();860NamedModuleImportPath.clear();861IsAtImport = true;862ModuleImportExpectsIdentifier = true;863CurLexerCallback = CLK_LexAfterModuleImport;864}865return true;866}867868void Preprocessor::Lex(Token &Result) {869++LexLevel;870871// We loop here until a lex function returns a token; this avoids recursion.872while (!CurLexerCallback(*this, Result))873;874875if (Result.is(tok::unknown) && TheModuleLoader.HadFatalFailure)876return;877878if (Result.is(tok::code_completion) && Result.getIdentifierInfo()) {879// Remember the identifier before code completion token.880setCodeCompletionIdentifierInfo(Result.getIdentifierInfo());881setCodeCompletionTokenRange(Result.getLocation(), Result.getEndLoc());882// Set IdenfitierInfo to null to avoid confusing code that handles both883// identifiers and completion tokens.884Result.setIdentifierInfo(nullptr);885}886887// Update StdCXXImportSeqState to track our position within a C++20 import-seq888// if this token is being produced as a result of phase 4 of translation.889// Update TrackGMFState to decide if we are currently in a Global Module890// Fragment. GMF state updates should precede StdCXXImportSeq ones, since GMF state891// depends on the prevailing StdCXXImportSeq state in two cases.892if (getLangOpts().CPlusPlusModules && LexLevel == 1 &&893!Result.getFlag(Token::IsReinjected)) {894switch (Result.getKind()) {895case tok::l_paren: case tok::l_square: case tok::l_brace:896StdCXXImportSeqState.handleOpenBracket();897break;898case tok::r_paren: case tok::r_square:899StdCXXImportSeqState.handleCloseBracket();900break;901case tok::r_brace:902StdCXXImportSeqState.handleCloseBrace();903break;904// This token is injected to represent the translation of '#include "a.h"'905// into "import a.h;". Mimic the notional ';'.906case tok::annot_module_include:907case tok::semi:908TrackGMFState.handleSemi();909StdCXXImportSeqState.handleSemi();910ModuleDeclState.handleSemi();911break;912case tok::header_name:913case tok::annot_header_unit:914StdCXXImportSeqState.handleHeaderName();915break;916case tok::kw_export:917TrackGMFState.handleExport();918StdCXXImportSeqState.handleExport();919ModuleDeclState.handleExport();920break;921case tok::colon:922ModuleDeclState.handleColon();923break;924case tok::period:925ModuleDeclState.handlePeriod();926break;927case tok::identifier:928// Check "import" and "module" when there is no open bracket. The two929// identifiers are not meaningful with open brackets.930if (StdCXXImportSeqState.atTopLevel()) {931if (Result.getIdentifierInfo()->isModulesImport()) {932TrackGMFState.handleImport(StdCXXImportSeqState.afterTopLevelSeq());933StdCXXImportSeqState.handleImport();934if (StdCXXImportSeqState.afterImportSeq()) {935ModuleImportLoc = Result.getLocation();936NamedModuleImportPath.clear();937IsAtImport = false;938ModuleImportExpectsIdentifier = true;939CurLexerCallback = CLK_LexAfterModuleImport;940}941break;942} else if (Result.getIdentifierInfo() == getIdentifierInfo("module")) {943TrackGMFState.handleModule(StdCXXImportSeqState.afterTopLevelSeq());944ModuleDeclState.handleModule();945break;946}947}948ModuleDeclState.handleIdentifier(Result.getIdentifierInfo());949if (ModuleDeclState.isModuleCandidate())950break;951[[fallthrough]];952default:953TrackGMFState.handleMisc();954StdCXXImportSeqState.handleMisc();955ModuleDeclState.handleMisc();956break;957}958}959960if (CurLexer && ++CheckPointCounter == CheckPointStepSize) {961CheckPoints[CurLexer->getFileID()].push_back(CurLexer->BufferPtr);962CheckPointCounter = 0;963}964965LastTokenWasAt = Result.is(tok::at);966--LexLevel;967968if ((LexLevel == 0 || PreprocessToken) &&969!Result.getFlag(Token::IsReinjected)) {970if (LexLevel == 0)971++TokenCount;972if (OnToken)973OnToken(Result);974}975}976977void Preprocessor::LexTokensUntilEOF(std::vector<Token> *Tokens) {978while (1) {979Token Tok;980Lex(Tok);981if (Tok.isOneOf(tok::unknown, tok::eof, tok::eod,982tok::annot_repl_input_end))983break;984if (Tokens != nullptr)985Tokens->push_back(Tok);986}987}988989/// Lex a header-name token (including one formed from header-name-tokens if990/// \p AllowMacroExpansion is \c true).991///992/// \param FilenameTok Filled in with the next token. On success, this will993/// be either a header_name token. On failure, it will be whatever other994/// token was found instead.995/// \param AllowMacroExpansion If \c true, allow the header name to be formed996/// by macro expansion (concatenating tokens as necessary if the first997/// token is a '<').998/// \return \c true if we reached EOD or EOF while looking for a > token in999/// a concatenated header name and diagnosed it. \c false otherwise.1000bool Preprocessor::LexHeaderName(Token &FilenameTok, bool AllowMacroExpansion) {1001// Lex using header-name tokenization rules if tokens are being lexed from1002// a file. Just grab a token normally if we're in a macro expansion.1003if (CurPPLexer)1004CurPPLexer->LexIncludeFilename(FilenameTok);1005else1006Lex(FilenameTok);10071008// This could be a <foo/bar.h> file coming from a macro expansion. In this1009// case, glue the tokens together into an angle_string_literal token.1010SmallString<128> FilenameBuffer;1011if (FilenameTok.is(tok::less) && AllowMacroExpansion) {1012bool StartOfLine = FilenameTok.isAtStartOfLine();1013bool LeadingSpace = FilenameTok.hasLeadingSpace();1014bool LeadingEmptyMacro = FilenameTok.hasLeadingEmptyMacro();10151016SourceLocation Start = FilenameTok.getLocation();1017SourceLocation End;1018FilenameBuffer.push_back('<');10191020// Consume tokens until we find a '>'.1021// FIXME: A header-name could be formed starting or ending with an1022// alternative token. It's not clear whether that's ill-formed in all1023// cases.1024while (FilenameTok.isNot(tok::greater)) {1025Lex(FilenameTok);1026if (FilenameTok.isOneOf(tok::eod, tok::eof)) {1027Diag(FilenameTok.getLocation(), diag::err_expected) << tok::greater;1028Diag(Start, diag::note_matching) << tok::less;1029return true;1030}10311032End = FilenameTok.getLocation();10331034// FIXME: Provide code completion for #includes.1035if (FilenameTok.is(tok::code_completion)) {1036setCodeCompletionReached();1037Lex(FilenameTok);1038continue;1039}10401041// Append the spelling of this token to the buffer. If there was a space1042// before it, add it now.1043if (FilenameTok.hasLeadingSpace())1044FilenameBuffer.push_back(' ');10451046// Get the spelling of the token, directly into FilenameBuffer if1047// possible.1048size_t PreAppendSize = FilenameBuffer.size();1049FilenameBuffer.resize(PreAppendSize + FilenameTok.getLength());10501051const char *BufPtr = &FilenameBuffer[PreAppendSize];1052unsigned ActualLen = getSpelling(FilenameTok, BufPtr);10531054// If the token was spelled somewhere else, copy it into FilenameBuffer.1055if (BufPtr != &FilenameBuffer[PreAppendSize])1056memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);10571058// Resize FilenameBuffer to the correct size.1059if (FilenameTok.getLength() != ActualLen)1060FilenameBuffer.resize(PreAppendSize + ActualLen);1061}10621063FilenameTok.startToken();1064FilenameTok.setKind(tok::header_name);1065FilenameTok.setFlagValue(Token::StartOfLine, StartOfLine);1066FilenameTok.setFlagValue(Token::LeadingSpace, LeadingSpace);1067FilenameTok.setFlagValue(Token::LeadingEmptyMacro, LeadingEmptyMacro);1068CreateString(FilenameBuffer, FilenameTok, Start, End);1069} else if (FilenameTok.is(tok::string_literal) && AllowMacroExpansion) {1070// Convert a string-literal token of the form " h-char-sequence "1071// (produced by macro expansion) into a header-name token.1072//1073// The rules for header-names don't quite match the rules for1074// string-literals, but all the places where they differ result in1075// undefined behavior, so we can and do treat them the same.1076//1077// A string-literal with a prefix or suffix is not translated into a1078// header-name. This could theoretically be observable via the C++201079// context-sensitive header-name formation rules.1080StringRef Str = getSpelling(FilenameTok, FilenameBuffer);1081if (Str.size() >= 2 && Str.front() == '"' && Str.back() == '"')1082FilenameTok.setKind(tok::header_name);1083}10841085return false;1086}10871088/// Collect the tokens of a C++20 pp-import-suffix.1089void Preprocessor::CollectPpImportSuffix(SmallVectorImpl<Token> &Toks) {1090// FIXME: For error recovery, consider recognizing attribute syntax here1091// and terminating / diagnosing a missing semicolon if we find anything1092// else? (Can we leave that to the parser?)1093unsigned BracketDepth = 0;1094while (true) {1095Toks.emplace_back();1096Lex(Toks.back());10971098switch (Toks.back().getKind()) {1099case tok::l_paren: case tok::l_square: case tok::l_brace:1100++BracketDepth;1101break;11021103case tok::r_paren: case tok::r_square: case tok::r_brace:1104if (BracketDepth == 0)1105return;1106--BracketDepth;1107break;11081109case tok::semi:1110if (BracketDepth == 0)1111return;1112break;11131114case tok::eof:1115return;11161117default:1118break;1119}1120}1121}112211231124/// Lex a token following the 'import' contextual keyword.1125///1126/// pp-import: [C++20]1127/// import header-name pp-import-suffix[opt] ;1128/// import header-name-tokens pp-import-suffix[opt] ;1129/// [ObjC] @ import module-name ;1130/// [Clang] import module-name ;1131///1132/// header-name-tokens:1133/// string-literal1134/// < [any sequence of preprocessing-tokens other than >] >1135///1136/// module-name:1137/// module-name-qualifier[opt] identifier1138///1139/// module-name-qualifier1140/// module-name-qualifier[opt] identifier .1141///1142/// We respond to a pp-import by importing macros from the named module.1143bool Preprocessor::LexAfterModuleImport(Token &Result) {1144// Figure out what kind of lexer we actually have.1145recomputeCurLexerKind();11461147// Lex the next token. The header-name lexing rules are used at the start of1148// a pp-import.1149//1150// For now, we only support header-name imports in C++20 mode.1151// FIXME: Should we allow this in all language modes that support an import1152// declaration as an extension?1153if (NamedModuleImportPath.empty() && getLangOpts().CPlusPlusModules) {1154if (LexHeaderName(Result))1155return true;11561157if (Result.is(tok::colon) && ModuleDeclState.isNamedModule()) {1158std::string Name = ModuleDeclState.getPrimaryName().str();1159Name += ":";1160NamedModuleImportPath.push_back(1161{getIdentifierInfo(Name), Result.getLocation()});1162CurLexerCallback = CLK_LexAfterModuleImport;1163return true;1164}1165} else {1166Lex(Result);1167}11681169// Allocate a holding buffer for a sequence of tokens and introduce it into1170// the token stream.1171auto EnterTokens = [this](ArrayRef<Token> Toks) {1172auto ToksCopy = std::make_unique<Token[]>(Toks.size());1173std::copy(Toks.begin(), Toks.end(), ToksCopy.get());1174EnterTokenStream(std::move(ToksCopy), Toks.size(),1175/*DisableMacroExpansion*/ true, /*IsReinject*/ false);1176};11771178bool ImportingHeader = Result.is(tok::header_name);1179// Check for a header-name.1180SmallVector<Token, 32> Suffix;1181if (ImportingHeader) {1182// Enter the header-name token into the token stream; a Lex action cannot1183// both return a token and cache tokens (doing so would corrupt the token1184// cache if the call to Lex comes from CachingLex / PeekAhead).1185Suffix.push_back(Result);11861187// Consume the pp-import-suffix and expand any macros in it now. We'll add1188// it back into the token stream later.1189CollectPpImportSuffix(Suffix);1190if (Suffix.back().isNot(tok::semi)) {1191// This is not a pp-import after all.1192EnterTokens(Suffix);1193return false;1194}11951196// C++2a [cpp.module]p1:1197// The ';' preprocessing-token terminating a pp-import shall not have1198// been produced by macro replacement.1199SourceLocation SemiLoc = Suffix.back().getLocation();1200if (SemiLoc.isMacroID())1201Diag(SemiLoc, diag::err_header_import_semi_in_macro);12021203// Reconstitute the import token.1204Token ImportTok;1205ImportTok.startToken();1206ImportTok.setKind(tok::kw_import);1207ImportTok.setLocation(ModuleImportLoc);1208ImportTok.setIdentifierInfo(getIdentifierInfo("import"));1209ImportTok.setLength(6);12101211auto Action = HandleHeaderIncludeOrImport(1212/*HashLoc*/ SourceLocation(), ImportTok, Suffix.front(), SemiLoc);1213switch (Action.Kind) {1214case ImportAction::None:1215break;12161217case ImportAction::ModuleBegin:1218// Let the parser know we're textually entering the module.1219Suffix.emplace_back();1220Suffix.back().startToken();1221Suffix.back().setKind(tok::annot_module_begin);1222Suffix.back().setLocation(SemiLoc);1223Suffix.back().setAnnotationEndLoc(SemiLoc);1224Suffix.back().setAnnotationValue(Action.ModuleForHeader);1225[[fallthrough]];12261227case ImportAction::ModuleImport:1228case ImportAction::HeaderUnitImport:1229case ImportAction::SkippedModuleImport:1230// We chose to import (or textually enter) the file. Convert the1231// header-name token into a header unit annotation token.1232Suffix[0].setKind(tok::annot_header_unit);1233Suffix[0].setAnnotationEndLoc(Suffix[0].getLocation());1234Suffix[0].setAnnotationValue(Action.ModuleForHeader);1235// FIXME: Call the moduleImport callback?1236break;1237case ImportAction::Failure:1238assert(TheModuleLoader.HadFatalFailure &&1239"This should be an early exit only to a fatal error");1240Result.setKind(tok::eof);1241CurLexer->cutOffLexing();1242EnterTokens(Suffix);1243return true;1244}12451246EnterTokens(Suffix);1247return false;1248}12491250// The token sequence1251//1252// import identifier (. identifier)*1253//1254// indicates a module import directive. We already saw the 'import'1255// contextual keyword, so now we're looking for the identifiers.1256if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {1257// We expected to see an identifier here, and we did; continue handling1258// identifiers.1259NamedModuleImportPath.push_back(1260std::make_pair(Result.getIdentifierInfo(), Result.getLocation()));1261ModuleImportExpectsIdentifier = false;1262CurLexerCallback = CLK_LexAfterModuleImport;1263return true;1264}12651266// If we're expecting a '.' or a ';', and we got a '.', then wait until we1267// see the next identifier. (We can also see a '[[' that begins an1268// attribute-specifier-seq here under the Standard C++ Modules.)1269if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {1270ModuleImportExpectsIdentifier = true;1271CurLexerCallback = CLK_LexAfterModuleImport;1272return true;1273}12741275// If we didn't recognize a module name at all, this is not a (valid) import.1276if (NamedModuleImportPath.empty() || Result.is(tok::eof))1277return true;12781279// Consume the pp-import-suffix and expand any macros in it now, if we're not1280// at the semicolon already.1281SourceLocation SemiLoc = Result.getLocation();1282if (Result.isNot(tok::semi)) {1283Suffix.push_back(Result);1284CollectPpImportSuffix(Suffix);1285if (Suffix.back().isNot(tok::semi)) {1286// This is not an import after all.1287EnterTokens(Suffix);1288return false;1289}1290SemiLoc = Suffix.back().getLocation();1291}12921293// Under the standard C++ Modules, the dot is just part of the module name,1294// and not a real hierarchy separator. Flatten such module names now.1295//1296// FIXME: Is this the right level to be performing this transformation?1297std::string FlatModuleName;1298if (getLangOpts().CPlusPlusModules) {1299for (auto &Piece : NamedModuleImportPath) {1300// If the FlatModuleName ends with colon, it implies it is a partition.1301if (!FlatModuleName.empty() && FlatModuleName.back() != ':')1302FlatModuleName += ".";1303FlatModuleName += Piece.first->getName();1304}1305SourceLocation FirstPathLoc = NamedModuleImportPath[0].second;1306NamedModuleImportPath.clear();1307NamedModuleImportPath.push_back(1308std::make_pair(getIdentifierInfo(FlatModuleName), FirstPathLoc));1309}13101311Module *Imported = nullptr;1312// We don't/shouldn't load the standard c++20 modules when preprocessing.1313if (getLangOpts().Modules && !isInImportingCXXNamedModules()) {1314Imported = TheModuleLoader.loadModule(ModuleImportLoc,1315NamedModuleImportPath,1316Module::Hidden,1317/*IsInclusionDirective=*/false);1318if (Imported)1319makeModuleVisible(Imported, SemiLoc);1320}13211322if (Callbacks)1323Callbacks->moduleImport(ModuleImportLoc, NamedModuleImportPath, Imported);13241325if (!Suffix.empty()) {1326EnterTokens(Suffix);1327return false;1328}1329return true;1330}13311332void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {1333CurSubmoduleState->VisibleModules.setVisible(1334M, Loc, [](Module *) {},1335[&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {1336// FIXME: Include the path in the diagnostic.1337// FIXME: Include the import location for the conflicting module.1338Diag(ModuleImportLoc, diag::warn_module_conflict)1339<< Path[0]->getFullModuleName()1340<< Conflict->getFullModuleName()1341<< Message;1342});13431344// Add this module to the imports list of the currently-built submodule.1345if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)1346BuildingSubmoduleStack.back().M->Imports.insert(M);1347}13481349bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,1350const char *DiagnosticTag,1351bool AllowMacroExpansion) {1352// We need at least one string literal.1353if (Result.isNot(tok::string_literal)) {1354Diag(Result, diag::err_expected_string_literal)1355<< /*Source='in...'*/0 << DiagnosticTag;1356return false;1357}13581359// Lex string literal tokens, optionally with macro expansion.1360SmallVector<Token, 4> StrToks;1361do {1362StrToks.push_back(Result);13631364if (Result.hasUDSuffix())1365Diag(Result, diag::err_invalid_string_udl);13661367if (AllowMacroExpansion)1368Lex(Result);1369else1370LexUnexpandedToken(Result);1371} while (Result.is(tok::string_literal));13721373// Concatenate and parse the strings.1374StringLiteralParser Literal(StrToks, *this);1375assert(Literal.isOrdinary() && "Didn't allow wide strings in");13761377if (Literal.hadError)1378return false;13791380if (Literal.Pascal) {1381Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)1382<< /*Source='in...'*/0 << DiagnosticTag;1383return false;1384}13851386String = std::string(Literal.GetString());1387return true;1388}13891390bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {1391assert(Tok.is(tok::numeric_constant));1392SmallString<8> IntegerBuffer;1393bool NumberInvalid = false;1394StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);1395if (NumberInvalid)1396return false;1397NumericLiteralParser Literal(Spelling, Tok.getLocation(), getSourceManager(),1398getLangOpts(), getTargetInfo(),1399getDiagnostics());1400if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())1401return false;1402llvm::APInt APVal(64, 0);1403if (Literal.GetIntegerValue(APVal))1404return false;1405Lex(Tok);1406Value = APVal.getLimitedValue();1407return true;1408}14091410void Preprocessor::addCommentHandler(CommentHandler *Handler) {1411assert(Handler && "NULL comment handler");1412assert(!llvm::is_contained(CommentHandlers, Handler) &&1413"Comment handler already registered");1414CommentHandlers.push_back(Handler);1415}14161417void Preprocessor::removeCommentHandler(CommentHandler *Handler) {1418std::vector<CommentHandler *>::iterator Pos =1419llvm::find(CommentHandlers, Handler);1420assert(Pos != CommentHandlers.end() && "Comment handler not registered");1421CommentHandlers.erase(Pos);1422}14231424bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {1425bool AnyPendingTokens = false;1426for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),1427HEnd = CommentHandlers.end();1428H != HEnd; ++H) {1429if ((*H)->HandleComment(*this, Comment))1430AnyPendingTokens = true;1431}1432if (!AnyPendingTokens || getCommentRetentionState())1433return false;1434Lex(result);1435return true;1436}14371438void Preprocessor::emitMacroDeprecationWarning(const Token &Identifier) const {1439const MacroAnnotations &A =1440getMacroAnnotations(Identifier.getIdentifierInfo());1441assert(A.DeprecationInfo &&1442"Macro deprecation warning without recorded annotation!");1443const MacroAnnotationInfo &Info = *A.DeprecationInfo;1444if (Info.Message.empty())1445Diag(Identifier, diag::warn_pragma_deprecated_macro_use)1446<< Identifier.getIdentifierInfo() << 0;1447else1448Diag(Identifier, diag::warn_pragma_deprecated_macro_use)1449<< Identifier.getIdentifierInfo() << 1 << Info.Message;1450Diag(Info.Location, diag::note_pp_macro_annotation) << 0;1451}14521453void Preprocessor::emitRestrictExpansionWarning(const Token &Identifier) const {1454const MacroAnnotations &A =1455getMacroAnnotations(Identifier.getIdentifierInfo());1456assert(A.RestrictExpansionInfo &&1457"Macro restricted expansion warning without recorded annotation!");1458const MacroAnnotationInfo &Info = *A.RestrictExpansionInfo;1459if (Info.Message.empty())1460Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)1461<< Identifier.getIdentifierInfo() << 0;1462else1463Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)1464<< Identifier.getIdentifierInfo() << 1 << Info.Message;1465Diag(Info.Location, diag::note_pp_macro_annotation) << 1;1466}14671468void Preprocessor::emitRestrictInfNaNWarning(const Token &Identifier,1469unsigned DiagSelection) const {1470Diag(Identifier, diag::warn_fp_nan_inf_when_disabled) << DiagSelection << 1;1471}14721473void Preprocessor::emitFinalMacroWarning(const Token &Identifier,1474bool IsUndef) const {1475const MacroAnnotations &A =1476getMacroAnnotations(Identifier.getIdentifierInfo());1477assert(A.FinalAnnotationLoc &&1478"Final macro warning without recorded annotation!");14791480Diag(Identifier, diag::warn_pragma_final_macro)1481<< Identifier.getIdentifierInfo() << (IsUndef ? 0 : 1);1482Diag(*A.FinalAnnotationLoc, diag::note_pp_macro_annotation) << 2;1483}14841485bool Preprocessor::isSafeBufferOptOut(const SourceManager &SourceMgr,1486const SourceLocation &Loc) const {1487// The lambda that tests if a `Loc` is in an opt-out region given one opt-out1488// region map:1489auto TestInMap = [&SourceMgr](const SafeBufferOptOutRegionsTy &Map,1490const SourceLocation &Loc) -> bool {1491// Try to find a region in `SafeBufferOptOutMap` where `Loc` is in:1492auto FirstRegionEndingAfterLoc = llvm::partition_point(1493Map, [&SourceMgr,1494&Loc](const std::pair<SourceLocation, SourceLocation> &Region) {1495return SourceMgr.isBeforeInTranslationUnit(Region.second, Loc);1496});14971498if (FirstRegionEndingAfterLoc != Map.end()) {1499// To test if the start location of the found region precedes `Loc`:1500return SourceMgr.isBeforeInTranslationUnit(1501FirstRegionEndingAfterLoc->first, Loc);1502}1503// If we do not find a region whose end location passes `Loc`, we want to1504// check if the current region is still open:1505if (!Map.empty() && Map.back().first == Map.back().second)1506return SourceMgr.isBeforeInTranslationUnit(Map.back().first, Loc);1507return false;1508};15091510// What the following does:1511//1512// If `Loc` belongs to the local TU, we just look up `SafeBufferOptOutMap`.1513// Otherwise, `Loc` is from a loaded AST. We look up the1514// `LoadedSafeBufferOptOutMap` first to get the opt-out region map of the1515// loaded AST where `Loc` is at. Then we find if `Loc` is in an opt-out1516// region w.r.t. the region map. If the region map is absent, it means there1517// is no opt-out pragma in that loaded AST.1518//1519// Opt-out pragmas in the local TU or a loaded AST is not visible to another1520// one of them. That means if you put the pragmas around a `#include1521// "module.h"`, where module.h is a module, it is not actually suppressing1522// warnings in module.h. This is fine because warnings in module.h will be1523// reported when module.h is compiled in isolation and nothing in module.h1524// will be analyzed ever again. So you will not see warnings from the file1525// that imports module.h anyway. And you can't even do the same thing for PCHs1526// because they can only be included from the command line.15271528if (SourceMgr.isLocalSourceLocation(Loc))1529return TestInMap(SafeBufferOptOutMap, Loc);15301531const SafeBufferOptOutRegionsTy *LoadedRegions =1532LoadedSafeBufferOptOutMap.lookupLoadedOptOutMap(Loc, SourceMgr);15331534if (LoadedRegions)1535return TestInMap(*LoadedRegions, Loc);1536return false;1537}15381539bool Preprocessor::enterOrExitSafeBufferOptOutRegion(1540bool isEnter, const SourceLocation &Loc) {1541if (isEnter) {1542if (isPPInSafeBufferOptOutRegion())1543return true; // invalid enter action1544InSafeBufferOptOutRegion = true;1545CurrentSafeBufferOptOutStart = Loc;15461547// To set the start location of a new region:15481549if (!SafeBufferOptOutMap.empty()) {1550[[maybe_unused]] auto *PrevRegion = &SafeBufferOptOutMap.back();1551assert(PrevRegion->first != PrevRegion->second &&1552"Shall not begin a safe buffer opt-out region before closing the "1553"previous one.");1554}1555// If the start location equals to the end location, we call the region a1556// open region or a unclosed region (i.e., end location has not been set1557// yet).1558SafeBufferOptOutMap.emplace_back(Loc, Loc);1559} else {1560if (!isPPInSafeBufferOptOutRegion())1561return true; // invalid enter action1562InSafeBufferOptOutRegion = false;15631564// To set the end location of the current open region:15651566assert(!SafeBufferOptOutMap.empty() &&1567"Misordered safe buffer opt-out regions");1568auto *CurrRegion = &SafeBufferOptOutMap.back();1569assert(CurrRegion->first == CurrRegion->second &&1570"Set end location to a closed safe buffer opt-out region");1571CurrRegion->second = Loc;1572}1573return false;1574}15751576bool Preprocessor::isPPInSafeBufferOptOutRegion() {1577return InSafeBufferOptOutRegion;1578}1579bool Preprocessor::isPPInSafeBufferOptOutRegion(SourceLocation &StartLoc) {1580StartLoc = CurrentSafeBufferOptOutStart;1581return InSafeBufferOptOutRegion;1582}15831584SmallVector<SourceLocation, 64>1585Preprocessor::serializeSafeBufferOptOutMap() const {1586assert(!InSafeBufferOptOutRegion &&1587"Attempt to serialize safe buffer opt-out regions before file being "1588"completely preprocessed");15891590SmallVector<SourceLocation, 64> SrcSeq;15911592for (const auto &[begin, end] : SafeBufferOptOutMap) {1593SrcSeq.push_back(begin);1594SrcSeq.push_back(end);1595}1596// Only `SafeBufferOptOutMap` gets serialized. No need to serialize1597// `LoadedSafeBufferOptOutMap` because if this TU loads a pch/module, every1598// pch/module in the pch-chain/module-DAG will be loaded one by one in order.1599// It means that for each loading pch/module m, it just needs to load m's own1600// `SafeBufferOptOutMap`.1601return SrcSeq;1602}16031604bool Preprocessor::setDeserializedSafeBufferOptOutMap(1605const SmallVectorImpl<SourceLocation> &SourceLocations) {1606if (SourceLocations.size() == 0)1607return false;16081609assert(SourceLocations.size() % 2 == 0 &&1610"ill-formed SourceLocation sequence");16111612auto It = SourceLocations.begin();1613SafeBufferOptOutRegionsTy &Regions =1614LoadedSafeBufferOptOutMap.findAndConsLoadedOptOutMap(*It, SourceMgr);16151616do {1617SourceLocation Begin = *It++;1618SourceLocation End = *It++;16191620Regions.emplace_back(Begin, End);1621} while (It != SourceLocations.end());1622return true;1623}16241625ModuleLoader::~ModuleLoader() = default;16261627CommentHandler::~CommentHandler() = default;16281629EmptylineHandler::~EmptylineHandler() = default;16301631CodeCompletionHandler::~CodeCompletionHandler() = default;16321633void Preprocessor::createPreprocessingRecord() {1634if (Record)1635return;16361637Record = new PreprocessingRecord(getSourceManager());1638addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));1639}16401641const char *Preprocessor::getCheckPoint(FileID FID, const char *Start) const {1642if (auto It = CheckPoints.find(FID); It != CheckPoints.end()) {1643const SmallVector<const char *> &FileCheckPoints = It->second;1644const char *Last = nullptr;1645// FIXME: Do better than a linear search.1646for (const char *P : FileCheckPoints) {1647if (P > Start)1648break;1649Last = P;1650}1651return Last;1652}16531654return nullptr;1655}165616571658