#include "clang/Lex/Preprocessor.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/FileSystemStatCache.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Lex/CodeCompletionHandler.h"
#include "clang/Lex/ExternalPreprocessorSource.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/LexDiagnostic.h"
#include "clang/Lex/Lexer.h"
#include "clang/Lex/LiteralSupport.h"
#include "clang/Lex/MacroArgs.h"
#include "clang/Lex/MacroInfo.h"
#include "clang/Lex/ModuleLoader.h"
#include "clang/Lex/Pragma.h"
#include "clang/Lex/PreprocessingRecord.h"
#include "clang/Lex/PreprocessorLexer.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Lex/ScratchBuffer.h"
#include "clang/Lex/Token.h"
#include "clang/Lex/TokenLexer.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/Capacity.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <memory>
#include <string>
#include <utility>
#include <vector>
using namespace clang;
LLVM_INSTANTIATE_REGISTRY(PragmaHandlerRegistry)
ExternalPreprocessorSource::~ExternalPreprocessorSource() = default;
Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts,
DiagnosticsEngine &diags, LangOptions &opts,
SourceManager &SM, HeaderSearch &Headers,
ModuleLoader &TheModuleLoader,
IdentifierInfoLookup *IILookup, bool OwnsHeaders,
TranslationUnitKind TUKind)
: PPOpts(std::move(PPOpts)), Diags(&diags), LangOpts(opts),
FileMgr(Headers.getFileMgr()), SourceMgr(SM),
ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers),
TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
Identifiers(IILookup), PragmaHandlers(new PragmaNamespace(StringRef())),
TUKind(TUKind), SkipMainFilePreamble(0, true),
CurSubmoduleState(&NullSubmoduleState) {
OwnsHeaderSearch = OwnsHeaders;
KeepComments = false;
KeepMacroComments = false;
SuppressIncludeNotFoundError = false;
DisableMacroExpansion = false;
MacroExpansionInDirectivesOverride = false;
InMacroArgs = false;
ArgMacro = nullptr;
InMacroArgPreExpansion = false;
NumCachedTokenLexers = 0;
PragmasEnabled = true;
ParsingIfOrElifDirective = false;
PreprocessedOutput = false;
ReadMacrosFromExternalSource = false;
BuiltinInfo = std::make_unique<Builtin::Context>();
(Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
(Ident__VA_OPT__ = getIdentifierInfo("__VA_OPT__"))->setIsPoisoned();
SetPoisonReason(Ident__VA_OPT__,diag::ext_pp_bad_vaopt_use);
RegisterBuiltinPragmas();
RegisterBuiltinMacros();
if(LangOpts.Borland) {
Ident__exception_info = getIdentifierInfo("_exception_info");
Ident___exception_info = getIdentifierInfo("__exception_info");
Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
Ident__exception_code = getIdentifierInfo("_exception_code");
Ident___exception_code = getIdentifierInfo("__exception_code");
Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
} else {
Ident__exception_info = Ident__exception_code = nullptr;
Ident__abnormal_termination = Ident___exception_info = nullptr;
Ident___exception_code = Ident___abnormal_termination = nullptr;
Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
Ident_AbnormalTermination = nullptr;
}
if (usingPCHWithPragmaHdrStop())
SkippingUntilPragmaHdrStop = true;
if (!this->PPOpts->PCHThroughHeader.empty() &&
!this->PPOpts->ImplicitPCHInclude.empty())
SkippingUntilPCHThroughHeader = true;
if (this->PPOpts->GeneratePreamble)
PreambleConditionalStack.startRecording();
MaxTokens = LangOpts.MaxTokens;
}
Preprocessor::~Preprocessor() {
assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
IncludeMacroStack.clear();
while (MacroInfoChain *I = MIChainHead) {
MIChainHead = I->Next;
I->~MacroInfoChain();
}
std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
CurTokenLexer.reset();
for (MacroArgs *ArgList = MacroArgCache; ArgList;)
ArgList = ArgList->deallocate();
if (OwnsHeaderSearch)
delete &HeaderInfo;
}
void Preprocessor::Initialize(const TargetInfo &Target,
const TargetInfo *AuxTarget) {
assert((!this->Target || this->Target == &Target) &&
"Invalid override of target information");
this->Target = &Target;
assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
"Invalid override of aux target information.");
this->AuxTarget = AuxTarget;
BuiltinInfo->InitializeTarget(Target, AuxTarget);
HeaderInfo.setTarget(Target);
Identifiers.AddKeywords(LangOpts);
setTUFPEvalMethod(getTargetInfo().getFPEvalMethod());
if (getLangOpts().getFPEvalMethod() == LangOptions::FEM_UnsetOnCommandLine)
setCurrentFPEvalMethod(SourceLocation(), Target.getFPEvalMethod());
else
setCurrentFPEvalMethod(SourceLocation(), getLangOpts().getFPEvalMethod());
if (getLangOpts().AllowFPReassoc || getLangOpts().AllowRecip)
setCurrentFPEvalMethod(SourceLocation(), LangOptions::FEM_Indeterminable);
}
void Preprocessor::InitializeForModelFile() {
NumEnteredSourceFiles = 0;
PragmaHandlersBackup = std::move(PragmaHandlers);
PragmaHandlers = std::make_unique<PragmaNamespace>(StringRef());
RegisterBuiltinPragmas();
PredefinesFileID = FileID();
}
void Preprocessor::FinalizeForModelFile() {
NumEnteredSourceFiles = 1;
PragmaHandlers = std::move(PragmaHandlersBackup);
}
void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
llvm::errs() << tok::getTokenName(Tok.getKind());
if (!Tok.isAnnotation())
llvm::errs() << " '" << getSpelling(Tok) << "'";
if (!DumpFlags) return;
llvm::errs() << "\t";
if (Tok.isAtStartOfLine())
llvm::errs() << " [StartOfLine]";
if (Tok.hasLeadingSpace())
llvm::errs() << " [LeadingSpace]";
if (Tok.isExpandDisabled())
llvm::errs() << " [ExpandDisabled]";
if (Tok.needsCleaning()) {
const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
<< "']";
}
llvm::errs() << "\tLoc=<";
DumpLocation(Tok.getLocation());
llvm::errs() << ">";
}
void Preprocessor::DumpLocation(SourceLocation Loc) const {
Loc.print(llvm::errs(), SourceMgr);
}
void Preprocessor::DumpMacro(const MacroInfo &MI) const {
llvm::errs() << "MACRO: ";
for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
DumpToken(MI.getReplacementToken(i));
llvm::errs() << " ";
}
llvm::errs() << "\n";
}
void Preprocessor::PrintStats() {
llvm::errs() << "\n*** Preprocessor Stats:\n";
llvm::errs() << NumDirectives << " directives found:\n";
llvm::errs() << " " << NumDefined << " #define.\n";
llvm::errs() << " " << NumUndefined << " #undef.\n";
llvm::errs() << " #include/#include_next/#import:\n";
llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
llvm::errs() << " " << NumElse << " #else/#elif/#elifdef/#elifndef.\n";
llvm::errs() << " " << NumEndif << " #endif.\n";
llvm::errs() << " " << NumPragma << " #pragma.\n";
llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
<< NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
<< NumFastMacroExpanded << " on the fast path.\n";
llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
<< " token paste (##) operations performed, "
<< NumFastTokenPaste << " on the fast path.\n";
llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
llvm::errs() << "\n Macro Expanded Tokens: "
<< llvm::capacity_in_bytes(MacroExpandedTokens);
llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
llvm::errs() << "\n Macros: "
<< llvm::capacity_in_bytes(CurSubmoduleState->Macros);
llvm::errs() << "\n #pragma push_macro Info: "
<< llvm::capacity_in_bytes(PragmaPushMacroInfo);
llvm::errs() << "\n Poison Reasons: "
<< llvm::capacity_in_bytes(PoisonReasons);
llvm::errs() << "\n Comment Handlers: "
<< llvm::capacity_in_bytes(CommentHandlers) << "\n";
}
Preprocessor::macro_iterator
Preprocessor::macro_begin(bool IncludeExternalMacros) const {
if (IncludeExternalMacros && ExternalSource &&
!ReadMacrosFromExternalSource) {
ReadMacrosFromExternalSource = true;
ExternalSource->ReadDefinedMacros();
}
for (const ModuleMacro &Macro : ModuleMacros)
CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState()));
return CurSubmoduleState->Macros.begin();
}
size_t Preprocessor::getTotalMemory() const {
return BP.getTotalMemory()
+ llvm::capacity_in_bytes(MacroExpandedTokens)
+ Predefines.capacity()
+ llvm::capacity_in_bytes(CurSubmoduleState->Macros)
+ llvm::capacity_in_bytes(PragmaPushMacroInfo)
+ llvm::capacity_in_bytes(PoisonReasons)
+ llvm::capacity_in_bytes(CommentHandlers);
}
Preprocessor::macro_iterator
Preprocessor::macro_end(bool IncludeExternalMacros) const {
if (IncludeExternalMacros && ExternalSource &&
!ReadMacrosFromExternalSource) {
ReadMacrosFromExternalSource = true;
ExternalSource->ReadDefinedMacros();
}
return CurSubmoduleState->Macros.end();
}
static bool MacroDefinitionEquals(const MacroInfo *MI,
ArrayRef<TokenValue> Tokens) {
return Tokens.size() == MI->getNumTokens() &&
std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
}
StringRef Preprocessor::getLastMacroWithSpelling(
SourceLocation Loc,
ArrayRef<TokenValue> Tokens) const {
SourceLocation BestLocation;
StringRef BestSpelling;
for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
I != E; ++I) {
const MacroDirective::DefInfo
Def = I->second.findDirectiveAtLoc(Loc, SourceMgr);
if (!Def || !Def.getMacroInfo())
continue;
if (!Def.getMacroInfo()->isObjectLike())
continue;
if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
continue;
SourceLocation Location = Def.getLocation();
if (BestLocation.isInvalid() ||
(Location.isValid() &&
SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
BestLocation = Location;
BestSpelling = I->first->getName();
}
}
return BestSpelling;
}
void Preprocessor::recomputeCurLexerKind() {
if (CurLexer)
CurLexerKind = CurLexer->isDependencyDirectivesLexer()
? CLK_DependencyDirectivesLexer
: CLK_Lexer;
else if (CurTokenLexer)
CurLexerKind = CLK_TokenLexer;
else
CurLexerKind = CLK_CachingLexer;
}
bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
unsigned CompleteLine,
unsigned CompleteColumn) {
assert(File);
assert(CompleteLine && CompleteColumn && "Starts from 1:1");
assert(!CodeCompletionFile && "Already set");
Optional<llvm::MemoryBufferRef> Buffer =
SourceMgr.getMemoryBufferForFileOrNone(File);
if (!Buffer)
return true;
const char *Position = Buffer->getBufferStart();
for (unsigned Line = 1; Line < CompleteLine; ++Line) {
for (; *Position; ++Position) {
if (*Position != '\r' && *Position != '\n')
continue;
if ((Position[1] == '\r' || Position[1] == '\n') &&
Position[0] != Position[1])
++Position;
++Position;
break;
}
}
Position += CompleteColumn - 1;
if (SkipMainFilePreamble.first &&
SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
}
if (Position > Buffer->getBufferEnd())
Position = Buffer->getBufferEnd();
CodeCompletionFile = File;
CodeCompletionOffset = Position - Buffer->getBufferStart();
auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier());
char *NewBuf = NewBuffer->getBufferStart();
char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
*NewPos = '\0';
std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
SourceMgr.overrideFileContents(File, std::move(NewBuffer));
return false;
}
void Preprocessor::CodeCompleteIncludedFile(llvm::StringRef Dir,
bool IsAngled) {
setCodeCompletionReached();
if (CodeComplete)
CodeComplete->CodeCompleteIncludedFile(Dir, IsAngled);
}
void Preprocessor::CodeCompleteNaturalLanguage() {
setCodeCompletionReached();
if (CodeComplete)
CodeComplete->CodeCompleteNaturalLanguage();
}
StringRef Preprocessor::getSpelling(const Token &Tok,
SmallVectorImpl<char> &Buffer,
bool *Invalid) const {
if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
if (const IdentifierInfo *II = Tok.getIdentifierInfo())
return II->getName();
}
if (Tok.needsCleaning())
Buffer.resize(Tok.getLength());
const char *Ptr = Buffer.data();
unsigned Len = getSpelling(Tok, Ptr, Invalid);
return StringRef(Ptr, Len);
}
void Preprocessor::CreateString(StringRef Str, Token &Tok,
SourceLocation ExpansionLocStart,
SourceLocation ExpansionLocEnd) {
Tok.setLength(Str.size());
const char *DestPtr;
SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
if (ExpansionLocStart.isValid())
Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
ExpansionLocEnd, Str.size());
Tok.setLocation(Loc);
if (Tok.is(tok::raw_identifier))
Tok.setRawIdentifierData(DestPtr);
else if (Tok.isLiteral())
Tok.setLiteralData(DestPtr);
}
SourceLocation Preprocessor::SplitToken(SourceLocation Loc, unsigned Length) {
auto &SM = getSourceManager();
SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellingLoc);
bool Invalid = false;
StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
if (Invalid)
return SourceLocation();
const char *DestPtr;
SourceLocation Spelling =
ScratchBuf->getToken(Buffer.data() + LocInfo.second, Length, DestPtr);
return SM.createTokenSplitLoc(Spelling, Loc, Loc.getLocWithOffset(Length));
}
Module *Preprocessor::getCurrentModule() {
if (!getLangOpts().isCompilingModule())
return nullptr;
return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
}
void Preprocessor::EnterMainSourceFile() {
assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
FileID MainFileID = SourceMgr.getMainFileID();
if (!SourceMgr.isLoadedFileID(MainFileID)) {
EnterSourceFile(MainFileID, nullptr, SourceLocation());
if (SkipMainFilePreamble.first > 0)
CurLexer->SetByteOffset(SkipMainFilePreamble.first,
SkipMainFilePreamble.second);
if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
markIncluded(FE);
}
std::unique_ptr<llvm::MemoryBuffer> SB =
llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
assert(SB && "Cannot create predefined source buffer");
FileID FID = SourceMgr.createFileID(std::move(SB));
assert(FID.isValid() && "Could not create FileID for predefines?");
setPredefinesFileID(FID);
EnterSourceFile(FID, nullptr, SourceLocation());
if (!PPOpts->PCHThroughHeader.empty()) {
Optional<FileEntryRef> File = LookupFile(
SourceLocation(), PPOpts->PCHThroughHeader,
false, nullptr, nullptr,
nullptr, nullptr, nullptr,
nullptr, nullptr,
nullptr);
if (!File) {
Diag(SourceLocation(), diag::err_pp_through_header_not_found)
<< PPOpts->PCHThroughHeader;
return;
}
setPCHThroughHeaderFileID(
SourceMgr.createFileID(*File, SourceLocation(), SrcMgr::C_User));
}
if ((usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) ||
(usingPCHWithPragmaHdrStop() && SkippingUntilPragmaHdrStop))
SkipTokensWhileUsingPCH();
}
void Preprocessor::setPCHThroughHeaderFileID(FileID FID) {
assert(PCHThroughHeaderFileID.isInvalid() &&
"PCHThroughHeaderFileID already set!");
PCHThroughHeaderFileID = FID;
}
bool Preprocessor::isPCHThroughHeader(const FileEntry *FE) {
assert(PCHThroughHeaderFileID.isValid() &&
"Invalid PCH through header FileID");
return FE == SourceMgr.getFileEntryForID(PCHThroughHeaderFileID);
}
bool Preprocessor::creatingPCHWithThroughHeader() {
return TUKind == TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
PCHThroughHeaderFileID.isValid();
}
bool Preprocessor::usingPCHWithThroughHeader() {
return TUKind != TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
PCHThroughHeaderFileID.isValid();
}
bool Preprocessor::creatingPCHWithPragmaHdrStop() {
return TUKind == TU_Prefix && PPOpts->PCHWithHdrStop;
}
bool Preprocessor::usingPCHWithPragmaHdrStop() {
return TUKind != TU_Prefix && PPOpts->PCHWithHdrStop;
}
void Preprocessor::SkipTokensWhileUsingPCH() {
bool ReachedMainFileEOF = false;
bool UsingPCHThroughHeader = SkippingUntilPCHThroughHeader;
bool UsingPragmaHdrStop = SkippingUntilPragmaHdrStop;
Token Tok;
while (true) {
bool InPredefines =
(CurLexer && CurLexer->getFileID() == getPredefinesFileID());
switch (CurLexerKind) {
case CLK_Lexer:
CurLexer->Lex(Tok);
break;
case CLK_TokenLexer:
CurTokenLexer->Lex(Tok);
break;
case CLK_CachingLexer:
CachingLex(Tok);
break;
case CLK_DependencyDirectivesLexer:
CurLexer->LexDependencyDirectiveToken(Tok);
break;
case CLK_LexAfterModuleImport:
LexAfterModuleImport(Tok);
break;
}
if (Tok.is(tok::eof) && !InPredefines) {
ReachedMainFileEOF = true;
break;
}
if (UsingPCHThroughHeader && !SkippingUntilPCHThroughHeader)
break;
if (UsingPragmaHdrStop && !SkippingUntilPragmaHdrStop)
break;
}
if (ReachedMainFileEOF) {
if (UsingPCHThroughHeader)
Diag(SourceLocation(), diag::err_pp_through_header_not_seen)
<< PPOpts->PCHThroughHeader << 1;
else if (!PPOpts->PCHWithHdrStopCreate)
Diag(SourceLocation(), diag::err_pp_pragma_hdrstop_not_seen);
}
}
void Preprocessor::replayPreambleConditionalStack() {
if (PreambleConditionalStack.isReplaying()) {
assert(CurPPLexer &&
"CurPPLexer is null when calling replayPreambleConditionalStack.");
CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack());
PreambleConditionalStack.doneReplaying();
if (PreambleConditionalStack.reachedEOFWhileSkipping())
SkipExcludedConditionalBlock(
PreambleConditionalStack.SkipInfo->HashTokenLoc,
PreambleConditionalStack.SkipInfo->IfTokenLoc,
PreambleConditionalStack.SkipInfo->FoundNonSkipPortion,
PreambleConditionalStack.SkipInfo->FoundElse,
PreambleConditionalStack.SkipInfo->ElseLoc);
}
}
void Preprocessor::EndSourceFile() {
if (Callbacks)
Callbacks->EndOfMainFile();
}
IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
IdentifierInfo *II;
if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
II = getIdentifierInfo(Identifier.getRawIdentifier());
} else {
SmallString<64> IdentifierBuffer;
StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
if (Identifier.hasUCN()) {
SmallString<64> UCNIdentifierBuffer;
expandUCNs(UCNIdentifierBuffer, CleanedStr);
II = getIdentifierInfo(UCNIdentifierBuffer);
} else {
II = getIdentifierInfo(CleanedStr);
}
}
Identifier.setIdentifierInfo(II);
Identifier.setKind(II->getTokenID());
return II;
}
void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
PoisonReasons[II] = DiagID;
}
void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
assert(Ident__exception_code && Ident__exception_info);
assert(Ident___exception_code && Ident___exception_info);
Ident__exception_code->setIsPoisoned(Poison);
Ident___exception_code->setIsPoisoned(Poison);
Ident_GetExceptionCode->setIsPoisoned(Poison);
Ident__exception_info->setIsPoisoned(Poison);
Ident___exception_info->setIsPoisoned(Poison);
Ident_GetExceptionInfo->setIsPoisoned(Poison);
Ident__abnormal_termination->setIsPoisoned(Poison);
Ident___abnormal_termination->setIsPoisoned(Poison);
Ident_AbnormalTermination->setIsPoisoned(Poison);
}
void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
assert(Identifier.getIdentifierInfo() &&
"Can't handle identifiers without identifier info!");
llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
PoisonReasons.find(Identifier.getIdentifierInfo());
if(it == PoisonReasons.end())
Diag(Identifier, diag::err_pp_used_poisoned_id);
else
Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
}
static diag::kind getFutureCompatDiagKind(const IdentifierInfo &II,
const LangOptions &LangOpts) {
assert(II.isFutureCompatKeyword() && "diagnostic should not be needed");
if (LangOpts.CPlusPlus)
return llvm::StringSwitch<diag::kind>(II.getName())
#define CXX11_KEYWORD(NAME, FLAGS) \
.Case(#NAME, diag::warn_cxx11_keyword)
#define CXX20_KEYWORD(NAME, FLAGS) \
.Case(#NAME, diag::warn_cxx20_keyword)
#include "clang/Basic/TokenKinds.def"
.Case("char8_t", diag::warn_cxx20_keyword)
;
llvm_unreachable(
"Keyword not known to come from a newer Standard or proposed Standard");
}
void Preprocessor::updateOutOfDateIdentifier(IdentifierInfo &II) const {
assert(II.isOutOfDate() && "not out of date");
getExternalSource()->updateOutOfDateIdentifier(II);
}
bool Preprocessor::HandleIdentifier(Token &Identifier) {
assert(Identifier.getIdentifierInfo() &&
"Can't handle identifiers without identifier info!");
IdentifierInfo &II = *Identifier.getIdentifierInfo();
if (II.isOutOfDate()) {
bool CurrentIsPoisoned = false;
const bool IsSpecialVariadicMacro =
&II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__;
if (IsSpecialVariadicMacro)
CurrentIsPoisoned = II.isPoisoned();
updateOutOfDateIdentifier(II);
Identifier.setKind(II.getTokenID());
if (IsSpecialVariadicMacro)
II.setIsPoisoned(CurrentIsPoisoned);
}
if (II.isPoisoned() && CurPPLexer) {
HandlePoisonedIdentifier(Identifier);
}
if (MacroDefinition MD = getMacroDefinition(&II)) {
auto *MI = MD.getMacroInfo();
assert(MI && "macro definition with no macro info?");
if (!DisableMacroExpansion) {
if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
if (!MI->isFunctionLike() || isNextPPTokenLParen())
return HandleMacroExpandedIdentifier(Identifier, MD);
} else {
Identifier.setFlag(Token::DisableExpand);
if (MI->isObjectLike() || isNextPPTokenLParen())
Diag(Identifier, diag::pp_disabled_macro_expansion);
}
}
}
if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
Diag(Identifier, getFutureCompatDiagKind(II, getLangOpts()))
<< II.getName();
II.setIsFutureCompatKeyword(false);
}
if (II.isExtensionToken() && !DisableMacroExpansion)
Diag(Identifier, diag::ext_token_used);
if (((LastTokenWasAt && II.isModulesImport()) ||
Identifier.is(tok::kw_import)) &&
!InMacroArgs && !DisableMacroExpansion &&
(getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
CurLexerKind != CLK_CachingLexer) {
ModuleImportLoc = Identifier.getLocation();
ModuleImportPath.clear();
ModuleImportExpectsIdentifier = true;
CurLexerKind = CLK_LexAfterModuleImport;
}
return true;
}
void Preprocessor::Lex(Token &Result) {
++LexLevel;
bool ReturnedToken;
do {
switch (CurLexerKind) {
case CLK_Lexer:
ReturnedToken = CurLexer->Lex(Result);
break;
case CLK_TokenLexer:
ReturnedToken = CurTokenLexer->Lex(Result);
break;
case CLK_CachingLexer:
CachingLex(Result);
ReturnedToken = true;
break;
case CLK_DependencyDirectivesLexer:
ReturnedToken = CurLexer->LexDependencyDirectiveToken(Result);
break;
case CLK_LexAfterModuleImport:
ReturnedToken = LexAfterModuleImport(Result);
break;
}
} while (!ReturnedToken);
if (Result.is(tok::unknown) && TheModuleLoader.HadFatalFailure)
return;
if (Result.is(tok::code_completion) && Result.getIdentifierInfo()) {
setCodeCompletionIdentifierInfo(Result.getIdentifierInfo());
setCodeCompletionTokenRange(Result.getLocation(), Result.getEndLoc());
Result.setIdentifierInfo(nullptr);
}
if (getLangOpts().CPlusPlusModules && LexLevel == 1 &&
!Result.getFlag(Token::IsReinjected)) {
switch (Result.getKind()) {
case tok::l_paren: case tok::l_square: case tok::l_brace:
ImportSeqState.handleOpenBracket();
break;
case tok::r_paren: case tok::r_square:
ImportSeqState.handleCloseBracket();
break;
case tok::r_brace:
ImportSeqState.handleCloseBrace();
break;
case tok::annot_module_include:
case tok::semi:
TrackGMFState.handleSemi();
ImportSeqState.handleSemi();
break;
case tok::header_name:
case tok::annot_header_unit:
ImportSeqState.handleHeaderName();
break;
case tok::kw_export:
TrackGMFState.handleExport();
ImportSeqState.handleExport();
break;
case tok::identifier:
if (Result.getIdentifierInfo()->isModulesImport()) {
TrackGMFState.handleImport(ImportSeqState.afterTopLevelSeq());
ImportSeqState.handleImport();
if (ImportSeqState.afterImportSeq()) {
ModuleImportLoc = Result.getLocation();
ModuleImportPath.clear();
ModuleImportExpectsIdentifier = true;
CurLexerKind = CLK_LexAfterModuleImport;
}
break;
} else if (Result.getIdentifierInfo() == getIdentifierInfo("module")) {
TrackGMFState.handleModule(ImportSeqState.afterTopLevelSeq());
break;
}
LLVM_FALLTHROUGH;
default:
TrackGMFState.handleMisc();
ImportSeqState.handleMisc();
break;
}
}
LastTokenWasAt = Result.is(tok::at);
--LexLevel;
if ((LexLevel == 0 || PreprocessToken) &&
!Result.getFlag(Token::IsReinjected)) {
if (LexLevel == 0)
++TokenCount;
if (OnToken)
OnToken(Result);
}
}
bool Preprocessor::LexHeaderName(Token &FilenameTok, bool AllowMacroExpansion) {
if (CurPPLexer)
CurPPLexer->LexIncludeFilename(FilenameTok);
else
Lex(FilenameTok);
SmallString<128> FilenameBuffer;
if (FilenameTok.is(tok::less) && AllowMacroExpansion) {
bool StartOfLine = FilenameTok.isAtStartOfLine();
bool LeadingSpace = FilenameTok.hasLeadingSpace();
bool LeadingEmptyMacro = FilenameTok.hasLeadingEmptyMacro();
SourceLocation Start = FilenameTok.getLocation();
SourceLocation End;
FilenameBuffer.push_back('<');
while (FilenameTok.isNot(tok::greater)) {
Lex(FilenameTok);
if (FilenameTok.isOneOf(tok::eod, tok::eof)) {
Diag(FilenameTok.getLocation(), diag::err_expected) << tok::greater;
Diag(Start, diag::note_matching) << tok::less;
return true;
}
End = FilenameTok.getLocation();
if (FilenameTok.is(tok::code_completion)) {
setCodeCompletionReached();
Lex(FilenameTok);
continue;
}
if (FilenameTok.hasLeadingSpace())
FilenameBuffer.push_back(' ');
size_t PreAppendSize = FilenameBuffer.size();
FilenameBuffer.resize(PreAppendSize + FilenameTok.getLength());
const char *BufPtr = &FilenameBuffer[PreAppendSize];
unsigned ActualLen = getSpelling(FilenameTok, BufPtr);
if (BufPtr != &FilenameBuffer[PreAppendSize])
memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
if (FilenameTok.getLength() != ActualLen)
FilenameBuffer.resize(PreAppendSize + ActualLen);
}
FilenameTok.startToken();
FilenameTok.setKind(tok::header_name);
FilenameTok.setFlagValue(Token::StartOfLine, StartOfLine);
FilenameTok.setFlagValue(Token::LeadingSpace, LeadingSpace);
FilenameTok.setFlagValue(Token::LeadingEmptyMacro, LeadingEmptyMacro);
CreateString(FilenameBuffer, FilenameTok, Start, End);
} else if (FilenameTok.is(tok::string_literal) && AllowMacroExpansion) {
StringRef Str = getSpelling(FilenameTok, FilenameBuffer);
if (Str.size() >= 2 && Str.front() == '"' && Str.back() == '"')
FilenameTok.setKind(tok::header_name);
}
return false;
}
void Preprocessor::CollectPpImportSuffix(SmallVectorImpl<Token> &Toks) {
unsigned BracketDepth = 0;
while (true) {
Toks.emplace_back();
Lex(Toks.back());
switch (Toks.back().getKind()) {
case tok::l_paren: case tok::l_square: case tok::l_brace:
++BracketDepth;
break;
case tok::r_paren: case tok::r_square: case tok::r_brace:
if (BracketDepth == 0)
return;
--BracketDepth;
break;
case tok::semi:
if (BracketDepth == 0)
return;
break;
case tok::eof:
return;
default:
break;
}
}
}
bool Preprocessor::LexAfterModuleImport(Token &Result) {
recomputeCurLexerKind();
if (ModuleImportPath.empty() && getLangOpts().CPlusPlusModules) {
if (LexHeaderName(Result))
return true;
} else {
Lex(Result);
}
auto EnterTokens = [this](ArrayRef<Token> Toks) {
auto ToksCopy = std::make_unique<Token[]>(Toks.size());
std::copy(Toks.begin(), Toks.end(), ToksCopy.get());
EnterTokenStream(std::move(ToksCopy), Toks.size(),
true, false);
};
SmallVector<Token, 32> Suffix;
if (Result.is(tok::header_name)) {
Suffix.push_back(Result);
CollectPpImportSuffix(Suffix);
if (Suffix.back().isNot(tok::semi)) {
EnterTokens(Suffix);
return false;
}
SourceLocation SemiLoc = Suffix.back().getLocation();
if (SemiLoc.isMacroID())
Diag(SemiLoc, diag::err_header_import_semi_in_macro);
Token ImportTok;
ImportTok.startToken();
ImportTok.setKind(tok::kw_import);
ImportTok.setLocation(ModuleImportLoc);
ImportTok.setIdentifierInfo(getIdentifierInfo("import"));
ImportTok.setLength(6);
auto Action = HandleHeaderIncludeOrImport(
SourceLocation(), ImportTok, Suffix.front(), SemiLoc);
switch (Action.Kind) {
case ImportAction::None:
break;
case ImportAction::ModuleBegin:
Suffix.emplace_back();
Suffix.back().startToken();
Suffix.back().setKind(tok::annot_module_begin);
Suffix.back().setLocation(SemiLoc);
Suffix.back().setAnnotationEndLoc(SemiLoc);
Suffix.back().setAnnotationValue(Action.ModuleForHeader);
LLVM_FALLTHROUGH;
case ImportAction::ModuleImport:
case ImportAction::HeaderUnitImport:
case ImportAction::SkippedModuleImport:
Suffix[0].setKind(tok::annot_header_unit);
Suffix[0].setAnnotationEndLoc(Suffix[0].getLocation());
Suffix[0].setAnnotationValue(Action.ModuleForHeader);
break;
case ImportAction::Failure:
assert(TheModuleLoader.HadFatalFailure &&
"This should be an early exit only to a fatal error");
Result.setKind(tok::eof);
CurLexer->cutOffLexing();
EnterTokens(Suffix);
return true;
}
EnterTokens(Suffix);
return false;
}
if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
Result.getLocation()));
ModuleImportExpectsIdentifier = false;
CurLexerKind = CLK_LexAfterModuleImport;
return true;
}
if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
ModuleImportExpectsIdentifier = true;
CurLexerKind = CLK_LexAfterModuleImport;
return true;
}
if (ModuleImportPath.empty() || Result.is(tok::eof))
return true;
SourceLocation SemiLoc = Result.getLocation();
if (Result.isNot(tok::semi)) {
Suffix.push_back(Result);
CollectPpImportSuffix(Suffix);
if (Suffix.back().isNot(tok::semi)) {
EnterTokens(Suffix);
return false;
}
SemiLoc = Suffix.back().getLocation();
}
std::string FlatModuleName;
if (getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) {
for (auto &Piece : ModuleImportPath) {
if (!FlatModuleName.empty())
FlatModuleName += ".";
FlatModuleName += Piece.first->getName();
}
SourceLocation FirstPathLoc = ModuleImportPath[0].second;
ModuleImportPath.clear();
ModuleImportPath.push_back(
std::make_pair(getIdentifierInfo(FlatModuleName), FirstPathLoc));
}
Module *Imported = nullptr;
if (getLangOpts().Modules) {
Imported = TheModuleLoader.loadModule(ModuleImportLoc,
ModuleImportPath,
Module::Hidden,
false);
if (Imported)
makeModuleVisible(Imported, SemiLoc);
}
if (Callbacks)
Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
if (!Suffix.empty()) {
EnterTokens(Suffix);
return false;
}
return true;
}
void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {
CurSubmoduleState->VisibleModules.setVisible(
M, Loc, [](Module *) {},
[&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
Diag(ModuleImportLoc, diag::warn_module_conflict)
<< Path[0]->getFullModuleName()
<< Conflict->getFullModuleName()
<< Message;
});
if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
BuildingSubmoduleStack.back().M->Imports.insert(M);
}
bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
const char *DiagnosticTag,
bool AllowMacroExpansion) {
if (Result.isNot(tok::string_literal)) {
Diag(Result, diag::err_expected_string_literal)
<< 0 << DiagnosticTag;
return false;
}
SmallVector<Token, 4> StrToks;
do {
StrToks.push_back(Result);
if (Result.hasUDSuffix())
Diag(Result, diag::err_invalid_string_udl);
if (AllowMacroExpansion)
Lex(Result);
else
LexUnexpandedToken(Result);
} while (Result.is(tok::string_literal));
StringLiteralParser Literal(StrToks, *this);
assert(Literal.isOrdinary() && "Didn't allow wide strings in");
if (Literal.hadError)
return false;
if (Literal.Pascal) {
Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
<< 0 << DiagnosticTag;
return false;
}
String = std::string(Literal.GetString());
return true;
}
bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
assert(Tok.is(tok::numeric_constant));
SmallString<8> IntegerBuffer;
bool NumberInvalid = false;
StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
if (NumberInvalid)
return false;
NumericLiteralParser Literal(Spelling, Tok.getLocation(), getSourceManager(),
getLangOpts(), getTargetInfo(),
getDiagnostics());
if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
return false;
llvm::APInt APVal(64, 0);
if (Literal.GetIntegerValue(APVal))
return false;
Lex(Tok);
Value = APVal.getLimitedValue();
return true;
}
void Preprocessor::addCommentHandler(CommentHandler *Handler) {
assert(Handler && "NULL comment handler");
assert(!llvm::is_contained(CommentHandlers, Handler) &&
"Comment handler already registered");
CommentHandlers.push_back(Handler);
}
void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
std::vector<CommentHandler *>::iterator Pos =
llvm::find(CommentHandlers, Handler);
assert(Pos != CommentHandlers.end() && "Comment handler not registered");
CommentHandlers.erase(Pos);
}
bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
bool AnyPendingTokens = false;
for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
HEnd = CommentHandlers.end();
H != HEnd; ++H) {
if ((*H)->HandleComment(*this, Comment))
AnyPendingTokens = true;
}
if (!AnyPendingTokens || getCommentRetentionState())
return false;
Lex(result);
return true;
}
void Preprocessor::emitMacroDeprecationWarning(const Token &Identifier) const {
const MacroAnnotations &A =
getMacroAnnotations(Identifier.getIdentifierInfo());
assert(A.DeprecationInfo &&
"Macro deprecation warning without recorded annotation!");
const MacroAnnotationInfo &Info = *A.DeprecationInfo;
if (Info.Message.empty())
Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
<< Identifier.getIdentifierInfo() << 0;
else
Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
<< Identifier.getIdentifierInfo() << 1 << Info.Message;
Diag(Info.Location, diag::note_pp_macro_annotation) << 0;
}
void Preprocessor::emitRestrictExpansionWarning(const Token &Identifier) const {
const MacroAnnotations &A =
getMacroAnnotations(Identifier.getIdentifierInfo());
assert(A.RestrictExpansionInfo &&
"Macro restricted expansion warning without recorded annotation!");
const MacroAnnotationInfo &Info = *A.RestrictExpansionInfo;
if (Info.Message.empty())
Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
<< Identifier.getIdentifierInfo() << 0;
else
Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
<< Identifier.getIdentifierInfo() << 1 << Info.Message;
Diag(Info.Location, diag::note_pp_macro_annotation) << 1;
}
void Preprocessor::emitFinalMacroWarning(const Token &Identifier,
bool IsUndef) const {
const MacroAnnotations &A =
getMacroAnnotations(Identifier.getIdentifierInfo());
assert(A.FinalAnnotationLoc &&
"Final macro warning without recorded annotation!");
Diag(Identifier, diag::warn_pragma_final_macro)
<< Identifier.getIdentifierInfo() << (IsUndef ? 0 : 1);
Diag(*A.FinalAnnotationLoc, diag::note_pp_macro_annotation) << 2;
}
ModuleLoader::~ModuleLoader() = default;
CommentHandler::~CommentHandler() = default;
EmptylineHandler::~EmptylineHandler() = default;
CodeCompletionHandler::~CodeCompletionHandler() = default;
void Preprocessor::createPreprocessingRecord() {
if (Record)
return;
Record = new PreprocessingRecord(getSourceManager());
addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
}