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