#include "clang/Lex/Pragma.h"
#include "clang/Basic/CLWarnings.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.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/TokenKinds.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/LexDiagnostic.h"
#include "clang/Lex/Lexer.h"
#include "clang/Lex/LiteralSupport.h"
#include "clang/Lex/MacroInfo.h"
#include "clang/Lex/ModuleLoader.h"
#include "clang/Lex/PPCallbacks.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/PreprocessorLexer.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Lex/Token.h"
#include "clang/Lex/TokenLexer.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/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Timer.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <string>
#include <utility>
#include <vector>
using namespace clang;
PragmaHandler::~PragmaHandler() = default;
EmptyPragmaHandler::EmptyPragmaHandler(StringRef Name) : PragmaHandler(Name) {}
void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer,
Token &FirstToken) {}
PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
bool IgnoreNull) const {
auto I = Handlers.find(Name);
if (I != Handlers.end())
return I->getValue().get();
if (IgnoreNull)
return nullptr;
I = Handlers.find(StringRef());
if (I != Handlers.end())
return I->getValue().get();
return nullptr;
}
void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
assert(!Handlers.count(Handler->getName()) &&
"A handler with this name is already registered in this namespace");
Handlers[Handler->getName()].reset(Handler);
}
void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
auto I = Handlers.find(Handler->getName());
assert(I != Handlers.end() &&
"Handler not registered in this namespace");
I->getValue().release();
Handlers.erase(I);
}
void PragmaNamespace::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer, Token &Tok) {
PP.LexUnexpandedToken(Tok);
PragmaHandler *Handler
= FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
: StringRef(),
false);
if (!Handler) {
PP.Diag(Tok, diag::warn_pragma_ignored);
return;
}
Handler->HandlePragma(PP, Introducer, Tok);
}
namespace {
struct TokenCollector {
Preprocessor &Self;
bool Collect;
SmallVector<Token, 3> Tokens;
Token &Tok;
void lex() {
if (Collect)
Tokens.push_back(Tok);
Self.Lex(Tok);
}
void revert() {
assert(Collect && "did not collect tokens");
assert(!Tokens.empty() && "collected unexpected number of tokens");
auto Toks = std::make_unique<Token[]>(Tokens.size());
std::copy(Tokens.begin() + 1, Tokens.end(), Toks.get());
Toks[Tokens.size() - 1] = Tok;
Self.EnterTokenStream(std::move(Toks), Tokens.size(),
true,
true);
Tok = *Tokens.begin();
}
};
}
void Preprocessor::HandlePragmaDirective(PragmaIntroducer Introducer) {
if (Callbacks)
Callbacks->PragmaDirective(Introducer.Loc, Introducer.Kind);
if (!PragmasEnabled)
return;
++NumPragma;
Token Tok;
PragmaHandlers->HandlePragma(*this, Introducer, Tok);
if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
|| (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
DiscardUntilEndOfDirective();
}
void Preprocessor::Handle_Pragma(Token &Tok) {
TokenCollector Toks = {*this, InMacroArgPreExpansion, {}, Tok};
SourceLocation PragmaLoc = Tok.getLocation();
Toks.lex();
if (Tok.isNot(tok::l_paren)) {
Diag(PragmaLoc, diag::err__Pragma_malformed);
return;
}
Toks.lex();
if (!tok::isStringLiteral(Tok.getKind())) {
Diag(PragmaLoc, diag::err__Pragma_malformed);
if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
Lex(Tok);
while (Tok.isNot(tok::r_paren) &&
!Tok.isAtStartOfLine() &&
Tok.isNot(tok::eof))
Lex(Tok);
if (Tok.is(tok::r_paren))
Lex(Tok);
return;
}
if (Tok.hasUDSuffix()) {
Diag(Tok, diag::err_invalid_string_udl);
Lex(Tok);
if (Tok.is(tok::r_paren))
Lex(Tok);
return;
}
Token StrTok = Tok;
Toks.lex();
if (Tok.isNot(tok::r_paren)) {
Diag(PragmaLoc, diag::err__Pragma_malformed);
return;
}
if (InMacroArgPreExpansion) {
Toks.revert();
return;
}
SourceLocation RParenLoc = Tok.getLocation();
bool Invalid = false;
std::string StrVal = getSpelling(StrTok, &Invalid);
if (Invalid) {
Diag(PragmaLoc, diag::err__Pragma_malformed);
return;
}
if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
(StrVal[0] == 'u' && StrVal[1] != '8'))
StrVal.erase(StrVal.begin());
else if (StrVal[0] == 'u')
StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
if (StrVal[0] == 'R') {
assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
"Invalid raw string token!");
unsigned NumDChars = 0;
while (StrVal[2 + NumDChars] != '(') {
assert(NumDChars < (StrVal.size() - 5) / 2 &&
"Invalid raw string token!");
++NumDChars;
}
assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
StrVal.erase(0, 2 + NumDChars);
StrVal.erase(StrVal.size() - 1 - NumDChars);
} else {
assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
"Invalid string token!");
unsigned ResultPos = 1;
for (size_t i = 1, e = StrVal.size() - 1; i != e; ++i) {
if (StrVal[i] == '\\' && i + 1 < e &&
(StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
++i;
StrVal[ResultPos++] = StrVal[i];
}
StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
}
StrVal[0] = ' ';
StrVal[StrVal.size()-1] = '\n';
Token TmpTok;
TmpTok.startToken();
CreateString(StrVal, TmpTok);
SourceLocation TokLoc = TmpTok.getLocation();
Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
StrVal.size(), *this);
EnterSourceFileWithLexer(TL, nullptr);
HandlePragmaDirective({PIK__Pragma, PragmaLoc});
return Lex(Tok);
}
void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
TokenCollector Toks = {*this, InMacroArgPreExpansion, {}, Tok};
SourceLocation PragmaLoc = Tok.getLocation();
Toks.lex();
if (Tok.isNot(tok::l_paren)) {
Diag(PragmaLoc, diag::err__Pragma_malformed);
return;
}
SmallVector<Token, 32> PragmaToks;
int NumParens = 0;
Toks.lex();
while (Tok.isNot(tok::eof)) {
PragmaToks.push_back(Tok);
if (Tok.is(tok::l_paren))
NumParens++;
else if (Tok.is(tok::r_paren) && NumParens-- == 0)
break;
Toks.lex();
}
if (Tok.is(tok::eof)) {
Diag(PragmaLoc, diag::err_unterminated___pragma);
return;
}
if (InMacroArgPreExpansion) {
Toks.revert();
return;
}
PragmaToks.front().setFlag(Token::LeadingSpace);
PragmaToks.back().setKind(tok::eod);
Token *TokArray = new Token[PragmaToks.size()];
std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
EnterTokenStream(TokArray, PragmaToks.size(), true, true,
false);
HandlePragmaDirective({PIK___pragma, PragmaLoc});
return Lex(Tok);
}
void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
if (isInPrimaryFile() && TUKind != TU_Prefix && !getLangOpts().IsHeaderFile) {
Diag(OnceTok, diag::pp_pragma_once_in_main_file);
return;
}
HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
}
void Preprocessor::HandlePragmaMark(Token &MarkTok) {
assert(CurPPLexer && "No current lexer?");
SmallString<64> Buffer;
CurLexer->ReadToEndOfLine(&Buffer);
if (Callbacks)
Callbacks->PragmaMark(MarkTok.getLocation(), Buffer);
}
void Preprocessor::HandlePragmaPoison() {
Token Tok;
while (true) {
if (CurPPLexer) CurPPLexer->LexingRawMode = true;
LexUnexpandedToken(Tok);
if (CurPPLexer) CurPPLexer->LexingRawMode = false;
if (Tok.is(tok::eod)) return;
if (Tok.isNot(tok::raw_identifier)) {
Diag(Tok, diag::err_pp_invalid_poison);
return;
}
IdentifierInfo *II = LookUpIdentifierInfo(Tok);
if (II->isPoisoned()) continue;
if (isMacroDefined(II))
Diag(Tok, diag::pp_poisoning_existing_macro);
II->setIsPoisoned();
if (II->isFromAST())
II->setChangedSinceDeserialization();
}
}
void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
if (isInPrimaryFile()) {
Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
return;
}
PreprocessorLexer *TheLexer = getCurrentFileLexer();
HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
if (PLoc.isInvalid())
return;
unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
if (Callbacks)
Callbacks->FileChanged(SysHeaderTok.getLocation(),
PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine() + 1,
FilenameID, false, false,
SrcMgr::C_System);
}
void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
Token FilenameTok;
if (LexHeaderName(FilenameTok, false))
return;
if (FilenameTok.isNot(tok::header_name)) {
Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
return;
}
SmallString<128> FilenameBuffer;
bool Invalid = false;
StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
if (Invalid)
return;
bool isAngled =
GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
if (Filename.empty())
return;
Optional<FileEntryRef> File =
LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
if (!File) {
if (!SuppressIncludeNotFoundError)
Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
return;
}
const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
std::string Message;
Lex(DependencyTok);
while (DependencyTok.isNot(tok::eod)) {
Message += getSpelling(DependencyTok) + " ";
Lex(DependencyTok);
}
if (!Message.empty())
Message.erase(Message.end()-1);
Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
}
}
IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
Token PragmaTok = Tok;
Lex(Tok);
if (Tok.isNot(tok::l_paren)) {
Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
<< getSpelling(PragmaTok);
return nullptr;
}
Lex(Tok);
if (Tok.isNot(tok::string_literal)) {
Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
<< getSpelling(PragmaTok);
return nullptr;
}
if (Tok.hasUDSuffix()) {
Diag(Tok, diag::err_invalid_string_udl);
return nullptr;
}
std::string StrVal = getSpelling(Tok);
Lex(Tok);
if (Tok.isNot(tok::r_paren)) {
Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
<< getSpelling(PragmaTok);
return nullptr;
}
assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
"Invalid string token!");
Token MacroTok;
MacroTok.startToken();
MacroTok.setKind(tok::raw_identifier);
CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
return LookUpIdentifierInfo(MacroTok);
}
void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
if (!IdentInfo) return;
MacroInfo *MI = getMacroInfo(IdentInfo);
if (MI) {
MI->setIsAllowRedefinitionsWithoutWarning(true);
}
PragmaPushMacroInfo[IdentInfo].push_back(MI);
}
void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
SourceLocation MessageLoc = PopMacroTok.getLocation();
IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
if (!IdentInfo) return;
llvm::DenseMap<IdentifierInfo *, std::vector<MacroInfo *>>::iterator iter =
PragmaPushMacroInfo.find(IdentInfo);
if (iter != PragmaPushMacroInfo.end()) {
if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
if (MI->isWarnIfUnused())
WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
}
MacroInfo *MacroToReInstall = iter->second.back();
if (MacroToReInstall)
appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
iter->second.pop_back();
if (iter->second.empty())
PragmaPushMacroInfo.erase(iter);
} else {
Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
<< IdentInfo->getName();
}
}
void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
Lex(Tok);
if (Tok.isNot(tok::l_paren)) {
Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
return;
}
Token SourceFilenameTok;
if (LexHeaderName(SourceFilenameTok))
return;
StringRef SourceFileName;
SmallString<128> FileNameBuffer;
if (SourceFilenameTok.is(tok::header_name)) {
SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
} else {
Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
return;
}
FileNameBuffer.clear();
Lex(Tok);
if (Tok.isNot(tok::comma)) {
Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
return;
}
Token ReplaceFilenameTok;
if (LexHeaderName(ReplaceFilenameTok))
return;
StringRef ReplaceFileName;
if (ReplaceFilenameTok.is(tok::header_name)) {
ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
} else {
Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
return;
}
Lex(Tok);
if (Tok.isNot(tok::r_paren)) {
Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
return;
}
StringRef OriginalSource = SourceFileName;
bool SourceIsAngled =
GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
SourceFileName);
bool ReplaceIsAngled =
GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
ReplaceFileName);
if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
(SourceIsAngled != ReplaceIsAngled)) {
unsigned int DiagID;
if (SourceIsAngled)
DiagID = diag::warn_pragma_include_alias_mismatch_angle;
else
DiagID = diag::warn_pragma_include_alias_mismatch_quote;
Diag(SourceFilenameTok.getLocation(), DiagID)
<< SourceFileName
<< ReplaceFileName;
return;
}
getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
}
static bool LexModuleNameComponent(
Preprocessor &PP, Token &Tok,
std::pair<IdentifierInfo *, SourceLocation> &ModuleNameComponent,
bool First) {
PP.LexUnexpandedToken(Tok);
if (Tok.is(tok::string_literal) && !Tok.hasUDSuffix()) {
StringLiteralParser Literal(Tok, PP);
if (Literal.hadError)
return true;
ModuleNameComponent = std::make_pair(
PP.getIdentifierInfo(Literal.GetString()), Tok.getLocation());
} else if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) {
ModuleNameComponent =
std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation());
} else {
PP.Diag(Tok.getLocation(), diag::err_pp_expected_module_name) << First;
return true;
}
return false;
}
static bool LexModuleName(
Preprocessor &PP, Token &Tok,
llvm::SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>>
&ModuleName) {
while (true) {
std::pair<IdentifierInfo*, SourceLocation> NameComponent;
if (LexModuleNameComponent(PP, Tok, NameComponent, ModuleName.empty()))
return true;
ModuleName.push_back(NameComponent);
PP.LexUnexpandedToken(Tok);
if (Tok.isNot(tok::period))
return false;
}
}
void Preprocessor::HandlePragmaModuleBuild(Token &Tok) {
SourceLocation Loc = Tok.getLocation();
std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
if (LexModuleNameComponent(*this, Tok, ModuleNameLoc, true))
return;
IdentifierInfo *ModuleName = ModuleNameLoc.first;
LexUnexpandedToken(Tok);
if (Tok.isNot(tok::eod)) {
Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
DiscardUntilEndOfDirective();
}
CurLexer->LexingRawMode = true;
auto TryConsumeIdentifier = [&](StringRef Ident) -> bool {
if (Tok.getKind() != tok::raw_identifier ||
Tok.getRawIdentifier() != Ident)
return false;
CurLexer->Lex(Tok);
return true;
};
const char *Start = CurLexer->getBufferLocation();
const char *End = nullptr;
unsigned NestingLevel = 1;
while (true) {
End = CurLexer->getBufferLocation();
CurLexer->Lex(Tok);
if (Tok.is(tok::eof)) {
Diag(Loc, diag::err_pp_module_build_missing_end);
break;
}
if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) {
continue;
}
CurLexer->ParsingPreprocessorDirective = true;
CurLexer->Lex(Tok);
if (TryConsumeIdentifier("pragma") && TryConsumeIdentifier("clang") &&
TryConsumeIdentifier("module")) {
if (TryConsumeIdentifier("build"))
++NestingLevel;
else if (TryConsumeIdentifier("endbuild")) {
if (--NestingLevel == 0)
break;
}
assert(Tok.getKind() != tok::eof && "missing EOD before EOF");
}
}
CurLexer->LexingRawMode = false;
assert(CurLexer->getBuffer().begin() <= Start &&
Start <= CurLexer->getBuffer().end() &&
CurLexer->getBuffer().begin() <= End &&
End <= CurLexer->getBuffer().end() &&
"module source range not contained within same file buffer");
TheModuleLoader.createModuleFromSource(Loc, ModuleName->getName(),
StringRef(Start, End - Start));
}
void Preprocessor::HandlePragmaHdrstop(Token &Tok) {
Lex(Tok);
if (Tok.is(tok::l_paren)) {
Diag(Tok.getLocation(), diag::warn_pp_hdrstop_filename_ignored);
std::string FileName;
if (!LexStringLiteral(Tok, FileName, "pragma hdrstop", false))
return;
if (Tok.isNot(tok::r_paren)) {
Diag(Tok, diag::err_expected) << tok::r_paren;
return;
}
Lex(Tok);
}
if (Tok.isNot(tok::eod))
Diag(Tok.getLocation(), diag::ext_pp_extra_tokens_at_eol)
<< "pragma hdrstop";
if (creatingPCHWithPragmaHdrStop() &&
SourceMgr.isInMainFile(Tok.getLocation())) {
assert(CurLexer && "no lexer for #pragma hdrstop processing");
Token &Result = Tok;
Result.startToken();
CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
CurLexer->cutOffLexing();
}
if (usingPCHWithPragmaHdrStop())
SkippingUntilPragmaHdrStop = false;
}
void Preprocessor::AddPragmaHandler(StringRef Namespace,
PragmaHandler *Handler) {
PragmaNamespace *InsertNS = PragmaHandlers.get();
if (!Namespace.empty()) {
if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
InsertNS = Existing->getIfNamespace();
assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
" handler with the same name!");
} else {
InsertNS = new PragmaNamespace(Namespace);
PragmaHandlers->AddPragma(InsertNS);
}
}
assert(!InsertNS->FindHandler(Handler->getName()) &&
"Pragma handler already exists for this identifier!");
InsertNS->AddPragma(Handler);
}
void Preprocessor::RemovePragmaHandler(StringRef Namespace,
PragmaHandler *Handler) {
PragmaNamespace *NS = PragmaHandlers.get();
if (!Namespace.empty()) {
PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
assert(Existing && "Namespace containing handler does not exist!");
NS = Existing->getIfNamespace();
assert(NS && "Invalid namespace, registered as a regular pragma handler!");
}
NS->RemovePragmaHandler(Handler);
if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
PragmaHandlers->RemovePragmaHandler(NS);
delete NS;
}
}
bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
Token Tok;
LexUnexpandedToken(Tok);
if (Tok.isNot(tok::identifier)) {
Diag(Tok, diag::ext_on_off_switch_syntax);
return true;
}
IdentifierInfo *II = Tok.getIdentifierInfo();
if (II->isStr("ON"))
Result = tok::OOS_ON;
else if (II->isStr("OFF"))
Result = tok::OOS_OFF;
else if (II->isStr("DEFAULT"))
Result = tok::OOS_DEFAULT;
else {
Diag(Tok, diag::ext_on_off_switch_syntax);
return true;
}
LexUnexpandedToken(Tok);
if (Tok.isNot(tok::eod))
Diag(Tok, diag::ext_pragma_syntax_eod);
return false;
}
namespace {
struct PragmaOnceHandler : public PragmaHandler {
PragmaOnceHandler() : PragmaHandler("once") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &OnceTok) override {
PP.CheckEndOfDirective("pragma once");
PP.HandlePragmaOnce(OnceTok);
}
};
struct PragmaMarkHandler : public PragmaHandler {
PragmaMarkHandler() : PragmaHandler("mark") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &MarkTok) override {
PP.HandlePragmaMark(MarkTok);
}
};
struct PragmaPoisonHandler : public PragmaHandler {
PragmaPoisonHandler() : PragmaHandler("poison") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &PoisonTok) override {
PP.HandlePragmaPoison();
}
};
struct PragmaSystemHeaderHandler : public PragmaHandler {
PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &SHToken) override {
PP.HandlePragmaSystemHeader(SHToken);
PP.CheckEndOfDirective("pragma");
}
};
struct PragmaDependencyHandler : public PragmaHandler {
PragmaDependencyHandler() : PragmaHandler("dependency") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &DepToken) override {
PP.HandlePragmaDependency(DepToken);
}
};
struct PragmaDebugHandler : public PragmaHandler {
PragmaDebugHandler() : PragmaHandler("__debug") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &DebugToken) override {
Token Tok;
PP.LexUnexpandedToken(Tok);
if (Tok.isNot(tok::identifier)) {
PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
return;
}
IdentifierInfo *II = Tok.getIdentifierInfo();
if (II->isStr("assert")) {
if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
llvm_unreachable("This is an assertion!");
} else if (II->isStr("crash")) {
llvm::Timer T("crash", "pragma crash");
llvm::TimeRegion R(&T);
if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
LLVM_BUILTIN_TRAP;
} else if (II->isStr("parser_crash")) {
if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash) {
Token Crasher;
Crasher.startToken();
Crasher.setKind(tok::annot_pragma_parser_crash);
Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
PP.EnterToken(Crasher, false);
}
} else if (II->isStr("dump")) {
Token Identifier;
PP.LexUnexpandedToken(Identifier);
if (auto *DumpII = Identifier.getIdentifierInfo()) {
Token DumpAnnot;
DumpAnnot.startToken();
DumpAnnot.setKind(tok::annot_pragma_dump);
DumpAnnot.setAnnotationRange(
SourceRange(Tok.getLocation(), Identifier.getLocation()));
DumpAnnot.setAnnotationValue(DumpII);
PP.DiscardUntilEndOfDirective();
PP.EnterToken(DumpAnnot, false);
} else {
PP.Diag(Identifier, diag::warn_pragma_debug_missing_argument)
<< II->getName();
}
} else if (II->isStr("diag_mapping")) {
Token DiagName;
PP.LexUnexpandedToken(DiagName);
if (DiagName.is(tok::eod))
PP.getDiagnostics().dump();
else if (DiagName.is(tok::string_literal) && !DiagName.hasUDSuffix()) {
StringLiteralParser Literal(DiagName, PP);
if (Literal.hadError)
return;
PP.getDiagnostics().dump(Literal.GetString());
} else {
PP.Diag(DiagName, diag::warn_pragma_debug_missing_argument)
<< II->getName();
}
} else if (II->isStr("llvm_fatal_error")) {
if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
} else if (II->isStr("llvm_unreachable")) {
if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
llvm_unreachable("#pragma clang __debug llvm_unreachable");
} else if (II->isStr("macro")) {
Token MacroName;
PP.LexUnexpandedToken(MacroName);
auto *MacroII = MacroName.getIdentifierInfo();
if (MacroII)
PP.dumpMacroInfo(MacroII);
else
PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument)
<< II->getName();
} else if (II->isStr("module_map")) {
llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
ModuleName;
if (LexModuleName(PP, Tok, ModuleName))
return;
ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
Module *M = nullptr;
for (auto IIAndLoc : ModuleName) {
M = MM.lookupModuleQualified(IIAndLoc.first->getName(), M);
if (!M) {
PP.Diag(IIAndLoc.second, diag::warn_pragma_debug_unknown_module)
<< IIAndLoc.first;
return;
}
}
M->dump();
} else if (II->isStr("overflow_stack")) {
if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
DebugOverflowStack();
} else if (II->isStr("captured")) {
HandleCaptured(PP);
} else if (II->isStr("modules")) {
struct ModuleVisitor {
Preprocessor &PP;
void visit(Module *M, bool VisibleOnly) {
SourceLocation ImportLoc = PP.getModuleImportLoc(M);
if (!VisibleOnly || ImportLoc.isValid()) {
llvm::errs() << M->getFullModuleName() << " ";
if (ImportLoc.isValid()) {
llvm::errs() << M << " visible ";
ImportLoc.print(llvm::errs(), PP.getSourceManager());
}
llvm::errs() << "\n";
}
for (Module *Sub : M->submodules()) {
if (!VisibleOnly || ImportLoc.isInvalid() || Sub->IsExplicit)
visit(Sub, VisibleOnly);
}
}
void visitAll(bool VisibleOnly) {
for (auto &NameAndMod :
PP.getHeaderSearchInfo().getModuleMap().modules())
visit(NameAndMod.second, VisibleOnly);
}
} Visitor{PP};
Token Kind;
PP.LexUnexpandedToken(Kind);
auto *DumpII = Kind.getIdentifierInfo();
if (!DumpII) {
PP.Diag(Kind, diag::warn_pragma_debug_missing_argument)
<< II->getName();
} else if (DumpII->isStr("all")) {
Visitor.visitAll(false);
} else if (DumpII->isStr("visible")) {
Visitor.visitAll(true);
} else if (DumpII->isStr("building")) {
for (auto &Building : PP.getBuildingSubmodules()) {
llvm::errs() << "in " << Building.M->getFullModuleName();
if (Building.ImportLoc.isValid()) {
llvm::errs() << " imported ";
if (Building.IsPragma)
llvm::errs() << "via pragma ";
llvm::errs() << "at ";
Building.ImportLoc.print(llvm::errs(), PP.getSourceManager());
llvm::errs() << "\n";
}
}
} else {
PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
<< DumpII->getName();
}
} else {
PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
<< II->getName();
}
PPCallbacks *Callbacks = PP.getPPCallbacks();
if (Callbacks)
Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
}
void HandleCaptured(Preprocessor &PP) {
Token Tok;
PP.LexUnexpandedToken(Tok);
if (Tok.isNot(tok::eod)) {
PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
<< "pragma clang __debug captured";
return;
}
SourceLocation NameLoc = Tok.getLocation();
MutableArrayRef<Token> Toks(
PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
Toks[0].startToken();
Toks[0].setKind(tok::annot_pragma_captured);
Toks[0].setLocation(NameLoc);
PP.EnterTokenStream(Toks, true,
false);
}
#ifdef _MSC_VER
#pragma warning(disable : 4717)
#endif
static void DebugOverflowStack(void (*P)() = nullptr) {
void (*volatile Self)(void(*P)()) = DebugOverflowStack;
Self(reinterpret_cast<void(*)()>(Self));
}
#ifdef _MSC_VER
#pragma warning(default : 4717)
#endif
};
struct PragmaDiagnosticHandler : public PragmaHandler {
private:
const char *Namespace;
public:
explicit PragmaDiagnosticHandler(const char *NS)
: PragmaHandler("diagnostic"), Namespace(NS) {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &DiagToken) override {
SourceLocation DiagLoc = DiagToken.getLocation();
Token Tok;
PP.LexUnexpandedToken(Tok);
if (Tok.isNot(tok::identifier)) {
PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
return;
}
IdentifierInfo *II = Tok.getIdentifierInfo();
PPCallbacks *Callbacks = PP.getPPCallbacks();
if (II->isStr("pop")) {
if (!PP.getDiagnostics().popMappings(DiagLoc))
PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
else if (Callbacks)
Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
return;
} else if (II->isStr("push")) {
PP.getDiagnostics().pushMappings(DiagLoc);
if (Callbacks)
Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
return;
}
diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
.Case("ignored", diag::Severity::Ignored)
.Case("warning", diag::Severity::Warning)
.Case("error", diag::Severity::Error)
.Case("fatal", diag::Severity::Fatal)
.Default(diag::Severity());
if (SV == diag::Severity()) {
PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
return;
}
PP.LexUnexpandedToken(Tok);
SourceLocation StringLoc = Tok.getLocation();
std::string WarningName;
if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
false))
return;
if (Tok.isNot(tok::eod)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
return;
}
if (WarningName.size() < 3 || WarningName[0] != '-' ||
(WarningName[1] != 'W' && WarningName[1] != 'R')) {
PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
return;
}
diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
: diag::Flavor::Remark;
StringRef Group = StringRef(WarningName).substr(2);
bool unknownDiag = false;
if (Group == "everything") {
PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc);
} else
unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV,
DiagLoc);
if (unknownDiag)
PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
<< WarningName;
else if (Callbacks)
Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
}
};
struct PragmaHdrstopHandler : public PragmaHandler {
PragmaHdrstopHandler() : PragmaHandler("hdrstop") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &DepToken) override {
PP.HandlePragmaHdrstop(DepToken);
}
};
struct PragmaWarningHandler : public PragmaHandler {
PragmaWarningHandler() : PragmaHandler("warning") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &Tok) override {
SourceLocation DiagLoc = Tok.getLocation();
PPCallbacks *Callbacks = PP.getPPCallbacks();
PP.Lex(Tok);
if (Tok.isNot(tok::l_paren)) {
PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
return;
}
PP.Lex(Tok);
IdentifierInfo *II = Tok.getIdentifierInfo();
if (II && II->isStr("push")) {
int Level = -1;
PP.Lex(Tok);
if (Tok.is(tok::comma)) {
PP.Lex(Tok);
uint64_t Value;
if (Tok.is(tok::numeric_constant) &&
PP.parseSimpleIntegerLiteral(Tok, Value))
Level = int(Value);
if (Level < 0 || Level > 4) {
PP.Diag(Tok, diag::warn_pragma_warning_push_level);
return;
}
}
PP.getDiagnostics().pushMappings(DiagLoc);
if (Callbacks)
Callbacks->PragmaWarningPush(DiagLoc, Level);
} else if (II && II->isStr("pop")) {
PP.Lex(Tok);
if (!PP.getDiagnostics().popMappings(DiagLoc))
PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
else if (Callbacks)
Callbacks->PragmaWarningPop(DiagLoc);
} else {
while (true) {
II = Tok.getIdentifierInfo();
if (!II && !Tok.is(tok::numeric_constant)) {
PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
return;
}
bool SpecifierValid;
PPCallbacks::PragmaWarningSpecifier Specifier;
if (II) {
int SpecifierInt = llvm::StringSwitch<int>(II->getName())
.Case("default", PPCallbacks::PWS_Default)
.Case("disable", PPCallbacks::PWS_Disable)
.Case("error", PPCallbacks::PWS_Error)
.Case("once", PPCallbacks::PWS_Once)
.Case("suppress", PPCallbacks::PWS_Suppress)
.Default(-1);
if ((SpecifierValid = SpecifierInt != -1))
Specifier =
static_cast<PPCallbacks::PragmaWarningSpecifier>(SpecifierInt);
if (SpecifierValid)
PP.Lex(Tok);
} else {
uint64_t Value;
if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
if ((SpecifierValid = (Value >= 1) && (Value <= 4)))
Specifier = static_cast<PPCallbacks::PragmaWarningSpecifier>(
PPCallbacks::PWS_Level1 + Value - 1);
} else
SpecifierValid = false;
}
if (!SpecifierValid) {
PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
return;
}
if (Tok.isNot(tok::colon)) {
PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
return;
}
SmallVector<int, 4> Ids;
PP.Lex(Tok);
while (Tok.is(tok::numeric_constant)) {
uint64_t Value;
if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
Value > INT_MAX) {
PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
return;
}
Ids.push_back(int(Value));
}
diag::Severity SV = diag::Severity();
if (Specifier == PPCallbacks::PWS_Disable)
SV = diag::Severity::Ignored;
if (SV != diag::Severity())
for (int Id : Ids) {
if (auto Group = diagGroupFromCLWarningID(Id)) {
bool unknownDiag = PP.getDiagnostics().setSeverityForGroup(
diag::Flavor::WarningOrError, *Group, SV, DiagLoc);
assert(!unknownDiag &&
"wd table should only contain known diags");
(void)unknownDiag;
}
}
if (Callbacks)
Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
if (Tok.isNot(tok::semi))
break;
PP.Lex(Tok);
}
}
if (Tok.isNot(tok::r_paren)) {
PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
return;
}
PP.Lex(Tok);
if (Tok.isNot(tok::eod))
PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
}
};
struct PragmaExecCharsetHandler : public PragmaHandler {
PragmaExecCharsetHandler() : PragmaHandler("execution_character_set") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &Tok) override {
SourceLocation DiagLoc = Tok.getLocation();
PPCallbacks *Callbacks = PP.getPPCallbacks();
PP.Lex(Tok);
if (Tok.isNot(tok::l_paren)) {
PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << "(";
return;
}
PP.Lex(Tok);
IdentifierInfo *II = Tok.getIdentifierInfo();
if (II && II->isStr("push")) {
PP.Lex(Tok);
if (Tok.is(tok::comma)) {
PP.Lex(Tok);
std::string ExecCharset;
if (!PP.FinishLexStringLiteral(Tok, ExecCharset,
"pragma execution_character_set",
false))
return;
if (ExecCharset != "UTF-8" && ExecCharset != "utf-8") {
PP.Diag(Tok, diag::warn_pragma_exec_charset_push_invalid) << ExecCharset;
return;
}
}
if (Callbacks)
Callbacks->PragmaExecCharsetPush(DiagLoc, "UTF-8");
} else if (II && II->isStr("pop")) {
PP.Lex(Tok);
if (Callbacks)
Callbacks->PragmaExecCharsetPop(DiagLoc);
} else {
PP.Diag(Tok, diag::warn_pragma_exec_charset_spec_invalid);
return;
}
if (Tok.isNot(tok::r_paren)) {
PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << ")";
return;
}
PP.Lex(Tok);
if (Tok.isNot(tok::eod))
PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma execution_character_set";
}
};
struct PragmaIncludeAliasHandler : public PragmaHandler {
PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &IncludeAliasTok) override {
PP.HandlePragmaIncludeAlias(IncludeAliasTok);
}
};
struct PragmaMessageHandler : public PragmaHandler {
private:
const PPCallbacks::PragmaMessageKind Kind;
const StringRef Namespace;
static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
bool PragmaNameOnly = false) {
switch (Kind) {
case PPCallbacks::PMK_Message:
return PragmaNameOnly ? "message" : "pragma message";
case PPCallbacks::PMK_Warning:
return PragmaNameOnly ? "warning" : "pragma warning";
case PPCallbacks::PMK_Error:
return PragmaNameOnly ? "error" : "pragma error";
}
llvm_unreachable("Unknown PragmaMessageKind!");
}
public:
PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
StringRef Namespace = StringRef())
: PragmaHandler(PragmaKind(Kind, true)), Kind(Kind),
Namespace(Namespace) {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &Tok) override {
SourceLocation MessageLoc = Tok.getLocation();
PP.Lex(Tok);
bool ExpectClosingParen = false;
switch (Tok.getKind()) {
case tok::l_paren:
ExpectClosingParen = true;
PP.Lex(Tok);
break;
case tok::string_literal:
break;
default:
PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
return;
}
std::string MessageString;
if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
true))
return;
if (ExpectClosingParen) {
if (Tok.isNot(tok::r_paren)) {
PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
return;
}
PP.Lex(Tok); }
if (Tok.isNot(tok::eod)) {
PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
return;
}
PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
? diag::err_pragma_message
: diag::warn_pragma_message) << MessageString;
if (PPCallbacks *Callbacks = PP.getPPCallbacks())
Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
}
};
struct PragmaModuleImportHandler : public PragmaHandler {
PragmaModuleImportHandler() : PragmaHandler("import") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &Tok) override {
SourceLocation ImportLoc = Tok.getLocation();
llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
ModuleName;
if (LexModuleName(PP, Tok, ModuleName))
return;
if (Tok.isNot(tok::eod))
PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
Module *Imported =
PP.getModuleLoader().loadModule(ImportLoc, ModuleName, Module::Hidden,
false);
if (!Imported)
return;
PP.makeModuleVisible(Imported, ImportLoc);
PP.EnterAnnotationToken(SourceRange(ImportLoc, ModuleName.back().second),
tok::annot_module_include, Imported);
if (auto *CB = PP.getPPCallbacks())
CB->moduleImport(ImportLoc, ModuleName, Imported);
}
};
struct PragmaModuleBeginHandler : public PragmaHandler {
PragmaModuleBeginHandler() : PragmaHandler("begin") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &Tok) override {
SourceLocation BeginLoc = Tok.getLocation();
llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
ModuleName;
if (LexModuleName(PP, Tok, ModuleName))
return;
if (Tok.isNot(tok::eod))
PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
StringRef Current = PP.getLangOpts().CurrentModule;
if (ModuleName.front().first->getName() != Current) {
PP.Diag(ModuleName.front().second, diag::err_pp_module_begin_wrong_module)
<< ModuleName.front().first << (ModuleName.size() > 1)
<< Current.empty() << Current;
return;
}
auto &HSI = PP.getHeaderSearchInfo();
Module *M = HSI.lookupModule(Current, ModuleName.front().second);
if (!M) {
PP.Diag(ModuleName.front().second,
diag::err_pp_module_begin_no_module_map) << Current;
return;
}
for (unsigned I = 1; I != ModuleName.size(); ++I) {
auto *NewM = M->findOrInferSubmodule(ModuleName[I].first->getName());
if (!NewM) {
PP.Diag(ModuleName[I].second, diag::err_pp_module_begin_no_submodule)
<< M->getFullModuleName() << ModuleName[I].first;
return;
}
M = NewM;
}
if (Preprocessor::checkModuleIsAvailable(
PP.getLangOpts(), PP.getTargetInfo(), PP.getDiagnostics(), M)) {
PP.Diag(BeginLoc, diag::note_pp_module_begin_here)
<< M->getTopLevelModuleName();
return;
}
PP.EnterSubmodule(M, BeginLoc, true);
PP.EnterAnnotationToken(SourceRange(BeginLoc, ModuleName.back().second),
tok::annot_module_begin, M);
}
};
struct PragmaModuleEndHandler : public PragmaHandler {
PragmaModuleEndHandler() : PragmaHandler("end") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &Tok) override {
SourceLocation Loc = Tok.getLocation();
PP.LexUnexpandedToken(Tok);
if (Tok.isNot(tok::eod))
PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
Module *M = PP.LeaveSubmodule(true);
if (M)
PP.EnterAnnotationToken(SourceRange(Loc), tok::annot_module_end, M);
else
PP.Diag(Loc, diag::err_pp_module_end_without_module_begin);
}
};
struct PragmaModuleBuildHandler : public PragmaHandler {
PragmaModuleBuildHandler() : PragmaHandler("build") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &Tok) override {
PP.HandlePragmaModuleBuild(Tok);
}
};
struct PragmaModuleLoadHandler : public PragmaHandler {
PragmaModuleLoadHandler() : PragmaHandler("load") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &Tok) override {
SourceLocation Loc = Tok.getLocation();
llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
ModuleName;
if (LexModuleName(PP, Tok, ModuleName))
return;
if (Tok.isNot(tok::eod))
PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
PP.getModuleLoader().loadModule(Loc, ModuleName, Module::Hidden,
false);
}
};
struct PragmaPushMacroHandler : public PragmaHandler {
PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &PushMacroTok) override {
PP.HandlePragmaPushMacro(PushMacroTok);
}
};
struct PragmaPopMacroHandler : public PragmaHandler {
PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &PopMacroTok) override {
PP.HandlePragmaPopMacro(PopMacroTok);
}
};
struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &NameTok) override {
SourceLocation Loc = NameTok.getLocation();
bool IsBegin;
Token Tok;
PP.LexUnexpandedToken(Tok);
const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
if (BeginEnd && BeginEnd->isStr("begin")) {
IsBegin = true;
} else if (BeginEnd && BeginEnd->isStr("end")) {
IsBegin = false;
} else {
PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
return;
}
PP.LexUnexpandedToken(Tok);
if (Tok.isNot(tok::eod))
PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedInfo().second;
SourceLocation NewLoc;
if (IsBegin) {
if (BeginLoc.isValid()) {
PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
PP.Diag(BeginLoc, diag::note_pragma_entered_here);
}
NewLoc = Loc;
} else {
if (!BeginLoc.isValid()) {
PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
return;
}
NewLoc = SourceLocation();
}
PP.setPragmaARCCFCodeAuditedInfo(NameTok.getIdentifierInfo(), NewLoc);
}
};
struct PragmaAssumeNonNullHandler : public PragmaHandler {
PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &NameTok) override {
SourceLocation Loc = NameTok.getLocation();
bool IsBegin;
Token Tok;
PP.LexUnexpandedToken(Tok);
const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
if (BeginEnd && BeginEnd->isStr("begin")) {
IsBegin = true;
} else if (BeginEnd && BeginEnd->isStr("end")) {
IsBegin = false;
} else {
PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
return;
}
PP.LexUnexpandedToken(Tok);
if (Tok.isNot(tok::eod))
PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
SourceLocation NewLoc;
PPCallbacks *Callbacks = PP.getPPCallbacks();
if (IsBegin) {
if (BeginLoc.isValid()) {
PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
PP.Diag(BeginLoc, diag::note_pragma_entered_here);
}
NewLoc = Loc;
if (Callbacks)
Callbacks->PragmaAssumeNonNullBegin(NewLoc);
} else {
if (!BeginLoc.isValid()) {
PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
return;
}
NewLoc = SourceLocation();
if (Callbacks)
Callbacks->PragmaAssumeNonNullEnd(NewLoc);
}
PP.setPragmaAssumeNonNullLoc(NewLoc);
}
};
struct PragmaRegionHandler : public PragmaHandler {
PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &NameTok) override {
}
};
static IdentifierInfo *HandleMacroAnnotationPragma(Preprocessor &PP, Token &Tok,
const char *Pragma,
std::string &MessageString) {
PP.Lex(Tok);
if (Tok.isNot(tok::l_paren)) {
PP.Diag(Tok, diag::err_expected) << "(";
return nullptr;
}
PP.LexUnexpandedToken(Tok);
if (!Tok.is(tok::identifier)) {
PP.Diag(Tok, diag::err_expected) << tok::identifier;
return nullptr;
}
IdentifierInfo *II = Tok.getIdentifierInfo();
if (!II->hasMacroDefinition()) {
PP.Diag(Tok, diag::err_pp_visibility_non_macro) << II;
return nullptr;
}
PP.Lex(Tok);
if (Tok.is(tok::comma)) {
PP.Lex(Tok);
if (!PP.FinishLexStringLiteral(Tok, MessageString, Pragma,
true))
return nullptr;
}
if (Tok.isNot(tok::r_paren)) {
PP.Diag(Tok, diag::err_expected) << ")";
return nullptr;
}
return II;
}
struct PragmaDeprecatedHandler : public PragmaHandler {
PragmaDeprecatedHandler() : PragmaHandler("deprecated") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &Tok) override {
std::string MessageString;
if (IdentifierInfo *II = HandleMacroAnnotationPragma(
PP, Tok, "#pragma clang deprecated", MessageString)) {
II->setIsDeprecatedMacro(true);
PP.addMacroDeprecationMsg(II, std::move(MessageString),
Tok.getLocation());
}
}
};
struct PragmaRestrictExpansionHandler : public PragmaHandler {
PragmaRestrictExpansionHandler() : PragmaHandler("restrict_expansion") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &Tok) override {
std::string MessageString;
if (IdentifierInfo *II = HandleMacroAnnotationPragma(
PP, Tok, "#pragma clang restrict_expansion", MessageString)) {
II->setIsRestrictExpansion(true);
PP.addRestrictExpansionMsg(II, std::move(MessageString),
Tok.getLocation());
}
}
};
struct PragmaFinalHandler : public PragmaHandler {
PragmaFinalHandler() : PragmaHandler("final") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &Tok) override {
PP.Lex(Tok);
if (Tok.isNot(tok::l_paren)) {
PP.Diag(Tok, diag::err_expected) << "(";
return;
}
PP.LexUnexpandedToken(Tok);
if (!Tok.is(tok::identifier)) {
PP.Diag(Tok, diag::err_expected) << tok::identifier;
return;
}
IdentifierInfo *II = Tok.getIdentifierInfo();
if (!II->hasMacroDefinition()) {
PP.Diag(Tok, diag::err_pp_visibility_non_macro) << II;
return;
}
PP.Lex(Tok);
if (Tok.isNot(tok::r_paren)) {
PP.Diag(Tok, diag::err_expected) << ")";
return;
}
II->setIsFinal(true);
PP.addFinalLoc(II, Tok.getLocation());
}
};
}
void Preprocessor::RegisterBuiltinPragmas() {
AddPragmaHandler(new PragmaOnceHandler());
AddPragmaHandler(new PragmaMarkHandler());
AddPragmaHandler(new PragmaPushMacroHandler());
AddPragmaHandler(new PragmaPopMacroHandler());
AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
AddPragmaHandler("GCC", new PragmaPoisonHandler());
AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
AddPragmaHandler("GCC", new PragmaDependencyHandler());
AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
"GCC"));
AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
"GCC"));
AddPragmaHandler("clang", new PragmaPoisonHandler());
AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
AddPragmaHandler("clang", new PragmaDebugHandler());
AddPragmaHandler("clang", new PragmaDependencyHandler());
AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
AddPragmaHandler("clang", new PragmaDeprecatedHandler());
AddPragmaHandler("clang", new PragmaRestrictExpansionHandler());
AddPragmaHandler("clang", new PragmaFinalHandler());
auto *ModuleHandler = new PragmaNamespace("module");
AddPragmaHandler("clang", ModuleHandler);
ModuleHandler->AddPragma(new PragmaModuleImportHandler());
ModuleHandler->AddPragma(new PragmaModuleBeginHandler());
ModuleHandler->AddPragma(new PragmaModuleEndHandler());
ModuleHandler->AddPragma(new PragmaModuleBuildHandler());
ModuleHandler->AddPragma(new PragmaModuleLoadHandler());
AddPragmaHandler(new PragmaRegionHandler("region"));
AddPragmaHandler(new PragmaRegionHandler("endregion"));
if (LangOpts.MicrosoftExt) {
AddPragmaHandler(new PragmaWarningHandler());
AddPragmaHandler(new PragmaExecCharsetHandler());
AddPragmaHandler(new PragmaIncludeAliasHandler());
AddPragmaHandler(new PragmaHdrstopHandler());
AddPragmaHandler(new PragmaSystemHeaderHandler());
}
for (const PragmaHandlerRegistry::entry &handler :
PragmaHandlerRegistry::entries()) {
AddPragmaHandler(handler.instantiate().release());
}
}
void Preprocessor::IgnorePragmas() {
AddPragmaHandler(new EmptyPragmaHandler());
AddPragmaHandler("GCC", new EmptyPragmaHandler());
AddPragmaHandler("clang", new EmptyPragmaHandler());
}