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 ? 0 : 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 == 0) { 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)) 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, 0); 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, 0, CurDir, NULL, NULL, NULL); 477 if (File == 0) { 478 if (!SuppressIncludeNotFoundError) 479 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename; 480 return; 481 } 482 483 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry(); 484 485 // If this file is older than the file it depends on, emit a diagnostic. 486 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) { 487 // Lex tokens at the end of the message and include them in the message. 488 std::string Message; 489 Lex(DependencyTok); 490 while (DependencyTok.isNot(tok::eod)) { 491 Message += getSpelling(DependencyTok) + " "; 492 Lex(DependencyTok); 493 } 494 495 // Remove the trailing ' ' if present. 496 if (!Message.empty()) 497 Message.erase(Message.end()-1); 498 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message; 499 } 500 } 501 502 /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro. 503 /// Return the IdentifierInfo* associated with the macro to push or pop. 504 IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) { 505 // Remember the pragma token location. 506 Token PragmaTok = Tok; 507 508 // Read the '('. 509 Lex(Tok); 510 if (Tok.isNot(tok::l_paren)) { 511 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed) 512 << getSpelling(PragmaTok); 513 return 0; 514 } 515 516 // Read the macro name string. 517 Lex(Tok); 518 if (Tok.isNot(tok::string_literal)) { 519 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed) 520 << getSpelling(PragmaTok); 521 return 0; 522 } 523 524 if (Tok.hasUDSuffix()) { 525 Diag(Tok, diag::err_invalid_string_udl); 526 return 0; 527 } 528 529 // Remember the macro string. 530 std::string StrVal = getSpelling(Tok); 531 532 // Read the ')'. 533 Lex(Tok); 534 if (Tok.isNot(tok::r_paren)) { 535 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed) 536 << getSpelling(PragmaTok); 537 return 0; 538 } 539 540 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' && 541 "Invalid string token!"); 542 543 // Create a Token from the string. 544 Token MacroTok; 545 MacroTok.startToken(); 546 MacroTok.setKind(tok::raw_identifier); 547 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok); 548 549 // Get the IdentifierInfo of MacroToPushTok. 550 return LookUpIdentifierInfo(MacroTok); 551 } 552 553 /// \brief Handle \#pragma push_macro. 554 /// 555 /// The syntax is: 556 /// \code 557 /// #pragma push_macro("macro") 558 /// \endcode 559 void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) { 560 // Parse the pragma directive and get the macro IdentifierInfo*. 561 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok); 562 if (!IdentInfo) return; 563 564 // Get the MacroInfo associated with IdentInfo. 565 MacroInfo *MI = getMacroInfo(IdentInfo); 566 567 if (MI) { 568 // Allow the original MacroInfo to be redefined later. 569 MI->setIsAllowRedefinitionsWithoutWarning(true); 570 } 571 572 // Push the cloned MacroInfo so we can retrieve it later. 573 PragmaPushMacroInfo[IdentInfo].push_back(MI); 574 } 575 576 /// \brief Handle \#pragma pop_macro. 577 /// 578 /// The syntax is: 579 /// \code 580 /// #pragma pop_macro("macro") 581 /// \endcode 582 void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) { 583 SourceLocation MessageLoc = PopMacroTok.getLocation(); 584 585 // Parse the pragma directive and get the macro IdentifierInfo*. 586 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok); 587 if (!IdentInfo) return; 588 589 // Find the vector<MacroInfo*> associated with the macro. 590 llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter = 591 PragmaPushMacroInfo.find(IdentInfo); 592 if (iter != PragmaPushMacroInfo.end()) { 593 // Forget the MacroInfo currently associated with IdentInfo. 594 if (MacroDirective *CurrentMD = getMacroDirective(IdentInfo)) { 595 MacroInfo *MI = CurrentMD->getMacroInfo(); 596 if (MI->isWarnIfUnused()) 597 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc()); 598 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc)); 599 } 600 601 // Get the MacroInfo we want to reinstall. 602 MacroInfo *MacroToReInstall = iter->second.back(); 603 604 if (MacroToReInstall) { 605 // Reinstall the previously pushed macro. 606 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc, 607 /*isImported=*/false); 608 } 609 610 // Pop PragmaPushMacroInfo stack. 611 iter->second.pop_back(); 612 if (iter->second.size() == 0) 613 PragmaPushMacroInfo.erase(iter); 614 } else { 615 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push) 616 << IdentInfo->getName(); 617 } 618 } 619 620 void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) { 621 // We will either get a quoted filename or a bracketed filename, and we 622 // have to track which we got. The first filename is the source name, 623 // and the second name is the mapped filename. If the first is quoted, 624 // the second must be as well (cannot mix and match quotes and brackets). 625 626 // Get the open paren 627 Lex(Tok); 628 if (Tok.isNot(tok::l_paren)) { 629 Diag(Tok, diag::warn_pragma_include_alias_expected) << "("; 630 return; 631 } 632 633 // We expect either a quoted string literal, or a bracketed name 634 Token SourceFilenameTok; 635 CurPPLexer->LexIncludeFilename(SourceFilenameTok); 636 if (SourceFilenameTok.is(tok::eod)) { 637 // The diagnostic has already been handled 638 return; 639 } 640 641 StringRef SourceFileName; 642 SmallString<128> FileNameBuffer; 643 if (SourceFilenameTok.is(tok::string_literal) || 644 SourceFilenameTok.is(tok::angle_string_literal)) { 645 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer); 646 } else if (SourceFilenameTok.is(tok::less)) { 647 // This could be a path instead of just a name 648 FileNameBuffer.push_back('<'); 649 SourceLocation End; 650 if (ConcatenateIncludeName(FileNameBuffer, End)) 651 return; // Diagnostic already emitted 652 SourceFileName = FileNameBuffer.str(); 653 } else { 654 Diag(Tok, diag::warn_pragma_include_alias_expected_filename); 655 return; 656 } 657 FileNameBuffer.clear(); 658 659 // Now we expect a comma, followed by another include name 660 Lex(Tok); 661 if (Tok.isNot(tok::comma)) { 662 Diag(Tok, diag::warn_pragma_include_alias_expected) << ","; 663 return; 664 } 665 666 Token ReplaceFilenameTok; 667 CurPPLexer->LexIncludeFilename(ReplaceFilenameTok); 668 if (ReplaceFilenameTok.is(tok::eod)) { 669 // The diagnostic has already been handled 670 return; 671 } 672 673 StringRef ReplaceFileName; 674 if (ReplaceFilenameTok.is(tok::string_literal) || 675 ReplaceFilenameTok.is(tok::angle_string_literal)) { 676 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer); 677 } else if (ReplaceFilenameTok.is(tok::less)) { 678 // This could be a path instead of just a name 679 FileNameBuffer.push_back('<'); 680 SourceLocation End; 681 if (ConcatenateIncludeName(FileNameBuffer, End)) 682 return; // Diagnostic already emitted 683 ReplaceFileName = FileNameBuffer.str(); 684 } else { 685 Diag(Tok, diag::warn_pragma_include_alias_expected_filename); 686 return; 687 } 688 689 // Finally, we expect the closing paren 690 Lex(Tok); 691 if (Tok.isNot(tok::r_paren)) { 692 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")"; 693 return; 694 } 695 696 // Now that we have the source and target filenames, we need to make sure 697 // they're both of the same type (angled vs non-angled) 698 StringRef OriginalSource = SourceFileName; 699 700 bool SourceIsAngled = 701 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(), 702 SourceFileName); 703 bool ReplaceIsAngled = 704 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(), 705 ReplaceFileName); 706 if (!SourceFileName.empty() && !ReplaceFileName.empty() && 707 (SourceIsAngled != ReplaceIsAngled)) { 708 unsigned int DiagID; 709 if (SourceIsAngled) 710 DiagID = diag::warn_pragma_include_alias_mismatch_angle; 711 else 712 DiagID = diag::warn_pragma_include_alias_mismatch_quote; 713 714 Diag(SourceFilenameTok.getLocation(), DiagID) 715 << SourceFileName 716 << ReplaceFileName; 717 718 return; 719 } 720 721 // Now we can let the include handler know about this mapping 722 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName); 723 } 724 725 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor. 726 /// If 'Namespace' is non-null, then it is a token required to exist on the 727 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC". 728 void Preprocessor::AddPragmaHandler(StringRef Namespace, 729 PragmaHandler *Handler) { 730 PragmaNamespace *InsertNS = PragmaHandlers; 731 732 // If this is specified to be in a namespace, step down into it. 733 if (!Namespace.empty()) { 734 // If there is already a pragma handler with the name of this namespace, 735 // we either have an error (directive with the same name as a namespace) or 736 // we already have the namespace to insert into. 737 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) { 738 InsertNS = Existing->getIfNamespace(); 739 assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma" 740 " handler with the same name!"); 741 } else { 742 // Otherwise, this namespace doesn't exist yet, create and insert the 743 // handler for it. 744 InsertNS = new PragmaNamespace(Namespace); 745 PragmaHandlers->AddPragma(InsertNS); 746 } 747 } 748 749 // Check to make sure we don't already have a pragma for this identifier. 750 assert(!InsertNS->FindHandler(Handler->getName()) && 751 "Pragma handler already exists for this identifier!"); 752 InsertNS->AddPragma(Handler); 753 } 754 755 /// RemovePragmaHandler - Remove the specific pragma handler from the 756 /// preprocessor. If \arg Namespace is non-null, then it should be the 757 /// namespace that \arg Handler was added to. It is an error to remove 758 /// a handler that has not been registered. 759 void Preprocessor::RemovePragmaHandler(StringRef Namespace, 760 PragmaHandler *Handler) { 761 PragmaNamespace *NS = PragmaHandlers; 762 763 // If this is specified to be in a namespace, step down into it. 764 if (!Namespace.empty()) { 765 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace); 766 assert(Existing && "Namespace containing handler does not exist!"); 767 768 NS = Existing->getIfNamespace(); 769 assert(NS && "Invalid namespace, registered as a regular pragma handler!"); 770 } 771 772 NS->RemovePragmaHandler(Handler); 773 774 // If this is a non-default namespace and it is now empty, remove 775 // it. 776 if (NS != PragmaHandlers && 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 diag::Mapping Map; 957 if (II->isStr("warning")) 958 Map = diag::MAP_WARNING; 959 else if (II->isStr("error")) 960 Map = diag::MAP_ERROR; 961 else if (II->isStr("ignored")) 962 Map = diag::MAP_IGNORE; 963 else if (II->isStr("fatal")) 964 Map = diag::MAP_FATAL; 965 else if (II->isStr("pop")) { 966 if (!PP.getDiagnostics().popMappings(DiagLoc)) 967 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop); 968 else if (Callbacks) 969 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace); 970 return; 971 } else if (II->isStr("push")) { 972 PP.getDiagnostics().pushMappings(DiagLoc); 973 if (Callbacks) 974 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace); 975 return; 976 } else { 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') { 996 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option); 997 return; 998 } 999 1000 if (PP.getDiagnostics().setDiagnosticGroupMapping(WarningName.substr(2), 1001 Map, DiagLoc)) 1002 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning) 1003 << WarningName; 1004 else if (Callbacks) 1005 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, Map, WarningName); 1006 } 1007 }; 1008 1009 /// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's 1010 /// diagnostics, so we don't really implement this pragma. We parse it and 1011 /// ignore it to avoid -Wunknown-pragma warnings. 1012 struct PragmaWarningHandler : public PragmaHandler { 1013 PragmaWarningHandler() : PragmaHandler("warning") {} 1014 1015 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1016 Token &Tok) override { 1017 // Parse things like: 1018 // warning(push, 1) 1019 // warning(pop) 1020 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9) 1021 SourceLocation DiagLoc = Tok.getLocation(); 1022 PPCallbacks *Callbacks = PP.getPPCallbacks(); 1023 1024 PP.Lex(Tok); 1025 if (Tok.isNot(tok::l_paren)) { 1026 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "("; 1027 return; 1028 } 1029 1030 PP.Lex(Tok); 1031 IdentifierInfo *II = Tok.getIdentifierInfo(); 1032 if (!II) { 1033 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid); 1034 return; 1035 } 1036 1037 if (II->isStr("push")) { 1038 // #pragma warning( push[ ,n ] ) 1039 int Level = -1; 1040 PP.Lex(Tok); 1041 if (Tok.is(tok::comma)) { 1042 PP.Lex(Tok); 1043 uint64_t Value; 1044 if (Tok.is(tok::numeric_constant) && 1045 PP.parseSimpleIntegerLiteral(Tok, Value)) 1046 Level = int(Value); 1047 if (Level < 0 || Level > 4) { 1048 PP.Diag(Tok, diag::warn_pragma_warning_push_level); 1049 return; 1050 } 1051 } 1052 if (Callbacks) 1053 Callbacks->PragmaWarningPush(DiagLoc, Level); 1054 } else if (II->isStr("pop")) { 1055 // #pragma warning( pop ) 1056 PP.Lex(Tok); 1057 if (Callbacks) 1058 Callbacks->PragmaWarningPop(DiagLoc); 1059 } else { 1060 // #pragma warning( warning-specifier : warning-number-list 1061 // [; warning-specifier : warning-number-list...] ) 1062 while (true) { 1063 II = Tok.getIdentifierInfo(); 1064 if (!II) { 1065 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid); 1066 return; 1067 } 1068 1069 // Figure out which warning specifier this is. 1070 StringRef Specifier = II->getName(); 1071 bool SpecifierValid = 1072 llvm::StringSwitch<bool>(Specifier) 1073 .Cases("1", "2", "3", "4", true) 1074 .Cases("default", "disable", "error", "once", "suppress", true) 1075 .Default(false); 1076 if (!SpecifierValid) { 1077 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid); 1078 return; 1079 } 1080 PP.Lex(Tok); 1081 if (Tok.isNot(tok::colon)) { 1082 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":"; 1083 return; 1084 } 1085 1086 // Collect the warning ids. 1087 SmallVector<int, 4> Ids; 1088 PP.Lex(Tok); 1089 while (Tok.is(tok::numeric_constant)) { 1090 uint64_t Value; 1091 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 || 1092 Value > INT_MAX) { 1093 PP.Diag(Tok, diag::warn_pragma_warning_expected_number); 1094 return; 1095 } 1096 Ids.push_back(int(Value)); 1097 } 1098 if (Callbacks) 1099 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids); 1100 1101 // Parse the next specifier if there is a semicolon. 1102 if (Tok.isNot(tok::semi)) 1103 break; 1104 PP.Lex(Tok); 1105 } 1106 } 1107 1108 if (Tok.isNot(tok::r_paren)) { 1109 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")"; 1110 return; 1111 } 1112 1113 PP.Lex(Tok); 1114 if (Tok.isNot(tok::eod)) 1115 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning"; 1116 } 1117 }; 1118 1119 /// PragmaIncludeAliasHandler - "\#pragma include_alias("...")". 1120 struct PragmaIncludeAliasHandler : public PragmaHandler { 1121 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {} 1122 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1123 Token &IncludeAliasTok) override { 1124 PP.HandlePragmaIncludeAlias(IncludeAliasTok); 1125 } 1126 }; 1127 1128 /// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message 1129 /// extension. The syntax is: 1130 /// \code 1131 /// #pragma message(string) 1132 /// \endcode 1133 /// OR, in GCC mode: 1134 /// \code 1135 /// #pragma message string 1136 /// \endcode 1137 /// string is a string, which is fully macro expanded, and permits string 1138 /// concatenation, embedded escape characters, etc... See MSDN for more details. 1139 /// Also handles \#pragma GCC warning and \#pragma GCC error which take the same 1140 /// form as \#pragma message. 1141 struct PragmaMessageHandler : public PragmaHandler { 1142 private: 1143 const PPCallbacks::PragmaMessageKind Kind; 1144 const StringRef Namespace; 1145 1146 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind, 1147 bool PragmaNameOnly = false) { 1148 switch (Kind) { 1149 case PPCallbacks::PMK_Message: 1150 return PragmaNameOnly ? "message" : "pragma message"; 1151 case PPCallbacks::PMK_Warning: 1152 return PragmaNameOnly ? "warning" : "pragma warning"; 1153 case PPCallbacks::PMK_Error: 1154 return PragmaNameOnly ? "error" : "pragma error"; 1155 } 1156 llvm_unreachable("Unknown PragmaMessageKind!"); 1157 } 1158 1159 public: 1160 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind, 1161 StringRef Namespace = StringRef()) 1162 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), Namespace(Namespace) {} 1163 1164 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1165 Token &Tok) override { 1166 SourceLocation MessageLoc = Tok.getLocation(); 1167 PP.Lex(Tok); 1168 bool ExpectClosingParen = false; 1169 switch (Tok.getKind()) { 1170 case tok::l_paren: 1171 // We have a MSVC style pragma message. 1172 ExpectClosingParen = true; 1173 // Read the string. 1174 PP.Lex(Tok); 1175 break; 1176 case tok::string_literal: 1177 // We have a GCC style pragma message, and we just read the string. 1178 break; 1179 default: 1180 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind; 1181 return; 1182 } 1183 1184 std::string MessageString; 1185 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind), 1186 /*MacroExpansion=*/true)) 1187 return; 1188 1189 if (ExpectClosingParen) { 1190 if (Tok.isNot(tok::r_paren)) { 1191 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind; 1192 return; 1193 } 1194 PP.Lex(Tok); // eat the r_paren. 1195 } 1196 1197 if (Tok.isNot(tok::eod)) { 1198 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind; 1199 return; 1200 } 1201 1202 // Output the message. 1203 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error) 1204 ? diag::err_pragma_message 1205 : diag::warn_pragma_message) << MessageString; 1206 1207 // If the pragma is lexically sound, notify any interested PPCallbacks. 1208 if (PPCallbacks *Callbacks = PP.getPPCallbacks()) 1209 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString); 1210 } 1211 }; 1212 1213 /// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the 1214 /// macro on the top of the stack. 1215 struct PragmaPushMacroHandler : public PragmaHandler { 1216 PragmaPushMacroHandler() : PragmaHandler("push_macro") {} 1217 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1218 Token &PushMacroTok) override { 1219 PP.HandlePragmaPushMacro(PushMacroTok); 1220 } 1221 }; 1222 1223 1224 /// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the 1225 /// macro to the value on the top of the stack. 1226 struct PragmaPopMacroHandler : public PragmaHandler { 1227 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {} 1228 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1229 Token &PopMacroTok) override { 1230 PP.HandlePragmaPopMacro(PopMacroTok); 1231 } 1232 }; 1233 1234 // Pragma STDC implementations. 1235 1236 /// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...". 1237 struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler { 1238 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {} 1239 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1240 Token &Tok) override { 1241 tok::OnOffSwitch OOS; 1242 if (PP.LexOnOffSwitch(OOS)) 1243 return; 1244 if (OOS == tok::OOS_ON) 1245 PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported); 1246 } 1247 }; 1248 1249 /// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...". 1250 struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler { 1251 PragmaSTDC_CX_LIMITED_RANGEHandler() 1252 : PragmaHandler("CX_LIMITED_RANGE") {} 1253 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1254 Token &Tok) override { 1255 tok::OnOffSwitch OOS; 1256 PP.LexOnOffSwitch(OOS); 1257 } 1258 }; 1259 1260 /// PragmaSTDC_UnknownHandler - "\#pragma STDC ...". 1261 struct PragmaSTDC_UnknownHandler : public PragmaHandler { 1262 PragmaSTDC_UnknownHandler() {} 1263 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1264 Token &UnknownTok) override { 1265 // C99 6.10.6p2, unknown forms are not allowed. 1266 PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored); 1267 } 1268 }; 1269 1270 /// PragmaARCCFCodeAuditedHandler - 1271 /// \#pragma clang arc_cf_code_audited begin/end 1272 struct PragmaARCCFCodeAuditedHandler : public PragmaHandler { 1273 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {} 1274 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1275 Token &NameTok) override { 1276 SourceLocation Loc = NameTok.getLocation(); 1277 bool IsBegin; 1278 1279 Token Tok; 1280 1281 // Lex the 'begin' or 'end'. 1282 PP.LexUnexpandedToken(Tok); 1283 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo(); 1284 if (BeginEnd && BeginEnd->isStr("begin")) { 1285 IsBegin = true; 1286 } else if (BeginEnd && BeginEnd->isStr("end")) { 1287 IsBegin = false; 1288 } else { 1289 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax); 1290 return; 1291 } 1292 1293 // Verify that this is followed by EOD. 1294 PP.LexUnexpandedToken(Tok); 1295 if (Tok.isNot(tok::eod)) 1296 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma"; 1297 1298 // The start location of the active audit. 1299 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc(); 1300 1301 // The start location we want after processing this. 1302 SourceLocation NewLoc; 1303 1304 if (IsBegin) { 1305 // Complain about attempts to re-enter an audit. 1306 if (BeginLoc.isValid()) { 1307 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited); 1308 PP.Diag(BeginLoc, diag::note_pragma_entered_here); 1309 } 1310 NewLoc = Loc; 1311 } else { 1312 // Complain about attempts to leave an audit that doesn't exist. 1313 if (!BeginLoc.isValid()) { 1314 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited); 1315 return; 1316 } 1317 NewLoc = SourceLocation(); 1318 } 1319 1320 PP.setPragmaARCCFCodeAuditedLoc(NewLoc); 1321 } 1322 }; 1323 1324 /// \brief Handle "\#pragma region [...]" 1325 /// 1326 /// The syntax is 1327 /// \code 1328 /// #pragma region [optional name] 1329 /// #pragma endregion [optional comment] 1330 /// \endcode 1331 /// 1332 /// \note This is 1333 /// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a> 1334 /// pragma, just skipped by compiler. 1335 struct PragmaRegionHandler : public PragmaHandler { 1336 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) { } 1337 1338 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1339 Token &NameTok) override { 1340 // #pragma region: endregion matches can be verified 1341 // __pragma(region): no sense, but ignored by msvc 1342 // _Pragma is not valid for MSVC, but there isn't any point 1343 // to handle a _Pragma differently. 1344 } 1345 }; 1346 1347 } // end anonymous namespace 1348 1349 1350 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas: 1351 /// \#pragma GCC poison/system_header/dependency and \#pragma once. 1352 void Preprocessor::RegisterBuiltinPragmas() { 1353 AddPragmaHandler(new PragmaOnceHandler()); 1354 AddPragmaHandler(new PragmaMarkHandler()); 1355 AddPragmaHandler(new PragmaPushMacroHandler()); 1356 AddPragmaHandler(new PragmaPopMacroHandler()); 1357 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message)); 1358 1359 // #pragma GCC ... 1360 AddPragmaHandler("GCC", new PragmaPoisonHandler()); 1361 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler()); 1362 AddPragmaHandler("GCC", new PragmaDependencyHandler()); 1363 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC")); 1364 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning, 1365 "GCC")); 1366 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error, 1367 "GCC")); 1368 // #pragma clang ... 1369 AddPragmaHandler("clang", new PragmaPoisonHandler()); 1370 AddPragmaHandler("clang", new PragmaSystemHeaderHandler()); 1371 AddPragmaHandler("clang", new PragmaDebugHandler()); 1372 AddPragmaHandler("clang", new PragmaDependencyHandler()); 1373 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang")); 1374 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler()); 1375 1376 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler()); 1377 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler()); 1378 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler()); 1379 1380 // MS extensions. 1381 if (LangOpts.MicrosoftExt) { 1382 AddPragmaHandler(new PragmaWarningHandler()); 1383 AddPragmaHandler(new PragmaIncludeAliasHandler()); 1384 AddPragmaHandler(new PragmaRegionHandler("region")); 1385 AddPragmaHandler(new PragmaRegionHandler("endregion")); 1386 } 1387 } 1388