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