PPDirectives.cpp revision 651f13cea278ec967336033dd032faef0e9fc2ec
1//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9/// 10/// \file 11/// \brief Implements # directive processing for the Preprocessor. 12/// 13//===----------------------------------------------------------------------===// 14 15#include "clang/Lex/Preprocessor.h" 16#include "clang/Basic/FileManager.h" 17#include "clang/Basic/SourceManager.h" 18#include "clang/Lex/CodeCompletionHandler.h" 19#include "clang/Lex/HeaderSearch.h" 20#include "clang/Lex/HeaderSearchOptions.h" 21#include "clang/Lex/LexDiagnostic.h" 22#include "clang/Lex/LiteralSupport.h" 23#include "clang/Lex/MacroInfo.h" 24#include "clang/Lex/ModuleLoader.h" 25#include "clang/Lex/Pragma.h" 26#include "llvm/ADT/APInt.h" 27#include "llvm/Support/ErrorHandling.h" 28#include "llvm/Support/FileSystem.h" 29#include "llvm/Support/SaveAndRestore.h" 30using namespace clang; 31 32//===----------------------------------------------------------------------===// 33// Utility Methods for Preprocessor Directive Handling. 34//===----------------------------------------------------------------------===// 35 36MacroInfo *Preprocessor::AllocateMacroInfo() { 37 MacroInfoChain *MIChain; 38 39 if (MICache) { 40 MIChain = MICache; 41 MICache = MICache->Next; 42 } 43 else { 44 MIChain = BP.Allocate<MacroInfoChain>(); 45 } 46 47 MIChain->Next = MIChainHead; 48 MIChain->Prev = 0; 49 if (MIChainHead) 50 MIChainHead->Prev = MIChain; 51 MIChainHead = MIChain; 52 53 return &(MIChain->MI); 54} 55 56MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) { 57 MacroInfo *MI = AllocateMacroInfo(); 58 new (MI) MacroInfo(L); 59 return MI; 60} 61 62MacroInfo *Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L, 63 unsigned SubModuleID) { 64 static_assert(llvm::AlignOf<MacroInfo>::Alignment >= sizeof(SubModuleID), 65 "alignment for MacroInfo is less than the ID"); 66 DeserializedMacroInfoChain *MIChain = 67 BP.Allocate<DeserializedMacroInfoChain>(); 68 MIChain->Next = DeserialMIChainHead; 69 DeserialMIChainHead = MIChain; 70 71 MacroInfo *MI = &MIChain->MI; 72 new (MI) MacroInfo(L); 73 MI->FromASTFile = true; 74 MI->setOwningModuleID(SubModuleID); 75 return MI; 76} 77 78DefMacroDirective * 79Preprocessor::AllocateDefMacroDirective(MacroInfo *MI, SourceLocation Loc, 80 bool isImported) { 81 DefMacroDirective *MD = BP.Allocate<DefMacroDirective>(); 82 new (MD) DefMacroDirective(MI, Loc, isImported); 83 return MD; 84} 85 86UndefMacroDirective * 87Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) { 88 UndefMacroDirective *MD = BP.Allocate<UndefMacroDirective>(); 89 new (MD) UndefMacroDirective(UndefLoc); 90 return MD; 91} 92 93VisibilityMacroDirective * 94Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc, 95 bool isPublic) { 96 VisibilityMacroDirective *MD = BP.Allocate<VisibilityMacroDirective>(); 97 new (MD) VisibilityMacroDirective(Loc, isPublic); 98 return MD; 99} 100 101/// \brief Release the specified MacroInfo to be reused for allocating 102/// new MacroInfo objects. 103void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) { 104 MacroInfoChain *MIChain = (MacroInfoChain*) MI; 105 if (MacroInfoChain *Prev = MIChain->Prev) { 106 MacroInfoChain *Next = MIChain->Next; 107 Prev->Next = Next; 108 if (Next) 109 Next->Prev = Prev; 110 } 111 else { 112 assert(MIChainHead == MIChain); 113 MIChainHead = MIChain->Next; 114 MIChainHead->Prev = 0; 115 } 116 MIChain->Next = MICache; 117 MICache = MIChain; 118 119 MI->Destroy(); 120} 121 122/// \brief Read and discard all tokens remaining on the current line until 123/// the tok::eod token is found. 124void Preprocessor::DiscardUntilEndOfDirective() { 125 Token Tmp; 126 do { 127 LexUnexpandedToken(Tmp); 128 assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens"); 129 } while (Tmp.isNot(tok::eod)); 130} 131 132/// \brief Lex and validate a macro name, which occurs after a 133/// \#define or \#undef. 134/// 135/// This sets the token kind to eod and discards the rest 136/// of the macro line if the macro name is invalid. \p isDefineUndef is 1 if 137/// this is due to a a \#define, 2 if \#undef directive, 0 if it is something 138/// else (e.g. \#ifdef). 139void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) { 140 // Read the token, don't allow macro expansion on it. 141 LexUnexpandedToken(MacroNameTok); 142 143 if (MacroNameTok.is(tok::code_completion)) { 144 if (CodeComplete) 145 CodeComplete->CodeCompleteMacroName(isDefineUndef == 1); 146 setCodeCompletionReached(); 147 LexUnexpandedToken(MacroNameTok); 148 } 149 150 // Missing macro name? 151 if (MacroNameTok.is(tok::eod)) { 152 Diag(MacroNameTok, diag::err_pp_missing_macro_name); 153 return; 154 } 155 156 IdentifierInfo *II = MacroNameTok.getIdentifierInfo(); 157 if (II == 0) { 158 bool Invalid = false; 159 std::string Spelling = getSpelling(MacroNameTok, &Invalid); 160 if (Invalid) 161 return; 162 163 const IdentifierInfo &Info = Identifiers.get(Spelling); 164 165 // Allow #defining |and| and friends in microsoft mode. 166 if (Info.isCPlusPlusOperatorKeyword() && getLangOpts().MSVCCompat) { 167 MacroNameTok.setIdentifierInfo(getIdentifierInfo(Spelling)); 168 return; 169 } 170 171 if (Info.isCPlusPlusOperatorKeyword()) 172 // C++ 2.5p2: Alternative tokens behave the same as its primary token 173 // except for their spellings. 174 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling; 175 else 176 Diag(MacroNameTok, diag::err_pp_macro_not_identifier); 177 // Fall through on error. 178 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) { 179 // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4. 180 Diag(MacroNameTok, diag::err_defined_macro_name); 181 } else if (isDefineUndef == 2 && II->hasMacroDefinition() && 182 getMacroInfo(II)->isBuiltinMacro()) { 183 // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4 184 // and C++ [cpp.predefined]p4], but allow it as an extension. 185 Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro); 186 return; 187 } else { 188 // Okay, we got a good identifier node. Return it. 189 return; 190 } 191 192 // Invalid macro name, read and discard the rest of the line. Then set the 193 // token kind to tok::eod. 194 MacroNameTok.setKind(tok::eod); 195 return DiscardUntilEndOfDirective(); 196} 197 198/// \brief Ensure that the next token is a tok::eod token. 199/// 200/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is 201/// true, then we consider macros that expand to zero tokens as being ok. 202void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) { 203 Token Tmp; 204 // Lex unexpanded tokens for most directives: macros might expand to zero 205 // tokens, causing us to miss diagnosing invalid lines. Some directives (like 206 // #line) allow empty macros. 207 if (EnableMacros) 208 Lex(Tmp); 209 else 210 LexUnexpandedToken(Tmp); 211 212 // There should be no tokens after the directive, but we allow them as an 213 // extension. 214 while (Tmp.is(tok::comment)) // Skip comments in -C mode. 215 LexUnexpandedToken(Tmp); 216 217 if (Tmp.isNot(tok::eod)) { 218 // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89, 219 // or if this is a macro-style preprocessing directive, because it is more 220 // trouble than it is worth to insert /**/ and check that there is no /**/ 221 // in the range also. 222 FixItHint Hint; 223 if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) && 224 !CurTokenLexer) 225 Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//"); 226 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint; 227 DiscardUntilEndOfDirective(); 228 } 229} 230 231 232 233/// SkipExcludedConditionalBlock - We just read a \#if or related directive and 234/// decided that the subsequent tokens are in the \#if'd out portion of the 235/// file. Lex the rest of the file, until we see an \#endif. If 236/// FoundNonSkipPortion is true, then we have already emitted code for part of 237/// this \#if directive, so \#else/\#elif blocks should never be entered. 238/// If ElseOk is true, then \#else directives are ok, if not, then we have 239/// already seen one so a \#else directive is a duplicate. When this returns, 240/// the caller can lex the first valid token. 241void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, 242 bool FoundNonSkipPortion, 243 bool FoundElse, 244 SourceLocation ElseLoc) { 245 ++NumSkipped; 246 assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?"); 247 248 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false, 249 FoundNonSkipPortion, FoundElse); 250 251 if (CurPTHLexer) { 252 PTHSkipExcludedConditionalBlock(); 253 return; 254 } 255 256 // Enter raw mode to disable identifier lookup (and thus macro expansion), 257 // disabling warnings, etc. 258 CurPPLexer->LexingRawMode = true; 259 Token Tok; 260 while (1) { 261 CurLexer->Lex(Tok); 262 263 if (Tok.is(tok::code_completion)) { 264 if (CodeComplete) 265 CodeComplete->CodeCompleteInConditionalExclusion(); 266 setCodeCompletionReached(); 267 continue; 268 } 269 270 // If this is the end of the buffer, we have an error. 271 if (Tok.is(tok::eof)) { 272 // Emit errors for each unterminated conditional on the stack, including 273 // the current one. 274 while (!CurPPLexer->ConditionalStack.empty()) { 275 if (CurLexer->getFileLoc() != CodeCompletionFileLoc) 276 Diag(CurPPLexer->ConditionalStack.back().IfLoc, 277 diag::err_pp_unterminated_conditional); 278 CurPPLexer->ConditionalStack.pop_back(); 279 } 280 281 // Just return and let the caller lex after this #include. 282 break; 283 } 284 285 // If this token is not a preprocessor directive, just skip it. 286 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) 287 continue; 288 289 // We just parsed a # character at the start of a line, so we're in 290 // directive mode. Tell the lexer this so any newlines we see will be 291 // converted into an EOD token (this terminates the macro). 292 CurPPLexer->ParsingPreprocessorDirective = true; 293 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false); 294 295 296 // Read the next token, the directive flavor. 297 LexUnexpandedToken(Tok); 298 299 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or 300 // something bogus), skip it. 301 if (Tok.isNot(tok::raw_identifier)) { 302 CurPPLexer->ParsingPreprocessorDirective = false; 303 // Restore comment saving mode. 304 if (CurLexer) CurLexer->resetExtendedTokenMode(); 305 continue; 306 } 307 308 // If the first letter isn't i or e, it isn't intesting to us. We know that 309 // this is safe in the face of spelling differences, because there is no way 310 // to spell an i/e in a strange way that is another letter. Skipping this 311 // allows us to avoid looking up the identifier info for #define/#undef and 312 // other common directives. 313 const char *RawCharData = Tok.getRawIdentifierData(); 314 315 char FirstChar = RawCharData[0]; 316 if (FirstChar >= 'a' && FirstChar <= 'z' && 317 FirstChar != 'i' && FirstChar != 'e') { 318 CurPPLexer->ParsingPreprocessorDirective = false; 319 // Restore comment saving mode. 320 if (CurLexer) CurLexer->resetExtendedTokenMode(); 321 continue; 322 } 323 324 // Get the identifier name without trigraphs or embedded newlines. Note 325 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled 326 // when skipping. 327 char DirectiveBuf[20]; 328 StringRef Directive; 329 if (!Tok.needsCleaning() && Tok.getLength() < 20) { 330 Directive = StringRef(RawCharData, Tok.getLength()); 331 } else { 332 std::string DirectiveStr = getSpelling(Tok); 333 unsigned IdLen = DirectiveStr.size(); 334 if (IdLen >= 20) { 335 CurPPLexer->ParsingPreprocessorDirective = false; 336 // Restore comment saving mode. 337 if (CurLexer) CurLexer->resetExtendedTokenMode(); 338 continue; 339 } 340 memcpy(DirectiveBuf, &DirectiveStr[0], IdLen); 341 Directive = StringRef(DirectiveBuf, IdLen); 342 } 343 344 if (Directive.startswith("if")) { 345 StringRef Sub = Directive.substr(2); 346 if (Sub.empty() || // "if" 347 Sub == "def" || // "ifdef" 348 Sub == "ndef") { // "ifndef" 349 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't 350 // bother parsing the condition. 351 DiscardUntilEndOfDirective(); 352 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true, 353 /*foundnonskip*/false, 354 /*foundelse*/false); 355 } 356 } else if (Directive[0] == 'e') { 357 StringRef Sub = Directive.substr(1); 358 if (Sub == "ndif") { // "endif" 359 PPConditionalInfo CondInfo; 360 CondInfo.WasSkipping = true; // Silence bogus warning. 361 bool InCond = CurPPLexer->popConditionalLevel(CondInfo); 362 (void)InCond; // Silence warning in no-asserts mode. 363 assert(!InCond && "Can't be skipping if not in a conditional!"); 364 365 // If we popped the outermost skipping block, we're done skipping! 366 if (!CondInfo.WasSkipping) { 367 // Restore the value of LexingRawMode so that trailing comments 368 // are handled correctly, if we've reached the outermost block. 369 CurPPLexer->LexingRawMode = false; 370 CheckEndOfDirective("endif"); 371 CurPPLexer->LexingRawMode = true; 372 if (Callbacks) 373 Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc); 374 break; 375 } else { 376 DiscardUntilEndOfDirective(); 377 } 378 } else if (Sub == "lse") { // "else". 379 // #else directive in a skipping conditional. If not in some other 380 // skipping conditional, and if #else hasn't already been seen, enter it 381 // as a non-skipping conditional. 382 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel(); 383 384 // If this is a #else with a #else before it, report the error. 385 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else); 386 387 // Note that we've seen a #else in this conditional. 388 CondInfo.FoundElse = true; 389 390 // If the conditional is at the top level, and the #if block wasn't 391 // entered, enter the #else block now. 392 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) { 393 CondInfo.FoundNonSkip = true; 394 // Restore the value of LexingRawMode so that trailing comments 395 // are handled correctly. 396 CurPPLexer->LexingRawMode = false; 397 CheckEndOfDirective("else"); 398 CurPPLexer->LexingRawMode = true; 399 if (Callbacks) 400 Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc); 401 break; 402 } else { 403 DiscardUntilEndOfDirective(); // C99 6.10p4. 404 } 405 } else if (Sub == "lif") { // "elif". 406 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel(); 407 408 // If this is a #elif with a #else before it, report the error. 409 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else); 410 411 // If this is in a skipping block or if we're already handled this #if 412 // block, don't bother parsing the condition. 413 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) { 414 DiscardUntilEndOfDirective(); 415 } else { 416 const SourceLocation CondBegin = CurPPLexer->getSourceLocation(); 417 // Restore the value of LexingRawMode so that identifiers are 418 // looked up, etc, inside the #elif expression. 419 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!"); 420 CurPPLexer->LexingRawMode = false; 421 IdentifierInfo *IfNDefMacro = 0; 422 const bool CondValue = EvaluateDirectiveExpression(IfNDefMacro); 423 CurPPLexer->LexingRawMode = true; 424 if (Callbacks) { 425 const SourceLocation CondEnd = CurPPLexer->getSourceLocation(); 426 Callbacks->Elif(Tok.getLocation(), 427 SourceRange(CondBegin, CondEnd), 428 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), CondInfo.IfLoc); 429 } 430 // If this condition is true, enter it! 431 if (CondValue) { 432 CondInfo.FoundNonSkip = true; 433 break; 434 } 435 } 436 } 437 } 438 439 CurPPLexer->ParsingPreprocessorDirective = false; 440 // Restore comment saving mode. 441 if (CurLexer) CurLexer->resetExtendedTokenMode(); 442 } 443 444 // Finally, if we are out of the conditional (saw an #endif or ran off the end 445 // of the file, just stop skipping and return to lexing whatever came after 446 // the #if block. 447 CurPPLexer->LexingRawMode = false; 448 449 if (Callbacks) { 450 SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc; 451 Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation())); 452 } 453} 454 455void Preprocessor::PTHSkipExcludedConditionalBlock() { 456 457 while (1) { 458 assert(CurPTHLexer); 459 assert(CurPTHLexer->LexingRawMode == false); 460 461 // Skip to the next '#else', '#elif', or #endif. 462 if (CurPTHLexer->SkipBlock()) { 463 // We have reached an #endif. Both the '#' and 'endif' tokens 464 // have been consumed by the PTHLexer. Just pop off the condition level. 465 PPConditionalInfo CondInfo; 466 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo); 467 (void)InCond; // Silence warning in no-asserts mode. 468 assert(!InCond && "Can't be skipping if not in a conditional!"); 469 break; 470 } 471 472 // We have reached a '#else' or '#elif'. Lex the next token to get 473 // the directive flavor. 474 Token Tok; 475 LexUnexpandedToken(Tok); 476 477 // We can actually look up the IdentifierInfo here since we aren't in 478 // raw mode. 479 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID(); 480 481 if (K == tok::pp_else) { 482 // #else: Enter the else condition. We aren't in a nested condition 483 // since we skip those. We're always in the one matching the last 484 // blocked we skipped. 485 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel(); 486 // Note that we've seen a #else in this conditional. 487 CondInfo.FoundElse = true; 488 489 // If the #if block wasn't entered then enter the #else block now. 490 if (!CondInfo.FoundNonSkip) { 491 CondInfo.FoundNonSkip = true; 492 493 // Scan until the eod token. 494 CurPTHLexer->ParsingPreprocessorDirective = true; 495 DiscardUntilEndOfDirective(); 496 CurPTHLexer->ParsingPreprocessorDirective = false; 497 498 break; 499 } 500 501 // Otherwise skip this block. 502 continue; 503 } 504 505 assert(K == tok::pp_elif); 506 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel(); 507 508 // If this is a #elif with a #else before it, report the error. 509 if (CondInfo.FoundElse) 510 Diag(Tok, diag::pp_err_elif_after_else); 511 512 // If this is in a skipping block or if we're already handled this #if 513 // block, don't bother parsing the condition. We just skip this block. 514 if (CondInfo.FoundNonSkip) 515 continue; 516 517 // Evaluate the condition of the #elif. 518 IdentifierInfo *IfNDefMacro = 0; 519 CurPTHLexer->ParsingPreprocessorDirective = true; 520 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro); 521 CurPTHLexer->ParsingPreprocessorDirective = false; 522 523 // If this condition is true, enter it! 524 if (ShouldEnter) { 525 CondInfo.FoundNonSkip = true; 526 break; 527 } 528 529 // Otherwise, skip this block and go to the next one. 530 continue; 531 } 532} 533 534Module *Preprocessor::getModuleForLocation(SourceLocation FilenameLoc) { 535 ModuleMap &ModMap = HeaderInfo.getModuleMap(); 536 if (SourceMgr.isInMainFile(FilenameLoc)) { 537 if (Module *CurMod = getCurrentModule()) 538 return CurMod; // Compiling a module. 539 return HeaderInfo.getModuleMap().SourceModule; // Compiling a source. 540 } 541 // Try to determine the module of the include directive. 542 // FIXME: Look into directly passing the FileEntry from LookupFile instead. 543 FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(FilenameLoc)); 544 if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) { 545 // The include comes from a file. 546 return ModMap.findModuleForHeader(EntryOfIncl).getModule(); 547 } else { 548 // The include does not come from a file, 549 // so it is probably a module compilation. 550 return getCurrentModule(); 551 } 552} 553 554const FileEntry *Preprocessor::LookupFile( 555 SourceLocation FilenameLoc, 556 StringRef Filename, 557 bool isAngled, 558 const DirectoryLookup *FromDir, 559 const DirectoryLookup *&CurDir, 560 SmallVectorImpl<char> *SearchPath, 561 SmallVectorImpl<char> *RelativePath, 562 ModuleMap::KnownHeader *SuggestedModule, 563 bool SkipCache) { 564 // If the header lookup mechanism may be relative to the current inclusion 565 // stack, record the parent #includes. 566 SmallVector<const FileEntry *, 16> Includers; 567 if (!FromDir) { 568 FileID FID = getCurrentFileLexer()->getFileID(); 569 const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID); 570 571 // If there is no file entry associated with this file, it must be the 572 // predefines buffer. Any other file is not lexed with a normal lexer, so 573 // it won't be scanned for preprocessor directives. If we have the 574 // predefines buffer, resolve #include references (which come from the 575 // -include command line argument) as if they came from the main file, this 576 // affects file lookup etc. 577 if (!FileEnt) 578 FileEnt = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()); 579 580 if (FileEnt) 581 Includers.push_back(FileEnt); 582 583 // MSVC searches the current include stack from top to bottom for 584 // headers included by quoted include directives. 585 // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx 586 if (LangOpts.MSVCCompat && !isAngled) { 587 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) { 588 IncludeStackInfo &ISEntry = IncludeMacroStack[e - i - 1]; 589 if (IsFileLexer(ISEntry)) 590 if ((FileEnt = SourceMgr.getFileEntryForID( 591 ISEntry.ThePPLexer->getFileID()))) 592 Includers.push_back(FileEnt); 593 } 594 } 595 } 596 597 // Do a standard file entry lookup. 598 CurDir = CurDirLookup; 599 const FileEntry *FE = HeaderInfo.LookupFile( 600 Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath, 601 RelativePath, SuggestedModule, SkipCache); 602 if (FE) { 603 if (SuggestedModule && !LangOpts.AsmPreprocessor) 604 HeaderInfo.getModuleMap().diagnoseHeaderInclusion( 605 getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE); 606 return FE; 607 } 608 609 const FileEntry *CurFileEnt; 610 // Otherwise, see if this is a subframework header. If so, this is relative 611 // to one of the headers on the #include stack. Walk the list of the current 612 // headers on the #include stack and pass them to HeaderInfo. 613 if (IsFileLexer()) { 614 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))) 615 if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt, 616 SearchPath, RelativePath, 617 SuggestedModule))) 618 return FE; 619 } 620 621 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) { 622 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1]; 623 if (IsFileLexer(ISEntry)) { 624 if ((CurFileEnt = 625 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID()))) 626 if ((FE = HeaderInfo.LookupSubframeworkHeader( 627 Filename, CurFileEnt, SearchPath, RelativePath, 628 SuggestedModule))) 629 return FE; 630 } 631 } 632 633 // Otherwise, we really couldn't find the file. 634 return 0; 635} 636 637 638//===----------------------------------------------------------------------===// 639// Preprocessor Directive Handling. 640//===----------------------------------------------------------------------===// 641 642class Preprocessor::ResetMacroExpansionHelper { 643public: 644 ResetMacroExpansionHelper(Preprocessor *pp) 645 : PP(pp), save(pp->DisableMacroExpansion) { 646 if (pp->MacroExpansionInDirectivesOverride) 647 pp->DisableMacroExpansion = false; 648 } 649 ~ResetMacroExpansionHelper() { 650 PP->DisableMacroExpansion = save; 651 } 652private: 653 Preprocessor *PP; 654 bool save; 655}; 656 657/// HandleDirective - This callback is invoked when the lexer sees a # token 658/// at the start of a line. This consumes the directive, modifies the 659/// lexer/preprocessor state, and advances the lexer(s) so that the next token 660/// read is the correct one. 661void Preprocessor::HandleDirective(Token &Result) { 662 // FIXME: Traditional: # with whitespace before it not recognized by K&R? 663 664 // We just parsed a # character at the start of a line, so we're in directive 665 // mode. Tell the lexer this so any newlines we see will be converted into an 666 // EOD token (which terminates the directive). 667 CurPPLexer->ParsingPreprocessorDirective = true; 668 if (CurLexer) CurLexer->SetKeepWhitespaceMode(false); 669 670 bool ImmediatelyAfterTopLevelIfndef = 671 CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef(); 672 CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef(); 673 674 ++NumDirectives; 675 676 // We are about to read a token. For the multiple-include optimization FA to 677 // work, we have to remember if we had read any tokens *before* this 678 // pp-directive. 679 bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal(); 680 681 // Save the '#' token in case we need to return it later. 682 Token SavedHash = Result; 683 684 // Read the next token, the directive flavor. This isn't expanded due to 685 // C99 6.10.3p8. 686 LexUnexpandedToken(Result); 687 688 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.: 689 // #define A(x) #x 690 // A(abc 691 // #warning blah 692 // def) 693 // If so, the user is relying on undefined behavior, emit a diagnostic. Do 694 // not support this for #include-like directives, since that can result in 695 // terrible diagnostics, and does not work in GCC. 696 if (InMacroArgs) { 697 if (IdentifierInfo *II = Result.getIdentifierInfo()) { 698 switch (II->getPPKeywordID()) { 699 case tok::pp_include: 700 case tok::pp_import: 701 case tok::pp_include_next: 702 case tok::pp___include_macros: 703 Diag(Result, diag::err_embedded_include) << II->getName(); 704 DiscardUntilEndOfDirective(); 705 return; 706 default: 707 break; 708 } 709 } 710 Diag(Result, diag::ext_embedded_directive); 711 } 712 713 // Temporarily enable macro expansion if set so 714 // and reset to previous state when returning from this function. 715 ResetMacroExpansionHelper helper(this); 716 717 switch (Result.getKind()) { 718 case tok::eod: 719 return; // null directive. 720 case tok::code_completion: 721 if (CodeComplete) 722 CodeComplete->CodeCompleteDirective( 723 CurPPLexer->getConditionalStackDepth() > 0); 724 setCodeCompletionReached(); 725 return; 726 case tok::numeric_constant: // # 7 GNU line marker directive. 727 if (getLangOpts().AsmPreprocessor) 728 break; // # 4 is not a preprocessor directive in .S files. 729 return HandleDigitDirective(Result); 730 default: 731 IdentifierInfo *II = Result.getIdentifierInfo(); 732 if (II == 0) break; // Not an identifier. 733 734 // Ask what the preprocessor keyword ID is. 735 switch (II->getPPKeywordID()) { 736 default: break; 737 // C99 6.10.1 - Conditional Inclusion. 738 case tok::pp_if: 739 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective); 740 case tok::pp_ifdef: 741 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/); 742 case tok::pp_ifndef: 743 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective); 744 case tok::pp_elif: 745 return HandleElifDirective(Result); 746 case tok::pp_else: 747 return HandleElseDirective(Result); 748 case tok::pp_endif: 749 return HandleEndifDirective(Result); 750 751 // C99 6.10.2 - Source File Inclusion. 752 case tok::pp_include: 753 // Handle #include. 754 return HandleIncludeDirective(SavedHash.getLocation(), Result); 755 case tok::pp___include_macros: 756 // Handle -imacros. 757 return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result); 758 759 // C99 6.10.3 - Macro Replacement. 760 case tok::pp_define: 761 return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef); 762 case tok::pp_undef: 763 return HandleUndefDirective(Result); 764 765 // C99 6.10.4 - Line Control. 766 case tok::pp_line: 767 return HandleLineDirective(Result); 768 769 // C99 6.10.5 - Error Directive. 770 case tok::pp_error: 771 return HandleUserDiagnosticDirective(Result, false); 772 773 // C99 6.10.6 - Pragma Directive. 774 case tok::pp_pragma: 775 return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma); 776 777 // GNU Extensions. 778 case tok::pp_import: 779 return HandleImportDirective(SavedHash.getLocation(), Result); 780 case tok::pp_include_next: 781 return HandleIncludeNextDirective(SavedHash.getLocation(), Result); 782 783 case tok::pp_warning: 784 Diag(Result, diag::ext_pp_warning_directive); 785 return HandleUserDiagnosticDirective(Result, true); 786 case tok::pp_ident: 787 return HandleIdentSCCSDirective(Result); 788 case tok::pp_sccs: 789 return HandleIdentSCCSDirective(Result); 790 case tok::pp_assert: 791 //isExtension = true; // FIXME: implement #assert 792 break; 793 case tok::pp_unassert: 794 //isExtension = true; // FIXME: implement #unassert 795 break; 796 797 case tok::pp___public_macro: 798 if (getLangOpts().Modules) 799 return HandleMacroPublicDirective(Result); 800 break; 801 802 case tok::pp___private_macro: 803 if (getLangOpts().Modules) 804 return HandleMacroPrivateDirective(Result); 805 break; 806 } 807 break; 808 } 809 810 // If this is a .S file, treat unknown # directives as non-preprocessor 811 // directives. This is important because # may be a comment or introduce 812 // various pseudo-ops. Just return the # token and push back the following 813 // token to be lexed next time. 814 if (getLangOpts().AsmPreprocessor) { 815 Token *Toks = new Token[2]; 816 // Return the # and the token after it. 817 Toks[0] = SavedHash; 818 Toks[1] = Result; 819 820 // If the second token is a hashhash token, then we need to translate it to 821 // unknown so the token lexer doesn't try to perform token pasting. 822 if (Result.is(tok::hashhash)) 823 Toks[1].setKind(tok::unknown); 824 825 // Enter this token stream so that we re-lex the tokens. Make sure to 826 // enable macro expansion, in case the token after the # is an identifier 827 // that is expanded. 828 EnterTokenStream(Toks, 2, false, true); 829 return; 830 } 831 832 // If we reached here, the preprocessing token is not valid! 833 Diag(Result, diag::err_pp_invalid_directive); 834 835 // Read the rest of the PP line. 836 DiscardUntilEndOfDirective(); 837 838 // Okay, we're done parsing the directive. 839} 840 841/// GetLineValue - Convert a numeric token into an unsigned value, emitting 842/// Diagnostic DiagID if it is invalid, and returning the value in Val. 843static bool GetLineValue(Token &DigitTok, unsigned &Val, 844 unsigned DiagID, Preprocessor &PP, 845 bool IsGNULineDirective=false) { 846 if (DigitTok.isNot(tok::numeric_constant)) { 847 PP.Diag(DigitTok, DiagID); 848 849 if (DigitTok.isNot(tok::eod)) 850 PP.DiscardUntilEndOfDirective(); 851 return true; 852 } 853 854 SmallString<64> IntegerBuffer; 855 IntegerBuffer.resize(DigitTok.getLength()); 856 const char *DigitTokBegin = &IntegerBuffer[0]; 857 bool Invalid = false; 858 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid); 859 if (Invalid) 860 return true; 861 862 // Verify that we have a simple digit-sequence, and compute the value. This 863 // is always a simple digit string computed in decimal, so we do this manually 864 // here. 865 Val = 0; 866 for (unsigned i = 0; i != ActualLength; ++i) { 867 // C++1y [lex.fcon]p1: 868 // Optional separating single quotes in a digit-sequence are ignored 869 if (DigitTokBegin[i] == '\'') 870 continue; 871 872 if (!isDigit(DigitTokBegin[i])) { 873 PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i), 874 diag::err_pp_line_digit_sequence) << IsGNULineDirective; 875 PP.DiscardUntilEndOfDirective(); 876 return true; 877 } 878 879 unsigned NextVal = Val*10+(DigitTokBegin[i]-'0'); 880 if (NextVal < Val) { // overflow. 881 PP.Diag(DigitTok, DiagID); 882 PP.DiscardUntilEndOfDirective(); 883 return true; 884 } 885 Val = NextVal; 886 } 887 888 if (DigitTokBegin[0] == '0' && Val) 889 PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal) 890 << IsGNULineDirective; 891 892 return false; 893} 894 895/// \brief Handle a \#line directive: C99 6.10.4. 896/// 897/// The two acceptable forms are: 898/// \verbatim 899/// # line digit-sequence 900/// # line digit-sequence "s-char-sequence" 901/// \endverbatim 902void Preprocessor::HandleLineDirective(Token &Tok) { 903 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are 904 // expanded. 905 Token DigitTok; 906 Lex(DigitTok); 907 908 // Validate the number and convert it to an unsigned. 909 unsigned LineNo; 910 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this)) 911 return; 912 913 if (LineNo == 0) 914 Diag(DigitTok, diag::ext_pp_line_zero); 915 916 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a 917 // number greater than 2147483647". C90 requires that the line # be <= 32767. 918 unsigned LineLimit = 32768U; 919 if (LangOpts.C99 || LangOpts.CPlusPlus11) 920 LineLimit = 2147483648U; 921 if (LineNo >= LineLimit) 922 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit; 923 else if (LangOpts.CPlusPlus11 && LineNo >= 32768U) 924 Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big); 925 926 int FilenameID = -1; 927 Token StrTok; 928 Lex(StrTok); 929 930 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a 931 // string followed by eod. 932 if (StrTok.is(tok::eod)) 933 ; // ok 934 else if (StrTok.isNot(tok::string_literal)) { 935 Diag(StrTok, diag::err_pp_line_invalid_filename); 936 return DiscardUntilEndOfDirective(); 937 } else if (StrTok.hasUDSuffix()) { 938 Diag(StrTok, diag::err_invalid_string_udl); 939 return DiscardUntilEndOfDirective(); 940 } else { 941 // Parse and validate the string, converting it into a unique ID. 942 StringLiteralParser Literal(&StrTok, 1, *this); 943 assert(Literal.isAscii() && "Didn't allow wide strings in"); 944 if (Literal.hadError) 945 return DiscardUntilEndOfDirective(); 946 if (Literal.Pascal) { 947 Diag(StrTok, diag::err_pp_linemarker_invalid_filename); 948 return DiscardUntilEndOfDirective(); 949 } 950 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString()); 951 952 // Verify that there is nothing after the string, other than EOD. Because 953 // of C99 6.10.4p5, macros that expand to empty tokens are ok. 954 CheckEndOfDirective("line", true); 955 } 956 957 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID); 958 959 if (Callbacks) 960 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), 961 PPCallbacks::RenameFile, 962 SrcMgr::C_User); 963} 964 965/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line 966/// marker directive. 967static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit, 968 bool &IsSystemHeader, bool &IsExternCHeader, 969 Preprocessor &PP) { 970 unsigned FlagVal; 971 Token FlagTok; 972 PP.Lex(FlagTok); 973 if (FlagTok.is(tok::eod)) return false; 974 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP)) 975 return true; 976 977 if (FlagVal == 1) { 978 IsFileEntry = true; 979 980 PP.Lex(FlagTok); 981 if (FlagTok.is(tok::eod)) return false; 982 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP)) 983 return true; 984 } else if (FlagVal == 2) { 985 IsFileExit = true; 986 987 SourceManager &SM = PP.getSourceManager(); 988 // If we are leaving the current presumed file, check to make sure the 989 // presumed include stack isn't empty! 990 FileID CurFileID = 991 SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first; 992 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation()); 993 if (PLoc.isInvalid()) 994 return true; 995 996 // If there is no include loc (main file) or if the include loc is in a 997 // different physical file, then we aren't in a "1" line marker flag region. 998 SourceLocation IncLoc = PLoc.getIncludeLoc(); 999 if (IncLoc.isInvalid() || 1000 SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) { 1001 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop); 1002 PP.DiscardUntilEndOfDirective(); 1003 return true; 1004 } 1005 1006 PP.Lex(FlagTok); 1007 if (FlagTok.is(tok::eod)) return false; 1008 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP)) 1009 return true; 1010 } 1011 1012 // We must have 3 if there are still flags. 1013 if (FlagVal != 3) { 1014 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag); 1015 PP.DiscardUntilEndOfDirective(); 1016 return true; 1017 } 1018 1019 IsSystemHeader = true; 1020 1021 PP.Lex(FlagTok); 1022 if (FlagTok.is(tok::eod)) return false; 1023 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP)) 1024 return true; 1025 1026 // We must have 4 if there is yet another flag. 1027 if (FlagVal != 4) { 1028 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag); 1029 PP.DiscardUntilEndOfDirective(); 1030 return true; 1031 } 1032 1033 IsExternCHeader = true; 1034 1035 PP.Lex(FlagTok); 1036 if (FlagTok.is(tok::eod)) return false; 1037 1038 // There are no more valid flags here. 1039 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag); 1040 PP.DiscardUntilEndOfDirective(); 1041 return true; 1042} 1043 1044/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is 1045/// one of the following forms: 1046/// 1047/// # 42 1048/// # 42 "file" ('1' | '2')? 1049/// # 42 "file" ('1' | '2')? '3' '4'? 1050/// 1051void Preprocessor::HandleDigitDirective(Token &DigitTok) { 1052 // Validate the number and convert it to an unsigned. GNU does not have a 1053 // line # limit other than it fit in 32-bits. 1054 unsigned LineNo; 1055 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer, 1056 *this, true)) 1057 return; 1058 1059 Token StrTok; 1060 Lex(StrTok); 1061 1062 bool IsFileEntry = false, IsFileExit = false; 1063 bool IsSystemHeader = false, IsExternCHeader = false; 1064 int FilenameID = -1; 1065 1066 // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a 1067 // string followed by eod. 1068 if (StrTok.is(tok::eod)) 1069 ; // ok 1070 else if (StrTok.isNot(tok::string_literal)) { 1071 Diag(StrTok, diag::err_pp_linemarker_invalid_filename); 1072 return DiscardUntilEndOfDirective(); 1073 } else if (StrTok.hasUDSuffix()) { 1074 Diag(StrTok, diag::err_invalid_string_udl); 1075 return DiscardUntilEndOfDirective(); 1076 } else { 1077 // Parse and validate the string, converting it into a unique ID. 1078 StringLiteralParser Literal(&StrTok, 1, *this); 1079 assert(Literal.isAscii() && "Didn't allow wide strings in"); 1080 if (Literal.hadError) 1081 return DiscardUntilEndOfDirective(); 1082 if (Literal.Pascal) { 1083 Diag(StrTok, diag::err_pp_linemarker_invalid_filename); 1084 return DiscardUntilEndOfDirective(); 1085 } 1086 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString()); 1087 1088 // If a filename was present, read any flags that are present. 1089 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, 1090 IsSystemHeader, IsExternCHeader, *this)) 1091 return; 1092 } 1093 1094 // Create a line note with this information. 1095 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, 1096 IsFileEntry, IsFileExit, 1097 IsSystemHeader, IsExternCHeader); 1098 1099 // If the preprocessor has callbacks installed, notify them of the #line 1100 // change. This is used so that the line marker comes out in -E mode for 1101 // example. 1102 if (Callbacks) { 1103 PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile; 1104 if (IsFileEntry) 1105 Reason = PPCallbacks::EnterFile; 1106 else if (IsFileExit) 1107 Reason = PPCallbacks::ExitFile; 1108 SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User; 1109 if (IsExternCHeader) 1110 FileKind = SrcMgr::C_ExternCSystem; 1111 else if (IsSystemHeader) 1112 FileKind = SrcMgr::C_System; 1113 1114 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind); 1115 } 1116} 1117 1118 1119/// HandleUserDiagnosticDirective - Handle a #warning or #error directive. 1120/// 1121void Preprocessor::HandleUserDiagnosticDirective(Token &Tok, 1122 bool isWarning) { 1123 // PTH doesn't emit #warning or #error directives. 1124 if (CurPTHLexer) 1125 return CurPTHLexer->DiscardToEndOfLine(); 1126 1127 // Read the rest of the line raw. We do this because we don't want macros 1128 // to be expanded and we don't require that the tokens be valid preprocessing 1129 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does 1130 // collapse multiple consequtive white space between tokens, but this isn't 1131 // specified by the standard. 1132 SmallString<128> Message; 1133 CurLexer->ReadToEndOfLine(&Message); 1134 1135 // Find the first non-whitespace character, so that we can make the 1136 // diagnostic more succinct. 1137 StringRef Msg = Message.str().ltrim(" "); 1138 1139 if (isWarning) 1140 Diag(Tok, diag::pp_hash_warning) << Msg; 1141 else 1142 Diag(Tok, diag::err_pp_hash_error) << Msg; 1143} 1144 1145/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive. 1146/// 1147void Preprocessor::HandleIdentSCCSDirective(Token &Tok) { 1148 // Yes, this directive is an extension. 1149 Diag(Tok, diag::ext_pp_ident_directive); 1150 1151 // Read the string argument. 1152 Token StrTok; 1153 Lex(StrTok); 1154 1155 // If the token kind isn't a string, it's a malformed directive. 1156 if (StrTok.isNot(tok::string_literal) && 1157 StrTok.isNot(tok::wide_string_literal)) { 1158 Diag(StrTok, diag::err_pp_malformed_ident); 1159 if (StrTok.isNot(tok::eod)) 1160 DiscardUntilEndOfDirective(); 1161 return; 1162 } 1163 1164 if (StrTok.hasUDSuffix()) { 1165 Diag(StrTok, diag::err_invalid_string_udl); 1166 return DiscardUntilEndOfDirective(); 1167 } 1168 1169 // Verify that there is nothing after the string, other than EOD. 1170 CheckEndOfDirective("ident"); 1171 1172 if (Callbacks) { 1173 bool Invalid = false; 1174 std::string Str = getSpelling(StrTok, &Invalid); 1175 if (!Invalid) 1176 Callbacks->Ident(Tok.getLocation(), Str); 1177 } 1178} 1179 1180/// \brief Handle a #public directive. 1181void Preprocessor::HandleMacroPublicDirective(Token &Tok) { 1182 Token MacroNameTok; 1183 ReadMacroName(MacroNameTok, 2); 1184 1185 // Error reading macro name? If so, diagnostic already issued. 1186 if (MacroNameTok.is(tok::eod)) 1187 return; 1188 1189 // Check to see if this is the last token on the #__public_macro line. 1190 CheckEndOfDirective("__public_macro"); 1191 1192 IdentifierInfo *II = MacroNameTok.getIdentifierInfo(); 1193 // Okay, we finally have a valid identifier to undef. 1194 MacroDirective *MD = getMacroDirective(II); 1195 1196 // If the macro is not defined, this is an error. 1197 if (MD == 0) { 1198 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II; 1199 return; 1200 } 1201 1202 // Note that this macro has now been exported. 1203 appendMacroDirective(II, AllocateVisibilityMacroDirective( 1204 MacroNameTok.getLocation(), /*IsPublic=*/true)); 1205} 1206 1207/// \brief Handle a #private directive. 1208void Preprocessor::HandleMacroPrivateDirective(Token &Tok) { 1209 Token MacroNameTok; 1210 ReadMacroName(MacroNameTok, 2); 1211 1212 // Error reading macro name? If so, diagnostic already issued. 1213 if (MacroNameTok.is(tok::eod)) 1214 return; 1215 1216 // Check to see if this is the last token on the #__private_macro line. 1217 CheckEndOfDirective("__private_macro"); 1218 1219 IdentifierInfo *II = MacroNameTok.getIdentifierInfo(); 1220 // Okay, we finally have a valid identifier to undef. 1221 MacroDirective *MD = getMacroDirective(II); 1222 1223 // If the macro is not defined, this is an error. 1224 if (MD == 0) { 1225 Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II; 1226 return; 1227 } 1228 1229 // Note that this macro has now been marked private. 1230 appendMacroDirective(II, AllocateVisibilityMacroDirective( 1231 MacroNameTok.getLocation(), /*IsPublic=*/false)); 1232} 1233 1234//===----------------------------------------------------------------------===// 1235// Preprocessor Include Directive Handling. 1236//===----------------------------------------------------------------------===// 1237 1238/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully 1239/// checked and spelled filename, e.g. as an operand of \#include. This returns 1240/// true if the input filename was in <>'s or false if it were in ""'s. The 1241/// caller is expected to provide a buffer that is large enough to hold the 1242/// spelling of the filename, but is also expected to handle the case when 1243/// this method decides to use a different buffer. 1244bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc, 1245 StringRef &Buffer) { 1246 // Get the text form of the filename. 1247 assert(!Buffer.empty() && "Can't have tokens with empty spellings!"); 1248 1249 // Make sure the filename is <x> or "x". 1250 bool isAngled; 1251 if (Buffer[0] == '<') { 1252 if (Buffer.back() != '>') { 1253 Diag(Loc, diag::err_pp_expects_filename); 1254 Buffer = StringRef(); 1255 return true; 1256 } 1257 isAngled = true; 1258 } else if (Buffer[0] == '"') { 1259 if (Buffer.back() != '"') { 1260 Diag(Loc, diag::err_pp_expects_filename); 1261 Buffer = StringRef(); 1262 return true; 1263 } 1264 isAngled = false; 1265 } else { 1266 Diag(Loc, diag::err_pp_expects_filename); 1267 Buffer = StringRef(); 1268 return true; 1269 } 1270 1271 // Diagnose #include "" as invalid. 1272 if (Buffer.size() <= 2) { 1273 Diag(Loc, diag::err_pp_empty_filename); 1274 Buffer = StringRef(); 1275 return true; 1276 } 1277 1278 // Skip the brackets. 1279 Buffer = Buffer.substr(1, Buffer.size()-2); 1280 return isAngled; 1281} 1282 1283// \brief Handle cases where the \#include name is expanded from a macro 1284// as multiple tokens, which need to be glued together. 1285// 1286// This occurs for code like: 1287// \code 1288// \#define FOO <a/b.h> 1289// \#include FOO 1290// \endcode 1291// because in this case, "<a/b.h>" is returned as 7 tokens, not one. 1292// 1293// This code concatenates and consumes tokens up to the '>' token. It returns 1294// false if the > was found, otherwise it returns true if it finds and consumes 1295// the EOD marker. 1296bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer, 1297 SourceLocation &End) { 1298 Token CurTok; 1299 1300 Lex(CurTok); 1301 while (CurTok.isNot(tok::eod)) { 1302 End = CurTok.getLocation(); 1303 1304 // FIXME: Provide code completion for #includes. 1305 if (CurTok.is(tok::code_completion)) { 1306 setCodeCompletionReached(); 1307 Lex(CurTok); 1308 continue; 1309 } 1310 1311 // Append the spelling of this token to the buffer. If there was a space 1312 // before it, add it now. 1313 if (CurTok.hasLeadingSpace()) 1314 FilenameBuffer.push_back(' '); 1315 1316 // Get the spelling of the token, directly into FilenameBuffer if possible. 1317 unsigned PreAppendSize = FilenameBuffer.size(); 1318 FilenameBuffer.resize(PreAppendSize+CurTok.getLength()); 1319 1320 const char *BufPtr = &FilenameBuffer[PreAppendSize]; 1321 unsigned ActualLen = getSpelling(CurTok, BufPtr); 1322 1323 // If the token was spelled somewhere else, copy it into FilenameBuffer. 1324 if (BufPtr != &FilenameBuffer[PreAppendSize]) 1325 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen); 1326 1327 // Resize FilenameBuffer to the correct size. 1328 if (CurTok.getLength() != ActualLen) 1329 FilenameBuffer.resize(PreAppendSize+ActualLen); 1330 1331 // If we found the '>' marker, return success. 1332 if (CurTok.is(tok::greater)) 1333 return false; 1334 1335 Lex(CurTok); 1336 } 1337 1338 // If we hit the eod marker, emit an error and return true so that the caller 1339 // knows the EOD has been read. 1340 Diag(CurTok.getLocation(), diag::err_pp_expects_filename); 1341 return true; 1342} 1343 1344/// \brief Push a token onto the token stream containing an annotation. 1345static void EnterAnnotationToken(Preprocessor &PP, 1346 SourceLocation Begin, SourceLocation End, 1347 tok::TokenKind Kind, void *AnnotationVal) { 1348 Token *Tok = new Token[1]; 1349 Tok[0].startToken(); 1350 Tok[0].setKind(Kind); 1351 Tok[0].setLocation(Begin); 1352 Tok[0].setAnnotationEndLoc(End); 1353 Tok[0].setAnnotationValue(AnnotationVal); 1354 PP.EnterTokenStream(Tok, 1, true, true); 1355} 1356 1357/// HandleIncludeDirective - The "\#include" tokens have just been read, read 1358/// the file to be included from the lexer, then include it! This is a common 1359/// routine with functionality shared between \#include, \#include_next and 1360/// \#import. LookupFrom is set when this is a \#include_next directive, it 1361/// specifies the file to start searching from. 1362void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc, 1363 Token &IncludeTok, 1364 const DirectoryLookup *LookupFrom, 1365 bool isImport) { 1366 1367 Token FilenameTok; 1368 CurPPLexer->LexIncludeFilename(FilenameTok); 1369 1370 // Reserve a buffer to get the spelling. 1371 SmallString<128> FilenameBuffer; 1372 StringRef Filename; 1373 SourceLocation End; 1374 SourceLocation CharEnd; // the end of this directive, in characters 1375 1376 switch (FilenameTok.getKind()) { 1377 case tok::eod: 1378 // If the token kind is EOD, the error has already been diagnosed. 1379 return; 1380 1381 case tok::angle_string_literal: 1382 case tok::string_literal: 1383 Filename = getSpelling(FilenameTok, FilenameBuffer); 1384 End = FilenameTok.getLocation(); 1385 CharEnd = End.getLocWithOffset(FilenameTok.getLength()); 1386 break; 1387 1388 case tok::less: 1389 // This could be a <foo/bar.h> file coming from a macro expansion. In this 1390 // case, glue the tokens together into FilenameBuffer and interpret those. 1391 FilenameBuffer.push_back('<'); 1392 if (ConcatenateIncludeName(FilenameBuffer, End)) 1393 return; // Found <eod> but no ">"? Diagnostic already emitted. 1394 Filename = FilenameBuffer.str(); 1395 CharEnd = End.getLocWithOffset(1); 1396 break; 1397 default: 1398 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename); 1399 DiscardUntilEndOfDirective(); 1400 return; 1401 } 1402 1403 CharSourceRange FilenameRange 1404 = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd); 1405 StringRef OriginalFilename = Filename; 1406 bool isAngled = 1407 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename); 1408 // If GetIncludeFilenameSpelling set the start ptr to null, there was an 1409 // error. 1410 if (Filename.empty()) { 1411 DiscardUntilEndOfDirective(); 1412 return; 1413 } 1414 1415 // Verify that there is nothing after the filename, other than EOD. Note that 1416 // we allow macros that expand to nothing after the filename, because this 1417 // falls into the category of "#include pp-tokens new-line" specified in 1418 // C99 6.10.2p4. 1419 CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true); 1420 1421 // Check that we don't have infinite #include recursion. 1422 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) { 1423 Diag(FilenameTok, diag::err_pp_include_too_deep); 1424 return; 1425 } 1426 1427 // Complain about attempts to #include files in an audit pragma. 1428 if (PragmaARCCFCodeAuditedLoc.isValid()) { 1429 Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited); 1430 Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here); 1431 1432 // Immediately leave the pragma. 1433 PragmaARCCFCodeAuditedLoc = SourceLocation(); 1434 } 1435 1436 if (HeaderInfo.HasIncludeAliasMap()) { 1437 // Map the filename with the brackets still attached. If the name doesn't 1438 // map to anything, fall back on the filename we've already gotten the 1439 // spelling for. 1440 StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename); 1441 if (!NewName.empty()) 1442 Filename = NewName; 1443 } 1444 1445 // Search include directories. 1446 const DirectoryLookup *CurDir; 1447 SmallString<1024> SearchPath; 1448 SmallString<1024> RelativePath; 1449 // We get the raw path only if we have 'Callbacks' to which we later pass 1450 // the path. 1451 ModuleMap::KnownHeader SuggestedModule; 1452 SourceLocation FilenameLoc = FilenameTok.getLocation(); 1453 SmallString<128> NormalizedPath; 1454 if (LangOpts.MSVCCompat) { 1455 NormalizedPath = Filename.str(); 1456 llvm::sys::fs::normalize_separators(NormalizedPath); 1457 } 1458 const FileEntry *File = LookupFile( 1459 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, 1460 isAngled, LookupFrom, CurDir, Callbacks ? &SearchPath : NULL, 1461 Callbacks ? &RelativePath : NULL, 1462 HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule : 0); 1463 1464 if (Callbacks) { 1465 if (!File) { 1466 // Give the clients a chance to recover. 1467 SmallString<128> RecoveryPath; 1468 if (Callbacks->FileNotFound(Filename, RecoveryPath)) { 1469 if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) { 1470 // Add the recovery path to the list of search paths. 1471 DirectoryLookup DL(DE, SrcMgr::C_User, false); 1472 HeaderInfo.AddSearchPath(DL, isAngled); 1473 1474 // Try the lookup again, skipping the cache. 1475 File = LookupFile(FilenameLoc, 1476 LangOpts.MSVCCompat ? NormalizedPath.c_str() 1477 : Filename, 1478 isAngled, LookupFrom, CurDir, 0, 0, 1479 HeaderInfo.getHeaderSearchOpts().ModuleMaps 1480 ? &SuggestedModule 1481 : 0, 1482 /*SkipCache*/ true); 1483 } 1484 } 1485 } 1486 1487 if (!SuggestedModule || !getLangOpts().Modules) { 1488 // Notify the callback object that we've seen an inclusion directive. 1489 Callbacks->InclusionDirective(HashLoc, IncludeTok, 1490 LangOpts.MSVCCompat ? NormalizedPath.c_str() 1491 : Filename, 1492 isAngled, FilenameRange, File, SearchPath, 1493 RelativePath, /*ImportedModule=*/0); 1494 } 1495 } 1496 1497 if (File == 0) { 1498 if (!SuppressIncludeNotFoundError) { 1499 // If the file could not be located and it was included via angle 1500 // brackets, we can attempt a lookup as though it were a quoted path to 1501 // provide the user with a possible fixit. 1502 if (isAngled) { 1503 File = LookupFile( 1504 FilenameLoc, LangOpts.MSVCCompat ? NormalizedPath.c_str() : Filename, 1505 false, LookupFrom, CurDir, Callbacks ? &SearchPath : 0, 1506 Callbacks ? &RelativePath : 0, 1507 HeaderInfo.getHeaderSearchOpts().ModuleMaps ? &SuggestedModule : 0); 1508 if (File) { 1509 SourceRange Range(FilenameTok.getLocation(), CharEnd); 1510 Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) << 1511 Filename << 1512 FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\""); 1513 } 1514 } 1515 // If the file is still not found, just go with the vanilla diagnostic 1516 if (!File) 1517 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename; 1518 } 1519 if (!File) 1520 return; 1521 } 1522 1523 // If we are supposed to import a module rather than including the header, 1524 // do so now. 1525 if (SuggestedModule && getLangOpts().Modules) { 1526 // Compute the module access path corresponding to this module. 1527 // FIXME: Should we have a second loadModule() overload to avoid this 1528 // extra lookup step? 1529 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; 1530 for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent) 1531 Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name), 1532 FilenameTok.getLocation())); 1533 std::reverse(Path.begin(), Path.end()); 1534 1535 // Warn that we're replacing the include/import with a module import. 1536 SmallString<128> PathString; 1537 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 1538 if (I) 1539 PathString += '.'; 1540 PathString += Path[I].first->getName(); 1541 } 1542 int IncludeKind = 0; 1543 1544 switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) { 1545 case tok::pp_include: 1546 IncludeKind = 0; 1547 break; 1548 1549 case tok::pp_import: 1550 IncludeKind = 1; 1551 break; 1552 1553 case tok::pp_include_next: 1554 IncludeKind = 2; 1555 break; 1556 1557 case tok::pp___include_macros: 1558 IncludeKind = 3; 1559 break; 1560 1561 default: 1562 llvm_unreachable("unknown include directive kind"); 1563 } 1564 1565 // Determine whether we are actually building the module that this 1566 // include directive maps to. 1567 bool BuildingImportedModule 1568 = Path[0].first->getName() == getLangOpts().CurrentModule; 1569 1570 if (!BuildingImportedModule && getLangOpts().ObjC2) { 1571 // If we're not building the imported module, warn that we're going 1572 // to automatically turn this inclusion directive into a module import. 1573 // We only do this in Objective-C, where we have a module-import syntax. 1574 CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd), 1575 /*IsTokenRange=*/false); 1576 Diag(HashLoc, diag::warn_auto_module_import) 1577 << IncludeKind << PathString 1578 << FixItHint::CreateReplacement(ReplaceRange, 1579 "@import " + PathString.str().str() + ";"); 1580 } 1581 1582 // Load the module. Only make macros visible. We'll make the declarations 1583 // visible when the parser gets here. 1584 Module::NameVisibilityKind Visibility = Module::MacrosVisible; 1585 ModuleLoadResult Imported 1586 = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility, 1587 /*IsIncludeDirective=*/true); 1588 assert((Imported == 0 || Imported == SuggestedModule.getModule()) && 1589 "the imported module is different than the suggested one"); 1590 1591 if (!Imported && hadModuleLoaderFatalFailure()) { 1592 // With a fatal failure in the module loader, we abort parsing. 1593 Token &Result = IncludeTok; 1594 if (CurLexer) { 1595 Result.startToken(); 1596 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof); 1597 CurLexer->cutOffLexing(); 1598 } else { 1599 assert(CurPTHLexer && "#include but no current lexer set!"); 1600 CurPTHLexer->getEOF(Result); 1601 } 1602 return; 1603 } 1604 1605 // If this header isn't part of the module we're building, we're done. 1606 if (!BuildingImportedModule && Imported) { 1607 if (Callbacks) { 1608 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, 1609 FilenameRange, File, 1610 SearchPath, RelativePath, Imported); 1611 } 1612 1613 if (IncludeKind != 3) { 1614 // Let the parser know that we hit a module import, and it should 1615 // make the module visible. 1616 // FIXME: Produce this as the current token directly, rather than 1617 // allocating a new token for it. 1618 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_include, 1619 Imported); 1620 } 1621 return; 1622 } 1623 1624 // If we failed to find a submodule that we expected to find, we can 1625 // continue. Otherwise, there's an error in the included file, so we 1626 // don't want to include it. 1627 if (!BuildingImportedModule && !Imported.isMissingExpected()) { 1628 return; 1629 } 1630 } 1631 1632 if (Callbacks && SuggestedModule) { 1633 // We didn't notify the callback object that we've seen an inclusion 1634 // directive before. Now that we are parsing the include normally and not 1635 // turning it to a module import, notify the callback object. 1636 Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, 1637 FilenameRange, File, 1638 SearchPath, RelativePath, 1639 /*ImportedModule=*/0); 1640 } 1641 1642 // The #included file will be considered to be a system header if either it is 1643 // in a system include directory, or if the #includer is a system include 1644 // header. 1645 SrcMgr::CharacteristicKind FileCharacter = 1646 std::max(HeaderInfo.getFileDirFlavor(File), 1647 SourceMgr.getFileCharacteristic(FilenameTok.getLocation())); 1648 1649 // Ask HeaderInfo if we should enter this #include file. If not, #including 1650 // this file will have no effect. 1651 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) { 1652 if (Callbacks) 1653 Callbacks->FileSkipped(*File, FilenameTok, FileCharacter); 1654 return; 1655 } 1656 1657 // Look up the file, create a File ID for it. 1658 SourceLocation IncludePos = End; 1659 // If the filename string was the result of macro expansions, set the include 1660 // position on the file where it will be included and after the expansions. 1661 if (IncludePos.isMacroID()) 1662 IncludePos = SourceMgr.getExpansionRange(IncludePos).second; 1663 FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter); 1664 assert(!FID.isInvalid() && "Expected valid file ID"); 1665 1666 // Determine if we're switching to building a new submodule, and which one. 1667 ModuleMap::KnownHeader BuildingModule; 1668 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty()) { 1669 Module *RequestingModule = getModuleForLocation(FilenameLoc); 1670 BuildingModule = 1671 HeaderInfo.getModuleMap().findModuleForHeader(File, RequestingModule); 1672 } 1673 1674 // If all is good, enter the new file! 1675 if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation())) 1676 return; 1677 1678 // If we're walking into another part of the same module, let the parser 1679 // know that any future declarations are within that other submodule. 1680 if (BuildingModule) { 1681 assert(!CurSubmodule && "should not have marked this as a module yet"); 1682 CurSubmodule = BuildingModule.getModule(); 1683 1684 EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_begin, 1685 CurSubmodule); 1686 } 1687} 1688 1689/// HandleIncludeNextDirective - Implements \#include_next. 1690/// 1691void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc, 1692 Token &IncludeNextTok) { 1693 Diag(IncludeNextTok, diag::ext_pp_include_next_directive); 1694 1695 // #include_next is like #include, except that we start searching after 1696 // the current found directory. If we can't do this, issue a 1697 // diagnostic. 1698 const DirectoryLookup *Lookup = CurDirLookup; 1699 if (isInPrimaryFile()) { 1700 Lookup = 0; 1701 Diag(IncludeNextTok, diag::pp_include_next_in_primary); 1702 } else if (Lookup == 0) { 1703 Diag(IncludeNextTok, diag::pp_include_next_absolute_path); 1704 } else { 1705 // Start looking up in the next directory. 1706 ++Lookup; 1707 } 1708 1709 return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup); 1710} 1711 1712/// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode 1713void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) { 1714 // The Microsoft #import directive takes a type library and generates header 1715 // files from it, and includes those. This is beyond the scope of what clang 1716 // does, so we ignore it and error out. However, #import can optionally have 1717 // trailing attributes that span multiple lines. We're going to eat those 1718 // so we can continue processing from there. 1719 Diag(Tok, diag::err_pp_import_directive_ms ); 1720 1721 // Read tokens until we get to the end of the directive. Note that the 1722 // directive can be split over multiple lines using the backslash character. 1723 DiscardUntilEndOfDirective(); 1724} 1725 1726/// HandleImportDirective - Implements \#import. 1727/// 1728void Preprocessor::HandleImportDirective(SourceLocation HashLoc, 1729 Token &ImportTok) { 1730 if (!LangOpts.ObjC1) { // #import is standard for ObjC. 1731 if (LangOpts.MSVCCompat) 1732 return HandleMicrosoftImportDirective(ImportTok); 1733 Diag(ImportTok, diag::ext_pp_import_directive); 1734 } 1735 return HandleIncludeDirective(HashLoc, ImportTok, 0, true); 1736} 1737 1738/// HandleIncludeMacrosDirective - The -imacros command line option turns into a 1739/// pseudo directive in the predefines buffer. This handles it by sucking all 1740/// tokens through the preprocessor and discarding them (only keeping the side 1741/// effects on the preprocessor). 1742void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc, 1743 Token &IncludeMacrosTok) { 1744 // This directive should only occur in the predefines buffer. If not, emit an 1745 // error and reject it. 1746 SourceLocation Loc = IncludeMacrosTok.getLocation(); 1747 if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) { 1748 Diag(IncludeMacrosTok.getLocation(), 1749 diag::pp_include_macros_out_of_predefines); 1750 DiscardUntilEndOfDirective(); 1751 return; 1752 } 1753 1754 // Treat this as a normal #include for checking purposes. If this is 1755 // successful, it will push a new lexer onto the include stack. 1756 HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false); 1757 1758 Token TmpTok; 1759 do { 1760 Lex(TmpTok); 1761 assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!"); 1762 } while (TmpTok.isNot(tok::hashhash)); 1763} 1764 1765//===----------------------------------------------------------------------===// 1766// Preprocessor Macro Directive Handling. 1767//===----------------------------------------------------------------------===// 1768 1769/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro 1770/// definition has just been read. Lex the rest of the arguments and the 1771/// closing ), updating MI with what we learn. Return true if an error occurs 1772/// parsing the arg list. 1773bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) { 1774 SmallVector<IdentifierInfo*, 32> Arguments; 1775 1776 while (1) { 1777 LexUnexpandedToken(Tok); 1778 switch (Tok.getKind()) { 1779 case tok::r_paren: 1780 // Found the end of the argument list. 1781 if (Arguments.empty()) // #define FOO() 1782 return false; 1783 // Otherwise we have #define FOO(A,) 1784 Diag(Tok, diag::err_pp_expected_ident_in_arg_list); 1785 return true; 1786 case tok::ellipsis: // #define X(... -> C99 varargs 1787 if (!LangOpts.C99) 1788 Diag(Tok, LangOpts.CPlusPlus11 ? 1789 diag::warn_cxx98_compat_variadic_macro : 1790 diag::ext_variadic_macro); 1791 1792 // OpenCL v1.2 s6.9.e: variadic macros are not supported. 1793 if (LangOpts.OpenCL) { 1794 Diag(Tok, diag::err_pp_opencl_variadic_macros); 1795 return true; 1796 } 1797 1798 // Lex the token after the identifier. 1799 LexUnexpandedToken(Tok); 1800 if (Tok.isNot(tok::r_paren)) { 1801 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def); 1802 return true; 1803 } 1804 // Add the __VA_ARGS__ identifier as an argument. 1805 Arguments.push_back(Ident__VA_ARGS__); 1806 MI->setIsC99Varargs(); 1807 MI->setArgumentList(&Arguments[0], Arguments.size(), BP); 1808 return false; 1809 case tok::eod: // #define X( 1810 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def); 1811 return true; 1812 default: 1813 // Handle keywords and identifiers here to accept things like 1814 // #define Foo(for) for. 1815 IdentifierInfo *II = Tok.getIdentifierInfo(); 1816 if (II == 0) { 1817 // #define X(1 1818 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list); 1819 return true; 1820 } 1821 1822 // If this is already used as an argument, it is used multiple times (e.g. 1823 // #define X(A,A. 1824 if (std::find(Arguments.begin(), Arguments.end(), II) != 1825 Arguments.end()) { // C99 6.10.3p6 1826 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II; 1827 return true; 1828 } 1829 1830 // Add the argument to the macro info. 1831 Arguments.push_back(II); 1832 1833 // Lex the token after the identifier. 1834 LexUnexpandedToken(Tok); 1835 1836 switch (Tok.getKind()) { 1837 default: // #define X(A B 1838 Diag(Tok, diag::err_pp_expected_comma_in_arg_list); 1839 return true; 1840 case tok::r_paren: // #define X(A) 1841 MI->setArgumentList(&Arguments[0], Arguments.size(), BP); 1842 return false; 1843 case tok::comma: // #define X(A, 1844 break; 1845 case tok::ellipsis: // #define X(A... -> GCC extension 1846 // Diagnose extension. 1847 Diag(Tok, diag::ext_named_variadic_macro); 1848 1849 // Lex the token after the identifier. 1850 LexUnexpandedToken(Tok); 1851 if (Tok.isNot(tok::r_paren)) { 1852 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def); 1853 return true; 1854 } 1855 1856 MI->setIsGNUVarargs(); 1857 MI->setArgumentList(&Arguments[0], Arguments.size(), BP); 1858 return false; 1859 } 1860 } 1861 } 1862} 1863 1864/// HandleDefineDirective - Implements \#define. This consumes the entire macro 1865/// line then lets the caller lex the next real token. 1866void Preprocessor::HandleDefineDirective(Token &DefineTok, 1867 bool ImmediatelyAfterHeaderGuard) { 1868 ++NumDefined; 1869 1870 Token MacroNameTok; 1871 ReadMacroName(MacroNameTok, 1); 1872 1873 // Error reading macro name? If so, diagnostic already issued. 1874 if (MacroNameTok.is(tok::eod)) 1875 return; 1876 1877 Token LastTok = MacroNameTok; 1878 1879 // If we are supposed to keep comments in #defines, reenable comment saving 1880 // mode. 1881 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments); 1882 1883 // Create the new macro. 1884 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation()); 1885 1886 Token Tok; 1887 LexUnexpandedToken(Tok); 1888 1889 // If this is a function-like macro definition, parse the argument list, 1890 // marking each of the identifiers as being used as macro arguments. Also, 1891 // check other constraints on the first token of the macro body. 1892 if (Tok.is(tok::eod)) { 1893 if (ImmediatelyAfterHeaderGuard) { 1894 // Save this macro information since it may part of a header guard. 1895 CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(), 1896 MacroNameTok.getLocation()); 1897 } 1898 // If there is no body to this macro, we have no special handling here. 1899 } else if (Tok.hasLeadingSpace()) { 1900 // This is a normal token with leading space. Clear the leading space 1901 // marker on the first token to get proper expansion. 1902 Tok.clearFlag(Token::LeadingSpace); 1903 } else if (Tok.is(tok::l_paren)) { 1904 // This is a function-like macro definition. Read the argument list. 1905 MI->setIsFunctionLike(); 1906 if (ReadMacroDefinitionArgList(MI, LastTok)) { 1907 // Forget about MI. 1908 ReleaseMacroInfo(MI); 1909 // Throw away the rest of the line. 1910 if (CurPPLexer->ParsingPreprocessorDirective) 1911 DiscardUntilEndOfDirective(); 1912 return; 1913 } 1914 1915 // If this is a definition of a variadic C99 function-like macro, not using 1916 // the GNU named varargs extension, enabled __VA_ARGS__. 1917 1918 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro. 1919 // This gets unpoisoned where it is allowed. 1920 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!"); 1921 if (MI->isC99Varargs()) 1922 Ident__VA_ARGS__->setIsPoisoned(false); 1923 1924 // Read the first token after the arg list for down below. 1925 LexUnexpandedToken(Tok); 1926 } else if (LangOpts.C99 || LangOpts.CPlusPlus11) { 1927 // C99 requires whitespace between the macro definition and the body. Emit 1928 // a diagnostic for something like "#define X+". 1929 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name); 1930 } else { 1931 // C90 6.8 TC1 says: "In the definition of an object-like macro, if the 1932 // first character of a replacement list is not a character required by 1933 // subclause 5.2.1, then there shall be white-space separation between the 1934 // identifier and the replacement list.". 5.2.1 lists this set: 1935 // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which 1936 // is irrelevant here. 1937 bool isInvalid = false; 1938 if (Tok.is(tok::at)) // @ is not in the list above. 1939 isInvalid = true; 1940 else if (Tok.is(tok::unknown)) { 1941 // If we have an unknown token, it is something strange like "`". Since 1942 // all of valid characters would have lexed into a single character 1943 // token of some sort, we know this is not a valid case. 1944 isInvalid = true; 1945 } 1946 if (isInvalid) 1947 Diag(Tok, diag::ext_missing_whitespace_after_macro_name); 1948 else 1949 Diag(Tok, diag::warn_missing_whitespace_after_macro_name); 1950 } 1951 1952 if (!Tok.is(tok::eod)) 1953 LastTok = Tok; 1954 1955 // Read the rest of the macro body. 1956 if (MI->isObjectLike()) { 1957 // Object-like macros are very simple, just read their body. 1958 while (Tok.isNot(tok::eod)) { 1959 LastTok = Tok; 1960 MI->AddTokenToBody(Tok); 1961 // Get the next token of the macro. 1962 LexUnexpandedToken(Tok); 1963 } 1964 1965 } else { 1966 // Otherwise, read the body of a function-like macro. While we are at it, 1967 // check C99 6.10.3.2p1: ensure that # operators are followed by macro 1968 // parameters in function-like macro expansions. 1969 while (Tok.isNot(tok::eod)) { 1970 LastTok = Tok; 1971 1972 if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) { 1973 MI->AddTokenToBody(Tok); 1974 1975 // Get the next token of the macro. 1976 LexUnexpandedToken(Tok); 1977 continue; 1978 } 1979 1980 // If we're in -traditional mode, then we should ignore stringification 1981 // and token pasting. Mark the tokens as unknown so as not to confuse 1982 // things. 1983 if (getLangOpts().TraditionalCPP) { 1984 Tok.setKind(tok::unknown); 1985 MI->AddTokenToBody(Tok); 1986 1987 // Get the next token of the macro. 1988 LexUnexpandedToken(Tok); 1989 continue; 1990 } 1991 1992 if (Tok.is(tok::hashhash)) { 1993 1994 // If we see token pasting, check if it looks like the gcc comma 1995 // pasting extension. We'll use this information to suppress 1996 // diagnostics later on. 1997 1998 // Get the next token of the macro. 1999 LexUnexpandedToken(Tok); 2000 2001 if (Tok.is(tok::eod)) { 2002 MI->AddTokenToBody(LastTok); 2003 break; 2004 } 2005 2006 unsigned NumTokens = MI->getNumTokens(); 2007 if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ && 2008 MI->getReplacementToken(NumTokens-1).is(tok::comma)) 2009 MI->setHasCommaPasting(); 2010 2011 // Things look ok, add the '##' token to the macro. 2012 MI->AddTokenToBody(LastTok); 2013 continue; 2014 } 2015 2016 // Get the next token of the macro. 2017 LexUnexpandedToken(Tok); 2018 2019 // Check for a valid macro arg identifier. 2020 if (Tok.getIdentifierInfo() == 0 || 2021 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) { 2022 2023 // If this is assembler-with-cpp mode, we accept random gibberish after 2024 // the '#' because '#' is often a comment character. However, change 2025 // the kind of the token to tok::unknown so that the preprocessor isn't 2026 // confused. 2027 if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) { 2028 LastTok.setKind(tok::unknown); 2029 MI->AddTokenToBody(LastTok); 2030 continue; 2031 } else { 2032 Diag(Tok, diag::err_pp_stringize_not_parameter); 2033 ReleaseMacroInfo(MI); 2034 2035 // Disable __VA_ARGS__ again. 2036 Ident__VA_ARGS__->setIsPoisoned(true); 2037 return; 2038 } 2039 } 2040 2041 // Things look ok, add the '#' and param name tokens to the macro. 2042 MI->AddTokenToBody(LastTok); 2043 MI->AddTokenToBody(Tok); 2044 LastTok = Tok; 2045 2046 // Get the next token of the macro. 2047 LexUnexpandedToken(Tok); 2048 } 2049 } 2050 2051 2052 // Disable __VA_ARGS__ again. 2053 Ident__VA_ARGS__->setIsPoisoned(true); 2054 2055 // Check that there is no paste (##) operator at the beginning or end of the 2056 // replacement list. 2057 unsigned NumTokens = MI->getNumTokens(); 2058 if (NumTokens != 0) { 2059 if (MI->getReplacementToken(0).is(tok::hashhash)) { 2060 Diag(MI->getReplacementToken(0), diag::err_paste_at_start); 2061 ReleaseMacroInfo(MI); 2062 return; 2063 } 2064 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) { 2065 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end); 2066 ReleaseMacroInfo(MI); 2067 return; 2068 } 2069 } 2070 2071 MI->setDefinitionEndLoc(LastTok.getLocation()); 2072 2073 // Finally, if this identifier already had a macro defined for it, verify that 2074 // the macro bodies are identical, and issue diagnostics if they are not. 2075 if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) { 2076 // It is very common for system headers to have tons of macro redefinitions 2077 // and for warnings to be disabled in system headers. If this is the case, 2078 // then don't bother calling MacroInfo::isIdenticalTo. 2079 if (!getDiagnostics().getSuppressSystemWarnings() || 2080 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) { 2081 if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused()) 2082 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used); 2083 2084 // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and 2085 // C++ [cpp.predefined]p4, but allow it as an extension. 2086 if (OtherMI->isBuiltinMacro()) 2087 Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro); 2088 // Macros must be identical. This means all tokens and whitespace 2089 // separation must be the same. C99 6.10.3p2. 2090 else if (!OtherMI->isAllowRedefinitionsWithoutWarning() && 2091 !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) { 2092 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef) 2093 << MacroNameTok.getIdentifierInfo(); 2094 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition); 2095 } 2096 } 2097 if (OtherMI->isWarnIfUnused()) 2098 WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc()); 2099 } 2100 2101 DefMacroDirective *MD = 2102 appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI); 2103 2104 assert(!MI->isUsed()); 2105 // If we need warning for not using the macro, add its location in the 2106 // warn-because-unused-macro set. If it gets used it will be removed from set. 2107 if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) && 2108 Diags->getDiagnosticLevel(diag::pp_macro_not_used, 2109 MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) { 2110 MI->setIsWarnIfUnused(true); 2111 WarnUnusedMacroLocs.insert(MI->getDefinitionLoc()); 2112 } 2113 2114 // If the callbacks want to know, tell them about the macro definition. 2115 if (Callbacks) 2116 Callbacks->MacroDefined(MacroNameTok, MD); 2117} 2118 2119/// HandleUndefDirective - Implements \#undef. 2120/// 2121void Preprocessor::HandleUndefDirective(Token &UndefTok) { 2122 ++NumUndefined; 2123 2124 Token MacroNameTok; 2125 ReadMacroName(MacroNameTok, 2); 2126 2127 // Error reading macro name? If so, diagnostic already issued. 2128 if (MacroNameTok.is(tok::eod)) 2129 return; 2130 2131 // Check to see if this is the last token on the #undef line. 2132 CheckEndOfDirective("undef"); 2133 2134 // Okay, we finally have a valid identifier to undef. 2135 MacroDirective *MD = getMacroDirective(MacroNameTok.getIdentifierInfo()); 2136 const MacroInfo *MI = MD ? MD->getMacroInfo() : 0; 2137 2138 // If the callbacks want to know, tell them about the macro #undef. 2139 // Note: no matter if the macro was defined or not. 2140 if (Callbacks) 2141 Callbacks->MacroUndefined(MacroNameTok, MD); 2142 2143 // If the macro is not defined, this is a noop undef, just return. 2144 if (MI == 0) return; 2145 2146 if (!MI->isUsed() && MI->isWarnIfUnused()) 2147 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used); 2148 2149 if (MI->isWarnIfUnused()) 2150 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc()); 2151 2152 appendMacroDirective(MacroNameTok.getIdentifierInfo(), 2153 AllocateUndefMacroDirective(MacroNameTok.getLocation())); 2154} 2155 2156 2157//===----------------------------------------------------------------------===// 2158// Preprocessor Conditional Directive Handling. 2159//===----------------------------------------------------------------------===// 2160 2161/// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef 2162/// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is 2163/// true if any tokens have been returned or pp-directives activated before this 2164/// \#ifndef has been lexed. 2165/// 2166void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef, 2167 bool ReadAnyTokensBeforeDirective) { 2168 ++NumIf; 2169 Token DirectiveTok = Result; 2170 2171 Token MacroNameTok; 2172 ReadMacroName(MacroNameTok); 2173 2174 // Error reading macro name? If so, diagnostic already issued. 2175 if (MacroNameTok.is(tok::eod)) { 2176 // Skip code until we get to #endif. This helps with recovery by not 2177 // emitting an error when the #endif is reached. 2178 SkipExcludedConditionalBlock(DirectiveTok.getLocation(), 2179 /*Foundnonskip*/false, /*FoundElse*/false); 2180 return; 2181 } 2182 2183 // Check to see if this is the last token on the #if[n]def line. 2184 CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef"); 2185 2186 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo(); 2187 MacroDirective *MD = getMacroDirective(MII); 2188 MacroInfo *MI = MD ? MD->getMacroInfo() : 0; 2189 2190 if (CurPPLexer->getConditionalStackDepth() == 0) { 2191 // If the start of a top-level #ifdef and if the macro is not defined, 2192 // inform MIOpt that this might be the start of a proper include guard. 2193 // Otherwise it is some other form of unknown conditional which we can't 2194 // handle. 2195 if (!ReadAnyTokensBeforeDirective && MI == 0) { 2196 assert(isIfndef && "#ifdef shouldn't reach here"); 2197 CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation()); 2198 } else 2199 CurPPLexer->MIOpt.EnterTopLevelConditional(); 2200 } 2201 2202 // If there is a macro, process it. 2203 if (MI) // Mark it used. 2204 markMacroAsUsed(MI); 2205 2206 if (Callbacks) { 2207 if (isIfndef) 2208 Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD); 2209 else 2210 Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD); 2211 } 2212 2213 // Should we include the stuff contained by this directive? 2214 if (!MI == isIfndef) { 2215 // Yes, remember that we are inside a conditional, then lex the next token. 2216 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(), 2217 /*wasskip*/false, /*foundnonskip*/true, 2218 /*foundelse*/false); 2219 } else { 2220 // No, skip the contents of this block. 2221 SkipExcludedConditionalBlock(DirectiveTok.getLocation(), 2222 /*Foundnonskip*/false, 2223 /*FoundElse*/false); 2224 } 2225} 2226 2227/// HandleIfDirective - Implements the \#if directive. 2228/// 2229void Preprocessor::HandleIfDirective(Token &IfToken, 2230 bool ReadAnyTokensBeforeDirective) { 2231 ++NumIf; 2232 2233 // Parse and evaluate the conditional expression. 2234 IdentifierInfo *IfNDefMacro = 0; 2235 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation(); 2236 const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro); 2237 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation(); 2238 2239 // If this condition is equivalent to #ifndef X, and if this is the first 2240 // directive seen, handle it for the multiple-include optimization. 2241 if (CurPPLexer->getConditionalStackDepth() == 0) { 2242 if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue) 2243 // FIXME: Pass in the location of the macro name, not the 'if' token. 2244 CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation()); 2245 else 2246 CurPPLexer->MIOpt.EnterTopLevelConditional(); 2247 } 2248 2249 if (Callbacks) 2250 Callbacks->If(IfToken.getLocation(), 2251 SourceRange(ConditionalBegin, ConditionalEnd), 2252 (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False)); 2253 2254 // Should we include the stuff contained by this directive? 2255 if (ConditionalTrue) { 2256 // Yes, remember that we are inside a conditional, then lex the next token. 2257 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false, 2258 /*foundnonskip*/true, /*foundelse*/false); 2259 } else { 2260 // No, skip the contents of this block. 2261 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false, 2262 /*FoundElse*/false); 2263 } 2264} 2265 2266/// HandleEndifDirective - Implements the \#endif directive. 2267/// 2268void Preprocessor::HandleEndifDirective(Token &EndifToken) { 2269 ++NumEndif; 2270 2271 // Check that this is the whole directive. 2272 CheckEndOfDirective("endif"); 2273 2274 PPConditionalInfo CondInfo; 2275 if (CurPPLexer->popConditionalLevel(CondInfo)) { 2276 // No conditionals on the stack: this is an #endif without an #if. 2277 Diag(EndifToken, diag::err_pp_endif_without_if); 2278 return; 2279 } 2280 2281 // If this the end of a top-level #endif, inform MIOpt. 2282 if (CurPPLexer->getConditionalStackDepth() == 0) 2283 CurPPLexer->MIOpt.ExitTopLevelConditional(); 2284 2285 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode && 2286 "This code should only be reachable in the non-skipping case!"); 2287 2288 if (Callbacks) 2289 Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc); 2290} 2291 2292/// HandleElseDirective - Implements the \#else directive. 2293/// 2294void Preprocessor::HandleElseDirective(Token &Result) { 2295 ++NumElse; 2296 2297 // #else directive in a non-skipping conditional... start skipping. 2298 CheckEndOfDirective("else"); 2299 2300 PPConditionalInfo CI; 2301 if (CurPPLexer->popConditionalLevel(CI)) { 2302 Diag(Result, diag::pp_err_else_without_if); 2303 return; 2304 } 2305 2306 // If this is a top-level #else, inform the MIOpt. 2307 if (CurPPLexer->getConditionalStackDepth() == 0) 2308 CurPPLexer->MIOpt.EnterTopLevelConditional(); 2309 2310 // If this is a #else with a #else before it, report the error. 2311 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else); 2312 2313 if (Callbacks) 2314 Callbacks->Else(Result.getLocation(), CI.IfLoc); 2315 2316 // Finally, skip the rest of the contents of this block. 2317 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true, 2318 /*FoundElse*/true, Result.getLocation()); 2319} 2320 2321/// HandleElifDirective - Implements the \#elif directive. 2322/// 2323void Preprocessor::HandleElifDirective(Token &ElifToken) { 2324 ++NumElse; 2325 2326 // #elif directive in a non-skipping conditional... start skipping. 2327 // We don't care what the condition is, because we will always skip it (since 2328 // the block immediately before it was included). 2329 const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation(); 2330 DiscardUntilEndOfDirective(); 2331 const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation(); 2332 2333 PPConditionalInfo CI; 2334 if (CurPPLexer->popConditionalLevel(CI)) { 2335 Diag(ElifToken, diag::pp_err_elif_without_if); 2336 return; 2337 } 2338 2339 // If this is a top-level #elif, inform the MIOpt. 2340 if (CurPPLexer->getConditionalStackDepth() == 0) 2341 CurPPLexer->MIOpt.EnterTopLevelConditional(); 2342 2343 // If this is a #elif with a #else before it, report the error. 2344 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else); 2345 2346 if (Callbacks) 2347 Callbacks->Elif(ElifToken.getLocation(), 2348 SourceRange(ConditionalBegin, ConditionalEnd), 2349 PPCallbacks::CVK_NotEvaluated, CI.IfLoc); 2350 2351 // Finally, skip the rest of the contents of this block. 2352 SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true, 2353 /*FoundElse*/CI.FoundElse, 2354 ElifToken.getLocation()); 2355} 2356