#include "clang/Basic/CharInfo.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/IdentifierTable.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/CodeCompletionHandler.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/LexDiagnostic.h"
#include "clang/Lex/LiteralSupport.h"
#include "clang/Lex/MacroInfo.h"
#include "clang/Lex/ModuleLoader.h"
#include "clang/Lex/ModuleMap.h"
#include "clang/Lex/PPCallbacks.h"
#include "clang/Lex/Pragma.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Lex/Token.h"
#include "clang/Lex/VariadicMacroSupport.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/AlignOf.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SaveAndRestore.h"
#include <algorithm>
#include <cassert>
#include <cstring>
#include <new>
#include <string>
#include <utility>
using namespace clang;
MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
auto *MIChain = new (BP) MacroInfoChain{L, MIChainHead};
MIChainHead = MIChain;
return &MIChain->MI;
}
DefMacroDirective *Preprocessor::AllocateDefMacroDirective(MacroInfo *MI,
SourceLocation Loc) {
return new (BP) DefMacroDirective(MI, Loc);
}
UndefMacroDirective *
Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) {
return new (BP) UndefMacroDirective(UndefLoc);
}
VisibilityMacroDirective *
Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
bool isPublic) {
return new (BP) VisibilityMacroDirective(Loc, isPublic);
}
SourceRange Preprocessor::DiscardUntilEndOfDirective() {
Token Tmp;
SourceRange Res;
LexUnexpandedToken(Tmp);
Res.setBegin(Tmp.getLocation());
while (Tmp.isNot(tok::eod)) {
assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
LexUnexpandedToken(Tmp);
}
Res.setEnd(Tmp.getLocation());
return Res;
}
enum MacroDiag {
MD_NoWarn, MD_KeywordDef, MD_ReservedMacro };
enum PPElifDiag {
PED_Elif,
PED_Elifdef,
PED_Elifndef
};
static bool isForModuleBuilding(Module *M, StringRef CurrentModule,
StringRef ModuleName) {
StringRef TopLevelName = M->getTopLevelModuleName();
if (M->getTopLevelModule()->IsFramework && CurrentModule == ModuleName &&
!CurrentModule.endswith("_Private") && TopLevelName.endswith("_Private"))
TopLevelName = TopLevelName.drop_back(8);
return TopLevelName == CurrentModule;
}
static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) {
const LangOptions &Lang = PP.getLangOpts();
if (isReservedInAllContexts(II->isReserved(Lang))) {
static constexpr StringRef ReservedMacro[] = {
"_ATFILE_SOURCE",
"_BSD_SOURCE",
"_CRT_NONSTDC_NO_WARNINGS",
"_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES",
"_CRT_SECURE_NO_WARNINGS",
"_FILE_OFFSET_BITS",
"_FORTIFY_SOURCE",
"_GLIBCXX_ASSERTIONS",
"_GLIBCXX_CONCEPT_CHECKS",
"_GLIBCXX_DEBUG",
"_GLIBCXX_DEBUG_PEDANTIC",
"_GLIBCXX_PARALLEL",
"_GLIBCXX_PARALLEL_ASSERTIONS",
"_GLIBCXX_SANITIZE_VECTOR",
"_GLIBCXX_USE_CXX11_ABI",
"_GLIBCXX_USE_DEPRECATED",
"_GNU_SOURCE",
"_ISOC11_SOURCE",
"_ISOC95_SOURCE",
"_ISOC99_SOURCE",
"_LARGEFILE64_SOURCE",
"_POSIX_C_SOURCE",
"_REENTRANT",
"_SVID_SOURCE",
"_THREAD_SAFE",
"_XOPEN_SOURCE",
"_XOPEN_SOURCE_EXTENDED",
"__STDCPP_WANT_MATH_SPEC_FUNCS__",
"__STDC_FORMAT_MACROS",
};
if (std::binary_search(std::begin(ReservedMacro), std::end(ReservedMacro),
II->getName()))
return MD_NoWarn;
return MD_ReservedMacro;
}
StringRef Text = II->getName();
if (II->isKeyword(Lang))
return MD_KeywordDef;
if (Lang.CPlusPlus11 && (Text.equals("override") || Text.equals("final")))
return MD_KeywordDef;
return MD_NoWarn;
}
static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) {
const LangOptions &Lang = PP.getLangOpts();
if (isReservedInAllContexts(II->isReserved(Lang)))
return MD_ReservedMacro;
return MD_NoWarn;
}
static bool warnByDefaultOnWrongCase(StringRef Include) {
if (::llvm::sys::path::begin(Include)->equals_insensitive("boost"))
return true;
static const size_t MaxStdHeaderNameLen = 18u;
if (Include.size() > MaxStdHeaderNameLen)
return false;
SmallString<32> LowerInclude{Include};
for (char &Ch : LowerInclude) {
if (static_cast<unsigned char>(Ch) > 0x7f)
return false; if (Ch >= 'A' && Ch <= 'Z')
Ch += 'a' - 'A';
else if (::llvm::sys::path::is_separator(Ch))
Ch = '/';
}
return llvm::StringSwitch<bool>(LowerInclude)
.Cases("assert.h", "complex.h", "ctype.h", "errno.h", "fenv.h", true)
.Cases("float.h", "inttypes.h", "iso646.h", "limits.h", "locale.h", true)
.Cases("math.h", "setjmp.h", "signal.h", "stdalign.h", "stdarg.h", true)
.Cases("stdatomic.h", "stdbool.h", "stddef.h", "stdint.h", "stdio.h", true)
.Cases("stdlib.h", "stdnoreturn.h", "string.h", "tgmath.h", "threads.h", true)
.Cases("time.h", "uchar.h", "wchar.h", "wctype.h", true)
.Cases("cassert", "ccomplex", "cctype", "cerrno", "cfenv", true)
.Cases("cfloat", "cinttypes", "ciso646", "climits", "clocale", true)
.Cases("cmath", "csetjmp", "csignal", "cstdalign", "cstdarg", true)
.Cases("cstdbool", "cstddef", "cstdint", "cstdio", "cstdlib", true)
.Cases("cstring", "ctgmath", "ctime", "cuchar", "cwchar", true)
.Case("cwctype", true)
.Cases("algorithm", "fstream", "list", "regex", "thread", true)
.Cases("array", "functional", "locale", "scoped_allocator", "tuple", true)
.Cases("atomic", "future", "map", "set", "type_traits", true)
.Cases("bitset", "initializer_list", "memory", "shared_mutex", "typeindex", true)
.Cases("chrono", "iomanip", "mutex", "sstream", "typeinfo", true)
.Cases("codecvt", "ios", "new", "stack", "unordered_map", true)
.Cases("complex", "iosfwd", "numeric", "stdexcept", "unordered_set", true)
.Cases("condition_variable", "iostream", "ostream", "streambuf", "utility", true)
.Cases("deque", "istream", "queue", "string", "valarray", true)
.Cases("exception", "iterator", "random", "strstream", "vector", true)
.Cases("forward_list", "limits", "ratio", "system_error", true)
.Cases("aio.h", "arpa/inet.h", "cpio.h", "dirent.h", "dlfcn.h", true)
.Cases("fcntl.h", "fmtmsg.h", "fnmatch.h", "ftw.h", "glob.h", true)
.Cases("grp.h", "iconv.h", "langinfo.h", "libgen.h", "monetary.h", true)
.Cases("mqueue.h", "ndbm.h", "net/if.h", "netdb.h", "netinet/in.h", true)
.Cases("netinet/tcp.h", "nl_types.h", "poll.h", "pthread.h", "pwd.h", true)
.Cases("regex.h", "sched.h", "search.h", "semaphore.h", "spawn.h", true)
.Cases("strings.h", "stropts.h", "sys/ipc.h", "sys/mman.h", "sys/msg.h", true)
.Cases("sys/resource.h", "sys/select.h", "sys/sem.h", "sys/shm.h", "sys/socket.h", true)
.Cases("sys/stat.h", "sys/statvfs.h", "sys/time.h", "sys/times.h", "sys/types.h", true)
.Cases("sys/uio.h", "sys/un.h", "sys/utsname.h", "sys/wait.h", "syslog.h", true)
.Cases("tar.h", "termios.h", "trace.h", "ulimit.h", true)
.Cases("unistd.h", "utime.h", "utmpx.h", "wordexp.h", true)
.Default(false);
}
static Optional<StringRef> findSimilarStr(
StringRef LHS, const std::vector<StringRef> &Candidates) {
for (StringRef C : Candidates) {
if (LHS.equals_insensitive(C)) {
return C;
}
}
size_t Length = LHS.size();
size_t MaxDist = Length < 3 ? Length - 1 : Length / 3;
Optional<std::pair<StringRef, size_t>> SimilarStr = None;
for (StringRef C : Candidates) {
size_t CurDist = LHS.edit_distance(C, true);
if (CurDist <= MaxDist) {
if (!SimilarStr) {
SimilarStr = {C, CurDist};
} else if (CurDist < SimilarStr->second) {
SimilarStr = {C, CurDist};
}
}
}
if (SimilarStr) {
return SimilarStr->first;
} else {
return None;
}
}
bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
bool *ShadowFlag) {
if (MacroNameTok.is(tok::eod))
return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
if (!II)
return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
if (II->isCPlusPlusOperatorKeyword()) {
Diag(MacroNameTok, getLangOpts().MicrosoftExt
? diag::ext_pp_operator_used_as_macro_name
: diag::err_pp_operator_used_as_macro_name)
<< II << MacroNameTok.getKind();
}
if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) {
return Diag(MacroNameTok, diag::err_defined_macro_name);
}
if (isDefineUndef == MU_Undef) {
auto *MI = getMacroInfo(II);
if (MI && MI->isBuiltinMacro()) {
Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
}
}
SourceLocation MacroNameLoc = MacroNameTok.getLocation();
if (ShadowFlag)
*ShadowFlag = false;
if (!SourceMgr.isInSystemHeader(MacroNameLoc) &&
(SourceMgr.getBufferName(MacroNameLoc) != "<built-in>")) {
MacroDiag D = MD_NoWarn;
if (isDefineUndef == MU_Define) {
D = shouldWarnOnMacroDef(*this, II);
}
else if (isDefineUndef == MU_Undef)
D = shouldWarnOnMacroUndef(*this, II);
if (D == MD_KeywordDef) {
if (ShadowFlag)
*ShadowFlag = true;
}
if (D == MD_ReservedMacro)
Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id);
}
return false;
}
void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
bool *ShadowFlag) {
LexUnexpandedToken(MacroNameTok);
if (MacroNameTok.is(tok::code_completion)) {
if (CodeComplete)
CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define);
setCodeCompletionReached();
LexUnexpandedToken(MacroNameTok);
}
if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag))
return;
if (MacroNameTok.isNot(tok::eod)) {
MacroNameTok.setKind(tok::eod);
DiscardUntilEndOfDirective();
}
}
SourceLocation Preprocessor::CheckEndOfDirective(const char *DirType,
bool EnableMacros) {
Token Tmp;
if (EnableMacros)
Lex(Tmp);
else
LexUnexpandedToken(Tmp);
while (Tmp.is(tok::comment)) LexUnexpandedToken(Tmp);
if (Tmp.is(tok::eod))
return Tmp.getLocation();
FixItHint Hint;
if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
!CurTokenLexer)
Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
return DiscardUntilEndOfDirective().getEnd();
}
void Preprocessor::SuggestTypoedDirective(const Token &Tok,
StringRef Directive) const {
if (getLangOpts().AsmPreprocessor) return;
std::vector<StringRef> Candidates = {
"if", "ifdef", "ifndef", "elif", "else", "endif"
};
if (LangOpts.C2x || LangOpts.CPlusPlus2b)
Candidates.insert(Candidates.end(), {"elifdef", "elifndef"});
if (Optional<StringRef> Sugg = findSimilarStr(Directive, Candidates)) {
assert(Tok.getLocation().isFileID());
CharSourceRange DirectiveRange = CharSourceRange::getCharRange(
Tok.getLocation(),
Tok.getLocation().getLocWithOffset(Directive.size()));
StringRef SuggValue = *Sugg;
auto Hint = FixItHint::CreateReplacement(DirectiveRange, SuggValue);
Diag(Tok, diag::warn_pp_invalid_directive) << 1 << SuggValue << Hint;
}
}
void Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
SourceLocation IfTokenLoc,
bool FoundNonSkipPortion,
bool FoundElse,
SourceLocation ElseLoc) {
assert(!SkippingExcludedConditionalBlock &&
"calling SkipExcludedConditionalBlock recursively");
llvm::SaveAndRestore<bool> SARSkipping(SkippingExcludedConditionalBlock,
true);
++NumSkipped;
assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
if (PreambleConditionalStack.reachedEOFWhileSkipping())
PreambleConditionalStack.clearSkipInfo();
else
CurPPLexer->pushConditionalLevel(IfTokenLoc, false,
FoundNonSkipPortion, FoundElse);
CurPPLexer->LexingRawMode = true;
Token Tok;
SourceLocation endLoc;
struct SkippingRangeStateTy {
Preprocessor &PP;
const char *BeginPtr = nullptr;
unsigned *SkipRangePtr = nullptr;
SkippingRangeStateTy(Preprocessor &PP) : PP(PP) {}
void beginLexPass() {
if (BeginPtr)
return;
BeginPtr = PP.CurLexer->getBufferLocation();
SkipRangePtr = &PP.RecordedSkippedRanges[BeginPtr];
if (*SkipRangePtr) {
PP.CurLexer->seek(PP.CurLexer->getCurrentBufferOffset() + *SkipRangePtr,
true);
}
}
void endLexPass(const char *Hashptr) {
if (!BeginPtr) {
assert(PP.CurLexer->isDependencyDirectivesLexer());
return;
}
if (!*SkipRangePtr) {
*SkipRangePtr = Hashptr - BeginPtr;
}
assert(*SkipRangePtr == Hashptr - BeginPtr);
BeginPtr = nullptr;
SkipRangePtr = nullptr;
}
} SkippingRangeState(*this);
while (true) {
if (CurLexer->isDependencyDirectivesLexer()) {
CurLexer->LexDependencyDirectiveTokenWhileSkipping(Tok);
} else {
SkippingRangeState.beginLexPass();
while (true) {
CurLexer->Lex(Tok);
if (Tok.is(tok::code_completion)) {
setCodeCompletionReached();
if (CodeComplete)
CodeComplete->CodeCompleteInConditionalExclusion();
continue;
}
if (Tok.is(tok::eof)) {
if (PreambleConditionalStack.isRecording())
PreambleConditionalStack.SkipInfo.emplace(HashTokenLoc, IfTokenLoc,
FoundNonSkipPortion,
FoundElse, ElseLoc);
break;
}
if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
continue;
break;
}
}
if (Tok.is(tok::eof))
break;
CurPPLexer->ParsingPreprocessorDirective = true;
if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
assert(Tok.is(tok::hash));
const char *Hashptr = CurLexer->getBufferLocation() - Tok.getLength();
assert(CurLexer->getSourceLocation(Hashptr) == Tok.getLocation());
LexUnexpandedToken(Tok);
if (Tok.isNot(tok::raw_identifier)) {
CurPPLexer->ParsingPreprocessorDirective = false;
if (CurLexer) CurLexer->resetExtendedTokenMode();
continue;
}
StringRef RI = Tok.getRawIdentifier();
char FirstChar = RI[0];
if (FirstChar >= 'a' && FirstChar <= 'z' &&
FirstChar != 'i' && FirstChar != 'e') {
CurPPLexer->ParsingPreprocessorDirective = false;
if (CurLexer) CurLexer->resetExtendedTokenMode();
continue;
}
char DirectiveBuf[20];
StringRef Directive;
if (!Tok.needsCleaning() && RI.size() < 20) {
Directive = RI;
} else {
std::string DirectiveStr = getSpelling(Tok);
size_t IdLen = DirectiveStr.size();
if (IdLen >= 20) {
CurPPLexer->ParsingPreprocessorDirective = false;
if (CurLexer) CurLexer->resetExtendedTokenMode();
continue;
}
memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Directive = StringRef(DirectiveBuf, IdLen);
}
if (Directive.startswith("if")) {
StringRef Sub = Directive.substr(2);
if (Sub.empty() || Sub == "def" || Sub == "ndef") { DiscardUntilEndOfDirective();
CurPPLexer->pushConditionalLevel(Tok.getLocation(), true,
false,
false);
} else {
SuggestTypoedDirective(Tok, Directive);
}
} else if (Directive[0] == 'e') {
StringRef Sub = Directive.substr(1);
if (Sub == "ndif") { PPConditionalInfo CondInfo;
CondInfo.WasSkipping = true; bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
(void)InCond; assert(!InCond && "Can't be skipping if not in a conditional!");
if (!CondInfo.WasSkipping) {
SkippingRangeState.endLexPass(Hashptr);
CurPPLexer->LexingRawMode = false;
endLoc = CheckEndOfDirective("endif");
CurPPLexer->LexingRawMode = true;
if (Callbacks)
Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
break;
} else {
DiscardUntilEndOfDirective();
}
} else if (Sub == "lse") { PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
if (!CondInfo.WasSkipping)
SkippingRangeState.endLexPass(Hashptr);
if (CondInfo.FoundElse)
Diag(Tok, diag::pp_err_else_after_else);
CondInfo.FoundElse = true;
if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
CondInfo.FoundNonSkip = true;
CurPPLexer->LexingRawMode = false;
endLoc = CheckEndOfDirective("else");
CurPPLexer->LexingRawMode = true;
if (Callbacks)
Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
break;
} else {
DiscardUntilEndOfDirective(); }
} else if (Sub == "lif") { PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
if (!CondInfo.WasSkipping)
SkippingRangeState.endLexPass(Hashptr);
if (CondInfo.FoundElse)
Diag(Tok, diag::pp_err_elif_after_else) << PED_Elif;
if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
DiscardUntilEndOfDirective();
} else {
assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
CurPPLexer->LexingRawMode = false;
IdentifierInfo *IfNDefMacro = nullptr;
DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
if (!CurPPLexer)
return;
const bool CondValue = DER.Conditional;
CurPPLexer->LexingRawMode = true;
if (Callbacks) {
Callbacks->Elif(
Tok.getLocation(), DER.ExprRange,
(CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False),
CondInfo.IfLoc);
}
if (CondValue) {
CondInfo.FoundNonSkip = true;
break;
}
}
} else if (Sub == "lifdef" || Sub == "lifndef") { bool IsElifDef = Sub == "lifdef";
PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Token DirectiveToken = Tok;
if (!CondInfo.WasSkipping)
SkippingRangeState.endLexPass(Hashptr);
unsigned DiagID;
if (LangOpts.CPlusPlus)
DiagID = LangOpts.CPlusPlus2b ? diag::warn_cxx2b_compat_pp_directive
: diag::ext_cxx2b_pp_directive;
else
DiagID = LangOpts.C2x ? diag::warn_c2x_compat_pp_directive
: diag::ext_c2x_pp_directive;
Diag(Tok, DiagID) << (IsElifDef ? PED_Elifdef : PED_Elifndef);
if (CondInfo.FoundElse)
Diag(Tok, diag::pp_err_elif_after_else)
<< (IsElifDef ? PED_Elifdef : PED_Elifndef);
if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
DiscardUntilEndOfDirective();
} else {
assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
CurPPLexer->LexingRawMode = false;
Token MacroNameTok;
ReadMacroName(MacroNameTok);
CurPPLexer->LexingRawMode = true;
if (MacroNameTok.is(tok::eod)) {
continue;
}
emitMacroExpansionWarnings(MacroNameTok);
CheckEndOfDirective(IsElifDef ? "elifdef" : "elifndef");
IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
auto MD = getMacroDefinition(MII);
MacroInfo *MI = MD.getMacroInfo();
if (Callbacks) {
if (IsElifDef) {
Callbacks->Elifdef(DirectiveToken.getLocation(), MacroNameTok,
MD);
} else {
Callbacks->Elifndef(DirectiveToken.getLocation(), MacroNameTok,
MD);
}
}
if (static_cast<bool>(MI) == IsElifDef) {
CondInfo.FoundNonSkip = true;
break;
}
}
} else {
SuggestTypoedDirective(Tok, Directive);
}
} else {
SuggestTypoedDirective(Tok, Directive);
}
CurPPLexer->ParsingPreprocessorDirective = false;
if (CurLexer) CurLexer->resetExtendedTokenMode();
}
CurPPLexer->LexingRawMode = false;
if (Callbacks && (Tok.isNot(tok::eof) || !isRecordingPreamble()))
Callbacks->SourceRangeSkipped(
SourceRange(HashTokenLoc, endLoc.isValid()
? endLoc
: CurPPLexer->getSourceLocation()),
Tok.getLocation());
}
Module *Preprocessor::getModuleForLocation(SourceLocation Loc) {
if (!SourceMgr.isInMainFile(Loc)) {
FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc));
if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
return HeaderInfo.getModuleMap()
.findModuleForHeader(EntryOfIncl)
.getModule();
}
}
return getLangOpts().CurrentModule.empty()
? nullptr
: HeaderInfo.lookupModule(getLangOpts().CurrentModule, Loc);
}
const FileEntry *
Preprocessor::getHeaderToIncludeForDiagnostics(SourceLocation IncLoc,
SourceLocation Loc) {
Module *IncM = getModuleForLocation(IncLoc);
auto &SM = getSourceManager();
while (!Loc.isInvalid() && !SM.isInMainFile(Loc)) {
auto ID = SM.getFileID(SM.getExpansionLoc(Loc));
auto *FE = SM.getFileEntryForID(ID);
if (!FE)
break;
HeaderInfo.hasModuleMap(FE->getName(), nullptr,
SourceMgr.isInSystemHeader(Loc));
bool InPrivateHeader = false;
for (auto Header : HeaderInfo.findAllModulesForHeader(FE)) {
if (!Header.isAccessibleFrom(IncM)) {
InPrivateHeader = true;
continue;
}
if (Header.getRole() & ModuleMap::TextualHeader)
continue;
if (getLangOpts().ObjC || getLangOpts().CPlusPlusModules ||
getLangOpts().ModulesTS)
return nullptr;
return FE;
}
if (InPrivateHeader)
return nullptr;
if (getHeaderSearchInfo().isFileMultipleIncludeGuarded(FE))
return FE;
Loc = SM.getIncludeLoc(ID);
}
return nullptr;
}
Optional<FileEntryRef> Preprocessor::LookupFile(
SourceLocation FilenameLoc, StringRef Filename, bool isAngled,
ConstSearchDirIterator FromDir, const FileEntry *FromFile,
ConstSearchDirIterator *CurDirArg, SmallVectorImpl<char> *SearchPath,
SmallVectorImpl<char> *RelativePath,
ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped,
bool *IsFrameworkFound, bool SkipCache) {
ConstSearchDirIterator CurDirLocal = nullptr;
ConstSearchDirIterator &CurDir = CurDirArg ? *CurDirArg : CurDirLocal;
Module *RequestingModule = getModuleForLocation(FilenameLoc);
bool RequestingModuleIsModuleInterface = !SourceMgr.isInMainFile(FilenameLoc);
SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
Includers;
bool BuildSystemModule = false;
if (!FromDir && !FromFile) {
FileID FID = getCurrentFileLexer()->getFileID();
const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
if (!FileEnt) {
if (FID == SourceMgr.getMainFileID() && MainFileDir) {
Includers.push_back(std::make_pair(nullptr, MainFileDir));
BuildSystemModule = getCurrentModule()->IsSystem;
} else if ((FileEnt =
SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
Includers.push_back(std::make_pair(FileEnt, *FileMgr.getDirectory(".")));
} else {
Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
}
if (LangOpts.MSVCCompat && !isAngled) {
for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
if (IsFileLexer(ISEntry))
if ((FileEnt = ISEntry.ThePPLexer->getFileEntry()))
Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
}
}
}
CurDir = CurDirLookup;
if (FromFile) {
ConstSearchDirIterator TmpCurDir = CurDir;
ConstSearchDirIterator TmpFromDir = nullptr;
while (Optional<FileEntryRef> FE = HeaderInfo.LookupFile(
Filename, FilenameLoc, isAngled, TmpFromDir, &TmpCurDir,
Includers, SearchPath, RelativePath, RequestingModule,
SuggestedModule, nullptr,
nullptr, SkipCache)) {
TmpFromDir = TmpCurDir;
++TmpFromDir;
if (&FE->getFileEntry() == FromFile) {
FromDir = TmpFromDir;
CurDir = TmpCurDir;
break;
}
}
}
Optional<FileEntryRef> FE = HeaderInfo.LookupFile(
Filename, FilenameLoc, isAngled, FromDir, &CurDir, Includers, SearchPath,
RelativePath, RequestingModule, SuggestedModule, IsMapped,
IsFrameworkFound, SkipCache, BuildSystemModule);
if (FE) {
if (SuggestedModule && !LangOpts.AsmPreprocessor)
HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
Filename, *FE);
return FE;
}
const FileEntry *CurFileEnt;
if (IsFileLexer()) {
if ((CurFileEnt = CurPPLexer->getFileEntry())) {
if (Optional<FileEntryRef> FE = HeaderInfo.LookupSubframeworkHeader(
Filename, CurFileEnt, SearchPath, RelativePath, RequestingModule,
SuggestedModule)) {
if (SuggestedModule && !LangOpts.AsmPreprocessor)
HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
Filename, *FE);
return FE;
}
}
}
for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
if (IsFileLexer(ISEntry)) {
if ((CurFileEnt = ISEntry.ThePPLexer->getFileEntry())) {
if (Optional<FileEntryRef> FE = HeaderInfo.LookupSubframeworkHeader(
Filename, CurFileEnt, SearchPath, RelativePath,
RequestingModule, SuggestedModule)) {
if (SuggestedModule && !LangOpts.AsmPreprocessor)
HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
RequestingModule, RequestingModuleIsModuleInterface,
FilenameLoc, Filename, *FE);
return FE;
}
}
}
}
return None;
}
class Preprocessor::ResetMacroExpansionHelper {
public:
ResetMacroExpansionHelper(Preprocessor *pp)
: PP(pp), save(pp->DisableMacroExpansion) {
if (pp->MacroExpansionInDirectivesOverride)
pp->DisableMacroExpansion = false;
}
~ResetMacroExpansionHelper() {
PP->DisableMacroExpansion = save;
}
private:
Preprocessor *PP;
bool save;
};
void Preprocessor::HandleSkippedDirectiveWhileUsingPCH(Token &Result,
SourceLocation HashLoc) {
if (const IdentifierInfo *II = Result.getIdentifierInfo()) {
if (II->getPPKeywordID() == tok::pp_define) {
return HandleDefineDirective(Result,
false);
}
if (SkippingUntilPCHThroughHeader &&
II->getPPKeywordID() == tok::pp_include) {
return HandleIncludeDirective(HashLoc, Result);
}
if (SkippingUntilPragmaHdrStop && II->getPPKeywordID() == tok::pp_pragma) {
Lex(Result);
auto *II = Result.getIdentifierInfo();
if (II && II->getName() == "hdrstop")
return HandlePragmaHdrstop(Result);
}
}
DiscardUntilEndOfDirective();
}
void Preprocessor::HandleDirective(Token &Result) {
CurPPLexer->ParsingPreprocessorDirective = true;
if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
bool ImmediatelyAfterTopLevelIfndef =
CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
++NumDirectives;
bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
Token SavedHash = Result;
LexUnexpandedToken(Result);
if (InMacroArgs) {
if (IdentifierInfo *II = Result.getIdentifierInfo()) {
switch (II->getPPKeywordID()) {
case tok::pp_include:
case tok::pp_import:
case tok::pp_include_next:
case tok::pp___include_macros:
case tok::pp_pragma:
Diag(Result, diag::err_embedded_directive) << II->getName();
Diag(*ArgMacro, diag::note_macro_expansion_here)
<< ArgMacro->getIdentifierInfo();
DiscardUntilEndOfDirective();
return;
default:
break;
}
}
Diag(Result, diag::ext_embedded_directive);
}
ResetMacroExpansionHelper helper(this);
if (SkippingUntilPCHThroughHeader || SkippingUntilPragmaHdrStop)
return HandleSkippedDirectiveWhileUsingPCH(Result, SavedHash.getLocation());
switch (Result.getKind()) {
case tok::eod:
return; case tok::code_completion:
setCodeCompletionReached();
if (CodeComplete)
CodeComplete->CodeCompleteDirective(
CurPPLexer->getConditionalStackDepth() > 0);
return;
case tok::numeric_constant: if (getLangOpts().AsmPreprocessor)
break; return HandleDigitDirective(Result);
default:
IdentifierInfo *II = Result.getIdentifierInfo();
if (!II) break;
switch (II->getPPKeywordID()) {
default: break;
case tok::pp_if:
return HandleIfDirective(Result, SavedHash, ReadAnyTokensBeforeDirective);
case tok::pp_ifdef:
return HandleIfdefDirective(Result, SavedHash, false,
true );
case tok::pp_ifndef:
return HandleIfdefDirective(Result, SavedHash, true,
ReadAnyTokensBeforeDirective);
case tok::pp_elif:
case tok::pp_elifdef:
case tok::pp_elifndef:
return HandleElifFamilyDirective(Result, SavedHash, II->getPPKeywordID());
case tok::pp_else:
return HandleElseDirective(Result, SavedHash);
case tok::pp_endif:
return HandleEndifDirective(Result);
case tok::pp_include:
return HandleIncludeDirective(SavedHash.getLocation(), Result);
case tok::pp___include_macros:
return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
case tok::pp_define:
return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
case tok::pp_undef:
return HandleUndefDirective();
case tok::pp_line:
return HandleLineDirective();
case tok::pp_error:
return HandleUserDiagnosticDirective(Result, false);
case tok::pp_pragma:
return HandlePragmaDirective({PIK_HashPragma, SavedHash.getLocation()});
case tok::pp_import:
return HandleImportDirective(SavedHash.getLocation(), Result);
case tok::pp_include_next:
return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
case tok::pp_warning:
if (LangOpts.CPlusPlus)
Diag(Result, LangOpts.CPlusPlus2b
? diag::warn_cxx2b_compat_warning_directive
: diag::ext_pp_warning_directive)
<< 1;
else
Diag(Result, LangOpts.C2x ? diag::warn_c2x_compat_warning_directive
: diag::ext_pp_warning_directive)
<< 0;
return HandleUserDiagnosticDirective(Result, true);
case tok::pp_ident:
return HandleIdentSCCSDirective(Result);
case tok::pp_sccs:
return HandleIdentSCCSDirective(Result);
case tok::pp_assert:
break;
case tok::pp_unassert:
break;
case tok::pp___public_macro:
if (getLangOpts().Modules || getLangOpts().ModulesLocalVisibility)
return HandleMacroPublicDirective(Result);
break;
case tok::pp___private_macro:
if (getLangOpts().Modules || getLangOpts().ModulesLocalVisibility)
return HandleMacroPrivateDirective();
break;
}
break;
}
if (getLangOpts().AsmPreprocessor) {
auto Toks = std::make_unique<Token[]>(2);
Toks[0] = SavedHash;
Toks[1] = Result;
if (Result.is(tok::hashhash))
Toks[1].setKind(tok::unknown);
EnterTokenStream(std::move(Toks), 2, false, false);
return;
}
Diag(Result, diag::err_pp_invalid_directive) << 0;
DiscardUntilEndOfDirective();
}
static bool GetLineValue(Token &DigitTok, unsigned &Val,
unsigned DiagID, Preprocessor &PP,
bool IsGNULineDirective=false) {
if (DigitTok.isNot(tok::numeric_constant)) {
PP.Diag(DigitTok, DiagID);
if (DigitTok.isNot(tok::eod))
PP.DiscardUntilEndOfDirective();
return true;
}
SmallString<64> IntegerBuffer;
IntegerBuffer.resize(DigitTok.getLength());
const char *DigitTokBegin = &IntegerBuffer[0];
bool Invalid = false;
unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
if (Invalid)
return true;
Val = 0;
for (unsigned i = 0; i != ActualLength; ++i) {
if (DigitTokBegin[i] == '\'')
continue;
if (!isDigit(DigitTokBegin[i])) {
PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
diag::err_pp_line_digit_sequence) << IsGNULineDirective;
PP.DiscardUntilEndOfDirective();
return true;
}
unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
if (NextVal < Val) { PP.Diag(DigitTok, DiagID);
PP.DiscardUntilEndOfDirective();
return true;
}
Val = NextVal;
}
if (DigitTokBegin[0] == '0' && Val)
PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
<< IsGNULineDirective;
return false;
}
void Preprocessor::HandleLineDirective() {
Token DigitTok;
Lex(DigitTok);
unsigned LineNo;
if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
return;
if (LineNo == 0)
Diag(DigitTok, diag::ext_pp_line_zero);
unsigned LineLimit = 32768U;
if (LangOpts.C99 || LangOpts.CPlusPlus11)
LineLimit = 2147483648U;
if (LineNo >= LineLimit)
Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
int FilenameID = -1;
Token StrTok;
Lex(StrTok);
if (StrTok.is(tok::eod))
; else if (StrTok.isNot(tok::string_literal)) {
Diag(StrTok, diag::err_pp_line_invalid_filename);
DiscardUntilEndOfDirective();
return;
} else if (StrTok.hasUDSuffix()) {
Diag(StrTok, diag::err_invalid_string_udl);
DiscardUntilEndOfDirective();
return;
} else {
StringLiteralParser Literal(StrTok, *this);
assert(Literal.isOrdinary() && "Didn't allow wide strings in");
if (Literal.hadError) {
DiscardUntilEndOfDirective();
return;
}
if (Literal.Pascal) {
Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
DiscardUntilEndOfDirective();
return;
}
FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
CheckEndOfDirective("line", true);
}
SrcMgr::CharacteristicKind FileKind =
SourceMgr.getFileCharacteristic(DigitTok.getLocation());
SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, false,
false, FileKind);
if (Callbacks)
Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
PPCallbacks::RenameFile, FileKind);
}
static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
SrcMgr::CharacteristicKind &FileKind,
Preprocessor &PP) {
unsigned FlagVal;
Token FlagTok;
PP.Lex(FlagTok);
if (FlagTok.is(tok::eod)) return false;
if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
return true;
if (FlagVal == 1) {
IsFileEntry = true;
PP.Lex(FlagTok);
if (FlagTok.is(tok::eod)) return false;
if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
return true;
} else if (FlagVal == 2) {
IsFileExit = true;
SourceManager &SM = PP.getSourceManager();
FileID CurFileID =
SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
if (PLoc.isInvalid())
return true;
SourceLocation IncLoc = PLoc.getIncludeLoc();
if (IncLoc.isInvalid() ||
SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
PP.DiscardUntilEndOfDirective();
return true;
}
PP.Lex(FlagTok);
if (FlagTok.is(tok::eod)) return false;
if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
return true;
}
if (FlagVal != 3) {
PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
PP.DiscardUntilEndOfDirective();
return true;
}
FileKind = SrcMgr::C_System;
PP.Lex(FlagTok);
if (FlagTok.is(tok::eod)) return false;
if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
return true;
if (FlagVal != 4) {
PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
PP.DiscardUntilEndOfDirective();
return true;
}
FileKind = SrcMgr::C_ExternCSystem;
PP.Lex(FlagTok);
if (FlagTok.is(tok::eod)) return false;
PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
PP.DiscardUntilEndOfDirective();
return true;
}
void Preprocessor::HandleDigitDirective(Token &DigitTok) {
unsigned LineNo;
if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
*this, true))
return;
Token StrTok;
Lex(StrTok);
bool IsFileEntry = false, IsFileExit = false;
int FilenameID = -1;
SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
if (StrTok.is(tok::eod)) {
Diag(StrTok, diag::ext_pp_gnu_line_directive);
FileKind = SourceMgr.getFileCharacteristic(DigitTok.getLocation());
} else if (StrTok.isNot(tok::string_literal)) {
Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
DiscardUntilEndOfDirective();
return;
} else if (StrTok.hasUDSuffix()) {
Diag(StrTok, diag::err_invalid_string_udl);
DiscardUntilEndOfDirective();
return;
} else {
StringLiteralParser Literal(StrTok, *this);
assert(Literal.isOrdinary() && "Didn't allow wide strings in");
if (Literal.hadError) {
DiscardUntilEndOfDirective();
return;
}
if (Literal.Pascal) {
Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
DiscardUntilEndOfDirective();
return;
}
if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, FileKind, *this))
return;
if (!SourceMgr.isWrittenInBuiltinFile(DigitTok.getLocation()) &&
!SourceMgr.isWrittenInCommandLineFile(DigitTok.getLocation()))
Diag(StrTok, diag::ext_pp_gnu_line_directive);
if (!(IsFileExit && Literal.GetString().empty()))
FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
}
SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, IsFileEntry,
IsFileExit, FileKind);
if (Callbacks) {
PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
if (IsFileEntry)
Reason = PPCallbacks::EnterFile;
else if (IsFileExit)
Reason = PPCallbacks::ExitFile;
Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
}
}
void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
bool isWarning) {
SmallString<128> Message;
CurLexer->ReadToEndOfLine(&Message);
StringRef Msg = Message.str().ltrim(' ');
if (isWarning)
Diag(Tok, diag::pp_hash_warning) << Msg;
else
Diag(Tok, diag::err_pp_hash_error) << Msg;
}
void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
Diag(Tok, diag::ext_pp_ident_directive);
Token StrTok;
Lex(StrTok);
if (StrTok.isNot(tok::string_literal) &&
StrTok.isNot(tok::wide_string_literal)) {
Diag(StrTok, diag::err_pp_malformed_ident);
if (StrTok.isNot(tok::eod))
DiscardUntilEndOfDirective();
return;
}
if (StrTok.hasUDSuffix()) {
Diag(StrTok, diag::err_invalid_string_udl);
DiscardUntilEndOfDirective();
return;
}
CheckEndOfDirective("ident");
if (Callbacks) {
bool Invalid = false;
std::string Str = getSpelling(StrTok, &Invalid);
if (!Invalid)
Callbacks->Ident(Tok.getLocation(), Str);
}
}
void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
Token MacroNameTok;
ReadMacroName(MacroNameTok, MU_Undef);
if (MacroNameTok.is(tok::eod))
return;
CheckEndOfDirective("__public_macro");
IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
MacroDirective *MD = getLocalMacroDirective(II);
if (!MD) {
Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
return;
}
appendMacroDirective(II, AllocateVisibilityMacroDirective(
MacroNameTok.getLocation(), true));
}
void Preprocessor::HandleMacroPrivateDirective() {
Token MacroNameTok;
ReadMacroName(MacroNameTok, MU_Undef);
if (MacroNameTok.is(tok::eod))
return;
CheckEndOfDirective("__private_macro");
IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
MacroDirective *MD = getLocalMacroDirective(II);
if (!MD) {
Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
return;
}
appendMacroDirective(II, AllocateVisibilityMacroDirective(
MacroNameTok.getLocation(), false));
}
bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
StringRef &Buffer) {
assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
bool isAngled;
if (Buffer[0] == '<') {
if (Buffer.back() != '>') {
Diag(Loc, diag::err_pp_expects_filename);
Buffer = StringRef();
return true;
}
isAngled = true;
} else if (Buffer[0] == '"') {
if (Buffer.back() != '"') {
Diag(Loc, diag::err_pp_expects_filename);
Buffer = StringRef();
return true;
}
isAngled = false;
} else {
Diag(Loc, diag::err_pp_expects_filename);
Buffer = StringRef();
return true;
}
if (Buffer.size() <= 2) {
Diag(Loc, diag::err_pp_empty_filename);
Buffer = StringRef();
return true;
}
Buffer = Buffer.substr(1, Buffer.size()-2);
return isAngled;
}
void Preprocessor::EnterAnnotationToken(SourceRange Range,
tok::TokenKind Kind,
void *AnnotationVal) {
auto Tok = std::make_unique<Token[]>(1);
Tok[0].startToken();
Tok[0].setKind(Kind);
Tok[0].setLocation(Range.getBegin());
Tok[0].setAnnotationEndLoc(Range.getEnd());
Tok[0].setAnnotationValue(AnnotationVal);
EnterTokenStream(std::move(Tok), 1, true, false);
}
static void diagnoseAutoModuleImport(
Preprocessor &PP, SourceLocation HashLoc, Token &IncludeTok,
ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> Path,
SourceLocation PathEnd) {
SmallString<128> PathString;
for (size_t I = 0, N = Path.size(); I != N; ++I) {
if (I)
PathString += '.';
PathString += Path[I].first->getName();
}
int IncludeKind = 0;
switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
case tok::pp_include:
IncludeKind = 0;
break;
case tok::pp_import:
IncludeKind = 1;
break;
case tok::pp_include_next:
IncludeKind = 2;
break;
case tok::pp___include_macros:
IncludeKind = 3;
break;
default:
llvm_unreachable("unknown include directive kind");
}
PP.Diag(HashLoc, diag::remark_pp_include_directive_modular_translation)
<< IncludeKind << PathString;
}
static bool trySimplifyPath(SmallVectorImpl<StringRef> &Components,
StringRef RealPathName) {
auto RealPathComponentIter = llvm::sys::path::rbegin(RealPathName);
auto RealPathComponentEnd = llvm::sys::path::rend(RealPathName);
int Cnt = 0;
bool SuggestReplacement = false;
for (auto &Component : llvm::reverse(Components)) {
if ("." == Component) {
} else if (".." == Component) {
++Cnt;
} else if (Cnt) {
--Cnt;
} else if (RealPathComponentIter != RealPathComponentEnd) {
if (Component != *RealPathComponentIter) {
SuggestReplacement =
RealPathComponentIter->equals_insensitive(Component);
if (!SuggestReplacement)
break;
Component = *RealPathComponentIter;
}
++RealPathComponentIter;
}
}
return SuggestReplacement;
}
bool Preprocessor::checkModuleIsAvailable(const LangOptions &LangOpts,
const TargetInfo &TargetInfo,
DiagnosticsEngine &Diags, Module *M) {
Module::Requirement Requirement;
Module::UnresolvedHeaderDirective MissingHeader;
Module *ShadowingModule = nullptr;
if (M->isAvailable(LangOpts, TargetInfo, Requirement, MissingHeader,
ShadowingModule))
return false;
if (MissingHeader.FileNameLoc.isValid()) {
Diags.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
<< MissingHeader.IsUmbrella << MissingHeader.FileName;
} else if (ShadowingModule) {
Diags.Report(M->DefinitionLoc, diag::err_module_shadowed) << M->Name;
Diags.Report(ShadowingModule->DefinitionLoc,
diag::note_previous_definition);
} else {
Diags.Report(M->DefinitionLoc, diag::err_module_unavailable)
<< M->getFullModuleName() << Requirement.second << Requirement.first;
}
return true;
}
std::pair<ConstSearchDirIterator, const FileEntry *>
Preprocessor::getIncludeNextStart(const Token &IncludeNextTok) const {
ConstSearchDirIterator Lookup = CurDirLookup;
const FileEntry *LookupFromFile = nullptr;
if (isInPrimaryFile() && LangOpts.IsHeaderFile) {
} else if (isInPrimaryFile()) {
Lookup = nullptr;
Diag(IncludeNextTok, diag::pp_include_next_in_primary);
} else if (CurLexerSubmodule) {
assert(CurPPLexer && "#include_next directive in macro?");
LookupFromFile = CurPPLexer->getFileEntry();
Lookup = nullptr;
} else if (!Lookup) {
Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
} else {
++Lookup;
}
return {Lookup, LookupFromFile};
}
void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
Token &IncludeTok,
ConstSearchDirIterator LookupFrom,
const FileEntry *LookupFromFile) {
Token FilenameTok;
if (LexHeaderName(FilenameTok))
return;
if (FilenameTok.isNot(tok::header_name)) {
Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
if (FilenameTok.isNot(tok::eod))
DiscardUntilEndOfDirective();
return;
}
SourceLocation EndLoc =
CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
auto Action = HandleHeaderIncludeOrImport(HashLoc, IncludeTok, FilenameTok,
EndLoc, LookupFrom, LookupFromFile);
switch (Action.Kind) {
case ImportAction::None:
case ImportAction::SkippedModuleImport:
break;
case ImportAction::ModuleBegin:
EnterAnnotationToken(SourceRange(HashLoc, EndLoc),
tok::annot_module_begin, Action.ModuleForHeader);
break;
case ImportAction::HeaderUnitImport:
EnterAnnotationToken(SourceRange(HashLoc, EndLoc), tok::annot_header_unit,
Action.ModuleForHeader);
break;
case ImportAction::ModuleImport:
EnterAnnotationToken(SourceRange(HashLoc, EndLoc),
tok::annot_module_include, Action.ModuleForHeader);
break;
case ImportAction::Failure:
assert(TheModuleLoader.HadFatalFailure &&
"This should be an early exit only to a fatal error");
TheModuleLoader.HadFatalFailure = true;
IncludeTok.setKind(tok::eof);
CurLexer->cutOffLexing();
return;
}
}
Optional<FileEntryRef> Preprocessor::LookupHeaderIncludeOrImport(
ConstSearchDirIterator *CurDir, StringRef &Filename,
SourceLocation FilenameLoc, CharSourceRange FilenameRange,
const Token &FilenameTok, bool &IsFrameworkFound, bool IsImportDecl,
bool &IsMapped, ConstSearchDirIterator LookupFrom,
const FileEntry *LookupFromFile, StringRef &LookupFilename,
SmallVectorImpl<char> &RelativePath, SmallVectorImpl<char> &SearchPath,
ModuleMap::KnownHeader &SuggestedModule, bool isAngled) {
Optional<FileEntryRef> File = LookupFile(
FilenameLoc, LookupFilename,
isAngled, LookupFrom, LookupFromFile, CurDir,
Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
&SuggestedModule, &IsMapped, &IsFrameworkFound);
if (File)
return File;
if (SuppressIncludeNotFoundError)
return None;
if (isAngled) {
Optional<FileEntryRef> File = LookupFile(
FilenameLoc, LookupFilename,
false, LookupFrom, LookupFromFile, CurDir,
Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
&SuggestedModule, &IsMapped,
nullptr);
if (File) {
Diag(FilenameTok, diag::err_pp_file_not_found_angled_include_not_fatal)
<< Filename << IsImportDecl
<< FixItHint::CreateReplacement(FilenameRange,
"\"" + Filename.str() + "\"");
return File;
}
}
StringRef OriginalFilename = Filename;
if (LangOpts.SpellChecking) {
auto CorrectTypoFilename = [](llvm::StringRef Filename) {
Filename = Filename.drop_until(isAlphanumeric);
while (!Filename.empty() && !isAlphanumeric(Filename.back())) {
Filename = Filename.drop_back();
}
return Filename;
};
StringRef TypoCorrectionName = CorrectTypoFilename(Filename);
StringRef TypoCorrectionLookupName = CorrectTypoFilename(LookupFilename);
Optional<FileEntryRef> File = LookupFile(
FilenameLoc, TypoCorrectionLookupName, isAngled, LookupFrom, LookupFromFile,
CurDir, Callbacks ? &SearchPath : nullptr,
Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped,
nullptr);
if (File) {
auto Hint =
isAngled ? FixItHint::CreateReplacement(
FilenameRange, "<" + TypoCorrectionName.str() + ">")
: FixItHint::CreateReplacement(
FilenameRange, "\"" + TypoCorrectionName.str() + "\"");
Diag(FilenameTok, diag::err_pp_file_not_found_typo_not_fatal)
<< OriginalFilename << TypoCorrectionName << Hint;
Filename = TypoCorrectionName;
LookupFilename = TypoCorrectionLookupName;
return File;
}
}
assert(!File && "expected missing file");
Diag(FilenameTok, diag::err_pp_file_not_found)
<< OriginalFilename << FilenameRange;
if (IsFrameworkFound) {
size_t SlashPos = OriginalFilename.find('/');
assert(SlashPos != StringRef::npos &&
"Include with framework name should have '/' in the filename");
StringRef FrameworkName = OriginalFilename.substr(0, SlashPos);
FrameworkCacheEntry &CacheEntry =
HeaderInfo.LookupFrameworkCache(FrameworkName);
assert(CacheEntry.Directory && "Found framework should be in cache");
Diag(FilenameTok, diag::note_pp_framework_without_header)
<< OriginalFilename.substr(SlashPos + 1) << FrameworkName
<< CacheEntry.Directory->getName();
}
return None;
}
Preprocessor::ImportAction Preprocessor::HandleHeaderIncludeOrImport(
SourceLocation HashLoc, Token &IncludeTok, Token &FilenameTok,
SourceLocation EndLoc, ConstSearchDirIterator LookupFrom,
const FileEntry *LookupFromFile) {
SmallString<128> FilenameBuffer;
StringRef Filename = getSpelling(FilenameTok, FilenameBuffer);
SourceLocation CharEnd = FilenameTok.getEndLoc();
CharSourceRange FilenameRange
= CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
StringRef OriginalFilename = Filename;
bool isAngled =
GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
if (Filename.empty())
return {ImportAction::None};
bool IsImportDecl = HashLoc.isInvalid();
SourceLocation StartLoc = IsImportDecl ? IncludeTok.getLocation() : HashLoc;
if (PragmaARCCFCodeAuditedInfo.second.isValid()) {
Diag(StartLoc, diag::err_pp_include_in_arc_cf_code_audited) << IsImportDecl;
Diag(PragmaARCCFCodeAuditedInfo.second, diag::note_pragma_entered_here);
PragmaARCCFCodeAuditedInfo = {nullptr, SourceLocation()};
}
if (PragmaAssumeNonNullLoc.isValid()) {
Diag(StartLoc, diag::err_pp_include_in_assume_nonnull) << IsImportDecl;
Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here);
PragmaAssumeNonNullLoc = SourceLocation();
}
if (HeaderInfo.HasIncludeAliasMap()) {
StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
if (!NewName.empty())
Filename = NewName;
}
bool IsMapped = false;
bool IsFrameworkFound = false;
ConstSearchDirIterator CurDir = nullptr;
SmallString<1024> SearchPath;
SmallString<1024> RelativePath;
ModuleMap::KnownHeader SuggestedModule;
SourceLocation FilenameLoc = FilenameTok.getLocation();
StringRef LookupFilename = Filename;
SmallString<128> NormalizedPath;
llvm::sys::path::Style BackslashStyle = llvm::sys::path::Style::native;
if (is_style_posix(BackslashStyle) && LangOpts.MicrosoftExt) {
NormalizedPath = Filename.str();
llvm::sys::path::native(NormalizedPath);
LookupFilename = NormalizedPath;
BackslashStyle = llvm::sys::path::Style::windows;
}
Optional<FileEntryRef> File = LookupHeaderIncludeOrImport(
&CurDir, Filename, FilenameLoc, FilenameRange, FilenameTok,
IsFrameworkFound, IsImportDecl, IsMapped, LookupFrom, LookupFromFile,
LookupFilename, RelativePath, SearchPath, SuggestedModule, isAngled);
if (usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) {
if (File && isPCHThroughHeader(&File->getFileEntry()))
SkippingUntilPCHThroughHeader = false;
return {ImportAction::None};
}
enum { Enter, Import, Skip, IncludeLimitReached } Action = Enter;
if (PPOpts->SingleFileParseMode)
Action = IncludeLimitReached;
if (Action == Enter && HasReachedMaxIncludeDepth && File &&
alreadyIncluded(*File))
Action = IncludeLimitReached;
bool MaybeTranslateInclude = Action == Enter && File && SuggestedModule &&
!isForModuleBuilding(SuggestedModule.getModule(),
getLangOpts().CurrentModule,
getLangOpts().ModuleName);
Module *SM = SuggestedModule.getModule();
bool UsableHeaderUnit = false;
if (getLangOpts().CPlusPlusModules && SM && SM->isHeaderUnit()) {
if (TrackGMFState.inGMF() || IsImportDecl)
UsableHeaderUnit = true;
else if (!IsImportDecl) {
SuggestedModule = ModuleMap::KnownHeader();
SM = nullptr;
}
}
bool UsableHeaderModule =
(getLangOpts().CPlusPlusModules || getLangOpts().Modules) && SM &&
!SM->isHeaderUnit();
if (MaybeTranslateInclude && (UsableHeaderUnit || UsableHeaderModule)) {
if (checkModuleIsAvailable(getLangOpts(), getTargetInfo(), getDiagnostics(),
SuggestedModule.getModule())) {
Diag(FilenameTok.getLocation(),
diag::note_implicit_top_level_module_import_here)
<< SuggestedModule.getModule()->getTopLevelModuleName();
return {ImportAction::None};
}
SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
for (Module *Mod = SM; Mod; Mod = Mod->Parent)
Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
FilenameTok.getLocation()));
std::reverse(Path.begin(), Path.end());
if (!IsImportDecl)
diagnoseAutoModuleImport(*this, StartLoc, IncludeTok, Path, CharEnd);
ModuleLoadResult Imported = TheModuleLoader.loadModule(
IncludeTok.getLocation(), Path, Module::Hidden,
true);
assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
"the imported module is different than the suggested one");
if (Imported) {
Action = Import;
} else if (Imported.isMissingExpected()) {
SuggestedModule = ModuleMap::KnownHeader();
} else if (Imported.isConfigMismatch()) {
} else {
if (hadModuleLoaderFatalFailure()) {
Token &Result = IncludeTok;
assert(CurLexer && "#include but no current lexer set!");
Result.startToken();
CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
CurLexer->cutOffLexing();
}
return {ImportAction::None};
}
}
SrcMgr::CharacteristicKind FileCharacter =
SourceMgr.getFileCharacteristic(FilenameTok.getLocation());
if (File)
FileCharacter = std::max(HeaderInfo.getFileDirFlavor(&File->getFileEntry()),
FileCharacter);
bool EnterOnce =
IsImportDecl ||
IncludeTok.getIdentifierInfo()->getPPKeywordID() == tok::pp_import;
bool IsFirstIncludeOfFile = false;
if (Action == Enter && File &&
!HeaderInfo.ShouldEnterIncludeFile(*this, &File->getFileEntry(),
EnterOnce, getLangOpts().Modules, SM,
IsFirstIncludeOfFile)) {
if (UsableHeaderUnit && !getLangOpts().CompilingPCH)
Action = TrackGMFState.inGMF() ? Import : Skip;
else
Action = (SuggestedModule && !getLangOpts().CompilingPCH) ? Import : Skip;
}
if (Action == Enter && File && PreambleConditionalStack.isRecording() &&
SourceMgr.isMainFile(File->getFileEntry())) {
Diag(FilenameTok.getLocation(),
diag::err_pp_including_mainfile_in_preamble);
return {ImportAction::None};
}
if (Callbacks && !IsImportDecl) {
Callbacks->InclusionDirective(HashLoc, IncludeTok, LookupFilename, isAngled,
FilenameRange, File, SearchPath, RelativePath,
Action == Import ? SuggestedModule.getModule()
: nullptr,
FileCharacter);
if (Action == Skip && File)
Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
}
if (!File)
return {ImportAction::None};
if (IsImportDecl && !SuggestedModule) {
Diag(FilenameTok, diag::err_header_import_not_header_unit)
<< OriginalFilename << File->getName();
return {ImportAction::None};
}
const bool CheckIncludePathPortability =
!IsMapped && !File->getFileEntry().tryGetRealPathName().empty();
if (CheckIncludePathPortability) {
StringRef Name = LookupFilename;
StringRef NameWithoriginalSlashes = Filename;
#if defined(_WIN32)
bool NameWasUNC = Name.consume_front("\\\\?\\");
NameWithoriginalSlashes.consume_front("\\\\?\\");
#endif
StringRef RealPathName = File->getFileEntry().tryGetRealPathName();
SmallVector<StringRef, 16> Components(llvm::sys::path::begin(Name),
llvm::sys::path::end(Name));
#if defined(_WIN32)
SmallString<128> FixedDriveRealPath;
if (llvm::sys::path::is_absolute(Name) &&
llvm::sys::path::is_absolute(RealPathName) &&
toLowercase(Name[0]) == toLowercase(RealPathName[0]) &&
isLowercase(Name[0]) != isLowercase(RealPathName[0])) {
assert(Components.size() >= 3 && "should have drive, backslash, name");
assert(Components[0].size() == 2 && "should start with drive");
assert(Components[0][1] == ':' && "should have colon");
FixedDriveRealPath = (Name.substr(0, 1) + RealPathName.substr(1)).str();
RealPathName = FixedDriveRealPath;
}
#endif
if (trySimplifyPath(Components, RealPathName)) {
SmallString<128> Path;
Path.reserve(Name.size()+2);
Path.push_back(isAngled ? '<' : '"');
const auto IsSep = [BackslashStyle](char c) {
return llvm::sys::path::is_separator(c, BackslashStyle);
};
for (auto Component : Components) {
if (!(Component.size() == 1 && IsSep(Component[0])))
Path.append(Component);
else if (!Path.empty())
continue;
if (Path.size() > NameWithoriginalSlashes.size()) {
Path.push_back(isAngled ? '>' : '"');
continue;
}
assert(IsSep(NameWithoriginalSlashes[Path.size()-1]));
do
Path.push_back(NameWithoriginalSlashes[Path.size()-1]);
while (Path.size() <= NameWithoriginalSlashes.size() &&
IsSep(NameWithoriginalSlashes[Path.size()-1]));
}
#if defined(_WIN32)
if (NameWasUNC)
Path = (Path.substr(0, 1) + "\\\\?\\" + Path.substr(1)).str();
#endif
auto DiagId =
(FileCharacter == SrcMgr::C_User || warnByDefaultOnWrongCase(Name))
? diag::pp_nonportable_path
: diag::pp_nonportable_system_path;
Diag(FilenameTok, DiagId) << Path <<
FixItHint::CreateReplacement(FilenameRange, Path);
}
}
switch (Action) {
case Skip:
if (SM)
return {ImportAction::SkippedModuleImport, SM};
return {ImportAction::None};
case IncludeLimitReached:
return {ImportAction::None};
case Import: {
assert(SM && "no module to import");
makeModuleVisible(SM, EndLoc);
if (IncludeTok.getIdentifierInfo()->getPPKeywordID() ==
tok::pp___include_macros)
return {ImportAction::None};
return {ImportAction::ModuleImport, SM};
}
case Enter:
break;
}
if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
Diag(FilenameTok, diag::err_pp_include_too_deep);
HasReachedMaxIncludeDepth = true;
return {ImportAction::None};
}
SourceLocation IncludePos = FilenameTok.getLocation();
if (IncludePos.isMacroID())
IncludePos = SourceMgr.getExpansionRange(IncludePos).getEnd();
FileID FID = SourceMgr.createFileID(*File, IncludePos, FileCharacter);
if (!FID.isValid()) {
TheModuleLoader.HadFatalFailure = true;
return ImportAction::Failure;
}
if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation(),
IsFirstIncludeOfFile))
return {ImportAction::None};
if (SM && !SM->isHeaderUnit()) {
if (SM->getTopLevelModule()->ShadowingModule) {
Diag(SM->DefinitionLoc, diag::err_module_build_shadowed_submodule)
<< SM->getFullModuleName();
Diag(SM->getTopLevelModule()->ShadowingModule->DefinitionLoc,
diag::note_previous_definition);
return {ImportAction::None};
}
if (getLangOpts().CompilingPCH &&
isForModuleBuilding(SM, getLangOpts().CurrentModule,
getLangOpts().ModuleName))
return {ImportAction::None};
assert(!CurLexerSubmodule && "should not have marked this as a module yet");
CurLexerSubmodule = SM;
EnterSubmodule(SM, EndLoc, false);
return {ImportAction::ModuleBegin, SM};
}
assert(!IsImportDecl && "failed to diagnose missing module for import decl");
return {ImportAction::None};
}
void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
Token &IncludeNextTok) {
Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
ConstSearchDirIterator Lookup = nullptr;
const FileEntry *LookupFromFile;
std::tie(Lookup, LookupFromFile) = getIncludeNextStart(IncludeNextTok);
return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
LookupFromFile);
}
void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
Diag(Tok, diag::err_pp_import_directive_ms );
DiscardUntilEndOfDirective();
}
void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
Token &ImportTok) {
if (!LangOpts.ObjC) { if (LangOpts.MSVCCompat)
return HandleMicrosoftImportDirective(ImportTok);
Diag(ImportTok, diag::ext_pp_import_directive);
}
return HandleIncludeDirective(HashLoc, ImportTok);
}
void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
Token &IncludeMacrosTok) {
SourceLocation Loc = IncludeMacrosTok.getLocation();
if (SourceMgr.getBufferName(Loc) != "<built-in>") {
Diag(IncludeMacrosTok.getLocation(),
diag::pp_include_macros_out_of_predefines);
DiscardUntilEndOfDirective();
return;
}
HandleIncludeDirective(HashLoc, IncludeMacrosTok);
Token TmpTok;
do {
Lex(TmpTok);
assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
} while (TmpTok.isNot(tok::hashhash));
}
bool Preprocessor::ReadMacroParameterList(MacroInfo *MI, Token &Tok) {
SmallVector<IdentifierInfo*, 32> Parameters;
while (true) {
LexUnexpandedToken(Tok);
switch (Tok.getKind()) {
case tok::r_paren:
if (Parameters.empty()) return false;
Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
return true;
case tok::ellipsis: if (!LangOpts.C99)
Diag(Tok, LangOpts.CPlusPlus11 ?
diag::warn_cxx98_compat_variadic_macro :
diag::ext_variadic_macro);
if (LangOpts.OpenCL && !LangOpts.OpenCLCPlusPlus) {
Diag(Tok, diag::ext_pp_opencl_variadic_macros);
}
LexUnexpandedToken(Tok);
if (Tok.isNot(tok::r_paren)) {
Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
return true;
}
Parameters.push_back(Ident__VA_ARGS__);
MI->setIsC99Varargs();
MI->setParameterList(Parameters, BP);
return false;
case tok::eod: Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
return true;
default:
IdentifierInfo *II = Tok.getIdentifierInfo();
if (!II) {
Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
return true;
}
if (llvm::is_contained(Parameters, II)) { Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
return true;
}
Parameters.push_back(II);
LexUnexpandedToken(Tok);
switch (Tok.getKind()) {
default: Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
return true;
case tok::r_paren: MI->setParameterList(Parameters, BP);
return false;
case tok::comma: break;
case tok::ellipsis: Diag(Tok, diag::ext_named_variadic_macro);
LexUnexpandedToken(Tok);
if (Tok.isNot(tok::r_paren)) {
Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
return true;
}
MI->setIsGNUVarargs();
MI->setParameterList(Parameters, BP);
return false;
}
}
}
}
static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
const LangOptions &LOptions) {
if (MI->getNumTokens() == 1) {
const Token &Value = MI->getReplacementToken(0);
if (MacroName.getKind() == Value.getKind())
return true;
StringRef MacroText = MacroName.getIdentifierInfo()->getName();
if (IdentifierInfo *II = Value.getIdentifierInfo()) {
if (!II->isKeyword(LOptions))
return false;
StringRef ValueText = II->getName();
StringRef TrimmedValue = ValueText;
if (!ValueText.startswith("__")) {
if (ValueText.startswith("_"))
TrimmedValue = TrimmedValue.drop_front(1);
else
return false;
} else {
TrimmedValue = TrimmedValue.drop_front(2);
if (TrimmedValue.endswith("__"))
TrimmedValue = TrimmedValue.drop_back(2);
}
return TrimmedValue.equals(MacroText);
} else {
return false;
}
}
return MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static,
tok::kw_const) &&
MI->getNumTokens() == 0;
}
MacroInfo *Preprocessor::ReadOptionalMacroParameterListAndBody(
const Token &MacroNameTok, const bool ImmediatelyAfterHeaderGuard) {
Token LastTok = MacroNameTok;
MacroInfo *const MI = AllocateMacroInfo(MacroNameTok.getLocation());
Token Tok;
LexUnexpandedToken(Tok);
auto _ = llvm::make_scope_exit([&]() {
if (CurLexer->ParsingPreprocessorDirective)
DiscardUntilEndOfDirective();
});
VariadicMacroScopeGuard VariadicMacroScopeGuard(*this);
if (Tok.is(tok::eod)) {
if (ImmediatelyAfterHeaderGuard) {
CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
MacroNameTok.getLocation());
}
} else if (Tok.hasLeadingSpace()) {
Tok.clearFlag(Token::LeadingSpace);
} else if (Tok.is(tok::l_paren)) {
MI->setIsFunctionLike();
if (ReadMacroParameterList(MI, LastTok))
return nullptr;
if (MI->isC99Varargs()) {
VariadicMacroScopeGuard.enterScope();
}
LexUnexpandedToken(Tok);
} else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
} else {
bool isInvalid = false;
if (Tok.is(tok::at)) isInvalid = true;
else if (Tok.is(tok::unknown)) {
isInvalid = true;
}
if (isInvalid)
Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
else
Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
}
if (!Tok.is(tok::eod))
LastTok = Tok;
SmallVector<Token, 16> Tokens;
if (MI->isObjectLike()) {
while (Tok.isNot(tok::eod)) {
LastTok = Tok;
Tokens.push_back(Tok);
LexUnexpandedToken(Tok);
}
} else {
VAOptDefinitionContext VAOCtx(*this);
while (Tok.isNot(tok::eod)) {
LastTok = Tok;
if (!Tok.isOneOf(tok::hash, tok::hashat, tok::hashhash)) {
Tokens.push_back(Tok);
if (VAOCtx.isVAOptToken(Tok)) {
if (VAOCtx.isInVAOpt()) {
Diag(Tok, diag::err_pp_vaopt_nested_use);
return nullptr;
}
LexUnexpandedToken(Tok);
if (Tok.isNot(tok::l_paren)) {
Diag(Tok, diag::err_pp_missing_lparen_in_vaopt_use);
return nullptr;
}
Tokens.push_back(Tok);
VAOCtx.sawVAOptFollowedByOpeningParens(Tok.getLocation());
LexUnexpandedToken(Tok);
if (Tok.is(tok::hashhash)) {
Diag(Tok, diag::err_vaopt_paste_at_start);
return nullptr;
}
continue;
} else if (VAOCtx.isInVAOpt()) {
if (Tok.is(tok::r_paren)) {
if (VAOCtx.sawClosingParen()) {
assert(Tokens.size() >= 3 &&
"Must have seen at least __VA_OPT__( "
"and a subsequent tok::r_paren");
if (Tokens[Tokens.size() - 2].is(tok::hashhash)) {
Diag(Tok, diag::err_vaopt_paste_at_end);
return nullptr;
}
}
} else if (Tok.is(tok::l_paren)) {
VAOCtx.sawOpeningParen(Tok.getLocation());
}
}
LexUnexpandedToken(Tok);
continue;
}
if (getLangOpts().TraditionalCPP) {
Tok.setKind(tok::unknown);
Tokens.push_back(Tok);
LexUnexpandedToken(Tok);
continue;
}
if (Tok.is(tok::hashhash)) {
LexUnexpandedToken(Tok);
if (Tok.is(tok::eod)) {
Tokens.push_back(LastTok);
break;
}
if (!Tokens.empty() && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
Tokens[Tokens.size() - 1].is(tok::comma))
MI->setHasCommaPasting();
Tokens.push_back(LastTok);
continue;
}
LexUnexpandedToken(Tok);
if (!VAOCtx.isVAOptToken(Tok) &&
(Tok.getIdentifierInfo() == nullptr ||
MI->getParameterNum(Tok.getIdentifierInfo()) == -1)) {
if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
LastTok.setKind(tok::unknown);
Tokens.push_back(LastTok);
continue;
} else {
Diag(Tok, diag::err_pp_stringize_not_parameter)
<< LastTok.is(tok::hashat);
return nullptr;
}
}
Tokens.push_back(LastTok);
if (!VAOCtx.isVAOptToken(Tok)) {
Tokens.push_back(Tok);
LastTok = Tok;
LexUnexpandedToken(Tok);
}
}
if (VAOCtx.isInVAOpt()) {
assert(Tok.is(tok::eod) && "Must be at End Of preprocessing Directive");
Diag(Tok, diag::err_pp_expected_after)
<< LastTok.getKind() << tok::r_paren;
Diag(VAOCtx.getUnmatchedOpeningParenLoc(), diag::note_matching) << tok::l_paren;
return nullptr;
}
}
MI->setDefinitionEndLoc(LastTok.getLocation());
MI->setTokens(Tokens, BP);
return MI;
}
void Preprocessor::HandleDefineDirective(
Token &DefineTok, const bool ImmediatelyAfterHeaderGuard) {
++NumDefined;
Token MacroNameTok;
bool MacroShadowsKeyword;
ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
if (MacroNameTok.is(tok::eod))
return;
IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
if (!II->hasMacroDefinition() && II->hadMacroDefinition() && II->isFinal())
emitFinalMacroWarning(MacroNameTok, false);
if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
MacroInfo *const MI = ReadOptionalMacroParameterListAndBody(
MacroNameTok, ImmediatelyAfterHeaderGuard);
if (!MI) return;
if (MacroShadowsKeyword &&
!isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
}
unsigned NumTokens = MI->getNumTokens();
if (NumTokens != 0) {
if (MI->getReplacementToken(0).is(tok::hashhash)) {
Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
return;
}
if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
return;
}
}
if (SkippingUntilPCHThroughHeader) {
const MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo());
if (!OtherMI || !MI->isIdenticalTo(*OtherMI, *this,
LangOpts.MicrosoftExt))
Diag(MI->getDefinitionLoc(), diag::warn_pp_macro_def_mismatch_with_pch)
<< MacroNameTok.getIdentifierInfo();
if (!LangOpts.MicrosoftExt)
return;
}
if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
if (MacroNameTok.getIdentifierInfo()->isFinal())
emitFinalMacroWarning(MacroNameTok, false);
auto isObjCProtectedMacro = [](const IdentifierInfo *II) -> bool {
return II->isStr("__strong") ||
II->isStr("__weak") ||
II->isStr("__unsafe_unretained") ||
II->isStr("__autoreleasing");
};
if (getLangOpts().ObjC &&
SourceMgr.getFileID(OtherMI->getDefinitionLoc())
== getPredefinesFileID() &&
isObjCProtectedMacro(MacroNameTok.getIdentifierInfo())) {
if ((!getDiagnostics().getSuppressSystemWarnings() ||
!SourceMgr.isInSystemHeader(DefineTok.getLocation())) &&
!MI->isIdenticalTo(*OtherMI, *this,
LangOpts.MicrosoftExt)) {
Diag(MI->getDefinitionLoc(), diag::warn_pp_objc_macro_redef_ignored);
}
assert(!OtherMI->isWarnIfUnused());
return;
}
if (!getDiagnostics().getSuppressSystemWarnings() ||
!SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
if (OtherMI->isBuiltinMacro())
Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
!MI->isIdenticalTo(*OtherMI, *this, LangOpts.MicrosoftExt)) {
Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
<< MacroNameTok.getIdentifierInfo();
Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
}
}
if (OtherMI->isWarnIfUnused())
WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
}
DefMacroDirective *MD =
appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
assert(!MI->isUsed());
if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
!Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc()) &&
!MacroExpansionInDirectivesOverride &&
getSourceManager().getFileID(MI->getDefinitionLoc()) !=
getPredefinesFileID()) {
MI->setIsWarnIfUnused(true);
WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
}
if (Callbacks)
Callbacks->MacroDefined(MacroNameTok, MD);
if (!getLangOpts().CPlusPlus && getLangOpts().MSVCCompat &&
MacroNameTok.getIdentifierInfo()->isStr("assert") &&
!isMacroDefined("static_assert")) {
MacroInfo *MI = AllocateMacroInfo(SourceLocation());
Token Tok;
Tok.startToken();
Tok.setKind(tok::kw__Static_assert);
Tok.setIdentifierInfo(getIdentifierInfo("_Static_assert"));
MI->setTokens({Tok}, BP);
(void)appendDefMacroDirective(getIdentifierInfo("static_assert"), MI);
}
}
void Preprocessor::HandleUndefDirective() {
++NumUndefined;
Token MacroNameTok;
ReadMacroName(MacroNameTok, MU_Undef);
if (MacroNameTok.is(tok::eod))
return;
CheckEndOfDirective("undef");
auto *II = MacroNameTok.getIdentifierInfo();
auto MD = getMacroDefinition(II);
UndefMacroDirective *Undef = nullptr;
if (II->isFinal())
emitFinalMacroWarning(MacroNameTok, true);
if (const MacroInfo *MI = MD.getMacroInfo()) {
if (!MI->isUsed() && MI->isWarnIfUnused())
Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
if (MI->isWarnIfUnused())
WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
Undef = AllocateUndefMacroDirective(MacroNameTok.getLocation());
}
if (Callbacks)
Callbacks->MacroUndefined(MacroNameTok, MD, Undef);
if (Undef)
appendMacroDirective(II, Undef);
}
void Preprocessor::HandleIfdefDirective(Token &Result,
const Token &HashToken,
bool isIfndef,
bool ReadAnyTokensBeforeDirective) {
++NumIf;
Token DirectiveTok = Result;
Token MacroNameTok;
ReadMacroName(MacroNameTok);
if (MacroNameTok.is(tok::eod)) {
SkipExcludedConditionalBlock(HashToken.getLocation(),
DirectiveTok.getLocation(),
false, false);
return;
}
emitMacroExpansionWarnings(MacroNameTok);
CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
auto MD = getMacroDefinition(MII);
MacroInfo *MI = MD.getMacroInfo();
if (CurPPLexer->getConditionalStackDepth() == 0) {
if (!ReadAnyTokensBeforeDirective && !MI) {
assert(isIfndef && "#ifdef shouldn't reach here");
CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
} else
CurPPLexer->MIOpt.EnterTopLevelConditional();
}
if (MI) markMacroAsUsed(MI);
if (Callbacks) {
if (isIfndef)
Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
else
Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
}
bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
getSourceManager().isInMainFile(DirectiveTok.getLocation());
if (PPOpts->SingleFileParseMode && !MI) {
CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
false, false,
false);
} else if (!MI == isIfndef || RetainExcludedCB) {
CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
false, true,
false);
} else {
SkipExcludedConditionalBlock(HashToken.getLocation(),
DirectiveTok.getLocation(),
false,
false);
}
}
void Preprocessor::HandleIfDirective(Token &IfToken,
const Token &HashToken,
bool ReadAnyTokensBeforeDirective) {
++NumIf;
IdentifierInfo *IfNDefMacro = nullptr;
const DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
const bool ConditionalTrue = DER.Conditional;
if (!CurPPLexer)
return;
if (CurPPLexer->getConditionalStackDepth() == 0) {
if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
else
CurPPLexer->MIOpt.EnterTopLevelConditional();
}
if (Callbacks)
Callbacks->If(
IfToken.getLocation(), DER.ExprRange,
(ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
getSourceManager().isInMainFile(IfToken.getLocation());
if (PPOpts->SingleFileParseMode && DER.IncludedUndefinedIds) {
CurPPLexer->pushConditionalLevel(IfToken.getLocation(), false,
false, false);
} else if (ConditionalTrue || RetainExcludedCB) {
CurPPLexer->pushConditionalLevel(IfToken.getLocation(), false,
true, false);
} else {
SkipExcludedConditionalBlock(HashToken.getLocation(), IfToken.getLocation(),
false,
false);
}
}
void Preprocessor::HandleEndifDirective(Token &EndifToken) {
++NumEndif;
CheckEndOfDirective("endif");
PPConditionalInfo CondInfo;
if (CurPPLexer->popConditionalLevel(CondInfo)) {
Diag(EndifToken, diag::err_pp_endif_without_if);
return;
}
if (CurPPLexer->getConditionalStackDepth() == 0)
CurPPLexer->MIOpt.ExitTopLevelConditional();
assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
"This code should only be reachable in the non-skipping case!");
if (Callbacks)
Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
}
void Preprocessor::HandleElseDirective(Token &Result, const Token &HashToken) {
++NumElse;
CheckEndOfDirective("else");
PPConditionalInfo CI;
if (CurPPLexer->popConditionalLevel(CI)) {
Diag(Result, diag::pp_err_else_without_if);
return;
}
if (CurPPLexer->getConditionalStackDepth() == 0)
CurPPLexer->MIOpt.EnterTopLevelConditional();
if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
if (Callbacks)
Callbacks->Else(Result.getLocation(), CI.IfLoc);
bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
getSourceManager().isInMainFile(Result.getLocation());
if ((PPOpts->SingleFileParseMode && !CI.FoundNonSkip) || RetainExcludedCB) {
CurPPLexer->pushConditionalLevel(CI.IfLoc, false,
false, true);
return;
}
SkipExcludedConditionalBlock(HashToken.getLocation(), CI.IfLoc,
true,
true, Result.getLocation());
}
void Preprocessor::HandleElifFamilyDirective(Token &ElifToken,
const Token &HashToken,
tok::PPKeywordKind Kind) {
PPElifDiag DirKind = Kind == tok::pp_elif ? PED_Elif
: Kind == tok::pp_elifdef ? PED_Elifdef
: PED_Elifndef;
++NumElse;
switch (DirKind) {
case PED_Elifdef:
case PED_Elifndef:
unsigned DiagID;
if (LangOpts.CPlusPlus)
DiagID = LangOpts.CPlusPlus2b ? diag::warn_cxx2b_compat_pp_directive
: diag::ext_cxx2b_pp_directive;
else
DiagID = LangOpts.C2x ? diag::warn_c2x_compat_pp_directive
: diag::ext_c2x_pp_directive;
Diag(ElifToken, DiagID) << DirKind;
break;
default:
break;
}
SourceRange ConditionRange = DiscardUntilEndOfDirective();
PPConditionalInfo CI;
if (CurPPLexer->popConditionalLevel(CI)) {
Diag(ElifToken, diag::pp_err_elif_without_if) << DirKind;
return;
}
if (CurPPLexer->getConditionalStackDepth() == 0)
CurPPLexer->MIOpt.EnterTopLevelConditional();
if (CI.FoundElse)
Diag(ElifToken, diag::pp_err_elif_after_else) << DirKind;
if (Callbacks) {
switch (Kind) {
case tok::pp_elif:
Callbacks->Elif(ElifToken.getLocation(), ConditionRange,
PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
break;
case tok::pp_elifdef:
Callbacks->Elifdef(ElifToken.getLocation(), ConditionRange, CI.IfLoc);
break;
case tok::pp_elifndef:
Callbacks->Elifndef(ElifToken.getLocation(), ConditionRange, CI.IfLoc);
break;
default:
assert(false && "unexpected directive kind");
break;
}
}
bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
getSourceManager().isInMainFile(ElifToken.getLocation());
if ((PPOpts->SingleFileParseMode && !CI.FoundNonSkip) || RetainExcludedCB) {
CurPPLexer->pushConditionalLevel(ElifToken.getLocation(), false,
false, false);
return;
}
SkipExcludedConditionalBlock(
HashToken.getLocation(), CI.IfLoc, true,
CI.FoundElse, ElifToken.getLocation());
}