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