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