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