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