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