PPDirectives.cpp revision cf29e0716bb3ecbbc15b74cd648367d6b075fdf0
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/Basic/SourceManager.h" 20#include "llvm/ADT/APInt.h" 21using namespace clang; 22 23//===----------------------------------------------------------------------===// 24// Utility Methods for Preprocessor Directive Handling. 25//===----------------------------------------------------------------------===// 26 27MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) { 28 MacroInfo *MI; 29 30 if (!MICache.empty()) { 31 MI = MICache.back(); 32 MICache.pop_back(); 33 } else 34 MI = (MacroInfo*) BP.Allocate<MacroInfo>(); 35 new (MI) MacroInfo(L); 36 return MI; 37} 38 39/// ReleaseMacroInfo - Release the specified MacroInfo. This memory will 40/// be reused for allocating new MacroInfo objects. 41void Preprocessor::ReleaseMacroInfo(MacroInfo* MI) { 42 MICache.push_back(MI); 43 MI->FreeArgumentList(); 44} 45 46 47/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the 48/// current line until the tok::eom token is found. 49void Preprocessor::DiscardUntilEndOfDirective() { 50 Token Tmp; 51 do { 52 LexUnexpandedToken(Tmp); 53 } while (Tmp.isNot(tok::eom)); 54} 55 56/// ReadMacroName - Lex and validate a macro name, which occurs after a 57/// #define or #undef. This sets the token kind to eom and discards the rest 58/// of the macro line if the macro name is invalid. isDefineUndef is 1 if 59/// this is due to a a #define, 2 if #undef directive, 0 if it is something 60/// else (e.g. #ifdef). 61void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) { 62 // Read the token, don't allow macro expansion on it. 63 LexUnexpandedToken(MacroNameTok); 64 65 // Missing macro name? 66 if (MacroNameTok.is(tok::eom)) { 67 Diag(MacroNameTok, diag::err_pp_missing_macro_name); 68 return; 69 } 70 71 IdentifierInfo *II = MacroNameTok.getIdentifierInfo(); 72 if (II == 0) { 73 std::string Spelling = getSpelling(MacroNameTok); 74 const IdentifierInfo &Info = Identifiers.get(Spelling); 75 if (Info.isCPlusPlusOperatorKeyword()) 76 // C++ 2.5p2: Alternative tokens behave the same as its primary token 77 // except for their spellings. 78 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling; 79 else 80 Diag(MacroNameTok, diag::err_pp_macro_not_identifier); 81 // Fall through on error. 82 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) { 83 // Error if defining "defined": C99 6.10.8.4. 84 Diag(MacroNameTok, diag::err_defined_macro_name); 85 } else if (isDefineUndef && II->hasMacroDefinition() && 86 getMacroInfo(II)->isBuiltinMacro()) { 87 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4. 88 if (isDefineUndef == 1) 89 Diag(MacroNameTok, diag::pp_redef_builtin_macro); 90 else 91 Diag(MacroNameTok, diag::pp_undef_builtin_macro); 92 } else { 93 // Okay, we got a good identifier node. Return it. 94 return; 95 } 96 97 // Invalid macro name, read and discard the rest of the line. Then set the 98 // token kind to tok::eom. 99 MacroNameTok.setKind(tok::eom); 100 return DiscardUntilEndOfDirective(); 101} 102 103/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If 104/// not, emit a diagnostic and consume up until the eom. 105void Preprocessor::CheckEndOfDirective(const char *DirType) { 106 Token Tmp; 107 // Lex unexpanded tokens: macros might expand to zero tokens, causing us to 108 // miss diagnosing invalid lines. 109 LexUnexpandedToken(Tmp); 110 111 // There should be no tokens after the directive, but we allow them as an 112 // extension. 113 while (Tmp.is(tok::comment)) // Skip comments in -C mode. 114 LexUnexpandedToken(Tmp); 115 116 if (Tmp.isNot(tok::eom)) { 117 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType; 118 DiscardUntilEndOfDirective(); 119 } 120} 121 122 123 124/// SkipExcludedConditionalBlock - We just read a #if or related directive and 125/// decided that the subsequent tokens are in the #if'd out portion of the 126/// file. Lex the rest of the file, until we see an #endif. If 127/// FoundNonSkipPortion is true, then we have already emitted code for part of 128/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk 129/// is true, then #else directives are ok, if not, then we have already seen one 130/// so a #else directive is a duplicate. When this returns, the caller can lex 131/// the first valid token. 132void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, 133 bool FoundNonSkipPortion, 134 bool FoundElse) { 135 ++NumSkipped; 136 assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?"); 137 138 CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false, 139 FoundNonSkipPortion, FoundElse); 140 141 if (CurPTHLexer) { 142 PTHSkipExcludedConditionalBlock(); 143 return; 144 } 145 146 // Enter raw mode to disable identifier lookup (and thus macro expansion), 147 // disabling warnings, etc. 148 CurPPLexer->LexingRawMode = true; 149 Token Tok; 150 while (1) { 151 if (CurLexer) 152 CurLexer->Lex(Tok); 153 else 154 CurPTHLexer->Lex(Tok); 155 156 // If this is the end of the buffer, we have an error. 157 if (Tok.is(tok::eof)) { 158 // Emit errors for each unterminated conditional on the stack, including 159 // the current one. 160 while (!CurPPLexer->ConditionalStack.empty()) { 161 Diag(CurPPLexer->ConditionalStack.back().IfLoc, 162 diag::err_pp_unterminated_conditional); 163 CurPPLexer->ConditionalStack.pop_back(); 164 } 165 166 // Just return and let the caller lex after this #include. 167 break; 168 } 169 170 // If this token is not a preprocessor directive, just skip it. 171 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) 172 continue; 173 174 // We just parsed a # character at the start of a line, so we're in 175 // directive mode. Tell the lexer this so any newlines we see will be 176 // converted into an EOM token (this terminates the macro). 177 CurPPLexer->ParsingPreprocessorDirective = true; 178 if (CurLexer) CurLexer->SetCommentRetentionState(false); 179 180 181 // Read the next token, the directive flavor. 182 LexUnexpandedToken(Tok); 183 184 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or 185 // something bogus), skip it. 186 if (Tok.isNot(tok::identifier)) { 187 CurPPLexer->ParsingPreprocessorDirective = false; 188 // Restore comment saving mode. 189 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments); 190 continue; 191 } 192 193 // If the first letter isn't i or e, it isn't intesting to us. We know that 194 // this is safe in the face of spelling differences, because there is no way 195 // to spell an i/e in a strange way that is another letter. Skipping this 196 // allows us to avoid looking up the identifier info for #define/#undef and 197 // other common directives. 198 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation()); 199 char FirstChar = RawCharData[0]; 200 if (FirstChar >= 'a' && FirstChar <= 'z' && 201 FirstChar != 'i' && FirstChar != 'e') { 202 CurPPLexer->ParsingPreprocessorDirective = false; 203 // Restore comment saving mode. 204 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments); 205 continue; 206 } 207 208 // Get the identifier name without trigraphs or embedded newlines. Note 209 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled 210 // when skipping. 211 // TODO: could do this with zero copies in the no-clean case by using 212 // strncmp below. 213 char Directive[20]; 214 unsigned IdLen; 215 if (!Tok.needsCleaning() && Tok.getLength() < 20) { 216 IdLen = Tok.getLength(); 217 memcpy(Directive, RawCharData, IdLen); 218 Directive[IdLen] = 0; 219 } else { 220 std::string DirectiveStr = getSpelling(Tok); 221 IdLen = DirectiveStr.size(); 222 if (IdLen >= 20) { 223 CurPPLexer->ParsingPreprocessorDirective = false; 224 // Restore comment saving mode. 225 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments); 226 continue; 227 } 228 memcpy(Directive, &DirectiveStr[0], IdLen); 229 Directive[IdLen] = 0; 230 FirstChar = Directive[0]; 231 } 232 233 if (FirstChar == 'i' && Directive[1] == 'f') { 234 if ((IdLen == 2) || // "if" 235 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef" 236 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef" 237 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't 238 // bother parsing the condition. 239 DiscardUntilEndOfDirective(); 240 CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true, 241 /*foundnonskip*/false, 242 /*fnddelse*/false); 243 } 244 } else if (FirstChar == 'e') { 245 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif" 246 CheckEndOfDirective("#endif"); 247 PPConditionalInfo CondInfo; 248 CondInfo.WasSkipping = true; // Silence bogus warning. 249 bool InCond = CurPPLexer->popConditionalLevel(CondInfo); 250 InCond = InCond; // Silence warning in no-asserts mode. 251 assert(!InCond && "Can't be skipping if not in a conditional!"); 252 253 // If we popped the outermost skipping block, we're done skipping! 254 if (!CondInfo.WasSkipping) 255 break; 256 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else". 257 // #else directive in a skipping conditional. If not in some other 258 // skipping conditional, and if #else hasn't already been seen, enter it 259 // as a non-skipping conditional. 260 CheckEndOfDirective("#else"); 261 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel(); 262 263 // If this is a #else with a #else before it, report the error. 264 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else); 265 266 // Note that we've seen a #else in this conditional. 267 CondInfo.FoundElse = true; 268 269 // If the conditional is at the top level, and the #if block wasn't 270 // entered, enter the #else block now. 271 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) { 272 CondInfo.FoundNonSkip = true; 273 break; 274 } 275 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif". 276 PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel(); 277 278 bool ShouldEnter; 279 // If this is in a skipping block or if we're already handled this #if 280 // block, don't bother parsing the condition. 281 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) { 282 DiscardUntilEndOfDirective(); 283 ShouldEnter = false; 284 } else { 285 // Restore the value of LexingRawMode so that identifiers are 286 // looked up, etc, inside the #elif expression. 287 assert(CurPPLexer->LexingRawMode && "We have to be skipping here!"); 288 CurPPLexer->LexingRawMode = false; 289 IdentifierInfo *IfNDefMacro = 0; 290 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro); 291 CurPPLexer->LexingRawMode = true; 292 } 293 294 // If this is a #elif with a #else before it, report the error. 295 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else); 296 297 // If this condition is true, enter it! 298 if (ShouldEnter) { 299 CondInfo.FoundNonSkip = true; 300 break; 301 } 302 } 303 } 304 305 CurPPLexer->ParsingPreprocessorDirective = false; 306 // Restore comment saving mode. 307 if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments); 308 } 309 310 // Finally, if we are out of the conditional (saw an #endif or ran off the end 311 // of the file, just stop skipping and return to lexing whatever came after 312 // the #if block. 313 CurPPLexer->LexingRawMode = false; 314} 315 316void Preprocessor::PTHSkipExcludedConditionalBlock() { 317 318 while(1) { 319 assert(CurPTHLexer); 320 assert(CurPTHLexer->LexingRawMode == false); 321 322 // Skip to the next '#else', '#elif', or #endif. 323 if (CurPTHLexer->SkipBlock()) { 324 // We have reached an #endif. Both the '#' and 'endif' tokens 325 // have been consumed by the PTHLexer. Just pop off the condition level. 326 PPConditionalInfo CondInfo; 327 bool InCond = CurPTHLexer->popConditionalLevel(CondInfo); 328 InCond = InCond; // Silence warning in no-asserts mode. 329 assert(!InCond && "Can't be skipping if not in a conditional!"); 330 break; 331 } 332 333 // We have reached a '#else' or '#elif'. Lex the next token to get 334 // the directive flavor. 335 Token Tok; 336 LexUnexpandedToken(Tok); 337 338 // We can actually look up the IdentifierInfo here since we aren't in 339 // raw mode. 340 tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID(); 341 342 if (K == tok::pp_else) { 343 // #else: Enter the else condition. We aren't in a nested condition 344 // since we skip those. We're always in the one matching the last 345 // blocked we skipped. 346 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel(); 347 // Note that we've seen a #else in this conditional. 348 CondInfo.FoundElse = true; 349 350 // If the #if block wasn't entered then enter the #else block now. 351 if (!CondInfo.FoundNonSkip) { 352 CondInfo.FoundNonSkip = true; 353 354 // Consume the eom token. 355 CurPTHLexer->ParsingPreprocessorDirective = true; 356 LexUnexpandedToken(Tok); 357 assert(Tok.is(tok::eom)); 358 CurPTHLexer->ParsingPreprocessorDirective = false; 359 360 break; 361 } 362 363 // Otherwise skip this block. 364 continue; 365 } 366 367 assert(K == tok::pp_elif); 368 PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel(); 369 370 // If this is a #elif with a #else before it, report the error. 371 if (CondInfo.FoundElse) 372 Diag(Tok, diag::pp_err_elif_after_else); 373 374 // If this is in a skipping block or if we're already handled this #if 375 // block, don't bother parsing the condition. We just skip this block. 376 if (CondInfo.FoundNonSkip) 377 continue; 378 379 // Evaluate the condition of the #elif. 380 IdentifierInfo *IfNDefMacro = 0; 381 CurPTHLexer->ParsingPreprocessorDirective = true; 382 bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro); 383 CurPTHLexer->ParsingPreprocessorDirective = false; 384 385 // If this condition is true, enter it! 386 if (ShouldEnter) { 387 CondInfo.FoundNonSkip = true; 388 break; 389 } 390 391 // Otherwise, skip this block and go to the next one. 392 continue; 393 } 394} 395 396/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file, 397/// return null on failure. isAngled indicates whether the file reference is 398/// for system #include's or not (i.e. using <> instead of ""). 399const FileEntry *Preprocessor::LookupFile(const char *FilenameStart, 400 const char *FilenameEnd, 401 bool isAngled, 402 const DirectoryLookup *FromDir, 403 const DirectoryLookup *&CurDir) { 404 // If the header lookup mechanism may be relative to the current file, pass in 405 // info about where the current file is. 406 const FileEntry *CurFileEnt = 0; 407 if (!FromDir) { 408 FileID FID = getCurrentFileLexer()->getFileID(); 409 CurFileEnt = SourceMgr.getFileEntryForID(FID); 410 411 // If there is no file entry associated with this file, it must be the 412 // predefines buffer. Any other file is not lexed with a normal lexer, so 413 // it won't be scanned for preprocessor directives. If we have the 414 // predefines buffer, resolve #include references (which come from the 415 // -include command line argument) as if they came from the main file, this 416 // affects file lookup etc. 417 if (CurFileEnt == 0) { 418 FID = SourceMgr.getMainFileID(); 419 CurFileEnt = SourceMgr.getFileEntryForID(FID); 420 } 421 } 422 423 // Do a standard file entry lookup. 424 CurDir = CurDirLookup; 425 const FileEntry *FE = 426 HeaderInfo.LookupFile(FilenameStart, FilenameEnd, 427 isAngled, FromDir, CurDir, CurFileEnt); 428 if (FE) return FE; 429 430 // Otherwise, see if this is a subframework header. If so, this is relative 431 // to one of the headers on the #include stack. Walk the list of the current 432 // headers on the #include stack and pass them to HeaderInfo. 433 if (IsFileLexer()) { 434 if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))) 435 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd, 436 CurFileEnt))) 437 return FE; 438 } 439 440 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) { 441 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1]; 442 if (IsFileLexer(ISEntry)) { 443 if ((CurFileEnt = 444 SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID()))) 445 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, 446 FilenameEnd, CurFileEnt))) 447 return FE; 448 } 449 } 450 451 // Otherwise, we really couldn't find the file. 452 return 0; 453} 454 455 456//===----------------------------------------------------------------------===// 457// Preprocessor Directive Handling. 458//===----------------------------------------------------------------------===// 459 460/// HandleDirective - This callback is invoked when the lexer sees a # token 461/// at the start of a line. This consumes the directive, modifies the 462/// lexer/preprocessor state, and advances the lexer(s) so that the next token 463/// read is the correct one. 464void Preprocessor::HandleDirective(Token &Result) { 465 // FIXME: Traditional: # with whitespace before it not recognized by K&R? 466 467 // We just parsed a # character at the start of a line, so we're in directive 468 // mode. Tell the lexer this so any newlines we see will be converted into an 469 // EOM token (which terminates the directive). 470 CurPPLexer->ParsingPreprocessorDirective = true; 471 472 ++NumDirectives; 473 474 // We are about to read a token. For the multiple-include optimization FA to 475 // work, we have to remember if we had read any tokens *before* this 476 // pp-directive. 477 bool ReadAnyTokensBeforeDirective = CurPPLexer->MIOpt.getHasReadAnyTokensVal(); 478 479 // Read the next token, the directive flavor. This isn't expanded due to 480 // C99 6.10.3p8. 481 LexUnexpandedToken(Result); 482 483 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.: 484 // #define A(x) #x 485 // A(abc 486 // #warning blah 487 // def) 488 // If so, the user is relying on non-portable behavior, emit a diagnostic. 489 if (InMacroArgs) 490 Diag(Result, diag::ext_embedded_directive); 491 492TryAgain: 493 switch (Result.getKind()) { 494 case tok::eom: 495 return; // null directive. 496 case tok::comment: 497 // Handle stuff like "# /*foo*/ define X" in -E -C mode. 498 LexUnexpandedToken(Result); 499 goto TryAgain; 500 501 case tok::numeric_constant: // # 7 GNU line marker directive. 502 return HandleDigitDirective(Result); 503 default: 504 IdentifierInfo *II = Result.getIdentifierInfo(); 505 if (II == 0) break; // Not an identifier. 506 507 // Ask what the preprocessor keyword ID is. 508 switch (II->getPPKeywordID()) { 509 default: break; 510 // C99 6.10.1 - Conditional Inclusion. 511 case tok::pp_if: 512 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective); 513 case tok::pp_ifdef: 514 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/); 515 case tok::pp_ifndef: 516 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective); 517 case tok::pp_elif: 518 return HandleElifDirective(Result); 519 case tok::pp_else: 520 return HandleElseDirective(Result); 521 case tok::pp_endif: 522 return HandleEndifDirective(Result); 523 524 // C99 6.10.2 - Source File Inclusion. 525 case tok::pp_include: 526 return HandleIncludeDirective(Result); // Handle #include. 527 528 // C99 6.10.3 - Macro Replacement. 529 case tok::pp_define: 530 return HandleDefineDirective(Result); 531 case tok::pp_undef: 532 return HandleUndefDirective(Result); 533 534 // C99 6.10.4 - Line Control. 535 case tok::pp_line: 536 return HandleLineDirective(Result); 537 538 // C99 6.10.5 - Error Directive. 539 case tok::pp_error: 540 return HandleUserDiagnosticDirective(Result, false); 541 542 // C99 6.10.6 - Pragma Directive. 543 case tok::pp_pragma: 544 return HandlePragmaDirective(); 545 546 // GNU Extensions. 547 case tok::pp_import: 548 return HandleImportDirective(Result); 549 case tok::pp_include_next: 550 return HandleIncludeNextDirective(Result); 551 552 case tok::pp_warning: 553 Diag(Result, diag::ext_pp_warning_directive); 554 return HandleUserDiagnosticDirective(Result, true); 555 case tok::pp_ident: 556 return HandleIdentSCCSDirective(Result); 557 case tok::pp_sccs: 558 return HandleIdentSCCSDirective(Result); 559 case tok::pp_assert: 560 //isExtension = true; // FIXME: implement #assert 561 break; 562 case tok::pp_unassert: 563 //isExtension = true; // FIXME: implement #unassert 564 break; 565 } 566 break; 567 } 568 569 // If we reached here, the preprocessing token is not valid! 570 Diag(Result, diag::err_pp_invalid_directive); 571 572 // Read the rest of the PP line. 573 DiscardUntilEndOfDirective(); 574 575 // Okay, we're done parsing the directive. 576} 577 578/// GetLineValue - Convert a numeric token into an unsigned value, emitting 579/// Diagnostic DiagID if it is invalid, and returning the value in Val. 580static bool GetLineValue(Token &DigitTok, unsigned &Val, 581 unsigned DiagID, Preprocessor &PP) { 582 if (DigitTok.isNot(tok::numeric_constant)) { 583 PP.Diag(DigitTok, DiagID); 584 585 if (DigitTok.isNot(tok::eom)) 586 PP.DiscardUntilEndOfDirective(); 587 return true; 588 } 589 590 llvm::SmallString<64> IntegerBuffer; 591 IntegerBuffer.resize(DigitTok.getLength()); 592 const char *DigitTokBegin = &IntegerBuffer[0]; 593 unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin); 594 NumericLiteralParser Literal(DigitTokBegin, DigitTokBegin+ActualLength, 595 DigitTok.getLocation(), PP); 596 if (Literal.hadError) 597 return true; // Error already emitted. 598 599 if (Literal.isFloatingLiteral() || Literal.isImaginary) { 600 PP.Diag(DigitTok, DiagID); 601 return true; 602 } 603 604 // Parse the integer literal into Result. 605 llvm::APInt APVal(32, 0); 606 if (Literal.GetIntegerValue(APVal)) { 607 // Overflow parsing integer literal. 608 PP.Diag(DigitTok, DiagID); 609 return true; 610 } 611 Val = APVal.getZExtValue(); 612 613 // Reject 0, this is needed both by #line numbers and flags. 614 if (Val == 0) { 615 PP.Diag(DigitTok, DiagID); 616 PP.DiscardUntilEndOfDirective(); 617 return true; 618 } 619 620 return false; 621} 622 623/// HandleLineDirective - Handle #line directive: C99 6.10.4. The two 624/// acceptable forms are: 625/// # line digit-sequence 626/// # line digit-sequence "s-char-sequence" 627void Preprocessor::HandleLineDirective(Token &Tok) { 628 // Read the line # and string argument. Per C99 6.10.4p5, these tokens are 629 // expanded. 630 Token DigitTok; 631 Lex(DigitTok); 632 633 // Validate the number and convert it to an unsigned. 634 unsigned LineNo; 635 if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer, *this)) 636 return; 637 638 // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a 639 // number greater than 2147483647". C90 requires that the line # be <= 32767. 640 unsigned LineLimit = Features.C99 ? 2147483648U : 32768U; 641 if (LineNo >= LineLimit) 642 Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit; 643 644 int FilenameID = -1; 645 Token StrTok; 646 Lex(StrTok); 647 648 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a 649 // string followed by eom. 650 if (StrTok.is(tok::eom)) 651 ; // ok 652 else if (StrTok.isNot(tok::string_literal)) { 653 Diag(StrTok, diag::err_pp_line_invalid_filename); 654 DiscardUntilEndOfDirective(); 655 return; 656 } else { 657 // Parse and validate the string, converting it into a unique ID. 658 StringLiteralParser Literal(&StrTok, 1, *this); 659 assert(!Literal.AnyWide && "Didn't allow wide strings in"); 660 if (Literal.hadError) 661 return DiscardUntilEndOfDirective(); 662 if (Literal.Pascal) { 663 Diag(StrTok, diag::err_pp_linemarker_invalid_filename); 664 return DiscardUntilEndOfDirective(); 665 } 666 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(), 667 Literal.GetStringLength()); 668 669 // Verify that there is nothing after the string, other than EOM. 670 CheckEndOfDirective("#line"); 671 } 672 673 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID); 674} 675 676/// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line 677/// marker directive. 678static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit, 679 bool &IsSystemHeader, bool &IsExternCHeader, 680 Preprocessor &PP) { 681 unsigned FlagVal; 682 Token FlagTok; 683 PP.Lex(FlagTok); 684 if (FlagTok.is(tok::eom)) return false; 685 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP)) 686 return true; 687 688 if (FlagVal == 1) { 689 IsFileEntry = true; 690 691 PP.Lex(FlagTok); 692 if (FlagTok.is(tok::eom)) return false; 693 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP)) 694 return true; 695 } else if (FlagVal == 2) { 696 IsFileExit = true; 697 698 SourceManager &SM = PP.getSourceManager(); 699 // If we are leaving the current presumed file, check to make sure the 700 // presumed include stack isn't empty! 701 FileID CurFileID = 702 SM.getDecomposedInstantiationLoc(FlagTok.getLocation()).first; 703 PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation()); 704 705 // If there is no include loc (main file) or if the include loc is in a 706 // different physical file, then we aren't in a "1" line marker flag region. 707 SourceLocation IncLoc = PLoc.getIncludeLoc(); 708 if (IncLoc.isInvalid() || 709 SM.getDecomposedInstantiationLoc(IncLoc).first != CurFileID) { 710 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop); 711 PP.DiscardUntilEndOfDirective(); 712 return true; 713 } 714 715 PP.Lex(FlagTok); 716 if (FlagTok.is(tok::eom)) return false; 717 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP)) 718 return true; 719 } 720 721 // We must have 3 if there are still flags. 722 if (FlagVal != 3) { 723 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag); 724 PP.DiscardUntilEndOfDirective(); 725 return true; 726 } 727 728 IsSystemHeader = true; 729 730 PP.Lex(FlagTok); 731 if (FlagTok.is(tok::eom)) return false; 732 if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP)) 733 return true; 734 735 // We must have 4 if there is yet another flag. 736 if (FlagVal != 4) { 737 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag); 738 PP.DiscardUntilEndOfDirective(); 739 return true; 740 } 741 742 IsExternCHeader = true; 743 744 PP.Lex(FlagTok); 745 if (FlagTok.is(tok::eom)) return false; 746 747 // There are no more valid flags here. 748 PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag); 749 PP.DiscardUntilEndOfDirective(); 750 return true; 751} 752 753/// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is 754/// one of the following forms: 755/// 756/// # 42 757/// # 42 "file" ('1' | '2')? 758/// # 42 "file" ('1' | '2')? '3' '4'? 759/// 760void Preprocessor::HandleDigitDirective(Token &DigitTok) { 761 // Validate the number and convert it to an unsigned. GNU does not have a 762 // line # limit other than it fit in 32-bits. 763 unsigned LineNo; 764 if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer, 765 *this)) 766 return; 767 768 Token StrTok; 769 Lex(StrTok); 770 771 bool IsFileEntry = false, IsFileExit = false; 772 bool IsSystemHeader = false, IsExternCHeader = false; 773 int FilenameID = -1; 774 775 // If the StrTok is "eom", then it wasn't present. Otherwise, it must be a 776 // string followed by eom. 777 if (StrTok.is(tok::eom)) 778 ; // ok 779 else if (StrTok.isNot(tok::string_literal)) { 780 Diag(StrTok, diag::err_pp_linemarker_invalid_filename); 781 return DiscardUntilEndOfDirective(); 782 } else { 783 // Parse and validate the string, converting it into a unique ID. 784 StringLiteralParser Literal(&StrTok, 1, *this); 785 assert(!Literal.AnyWide && "Didn't allow wide strings in"); 786 if (Literal.hadError) 787 return DiscardUntilEndOfDirective(); 788 if (Literal.Pascal) { 789 Diag(StrTok, diag::err_pp_linemarker_invalid_filename); 790 return DiscardUntilEndOfDirective(); 791 } 792 FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString(), 793 Literal.GetStringLength()); 794 795 // If a filename was present, read any flags that are present. 796 if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, 797 IsSystemHeader, IsExternCHeader, *this)) 798 return; 799 } 800 801 // Create a line note with this information. 802 SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, 803 IsFileEntry, IsFileExit, 804 IsSystemHeader, IsExternCHeader); 805} 806 807 808/// HandleUserDiagnosticDirective - Handle a #warning or #error directive. 809/// 810void Preprocessor::HandleUserDiagnosticDirective(Token &Tok, 811 bool isWarning) { 812 // PTH doesn't emit #warning or #error directives. 813 if (CurPTHLexer) 814 return CurPTHLexer->DiscardToEndOfLine(); 815 816 // Read the rest of the line raw. We do this because we don't want macros 817 // to be expanded and we don't require that the tokens be valid preprocessing 818 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does 819 // collapse multiple consequtive white space between tokens, but this isn't 820 // specified by the standard. 821 std::string Message = CurLexer->ReadToEndOfLine(); 822 if (isWarning) 823 Diag(Tok, diag::pp_hash_warning) << Message; 824 else 825 Diag(Tok, diag::err_pp_hash_error) << Message; 826} 827 828/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive. 829/// 830void Preprocessor::HandleIdentSCCSDirective(Token &Tok) { 831 // Yes, this directive is an extension. 832 Diag(Tok, diag::ext_pp_ident_directive); 833 834 // Read the string argument. 835 Token StrTok; 836 Lex(StrTok); 837 838 // If the token kind isn't a string, it's a malformed directive. 839 if (StrTok.isNot(tok::string_literal) && 840 StrTok.isNot(tok::wide_string_literal)) { 841 Diag(StrTok, diag::err_pp_malformed_ident); 842 if (StrTok.isNot(tok::eom)) 843 DiscardUntilEndOfDirective(); 844 return; 845 } 846 847 // Verify that there is nothing after the string, other than EOM. 848 CheckEndOfDirective("#ident"); 849 850 if (Callbacks) 851 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok)); 852} 853 854//===----------------------------------------------------------------------===// 855// Preprocessor Include Directive Handling. 856//===----------------------------------------------------------------------===// 857 858/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully 859/// checked and spelled filename, e.g. as an operand of #include. This returns 860/// true if the input filename was in <>'s or false if it were in ""'s. The 861/// caller is expected to provide a buffer that is large enough to hold the 862/// spelling of the filename, but is also expected to handle the case when 863/// this method decides to use a different buffer. 864bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc, 865 const char *&BufStart, 866 const char *&BufEnd) { 867 // Get the text form of the filename. 868 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!"); 869 870 // Make sure the filename is <x> or "x". 871 bool isAngled; 872 if (BufStart[0] == '<') { 873 if (BufEnd[-1] != '>') { 874 Diag(Loc, diag::err_pp_expects_filename); 875 BufStart = 0; 876 return true; 877 } 878 isAngled = true; 879 } else if (BufStart[0] == '"') { 880 if (BufEnd[-1] != '"') { 881 Diag(Loc, diag::err_pp_expects_filename); 882 BufStart = 0; 883 return true; 884 } 885 isAngled = false; 886 } else { 887 Diag(Loc, diag::err_pp_expects_filename); 888 BufStart = 0; 889 return true; 890 } 891 892 // Diagnose #include "" as invalid. 893 if (BufEnd-BufStart <= 2) { 894 Diag(Loc, diag::err_pp_empty_filename); 895 BufStart = 0; 896 return ""; 897 } 898 899 // Skip the brackets. 900 ++BufStart; 901 --BufEnd; 902 return isAngled; 903} 904 905/// ConcatenateIncludeName - Handle cases where the #include name is expanded 906/// from a macro as multiple tokens, which need to be glued together. This 907/// occurs for code like: 908/// #define FOO <a/b.h> 909/// #include FOO 910/// because in this case, "<a/b.h>" is returned as 7 tokens, not one. 911/// 912/// This code concatenates and consumes tokens up to the '>' token. It returns 913/// false if the > was found, otherwise it returns true if it finds and consumes 914/// the EOM marker. 915static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer, 916 Preprocessor &PP) { 917 Token CurTok; 918 919 PP.Lex(CurTok); 920 while (CurTok.isNot(tok::eom)) { 921 // Append the spelling of this token to the buffer. If there was a space 922 // before it, add it now. 923 if (CurTok.hasLeadingSpace()) 924 FilenameBuffer.push_back(' '); 925 926 // Get the spelling of the token, directly into FilenameBuffer if possible. 927 unsigned PreAppendSize = FilenameBuffer.size(); 928 FilenameBuffer.resize(PreAppendSize+CurTok.getLength()); 929 930 const char *BufPtr = &FilenameBuffer[PreAppendSize]; 931 unsigned ActualLen = PP.getSpelling(CurTok, BufPtr); 932 933 // If the token was spelled somewhere else, copy it into FilenameBuffer. 934 if (BufPtr != &FilenameBuffer[PreAppendSize]) 935 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen); 936 937 // Resize FilenameBuffer to the correct size. 938 if (CurTok.getLength() != ActualLen) 939 FilenameBuffer.resize(PreAppendSize+ActualLen); 940 941 // If we found the '>' marker, return success. 942 if (CurTok.is(tok::greater)) 943 return false; 944 945 PP.Lex(CurTok); 946 } 947 948 // If we hit the eom marker, emit an error and return true so that the caller 949 // knows the EOM has been read. 950 PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename); 951 return true; 952} 953 954/// HandleIncludeDirective - The "#include" tokens have just been read, read the 955/// file to be included from the lexer, then include it! This is a common 956/// routine with functionality shared between #include, #include_next and 957/// #import. LookupFrom is set when this is a #include_next directive, it 958/// specifies the file to start searching from. 959void Preprocessor::HandleIncludeDirective(Token &IncludeTok, 960 const DirectoryLookup *LookupFrom, 961 bool isImport) { 962 963 Token FilenameTok; 964 CurPPLexer->LexIncludeFilename(FilenameTok); 965 966 // Reserve a buffer to get the spelling. 967 llvm::SmallVector<char, 128> FilenameBuffer; 968 const char *FilenameStart, *FilenameEnd; 969 970 switch (FilenameTok.getKind()) { 971 case tok::eom: 972 // If the token kind is EOM, the error has already been diagnosed. 973 return; 974 975 case tok::angle_string_literal: 976 case tok::string_literal: { 977 FilenameBuffer.resize(FilenameTok.getLength()); 978 FilenameStart = &FilenameBuffer[0]; 979 unsigned Len = getSpelling(FilenameTok, FilenameStart); 980 FilenameEnd = FilenameStart+Len; 981 break; 982 } 983 984 case tok::less: 985 // This could be a <foo/bar.h> file coming from a macro expansion. In this 986 // case, glue the tokens together into FilenameBuffer and interpret those. 987 FilenameBuffer.push_back('<'); 988 if (ConcatenateIncludeName(FilenameBuffer, *this)) 989 return; // Found <eom> but no ">"? Diagnostic already emitted. 990 FilenameStart = &FilenameBuffer[0]; 991 FilenameEnd = &FilenameBuffer[FilenameBuffer.size()]; 992 break; 993 default: 994 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename); 995 DiscardUntilEndOfDirective(); 996 return; 997 } 998 999 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(), 1000 FilenameStart, FilenameEnd); 1001 // If GetIncludeFilenameSpelling set the start ptr to null, there was an 1002 // error. 1003 if (FilenameStart == 0) { 1004 DiscardUntilEndOfDirective(); 1005 return; 1006 } 1007 1008 // Verify that there is nothing after the filename, other than EOM. Use the 1009 // preprocessor to lex this in case lexing the filename entered a macro. 1010 CheckEndOfDirective("#include"); 1011 1012 // Check that we don't have infinite #include recursion. 1013 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) { 1014 Diag(FilenameTok, diag::err_pp_include_too_deep); 1015 return; 1016 } 1017 1018 // Search include directories. 1019 const DirectoryLookup *CurDir; 1020 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd, 1021 isAngled, LookupFrom, CurDir); 1022 if (File == 0) { 1023 Diag(FilenameTok, diag::err_pp_file_not_found) 1024 << std::string(FilenameStart, FilenameEnd); 1025 return; 1026 } 1027 1028 // Ask HeaderInfo if we should enter this #include file. If not, #including 1029 // this file will have no effect. 1030 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) 1031 return; 1032 1033 // The #included file will be considered to be a system header if either it is 1034 // in a system include directory, or if the #includer is a system include 1035 // header. 1036 SrcMgr::CharacteristicKind FileCharacter = 1037 std::max(HeaderInfo.getFileDirFlavor(File), 1038 SourceMgr.getFileCharacteristic(FilenameTok.getLocation())); 1039 1040 // Look up the file, create a File ID for it. 1041 FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(), 1042 FileCharacter); 1043 if (FID.isInvalid()) { 1044 Diag(FilenameTok, diag::err_pp_file_not_found) 1045 << std::string(FilenameStart, FilenameEnd); 1046 return; 1047 } 1048 1049 // Finally, if all is good, enter the new file! 1050 EnterSourceFile(FID, CurDir); 1051} 1052 1053/// HandleIncludeNextDirective - Implements #include_next. 1054/// 1055void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) { 1056 Diag(IncludeNextTok, diag::ext_pp_include_next_directive); 1057 1058 // #include_next is like #include, except that we start searching after 1059 // the current found directory. If we can't do this, issue a 1060 // diagnostic. 1061 const DirectoryLookup *Lookup = CurDirLookup; 1062 if (isInPrimaryFile()) { 1063 Lookup = 0; 1064 Diag(IncludeNextTok, diag::pp_include_next_in_primary); 1065 } else if (Lookup == 0) { 1066 Diag(IncludeNextTok, diag::pp_include_next_absolute_path); 1067 } else { 1068 // Start looking up in the next directory. 1069 ++Lookup; 1070 } 1071 1072 return HandleIncludeDirective(IncludeNextTok, Lookup); 1073} 1074 1075/// HandleImportDirective - Implements #import. 1076/// 1077void Preprocessor::HandleImportDirective(Token &ImportTok) { 1078 Diag(ImportTok, diag::ext_pp_import_directive); 1079 1080 return HandleIncludeDirective(ImportTok, 0, true); 1081} 1082 1083//===----------------------------------------------------------------------===// 1084// Preprocessor Macro Directive Handling. 1085//===----------------------------------------------------------------------===// 1086 1087/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro 1088/// definition has just been read. Lex the rest of the arguments and the 1089/// closing ), updating MI with what we learn. Return true if an error occurs 1090/// parsing the arg list. 1091bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) { 1092 llvm::SmallVector<IdentifierInfo*, 32> Arguments; 1093 1094 Token Tok; 1095 while (1) { 1096 LexUnexpandedToken(Tok); 1097 switch (Tok.getKind()) { 1098 case tok::r_paren: 1099 // Found the end of the argument list. 1100 if (Arguments.empty()) // #define FOO() 1101 return false; 1102 // Otherwise we have #define FOO(A,) 1103 Diag(Tok, diag::err_pp_expected_ident_in_arg_list); 1104 return true; 1105 case tok::ellipsis: // #define X(... -> C99 varargs 1106 // Warn if use of C99 feature in non-C99 mode. 1107 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro); 1108 1109 // Lex the token after the identifier. 1110 LexUnexpandedToken(Tok); 1111 if (Tok.isNot(tok::r_paren)) { 1112 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def); 1113 return true; 1114 } 1115 // Add the __VA_ARGS__ identifier as an argument. 1116 Arguments.push_back(Ident__VA_ARGS__); 1117 MI->setIsC99Varargs(); 1118 MI->setArgumentList(&Arguments[0], Arguments.size()); 1119 return false; 1120 case tok::eom: // #define X( 1121 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def); 1122 return true; 1123 default: 1124 // Handle keywords and identifiers here to accept things like 1125 // #define Foo(for) for. 1126 IdentifierInfo *II = Tok.getIdentifierInfo(); 1127 if (II == 0) { 1128 // #define X(1 1129 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list); 1130 return true; 1131 } 1132 1133 // If this is already used as an argument, it is used multiple times (e.g. 1134 // #define X(A,A. 1135 if (std::find(Arguments.begin(), Arguments.end(), II) != 1136 Arguments.end()) { // C99 6.10.3p6 1137 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II; 1138 return true; 1139 } 1140 1141 // Add the argument to the macro info. 1142 Arguments.push_back(II); 1143 1144 // Lex the token after the identifier. 1145 LexUnexpandedToken(Tok); 1146 1147 switch (Tok.getKind()) { 1148 default: // #define X(A B 1149 Diag(Tok, diag::err_pp_expected_comma_in_arg_list); 1150 return true; 1151 case tok::r_paren: // #define X(A) 1152 MI->setArgumentList(&Arguments[0], Arguments.size()); 1153 return false; 1154 case tok::comma: // #define X(A, 1155 break; 1156 case tok::ellipsis: // #define X(A... -> GCC extension 1157 // Diagnose extension. 1158 Diag(Tok, diag::ext_named_variadic_macro); 1159 1160 // Lex the token after the identifier. 1161 LexUnexpandedToken(Tok); 1162 if (Tok.isNot(tok::r_paren)) { 1163 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def); 1164 return true; 1165 } 1166 1167 MI->setIsGNUVarargs(); 1168 MI->setArgumentList(&Arguments[0], Arguments.size()); 1169 return false; 1170 } 1171 } 1172 } 1173} 1174 1175/// HandleDefineDirective - Implements #define. This consumes the entire macro 1176/// line then lets the caller lex the next real token. 1177void Preprocessor::HandleDefineDirective(Token &DefineTok) { 1178 ++NumDefined; 1179 1180 Token MacroNameTok; 1181 ReadMacroName(MacroNameTok, 1); 1182 1183 // Error reading macro name? If so, diagnostic already issued. 1184 if (MacroNameTok.is(tok::eom)) 1185 return; 1186 1187 // If we are supposed to keep comments in #defines, reenable comment saving 1188 // mode. 1189 if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments); 1190 1191 // Create the new macro. 1192 MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation()); 1193 1194 Token Tok; 1195 LexUnexpandedToken(Tok); 1196 1197 // If this is a function-like macro definition, parse the argument list, 1198 // marking each of the identifiers as being used as macro arguments. Also, 1199 // check other constraints on the first token of the macro body. 1200 if (Tok.is(tok::eom)) { 1201 // If there is no body to this macro, we have no special handling here. 1202 } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) { 1203 // This is a function-like macro definition. Read the argument list. 1204 MI->setIsFunctionLike(); 1205 if (ReadMacroDefinitionArgList(MI)) { 1206 // Forget about MI. 1207 ReleaseMacroInfo(MI); 1208 // Throw away the rest of the line. 1209 if (CurPPLexer->ParsingPreprocessorDirective) 1210 DiscardUntilEndOfDirective(); 1211 return; 1212 } 1213 1214 // Read the first token after the arg list for down below. 1215 LexUnexpandedToken(Tok); 1216 } else if (!Tok.hasLeadingSpace()) { 1217 // C99 requires whitespace between the macro definition and the body. Emit 1218 // a diagnostic for something like "#define X+". 1219 if (Features.C99) { 1220 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name); 1221 } else { 1222 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar 1223 // one in some cases! 1224 } 1225 } else { 1226 // This is a normal token with leading space. Clear the leading space 1227 // marker on the first token to get proper expansion. 1228 Tok.clearFlag(Token::LeadingSpace); 1229 } 1230 1231 // If this is a definition of a variadic C99 function-like macro, not using 1232 // the GNU named varargs extension, enabled __VA_ARGS__. 1233 1234 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro. 1235 // This gets unpoisoned where it is allowed. 1236 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!"); 1237 if (MI->isC99Varargs()) 1238 Ident__VA_ARGS__->setIsPoisoned(false); 1239 1240 // Read the rest of the macro body. 1241 if (MI->isObjectLike()) { 1242 // Object-like macros are very simple, just read their body. 1243 while (Tok.isNot(tok::eom)) { 1244 MI->AddTokenToBody(Tok); 1245 // Get the next token of the macro. 1246 LexUnexpandedToken(Tok); 1247 } 1248 1249 } else { 1250 // Otherwise, read the body of a function-like macro. This has to validate 1251 // the # (stringize) operator. 1252 while (Tok.isNot(tok::eom)) { 1253 MI->AddTokenToBody(Tok); 1254 1255 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro 1256 // parameters in function-like macro expansions. 1257 if (Tok.isNot(tok::hash)) { 1258 // Get the next token of the macro. 1259 LexUnexpandedToken(Tok); 1260 continue; 1261 } 1262 1263 // Get the next token of the macro. 1264 LexUnexpandedToken(Tok); 1265 1266 // Not a macro arg identifier? 1267 if (!Tok.getIdentifierInfo() || 1268 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) { 1269 Diag(Tok, diag::err_pp_stringize_not_parameter); 1270 ReleaseMacroInfo(MI); 1271 1272 // Disable __VA_ARGS__ again. 1273 Ident__VA_ARGS__->setIsPoisoned(true); 1274 return; 1275 } 1276 1277 // Things look ok, add the param name token to the macro. 1278 MI->AddTokenToBody(Tok); 1279 1280 // Get the next token of the macro. 1281 LexUnexpandedToken(Tok); 1282 } 1283 } 1284 1285 1286 // Disable __VA_ARGS__ again. 1287 Ident__VA_ARGS__->setIsPoisoned(true); 1288 1289 // Check that there is no paste (##) operator at the begining or end of the 1290 // replacement list. 1291 unsigned NumTokens = MI->getNumTokens(); 1292 if (NumTokens != 0) { 1293 if (MI->getReplacementToken(0).is(tok::hashhash)) { 1294 Diag(MI->getReplacementToken(0), diag::err_paste_at_start); 1295 ReleaseMacroInfo(MI); 1296 return; 1297 } 1298 if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) { 1299 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end); 1300 ReleaseMacroInfo(MI); 1301 return; 1302 } 1303 } 1304 1305 // If this is the primary source file, remember that this macro hasn't been 1306 // used yet. 1307 if (isInPrimaryFile()) 1308 MI->setIsUsed(false); 1309 1310 // Finally, if this identifier already had a macro defined for it, verify that 1311 // the macro bodies are identical and free the old definition. 1312 if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) { 1313 // It is very common for system headers to have tons of macro redefinitions 1314 // and for warnings to be disabled in system headers. If this is the case, 1315 // then don't bother calling MacroInfo::isIdenticalTo. 1316 if (!Diags.getSuppressSystemWarnings() || 1317 !SourceMgr.isInSystemHeader(DefineTok.getLocation())) { 1318 if (!OtherMI->isUsed()) 1319 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used); 1320 1321 // Macros must be identical. This means all tokes and whitespace 1322 // separation must be the same. C99 6.10.3.2. 1323 if (!MI->isIdenticalTo(*OtherMI, *this)) { 1324 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef) 1325 << MacroNameTok.getIdentifierInfo(); 1326 Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition); 1327 } 1328 } 1329 1330 ReleaseMacroInfo(OtherMI); 1331 } 1332 1333 setMacroInfo(MacroNameTok.getIdentifierInfo(), MI); 1334} 1335 1336/// HandleUndefDirective - Implements #undef. 1337/// 1338void Preprocessor::HandleUndefDirective(Token &UndefTok) { 1339 ++NumUndefined; 1340 1341 Token MacroNameTok; 1342 ReadMacroName(MacroNameTok, 2); 1343 1344 // Error reading macro name? If so, diagnostic already issued. 1345 if (MacroNameTok.is(tok::eom)) 1346 return; 1347 1348 // Check to see if this is the last token on the #undef line. 1349 CheckEndOfDirective("#undef"); 1350 1351 // Okay, we finally have a valid identifier to undef. 1352 MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo()); 1353 1354 // If the macro is not defined, this is a noop undef, just return. 1355 if (MI == 0) return; 1356 1357 if (!MI->isUsed()) 1358 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used); 1359 1360 // Free macro definition. 1361 ReleaseMacroInfo(MI); 1362 setMacroInfo(MacroNameTok.getIdentifierInfo(), 0); 1363} 1364 1365 1366//===----------------------------------------------------------------------===// 1367// Preprocessor Conditional Directive Handling. 1368//===----------------------------------------------------------------------===// 1369 1370/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is 1371/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true 1372/// if any tokens have been returned or pp-directives activated before this 1373/// #ifndef has been lexed. 1374/// 1375void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef, 1376 bool ReadAnyTokensBeforeDirective) { 1377 ++NumIf; 1378 Token DirectiveTok = Result; 1379 1380 Token MacroNameTok; 1381 ReadMacroName(MacroNameTok); 1382 1383 // Error reading macro name? If so, diagnostic already issued. 1384 if (MacroNameTok.is(tok::eom)) { 1385 // Skip code until we get to #endif. This helps with recovery by not 1386 // emitting an error when the #endif is reached. 1387 SkipExcludedConditionalBlock(DirectiveTok.getLocation(), 1388 /*Foundnonskip*/false, /*FoundElse*/false); 1389 return; 1390 } 1391 1392 // Check to see if this is the last token on the #if[n]def line. 1393 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef"); 1394 1395 if (CurPPLexer->getConditionalStackDepth() == 0) { 1396 // If the start of a top-level #ifdef, inform MIOpt. 1397 if (!ReadAnyTokensBeforeDirective) { 1398 assert(isIfndef && "#ifdef shouldn't reach here"); 1399 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo()); 1400 } else 1401 CurPPLexer->MIOpt.EnterTopLevelConditional(); 1402 } 1403 1404 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo(); 1405 MacroInfo *MI = getMacroInfo(MII); 1406 1407 // If there is a macro, process it. 1408 if (MI) // Mark it used. 1409 MI->setIsUsed(true); 1410 1411 // Should we include the stuff contained by this directive? 1412 if (!MI == isIfndef) { 1413 // Yes, remember that we are inside a conditional, then lex the next token. 1414 CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false, 1415 /*foundnonskip*/true, /*foundelse*/false); 1416 } else { 1417 // No, skip the contents of this block and return the first token after it. 1418 SkipExcludedConditionalBlock(DirectiveTok.getLocation(), 1419 /*Foundnonskip*/false, 1420 /*FoundElse*/false); 1421 } 1422} 1423 1424/// HandleIfDirective - Implements the #if directive. 1425/// 1426void Preprocessor::HandleIfDirective(Token &IfToken, 1427 bool ReadAnyTokensBeforeDirective) { 1428 ++NumIf; 1429 1430 // Parse and evaluation the conditional expression. 1431 IdentifierInfo *IfNDefMacro = 0; 1432 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro); 1433 1434 1435 // If this condition is equivalent to #ifndef X, and if this is the first 1436 // directive seen, handle it for the multiple-include optimization. 1437 if (CurPPLexer->getConditionalStackDepth() == 0) { 1438 if (!ReadAnyTokensBeforeDirective && IfNDefMacro) 1439 CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro); 1440 else 1441 CurPPLexer->MIOpt.EnterTopLevelConditional(); 1442 } 1443 1444 // Should we include the stuff contained by this directive? 1445 if (ConditionalTrue) { 1446 // Yes, remember that we are inside a conditional, then lex the next token. 1447 CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false, 1448 /*foundnonskip*/true, /*foundelse*/false); 1449 } else { 1450 // No, skip the contents of this block and return the first token after it. 1451 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false, 1452 /*FoundElse*/false); 1453 } 1454} 1455 1456/// HandleEndifDirective - Implements the #endif directive. 1457/// 1458void Preprocessor::HandleEndifDirective(Token &EndifToken) { 1459 ++NumEndif; 1460 1461 // Check that this is the whole directive. 1462 CheckEndOfDirective("#endif"); 1463 1464 PPConditionalInfo CondInfo; 1465 if (CurPPLexer->popConditionalLevel(CondInfo)) { 1466 // No conditionals on the stack: this is an #endif without an #if. 1467 Diag(EndifToken, diag::err_pp_endif_without_if); 1468 return; 1469 } 1470 1471 // If this the end of a top-level #endif, inform MIOpt. 1472 if (CurPPLexer->getConditionalStackDepth() == 0) 1473 CurPPLexer->MIOpt.ExitTopLevelConditional(); 1474 1475 assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode && 1476 "This code should only be reachable in the non-skipping case!"); 1477} 1478 1479 1480void Preprocessor::HandleElseDirective(Token &Result) { 1481 ++NumElse; 1482 1483 // #else directive in a non-skipping conditional... start skipping. 1484 CheckEndOfDirective("#else"); 1485 1486 PPConditionalInfo CI; 1487 if (CurPPLexer->popConditionalLevel(CI)) { 1488 Diag(Result, diag::pp_err_else_without_if); 1489 return; 1490 } 1491 1492 // If this is a top-level #else, inform the MIOpt. 1493 if (CurPPLexer->getConditionalStackDepth() == 0) 1494 CurPPLexer->MIOpt.EnterTopLevelConditional(); 1495 1496 // If this is a #else with a #else before it, report the error. 1497 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else); 1498 1499 // Finally, skip the rest of the contents of this block and return the first 1500 // token after it. 1501 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true, 1502 /*FoundElse*/true); 1503} 1504 1505void Preprocessor::HandleElifDirective(Token &ElifToken) { 1506 ++NumElse; 1507 1508 // #elif directive in a non-skipping conditional... start skipping. 1509 // We don't care what the condition is, because we will always skip it (since 1510 // the block immediately before it was included). 1511 DiscardUntilEndOfDirective(); 1512 1513 PPConditionalInfo CI; 1514 if (CurPPLexer->popConditionalLevel(CI)) { 1515 Diag(ElifToken, diag::pp_err_elif_without_if); 1516 return; 1517 } 1518 1519 // If this is a top-level #elif, inform the MIOpt. 1520 if (CurPPLexer->getConditionalStackDepth() == 0) 1521 CurPPLexer->MIOpt.EnterTopLevelConditional(); 1522 1523 // If this is a #elif with a #else before it, report the error. 1524 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else); 1525 1526 // Finally, skip the rest of the contents of this block and return the first 1527 // token after it. 1528 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true, 1529 /*FoundElse*/CI.FoundElse); 1530} 1531 1532