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