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