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/Lex/HeaderSearch.h" 17 #include "clang/Lex/LiteralSupport.h" 18 #include "clang/Lex/Preprocessor.h" 19 #include "clang/Lex/MacroInfo.h" 20 #include "clang/Lex/LexDiagnostic.h" 21 #include "clang/Basic/FileManager.h" 22 #include "clang/Basic/SourceManager.h" 23 #include "llvm/Support/CrashRecoveryContext.h" 24 #include "llvm/Support/ErrorHandling.h" 25 #include <algorithm> 26 using namespace clang; 27 28 // Out-of-line destructor to provide a home for the class. 29 PragmaHandler::~PragmaHandler() { 30 } 31 32 //===----------------------------------------------------------------------===// 33 // EmptyPragmaHandler Implementation. 34 //===----------------------------------------------------------------------===// 35 36 EmptyPragmaHandler::EmptyPragmaHandler() {} 37 38 void EmptyPragmaHandler::HandlePragma(Preprocessor &PP, 39 PragmaIntroducerKind Introducer, 40 Token &FirstToken) {} 41 42 //===----------------------------------------------------------------------===// 43 // PragmaNamespace Implementation. 44 //===----------------------------------------------------------------------===// 45 46 47 PragmaNamespace::~PragmaNamespace() { 48 for (llvm::StringMap<PragmaHandler*>::iterator 49 I = Handlers.begin(), E = Handlers.end(); I != E; ++I) 50 delete I->second; 51 } 52 53 /// FindHandler - Check to see if there is already a handler for the 54 /// specified name. If not, return the handler for the null identifier if it 55 /// exists, otherwise return null. If IgnoreNull is true (the default) then 56 /// the null handler isn't returned on failure to match. 57 PragmaHandler *PragmaNamespace::FindHandler(llvm::StringRef Name, 58 bool IgnoreNull) const { 59 if (PragmaHandler *Handler = Handlers.lookup(Name)) 60 return Handler; 61 return IgnoreNull ? 0 : Handlers.lookup(llvm::StringRef()); 62 } 63 64 void PragmaNamespace::AddPragma(PragmaHandler *Handler) { 65 assert(!Handlers.lookup(Handler->getName()) && 66 "A handler with this name is already registered in this namespace"); 67 llvm::StringMapEntry<PragmaHandler *> &Entry = 68 Handlers.GetOrCreateValue(Handler->getName()); 69 Entry.setValue(Handler); 70 } 71 72 void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) { 73 assert(Handlers.lookup(Handler->getName()) && 74 "Handler not registered in this namespace"); 75 Handlers.erase(Handler->getName()); 76 } 77 78 void PragmaNamespace::HandlePragma(Preprocessor &PP, 79 PragmaIntroducerKind Introducer, 80 Token &Tok) { 81 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro 82 // expand it, the user can have a STDC #define, that should not affect this. 83 PP.LexUnexpandedToken(Tok); 84 85 // Get the handler for this token. If there is no handler, ignore the pragma. 86 PragmaHandler *Handler 87 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName() 88 : llvm::StringRef(), 89 /*IgnoreNull=*/false); 90 if (Handler == 0) { 91 PP.Diag(Tok, diag::warn_pragma_ignored); 92 return; 93 } 94 95 // Otherwise, pass it down. 96 Handler->HandlePragma(PP, Introducer, Tok); 97 } 98 99 //===----------------------------------------------------------------------===// 100 // Preprocessor Pragma Directive Handling. 101 //===----------------------------------------------------------------------===// 102 103 /// HandlePragmaDirective - The "#pragma" directive has been parsed. Lex the 104 /// rest of the pragma, passing it to the registered pragma handlers. 105 void Preprocessor::HandlePragmaDirective(unsigned Introducer) { 106 ++NumPragma; 107 108 // Invoke the first level of pragma handlers which reads the namespace id. 109 Token Tok; 110 PragmaHandlers->HandlePragma(*this, PragmaIntroducerKind(Introducer), Tok); 111 112 // If the pragma handler didn't read the rest of the line, consume it now. 113 if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective()) 114 || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective)) 115 DiscardUntilEndOfDirective(); 116 } 117 118 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then 119 /// return the first token after the directive. The _Pragma token has just 120 /// been read into 'Tok'. 121 void Preprocessor::Handle_Pragma(Token &Tok) { 122 // Remember the pragma token location. 123 SourceLocation PragmaLoc = Tok.getLocation(); 124 125 // Read the '('. 126 Lex(Tok); 127 if (Tok.isNot(tok::l_paren)) { 128 Diag(PragmaLoc, diag::err__Pragma_malformed); 129 return; 130 } 131 132 // Read the '"..."'. 133 Lex(Tok); 134 if (Tok.isNot(tok::string_literal) && Tok.isNot(tok::wide_string_literal)) { 135 Diag(PragmaLoc, diag::err__Pragma_malformed); 136 return; 137 } 138 139 // Remember the string. 140 std::string StrVal = getSpelling(Tok); 141 142 // Read the ')'. 143 Lex(Tok); 144 if (Tok.isNot(tok::r_paren)) { 145 Diag(PragmaLoc, diag::err__Pragma_malformed); 146 return; 147 } 148 149 SourceLocation RParenLoc = Tok.getLocation(); 150 151 // The _Pragma is lexically sound. Destringize according to C99 6.10.9.1: 152 // "The string literal is destringized by deleting the L prefix, if present, 153 // deleting the leading and trailing double-quotes, replacing each escape 154 // sequence \" by a double-quote, and replacing each escape sequence \\ by a 155 // single backslash." 156 if (StrVal[0] == 'L') // Remove L prefix. 157 StrVal.erase(StrVal.begin()); 158 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' && 159 "Invalid string token!"); 160 161 // Remove the front quote, replacing it with a space, so that the pragma 162 // contents appear to have a space before them. 163 StrVal[0] = ' '; 164 165 // Replace the terminating quote with a \n. 166 StrVal[StrVal.size()-1] = '\n'; 167 168 // Remove escaped quotes and escapes. 169 for (unsigned i = 0, e = StrVal.size(); i != e-1; ++i) { 170 if (StrVal[i] == '\\' && 171 (StrVal[i+1] == '\\' || StrVal[i+1] == '"')) { 172 // \\ -> '\' and \" -> '"'. 173 StrVal.erase(StrVal.begin()+i); 174 --e; 175 } 176 } 177 178 // Plop the string (including the newline and trailing null) into a buffer 179 // where we can lex it. 180 Token TmpTok; 181 TmpTok.startToken(); 182 CreateString(&StrVal[0], StrVal.size(), TmpTok); 183 SourceLocation TokLoc = TmpTok.getLocation(); 184 185 // Make and enter a lexer object so that we lex and expand the tokens just 186 // like any others. 187 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc, 188 StrVal.size(), *this); 189 190 EnterSourceFileWithLexer(TL, 0); 191 192 // With everything set up, lex this as a #pragma directive. 193 HandlePragmaDirective(PIK__Pragma); 194 195 // Finally, return whatever came after the pragma directive. 196 return Lex(Tok); 197 } 198 199 /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text 200 /// is not enclosed within a string literal. 201 void Preprocessor::HandleMicrosoft__pragma(Token &Tok) { 202 // Remember the pragma token location. 203 SourceLocation PragmaLoc = Tok.getLocation(); 204 205 // Read the '('. 206 Lex(Tok); 207 if (Tok.isNot(tok::l_paren)) { 208 Diag(PragmaLoc, diag::err__Pragma_malformed); 209 return; 210 } 211 212 // Get the tokens enclosed within the __pragma(), as well as the final ')'. 213 llvm::SmallVector<Token, 32> PragmaToks; 214 int NumParens = 0; 215 Lex(Tok); 216 while (Tok.isNot(tok::eof)) { 217 PragmaToks.push_back(Tok); 218 if (Tok.is(tok::l_paren)) 219 NumParens++; 220 else if (Tok.is(tok::r_paren) && NumParens-- == 0) 221 break; 222 Lex(Tok); 223 } 224 225 if (Tok.is(tok::eof)) { 226 Diag(PragmaLoc, diag::err_unterminated___pragma); 227 return; 228 } 229 230 PragmaToks.front().setFlag(Token::LeadingSpace); 231 232 // Replace the ')' with an EOD to mark the end of the pragma. 233 PragmaToks.back().setKind(tok::eod); 234 235 Token *TokArray = new Token[PragmaToks.size()]; 236 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray); 237 238 // Push the tokens onto the stack. 239 EnterTokenStream(TokArray, PragmaToks.size(), true, true); 240 241 // With everything set up, lex this as a #pragma directive. 242 HandlePragmaDirective(PIK___pragma); 243 244 // Finally, return whatever came after the pragma directive. 245 return Lex(Tok); 246 } 247 248 /// HandlePragmaOnce - Handle #pragma once. OnceTok is the 'once'. 249 /// 250 void Preprocessor::HandlePragmaOnce(Token &OnceTok) { 251 if (isInPrimaryFile()) { 252 Diag(OnceTok, diag::pp_pragma_once_in_main_file); 253 return; 254 } 255 256 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc. 257 // Mark the file as a once-only file now. 258 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry()); 259 } 260 261 void Preprocessor::HandlePragmaMark() { 262 assert(CurPPLexer && "No current lexer?"); 263 if (CurLexer) 264 CurLexer->ReadToEndOfLine(); 265 else 266 CurPTHLexer->DiscardToEndOfLine(); 267 } 268 269 270 /// HandlePragmaPoison - Handle #pragma GCC poison. PoisonTok is the 'poison'. 271 /// 272 void Preprocessor::HandlePragmaPoison(Token &PoisonTok) { 273 Token Tok; 274 275 while (1) { 276 // Read the next token to poison. While doing this, pretend that we are 277 // skipping while reading the identifier to poison. 278 // This avoids errors on code like: 279 // #pragma GCC poison X 280 // #pragma GCC poison X 281 if (CurPPLexer) CurPPLexer->LexingRawMode = true; 282 LexUnexpandedToken(Tok); 283 if (CurPPLexer) CurPPLexer->LexingRawMode = false; 284 285 // If we reached the end of line, we're done. 286 if (Tok.is(tok::eod)) return; 287 288 // Can only poison identifiers. 289 if (Tok.isNot(tok::raw_identifier)) { 290 Diag(Tok, diag::err_pp_invalid_poison); 291 return; 292 } 293 294 // Look up the identifier info for the token. We disabled identifier lookup 295 // by saying we're skipping contents, so we need to do this manually. 296 IdentifierInfo *II = LookUpIdentifierInfo(Tok); 297 298 // Already poisoned. 299 if (II->isPoisoned()) continue; 300 301 // If this is a macro identifier, emit a warning. 302 if (II->hasMacroDefinition()) 303 Diag(Tok, diag::pp_poisoning_existing_macro); 304 305 // Finally, poison it! 306 II->setIsPoisoned(); 307 } 308 } 309 310 /// HandlePragmaSystemHeader - Implement #pragma GCC system_header. We know 311 /// that the whole directive has been parsed. 312 void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) { 313 if (isInPrimaryFile()) { 314 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file); 315 return; 316 } 317 318 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc. 319 PreprocessorLexer *TheLexer = getCurrentFileLexer(); 320 321 // Mark the file as a system header. 322 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry()); 323 324 325 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation()); 326 if (PLoc.isInvalid()) 327 return; 328 329 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename()); 330 331 // Notify the client, if desired, that we are in a new source file. 332 if (Callbacks) 333 Callbacks->FileChanged(SysHeaderTok.getLocation(), 334 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System); 335 336 // Emit a line marker. This will change any source locations from this point 337 // forward to realize they are in a system header. 338 // Create a line note with this information. 339 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine(), FilenameID, 340 false, false, true, false); 341 } 342 343 /// HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah. 344 /// 345 void Preprocessor::HandlePragmaDependency(Token &DependencyTok) { 346 Token FilenameTok; 347 CurPPLexer->LexIncludeFilename(FilenameTok); 348 349 // If the token kind is EOD, the error has already been diagnosed. 350 if (FilenameTok.is(tok::eod)) 351 return; 352 353 // Reserve a buffer to get the spelling. 354 llvm::SmallString<128> FilenameBuffer; 355 bool Invalid = false; 356 llvm::StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid); 357 if (Invalid) 358 return; 359 360 bool isAngled = 361 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename); 362 // If GetIncludeFilenameSpelling set the start ptr to null, there was an 363 // error. 364 if (Filename.empty()) 365 return; 366 367 // Search include directories for this file. 368 const DirectoryLookup *CurDir; 369 const FileEntry *File = LookupFile(Filename, isAngled, 0, CurDir, NULL, NULL); 370 if (File == 0) { 371 Diag(FilenameTok, diag::warn_pp_file_not_found) << Filename; 372 return; 373 } 374 375 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry(); 376 377 // If this file is older than the file it depends on, emit a diagnostic. 378 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) { 379 // Lex tokens at the end of the message and include them in the message. 380 std::string Message; 381 Lex(DependencyTok); 382 while (DependencyTok.isNot(tok::eod)) { 383 Message += getSpelling(DependencyTok) + " "; 384 Lex(DependencyTok); 385 } 386 387 // Remove the trailing ' ' if present. 388 if (!Message.empty()) 389 Message.erase(Message.end()-1); 390 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message; 391 } 392 } 393 394 /// HandlePragmaComment - Handle the microsoft #pragma comment extension. The 395 /// syntax is: 396 /// #pragma comment(linker, "foo") 397 /// 'linker' is one of five identifiers: compiler, exestr, lib, linker, user. 398 /// "foo" is a string, which is fully macro expanded, and permits string 399 /// concatenation, embedded escape characters etc. See MSDN for more details. 400 void Preprocessor::HandlePragmaComment(Token &Tok) { 401 SourceLocation CommentLoc = Tok.getLocation(); 402 Lex(Tok); 403 if (Tok.isNot(tok::l_paren)) { 404 Diag(CommentLoc, diag::err_pragma_comment_malformed); 405 return; 406 } 407 408 // Read the identifier. 409 Lex(Tok); 410 if (Tok.isNot(tok::identifier)) { 411 Diag(CommentLoc, diag::err_pragma_comment_malformed); 412 return; 413 } 414 415 // Verify that this is one of the 5 whitelisted options. 416 // FIXME: warn that 'exestr' is deprecated. 417 const IdentifierInfo *II = Tok.getIdentifierInfo(); 418 if (!II->isStr("compiler") && !II->isStr("exestr") && !II->isStr("lib") && 419 !II->isStr("linker") && !II->isStr("user")) { 420 Diag(Tok.getLocation(), diag::err_pragma_comment_unknown_kind); 421 return; 422 } 423 424 // Read the optional string if present. 425 Lex(Tok); 426 std::string ArgumentString; 427 if (Tok.is(tok::comma)) { 428 Lex(Tok); // eat the comma. 429 430 // We need at least one string. 431 if (Tok.isNot(tok::string_literal)) { 432 Diag(Tok.getLocation(), diag::err_pragma_comment_malformed); 433 return; 434 } 435 436 // String concatenation allows multiple strings, which can even come from 437 // macro expansion. 438 // "foo " "bar" "Baz" 439 llvm::SmallVector<Token, 4> StrToks; 440 while (Tok.is(tok::string_literal)) { 441 StrToks.push_back(Tok); 442 Lex(Tok); 443 } 444 445 // Concatenate and parse the strings. 446 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this); 447 assert(!Literal.AnyWide && "Didn't allow wide strings in"); 448 if (Literal.hadError) 449 return; 450 if (Literal.Pascal) { 451 Diag(StrToks[0].getLocation(), diag::err_pragma_comment_malformed); 452 return; 453 } 454 455 ArgumentString = Literal.GetString(); 456 } 457 458 // FIXME: If the kind is "compiler" warn if the string is present (it is 459 // ignored). 460 // FIXME: 'lib' requires a comment string. 461 // FIXME: 'linker' requires a comment string, and has a specific list of 462 // things that are allowable. 463 464 if (Tok.isNot(tok::r_paren)) { 465 Diag(Tok.getLocation(), diag::err_pragma_comment_malformed); 466 return; 467 } 468 Lex(Tok); // eat the r_paren. 469 470 if (Tok.isNot(tok::eod)) { 471 Diag(Tok.getLocation(), diag::err_pragma_comment_malformed); 472 return; 473 } 474 475 // If the pragma is lexically sound, notify any interested PPCallbacks. 476 if (Callbacks) 477 Callbacks->PragmaComment(CommentLoc, II, ArgumentString); 478 } 479 480 /// HandlePragmaMessage - Handle the microsoft and gcc #pragma message 481 /// extension. The syntax is: 482 /// #pragma message(string) 483 /// OR, in GCC mode: 484 /// #pragma message string 485 /// string is a string, which is fully macro expanded, and permits string 486 /// concatenation, embedded escape characters, etc... See MSDN for more details. 487 void Preprocessor::HandlePragmaMessage(Token &Tok) { 488 SourceLocation MessageLoc = Tok.getLocation(); 489 Lex(Tok); 490 bool ExpectClosingParen = false; 491 switch (Tok.getKind()) { 492 case tok::l_paren: 493 // We have a MSVC style pragma message. 494 ExpectClosingParen = true; 495 // Read the string. 496 Lex(Tok); 497 break; 498 case tok::string_literal: 499 // We have a GCC style pragma message, and we just read the string. 500 break; 501 default: 502 Diag(MessageLoc, diag::err_pragma_message_malformed); 503 return; 504 } 505 506 // We need at least one string. 507 if (Tok.isNot(tok::string_literal)) { 508 Diag(Tok.getLocation(), diag::err_pragma_message_malformed); 509 return; 510 } 511 512 // String concatenation allows multiple strings, which can even come from 513 // macro expansion. 514 // "foo " "bar" "Baz" 515 llvm::SmallVector<Token, 4> StrToks; 516 while (Tok.is(tok::string_literal)) { 517 StrToks.push_back(Tok); 518 Lex(Tok); 519 } 520 521 // Concatenate and parse the strings. 522 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this); 523 assert(!Literal.AnyWide && "Didn't allow wide strings in"); 524 if (Literal.hadError) 525 return; 526 if (Literal.Pascal) { 527 Diag(StrToks[0].getLocation(), diag::err_pragma_message_malformed); 528 return; 529 } 530 531 llvm::StringRef MessageString(Literal.GetString()); 532 533 if (ExpectClosingParen) { 534 if (Tok.isNot(tok::r_paren)) { 535 Diag(Tok.getLocation(), diag::err_pragma_message_malformed); 536 return; 537 } 538 Lex(Tok); // eat the r_paren. 539 } 540 541 if (Tok.isNot(tok::eod)) { 542 Diag(Tok.getLocation(), diag::err_pragma_message_malformed); 543 return; 544 } 545 546 // Output the message. 547 Diag(MessageLoc, diag::warn_pragma_message) << MessageString; 548 549 // If the pragma is lexically sound, notify any interested PPCallbacks. 550 if (Callbacks) 551 Callbacks->PragmaMessage(MessageLoc, MessageString); 552 } 553 554 /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro. 555 /// Return the IdentifierInfo* associated with the macro to push or pop. 556 IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) { 557 // Remember the pragma token location. 558 Token PragmaTok = Tok; 559 560 // Read the '('. 561 Lex(Tok); 562 if (Tok.isNot(tok::l_paren)) { 563 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed) 564 << getSpelling(PragmaTok); 565 return 0; 566 } 567 568 // Read the macro name string. 569 Lex(Tok); 570 if (Tok.isNot(tok::string_literal)) { 571 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed) 572 << getSpelling(PragmaTok); 573 return 0; 574 } 575 576 // Remember the macro string. 577 std::string StrVal = getSpelling(Tok); 578 579 // Read the ')'. 580 Lex(Tok); 581 if (Tok.isNot(tok::r_paren)) { 582 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed) 583 << getSpelling(PragmaTok); 584 return 0; 585 } 586 587 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' && 588 "Invalid string token!"); 589 590 // Create a Token from the string. 591 Token MacroTok; 592 MacroTok.startToken(); 593 MacroTok.setKind(tok::raw_identifier); 594 CreateString(&StrVal[1], StrVal.size() - 2, MacroTok); 595 596 // Get the IdentifierInfo of MacroToPushTok. 597 return LookUpIdentifierInfo(MacroTok); 598 } 599 600 /// HandlePragmaPushMacro - Handle #pragma push_macro. 601 /// The syntax is: 602 /// #pragma push_macro("macro") 603 void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) { 604 // Parse the pragma directive and get the macro IdentifierInfo*. 605 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok); 606 if (!IdentInfo) return; 607 608 // Get the MacroInfo associated with IdentInfo. 609 MacroInfo *MI = getMacroInfo(IdentInfo); 610 611 MacroInfo *MacroCopyToPush = 0; 612 if (MI) { 613 // Make a clone of MI. 614 MacroCopyToPush = CloneMacroInfo(*MI); 615 616 // Allow the original MacroInfo to be redefined later. 617 MI->setIsAllowRedefinitionsWithoutWarning(true); 618 } 619 620 // Push the cloned MacroInfo so we can retrieve it later. 621 PragmaPushMacroInfo[IdentInfo].push_back(MacroCopyToPush); 622 } 623 624 /// HandlePragmaPopMacro - Handle #pragma pop_macro. 625 /// The syntax is: 626 /// #pragma pop_macro("macro") 627 void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) { 628 SourceLocation MessageLoc = PopMacroTok.getLocation(); 629 630 // Parse the pragma directive and get the macro IdentifierInfo*. 631 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok); 632 if (!IdentInfo) return; 633 634 // Find the vector<MacroInfo*> associated with the macro. 635 llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter = 636 PragmaPushMacroInfo.find(IdentInfo); 637 if (iter != PragmaPushMacroInfo.end()) { 638 // Release the MacroInfo currently associated with IdentInfo. 639 MacroInfo *CurrentMI = getMacroInfo(IdentInfo); 640 if (CurrentMI) { 641 if (CurrentMI->isWarnIfUnused()) 642 WarnUnusedMacroLocs.erase(CurrentMI->getDefinitionLoc()); 643 ReleaseMacroInfo(CurrentMI); 644 } 645 646 // Get the MacroInfo we want to reinstall. 647 MacroInfo *MacroToReInstall = iter->second.back(); 648 649 // Reinstall the previously pushed macro. 650 setMacroInfo(IdentInfo, MacroToReInstall); 651 652 // Pop PragmaPushMacroInfo stack. 653 iter->second.pop_back(); 654 if (iter->second.size() == 0) 655 PragmaPushMacroInfo.erase(iter); 656 } else { 657 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push) 658 << IdentInfo->getName(); 659 } 660 } 661 662 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor. 663 /// If 'Namespace' is non-null, then it is a token required to exist on the 664 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC". 665 void Preprocessor::AddPragmaHandler(llvm::StringRef Namespace, 666 PragmaHandler *Handler) { 667 PragmaNamespace *InsertNS = PragmaHandlers; 668 669 // If this is specified to be in a namespace, step down into it. 670 if (!Namespace.empty()) { 671 // If there is already a pragma handler with the name of this namespace, 672 // we either have an error (directive with the same name as a namespace) or 673 // we already have the namespace to insert into. 674 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) { 675 InsertNS = Existing->getIfNamespace(); 676 assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma" 677 " handler with the same name!"); 678 } else { 679 // Otherwise, this namespace doesn't exist yet, create and insert the 680 // handler for it. 681 InsertNS = new PragmaNamespace(Namespace); 682 PragmaHandlers->AddPragma(InsertNS); 683 } 684 } 685 686 // Check to make sure we don't already have a pragma for this identifier. 687 assert(!InsertNS->FindHandler(Handler->getName()) && 688 "Pragma handler already exists for this identifier!"); 689 InsertNS->AddPragma(Handler); 690 } 691 692 /// RemovePragmaHandler - Remove the specific pragma handler from the 693 /// preprocessor. If \arg Namespace is non-null, then it should be the 694 /// namespace that \arg Handler was added to. It is an error to remove 695 /// a handler that has not been registered. 696 void Preprocessor::RemovePragmaHandler(llvm::StringRef Namespace, 697 PragmaHandler *Handler) { 698 PragmaNamespace *NS = PragmaHandlers; 699 700 // If this is specified to be in a namespace, step down into it. 701 if (!Namespace.empty()) { 702 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace); 703 assert(Existing && "Namespace containing handler does not exist!"); 704 705 NS = Existing->getIfNamespace(); 706 assert(NS && "Invalid namespace, registered as a regular pragma handler!"); 707 } 708 709 NS->RemovePragmaHandler(Handler); 710 711 // If this is a non-default namespace and it is now empty, remove 712 // it. 713 if (NS != PragmaHandlers && NS->IsEmpty()) 714 PragmaHandlers->RemovePragmaHandler(NS); 715 } 716 717 bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) { 718 Token Tok; 719 LexUnexpandedToken(Tok); 720 721 if (Tok.isNot(tok::identifier)) { 722 Diag(Tok, diag::ext_on_off_switch_syntax); 723 return true; 724 } 725 IdentifierInfo *II = Tok.getIdentifierInfo(); 726 if (II->isStr("ON")) 727 Result = tok::OOS_ON; 728 else if (II->isStr("OFF")) 729 Result = tok::OOS_OFF; 730 else if (II->isStr("DEFAULT")) 731 Result = tok::OOS_DEFAULT; 732 else { 733 Diag(Tok, diag::ext_on_off_switch_syntax); 734 return true; 735 } 736 737 // Verify that this is followed by EOD. 738 LexUnexpandedToken(Tok); 739 if (Tok.isNot(tok::eod)) 740 Diag(Tok, diag::ext_pragma_syntax_eod); 741 return false; 742 } 743 744 namespace { 745 /// PragmaOnceHandler - "#pragma once" marks the file as atomically included. 746 struct PragmaOnceHandler : public PragmaHandler { 747 PragmaOnceHandler() : PragmaHandler("once") {} 748 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 749 Token &OnceTok) { 750 PP.CheckEndOfDirective("pragma once"); 751 PP.HandlePragmaOnce(OnceTok); 752 } 753 }; 754 755 /// PragmaMarkHandler - "#pragma mark ..." is ignored by the compiler, and the 756 /// rest of the line is not lexed. 757 struct PragmaMarkHandler : public PragmaHandler { 758 PragmaMarkHandler() : PragmaHandler("mark") {} 759 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 760 Token &MarkTok) { 761 PP.HandlePragmaMark(); 762 } 763 }; 764 765 /// PragmaPoisonHandler - "#pragma poison x" marks x as not usable. 766 struct PragmaPoisonHandler : public PragmaHandler { 767 PragmaPoisonHandler() : PragmaHandler("poison") {} 768 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 769 Token &PoisonTok) { 770 PP.HandlePragmaPoison(PoisonTok); 771 } 772 }; 773 774 /// PragmaSystemHeaderHandler - "#pragma system_header" marks the current file 775 /// as a system header, which silences warnings in it. 776 struct PragmaSystemHeaderHandler : public PragmaHandler { 777 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {} 778 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 779 Token &SHToken) { 780 PP.HandlePragmaSystemHeader(SHToken); 781 PP.CheckEndOfDirective("pragma"); 782 } 783 }; 784 struct PragmaDependencyHandler : public PragmaHandler { 785 PragmaDependencyHandler() : PragmaHandler("dependency") {} 786 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 787 Token &DepToken) { 788 PP.HandlePragmaDependency(DepToken); 789 } 790 }; 791 792 struct PragmaDebugHandler : public PragmaHandler { 793 PragmaDebugHandler() : PragmaHandler("__debug") {} 794 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 795 Token &DepToken) { 796 Token Tok; 797 PP.LexUnexpandedToken(Tok); 798 if (Tok.isNot(tok::identifier)) { 799 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid); 800 return; 801 } 802 IdentifierInfo *II = Tok.getIdentifierInfo(); 803 804 if (II->isStr("assert")) { 805 assert(0 && "This is an assertion!"); 806 } else if (II->isStr("crash")) { 807 *(volatile int*) 0x11 = 0; 808 } else if (II->isStr("llvm_fatal_error")) { 809 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error"); 810 } else if (II->isStr("llvm_unreachable")) { 811 llvm_unreachable("#pragma clang __debug llvm_unreachable"); 812 } else if (II->isStr("overflow_stack")) { 813 DebugOverflowStack(); 814 } else if (II->isStr("handle_crash")) { 815 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent(); 816 if (CRC) 817 CRC->HandleCrash(); 818 } else { 819 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command) 820 << II->getName(); 821 } 822 } 823 824 // Disable MSVC warning about runtime stack overflow. 825 #ifdef _MSC_VER 826 #pragma warning(disable : 4717) 827 #endif 828 void DebugOverflowStack() { 829 DebugOverflowStack(); 830 } 831 #ifdef _MSC_VER 832 #pragma warning(default : 4717) 833 #endif 834 835 }; 836 837 /// PragmaDiagnosticHandler - e.g. '#pragma GCC diagnostic ignored "-Wformat"' 838 struct PragmaDiagnosticHandler : public PragmaHandler { 839 private: 840 const char *Namespace; 841 public: 842 explicit PragmaDiagnosticHandler(const char *NS) : 843 PragmaHandler("diagnostic"), Namespace(NS) {} 844 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 845 Token &DiagToken) { 846 SourceLocation DiagLoc = DiagToken.getLocation(); 847 Token Tok; 848 PP.LexUnexpandedToken(Tok); 849 if (Tok.isNot(tok::identifier)) { 850 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid); 851 return; 852 } 853 IdentifierInfo *II = Tok.getIdentifierInfo(); 854 PPCallbacks *Callbacks = PP.getPPCallbacks(); 855 856 diag::Mapping Map; 857 if (II->isStr("warning")) 858 Map = diag::MAP_WARNING; 859 else if (II->isStr("error")) 860 Map = diag::MAP_ERROR; 861 else if (II->isStr("ignored")) 862 Map = diag::MAP_IGNORE; 863 else if (II->isStr("fatal")) 864 Map = diag::MAP_FATAL; 865 else if (II->isStr("pop")) { 866 if (!PP.getDiagnostics().popMappings(DiagLoc)) 867 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop); 868 else if (Callbacks) 869 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace); 870 return; 871 } else if (II->isStr("push")) { 872 PP.getDiagnostics().pushMappings(DiagLoc); 873 if (Callbacks) 874 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace); 875 return; 876 } else { 877 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid); 878 return; 879 } 880 881 PP.LexUnexpandedToken(Tok); 882 883 // We need at least one string. 884 if (Tok.isNot(tok::string_literal)) { 885 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token); 886 return; 887 } 888 889 // String concatenation allows multiple strings, which can even come from 890 // macro expansion. 891 // "foo " "bar" "Baz" 892 llvm::SmallVector<Token, 4> StrToks; 893 while (Tok.is(tok::string_literal)) { 894 StrToks.push_back(Tok); 895 PP.LexUnexpandedToken(Tok); 896 } 897 898 if (Tok.isNot(tok::eod)) { 899 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token); 900 return; 901 } 902 903 // Concatenate and parse the strings. 904 StringLiteralParser Literal(&StrToks[0], StrToks.size(), PP); 905 assert(!Literal.AnyWide && "Didn't allow wide strings in"); 906 if (Literal.hadError) 907 return; 908 if (Literal.Pascal) { 909 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid); 910 return; 911 } 912 913 llvm::StringRef WarningName(Literal.GetString()); 914 915 if (WarningName.size() < 3 || WarningName[0] != '-' || 916 WarningName[1] != 'W') { 917 PP.Diag(StrToks[0].getLocation(), 918 diag::warn_pragma_diagnostic_invalid_option); 919 return; 920 } 921 922 if (PP.getDiagnostics().setDiagnosticGroupMapping(WarningName.substr(2), 923 Map, DiagLoc)) 924 PP.Diag(StrToks[0].getLocation(), 925 diag::warn_pragma_diagnostic_unknown_warning) << WarningName; 926 else if (Callbacks) 927 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, Map, WarningName); 928 } 929 }; 930 931 /// PragmaCommentHandler - "#pragma comment ...". 932 struct PragmaCommentHandler : public PragmaHandler { 933 PragmaCommentHandler() : PragmaHandler("comment") {} 934 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 935 Token &CommentTok) { 936 PP.HandlePragmaComment(CommentTok); 937 } 938 }; 939 940 /// PragmaMessageHandler - "#pragma message("...")". 941 struct PragmaMessageHandler : public PragmaHandler { 942 PragmaMessageHandler() : PragmaHandler("message") {} 943 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 944 Token &CommentTok) { 945 PP.HandlePragmaMessage(CommentTok); 946 } 947 }; 948 949 /// PragmaPushMacroHandler - "#pragma push_macro" saves the value of the 950 /// macro on the top of the stack. 951 struct PragmaPushMacroHandler : public PragmaHandler { 952 PragmaPushMacroHandler() : PragmaHandler("push_macro") {} 953 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 954 Token &PushMacroTok) { 955 PP.HandlePragmaPushMacro(PushMacroTok); 956 } 957 }; 958 959 960 /// PragmaPopMacroHandler - "#pragma pop_macro" sets the value of the 961 /// macro to the value on the top of the stack. 962 struct PragmaPopMacroHandler : public PragmaHandler { 963 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {} 964 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 965 Token &PopMacroTok) { 966 PP.HandlePragmaPopMacro(PopMacroTok); 967 } 968 }; 969 970 // Pragma STDC implementations. 971 972 /// PragmaSTDC_FENV_ACCESSHandler - "#pragma STDC FENV_ACCESS ...". 973 struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler { 974 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {} 975 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 976 Token &Tok) { 977 tok::OnOffSwitch OOS; 978 if (PP.LexOnOffSwitch(OOS)) 979 return; 980 if (OOS == tok::OOS_ON) 981 PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported); 982 } 983 }; 984 985 /// PragmaSTDC_CX_LIMITED_RANGEHandler - "#pragma STDC CX_LIMITED_RANGE ...". 986 struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler { 987 PragmaSTDC_CX_LIMITED_RANGEHandler() 988 : PragmaHandler("CX_LIMITED_RANGE") {} 989 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 990 Token &Tok) { 991 tok::OnOffSwitch OOS; 992 PP.LexOnOffSwitch(OOS); 993 } 994 }; 995 996 /// PragmaSTDC_UnknownHandler - "#pragma STDC ...". 997 struct PragmaSTDC_UnknownHandler : public PragmaHandler { 998 PragmaSTDC_UnknownHandler() {} 999 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1000 Token &UnknownTok) { 1001 // C99 6.10.6p2, unknown forms are not allowed. 1002 PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored); 1003 } 1004 }; 1005 1006 } // end anonymous namespace 1007 1008 1009 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas: 1010 /// #pragma GCC poison/system_header/dependency and #pragma once. 1011 void Preprocessor::RegisterBuiltinPragmas() { 1012 AddPragmaHandler(new PragmaOnceHandler()); 1013 AddPragmaHandler(new PragmaMarkHandler()); 1014 AddPragmaHandler(new PragmaPushMacroHandler()); 1015 AddPragmaHandler(new PragmaPopMacroHandler()); 1016 AddPragmaHandler(new PragmaMessageHandler()); 1017 1018 // #pragma GCC ... 1019 AddPragmaHandler("GCC", new PragmaPoisonHandler()); 1020 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler()); 1021 AddPragmaHandler("GCC", new PragmaDependencyHandler()); 1022 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC")); 1023 // #pragma clang ... 1024 AddPragmaHandler("clang", new PragmaPoisonHandler()); 1025 AddPragmaHandler("clang", new PragmaSystemHeaderHandler()); 1026 AddPragmaHandler("clang", new PragmaDebugHandler()); 1027 AddPragmaHandler("clang", new PragmaDependencyHandler()); 1028 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang")); 1029 1030 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler()); 1031 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler()); 1032 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler()); 1033 1034 // MS extensions. 1035 if (Features.Microsoft) { 1036 AddPragmaHandler(new PragmaCommentHandler()); 1037 } 1038 } 1039