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