#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/LiteralSupport.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/MacroInfo.h"
#include "clang/Lex/LexDiagnostic.h"
#include "clang/Lex/CodeCompletionHandler.h"
#include "clang/Lex/ModuleLoader.h"
#include "clang/Lex/Pragma.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/ADT/APInt.h"
#include "llvm/Support/ErrorHandling.h"
using namespace clang;
MacroInfo *Preprocessor::AllocateMacroInfo() {
MacroInfoChain *MIChain;
if (MICache) {
MIChain = MICache;
MICache = MICache->Next;
}
else {
MIChain = BP.Allocate<MacroInfoChain>();
}
MIChain->Next = MIChainHead;
MIChain->Prev = 0;
if (MIChainHead)
MIChainHead->Prev = MIChain;
MIChainHead = MIChain;
return &(MIChain->MI);
}
MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
MacroInfo *MI = AllocateMacroInfo();
new (MI) MacroInfo(L);
return MI;
}
MacroInfo *Preprocessor::CloneMacroInfo(const MacroInfo &MacroToClone) {
MacroInfo *MI = AllocateMacroInfo();
new (MI) MacroInfo(MacroToClone, BP);
return MI;
}
void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
MacroInfoChain *MIChain = (MacroInfoChain*) MI;
if (MacroInfoChain *Prev = MIChain->Prev) {
MacroInfoChain *Next = MIChain->Next;
Prev->Next = Next;
if (Next)
Next->Prev = Prev;
}
else {
assert(MIChainHead == MIChain);
MIChainHead = MIChain->Next;
MIChainHead->Prev = 0;
}
MIChain->Next = MICache;
MICache = MIChain;
MI->Destroy();
}
void Preprocessor::DiscardUntilEndOfDirective() {
Token Tmp;
do {
LexUnexpandedToken(Tmp);
assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
} while (Tmp.isNot(tok::eod));
}
void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
LexUnexpandedToken(MacroNameTok);
if (MacroNameTok.is(tok::code_completion)) {
if (CodeComplete)
CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
setCodeCompletionReached();
LexUnexpandedToken(MacroNameTok);
}
if (MacroNameTok.is(tok::eod)) {
Diag(MacroNameTok, diag::err_pp_missing_macro_name);
return;
}
IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
if (II == 0) {
bool Invalid = false;
std::string Spelling = getSpelling(MacroNameTok, &Invalid);
if (Invalid)
return;
const IdentifierInfo &Info = Identifiers.get(Spelling);
if (Info.isCPlusPlusOperatorKeyword() && getLangOpts().MicrosoftMode) {
MacroNameTok.setIdentifierInfo(getIdentifierInfo(Spelling));
return;
}
if (Info.isCPlusPlusOperatorKeyword())
Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
else
Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
} else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
Diag(MacroNameTok, diag::err_defined_macro_name);
} else if (isDefineUndef && II->hasMacroDefinition() &&
getMacroInfo(II)->isBuiltinMacro()) {
if (isDefineUndef == 1)
Diag(MacroNameTok, diag::pp_redef_builtin_macro);
else
Diag(MacroNameTok, diag::pp_undef_builtin_macro);
} else {
return;
}
MacroNameTok.setKind(tok::eod);
return DiscardUntilEndOfDirective();
}
void 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.isNot(tok::eod)) {
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;
DiscardUntilEndOfDirective();
}
}
void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
bool FoundNonSkipPortion,
bool FoundElse,
SourceLocation ElseLoc) {
++NumSkipped;
assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
CurPPLexer->pushConditionalLevel(IfTokenLoc, false,
FoundNonSkipPortion, FoundElse);
if (CurPTHLexer) {
PTHSkipExcludedConditionalBlock();
return;
}
CurPPLexer->LexingRawMode = true;
Token Tok;
while (1) {
CurLexer->Lex(Tok);
if (Tok.is(tok::code_completion)) {
if (CodeComplete)
CodeComplete->CodeCompleteInConditionalExclusion();
setCodeCompletionReached();
continue;
}
if (Tok.is(tok::eof)) {
while (!CurPPLexer->ConditionalStack.empty()) {
if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
Diag(CurPPLexer->ConditionalStack.back().IfLoc,
diag::err_pp_unterminated_conditional);
CurPPLexer->ConditionalStack.pop_back();
}
break;
}
if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
continue;
CurPPLexer->ParsingPreprocessorDirective = true;
if (CurLexer) CurLexer->SetCommentRetentionState(false);
LexUnexpandedToken(Tok);
if (Tok.isNot(tok::raw_identifier)) {
CurPPLexer->ParsingPreprocessorDirective = false;
if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
continue;
}
const char *RawCharData = Tok.getRawIdentifierData();
char FirstChar = RawCharData[0];
if (FirstChar >= 'a' && FirstChar <= 'z' &&
FirstChar != 'i' && FirstChar != 'e') {
CurPPLexer->ParsingPreprocessorDirective = false;
if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
continue;
}
char DirectiveBuf[20];
StringRef Directive;
if (!Tok.needsCleaning() && Tok.getLength() < 20) {
Directive = StringRef(RawCharData, Tok.getLength());
} else {
std::string DirectiveStr = getSpelling(Tok);
unsigned IdLen = DirectiveStr.size();
if (IdLen >= 20) {
CurPPLexer->ParsingPreprocessorDirective = false;
if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
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 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) {
CurPPLexer->LexingRawMode = false;
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.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
CondInfo.FoundElse = true;
if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
CondInfo.FoundNonSkip = true;
CurPPLexer->LexingRawMode = false;
CheckEndOfDirective("else");
CurPPLexer->LexingRawMode = true;
if (Callbacks)
Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
break;
} else {
DiscardUntilEndOfDirective(); }
} else if (Sub == "lif") { PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
bool ShouldEnter;
const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
DiscardUntilEndOfDirective();
ShouldEnter = false;
} else {
assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
CurPPLexer->LexingRawMode = false;
IdentifierInfo *IfNDefMacro = 0;
ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
CurPPLexer->LexingRawMode = true;
}
const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
if (ShouldEnter) {
CondInfo.FoundNonSkip = true;
if (Callbacks)
Callbacks->Elif(Tok.getLocation(),
SourceRange(ConditionalBegin, ConditionalEnd),
CondInfo.IfLoc);
break;
}
}
}
CurPPLexer->ParsingPreprocessorDirective = false;
if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
}
CurPPLexer->LexingRawMode = false;
if (Callbacks) {
SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
}
}
void Preprocessor::PTHSkipExcludedConditionalBlock() {
while (1) {
assert(CurPTHLexer);
assert(CurPTHLexer->LexingRawMode == false);
if (CurPTHLexer->SkipBlock()) {
PPConditionalInfo CondInfo;
bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
(void)InCond; assert(!InCond && "Can't be skipping if not in a conditional!");
break;
}
Token Tok;
LexUnexpandedToken(Tok);
tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
if (K == tok::pp_else) {
PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
CondInfo.FoundElse = true;
if (!CondInfo.FoundNonSkip) {
CondInfo.FoundNonSkip = true;
CurPTHLexer->ParsingPreprocessorDirective = true;
DiscardUntilEndOfDirective();
CurPTHLexer->ParsingPreprocessorDirective = false;
break;
}
continue;
}
assert(K == tok::pp_elif);
PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
if (CondInfo.FoundElse)
Diag(Tok, diag::pp_err_elif_after_else);
if (CondInfo.FoundNonSkip)
continue;
IdentifierInfo *IfNDefMacro = 0;
CurPTHLexer->ParsingPreprocessorDirective = true;
bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
CurPTHLexer->ParsingPreprocessorDirective = false;
if (ShouldEnter) {
CondInfo.FoundNonSkip = true;
break;
}
continue;
}
}
const FileEntry *Preprocessor::LookupFile(
StringRef Filename,
bool isAngled,
const DirectoryLookup *FromDir,
const DirectoryLookup *&CurDir,
SmallVectorImpl<char> *SearchPath,
SmallVectorImpl<char> *RelativePath,
Module **SuggestedModule,
bool SkipCache) {
const FileEntry *CurFileEnt = 0;
if (!FromDir) {
FileID FID = getCurrentFileLexer()->getFileID();
CurFileEnt = SourceMgr.getFileEntryForID(FID);
if (CurFileEnt == 0) {
FID = SourceMgr.getMainFileID();
CurFileEnt = SourceMgr.getFileEntryForID(FID);
}
}
CurDir = CurDirLookup;
const FileEntry *FE = HeaderInfo.LookupFile(
Filename, isAngled, FromDir, CurDir, CurFileEnt,
SearchPath, RelativePath, SuggestedModule, SkipCache);
if (FE) return FE;
if (IsFileLexer()) {
if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
SearchPath, RelativePath)))
return FE;
}
for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
if (IsFileLexer(ISEntry)) {
if ((CurFileEnt =
SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
if ((FE = HeaderInfo.LookupSubframeworkHeader(
Filename, CurFileEnt, SearchPath, RelativePath)))
return FE;
}
}
return 0;
}
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::HandleDirective(Token &Result) {
CurPPLexer->ParsingPreprocessorDirective = true;
++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:
Diag(Result, diag::err_embedded_include) << II->getName();
DiscardUntilEndOfDirective();
return;
default:
break;
}
}
Diag(Result, diag::ext_embedded_directive);
}
ResetMacroExpansionHelper helper(this);
TryAgain:
switch (Result.getKind()) {
case tok::eod:
return; case tok::comment:
LexUnexpandedToken(Result);
goto TryAgain;
case tok::code_completion:
if (CodeComplete)
CodeComplete->CodeCompleteDirective(
CurPPLexer->getConditionalStackDepth() > 0);
setCodeCompletionReached();
return;
case tok::numeric_constant: if (getLangOpts().AsmPreprocessor)
break; return HandleDigitDirective(Result);
default:
IdentifierInfo *II = Result.getIdentifierInfo();
if (II == 0) break;
switch (II->getPPKeywordID()) {
default: break;
case tok::pp_if:
return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
case tok::pp_ifdef:
return HandleIfdefDirective(Result, false, true);
case tok::pp_ifndef:
return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
case tok::pp_elif:
return HandleElifDirective(Result);
case tok::pp_else:
return HandleElseDirective(Result);
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);
case tok::pp_undef:
return HandleUndefDirective(Result);
case tok::pp_line:
return HandleLineDirective(Result);
case tok::pp_error:
return HandleUserDiagnosticDirective(Result, false);
case tok::pp_pragma:
return HandlePragmaDirective(PIK_HashPragma);
case tok::pp_import:
return HandleImportDirective(SavedHash.getLocation(), Result);
case tok::pp_include_next:
return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
case tok::pp_warning:
Diag(Result, diag::ext_pp_warning_directive);
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)
return HandleMacroPublicDirective(Result);
break;
case tok::pp___private_macro:
if (getLangOpts().Modules)
return HandleMacroPrivateDirective(Result);
break;
}
break;
}
if (getLangOpts().AsmPreprocessor) {
Token *Toks = new Token[2];
Toks[0] = SavedHash;
Toks[1] = Result;
if (Result.is(tok::hashhash))
Toks[1].setKind(tok::unknown);
EnterTokenStream(Toks, 2, false, true);
return;
}
Diag(Result, diag::err_pp_invalid_directive);
DiscardUntilEndOfDirective();
}
static bool GetLineValue(Token &DigitTok, unsigned &Val,
unsigned DiagID, Preprocessor &PP) {
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 (!isdigit(DigitTokBegin[i])) {
PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
diag::err_pp_line_digit_sequence);
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);
return false;
}
void Preprocessor::HandleLineDirective(Token &Tok) {
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.CPlusPlus0x)
LineLimit = 2147483648U;
if (LineNo >= LineLimit)
Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
else if (LangOpts.CPlusPlus0x && 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);
return DiscardUntilEndOfDirective();
} else if (StrTok.hasUDSuffix()) {
Diag(StrTok, diag::err_invalid_string_udl);
return DiscardUntilEndOfDirective();
} else {
StringLiteralParser Literal(&StrTok, 1, *this);
assert(Literal.isAscii() && "Didn't allow wide strings in");
if (Literal.hadError)
return DiscardUntilEndOfDirective();
if (Literal.Pascal) {
Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
return DiscardUntilEndOfDirective();
}
FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
CheckEndOfDirective("line", true);
}
SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
if (Callbacks)
Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
PPCallbacks::RenameFile,
SrcMgr::C_User);
}
static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
bool &IsSystemHeader, bool &IsExternCHeader,
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;
}
IsSystemHeader = 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 != 4) {
PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
PP.DiscardUntilEndOfDirective();
return true;
}
IsExternCHeader = true;
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))
return;
Token StrTok;
Lex(StrTok);
bool IsFileEntry = false, IsFileExit = false;
bool IsSystemHeader = false, IsExternCHeader = false;
int FilenameID = -1;
if (StrTok.is(tok::eod))
; else if (StrTok.isNot(tok::string_literal)) {
Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
return DiscardUntilEndOfDirective();
} else if (StrTok.hasUDSuffix()) {
Diag(StrTok, diag::err_invalid_string_udl);
return DiscardUntilEndOfDirective();
} else {
StringLiteralParser Literal(&StrTok, 1, *this);
assert(Literal.isAscii() && "Didn't allow wide strings in");
if (Literal.hadError)
return DiscardUntilEndOfDirective();
if (Literal.Pascal) {
Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
return DiscardUntilEndOfDirective();
}
FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
IsSystemHeader, IsExternCHeader, *this))
return;
}
SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
IsFileEntry, IsFileExit,
IsSystemHeader, IsExternCHeader);
if (Callbacks) {
PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
if (IsFileEntry)
Reason = PPCallbacks::EnterFile;
else if (IsFileExit)
Reason = PPCallbacks::ExitFile;
SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
if (IsExternCHeader)
FileKind = SrcMgr::C_ExternCSystem;
else if (IsSystemHeader)
FileKind = SrcMgr::C_System;
Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
}
}
void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
bool isWarning) {
if (CurPTHLexer)
return CurPTHLexer->DiscardToEndOfLine();
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);
return DiscardUntilEndOfDirective();
}
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, 2);
if (MacroNameTok.is(tok::eod))
return;
CheckEndOfDirective("__public_macro");
MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
if (MI == 0) {
Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
<< MacroNameTok.getIdentifierInfo();
return;
}
MI->setVisibility(true, MacroNameTok.getLocation());
if (MI->isFromAST())
MI->setChangedAfterLoad();
}
void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
Token MacroNameTok;
ReadMacroName(MacroNameTok, 2);
if (MacroNameTok.is(tok::eod))
return;
CheckEndOfDirective("__private_macro");
MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
if (MI == 0) {
Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
<< MacroNameTok.getIdentifierInfo();
return;
}
MI->setVisibility(false, MacroNameTok.getLocation());
if (MI->isFromAST())
MI->setChangedAfterLoad();
}
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;
}
bool Preprocessor::ConcatenateIncludeName(
SmallString<128> &FilenameBuffer,
SourceLocation &End) {
Token CurTok;
Lex(CurTok);
while (CurTok.isNot(tok::eod)) {
End = CurTok.getLocation();
if (CurTok.is(tok::code_completion)) {
setCodeCompletionReached();
Lex(CurTok);
continue;
}
if (CurTok.hasLeadingSpace())
FilenameBuffer.push_back(' ');
unsigned PreAppendSize = FilenameBuffer.size();
FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
const char *BufPtr = &FilenameBuffer[PreAppendSize];
unsigned ActualLen = getSpelling(CurTok, BufPtr);
if (BufPtr != &FilenameBuffer[PreAppendSize])
memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
if (CurTok.getLength() != ActualLen)
FilenameBuffer.resize(PreAppendSize+ActualLen);
if (CurTok.is(tok::greater))
return false;
Lex(CurTok);
}
Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
return true;
}
void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
Token &IncludeTok,
const DirectoryLookup *LookupFrom,
bool isImport) {
Token FilenameTok;
CurPPLexer->LexIncludeFilename(FilenameTok);
SmallString<128> FilenameBuffer;
StringRef Filename;
SourceLocation End;
SourceLocation CharEnd;
switch (FilenameTok.getKind()) {
case tok::eod:
return;
case tok::angle_string_literal:
case tok::string_literal:
Filename = getSpelling(FilenameTok, FilenameBuffer);
End = FilenameTok.getLocation();
CharEnd = End.getLocWithOffset(Filename.size());
break;
case tok::less:
FilenameBuffer.push_back('<');
if (ConcatenateIncludeName(FilenameBuffer, End))
return; Filename = FilenameBuffer.str();
CharEnd = getLocForEndOfToken(End);
break;
default:
Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
DiscardUntilEndOfDirective();
return;
}
CharSourceRange FilenameRange
= CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
StringRef OriginalFilename = Filename;
bool isAngled =
GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
if (Filename.empty()) {
DiscardUntilEndOfDirective();
return;
}
CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
Diag(FilenameTok, diag::err_pp_include_too_deep);
return;
}
if (PragmaARCCFCodeAuditedLoc.isValid()) {
Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
PragmaARCCFCodeAuditedLoc = SourceLocation();
}
if (HeaderInfo.HasIncludeAliasMap()) {
StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
if (!NewName.empty())
Filename = NewName;
}
const DirectoryLookup *CurDir;
SmallString<1024> SearchPath;
SmallString<1024> RelativePath;
Module *SuggestedModule = 0;
const FileEntry *File = LookupFile(
Filename, isAngled, LookupFrom, CurDir,
Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
getLangOpts().Modules? &SuggestedModule : 0);
if (Callbacks) {
if (!File) {
SmallString<128> RecoveryPath;
if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
DirectoryLookup DL(DE, SrcMgr::C_User, true, false);
HeaderInfo.AddSearchPath(DL, isAngled);
File = LookupFile(Filename, isAngled, LookupFrom, CurDir, 0, 0,
getLangOpts().Modules? &SuggestedModule : 0,
true);
}
}
}
if (!SuggestedModule) {
Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
FilenameRange, File,
SearchPath, RelativePath,
0);
}
}
if (File == 0) {
if (!SuppressIncludeNotFoundError) {
if (isAngled) {
File = LookupFile(Filename, false, LookupFrom, CurDir,
Callbacks ? &SearchPath : 0,
Callbacks ? &RelativePath : 0,
getLangOpts().Modules ? &SuggestedModule : 0);
if (File) {
SourceRange Range(FilenameTok.getLocation(), CharEnd);
Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
Filename <<
FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
}
}
if (!File)
Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
}
if (!File)
return;
}
if (SuggestedModule) {
llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
for (Module *Mod = SuggestedModule; Mod; Mod = Mod->Parent)
Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
FilenameTok.getLocation()));
std::reverse(Path.begin(), Path.end());
SmallString<128> PathString;
for (unsigned 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");
}
bool BuildingImportedModule
= Path[0].first->getName() == getLangOpts().CurrentModule;
if (!BuildingImportedModule && getLangOpts().ObjC2) {
CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
false);
Diag(HashLoc, diag::warn_auto_module_import)
<< IncludeKind << PathString
<< FixItHint::CreateReplacement(ReplaceRange,
"@__experimental_modules_import " + PathString.str().str() + ";");
}
Module::NameVisibilityKind Visibility
= (IncludeKind == 3)? Module::MacrosVisible : Module::AllVisible;
Module *Imported
= TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
true);
assert((Imported == 0 || Imported == SuggestedModule) &&
"the imported module is different than the suggested one");
if (!BuildingImportedModule && Imported) {
if (Callbacks) {
Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
FilenameRange, File,
SearchPath, RelativePath, Imported);
}
return;
}
}
if (Callbacks && SuggestedModule) {
Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,
FilenameRange, File,
SearchPath, RelativePath,
0);
}
SrcMgr::CharacteristicKind FileCharacter =
std::max(HeaderInfo.getFileDirFlavor(File),
SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
if (Callbacks)
Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
return;
}
SourceLocation IncludePos = End;
if (IncludePos.isMacroID())
IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
assert(!FID.isInvalid() && "Expected valid file ID");
EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
}
void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
Token &IncludeNextTok) {
Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
const DirectoryLookup *Lookup = CurDirLookup;
if (isInPrimaryFile()) {
Lookup = 0;
Diag(IncludeNextTok, diag::pp_include_next_in_primary);
} else if (Lookup == 0) {
Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
} else {
++Lookup;
}
return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
}
void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
Diag(Tok, diag::err_pp_import_directive_ms );
DiscardUntilEndOfDirective();
}
void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
Token &ImportTok) {
if (!LangOpts.ObjC1) { if (LangOpts.MicrosoftMode)
return HandleMicrosoftImportDirective(ImportTok);
Diag(ImportTok, diag::ext_pp_import_directive);
}
return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
}
void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
Token &IncludeMacrosTok) {
SourceLocation Loc = IncludeMacrosTok.getLocation();
if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
Diag(IncludeMacrosTok.getLocation(),
diag::pp_include_macros_out_of_predefines);
DiscardUntilEndOfDirective();
return;
}
HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
Token TmpTok;
do {
Lex(TmpTok);
assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
} while (TmpTok.isNot(tok::hashhash));
}
bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
SmallVector<IdentifierInfo*, 32> Arguments;
while (1) {
LexUnexpandedToken(Tok);
switch (Tok.getKind()) {
case tok::r_paren:
if (Arguments.empty()) return false;
Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
return true;
case tok::ellipsis: if (!LangOpts.C99)
Diag(Tok, LangOpts.CPlusPlus0x ?
diag::warn_cxx98_compat_variadic_macro :
diag::ext_variadic_macro);
LexUnexpandedToken(Tok);
if (Tok.isNot(tok::r_paren)) {
Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
return true;
}
Arguments.push_back(Ident__VA_ARGS__);
MI->setIsC99Varargs();
MI->setArgumentList(&Arguments[0], Arguments.size(), 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 == 0) {
Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
return true;
}
if (std::find(Arguments.begin(), Arguments.end(), II) !=
Arguments.end()) { Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
return true;
}
Arguments.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->setArgumentList(&Arguments[0], Arguments.size(), 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->setArgumentList(&Arguments[0], Arguments.size(), BP);
return false;
}
}
}
}
void Preprocessor::HandleDefineDirective(Token &DefineTok) {
++NumDefined;
Token MacroNameTok;
ReadMacroName(MacroNameTok, 1);
if (MacroNameTok.is(tok::eod))
return;
Token LastTok = MacroNameTok;
if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
Token Tok;
LexUnexpandedToken(Tok);
if (Tok.is(tok::eod)) {
} else if (Tok.hasLeadingSpace()) {
Tok.clearFlag(Token::LeadingSpace);
} else if (Tok.is(tok::l_paren)) {
MI->setIsFunctionLike();
if (ReadMacroDefinitionArgList(MI, LastTok)) {
ReleaseMacroInfo(MI);
if (CurPPLexer->ParsingPreprocessorDirective)
DiscardUntilEndOfDirective();
return;
}
assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
if (MI->isC99Varargs())
Ident__VA_ARGS__->setIsPoisoned(false);
LexUnexpandedToken(Tok);
} else if (LangOpts.C99 || LangOpts.CPlusPlus0x) {
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;
if (MI->isObjectLike()) {
while (Tok.isNot(tok::eod)) {
LastTok = Tok;
MI->AddTokenToBody(Tok);
LexUnexpandedToken(Tok);
}
} else {
while (Tok.isNot(tok::eod)) {
LastTok = Tok;
if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) {
MI->AddTokenToBody(Tok);
LexUnexpandedToken(Tok);
continue;
}
if (Tok.is(tok::hashhash)) {
LexUnexpandedToken(Tok);
if (Tok.is(tok::eod)) {
MI->AddTokenToBody(LastTok);
break;
}
unsigned NumTokens = MI->getNumTokens();
if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
MI->getReplacementToken(NumTokens-1).is(tok::comma))
MI->setHasCommaPasting();
MI->AddTokenToBody(LastTok);
MI->AddTokenToBody(Tok);
LastTok = Tok;
LexUnexpandedToken(Tok);
continue;
}
LexUnexpandedToken(Tok);
if (Tok.getIdentifierInfo() == 0 ||
MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
LastTok.setKind(tok::unknown);
} else {
Diag(Tok, diag::err_pp_stringize_not_parameter);
ReleaseMacroInfo(MI);
Ident__VA_ARGS__->setIsPoisoned(true);
return;
}
}
MI->AddTokenToBody(LastTok);
MI->AddTokenToBody(Tok);
LastTok = Tok;
LexUnexpandedToken(Tok);
}
}
Ident__VA_ARGS__->setIsPoisoned(true);
unsigned NumTokens = MI->getNumTokens();
if (NumTokens != 0) {
if (MI->getReplacementToken(0).is(tok::hashhash)) {
Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
ReleaseMacroInfo(MI);
return;
}
if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
ReleaseMacroInfo(MI);
return;
}
}
MI->setDefinitionEndLoc(LastTok.getLocation());
if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
if (!getDiagnostics().getSuppressSystemWarnings() ||
!SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
!MI->isIdenticalTo(*OtherMI, *this)) {
Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
<< MacroNameTok.getIdentifierInfo();
Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
}
}
if (OtherMI->isWarnIfUnused())
WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
}
setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
assert(!MI->isUsed());
if (isInPrimaryFile() && Diags->getDiagnosticLevel(diag::pp_macro_not_used,
MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
MI->setIsWarnIfUnused(true);
WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
}
if (Callbacks)
Callbacks->MacroDefined(MacroNameTok, MI);
}
void Preprocessor::HandleUndefDirective(Token &UndefTok) {
++NumUndefined;
Token MacroNameTok;
ReadMacroName(MacroNameTok, 2);
if (MacroNameTok.is(tok::eod))
return;
CheckEndOfDirective("undef");
MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
if (MI == 0) return;
if (!MI->isUsed() && MI->isWarnIfUnused())
Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
if (Callbacks)
Callbacks->MacroUndefined(MacroNameTok, MI);
if (MI->isWarnIfUnused())
WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
MI->setUndefLoc(MacroNameTok.getLocation());
clearMacroInfo(MacroNameTok.getIdentifierInfo());
}
void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
bool ReadAnyTokensBeforeDirective) {
++NumIf;
Token DirectiveTok = Result;
Token MacroNameTok;
ReadMacroName(MacroNameTok);
if (MacroNameTok.is(tok::eod)) {
SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
false, false);
return;
}
CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
MacroInfo *MI = getMacroInfo(MII);
if (CurPPLexer->getConditionalStackDepth() == 0) {
if (!ReadAnyTokensBeforeDirective && MI == 0) {
assert(isIfndef && "#ifdef shouldn't reach here");
CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
} else
CurPPLexer->MIOpt.EnterTopLevelConditional();
}
if (MI) markMacroAsUsed(MI);
if (Callbacks) {
if (isIfndef)
Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok);
else
Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok);
}
if (!MI == isIfndef) {
CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
false, true,
false);
} else {
SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
false,
false);
}
}
void Preprocessor::HandleIfDirective(Token &IfToken,
bool ReadAnyTokensBeforeDirective) {
++NumIf;
IdentifierInfo *IfNDefMacro = 0;
const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
if (CurPPLexer->getConditionalStackDepth() == 0) {
if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
else
CurPPLexer->MIOpt.EnterTopLevelConditional();
}
if (Callbacks)
Callbacks->If(IfToken.getLocation(),
SourceRange(ConditionalBegin, ConditionalEnd));
if (ConditionalTrue) {
CurPPLexer->pushConditionalLevel(IfToken.getLocation(), false,
true, false);
} else {
SkipExcludedConditionalBlock(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) {
++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);
SkipExcludedConditionalBlock(CI.IfLoc, true,
true, Result.getLocation());
}
void Preprocessor::HandleElifDirective(Token &ElifToken) {
++NumElse;
const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
DiscardUntilEndOfDirective();
const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
PPConditionalInfo CI;
if (CurPPLexer->popConditionalLevel(CI)) {
Diag(ElifToken, diag::pp_err_elif_without_if);
return;
}
if (CurPPLexer->getConditionalStackDepth() == 0)
CurPPLexer->MIOpt.EnterTopLevelConditional();
if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
if (Callbacks)
Callbacks->Elif(ElifToken.getLocation(),
SourceRange(ConditionalBegin, ConditionalEnd), CI.IfLoc);
SkipExcludedConditionalBlock(CI.IfLoc, true,
CI.FoundElse,
ElifToken.getLocation());
}