1 //===--- Pragma.cpp - Pragma registration and handling --------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the PragmaHandler/PragmaTable interfaces and implements 11 // pragma related methods of the Preprocessor class. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/Lex/Pragma.h" 16 #include "clang/Basic/FileManager.h" 17 #include "clang/Basic/SourceManager.h" 18 #include "clang/Lex/HeaderSearch.h" 19 #include "clang/Lex/LexDiagnostic.h" 20 #include "clang/Lex/LiteralSupport.h" 21 #include "clang/Lex/MacroInfo.h" 22 #include "clang/Lex/Preprocessor.h" 23 #include "llvm/ADT/STLExtras.h" 24 #include "llvm/ADT/StringSwitch.h" 25 #include "llvm/ADT/StringExtras.h" 26 #include "llvm/Support/CrashRecoveryContext.h" 27 #include "llvm/Support/ErrorHandling.h" 28 #include <algorithm> 29 using namespace clang; 30 31 // Out-of-line destructor to provide a home for the class. 32 PragmaHandler::~PragmaHandler() { 33 } 34 35 //===----------------------------------------------------------------------===// 36 // EmptyPragmaHandler Implementation. 37 //===----------------------------------------------------------------------===// 38 39 EmptyPragmaHandler::EmptyPragmaHandler(StringRef Name) : PragmaHandler(Name) {} 40 41 void EmptyPragmaHandler::HandlePragma(Preprocessor &PP, 42 PragmaIntroducerKind Introducer, 43 Token &FirstToken) {} 44 45 //===----------------------------------------------------------------------===// 46 // PragmaNamespace Implementation. 47 //===----------------------------------------------------------------------===// 48 49 PragmaNamespace::~PragmaNamespace() { 50 llvm::DeleteContainerSeconds(Handlers); 51 } 52 53 /// FindHandler - Check to see if there is already a handler for the 54 /// specified name. If not, return the handler for the null identifier if it 55 /// exists, otherwise return null. If IgnoreNull is true (the default) then 56 /// the null handler isn't returned on failure to match. 57 PragmaHandler *PragmaNamespace::FindHandler(StringRef Name, 58 bool IgnoreNull) const { 59 if (PragmaHandler *Handler = Handlers.lookup(Name)) 60 return Handler; 61 return IgnoreNull ? nullptr : Handlers.lookup(StringRef()); 62 } 63 64 void PragmaNamespace::AddPragma(PragmaHandler *Handler) { 65 assert(!Handlers.lookup(Handler->getName()) && 66 "A handler with this name is already registered in this namespace"); 67 Handlers[Handler->getName()] = Handler; 68 } 69 70 void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) { 71 assert(Handlers.lookup(Handler->getName()) && 72 "Handler not registered in this namespace"); 73 Handlers.erase(Handler->getName()); 74 } 75 76 void PragmaNamespace::HandlePragma(Preprocessor &PP, 77 PragmaIntroducerKind Introducer, 78 Token &Tok) { 79 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro 80 // expand it, the user can have a STDC #define, that should not affect this. 81 PP.LexUnexpandedToken(Tok); 82 83 // Get the handler for this token. If there is no handler, ignore the pragma. 84 PragmaHandler *Handler 85 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName() 86 : StringRef(), 87 /*IgnoreNull=*/false); 88 if (!Handler) { 89 PP.Diag(Tok, diag::warn_pragma_ignored); 90 return; 91 } 92 93 // Otherwise, pass it down. 94 Handler->HandlePragma(PP, Introducer, Tok); 95 } 96 97 //===----------------------------------------------------------------------===// 98 // Preprocessor Pragma Directive Handling. 99 //===----------------------------------------------------------------------===// 100 101 /// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the 102 /// rest of the pragma, passing it to the registered pragma handlers. 103 void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc, 104 PragmaIntroducerKind Introducer) { 105 if (Callbacks) 106 Callbacks->PragmaDirective(IntroducerLoc, Introducer); 107 108 if (!PragmasEnabled) 109 return; 110 111 ++NumPragma; 112 113 // Invoke the first level of pragma handlers which reads the namespace id. 114 Token Tok; 115 PragmaHandlers->HandlePragma(*this, Introducer, Tok); 116 117 // If the pragma handler didn't read the rest of the line, consume it now. 118 if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective()) 119 || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective)) 120 DiscardUntilEndOfDirective(); 121 } 122 123 namespace { 124 /// \brief Helper class for \see Preprocessor::Handle_Pragma. 125 class LexingFor_PragmaRAII { 126 Preprocessor &PP; 127 bool InMacroArgPreExpansion; 128 bool Failed; 129 Token &OutTok; 130 Token PragmaTok; 131 132 public: 133 LexingFor_PragmaRAII(Preprocessor &PP, bool InMacroArgPreExpansion, 134 Token &Tok) 135 : PP(PP), InMacroArgPreExpansion(InMacroArgPreExpansion), 136 Failed(false), OutTok(Tok) { 137 if (InMacroArgPreExpansion) { 138 PragmaTok = OutTok; 139 PP.EnableBacktrackAtThisPos(); 140 } 141 } 142 143 ~LexingFor_PragmaRAII() { 144 if (InMacroArgPreExpansion) { 145 if (Failed) { 146 PP.CommitBacktrackedTokens(); 147 } else { 148 PP.Backtrack(); 149 OutTok = PragmaTok; 150 } 151 } 152 } 153 154 void failed() { 155 Failed = true; 156 } 157 }; 158 } 159 160 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then 161 /// return the first token after the directive. The _Pragma token has just 162 /// been read into 'Tok'. 163 void Preprocessor::Handle_Pragma(Token &Tok) { 164 165 // This works differently if we are pre-expanding a macro argument. 166 // In that case we don't actually "activate" the pragma now, we only lex it 167 // until we are sure it is lexically correct and then we backtrack so that 168 // we activate the pragma whenever we encounter the tokens again in the token 169 // stream. This ensures that we will activate it in the correct location 170 // or that we will ignore it if it never enters the token stream, e.g: 171 // 172 // #define EMPTY(x) 173 // #define INACTIVE(x) EMPTY(x) 174 // INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\"")) 175 176 LexingFor_PragmaRAII _PragmaLexing(*this, InMacroArgPreExpansion, Tok); 177 178 // Remember the pragma token location. 179 SourceLocation PragmaLoc = Tok.getLocation(); 180 181 // Read the '('. 182 Lex(Tok); 183 if (Tok.isNot(tok::l_paren)) { 184 Diag(PragmaLoc, diag::err__Pragma_malformed); 185 return _PragmaLexing.failed(); 186 } 187 188 // Read the '"..."'. 189 Lex(Tok); 190 if (!tok::isStringLiteral(Tok.getKind())) { 191 Diag(PragmaLoc, diag::err__Pragma_malformed); 192 // Skip bad tokens, and the ')', if present. 193 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof)) 194 Lex(Tok); 195 while (Tok.isNot(tok::r_paren) && 196 !Tok.isAtStartOfLine() && 197 Tok.isNot(tok::eof)) 198 Lex(Tok); 199 if (Tok.is(tok::r_paren)) 200 Lex(Tok); 201 return _PragmaLexing.failed(); 202 } 203 204 if (Tok.hasUDSuffix()) { 205 Diag(Tok, diag::err_invalid_string_udl); 206 // Skip this token, and the ')', if present. 207 Lex(Tok); 208 if (Tok.is(tok::r_paren)) 209 Lex(Tok); 210 return _PragmaLexing.failed(); 211 } 212 213 // Remember the string. 214 Token StrTok = Tok; 215 216 // Read the ')'. 217 Lex(Tok); 218 if (Tok.isNot(tok::r_paren)) { 219 Diag(PragmaLoc, diag::err__Pragma_malformed); 220 return _PragmaLexing.failed(); 221 } 222 223 if (InMacroArgPreExpansion) 224 return; 225 226 SourceLocation RParenLoc = Tok.getLocation(); 227 std::string StrVal = getSpelling(StrTok); 228 229 // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1: 230 // "The string literal is destringized by deleting any encoding prefix, 231 // deleting the leading and trailing double-quotes, replacing each escape 232 // sequence \" by a double-quote, and replacing each escape sequence \\ by a 233 // single backslash." 234 if (StrVal[0] == 'L' || StrVal[0] == 'U' || 235 (StrVal[0] == 'u' && StrVal[1] != '8')) 236 StrVal.erase(StrVal.begin()); 237 else if (StrVal[0] == 'u') 238 StrVal.erase(StrVal.begin(), StrVal.begin() + 2); 239 240 if (StrVal[0] == 'R') { 241 // FIXME: C++11 does not specify how to handle raw-string-literals here. 242 // We strip off the 'R', the quotes, the d-char-sequences, and the parens. 243 assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' && 244 "Invalid raw string token!"); 245 246 // Measure the length of the d-char-sequence. 247 unsigned NumDChars = 0; 248 while (StrVal[2 + NumDChars] != '(') { 249 assert(NumDChars < (StrVal.size() - 5) / 2 && 250 "Invalid raw string token!"); 251 ++NumDChars; 252 } 253 assert(StrVal[StrVal.size() - 2 - NumDChars] == ')'); 254 255 // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the 256 // parens below. 257 StrVal.erase(0, 2 + NumDChars); 258 StrVal.erase(StrVal.size() - 1 - NumDChars); 259 } else { 260 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' && 261 "Invalid string token!"); 262 263 // Remove escaped quotes and escapes. 264 unsigned ResultPos = 1; 265 for (unsigned i = 1, e = StrVal.size() - 1; i != e; ++i) { 266 // Skip escapes. \\ -> '\' and \" -> '"'. 267 if (StrVal[i] == '\\' && i + 1 < e && 268 (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"')) 269 ++i; 270 StrVal[ResultPos++] = StrVal[i]; 271 } 272 StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1); 273 } 274 275 // Remove the front quote, replacing it with a space, so that the pragma 276 // contents appear to have a space before them. 277 StrVal[0] = ' '; 278 279 // Replace the terminating quote with a \n. 280 StrVal[StrVal.size()-1] = '\n'; 281 282 // Plop the string (including the newline and trailing null) into a buffer 283 // where we can lex it. 284 Token TmpTok; 285 TmpTok.startToken(); 286 CreateString(StrVal, TmpTok); 287 SourceLocation TokLoc = TmpTok.getLocation(); 288 289 // Make and enter a lexer object so that we lex and expand the tokens just 290 // like any others. 291 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc, 292 StrVal.size(), *this); 293 294 EnterSourceFileWithLexer(TL, nullptr); 295 296 // With everything set up, lex this as a #pragma directive. 297 HandlePragmaDirective(PragmaLoc, PIK__Pragma); 298 299 // Finally, return whatever came after the pragma directive. 300 return Lex(Tok); 301 } 302 303 /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text 304 /// is not enclosed within a string literal. 305 void Preprocessor::HandleMicrosoft__pragma(Token &Tok) { 306 // Remember the pragma token location. 307 SourceLocation PragmaLoc = Tok.getLocation(); 308 309 // Read the '('. 310 Lex(Tok); 311 if (Tok.isNot(tok::l_paren)) { 312 Diag(PragmaLoc, diag::err__Pragma_malformed); 313 return; 314 } 315 316 // Get the tokens enclosed within the __pragma(), as well as the final ')'. 317 SmallVector<Token, 32> PragmaToks; 318 int NumParens = 0; 319 Lex(Tok); 320 while (Tok.isNot(tok::eof)) { 321 PragmaToks.push_back(Tok); 322 if (Tok.is(tok::l_paren)) 323 NumParens++; 324 else if (Tok.is(tok::r_paren) && NumParens-- == 0) 325 break; 326 Lex(Tok); 327 } 328 329 if (Tok.is(tok::eof)) { 330 Diag(PragmaLoc, diag::err_unterminated___pragma); 331 return; 332 } 333 334 PragmaToks.front().setFlag(Token::LeadingSpace); 335 336 // Replace the ')' with an EOD to mark the end of the pragma. 337 PragmaToks.back().setKind(tok::eod); 338 339 Token *TokArray = new Token[PragmaToks.size()]; 340 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray); 341 342 // Push the tokens onto the stack. 343 EnterTokenStream(TokArray, PragmaToks.size(), true, true); 344 345 // With everything set up, lex this as a #pragma directive. 346 HandlePragmaDirective(PragmaLoc, PIK___pragma); 347 348 // Finally, return whatever came after the pragma directive. 349 return Lex(Tok); 350 } 351 352 /// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'. 353 /// 354 void Preprocessor::HandlePragmaOnce(Token &OnceTok) { 355 if (isInPrimaryFile()) { 356 Diag(OnceTok, diag::pp_pragma_once_in_main_file); 357 return; 358 } 359 360 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc. 361 // Mark the file as a once-only file now. 362 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry()); 363 } 364 365 void Preprocessor::HandlePragmaMark() { 366 assert(CurPPLexer && "No current lexer?"); 367 if (CurLexer) 368 CurLexer->ReadToEndOfLine(); 369 else 370 CurPTHLexer->DiscardToEndOfLine(); 371 } 372 373 374 /// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'. 375 /// 376 void Preprocessor::HandlePragmaPoison(Token &PoisonTok) { 377 Token Tok; 378 379 while (1) { 380 // Read the next token to poison. While doing this, pretend that we are 381 // skipping while reading the identifier to poison. 382 // This avoids errors on code like: 383 // #pragma GCC poison X 384 // #pragma GCC poison X 385 if (CurPPLexer) CurPPLexer->LexingRawMode = true; 386 LexUnexpandedToken(Tok); 387 if (CurPPLexer) CurPPLexer->LexingRawMode = false; 388 389 // If we reached the end of line, we're done. 390 if (Tok.is(tok::eod)) return; 391 392 // Can only poison identifiers. 393 if (Tok.isNot(tok::raw_identifier)) { 394 Diag(Tok, diag::err_pp_invalid_poison); 395 return; 396 } 397 398 // Look up the identifier info for the token. We disabled identifier lookup 399 // by saying we're skipping contents, so we need to do this manually. 400 IdentifierInfo *II = LookUpIdentifierInfo(Tok); 401 402 // Already poisoned. 403 if (II->isPoisoned()) continue; 404 405 // If this is a macro identifier, emit a warning. 406 if (isMacroDefined(II)) 407 Diag(Tok, diag::pp_poisoning_existing_macro); 408 409 // Finally, poison it! 410 II->setIsPoisoned(); 411 if (II->isFromAST()) 412 II->setChangedSinceDeserialization(); 413 } 414 } 415 416 /// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know 417 /// that the whole directive has been parsed. 418 void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) { 419 if (isInPrimaryFile()) { 420 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file); 421 return; 422 } 423 424 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc. 425 PreprocessorLexer *TheLexer = getCurrentFileLexer(); 426 427 // Mark the file as a system header. 428 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry()); 429 430 431 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation()); 432 if (PLoc.isInvalid()) 433 return; 434 435 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename()); 436 437 // Notify the client, if desired, that we are in a new source file. 438 if (Callbacks) 439 Callbacks->FileChanged(SysHeaderTok.getLocation(), 440 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System); 441 442 // Emit a line marker. This will change any source locations from this point 443 // forward to realize they are in a system header. 444 // Create a line note with this information. 445 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine()+1, 446 FilenameID, /*IsEntry=*/false, /*IsExit=*/false, 447 /*IsSystem=*/true, /*IsExternC=*/false); 448 } 449 450 /// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah. 451 /// 452 void Preprocessor::HandlePragmaDependency(Token &DependencyTok) { 453 Token FilenameTok; 454 CurPPLexer->LexIncludeFilename(FilenameTok); 455 456 // If the token kind is EOD, the error has already been diagnosed. 457 if (FilenameTok.is(tok::eod)) 458 return; 459 460 // Reserve a buffer to get the spelling. 461 SmallString<128> FilenameBuffer; 462 bool Invalid = false; 463 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid); 464 if (Invalid) 465 return; 466 467 bool isAngled = 468 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename); 469 // If GetIncludeFilenameSpelling set the start ptr to null, there was an 470 // error. 471 if (Filename.empty()) 472 return; 473 474 // Search include directories for this file. 475 const DirectoryLookup *CurDir; 476 const FileEntry *File = 477 LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr, 478 nullptr, CurDir, nullptr, nullptr, nullptr); 479 if (!File) { 480 if (!SuppressIncludeNotFoundError) 481 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename; 482 return; 483 } 484 485 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry(); 486 487 // If this file is older than the file it depends on, emit a diagnostic. 488 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) { 489 // Lex tokens at the end of the message and include them in the message. 490 std::string Message; 491 Lex(DependencyTok); 492 while (DependencyTok.isNot(tok::eod)) { 493 Message += getSpelling(DependencyTok) + " "; 494 Lex(DependencyTok); 495 } 496 497 // Remove the trailing ' ' if present. 498 if (!Message.empty()) 499 Message.erase(Message.end()-1); 500 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message; 501 } 502 } 503 504 /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro. 505 /// Return the IdentifierInfo* associated with the macro to push or pop. 506 IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) { 507 // Remember the pragma token location. 508 Token PragmaTok = Tok; 509 510 // Read the '('. 511 Lex(Tok); 512 if (Tok.isNot(tok::l_paren)) { 513 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed) 514 << getSpelling(PragmaTok); 515 return nullptr; 516 } 517 518 // Read the macro name string. 519 Lex(Tok); 520 if (Tok.isNot(tok::string_literal)) { 521 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed) 522 << getSpelling(PragmaTok); 523 return nullptr; 524 } 525 526 if (Tok.hasUDSuffix()) { 527 Diag(Tok, diag::err_invalid_string_udl); 528 return nullptr; 529 } 530 531 // Remember the macro string. 532 std::string StrVal = getSpelling(Tok); 533 534 // Read the ')'. 535 Lex(Tok); 536 if (Tok.isNot(tok::r_paren)) { 537 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed) 538 << getSpelling(PragmaTok); 539 return nullptr; 540 } 541 542 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' && 543 "Invalid string token!"); 544 545 // Create a Token from the string. 546 Token MacroTok; 547 MacroTok.startToken(); 548 MacroTok.setKind(tok::raw_identifier); 549 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok); 550 551 // Get the IdentifierInfo of MacroToPushTok. 552 return LookUpIdentifierInfo(MacroTok); 553 } 554 555 /// \brief Handle \#pragma push_macro. 556 /// 557 /// The syntax is: 558 /// \code 559 /// #pragma push_macro("macro") 560 /// \endcode 561 void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) { 562 // Parse the pragma directive and get the macro IdentifierInfo*. 563 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok); 564 if (!IdentInfo) return; 565 566 // Get the MacroInfo associated with IdentInfo. 567 MacroInfo *MI = getMacroInfo(IdentInfo); 568 569 if (MI) { 570 // Allow the original MacroInfo to be redefined later. 571 MI->setIsAllowRedefinitionsWithoutWarning(true); 572 } 573 574 // Push the cloned MacroInfo so we can retrieve it later. 575 PragmaPushMacroInfo[IdentInfo].push_back(MI); 576 } 577 578 /// \brief Handle \#pragma pop_macro. 579 /// 580 /// The syntax is: 581 /// \code 582 /// #pragma pop_macro("macro") 583 /// \endcode 584 void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) { 585 SourceLocation MessageLoc = PopMacroTok.getLocation(); 586 587 // Parse the pragma directive and get the macro IdentifierInfo*. 588 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok); 589 if (!IdentInfo) return; 590 591 // Find the vector<MacroInfo*> associated with the macro. 592 llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter = 593 PragmaPushMacroInfo.find(IdentInfo); 594 if (iter != PragmaPushMacroInfo.end()) { 595 // Forget the MacroInfo currently associated with IdentInfo. 596 if (MacroInfo *MI = getMacroInfo(IdentInfo)) { 597 if (MI->isWarnIfUnused()) 598 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc()); 599 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc)); 600 } 601 602 // Get the MacroInfo we want to reinstall. 603 MacroInfo *MacroToReInstall = iter->second.back(); 604 605 if (MacroToReInstall) 606 // Reinstall the previously pushed macro. 607 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc); 608 609 // Pop PragmaPushMacroInfo stack. 610 iter->second.pop_back(); 611 if (iter->second.size() == 0) 612 PragmaPushMacroInfo.erase(iter); 613 } else { 614 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push) 615 << IdentInfo->getName(); 616 } 617 } 618 619 void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) { 620 // We will either get a quoted filename or a bracketed filename, and we 621 // have to track which we got. The first filename is the source name, 622 // and the second name is the mapped filename. If the first is quoted, 623 // the second must be as well (cannot mix and match quotes and brackets). 624 625 // Get the open paren 626 Lex(Tok); 627 if (Tok.isNot(tok::l_paren)) { 628 Diag(Tok, diag::warn_pragma_include_alias_expected) << "("; 629 return; 630 } 631 632 // We expect either a quoted string literal, or a bracketed name 633 Token SourceFilenameTok; 634 CurPPLexer->LexIncludeFilename(SourceFilenameTok); 635 if (SourceFilenameTok.is(tok::eod)) { 636 // The diagnostic has already been handled 637 return; 638 } 639 640 StringRef SourceFileName; 641 SmallString<128> FileNameBuffer; 642 if (SourceFilenameTok.is(tok::string_literal) || 643 SourceFilenameTok.is(tok::angle_string_literal)) { 644 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer); 645 } else if (SourceFilenameTok.is(tok::less)) { 646 // This could be a path instead of just a name 647 FileNameBuffer.push_back('<'); 648 SourceLocation End; 649 if (ConcatenateIncludeName(FileNameBuffer, End)) 650 return; // Diagnostic already emitted 651 SourceFileName = FileNameBuffer; 652 } else { 653 Diag(Tok, diag::warn_pragma_include_alias_expected_filename); 654 return; 655 } 656 FileNameBuffer.clear(); 657 658 // Now we expect a comma, followed by another include name 659 Lex(Tok); 660 if (Tok.isNot(tok::comma)) { 661 Diag(Tok, diag::warn_pragma_include_alias_expected) << ","; 662 return; 663 } 664 665 Token ReplaceFilenameTok; 666 CurPPLexer->LexIncludeFilename(ReplaceFilenameTok); 667 if (ReplaceFilenameTok.is(tok::eod)) { 668 // The diagnostic has already been handled 669 return; 670 } 671 672 StringRef ReplaceFileName; 673 if (ReplaceFilenameTok.is(tok::string_literal) || 674 ReplaceFilenameTok.is(tok::angle_string_literal)) { 675 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer); 676 } else if (ReplaceFilenameTok.is(tok::less)) { 677 // This could be a path instead of just a name 678 FileNameBuffer.push_back('<'); 679 SourceLocation End; 680 if (ConcatenateIncludeName(FileNameBuffer, End)) 681 return; // Diagnostic already emitted 682 ReplaceFileName = FileNameBuffer; 683 } else { 684 Diag(Tok, diag::warn_pragma_include_alias_expected_filename); 685 return; 686 } 687 688 // Finally, we expect the closing paren 689 Lex(Tok); 690 if (Tok.isNot(tok::r_paren)) { 691 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")"; 692 return; 693 } 694 695 // Now that we have the source and target filenames, we need to make sure 696 // they're both of the same type (angled vs non-angled) 697 StringRef OriginalSource = SourceFileName; 698 699 bool SourceIsAngled = 700 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(), 701 SourceFileName); 702 bool ReplaceIsAngled = 703 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(), 704 ReplaceFileName); 705 if (!SourceFileName.empty() && !ReplaceFileName.empty() && 706 (SourceIsAngled != ReplaceIsAngled)) { 707 unsigned int DiagID; 708 if (SourceIsAngled) 709 DiagID = diag::warn_pragma_include_alias_mismatch_angle; 710 else 711 DiagID = diag::warn_pragma_include_alias_mismatch_quote; 712 713 Diag(SourceFilenameTok.getLocation(), DiagID) 714 << SourceFileName 715 << ReplaceFileName; 716 717 return; 718 } 719 720 // Now we can let the include handler know about this mapping 721 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName); 722 } 723 724 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor. 725 /// If 'Namespace' is non-null, then it is a token required to exist on the 726 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC". 727 void Preprocessor::AddPragmaHandler(StringRef Namespace, 728 PragmaHandler *Handler) { 729 PragmaNamespace *InsertNS = PragmaHandlers.get(); 730 731 // If this is specified to be in a namespace, step down into it. 732 if (!Namespace.empty()) { 733 // If there is already a pragma handler with the name of this namespace, 734 // we either have an error (directive with the same name as a namespace) or 735 // we already have the namespace to insert into. 736 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) { 737 InsertNS = Existing->getIfNamespace(); 738 assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma" 739 " handler with the same name!"); 740 } else { 741 // Otherwise, this namespace doesn't exist yet, create and insert the 742 // handler for it. 743 InsertNS = new PragmaNamespace(Namespace); 744 PragmaHandlers->AddPragma(InsertNS); 745 } 746 } 747 748 // Check to make sure we don't already have a pragma for this identifier. 749 assert(!InsertNS->FindHandler(Handler->getName()) && 750 "Pragma handler already exists for this identifier!"); 751 InsertNS->AddPragma(Handler); 752 } 753 754 /// RemovePragmaHandler - Remove the specific pragma handler from the 755 /// preprocessor. If \arg Namespace is non-null, then it should be the 756 /// namespace that \arg Handler was added to. It is an error to remove 757 /// a handler that has not been registered. 758 void Preprocessor::RemovePragmaHandler(StringRef Namespace, 759 PragmaHandler *Handler) { 760 PragmaNamespace *NS = PragmaHandlers.get(); 761 762 // If this is specified to be in a namespace, step down into it. 763 if (!Namespace.empty()) { 764 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace); 765 assert(Existing && "Namespace containing handler does not exist!"); 766 767 NS = Existing->getIfNamespace(); 768 assert(NS && "Invalid namespace, registered as a regular pragma handler!"); 769 } 770 771 NS->RemovePragmaHandler(Handler); 772 773 // If this is a non-default namespace and it is now empty, remove it. 774 if (NS != PragmaHandlers.get() && NS->IsEmpty()) { 775 PragmaHandlers->RemovePragmaHandler(NS); 776 delete NS; 777 } 778 } 779 780 bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) { 781 Token Tok; 782 LexUnexpandedToken(Tok); 783 784 if (Tok.isNot(tok::identifier)) { 785 Diag(Tok, diag::ext_on_off_switch_syntax); 786 return true; 787 } 788 IdentifierInfo *II = Tok.getIdentifierInfo(); 789 if (II->isStr("ON")) 790 Result = tok::OOS_ON; 791 else if (II->isStr("OFF")) 792 Result = tok::OOS_OFF; 793 else if (II->isStr("DEFAULT")) 794 Result = tok::OOS_DEFAULT; 795 else { 796 Diag(Tok, diag::ext_on_off_switch_syntax); 797 return true; 798 } 799 800 // Verify that this is followed by EOD. 801 LexUnexpandedToken(Tok); 802 if (Tok.isNot(tok::eod)) 803 Diag(Tok, diag::ext_pragma_syntax_eod); 804 return false; 805 } 806 807 namespace { 808 /// PragmaOnceHandler - "\#pragma once" marks the file as atomically included. 809 struct PragmaOnceHandler : public PragmaHandler { 810 PragmaOnceHandler() : PragmaHandler("once") {} 811 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 812 Token &OnceTok) override { 813 PP.CheckEndOfDirective("pragma once"); 814 PP.HandlePragmaOnce(OnceTok); 815 } 816 }; 817 818 /// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the 819 /// rest of the line is not lexed. 820 struct PragmaMarkHandler : public PragmaHandler { 821 PragmaMarkHandler() : PragmaHandler("mark") {} 822 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 823 Token &MarkTok) override { 824 PP.HandlePragmaMark(); 825 } 826 }; 827 828 /// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable. 829 struct PragmaPoisonHandler : public PragmaHandler { 830 PragmaPoisonHandler() : PragmaHandler("poison") {} 831 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 832 Token &PoisonTok) override { 833 PP.HandlePragmaPoison(PoisonTok); 834 } 835 }; 836 837 /// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file 838 /// as a system header, which silences warnings in it. 839 struct PragmaSystemHeaderHandler : public PragmaHandler { 840 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {} 841 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 842 Token &SHToken) override { 843 PP.HandlePragmaSystemHeader(SHToken); 844 PP.CheckEndOfDirective("pragma"); 845 } 846 }; 847 struct PragmaDependencyHandler : public PragmaHandler { 848 PragmaDependencyHandler() : PragmaHandler("dependency") {} 849 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 850 Token &DepToken) override { 851 PP.HandlePragmaDependency(DepToken); 852 } 853 }; 854 855 struct PragmaDebugHandler : public PragmaHandler { 856 PragmaDebugHandler() : PragmaHandler("__debug") {} 857 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 858 Token &DepToken) override { 859 Token Tok; 860 PP.LexUnexpandedToken(Tok); 861 if (Tok.isNot(tok::identifier)) { 862 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid); 863 return; 864 } 865 IdentifierInfo *II = Tok.getIdentifierInfo(); 866 867 if (II->isStr("assert")) { 868 llvm_unreachable("This is an assertion!"); 869 } else if (II->isStr("crash")) { 870 LLVM_BUILTIN_TRAP; 871 } else if (II->isStr("parser_crash")) { 872 Token Crasher; 873 Crasher.startToken(); 874 Crasher.setKind(tok::annot_pragma_parser_crash); 875 Crasher.setAnnotationRange(SourceRange(Tok.getLocation())); 876 PP.EnterToken(Crasher); 877 } else if (II->isStr("dump")) { 878 Token Identifier; 879 PP.LexUnexpandedToken(Identifier); 880 if (auto *DumpII = Identifier.getIdentifierInfo()) { 881 Token DumpAnnot; 882 DumpAnnot.startToken(); 883 DumpAnnot.setKind(tok::annot_pragma_dump); 884 DumpAnnot.setAnnotationRange( 885 SourceRange(Tok.getLocation(), Identifier.getLocation())); 886 DumpAnnot.setAnnotationValue(DumpII); 887 PP.DiscardUntilEndOfDirective(); 888 PP.EnterToken(DumpAnnot); 889 } else { 890 PP.Diag(Identifier, diag::warn_pragma_debug_missing_argument) 891 << II->getName(); 892 } 893 } else if (II->isStr("llvm_fatal_error")) { 894 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error"); 895 } else if (II->isStr("llvm_unreachable")) { 896 llvm_unreachable("#pragma clang __debug llvm_unreachable"); 897 } else if (II->isStr("macro")) { 898 Token MacroName; 899 PP.LexUnexpandedToken(MacroName); 900 auto *MacroII = MacroName.getIdentifierInfo(); 901 if (MacroII) 902 PP.dumpMacroInfo(MacroII); 903 else 904 PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument) 905 << II->getName(); 906 } else if (II->isStr("overflow_stack")) { 907 DebugOverflowStack(); 908 } else if (II->isStr("handle_crash")) { 909 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent(); 910 if (CRC) 911 CRC->HandleCrash(); 912 } else if (II->isStr("captured")) { 913 HandleCaptured(PP); 914 } else { 915 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command) 916 << II->getName(); 917 } 918 919 PPCallbacks *Callbacks = PP.getPPCallbacks(); 920 if (Callbacks) 921 Callbacks->PragmaDebug(Tok.getLocation(), II->getName()); 922 } 923 924 void HandleCaptured(Preprocessor &PP) { 925 // Skip if emitting preprocessed output. 926 if (PP.isPreprocessedOutput()) 927 return; 928 929 Token Tok; 930 PP.LexUnexpandedToken(Tok); 931 932 if (Tok.isNot(tok::eod)) { 933 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) 934 << "pragma clang __debug captured"; 935 return; 936 } 937 938 SourceLocation NameLoc = Tok.getLocation(); 939 MutableArrayRef<Token> Toks( 940 PP.getPreprocessorAllocator().Allocate<Token>(1), 1); 941 Toks[0].startToken(); 942 Toks[0].setKind(tok::annot_pragma_captured); 943 Toks[0].setLocation(NameLoc); 944 945 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true); 946 } 947 948 // Disable MSVC warning about runtime stack overflow. 949 #ifdef _MSC_VER 950 #pragma warning(disable : 4717) 951 #endif 952 static void DebugOverflowStack() { 953 void (*volatile Self)() = DebugOverflowStack; 954 Self(); 955 } 956 #ifdef _MSC_VER 957 #pragma warning(default : 4717) 958 #endif 959 960 }; 961 962 /// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"' 963 struct PragmaDiagnosticHandler : public PragmaHandler { 964 private: 965 const char *Namespace; 966 public: 967 explicit PragmaDiagnosticHandler(const char *NS) : 968 PragmaHandler("diagnostic"), Namespace(NS) {} 969 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 970 Token &DiagToken) override { 971 SourceLocation DiagLoc = DiagToken.getLocation(); 972 Token Tok; 973 PP.LexUnexpandedToken(Tok); 974 if (Tok.isNot(tok::identifier)) { 975 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid); 976 return; 977 } 978 IdentifierInfo *II = Tok.getIdentifierInfo(); 979 PPCallbacks *Callbacks = PP.getPPCallbacks(); 980 981 if (II->isStr("pop")) { 982 if (!PP.getDiagnostics().popMappings(DiagLoc)) 983 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop); 984 else if (Callbacks) 985 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace); 986 return; 987 } else if (II->isStr("push")) { 988 PP.getDiagnostics().pushMappings(DiagLoc); 989 if (Callbacks) 990 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace); 991 return; 992 } 993 994 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName()) 995 .Case("ignored", diag::Severity::Ignored) 996 .Case("warning", diag::Severity::Warning) 997 .Case("error", diag::Severity::Error) 998 .Case("fatal", diag::Severity::Fatal) 999 .Default(diag::Severity()); 1000 1001 if (SV == diag::Severity()) { 1002 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid); 1003 return; 1004 } 1005 1006 PP.LexUnexpandedToken(Tok); 1007 SourceLocation StringLoc = Tok.getLocation(); 1008 1009 std::string WarningName; 1010 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic", 1011 /*MacroExpansion=*/false)) 1012 return; 1013 1014 if (Tok.isNot(tok::eod)) { 1015 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token); 1016 return; 1017 } 1018 1019 if (WarningName.size() < 3 || WarningName[0] != '-' || 1020 (WarningName[1] != 'W' && WarningName[1] != 'R')) { 1021 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option); 1022 return; 1023 } 1024 1025 diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError 1026 : diag::Flavor::Remark; 1027 StringRef Group = StringRef(WarningName).substr(2); 1028 bool unknownDiag = false; 1029 if (Group == "everything") { 1030 // Special handling for pragma clang diagnostic ... "-Weverything". 1031 // There is no formal group named "everything", so there has to be a 1032 // special case for it. 1033 PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc); 1034 } else 1035 unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV, 1036 DiagLoc); 1037 if (unknownDiag) 1038 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning) 1039 << WarningName; 1040 else if (Callbacks) 1041 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName); 1042 } 1043 }; 1044 1045 /// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's 1046 /// diagnostics, so we don't really implement this pragma. We parse it and 1047 /// ignore it to avoid -Wunknown-pragma warnings. 1048 struct PragmaWarningHandler : public PragmaHandler { 1049 PragmaWarningHandler() : PragmaHandler("warning") {} 1050 1051 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1052 Token &Tok) override { 1053 // Parse things like: 1054 // warning(push, 1) 1055 // warning(pop) 1056 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9) 1057 SourceLocation DiagLoc = Tok.getLocation(); 1058 PPCallbacks *Callbacks = PP.getPPCallbacks(); 1059 1060 PP.Lex(Tok); 1061 if (Tok.isNot(tok::l_paren)) { 1062 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "("; 1063 return; 1064 } 1065 1066 PP.Lex(Tok); 1067 IdentifierInfo *II = Tok.getIdentifierInfo(); 1068 1069 if (II && II->isStr("push")) { 1070 // #pragma warning( push[ ,n ] ) 1071 int Level = -1; 1072 PP.Lex(Tok); 1073 if (Tok.is(tok::comma)) { 1074 PP.Lex(Tok); 1075 uint64_t Value; 1076 if (Tok.is(tok::numeric_constant) && 1077 PP.parseSimpleIntegerLiteral(Tok, Value)) 1078 Level = int(Value); 1079 if (Level < 0 || Level > 4) { 1080 PP.Diag(Tok, diag::warn_pragma_warning_push_level); 1081 return; 1082 } 1083 } 1084 if (Callbacks) 1085 Callbacks->PragmaWarningPush(DiagLoc, Level); 1086 } else if (II && II->isStr("pop")) { 1087 // #pragma warning( pop ) 1088 PP.Lex(Tok); 1089 if (Callbacks) 1090 Callbacks->PragmaWarningPop(DiagLoc); 1091 } else { 1092 // #pragma warning( warning-specifier : warning-number-list 1093 // [; warning-specifier : warning-number-list...] ) 1094 while (true) { 1095 II = Tok.getIdentifierInfo(); 1096 if (!II && !Tok.is(tok::numeric_constant)) { 1097 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid); 1098 return; 1099 } 1100 1101 // Figure out which warning specifier this is. 1102 bool SpecifierValid; 1103 StringRef Specifier; 1104 llvm::SmallString<1> SpecifierBuf; 1105 if (II) { 1106 Specifier = II->getName(); 1107 SpecifierValid = llvm::StringSwitch<bool>(Specifier) 1108 .Cases("default", "disable", "error", "once", 1109 "suppress", true) 1110 .Default(false); 1111 // If we read a correct specifier, snatch next token (that should be 1112 // ":", checked later). 1113 if (SpecifierValid) 1114 PP.Lex(Tok); 1115 } else { 1116 // Token is a numeric constant. It should be either 1, 2, 3 or 4. 1117 uint64_t Value; 1118 Specifier = PP.getSpelling(Tok, SpecifierBuf); 1119 if (PP.parseSimpleIntegerLiteral(Tok, Value)) { 1120 SpecifierValid = (Value >= 1) && (Value <= 4); 1121 } else 1122 SpecifierValid = false; 1123 // Next token already snatched by parseSimpleIntegerLiteral. 1124 } 1125 1126 if (!SpecifierValid) { 1127 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid); 1128 return; 1129 } 1130 if (Tok.isNot(tok::colon)) { 1131 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":"; 1132 return; 1133 } 1134 1135 // Collect the warning ids. 1136 SmallVector<int, 4> Ids; 1137 PP.Lex(Tok); 1138 while (Tok.is(tok::numeric_constant)) { 1139 uint64_t Value; 1140 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 || 1141 Value > INT_MAX) { 1142 PP.Diag(Tok, diag::warn_pragma_warning_expected_number); 1143 return; 1144 } 1145 Ids.push_back(int(Value)); 1146 } 1147 if (Callbacks) 1148 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids); 1149 1150 // Parse the next specifier if there is a semicolon. 1151 if (Tok.isNot(tok::semi)) 1152 break; 1153 PP.Lex(Tok); 1154 } 1155 } 1156 1157 if (Tok.isNot(tok::r_paren)) { 1158 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")"; 1159 return; 1160 } 1161 1162 PP.Lex(Tok); 1163 if (Tok.isNot(tok::eod)) 1164 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning"; 1165 } 1166 }; 1167 1168 /// PragmaIncludeAliasHandler - "\#pragma include_alias("...")". 1169 struct PragmaIncludeAliasHandler : public PragmaHandler { 1170 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {} 1171 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1172 Token &IncludeAliasTok) override { 1173 PP.HandlePragmaIncludeAlias(IncludeAliasTok); 1174 } 1175 }; 1176 1177 /// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message 1178 /// extension. The syntax is: 1179 /// \code 1180 /// #pragma message(string) 1181 /// \endcode 1182 /// OR, in GCC mode: 1183 /// \code 1184 /// #pragma message string 1185 /// \endcode 1186 /// string is a string, which is fully macro expanded, and permits string 1187 /// concatenation, embedded escape characters, etc... See MSDN for more details. 1188 /// Also handles \#pragma GCC warning and \#pragma GCC error which take the same 1189 /// form as \#pragma message. 1190 struct PragmaMessageHandler : public PragmaHandler { 1191 private: 1192 const PPCallbacks::PragmaMessageKind Kind; 1193 const StringRef Namespace; 1194 1195 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind, 1196 bool PragmaNameOnly = false) { 1197 switch (Kind) { 1198 case PPCallbacks::PMK_Message: 1199 return PragmaNameOnly ? "message" : "pragma message"; 1200 case PPCallbacks::PMK_Warning: 1201 return PragmaNameOnly ? "warning" : "pragma warning"; 1202 case PPCallbacks::PMK_Error: 1203 return PragmaNameOnly ? "error" : "pragma error"; 1204 } 1205 llvm_unreachable("Unknown PragmaMessageKind!"); 1206 } 1207 1208 public: 1209 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind, 1210 StringRef Namespace = StringRef()) 1211 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), Namespace(Namespace) {} 1212 1213 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1214 Token &Tok) override { 1215 SourceLocation MessageLoc = Tok.getLocation(); 1216 PP.Lex(Tok); 1217 bool ExpectClosingParen = false; 1218 switch (Tok.getKind()) { 1219 case tok::l_paren: 1220 // We have a MSVC style pragma message. 1221 ExpectClosingParen = true; 1222 // Read the string. 1223 PP.Lex(Tok); 1224 break; 1225 case tok::string_literal: 1226 // We have a GCC style pragma message, and we just read the string. 1227 break; 1228 default: 1229 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind; 1230 return; 1231 } 1232 1233 std::string MessageString; 1234 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind), 1235 /*MacroExpansion=*/true)) 1236 return; 1237 1238 if (ExpectClosingParen) { 1239 if (Tok.isNot(tok::r_paren)) { 1240 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind; 1241 return; 1242 } 1243 PP.Lex(Tok); // eat the r_paren. 1244 } 1245 1246 if (Tok.isNot(tok::eod)) { 1247 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind; 1248 return; 1249 } 1250 1251 // Output the message. 1252 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error) 1253 ? diag::err_pragma_message 1254 : diag::warn_pragma_message) << MessageString; 1255 1256 // If the pragma is lexically sound, notify any interested PPCallbacks. 1257 if (PPCallbacks *Callbacks = PP.getPPCallbacks()) 1258 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString); 1259 } 1260 }; 1261 1262 /// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the 1263 /// macro on the top of the stack. 1264 struct PragmaPushMacroHandler : public PragmaHandler { 1265 PragmaPushMacroHandler() : PragmaHandler("push_macro") {} 1266 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1267 Token &PushMacroTok) override { 1268 PP.HandlePragmaPushMacro(PushMacroTok); 1269 } 1270 }; 1271 1272 1273 /// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the 1274 /// macro to the value on the top of the stack. 1275 struct PragmaPopMacroHandler : public PragmaHandler { 1276 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {} 1277 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1278 Token &PopMacroTok) override { 1279 PP.HandlePragmaPopMacro(PopMacroTok); 1280 } 1281 }; 1282 1283 // Pragma STDC implementations. 1284 1285 /// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...". 1286 struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler { 1287 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {} 1288 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1289 Token &Tok) override { 1290 tok::OnOffSwitch OOS; 1291 if (PP.LexOnOffSwitch(OOS)) 1292 return; 1293 if (OOS == tok::OOS_ON) 1294 PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported); 1295 } 1296 }; 1297 1298 /// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...". 1299 struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler { 1300 PragmaSTDC_CX_LIMITED_RANGEHandler() 1301 : PragmaHandler("CX_LIMITED_RANGE") {} 1302 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1303 Token &Tok) override { 1304 tok::OnOffSwitch OOS; 1305 PP.LexOnOffSwitch(OOS); 1306 } 1307 }; 1308 1309 /// PragmaSTDC_UnknownHandler - "\#pragma STDC ...". 1310 struct PragmaSTDC_UnknownHandler : public PragmaHandler { 1311 PragmaSTDC_UnknownHandler() {} 1312 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1313 Token &UnknownTok) override { 1314 // C99 6.10.6p2, unknown forms are not allowed. 1315 PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored); 1316 } 1317 }; 1318 1319 /// PragmaARCCFCodeAuditedHandler - 1320 /// \#pragma clang arc_cf_code_audited begin/end 1321 struct PragmaARCCFCodeAuditedHandler : public PragmaHandler { 1322 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {} 1323 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1324 Token &NameTok) override { 1325 SourceLocation Loc = NameTok.getLocation(); 1326 bool IsBegin; 1327 1328 Token Tok; 1329 1330 // Lex the 'begin' or 'end'. 1331 PP.LexUnexpandedToken(Tok); 1332 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo(); 1333 if (BeginEnd && BeginEnd->isStr("begin")) { 1334 IsBegin = true; 1335 } else if (BeginEnd && BeginEnd->isStr("end")) { 1336 IsBegin = false; 1337 } else { 1338 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax); 1339 return; 1340 } 1341 1342 // Verify that this is followed by EOD. 1343 PP.LexUnexpandedToken(Tok); 1344 if (Tok.isNot(tok::eod)) 1345 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma"; 1346 1347 // The start location of the active audit. 1348 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc(); 1349 1350 // The start location we want after processing this. 1351 SourceLocation NewLoc; 1352 1353 if (IsBegin) { 1354 // Complain about attempts to re-enter an audit. 1355 if (BeginLoc.isValid()) { 1356 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited); 1357 PP.Diag(BeginLoc, diag::note_pragma_entered_here); 1358 } 1359 NewLoc = Loc; 1360 } else { 1361 // Complain about attempts to leave an audit that doesn't exist. 1362 if (!BeginLoc.isValid()) { 1363 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited); 1364 return; 1365 } 1366 NewLoc = SourceLocation(); 1367 } 1368 1369 PP.setPragmaARCCFCodeAuditedLoc(NewLoc); 1370 } 1371 }; 1372 1373 /// PragmaAssumeNonNullHandler - 1374 /// \#pragma clang assume_nonnull begin/end 1375 struct PragmaAssumeNonNullHandler : public PragmaHandler { 1376 PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {} 1377 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1378 Token &NameTok) override { 1379 SourceLocation Loc = NameTok.getLocation(); 1380 bool IsBegin; 1381 1382 Token Tok; 1383 1384 // Lex the 'begin' or 'end'. 1385 PP.LexUnexpandedToken(Tok); 1386 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo(); 1387 if (BeginEnd && BeginEnd->isStr("begin")) { 1388 IsBegin = true; 1389 } else if (BeginEnd && BeginEnd->isStr("end")) { 1390 IsBegin = false; 1391 } else { 1392 PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax); 1393 return; 1394 } 1395 1396 // Verify that this is followed by EOD. 1397 PP.LexUnexpandedToken(Tok); 1398 if (Tok.isNot(tok::eod)) 1399 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma"; 1400 1401 // The start location of the active audit. 1402 SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc(); 1403 1404 // The start location we want after processing this. 1405 SourceLocation NewLoc; 1406 1407 if (IsBegin) { 1408 // Complain about attempts to re-enter an audit. 1409 if (BeginLoc.isValid()) { 1410 PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull); 1411 PP.Diag(BeginLoc, diag::note_pragma_entered_here); 1412 } 1413 NewLoc = Loc; 1414 } else { 1415 // Complain about attempts to leave an audit that doesn't exist. 1416 if (!BeginLoc.isValid()) { 1417 PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull); 1418 return; 1419 } 1420 NewLoc = SourceLocation(); 1421 } 1422 1423 PP.setPragmaAssumeNonNullLoc(NewLoc); 1424 } 1425 }; 1426 1427 /// \brief Handle "\#pragma region [...]" 1428 /// 1429 /// The syntax is 1430 /// \code 1431 /// #pragma region [optional name] 1432 /// #pragma endregion [optional comment] 1433 /// \endcode 1434 /// 1435 /// \note This is 1436 /// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a> 1437 /// pragma, just skipped by compiler. 1438 struct PragmaRegionHandler : public PragmaHandler { 1439 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) { } 1440 1441 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1442 Token &NameTok) override { 1443 // #pragma region: endregion matches can be verified 1444 // __pragma(region): no sense, but ignored by msvc 1445 // _Pragma is not valid for MSVC, but there isn't any point 1446 // to handle a _Pragma differently. 1447 } 1448 }; 1449 1450 } // end anonymous namespace 1451 1452 1453 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas: 1454 /// \#pragma GCC poison/system_header/dependency and \#pragma once. 1455 void Preprocessor::RegisterBuiltinPragmas() { 1456 AddPragmaHandler(new PragmaOnceHandler()); 1457 AddPragmaHandler(new PragmaMarkHandler()); 1458 AddPragmaHandler(new PragmaPushMacroHandler()); 1459 AddPragmaHandler(new PragmaPopMacroHandler()); 1460 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message)); 1461 1462 // #pragma GCC ... 1463 AddPragmaHandler("GCC", new PragmaPoisonHandler()); 1464 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler()); 1465 AddPragmaHandler("GCC", new PragmaDependencyHandler()); 1466 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC")); 1467 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning, 1468 "GCC")); 1469 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error, 1470 "GCC")); 1471 // #pragma clang ... 1472 AddPragmaHandler("clang", new PragmaPoisonHandler()); 1473 AddPragmaHandler("clang", new PragmaSystemHeaderHandler()); 1474 AddPragmaHandler("clang", new PragmaDebugHandler()); 1475 AddPragmaHandler("clang", new PragmaDependencyHandler()); 1476 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang")); 1477 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler()); 1478 AddPragmaHandler("clang", new PragmaAssumeNonNullHandler()); 1479 1480 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler()); 1481 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler()); 1482 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler()); 1483 1484 // MS extensions. 1485 if (LangOpts.MicrosoftExt) { 1486 AddPragmaHandler(new PragmaWarningHandler()); 1487 AddPragmaHandler(new PragmaIncludeAliasHandler()); 1488 AddPragmaHandler(new PragmaRegionHandler("region")); 1489 AddPragmaHandler(new PragmaRegionHandler("endregion")); 1490 } 1491 1492 // Pragmas added by plugins 1493 for (PragmaHandlerRegistry::iterator it = PragmaHandlerRegistry::begin(), 1494 ie = PragmaHandlerRegistry::end(); 1495 it != ie; ++it) { 1496 AddPragmaHandler(it->instantiate().release()); 1497 } 1498 } 1499 1500 /// Ignore all pragmas, useful for modes such as -Eonly which would otherwise 1501 /// warn about those pragmas being unknown. 1502 void Preprocessor::IgnorePragmas() { 1503 AddPragmaHandler(new EmptyPragmaHandler()); 1504 // Also ignore all pragmas in all namespaces created 1505 // in Preprocessor::RegisterBuiltinPragmas(). 1506 AddPragmaHandler("GCC", new EmptyPragmaHandler()); 1507 AddPragmaHandler("clang", new EmptyPragmaHandler()); 1508 if (PragmaHandler *NS = PragmaHandlers->FindHandler("STDC")) { 1509 // Preprocessor::RegisterBuiltinPragmas() already registers 1510 // PragmaSTDC_UnknownHandler as the empty handler, so remove it first, 1511 // otherwise there will be an assert about a duplicate handler. 1512 PragmaNamespace *STDCNamespace = NS->getIfNamespace(); 1513 assert(STDCNamespace && 1514 "Invalid namespace, registered as a regular pragma handler!"); 1515 if (PragmaHandler *Existing = STDCNamespace->FindHandler("", false)) { 1516 RemovePragmaHandler("STDC", Existing); 1517 delete Existing; 1518 } 1519 } 1520 AddPragmaHandler("STDC", new EmptyPragmaHandler()); 1521 } 1522