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