1 //===- Pragma.cpp - Pragma registration and handling ----------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the PragmaHandler/PragmaTable interfaces and implements 10 // pragma related methods of the Preprocessor class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Lex/Pragma.h" 15 #include "clang/Basic/Diagnostic.h" 16 #include "clang/Basic/FileManager.h" 17 #include "clang/Basic/IdentifierTable.h" 18 #include "clang/Basic/LLVM.h" 19 #include "clang/Basic/LangOptions.h" 20 #include "clang/Basic/Module.h" 21 #include "clang/Basic/SourceLocation.h" 22 #include "clang/Basic/SourceManager.h" 23 #include "clang/Basic/TokenKinds.h" 24 #include "clang/Lex/HeaderSearch.h" 25 #include "clang/Lex/LexDiagnostic.h" 26 #include "clang/Lex/Lexer.h" 27 #include "clang/Lex/LiteralSupport.h" 28 #include "clang/Lex/MacroInfo.h" 29 #include "clang/Lex/ModuleLoader.h" 30 #include "clang/Lex/PPCallbacks.h" 31 #include "clang/Lex/Preprocessor.h" 32 #include "clang/Lex/PreprocessorLexer.h" 33 #include "clang/Lex/Token.h" 34 #include "clang/Lex/TokenLexer.h" 35 #include "llvm/ADT/ArrayRef.h" 36 #include "llvm/ADT/DenseMap.h" 37 #include "llvm/ADT/STLExtras.h" 38 #include "llvm/ADT/SmallString.h" 39 #include "llvm/ADT/SmallVector.h" 40 #include "llvm/ADT/StringSwitch.h" 41 #include "llvm/ADT/StringRef.h" 42 #include "llvm/Support/CrashRecoveryContext.h" 43 #include "llvm/Support/Compiler.h" 44 #include "llvm/Support/ErrorHandling.h" 45 #include <algorithm> 46 #include <cassert> 47 #include <cstddef> 48 #include <cstdint> 49 #include <limits> 50 #include <string> 51 #include <utility> 52 #include <vector> 53 54 using namespace clang; 55 56 // Out-of-line destructor to provide a home for the class. 57 PragmaHandler::~PragmaHandler() = default; 58 59 //===----------------------------------------------------------------------===// 60 // EmptyPragmaHandler Implementation. 61 //===----------------------------------------------------------------------===// 62 63 EmptyPragmaHandler::EmptyPragmaHandler(StringRef Name) : PragmaHandler(Name) {} 64 65 void EmptyPragmaHandler::HandlePragma(Preprocessor &PP, 66 PragmaIntroducerKind Introducer, 67 Token &FirstToken) {} 68 69 //===----------------------------------------------------------------------===// 70 // PragmaNamespace Implementation. 71 //===----------------------------------------------------------------------===// 72 73 PragmaNamespace::~PragmaNamespace() { 74 llvm::DeleteContainerSeconds(Handlers); 75 } 76 77 /// FindHandler - Check to see if there is already a handler for the 78 /// specified name. If not, return the handler for the null identifier if it 79 /// exists, otherwise return null. If IgnoreNull is true (the default) then 80 /// the null handler isn't returned on failure to match. 81 PragmaHandler *PragmaNamespace::FindHandler(StringRef Name, 82 bool IgnoreNull) const { 83 if (PragmaHandler *Handler = Handlers.lookup(Name)) 84 return Handler; 85 return IgnoreNull ? nullptr : Handlers.lookup(StringRef()); 86 } 87 88 void PragmaNamespace::AddPragma(PragmaHandler *Handler) { 89 assert(!Handlers.lookup(Handler->getName()) && 90 "A handler with this name is already registered in this namespace"); 91 Handlers[Handler->getName()] = Handler; 92 } 93 94 void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) { 95 assert(Handlers.lookup(Handler->getName()) && 96 "Handler not registered in this namespace"); 97 Handlers.erase(Handler->getName()); 98 } 99 100 void PragmaNamespace::HandlePragma(Preprocessor &PP, 101 PragmaIntroducerKind Introducer, 102 Token &Tok) { 103 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro 104 // expand it, the user can have a STDC #define, that should not affect this. 105 PP.LexUnexpandedToken(Tok); 106 107 // Get the handler for this token. If there is no handler, ignore the pragma. 108 PragmaHandler *Handler 109 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName() 110 : StringRef(), 111 /*IgnoreNull=*/false); 112 if (!Handler) { 113 PP.Diag(Tok, diag::warn_pragma_ignored); 114 return; 115 } 116 117 // Otherwise, pass it down. 118 Handler->HandlePragma(PP, Introducer, Tok); 119 } 120 121 //===----------------------------------------------------------------------===// 122 // Preprocessor Pragma Directive Handling. 123 //===----------------------------------------------------------------------===// 124 125 /// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the 126 /// rest of the pragma, passing it to the registered pragma handlers. 127 void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc, 128 PragmaIntroducerKind Introducer) { 129 if (Callbacks) 130 Callbacks->PragmaDirective(IntroducerLoc, Introducer); 131 132 if (!PragmasEnabled) 133 return; 134 135 ++NumPragma; 136 137 // Invoke the first level of pragma handlers which reads the namespace id. 138 Token Tok; 139 PragmaHandlers->HandlePragma(*this, Introducer, Tok); 140 141 // If the pragma handler didn't read the rest of the line, consume it now. 142 if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective()) 143 || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective)) 144 DiscardUntilEndOfDirective(); 145 } 146 147 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then 148 /// return the first token after the directive. The _Pragma token has just 149 /// been read into 'Tok'. 150 void Preprocessor::Handle_Pragma(Token &Tok) { 151 // C11 6.10.3.4/3: 152 // all pragma unary operator expressions within [a completely 153 // macro-replaced preprocessing token sequence] are [...] processed [after 154 // rescanning is complete] 155 // 156 // This means that we execute _Pragma operators in two cases: 157 // 158 // 1) on token sequences that would otherwise be produced as the output of 159 // phase 4 of preprocessing, and 160 // 2) on token sequences formed as the macro-replaced token sequence of a 161 // macro argument 162 // 163 // Case #2 appears to be a wording bug: only _Pragmas that would survive to 164 // the end of phase 4 should actually be executed. Discussion on the WG14 165 // mailing list suggests that a _Pragma operator is notionally checked early, 166 // but only pragmas that survive to the end of phase 4 should be executed. 167 // 168 // In Case #2, we check the syntax now, but then put the tokens back into the 169 // token stream for later consumption. 170 171 struct TokenCollector { 172 Preprocessor &Self; 173 bool Collect; 174 SmallVector<Token, 3> Tokens; 175 Token &Tok; 176 177 void lex() { 178 if (Collect) 179 Tokens.push_back(Tok); 180 Self.Lex(Tok); 181 } 182 183 void revert() { 184 assert(Collect && "did not collect tokens"); 185 assert(!Tokens.empty() && "collected unexpected number of tokens"); 186 187 // Push the ( "string" ) tokens into the token stream. 188 auto Toks = llvm::make_unique<Token[]>(Tokens.size()); 189 std::copy(Tokens.begin() + 1, Tokens.end(), Toks.get()); 190 Toks[Tokens.size() - 1] = Tok; 191 Self.EnterTokenStream(std::move(Toks), Tokens.size(), 192 /*DisableMacroExpansion*/ true); 193 194 // ... and return the _Pragma token unchanged. 195 Tok = *Tokens.begin(); 196 } 197 }; 198 199 TokenCollector Toks = {*this, InMacroArgPreExpansion, {}, Tok}; 200 201 // Remember the pragma token location. 202 SourceLocation PragmaLoc = Tok.getLocation(); 203 204 // Read the '('. 205 Toks.lex(); 206 if (Tok.isNot(tok::l_paren)) { 207 Diag(PragmaLoc, diag::err__Pragma_malformed); 208 return; 209 } 210 211 // Read the '"..."'. 212 Toks.lex(); 213 if (!tok::isStringLiteral(Tok.getKind())) { 214 Diag(PragmaLoc, diag::err__Pragma_malformed); 215 // Skip bad tokens, and the ')', if present. 216 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof)) 217 Lex(Tok); 218 while (Tok.isNot(tok::r_paren) && 219 !Tok.isAtStartOfLine() && 220 Tok.isNot(tok::eof)) 221 Lex(Tok); 222 if (Tok.is(tok::r_paren)) 223 Lex(Tok); 224 return; 225 } 226 227 if (Tok.hasUDSuffix()) { 228 Diag(Tok, diag::err_invalid_string_udl); 229 // Skip this token, and the ')', if present. 230 Lex(Tok); 231 if (Tok.is(tok::r_paren)) 232 Lex(Tok); 233 return; 234 } 235 236 // Remember the string. 237 Token StrTok = Tok; 238 239 // Read the ')'. 240 Toks.lex(); 241 if (Tok.isNot(tok::r_paren)) { 242 Diag(PragmaLoc, diag::err__Pragma_malformed); 243 return; 244 } 245 246 // If we're expanding a macro argument, put the tokens back. 247 if (InMacroArgPreExpansion) { 248 Toks.revert(); 249 return; 250 } 251 252 SourceLocation RParenLoc = Tok.getLocation(); 253 std::string StrVal = getSpelling(StrTok); 254 255 // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1: 256 // "The string literal is destringized by deleting any encoding prefix, 257 // deleting the leading and trailing double-quotes, replacing each escape 258 // sequence \" by a double-quote, and replacing each escape sequence \\ by a 259 // single backslash." 260 if (StrVal[0] == 'L' || StrVal[0] == 'U' || 261 (StrVal[0] == 'u' && StrVal[1] != '8')) 262 StrVal.erase(StrVal.begin()); 263 else if (StrVal[0] == 'u') 264 StrVal.erase(StrVal.begin(), StrVal.begin() + 2); 265 266 if (StrVal[0] == 'R') { 267 // FIXME: C++11 does not specify how to handle raw-string-literals here. 268 // We strip off the 'R', the quotes, the d-char-sequences, and the parens. 269 assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' && 270 "Invalid raw string token!"); 271 272 // Measure the length of the d-char-sequence. 273 unsigned NumDChars = 0; 274 while (StrVal[2 + NumDChars] != '(') { 275 assert(NumDChars < (StrVal.size() - 5) / 2 && 276 "Invalid raw string token!"); 277 ++NumDChars; 278 } 279 assert(StrVal[StrVal.size() - 2 - NumDChars] == ')'); 280 281 // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the 282 // parens below. 283 StrVal.erase(0, 2 + NumDChars); 284 StrVal.erase(StrVal.size() - 1 - NumDChars); 285 } else { 286 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' && 287 "Invalid string token!"); 288 289 // Remove escaped quotes and escapes. 290 unsigned ResultPos = 1; 291 for (size_t i = 1, e = StrVal.size() - 1; i != e; ++i) { 292 // Skip escapes. \\ -> '\' and \" -> '"'. 293 if (StrVal[i] == '\\' && i + 1 < e && 294 (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"')) 295 ++i; 296 StrVal[ResultPos++] = StrVal[i]; 297 } 298 StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1); 299 } 300 301 // Remove the front quote, replacing it with a space, so that the pragma 302 // contents appear to have a space before them. 303 StrVal[0] = ' '; 304 305 // Replace the terminating quote with a \n. 306 StrVal[StrVal.size()-1] = '\n'; 307 308 // Plop the string (including the newline and trailing null) into a buffer 309 // where we can lex it. 310 Token TmpTok; 311 TmpTok.startToken(); 312 CreateString(StrVal, TmpTok); 313 SourceLocation TokLoc = TmpTok.getLocation(); 314 315 // Make and enter a lexer object so that we lex and expand the tokens just 316 // like any others. 317 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc, 318 StrVal.size(), *this); 319 320 EnterSourceFileWithLexer(TL, nullptr); 321 322 // With everything set up, lex this as a #pragma directive. 323 HandlePragmaDirective(PragmaLoc, PIK__Pragma); 324 325 // Finally, return whatever came after the pragma directive. 326 return Lex(Tok); 327 } 328 329 /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text 330 /// is not enclosed within a string literal. 331 void Preprocessor::HandleMicrosoft__pragma(Token &Tok) { 332 // Remember the pragma token location. 333 SourceLocation PragmaLoc = Tok.getLocation(); 334 335 // Read the '('. 336 Lex(Tok); 337 if (Tok.isNot(tok::l_paren)) { 338 Diag(PragmaLoc, diag::err__Pragma_malformed); 339 return; 340 } 341 342 // Get the tokens enclosed within the __pragma(), as well as the final ')'. 343 SmallVector<Token, 32> PragmaToks; 344 int NumParens = 0; 345 Lex(Tok); 346 while (Tok.isNot(tok::eof)) { 347 PragmaToks.push_back(Tok); 348 if (Tok.is(tok::l_paren)) 349 NumParens++; 350 else if (Tok.is(tok::r_paren) && NumParens-- == 0) 351 break; 352 Lex(Tok); 353 } 354 355 if (Tok.is(tok::eof)) { 356 Diag(PragmaLoc, diag::err_unterminated___pragma); 357 return; 358 } 359 360 PragmaToks.front().setFlag(Token::LeadingSpace); 361 362 // Replace the ')' with an EOD to mark the end of the pragma. 363 PragmaToks.back().setKind(tok::eod); 364 365 Token *TokArray = new Token[PragmaToks.size()]; 366 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray); 367 368 // Push the tokens onto the stack. 369 EnterTokenStream(TokArray, PragmaToks.size(), true, true); 370 371 // With everything set up, lex this as a #pragma directive. 372 HandlePragmaDirective(PragmaLoc, PIK___pragma); 373 374 // Finally, return whatever came after the pragma directive. 375 return Lex(Tok); 376 } 377 378 /// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'. 379 void Preprocessor::HandlePragmaOnce(Token &OnceTok) { 380 // Don't honor the 'once' when handling the primary source file, unless 381 // this is a prefix to a TU, which indicates we're generating a PCH file, or 382 // when the main file is a header (e.g. when -xc-header is provided on the 383 // commandline). 384 if (isInPrimaryFile() && TUKind != TU_Prefix && !getLangOpts().IsHeaderFile) { 385 Diag(OnceTok, diag::pp_pragma_once_in_main_file); 386 return; 387 } 388 389 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc. 390 // Mark the file as a once-only file now. 391 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry()); 392 } 393 394 void Preprocessor::HandlePragmaMark() { 395 assert(CurPPLexer && "No current lexer?"); 396 CurLexer->ReadToEndOfLine(); 397 } 398 399 /// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'. 400 void Preprocessor::HandlePragmaPoison() { 401 Token Tok; 402 403 while (true) { 404 // Read the next token to poison. While doing this, pretend that we are 405 // skipping while reading the identifier to poison. 406 // This avoids errors on code like: 407 // #pragma GCC poison X 408 // #pragma GCC poison X 409 if (CurPPLexer) CurPPLexer->LexingRawMode = true; 410 LexUnexpandedToken(Tok); 411 if (CurPPLexer) CurPPLexer->LexingRawMode = false; 412 413 // If we reached the end of line, we're done. 414 if (Tok.is(tok::eod)) return; 415 416 // Can only poison identifiers. 417 if (Tok.isNot(tok::raw_identifier)) { 418 Diag(Tok, diag::err_pp_invalid_poison); 419 return; 420 } 421 422 // Look up the identifier info for the token. We disabled identifier lookup 423 // by saying we're skipping contents, so we need to do this manually. 424 IdentifierInfo *II = LookUpIdentifierInfo(Tok); 425 426 // Already poisoned. 427 if (II->isPoisoned()) continue; 428 429 // If this is a macro identifier, emit a warning. 430 if (isMacroDefined(II)) 431 Diag(Tok, diag::pp_poisoning_existing_macro); 432 433 // Finally, poison it! 434 II->setIsPoisoned(); 435 if (II->isFromAST()) 436 II->setChangedSinceDeserialization(); 437 } 438 } 439 440 /// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know 441 /// that the whole directive has been parsed. 442 void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) { 443 if (isInPrimaryFile()) { 444 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file); 445 return; 446 } 447 448 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc. 449 PreprocessorLexer *TheLexer = getCurrentFileLexer(); 450 451 // Mark the file as a system header. 452 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry()); 453 454 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation()); 455 if (PLoc.isInvalid()) 456 return; 457 458 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename()); 459 460 // Notify the client, if desired, that we are in a new source file. 461 if (Callbacks) 462 Callbacks->FileChanged(SysHeaderTok.getLocation(), 463 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System); 464 465 // Emit a line marker. This will change any source locations from this point 466 // forward to realize they are in a system header. 467 // Create a line note with this information. 468 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine() + 1, 469 FilenameID, /*IsEntry=*/false, /*IsExit=*/false, 470 SrcMgr::C_System); 471 } 472 473 /// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah. 474 void Preprocessor::HandlePragmaDependency(Token &DependencyTok) { 475 Token FilenameTok; 476 if (LexHeaderName(FilenameTok, /*AllowConcatenation*/false)) 477 return; 478 479 // If the next token wasn't a header-name, diagnose the error. 480 if (FilenameTok.isNot(tok::header_name)) { 481 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename); 482 return; 483 } 484 485 // Reserve a buffer to get the spelling. 486 SmallString<128> FilenameBuffer; 487 bool Invalid = false; 488 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid); 489 if (Invalid) 490 return; 491 492 bool isAngled = 493 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename); 494 // If GetIncludeFilenameSpelling set the start ptr to null, there was an 495 // error. 496 if (Filename.empty()) 497 return; 498 499 // Search include directories for this file. 500 const DirectoryLookup *CurDir; 501 const FileEntry *File = 502 LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr, 503 nullptr, CurDir, nullptr, nullptr, nullptr, nullptr, nullptr); 504 if (!File) { 505 if (!SuppressIncludeNotFoundError) 506 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename; 507 return; 508 } 509 510 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry(); 511 512 // If this file is older than the file it depends on, emit a diagnostic. 513 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) { 514 // Lex tokens at the end of the message and include them in the message. 515 std::string Message; 516 Lex(DependencyTok); 517 while (DependencyTok.isNot(tok::eod)) { 518 Message += getSpelling(DependencyTok) + " "; 519 Lex(DependencyTok); 520 } 521 522 // Remove the trailing ' ' if present. 523 if (!Message.empty()) 524 Message.erase(Message.end()-1); 525 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message; 526 } 527 } 528 529 /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro. 530 /// Return the IdentifierInfo* associated with the macro to push or pop. 531 IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) { 532 // Remember the pragma token location. 533 Token PragmaTok = Tok; 534 535 // Read the '('. 536 Lex(Tok); 537 if (Tok.isNot(tok::l_paren)) { 538 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed) 539 << getSpelling(PragmaTok); 540 return nullptr; 541 } 542 543 // Read the macro name string. 544 Lex(Tok); 545 if (Tok.isNot(tok::string_literal)) { 546 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed) 547 << getSpelling(PragmaTok); 548 return nullptr; 549 } 550 551 if (Tok.hasUDSuffix()) { 552 Diag(Tok, diag::err_invalid_string_udl); 553 return nullptr; 554 } 555 556 // Remember the macro string. 557 std::string StrVal = getSpelling(Tok); 558 559 // Read the ')'. 560 Lex(Tok); 561 if (Tok.isNot(tok::r_paren)) { 562 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed) 563 << getSpelling(PragmaTok); 564 return nullptr; 565 } 566 567 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' && 568 "Invalid string token!"); 569 570 // Create a Token from the string. 571 Token MacroTok; 572 MacroTok.startToken(); 573 MacroTok.setKind(tok::raw_identifier); 574 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok); 575 576 // Get the IdentifierInfo of MacroToPushTok. 577 return LookUpIdentifierInfo(MacroTok); 578 } 579 580 /// Handle \#pragma push_macro. 581 /// 582 /// The syntax is: 583 /// \code 584 /// #pragma push_macro("macro") 585 /// \endcode 586 void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) { 587 // Parse the pragma directive and get the macro IdentifierInfo*. 588 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok); 589 if (!IdentInfo) return; 590 591 // Get the MacroInfo associated with IdentInfo. 592 MacroInfo *MI = getMacroInfo(IdentInfo); 593 594 if (MI) { 595 // Allow the original MacroInfo to be redefined later. 596 MI->setIsAllowRedefinitionsWithoutWarning(true); 597 } 598 599 // Push the cloned MacroInfo so we can retrieve it later. 600 PragmaPushMacroInfo[IdentInfo].push_back(MI); 601 } 602 603 /// Handle \#pragma pop_macro. 604 /// 605 /// The syntax is: 606 /// \code 607 /// #pragma pop_macro("macro") 608 /// \endcode 609 void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) { 610 SourceLocation MessageLoc = PopMacroTok.getLocation(); 611 612 // Parse the pragma directive and get the macro IdentifierInfo*. 613 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok); 614 if (!IdentInfo) return; 615 616 // Find the vector<MacroInfo*> associated with the macro. 617 llvm::DenseMap<IdentifierInfo *, std::vector<MacroInfo *>>::iterator iter = 618 PragmaPushMacroInfo.find(IdentInfo); 619 if (iter != PragmaPushMacroInfo.end()) { 620 // Forget the MacroInfo currently associated with IdentInfo. 621 if (MacroInfo *MI = getMacroInfo(IdentInfo)) { 622 if (MI->isWarnIfUnused()) 623 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc()); 624 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc)); 625 } 626 627 // Get the MacroInfo we want to reinstall. 628 MacroInfo *MacroToReInstall = iter->second.back(); 629 630 if (MacroToReInstall) 631 // Reinstall the previously pushed macro. 632 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc); 633 634 // Pop PragmaPushMacroInfo stack. 635 iter->second.pop_back(); 636 if (iter->second.empty()) 637 PragmaPushMacroInfo.erase(iter); 638 } else { 639 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push) 640 << IdentInfo->getName(); 641 } 642 } 643 644 void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) { 645 // We will either get a quoted filename or a bracketed filename, and we 646 // have to track which we got. The first filename is the source name, 647 // and the second name is the mapped filename. If the first is quoted, 648 // the second must be as well (cannot mix and match quotes and brackets). 649 650 // Get the open paren 651 Lex(Tok); 652 if (Tok.isNot(tok::l_paren)) { 653 Diag(Tok, diag::warn_pragma_include_alias_expected) << "("; 654 return; 655 } 656 657 // We expect either a quoted string literal, or a bracketed name 658 Token SourceFilenameTok; 659 if (LexHeaderName(SourceFilenameTok)) 660 return; 661 662 StringRef SourceFileName; 663 SmallString<128> FileNameBuffer; 664 if (SourceFilenameTok.is(tok::header_name)) { 665 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer); 666 } else { 667 Diag(Tok, diag::warn_pragma_include_alias_expected_filename); 668 return; 669 } 670 FileNameBuffer.clear(); 671 672 // Now we expect a comma, followed by another include name 673 Lex(Tok); 674 if (Tok.isNot(tok::comma)) { 675 Diag(Tok, diag::warn_pragma_include_alias_expected) << ","; 676 return; 677 } 678 679 Token ReplaceFilenameTok; 680 if (LexHeaderName(ReplaceFilenameTok)) 681 return; 682 683 StringRef ReplaceFileName; 684 if (ReplaceFilenameTok.is(tok::header_name)) { 685 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer); 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 // Lex a component of a module name: either an identifier or a string literal; 728 // for components that can be expressed both ways, the two forms are equivalent. 729 static bool LexModuleNameComponent( 730 Preprocessor &PP, Token &Tok, 731 std::pair<IdentifierInfo *, SourceLocation> &ModuleNameComponent, 732 bool First) { 733 PP.LexUnexpandedToken(Tok); 734 if (Tok.is(tok::string_literal) && !Tok.hasUDSuffix()) { 735 StringLiteralParser Literal(Tok, PP); 736 if (Literal.hadError) 737 return true; 738 ModuleNameComponent = std::make_pair( 739 PP.getIdentifierInfo(Literal.GetString()), Tok.getLocation()); 740 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) { 741 ModuleNameComponent = 742 std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation()); 743 } else { 744 PP.Diag(Tok.getLocation(), diag::err_pp_expected_module_name) << First; 745 return true; 746 } 747 return false; 748 } 749 750 static bool LexModuleName( 751 Preprocessor &PP, Token &Tok, 752 llvm::SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> 753 &ModuleName) { 754 while (true) { 755 std::pair<IdentifierInfo*, SourceLocation> NameComponent; 756 if (LexModuleNameComponent(PP, Tok, NameComponent, ModuleName.empty())) 757 return true; 758 ModuleName.push_back(NameComponent); 759 760 PP.LexUnexpandedToken(Tok); 761 if (Tok.isNot(tok::period)) 762 return false; 763 } 764 } 765 766 void Preprocessor::HandlePragmaModuleBuild(Token &Tok) { 767 SourceLocation Loc = Tok.getLocation(); 768 769 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc; 770 if (LexModuleNameComponent(*this, Tok, ModuleNameLoc, true)) 771 return; 772 IdentifierInfo *ModuleName = ModuleNameLoc.first; 773 774 LexUnexpandedToken(Tok); 775 if (Tok.isNot(tok::eod)) { 776 Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma"; 777 DiscardUntilEndOfDirective(); 778 } 779 780 CurLexer->LexingRawMode = true; 781 782 auto TryConsumeIdentifier = [&](StringRef Ident) -> bool { 783 if (Tok.getKind() != tok::raw_identifier || 784 Tok.getRawIdentifier() != Ident) 785 return false; 786 CurLexer->Lex(Tok); 787 return true; 788 }; 789 790 // Scan forward looking for the end of the module. 791 const char *Start = CurLexer->getBufferLocation(); 792 const char *End = nullptr; 793 unsigned NestingLevel = 1; 794 while (true) { 795 End = CurLexer->getBufferLocation(); 796 CurLexer->Lex(Tok); 797 798 if (Tok.is(tok::eof)) { 799 Diag(Loc, diag::err_pp_module_build_missing_end); 800 break; 801 } 802 803 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) { 804 // Token was part of module; keep going. 805 continue; 806 } 807 808 // We hit something directive-shaped; check to see if this is the end 809 // of the module build. 810 CurLexer->ParsingPreprocessorDirective = true; 811 CurLexer->Lex(Tok); 812 if (TryConsumeIdentifier("pragma") && TryConsumeIdentifier("clang") && 813 TryConsumeIdentifier("module")) { 814 if (TryConsumeIdentifier("build")) 815 // #pragma clang module build -> entering a nested module build. 816 ++NestingLevel; 817 else if (TryConsumeIdentifier("endbuild")) { 818 // #pragma clang module endbuild -> leaving a module build. 819 if (--NestingLevel == 0) 820 break; 821 } 822 // We should either be looking at the EOD or more of the current directive 823 // preceding the EOD. Either way we can ignore this token and keep going. 824 assert(Tok.getKind() != tok::eof && "missing EOD before EOF"); 825 } 826 } 827 828 CurLexer->LexingRawMode = false; 829 830 // Load the extracted text as a preprocessed module. 831 assert(CurLexer->getBuffer().begin() <= Start && 832 Start <= CurLexer->getBuffer().end() && 833 CurLexer->getBuffer().begin() <= End && 834 End <= CurLexer->getBuffer().end() && 835 "module source range not contained within same file buffer"); 836 TheModuleLoader.loadModuleFromSource(Loc, ModuleName->getName(), 837 StringRef(Start, End - Start)); 838 } 839 840 void Preprocessor::HandlePragmaHdrstop(Token &Tok) { 841 Lex(Tok); 842 if (Tok.is(tok::l_paren)) { 843 Diag(Tok.getLocation(), diag::warn_pp_hdrstop_filename_ignored); 844 845 std::string FileName; 846 if (!LexStringLiteral(Tok, FileName, "pragma hdrstop", false)) 847 return; 848 849 if (Tok.isNot(tok::r_paren)) { 850 Diag(Tok, diag::err_expected) << tok::r_paren; 851 return; 852 } 853 Lex(Tok); 854 } 855 if (Tok.isNot(tok::eod)) 856 Diag(Tok.getLocation(), diag::ext_pp_extra_tokens_at_eol) 857 << "pragma hdrstop"; 858 859 if (creatingPCHWithPragmaHdrStop() && 860 SourceMgr.isInMainFile(Tok.getLocation())) { 861 assert(CurLexer && "no lexer for #pragma hdrstop processing"); 862 Token &Result = Tok; 863 Result.startToken(); 864 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof); 865 CurLexer->cutOffLexing(); 866 } 867 if (usingPCHWithPragmaHdrStop()) 868 SkippingUntilPragmaHdrStop = false; 869 } 870 871 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor. 872 /// If 'Namespace' is non-null, then it is a token required to exist on the 873 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC". 874 void Preprocessor::AddPragmaHandler(StringRef Namespace, 875 PragmaHandler *Handler) { 876 PragmaNamespace *InsertNS = PragmaHandlers.get(); 877 878 // If this is specified to be in a namespace, step down into it. 879 if (!Namespace.empty()) { 880 // If there is already a pragma handler with the name of this namespace, 881 // we either have an error (directive with the same name as a namespace) or 882 // we already have the namespace to insert into. 883 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) { 884 InsertNS = Existing->getIfNamespace(); 885 assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma" 886 " handler with the same name!"); 887 } else { 888 // Otherwise, this namespace doesn't exist yet, create and insert the 889 // handler for it. 890 InsertNS = new PragmaNamespace(Namespace); 891 PragmaHandlers->AddPragma(InsertNS); 892 } 893 } 894 895 // Check to make sure we don't already have a pragma for this identifier. 896 assert(!InsertNS->FindHandler(Handler->getName()) && 897 "Pragma handler already exists for this identifier!"); 898 InsertNS->AddPragma(Handler); 899 } 900 901 /// RemovePragmaHandler - Remove the specific pragma handler from the 902 /// preprocessor. If \arg Namespace is non-null, then it should be the 903 /// namespace that \arg Handler was added to. It is an error to remove 904 /// a handler that has not been registered. 905 void Preprocessor::RemovePragmaHandler(StringRef Namespace, 906 PragmaHandler *Handler) { 907 PragmaNamespace *NS = PragmaHandlers.get(); 908 909 // If this is specified to be in a namespace, step down into it. 910 if (!Namespace.empty()) { 911 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace); 912 assert(Existing && "Namespace containing handler does not exist!"); 913 914 NS = Existing->getIfNamespace(); 915 assert(NS && "Invalid namespace, registered as a regular pragma handler!"); 916 } 917 918 NS->RemovePragmaHandler(Handler); 919 920 // If this is a non-default namespace and it is now empty, remove it. 921 if (NS != PragmaHandlers.get() && NS->IsEmpty()) { 922 PragmaHandlers->RemovePragmaHandler(NS); 923 delete NS; 924 } 925 } 926 927 bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) { 928 Token Tok; 929 LexUnexpandedToken(Tok); 930 931 if (Tok.isNot(tok::identifier)) { 932 Diag(Tok, diag::ext_on_off_switch_syntax); 933 return true; 934 } 935 IdentifierInfo *II = Tok.getIdentifierInfo(); 936 if (II->isStr("ON")) 937 Result = tok::OOS_ON; 938 else if (II->isStr("OFF")) 939 Result = tok::OOS_OFF; 940 else if (II->isStr("DEFAULT")) 941 Result = tok::OOS_DEFAULT; 942 else { 943 Diag(Tok, diag::ext_on_off_switch_syntax); 944 return true; 945 } 946 947 // Verify that this is followed by EOD. 948 LexUnexpandedToken(Tok); 949 if (Tok.isNot(tok::eod)) 950 Diag(Tok, diag::ext_pragma_syntax_eod); 951 return false; 952 } 953 954 namespace { 955 956 /// PragmaOnceHandler - "\#pragma once" marks the file as atomically included. 957 struct PragmaOnceHandler : public PragmaHandler { 958 PragmaOnceHandler() : PragmaHandler("once") {} 959 960 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 961 Token &OnceTok) override { 962 PP.CheckEndOfDirective("pragma once"); 963 PP.HandlePragmaOnce(OnceTok); 964 } 965 }; 966 967 /// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the 968 /// rest of the line is not lexed. 969 struct PragmaMarkHandler : public PragmaHandler { 970 PragmaMarkHandler() : PragmaHandler("mark") {} 971 972 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 973 Token &MarkTok) override { 974 PP.HandlePragmaMark(); 975 } 976 }; 977 978 /// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable. 979 struct PragmaPoisonHandler : public PragmaHandler { 980 PragmaPoisonHandler() : PragmaHandler("poison") {} 981 982 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 983 Token &PoisonTok) override { 984 PP.HandlePragmaPoison(); 985 } 986 }; 987 988 /// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file 989 /// as a system header, which silences warnings in it. 990 struct PragmaSystemHeaderHandler : public PragmaHandler { 991 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {} 992 993 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 994 Token &SHToken) override { 995 PP.HandlePragmaSystemHeader(SHToken); 996 PP.CheckEndOfDirective("pragma"); 997 } 998 }; 999 1000 struct PragmaDependencyHandler : public PragmaHandler { 1001 PragmaDependencyHandler() : PragmaHandler("dependency") {} 1002 1003 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1004 Token &DepToken) override { 1005 PP.HandlePragmaDependency(DepToken); 1006 } 1007 }; 1008 1009 struct PragmaDebugHandler : public PragmaHandler { 1010 PragmaDebugHandler() : PragmaHandler("__debug") {} 1011 1012 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1013 Token &DebugToken) override { 1014 Token Tok; 1015 PP.LexUnexpandedToken(Tok); 1016 if (Tok.isNot(tok::identifier)) { 1017 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid); 1018 return; 1019 } 1020 IdentifierInfo *II = Tok.getIdentifierInfo(); 1021 1022 if (II->isStr("assert")) { 1023 llvm_unreachable("This is an assertion!"); 1024 } else if (II->isStr("crash")) { 1025 LLVM_BUILTIN_TRAP; 1026 } else if (II->isStr("parser_crash")) { 1027 Token Crasher; 1028 Crasher.startToken(); 1029 Crasher.setKind(tok::annot_pragma_parser_crash); 1030 Crasher.setAnnotationRange(SourceRange(Tok.getLocation())); 1031 PP.EnterToken(Crasher); 1032 } else if (II->isStr("dump")) { 1033 Token Identifier; 1034 PP.LexUnexpandedToken(Identifier); 1035 if (auto *DumpII = Identifier.getIdentifierInfo()) { 1036 Token DumpAnnot; 1037 DumpAnnot.startToken(); 1038 DumpAnnot.setKind(tok::annot_pragma_dump); 1039 DumpAnnot.setAnnotationRange( 1040 SourceRange(Tok.getLocation(), Identifier.getLocation())); 1041 DumpAnnot.setAnnotationValue(DumpII); 1042 PP.DiscardUntilEndOfDirective(); 1043 PP.EnterToken(DumpAnnot); 1044 } else { 1045 PP.Diag(Identifier, diag::warn_pragma_debug_missing_argument) 1046 << II->getName(); 1047 } 1048 } else if (II->isStr("diag_mapping")) { 1049 Token DiagName; 1050 PP.LexUnexpandedToken(DiagName); 1051 if (DiagName.is(tok::eod)) 1052 PP.getDiagnostics().dump(); 1053 else if (DiagName.is(tok::string_literal) && !DiagName.hasUDSuffix()) { 1054 StringLiteralParser Literal(DiagName, PP); 1055 if (Literal.hadError) 1056 return; 1057 PP.getDiagnostics().dump(Literal.GetString()); 1058 } else { 1059 PP.Diag(DiagName, diag::warn_pragma_debug_missing_argument) 1060 << II->getName(); 1061 } 1062 } else if (II->isStr("llvm_fatal_error")) { 1063 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error"); 1064 } else if (II->isStr("llvm_unreachable")) { 1065 llvm_unreachable("#pragma clang __debug llvm_unreachable"); 1066 } else if (II->isStr("macro")) { 1067 Token MacroName; 1068 PP.LexUnexpandedToken(MacroName); 1069 auto *MacroII = MacroName.getIdentifierInfo(); 1070 if (MacroII) 1071 PP.dumpMacroInfo(MacroII); 1072 else 1073 PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument) 1074 << II->getName(); 1075 } else if (II->isStr("module_map")) { 1076 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8> 1077 ModuleName; 1078 if (LexModuleName(PP, Tok, ModuleName)) 1079 return; 1080 ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap(); 1081 Module *M = nullptr; 1082 for (auto IIAndLoc : ModuleName) { 1083 M = MM.lookupModuleQualified(IIAndLoc.first->getName(), M); 1084 if (!M) { 1085 PP.Diag(IIAndLoc.second, diag::warn_pragma_debug_unknown_module) 1086 << IIAndLoc.first; 1087 return; 1088 } 1089 } 1090 M->dump(); 1091 } else if (II->isStr("overflow_stack")) { 1092 DebugOverflowStack(); 1093 } else if (II->isStr("handle_crash")) { 1094 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent(); 1095 if (CRC) 1096 CRC->HandleCrash(); 1097 } else if (II->isStr("captured")) { 1098 HandleCaptured(PP); 1099 } else { 1100 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command) 1101 << II->getName(); 1102 } 1103 1104 PPCallbacks *Callbacks = PP.getPPCallbacks(); 1105 if (Callbacks) 1106 Callbacks->PragmaDebug(Tok.getLocation(), II->getName()); 1107 } 1108 1109 void HandleCaptured(Preprocessor &PP) { 1110 Token Tok; 1111 PP.LexUnexpandedToken(Tok); 1112 1113 if (Tok.isNot(tok::eod)) { 1114 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) 1115 << "pragma clang __debug captured"; 1116 return; 1117 } 1118 1119 SourceLocation NameLoc = Tok.getLocation(); 1120 MutableArrayRef<Token> Toks( 1121 PP.getPreprocessorAllocator().Allocate<Token>(1), 1); 1122 Toks[0].startToken(); 1123 Toks[0].setKind(tok::annot_pragma_captured); 1124 Toks[0].setLocation(NameLoc); 1125 1126 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true); 1127 } 1128 1129 // Disable MSVC warning about runtime stack overflow. 1130 #ifdef _MSC_VER 1131 #pragma warning(disable : 4717) 1132 #endif 1133 static void DebugOverflowStack(void (*P)() = nullptr) { 1134 void (*volatile Self)(void(*P)()) = DebugOverflowStack; 1135 Self(reinterpret_cast<void(*)()>(Self)); 1136 } 1137 #ifdef _MSC_VER 1138 #pragma warning(default : 4717) 1139 #endif 1140 }; 1141 1142 /// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"' 1143 struct PragmaDiagnosticHandler : public PragmaHandler { 1144 private: 1145 const char *Namespace; 1146 1147 public: 1148 explicit PragmaDiagnosticHandler(const char *NS) 1149 : PragmaHandler("diagnostic"), Namespace(NS) {} 1150 1151 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1152 Token &DiagToken) override { 1153 SourceLocation DiagLoc = DiagToken.getLocation(); 1154 Token Tok; 1155 PP.LexUnexpandedToken(Tok); 1156 if (Tok.isNot(tok::identifier)) { 1157 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid); 1158 return; 1159 } 1160 IdentifierInfo *II = Tok.getIdentifierInfo(); 1161 PPCallbacks *Callbacks = PP.getPPCallbacks(); 1162 1163 if (II->isStr("pop")) { 1164 if (!PP.getDiagnostics().popMappings(DiagLoc)) 1165 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop); 1166 else if (Callbacks) 1167 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace); 1168 return; 1169 } else if (II->isStr("push")) { 1170 PP.getDiagnostics().pushMappings(DiagLoc); 1171 if (Callbacks) 1172 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace); 1173 return; 1174 } 1175 1176 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName()) 1177 .Case("ignored", diag::Severity::Ignored) 1178 .Case("warning", diag::Severity::Warning) 1179 .Case("error", diag::Severity::Error) 1180 .Case("fatal", diag::Severity::Fatal) 1181 .Default(diag::Severity()); 1182 1183 if (SV == diag::Severity()) { 1184 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid); 1185 return; 1186 } 1187 1188 PP.LexUnexpandedToken(Tok); 1189 SourceLocation StringLoc = Tok.getLocation(); 1190 1191 std::string WarningName; 1192 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic", 1193 /*MacroExpansion=*/false)) 1194 return; 1195 1196 if (Tok.isNot(tok::eod)) { 1197 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token); 1198 return; 1199 } 1200 1201 if (WarningName.size() < 3 || WarningName[0] != '-' || 1202 (WarningName[1] != 'W' && WarningName[1] != 'R')) { 1203 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option); 1204 return; 1205 } 1206 1207 diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError 1208 : diag::Flavor::Remark; 1209 StringRef Group = StringRef(WarningName).substr(2); 1210 bool unknownDiag = false; 1211 if (Group == "everything") { 1212 // Special handling for pragma clang diagnostic ... "-Weverything". 1213 // There is no formal group named "everything", so there has to be a 1214 // special case for it. 1215 PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc); 1216 } else 1217 unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV, 1218 DiagLoc); 1219 if (unknownDiag) 1220 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning) 1221 << WarningName; 1222 else if (Callbacks) 1223 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName); 1224 } 1225 }; 1226 1227 /// "\#pragma hdrstop [<header-name-string>]" 1228 struct PragmaHdrstopHandler : public PragmaHandler { 1229 PragmaHdrstopHandler() : PragmaHandler("hdrstop") {} 1230 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1231 Token &DepToken) override { 1232 PP.HandlePragmaHdrstop(DepToken); 1233 } 1234 }; 1235 1236 /// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's 1237 /// diagnostics, so we don't really implement this pragma. We parse it and 1238 /// ignore it to avoid -Wunknown-pragma warnings. 1239 struct PragmaWarningHandler : public PragmaHandler { 1240 PragmaWarningHandler() : PragmaHandler("warning") {} 1241 1242 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1243 Token &Tok) override { 1244 // Parse things like: 1245 // warning(push, 1) 1246 // warning(pop) 1247 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9) 1248 SourceLocation DiagLoc = Tok.getLocation(); 1249 PPCallbacks *Callbacks = PP.getPPCallbacks(); 1250 1251 PP.Lex(Tok); 1252 if (Tok.isNot(tok::l_paren)) { 1253 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "("; 1254 return; 1255 } 1256 1257 PP.Lex(Tok); 1258 IdentifierInfo *II = Tok.getIdentifierInfo(); 1259 1260 if (II && II->isStr("push")) { 1261 // #pragma warning( push[ ,n ] ) 1262 int Level = -1; 1263 PP.Lex(Tok); 1264 if (Tok.is(tok::comma)) { 1265 PP.Lex(Tok); 1266 uint64_t Value; 1267 if (Tok.is(tok::numeric_constant) && 1268 PP.parseSimpleIntegerLiteral(Tok, Value)) 1269 Level = int(Value); 1270 if (Level < 0 || Level > 4) { 1271 PP.Diag(Tok, diag::warn_pragma_warning_push_level); 1272 return; 1273 } 1274 } 1275 if (Callbacks) 1276 Callbacks->PragmaWarningPush(DiagLoc, Level); 1277 } else if (II && II->isStr("pop")) { 1278 // #pragma warning( pop ) 1279 PP.Lex(Tok); 1280 if (Callbacks) 1281 Callbacks->PragmaWarningPop(DiagLoc); 1282 } else { 1283 // #pragma warning( warning-specifier : warning-number-list 1284 // [; warning-specifier : warning-number-list...] ) 1285 while (true) { 1286 II = Tok.getIdentifierInfo(); 1287 if (!II && !Tok.is(tok::numeric_constant)) { 1288 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid); 1289 return; 1290 } 1291 1292 // Figure out which warning specifier this is. 1293 bool SpecifierValid; 1294 StringRef Specifier; 1295 llvm::SmallString<1> SpecifierBuf; 1296 if (II) { 1297 Specifier = II->getName(); 1298 SpecifierValid = llvm::StringSwitch<bool>(Specifier) 1299 .Cases("default", "disable", "error", "once", 1300 "suppress", true) 1301 .Default(false); 1302 // If we read a correct specifier, snatch next token (that should be 1303 // ":", checked later). 1304 if (SpecifierValid) 1305 PP.Lex(Tok); 1306 } else { 1307 // Token is a numeric constant. It should be either 1, 2, 3 or 4. 1308 uint64_t Value; 1309 Specifier = PP.getSpelling(Tok, SpecifierBuf); 1310 if (PP.parseSimpleIntegerLiteral(Tok, Value)) { 1311 SpecifierValid = (Value >= 1) && (Value <= 4); 1312 } else 1313 SpecifierValid = false; 1314 // Next token already snatched by parseSimpleIntegerLiteral. 1315 } 1316 1317 if (!SpecifierValid) { 1318 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid); 1319 return; 1320 } 1321 if (Tok.isNot(tok::colon)) { 1322 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":"; 1323 return; 1324 } 1325 1326 // Collect the warning ids. 1327 SmallVector<int, 4> Ids; 1328 PP.Lex(Tok); 1329 while (Tok.is(tok::numeric_constant)) { 1330 uint64_t Value; 1331 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 || 1332 Value > std::numeric_limits<int>::max()) { 1333 PP.Diag(Tok, diag::warn_pragma_warning_expected_number); 1334 return; 1335 } 1336 Ids.push_back(int(Value)); 1337 } 1338 if (Callbacks) 1339 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids); 1340 1341 // Parse the next specifier if there is a semicolon. 1342 if (Tok.isNot(tok::semi)) 1343 break; 1344 PP.Lex(Tok); 1345 } 1346 } 1347 1348 if (Tok.isNot(tok::r_paren)) { 1349 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")"; 1350 return; 1351 } 1352 1353 PP.Lex(Tok); 1354 if (Tok.isNot(tok::eod)) 1355 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning"; 1356 } 1357 }; 1358 1359 /// "\#pragma execution_character_set(...)". MSVC supports this pragma only 1360 /// for "UTF-8". We parse it and ignore it if UTF-8 is provided and warn 1361 /// otherwise to avoid -Wunknown-pragma warnings. 1362 struct PragmaExecCharsetHandler : public PragmaHandler { 1363 PragmaExecCharsetHandler() : PragmaHandler("execution_character_set") {} 1364 1365 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1366 Token &Tok) override { 1367 // Parse things like: 1368 // execution_character_set(push, "UTF-8") 1369 // execution_character_set(pop) 1370 SourceLocation DiagLoc = Tok.getLocation(); 1371 PPCallbacks *Callbacks = PP.getPPCallbacks(); 1372 1373 PP.Lex(Tok); 1374 if (Tok.isNot(tok::l_paren)) { 1375 PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << "("; 1376 return; 1377 } 1378 1379 PP.Lex(Tok); 1380 IdentifierInfo *II = Tok.getIdentifierInfo(); 1381 1382 if (II && II->isStr("push")) { 1383 // #pragma execution_character_set( push[ , string ] ) 1384 PP.Lex(Tok); 1385 if (Tok.is(tok::comma)) { 1386 PP.Lex(Tok); 1387 1388 std::string ExecCharset; 1389 if (!PP.FinishLexStringLiteral(Tok, ExecCharset, 1390 "pragma execution_character_set", 1391 /*MacroExpansion=*/false)) 1392 return; 1393 1394 // MSVC supports either of these, but nothing else. 1395 if (ExecCharset != "UTF-8" && ExecCharset != "utf-8") { 1396 PP.Diag(Tok, diag::warn_pragma_exec_charset_push_invalid) << ExecCharset; 1397 return; 1398 } 1399 } 1400 if (Callbacks) 1401 Callbacks->PragmaExecCharsetPush(DiagLoc, "UTF-8"); 1402 } else if (II && II->isStr("pop")) { 1403 // #pragma execution_character_set( pop ) 1404 PP.Lex(Tok); 1405 if (Callbacks) 1406 Callbacks->PragmaExecCharsetPop(DiagLoc); 1407 } else { 1408 PP.Diag(Tok, diag::warn_pragma_exec_charset_spec_invalid); 1409 return; 1410 } 1411 1412 if (Tok.isNot(tok::r_paren)) { 1413 PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << ")"; 1414 return; 1415 } 1416 1417 PP.Lex(Tok); 1418 if (Tok.isNot(tok::eod)) 1419 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma execution_character_set"; 1420 } 1421 }; 1422 1423 /// PragmaIncludeAliasHandler - "\#pragma include_alias("...")". 1424 struct PragmaIncludeAliasHandler : public PragmaHandler { 1425 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {} 1426 1427 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1428 Token &IncludeAliasTok) override { 1429 PP.HandlePragmaIncludeAlias(IncludeAliasTok); 1430 } 1431 }; 1432 1433 /// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message 1434 /// extension. The syntax is: 1435 /// \code 1436 /// #pragma message(string) 1437 /// \endcode 1438 /// OR, in GCC mode: 1439 /// \code 1440 /// #pragma message string 1441 /// \endcode 1442 /// string is a string, which is fully macro expanded, and permits string 1443 /// concatenation, embedded escape characters, etc... See MSDN for more details. 1444 /// Also handles \#pragma GCC warning and \#pragma GCC error which take the same 1445 /// form as \#pragma message. 1446 struct PragmaMessageHandler : public PragmaHandler { 1447 private: 1448 const PPCallbacks::PragmaMessageKind Kind; 1449 const StringRef Namespace; 1450 1451 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind, 1452 bool PragmaNameOnly = false) { 1453 switch (Kind) { 1454 case PPCallbacks::PMK_Message: 1455 return PragmaNameOnly ? "message" : "pragma message"; 1456 case PPCallbacks::PMK_Warning: 1457 return PragmaNameOnly ? "warning" : "pragma warning"; 1458 case PPCallbacks::PMK_Error: 1459 return PragmaNameOnly ? "error" : "pragma error"; 1460 } 1461 llvm_unreachable("Unknown PragmaMessageKind!"); 1462 } 1463 1464 public: 1465 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind, 1466 StringRef Namespace = StringRef()) 1467 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), 1468 Namespace(Namespace) {} 1469 1470 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1471 Token &Tok) override { 1472 SourceLocation MessageLoc = Tok.getLocation(); 1473 PP.Lex(Tok); 1474 bool ExpectClosingParen = false; 1475 switch (Tok.getKind()) { 1476 case tok::l_paren: 1477 // We have a MSVC style pragma message. 1478 ExpectClosingParen = true; 1479 // Read the string. 1480 PP.Lex(Tok); 1481 break; 1482 case tok::string_literal: 1483 // We have a GCC style pragma message, and we just read the string. 1484 break; 1485 default: 1486 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind; 1487 return; 1488 } 1489 1490 std::string MessageString; 1491 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind), 1492 /*MacroExpansion=*/true)) 1493 return; 1494 1495 if (ExpectClosingParen) { 1496 if (Tok.isNot(tok::r_paren)) { 1497 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind; 1498 return; 1499 } 1500 PP.Lex(Tok); // eat the r_paren. 1501 } 1502 1503 if (Tok.isNot(tok::eod)) { 1504 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind; 1505 return; 1506 } 1507 1508 // Output the message. 1509 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error) 1510 ? diag::err_pragma_message 1511 : diag::warn_pragma_message) << MessageString; 1512 1513 // If the pragma is lexically sound, notify any interested PPCallbacks. 1514 if (PPCallbacks *Callbacks = PP.getPPCallbacks()) 1515 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString); 1516 } 1517 }; 1518 1519 /// Handle the clang \#pragma module import extension. The syntax is: 1520 /// \code 1521 /// #pragma clang module import some.module.name 1522 /// \endcode 1523 struct PragmaModuleImportHandler : public PragmaHandler { 1524 PragmaModuleImportHandler() : PragmaHandler("import") {} 1525 1526 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1527 Token &Tok) override { 1528 SourceLocation ImportLoc = Tok.getLocation(); 1529 1530 // Read the module name. 1531 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8> 1532 ModuleName; 1533 if (LexModuleName(PP, Tok, ModuleName)) 1534 return; 1535 1536 if (Tok.isNot(tok::eod)) 1537 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma"; 1538 1539 // If we have a non-empty module path, load the named module. 1540 Module *Imported = 1541 PP.getModuleLoader().loadModule(ImportLoc, ModuleName, Module::Hidden, 1542 /*IsIncludeDirective=*/false); 1543 if (!Imported) 1544 return; 1545 1546 PP.makeModuleVisible(Imported, ImportLoc); 1547 PP.EnterAnnotationToken(SourceRange(ImportLoc, ModuleName.back().second), 1548 tok::annot_module_include, Imported); 1549 if (auto *CB = PP.getPPCallbacks()) 1550 CB->moduleImport(ImportLoc, ModuleName, Imported); 1551 } 1552 }; 1553 1554 /// Handle the clang \#pragma module begin extension. The syntax is: 1555 /// \code 1556 /// #pragma clang module begin some.module.name 1557 /// ... 1558 /// #pragma clang module end 1559 /// \endcode 1560 struct PragmaModuleBeginHandler : public PragmaHandler { 1561 PragmaModuleBeginHandler() : PragmaHandler("begin") {} 1562 1563 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1564 Token &Tok) override { 1565 SourceLocation BeginLoc = Tok.getLocation(); 1566 1567 // Read the module name. 1568 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8> 1569 ModuleName; 1570 if (LexModuleName(PP, Tok, ModuleName)) 1571 return; 1572 1573 if (Tok.isNot(tok::eod)) 1574 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma"; 1575 1576 // We can only enter submodules of the current module. 1577 StringRef Current = PP.getLangOpts().CurrentModule; 1578 if (ModuleName.front().first->getName() != Current) { 1579 PP.Diag(ModuleName.front().second, diag::err_pp_module_begin_wrong_module) 1580 << ModuleName.front().first << (ModuleName.size() > 1) 1581 << Current.empty() << Current; 1582 return; 1583 } 1584 1585 // Find the module we're entering. We require that a module map for it 1586 // be loaded or implicitly loadable. 1587 // FIXME: We could create the submodule here. We'd need to know whether 1588 // it's supposed to be explicit, but not much else. 1589 Module *M = PP.getHeaderSearchInfo().lookupModule(Current); 1590 if (!M) { 1591 PP.Diag(ModuleName.front().second, 1592 diag::err_pp_module_begin_no_module_map) << Current; 1593 return; 1594 } 1595 for (unsigned I = 1; I != ModuleName.size(); ++I) { 1596 auto *NewM = M->findSubmodule(ModuleName[I].first->getName()); 1597 if (!NewM) { 1598 PP.Diag(ModuleName[I].second, diag::err_pp_module_begin_no_submodule) 1599 << M->getFullModuleName() << ModuleName[I].first; 1600 return; 1601 } 1602 M = NewM; 1603 } 1604 1605 // If the module isn't available, it doesn't make sense to enter it. 1606 if (Preprocessor::checkModuleIsAvailable( 1607 PP.getLangOpts(), PP.getTargetInfo(), PP.getDiagnostics(), M)) { 1608 PP.Diag(BeginLoc, diag::note_pp_module_begin_here) 1609 << M->getTopLevelModuleName(); 1610 return; 1611 } 1612 1613 // Enter the scope of the submodule. 1614 PP.EnterSubmodule(M, BeginLoc, /*ForPragma*/true); 1615 PP.EnterAnnotationToken(SourceRange(BeginLoc, ModuleName.back().second), 1616 tok::annot_module_begin, M); 1617 } 1618 }; 1619 1620 /// Handle the clang \#pragma module end extension. 1621 struct PragmaModuleEndHandler : public PragmaHandler { 1622 PragmaModuleEndHandler() : PragmaHandler("end") {} 1623 1624 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1625 Token &Tok) override { 1626 SourceLocation Loc = Tok.getLocation(); 1627 1628 PP.LexUnexpandedToken(Tok); 1629 if (Tok.isNot(tok::eod)) 1630 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma"; 1631 1632 Module *M = PP.LeaveSubmodule(/*ForPragma*/true); 1633 if (M) 1634 PP.EnterAnnotationToken(SourceRange(Loc), tok::annot_module_end, M); 1635 else 1636 PP.Diag(Loc, diag::err_pp_module_end_without_module_begin); 1637 } 1638 }; 1639 1640 /// Handle the clang \#pragma module build extension. 1641 struct PragmaModuleBuildHandler : public PragmaHandler { 1642 PragmaModuleBuildHandler() : PragmaHandler("build") {} 1643 1644 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1645 Token &Tok) override { 1646 PP.HandlePragmaModuleBuild(Tok); 1647 } 1648 }; 1649 1650 /// Handle the clang \#pragma module load extension. 1651 struct PragmaModuleLoadHandler : public PragmaHandler { 1652 PragmaModuleLoadHandler() : PragmaHandler("load") {} 1653 1654 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1655 Token &Tok) override { 1656 SourceLocation Loc = Tok.getLocation(); 1657 1658 // Read the module name. 1659 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8> 1660 ModuleName; 1661 if (LexModuleName(PP, Tok, ModuleName)) 1662 return; 1663 1664 if (Tok.isNot(tok::eod)) 1665 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma"; 1666 1667 // Load the module, don't make it visible. 1668 PP.getModuleLoader().loadModule(Loc, ModuleName, Module::Hidden, 1669 /*IsIncludeDirective=*/false); 1670 } 1671 }; 1672 1673 /// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the 1674 /// macro on the top of the stack. 1675 struct PragmaPushMacroHandler : public PragmaHandler { 1676 PragmaPushMacroHandler() : PragmaHandler("push_macro") {} 1677 1678 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1679 Token &PushMacroTok) override { 1680 PP.HandlePragmaPushMacro(PushMacroTok); 1681 } 1682 }; 1683 1684 /// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the 1685 /// macro to the value on the top of the stack. 1686 struct PragmaPopMacroHandler : public PragmaHandler { 1687 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {} 1688 1689 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1690 Token &PopMacroTok) override { 1691 PP.HandlePragmaPopMacro(PopMacroTok); 1692 } 1693 }; 1694 1695 /// PragmaARCCFCodeAuditedHandler - 1696 /// \#pragma clang arc_cf_code_audited begin/end 1697 struct PragmaARCCFCodeAuditedHandler : public PragmaHandler { 1698 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {} 1699 1700 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1701 Token &NameTok) override { 1702 SourceLocation Loc = NameTok.getLocation(); 1703 bool IsBegin; 1704 1705 Token Tok; 1706 1707 // Lex the 'begin' or 'end'. 1708 PP.LexUnexpandedToken(Tok); 1709 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo(); 1710 if (BeginEnd && BeginEnd->isStr("begin")) { 1711 IsBegin = true; 1712 } else if (BeginEnd && BeginEnd->isStr("end")) { 1713 IsBegin = false; 1714 } else { 1715 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax); 1716 return; 1717 } 1718 1719 // Verify that this is followed by EOD. 1720 PP.LexUnexpandedToken(Tok); 1721 if (Tok.isNot(tok::eod)) 1722 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma"; 1723 1724 // The start location of the active audit. 1725 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc(); 1726 1727 // The start location we want after processing this. 1728 SourceLocation NewLoc; 1729 1730 if (IsBegin) { 1731 // Complain about attempts to re-enter an audit. 1732 if (BeginLoc.isValid()) { 1733 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited); 1734 PP.Diag(BeginLoc, diag::note_pragma_entered_here); 1735 } 1736 NewLoc = Loc; 1737 } else { 1738 // Complain about attempts to leave an audit that doesn't exist. 1739 if (!BeginLoc.isValid()) { 1740 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited); 1741 return; 1742 } 1743 NewLoc = SourceLocation(); 1744 } 1745 1746 PP.setPragmaARCCFCodeAuditedLoc(NewLoc); 1747 } 1748 }; 1749 1750 /// PragmaAssumeNonNullHandler - 1751 /// \#pragma clang assume_nonnull begin/end 1752 struct PragmaAssumeNonNullHandler : public PragmaHandler { 1753 PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {} 1754 1755 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1756 Token &NameTok) override { 1757 SourceLocation Loc = NameTok.getLocation(); 1758 bool IsBegin; 1759 1760 Token Tok; 1761 1762 // Lex the 'begin' or 'end'. 1763 PP.LexUnexpandedToken(Tok); 1764 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo(); 1765 if (BeginEnd && BeginEnd->isStr("begin")) { 1766 IsBegin = true; 1767 } else if (BeginEnd && BeginEnd->isStr("end")) { 1768 IsBegin = false; 1769 } else { 1770 PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax); 1771 return; 1772 } 1773 1774 // Verify that this is followed by EOD. 1775 PP.LexUnexpandedToken(Tok); 1776 if (Tok.isNot(tok::eod)) 1777 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma"; 1778 1779 // The start location of the active audit. 1780 SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc(); 1781 1782 // The start location we want after processing this. 1783 SourceLocation NewLoc; 1784 PPCallbacks *Callbacks = PP.getPPCallbacks(); 1785 1786 if (IsBegin) { 1787 // Complain about attempts to re-enter an audit. 1788 if (BeginLoc.isValid()) { 1789 PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull); 1790 PP.Diag(BeginLoc, diag::note_pragma_entered_here); 1791 } 1792 NewLoc = Loc; 1793 if (Callbacks) 1794 Callbacks->PragmaAssumeNonNullBegin(NewLoc); 1795 } else { 1796 // Complain about attempts to leave an audit that doesn't exist. 1797 if (!BeginLoc.isValid()) { 1798 PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull); 1799 return; 1800 } 1801 NewLoc = SourceLocation(); 1802 if (Callbacks) 1803 Callbacks->PragmaAssumeNonNullEnd(NewLoc); 1804 } 1805 1806 PP.setPragmaAssumeNonNullLoc(NewLoc); 1807 } 1808 }; 1809 1810 /// Handle "\#pragma region [...]" 1811 /// 1812 /// The syntax is 1813 /// \code 1814 /// #pragma region [optional name] 1815 /// #pragma endregion [optional comment] 1816 /// \endcode 1817 /// 1818 /// \note This is 1819 /// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a> 1820 /// pragma, just skipped by compiler. 1821 struct PragmaRegionHandler : public PragmaHandler { 1822 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) {} 1823 1824 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, 1825 Token &NameTok) override { 1826 // #pragma region: endregion matches can be verified 1827 // __pragma(region): no sense, but ignored by msvc 1828 // _Pragma is not valid for MSVC, but there isn't any point 1829 // to handle a _Pragma differently. 1830 } 1831 }; 1832 1833 } // namespace 1834 1835 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas: 1836 /// \#pragma GCC poison/system_header/dependency and \#pragma once. 1837 void Preprocessor::RegisterBuiltinPragmas() { 1838 AddPragmaHandler(new PragmaOnceHandler()); 1839 AddPragmaHandler(new PragmaMarkHandler()); 1840 AddPragmaHandler(new PragmaPushMacroHandler()); 1841 AddPragmaHandler(new PragmaPopMacroHandler()); 1842 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message)); 1843 1844 // #pragma GCC ... 1845 AddPragmaHandler("GCC", new PragmaPoisonHandler()); 1846 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler()); 1847 AddPragmaHandler("GCC", new PragmaDependencyHandler()); 1848 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC")); 1849 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning, 1850 "GCC")); 1851 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error, 1852 "GCC")); 1853 // #pragma clang ... 1854 AddPragmaHandler("clang", new PragmaPoisonHandler()); 1855 AddPragmaHandler("clang", new PragmaSystemHeaderHandler()); 1856 AddPragmaHandler("clang", new PragmaDebugHandler()); 1857 AddPragmaHandler("clang", new PragmaDependencyHandler()); 1858 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang")); 1859 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler()); 1860 AddPragmaHandler("clang", new PragmaAssumeNonNullHandler()); 1861 1862 // #pragma clang module ... 1863 auto *ModuleHandler = new PragmaNamespace("module"); 1864 AddPragmaHandler("clang", ModuleHandler); 1865 ModuleHandler->AddPragma(new PragmaModuleImportHandler()); 1866 ModuleHandler->AddPragma(new PragmaModuleBeginHandler()); 1867 ModuleHandler->AddPragma(new PragmaModuleEndHandler()); 1868 ModuleHandler->AddPragma(new PragmaModuleBuildHandler()); 1869 ModuleHandler->AddPragma(new PragmaModuleLoadHandler()); 1870 1871 // Add region pragmas. 1872 AddPragmaHandler(new PragmaRegionHandler("region")); 1873 AddPragmaHandler(new PragmaRegionHandler("endregion")); 1874 1875 // MS extensions. 1876 if (LangOpts.MicrosoftExt) { 1877 AddPragmaHandler(new PragmaWarningHandler()); 1878 AddPragmaHandler(new PragmaExecCharsetHandler()); 1879 AddPragmaHandler(new PragmaIncludeAliasHandler()); 1880 AddPragmaHandler(new PragmaHdrstopHandler()); 1881 } 1882 1883 // Pragmas added by plugins 1884 for (PragmaHandlerRegistry::iterator it = PragmaHandlerRegistry::begin(), 1885 ie = PragmaHandlerRegistry::end(); 1886 it != ie; ++it) { 1887 AddPragmaHandler(it->instantiate().release()); 1888 } 1889 } 1890 1891 /// Ignore all pragmas, useful for modes such as -Eonly which would otherwise 1892 /// warn about those pragmas being unknown. 1893 void Preprocessor::IgnorePragmas() { 1894 AddPragmaHandler(new EmptyPragmaHandler()); 1895 // Also ignore all pragmas in all namespaces created 1896 // in Preprocessor::RegisterBuiltinPragmas(). 1897 AddPragmaHandler("GCC", new EmptyPragmaHandler()); 1898 AddPragmaHandler("clang", new EmptyPragmaHandler()); 1899 } 1900