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 (isMacroDefined(II)) 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 (MacroInfo *MI = getMacroInfo(IdentInfo)) { 594 if (MI->isWarnIfUnused()) 595 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc()); 596 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc)); 597 } 598 599 // Get the MacroInfo we want to reinstall. 600 MacroInfo *MacroToReInstall = iter->second.back(); 601 602 if (MacroToReInstall) 603 // Reinstall the previously pushed macro. 604 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc); 605 606 // Pop PragmaPushMacroInfo stack. 607 iter->second.pop_back(); 608 if (iter->second.size() == 0) 609 PragmaPushMacroInfo.erase(iter); 610 } else { 611 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push) 612 << IdentInfo->getName(); 613 } 614 } 615 616 void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) { 617 // We will either get a quoted filename or a bracketed filename, and we 618 // have to track which we got. The first filename is the source name, 619 // and the second name is the mapped filename. If the first is quoted, 620 // the second must be as well (cannot mix and match quotes and brackets). 621 622 // Get the open paren 623 Lex(Tok); 624 if (Tok.isNot(tok::l_paren)) { 625 Diag(Tok, diag::warn_pragma_include_alias_expected) << "("; 626 return; 627 } 628 629 // We expect either a quoted string literal, or a bracketed name 630 Token SourceFilenameTok; 631 CurPPLexer->LexIncludeFilename(SourceFilenameTok); 632 if (SourceFilenameTok.is(tok::eod)) { 633 // The diagnostic has already been handled 634 return; 635 } 636 637 StringRef SourceFileName; 638 SmallString<128> FileNameBuffer; 639 if (SourceFilenameTok.is(tok::string_literal) || 640 SourceFilenameTok.is(tok::angle_string_literal)) { 641 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer); 642 } else if (SourceFilenameTok.is(tok::less)) { 643 // This could be a path instead of just a name 644 FileNameBuffer.push_back('<'); 645 SourceLocation End; 646 if (ConcatenateIncludeName(FileNameBuffer, End)) 647 return; // Diagnostic already emitted 648 SourceFileName = FileNameBuffer; 649 } else { 650 Diag(Tok, diag::warn_pragma_include_alias_expected_filename); 651 return; 652 } 653 FileNameBuffer.clear(); 654 655 // Now we expect a comma, followed by another include name 656 Lex(Tok); 657 if (Tok.isNot(tok::comma)) { 658 Diag(Tok, diag::warn_pragma_include_alias_expected) << ","; 659 return; 660 } 661 662 Token ReplaceFilenameTok; 663 CurPPLexer->LexIncludeFilename(ReplaceFilenameTok); 664 if (ReplaceFilenameTok.is(tok::eod)) { 665 // The diagnostic has already been handled 666 return; 667 } 668 669 StringRef ReplaceFileName; 670 if (ReplaceFilenameTok.is(tok::string_literal) || 671 ReplaceFilenameTok.is(tok::angle_string_literal)) { 672 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer); 673 } else if (ReplaceFilenameTok.is(tok::less)) { 674 // This could be a path instead of just a name 675 FileNameBuffer.push_back('<'); 676 SourceLocation End; 677 if (ConcatenateIncludeName(FileNameBuffer, End)) 678 return; // Diagnostic already emitted 679 ReplaceFileName = FileNameBuffer; 680 } else { 681 Diag(Tok, diag::warn_pragma_include_alias_expected_filename); 682 return; 683 } 684 685 // Finally, we expect the closing paren 686 Lex(Tok); 687 if (Tok.isNot(tok::r_paren)) { 688 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")"; 689 return; 690 } 691 692 // Now that we have the source and target filenames, we need to make sure 693 // they're both of the same type (angled vs non-angled) 694 StringRef OriginalSource = SourceFileName; 695 696 bool SourceIsAngled = 697 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(), 698 SourceFileName); 699 bool ReplaceIsAngled = 700 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(), 701 ReplaceFileName); 702 if (!SourceFileName.empty() && !ReplaceFileName.empty() && 703 (SourceIsAngled != ReplaceIsAngled)) { 704 unsigned int DiagID; 705 if (SourceIsAngled) 706 DiagID = diag::warn_pragma_include_alias_mismatch_angle; 707 else 708 DiagID = diag::warn_pragma_include_alias_mismatch_quote; 709 710 Diag(SourceFilenameTok.getLocation(), DiagID) 711 << SourceFileName 712 << ReplaceFileName; 713 714 return; 715 } 716 717 // Now we can let the include handler know about this mapping 718 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName); 719 } 720 721 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor. 722 /// If 'Namespace' is non-null, then it is a token required to exist on the 723 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC". 724 void Preprocessor::AddPragmaHandler(StringRef Namespace, 725 PragmaHandler *Handler) { 726 PragmaNamespace *InsertNS = PragmaHandlers.get(); 727 728 // If this is specified to be in a namespace, step down into it. 729 if (!Namespace.empty()) { 730 // If there is already a pragma handler with the name of this namespace, 731 // we either have an error (directive with the same name as a namespace) or 732 // we already have the namespace to insert into. 733 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) { 734 InsertNS = Existing->getIfNamespace(); 735 assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma" 736 " handler with the same name!"); 737 } else { 738 // Otherwise, this namespace doesn't exist yet, create and insert the 739 // handler for it. 740 InsertNS = new PragmaNamespace(Namespace); 741 PragmaHandlers->AddPragma(InsertNS); 742 } 743 } 744 745 // Check to make sure we don't already have a pragma for this identifier. 746 assert(!InsertNS->FindHandler(Handler->getName()) && 747 "Pragma handler already exists for this identifier!"); 748 InsertNS->AddPragma(Handler); 749 } 750 751 /// RemovePragmaHandler - Remove the specific pragma handler from the 752 /// preprocessor. If \arg Namespace is non-null, then it should be the 753 /// namespace that \arg Handler was added to. It is an error to remove 754 /// a handler that has not been registered. 755 void Preprocessor::RemovePragmaHandler(StringRef Namespace, 756 PragmaHandler *Handler) { 757 PragmaNamespace *NS = PragmaHandlers.get(); 758 759 // If this is specified to be in a namespace, step down into it. 760 if (!Namespace.empty()) { 761 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace); 762 assert(Existing && "Namespace containing handler does not exist!"); 763 764 NS = Existing->getIfNamespace(); 765 assert(NS && "Invalid namespace, registered as a regular pragma handler!"); 766 } 767 768 NS->RemovePragmaHandler(Handler); 769 770 // If this is a non-default namespace and it is now empty, remove it. 771 if (NS != PragmaHandlers.get() && NS->IsEmpty()) { 772 PragmaHandlers->RemovePragmaHandler(NS); 773 delete NS; 774 } 775 } 776 777 bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) { 778 Token Tok; 779 LexUnexpandedToken(Tok); 780 781 if (Tok.isNot(tok::identifier)) { 782 Diag(Tok, diag::ext_on_off_switch_syntax); 783 return true; 784 } 785 IdentifierInfo *II = Tok.getIdentifierInfo(); 786 if (II->isStr("ON")) 787 Result = tok::OOS_ON; 788 else if (II->isStr("OFF")) 789 Result = tok::OOS_OFF; 790 else if (II->isStr("DEFAULT")) 791 Result = tok::OOS_DEFAULT; 792 else { 793 Diag(Tok, diag::ext_on_off_switch_syntax); 794 return true; 795 } 796 797 // Verify that this is followed by EOD. 798 LexUnexpandedToken(Tok); 799 if (Tok.isNot(tok::eod)) 800 Diag(Tok, diag::ext_pragma_syntax_eod); 801 return false; 802 } 803 804 namespace { 805 /// PragmaOnceHandler - "\#pragma once" marks the file as atomically included. 806 struct PragmaOnceHandler : public PragmaHandler { 807 PragmaOnceHandler() : PragmaHandler("once") {} 808 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 809 Token &OnceTok) override { 810 PP.CheckEndOfDirective("pragma once"); 811 PP.HandlePragmaOnce(OnceTok); 812 } 813 }; 814 815 /// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the 816 /// rest of the line is not lexed. 817 struct PragmaMarkHandler : public PragmaHandler { 818 PragmaMarkHandler() : PragmaHandler("mark") {} 819 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 820 Token &MarkTok) override { 821 PP.HandlePragmaMark(); 822 } 823 }; 824 825 /// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable. 826 struct PragmaPoisonHandler : public PragmaHandler { 827 PragmaPoisonHandler() : PragmaHandler("poison") {} 828 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 829 Token &PoisonTok) override { 830 PP.HandlePragmaPoison(PoisonTok); 831 } 832 }; 833 834 /// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file 835 /// as a system header, which silences warnings in it. 836 struct PragmaSystemHeaderHandler : public PragmaHandler { 837 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {} 838 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 839 Token &SHToken) override { 840 PP.HandlePragmaSystemHeader(SHToken); 841 PP.CheckEndOfDirective("pragma"); 842 } 843 }; 844 struct PragmaDependencyHandler : public PragmaHandler { 845 PragmaDependencyHandler() : PragmaHandler("dependency") {} 846 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 847 Token &DepToken) override { 848 PP.HandlePragmaDependency(DepToken); 849 } 850 }; 851 852 struct PragmaDebugHandler : public PragmaHandler { 853 PragmaDebugHandler() : PragmaHandler("__debug") {} 854 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 855 Token &DepToken) override { 856 Token Tok; 857 PP.LexUnexpandedToken(Tok); 858 if (Tok.isNot(tok::identifier)) { 859 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid); 860 return; 861 } 862 IdentifierInfo *II = Tok.getIdentifierInfo(); 863 864 if (II->isStr("assert")) { 865 llvm_unreachable("This is an assertion!"); 866 } else if (II->isStr("crash")) { 867 LLVM_BUILTIN_TRAP; 868 } else if (II->isStr("parser_crash")) { 869 Token Crasher; 870 Crasher.startToken(); 871 Crasher.setKind(tok::annot_pragma_parser_crash); 872 Crasher.setAnnotationRange(SourceRange(Tok.getLocation())); 873 PP.EnterToken(Crasher); 874 } else if (II->isStr("llvm_fatal_error")) { 875 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error"); 876 } else if (II->isStr("llvm_unreachable")) { 877 llvm_unreachable("#pragma clang __debug llvm_unreachable"); 878 } else if (II->isStr("macro")) { 879 Token MacroName; 880 PP.LexUnexpandedToken(MacroName); 881 auto *MacroII = MacroName.getIdentifierInfo(); 882 if (MacroII) 883 PP.dumpMacroInfo(MacroII); 884 else 885 PP.Diag(MacroName, diag::warn_pragma_diagnostic_invalid); 886 } else if (II->isStr("overflow_stack")) { 887 DebugOverflowStack(); 888 } else if (II->isStr("handle_crash")) { 889 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent(); 890 if (CRC) 891 CRC->HandleCrash(); 892 } else if (II->isStr("captured")) { 893 HandleCaptured(PP); 894 } else { 895 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command) 896 << II->getName(); 897 } 898 899 PPCallbacks *Callbacks = PP.getPPCallbacks(); 900 if (Callbacks) 901 Callbacks->PragmaDebug(Tok.getLocation(), II->getName()); 902 } 903 904 void HandleCaptured(Preprocessor &PP) { 905 // Skip if emitting preprocessed output. 906 if (PP.isPreprocessedOutput()) 907 return; 908 909 Token Tok; 910 PP.LexUnexpandedToken(Tok); 911 912 if (Tok.isNot(tok::eod)) { 913 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) 914 << "pragma clang __debug captured"; 915 return; 916 } 917 918 SourceLocation NameLoc = Tok.getLocation(); 919 Token *Toks = PP.getPreprocessorAllocator().Allocate<Token>(1); 920 Toks->startToken(); 921 Toks->setKind(tok::annot_pragma_captured); 922 Toks->setLocation(NameLoc); 923 924 PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true, 925 /*OwnsTokens=*/false); 926 } 927 928 // Disable MSVC warning about runtime stack overflow. 929 #ifdef _MSC_VER 930 #pragma warning(disable : 4717) 931 #endif 932 static void DebugOverflowStack() { 933 void (*volatile Self)() = DebugOverflowStack; 934 Self(); 935 } 936 #ifdef _MSC_VER 937 #pragma warning(default : 4717) 938 #endif 939 940 }; 941 942 /// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"' 943 struct PragmaDiagnosticHandler : public PragmaHandler { 944 private: 945 const char *Namespace; 946 public: 947 explicit PragmaDiagnosticHandler(const char *NS) : 948 PragmaHandler("diagnostic"), Namespace(NS) {} 949 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 950 Token &DiagToken) override { 951 SourceLocation DiagLoc = DiagToken.getLocation(); 952 Token Tok; 953 PP.LexUnexpandedToken(Tok); 954 if (Tok.isNot(tok::identifier)) { 955 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid); 956 return; 957 } 958 IdentifierInfo *II = Tok.getIdentifierInfo(); 959 PPCallbacks *Callbacks = PP.getPPCallbacks(); 960 961 if (II->isStr("pop")) { 962 if (!PP.getDiagnostics().popMappings(DiagLoc)) 963 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop); 964 else if (Callbacks) 965 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace); 966 return; 967 } else if (II->isStr("push")) { 968 PP.getDiagnostics().pushMappings(DiagLoc); 969 if (Callbacks) 970 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace); 971 return; 972 } 973 974 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName()) 975 .Case("ignored", diag::Severity::Ignored) 976 .Case("warning", diag::Severity::Warning) 977 .Case("error", diag::Severity::Error) 978 .Case("fatal", diag::Severity::Fatal) 979 .Default(diag::Severity()); 980 981 if (SV == diag::Severity()) { 982 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid); 983 return; 984 } 985 986 PP.LexUnexpandedToken(Tok); 987 SourceLocation StringLoc = Tok.getLocation(); 988 989 std::string WarningName; 990 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic", 991 /*MacroExpansion=*/false)) 992 return; 993 994 if (Tok.isNot(tok::eod)) { 995 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token); 996 return; 997 } 998 999 if (WarningName.size() < 3 || WarningName[0] != '-' || 1000 (WarningName[1] != 'W' && WarningName[1] != 'R')) { 1001 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option); 1002 return; 1003 } 1004 1005 if (PP.getDiagnostics().setSeverityForGroup( 1006 WarningName[1] == 'W' ? diag::Flavor::WarningOrError 1007 : diag::Flavor::Remark, 1008 WarningName.substr(2), SV, DiagLoc)) 1009 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning) 1010 << WarningName; 1011 else if (Callbacks) 1012 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName); 1013 } 1014 }; 1015 1016 /// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's 1017 /// diagnostics, so we don't really implement this pragma. We parse it and 1018 /// ignore it to avoid -Wunknown-pragma warnings. 1019 struct PragmaWarningHandler : public PragmaHandler { 1020 PragmaWarningHandler() : PragmaHandler("warning") {} 1021 1022 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1023 Token &Tok) override { 1024 // Parse things like: 1025 // warning(push, 1) 1026 // warning(pop) 1027 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9) 1028 SourceLocation DiagLoc = Tok.getLocation(); 1029 PPCallbacks *Callbacks = PP.getPPCallbacks(); 1030 1031 PP.Lex(Tok); 1032 if (Tok.isNot(tok::l_paren)) { 1033 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "("; 1034 return; 1035 } 1036 1037 PP.Lex(Tok); 1038 IdentifierInfo *II = Tok.getIdentifierInfo(); 1039 if (!II) { 1040 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid); 1041 return; 1042 } 1043 1044 if (II->isStr("push")) { 1045 // #pragma warning( push[ ,n ] ) 1046 int Level = -1; 1047 PP.Lex(Tok); 1048 if (Tok.is(tok::comma)) { 1049 PP.Lex(Tok); 1050 uint64_t Value; 1051 if (Tok.is(tok::numeric_constant) && 1052 PP.parseSimpleIntegerLiteral(Tok, Value)) 1053 Level = int(Value); 1054 if (Level < 0 || Level > 4) { 1055 PP.Diag(Tok, diag::warn_pragma_warning_push_level); 1056 return; 1057 } 1058 } 1059 if (Callbacks) 1060 Callbacks->PragmaWarningPush(DiagLoc, Level); 1061 } else if (II->isStr("pop")) { 1062 // #pragma warning( pop ) 1063 PP.Lex(Tok); 1064 if (Callbacks) 1065 Callbacks->PragmaWarningPop(DiagLoc); 1066 } else { 1067 // #pragma warning( warning-specifier : warning-number-list 1068 // [; warning-specifier : warning-number-list...] ) 1069 while (true) { 1070 II = Tok.getIdentifierInfo(); 1071 if (!II) { 1072 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid); 1073 return; 1074 } 1075 1076 // Figure out which warning specifier this is. 1077 StringRef Specifier = II->getName(); 1078 bool SpecifierValid = 1079 llvm::StringSwitch<bool>(Specifier) 1080 .Cases("1", "2", "3", "4", true) 1081 .Cases("default", "disable", "error", "once", "suppress", true) 1082 .Default(false); 1083 if (!SpecifierValid) { 1084 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid); 1085 return; 1086 } 1087 PP.Lex(Tok); 1088 if (Tok.isNot(tok::colon)) { 1089 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":"; 1090 return; 1091 } 1092 1093 // Collect the warning ids. 1094 SmallVector<int, 4> Ids; 1095 PP.Lex(Tok); 1096 while (Tok.is(tok::numeric_constant)) { 1097 uint64_t Value; 1098 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 || 1099 Value > INT_MAX) { 1100 PP.Diag(Tok, diag::warn_pragma_warning_expected_number); 1101 return; 1102 } 1103 Ids.push_back(int(Value)); 1104 } 1105 if (Callbacks) 1106 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids); 1107 1108 // Parse the next specifier if there is a semicolon. 1109 if (Tok.isNot(tok::semi)) 1110 break; 1111 PP.Lex(Tok); 1112 } 1113 } 1114 1115 if (Tok.isNot(tok::r_paren)) { 1116 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")"; 1117 return; 1118 } 1119 1120 PP.Lex(Tok); 1121 if (Tok.isNot(tok::eod)) 1122 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning"; 1123 } 1124 }; 1125 1126 /// PragmaIncludeAliasHandler - "\#pragma include_alias("...")". 1127 struct PragmaIncludeAliasHandler : public PragmaHandler { 1128 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {} 1129 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1130 Token &IncludeAliasTok) override { 1131 PP.HandlePragmaIncludeAlias(IncludeAliasTok); 1132 } 1133 }; 1134 1135 /// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message 1136 /// extension. The syntax is: 1137 /// \code 1138 /// #pragma message(string) 1139 /// \endcode 1140 /// OR, in GCC mode: 1141 /// \code 1142 /// #pragma message string 1143 /// \endcode 1144 /// string is a string, which is fully macro expanded, and permits string 1145 /// concatenation, embedded escape characters, etc... See MSDN for more details. 1146 /// Also handles \#pragma GCC warning and \#pragma GCC error which take the same 1147 /// form as \#pragma message. 1148 struct PragmaMessageHandler : public PragmaHandler { 1149 private: 1150 const PPCallbacks::PragmaMessageKind Kind; 1151 const StringRef Namespace; 1152 1153 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind, 1154 bool PragmaNameOnly = false) { 1155 switch (Kind) { 1156 case PPCallbacks::PMK_Message: 1157 return PragmaNameOnly ? "message" : "pragma message"; 1158 case PPCallbacks::PMK_Warning: 1159 return PragmaNameOnly ? "warning" : "pragma warning"; 1160 case PPCallbacks::PMK_Error: 1161 return PragmaNameOnly ? "error" : "pragma error"; 1162 } 1163 llvm_unreachable("Unknown PragmaMessageKind!"); 1164 } 1165 1166 public: 1167 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind, 1168 StringRef Namespace = StringRef()) 1169 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), Namespace(Namespace) {} 1170 1171 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1172 Token &Tok) override { 1173 SourceLocation MessageLoc = Tok.getLocation(); 1174 PP.Lex(Tok); 1175 bool ExpectClosingParen = false; 1176 switch (Tok.getKind()) { 1177 case tok::l_paren: 1178 // We have a MSVC style pragma message. 1179 ExpectClosingParen = true; 1180 // Read the string. 1181 PP.Lex(Tok); 1182 break; 1183 case tok::string_literal: 1184 // We have a GCC style pragma message, and we just read the string. 1185 break; 1186 default: 1187 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind; 1188 return; 1189 } 1190 1191 std::string MessageString; 1192 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind), 1193 /*MacroExpansion=*/true)) 1194 return; 1195 1196 if (ExpectClosingParen) { 1197 if (Tok.isNot(tok::r_paren)) { 1198 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind; 1199 return; 1200 } 1201 PP.Lex(Tok); // eat the r_paren. 1202 } 1203 1204 if (Tok.isNot(tok::eod)) { 1205 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind; 1206 return; 1207 } 1208 1209 // Output the message. 1210 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error) 1211 ? diag::err_pragma_message 1212 : diag::warn_pragma_message) << MessageString; 1213 1214 // If the pragma is lexically sound, notify any interested PPCallbacks. 1215 if (PPCallbacks *Callbacks = PP.getPPCallbacks()) 1216 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString); 1217 } 1218 }; 1219 1220 /// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the 1221 /// macro on the top of the stack. 1222 struct PragmaPushMacroHandler : public PragmaHandler { 1223 PragmaPushMacroHandler() : PragmaHandler("push_macro") {} 1224 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1225 Token &PushMacroTok) override { 1226 PP.HandlePragmaPushMacro(PushMacroTok); 1227 } 1228 }; 1229 1230 1231 /// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the 1232 /// macro to the value on the top of the stack. 1233 struct PragmaPopMacroHandler : public PragmaHandler { 1234 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {} 1235 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1236 Token &PopMacroTok) override { 1237 PP.HandlePragmaPopMacro(PopMacroTok); 1238 } 1239 }; 1240 1241 // Pragma STDC implementations. 1242 1243 /// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...". 1244 struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler { 1245 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {} 1246 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1247 Token &Tok) override { 1248 tok::OnOffSwitch OOS; 1249 if (PP.LexOnOffSwitch(OOS)) 1250 return; 1251 if (OOS == tok::OOS_ON) 1252 PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported); 1253 } 1254 }; 1255 1256 /// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...". 1257 struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler { 1258 PragmaSTDC_CX_LIMITED_RANGEHandler() 1259 : PragmaHandler("CX_LIMITED_RANGE") {} 1260 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1261 Token &Tok) override { 1262 tok::OnOffSwitch OOS; 1263 PP.LexOnOffSwitch(OOS); 1264 } 1265 }; 1266 1267 /// PragmaSTDC_UnknownHandler - "\#pragma STDC ...". 1268 struct PragmaSTDC_UnknownHandler : public PragmaHandler { 1269 PragmaSTDC_UnknownHandler() {} 1270 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1271 Token &UnknownTok) override { 1272 // C99 6.10.6p2, unknown forms are not allowed. 1273 PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored); 1274 } 1275 }; 1276 1277 /// PragmaARCCFCodeAuditedHandler - 1278 /// \#pragma clang arc_cf_code_audited begin/end 1279 struct PragmaARCCFCodeAuditedHandler : public PragmaHandler { 1280 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {} 1281 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1282 Token &NameTok) override { 1283 SourceLocation Loc = NameTok.getLocation(); 1284 bool IsBegin; 1285 1286 Token Tok; 1287 1288 // Lex the 'begin' or 'end'. 1289 PP.LexUnexpandedToken(Tok); 1290 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo(); 1291 if (BeginEnd && BeginEnd->isStr("begin")) { 1292 IsBegin = true; 1293 } else if (BeginEnd && BeginEnd->isStr("end")) { 1294 IsBegin = false; 1295 } else { 1296 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax); 1297 return; 1298 } 1299 1300 // Verify that this is followed by EOD. 1301 PP.LexUnexpandedToken(Tok); 1302 if (Tok.isNot(tok::eod)) 1303 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma"; 1304 1305 // The start location of the active audit. 1306 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc(); 1307 1308 // The start location we want after processing this. 1309 SourceLocation NewLoc; 1310 1311 if (IsBegin) { 1312 // Complain about attempts to re-enter an audit. 1313 if (BeginLoc.isValid()) { 1314 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited); 1315 PP.Diag(BeginLoc, diag::note_pragma_entered_here); 1316 } 1317 NewLoc = Loc; 1318 } else { 1319 // Complain about attempts to leave an audit that doesn't exist. 1320 if (!BeginLoc.isValid()) { 1321 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited); 1322 return; 1323 } 1324 NewLoc = SourceLocation(); 1325 } 1326 1327 PP.setPragmaARCCFCodeAuditedLoc(NewLoc); 1328 } 1329 }; 1330 1331 /// \brief Handle "\#pragma region [...]" 1332 /// 1333 /// The syntax is 1334 /// \code 1335 /// #pragma region [optional name] 1336 /// #pragma endregion [optional comment] 1337 /// \endcode 1338 /// 1339 /// \note This is 1340 /// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a> 1341 /// pragma, just skipped by compiler. 1342 struct PragmaRegionHandler : public PragmaHandler { 1343 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) { } 1344 1345 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1346 Token &NameTok) override { 1347 // #pragma region: endregion matches can be verified 1348 // __pragma(region): no sense, but ignored by msvc 1349 // _Pragma is not valid for MSVC, but there isn't any point 1350 // to handle a _Pragma differently. 1351 } 1352 }; 1353 1354 } // end anonymous namespace 1355 1356 1357 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas: 1358 /// \#pragma GCC poison/system_header/dependency and \#pragma once. 1359 void Preprocessor::RegisterBuiltinPragmas() { 1360 AddPragmaHandler(new PragmaOnceHandler()); 1361 AddPragmaHandler(new PragmaMarkHandler()); 1362 AddPragmaHandler(new PragmaPushMacroHandler()); 1363 AddPragmaHandler(new PragmaPopMacroHandler()); 1364 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message)); 1365 1366 // #pragma GCC ... 1367 AddPragmaHandler("GCC", new PragmaPoisonHandler()); 1368 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler()); 1369 AddPragmaHandler("GCC", new PragmaDependencyHandler()); 1370 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC")); 1371 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning, 1372 "GCC")); 1373 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error, 1374 "GCC")); 1375 // #pragma clang ... 1376 AddPragmaHandler("clang", new PragmaPoisonHandler()); 1377 AddPragmaHandler("clang", new PragmaSystemHeaderHandler()); 1378 AddPragmaHandler("clang", new PragmaDebugHandler()); 1379 AddPragmaHandler("clang", new PragmaDependencyHandler()); 1380 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang")); 1381 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler()); 1382 1383 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler()); 1384 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler()); 1385 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler()); 1386 1387 // MS extensions. 1388 if (LangOpts.MicrosoftExt) { 1389 AddPragmaHandler(new PragmaWarningHandler()); 1390 AddPragmaHandler(new PragmaIncludeAliasHandler()); 1391 AddPragmaHandler(new PragmaRegionHandler("region")); 1392 AddPragmaHandler(new PragmaRegionHandler("endregion")); 1393 } 1394 } 1395 1396 /// Ignore all pragmas, useful for modes such as -Eonly which would otherwise 1397 /// warn about those pragmas being unknown. 1398 void Preprocessor::IgnorePragmas() { 1399 AddPragmaHandler(new EmptyPragmaHandler()); 1400 // Also ignore all pragmas in all namespaces created 1401 // in Preprocessor::RegisterBuiltinPragmas(). 1402 AddPragmaHandler("GCC", new EmptyPragmaHandler()); 1403 AddPragmaHandler("clang", new EmptyPragmaHandler()); 1404 if (PragmaHandler *NS = PragmaHandlers->FindHandler("STDC")) { 1405 // Preprocessor::RegisterBuiltinPragmas() already registers 1406 // PragmaSTDC_UnknownHandler as the empty handler, so remove it first, 1407 // otherwise there will be an assert about a duplicate handler. 1408 PragmaNamespace *STDCNamespace = NS->getIfNamespace(); 1409 assert(STDCNamespace && 1410 "Invalid namespace, registered as a regular pragma handler!"); 1411 if (PragmaHandler *Existing = STDCNamespace->FindHandler("", false)) { 1412 RemovePragmaHandler("STDC", Existing); 1413 delete Existing; 1414 } 1415 } 1416 AddPragmaHandler("STDC", new EmptyPragmaHandler()); 1417 } 1418