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