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