1 //===--- Pragma.cpp - Pragma registration and handling --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the PragmaHandler/PragmaTable interfaces and implements
11 // pragma related methods of the Preprocessor class.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Lex/Pragma.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/IdentifierTable.h"
18 #include "clang/Basic/SourceLocation.h"
19 #include "clang/Basic/SourceManager.h"
20 #include "clang/Basic/TokenKinds.h"
21 #include "clang/Lex/HeaderSearch.h"
22 #include "clang/Lex/LexDiagnostic.h"
23 #include "clang/Lex/MacroInfo.h"
24 #include "clang/Lex/PPCallbacks.h"
25 #include "clang/Lex/Preprocessor.h"
26 #include "clang/Lex/PreprocessorLexer.h"
27 #include "clang/Lex/PTHLexer.h"
28 #include "clang/Lex/Token.h"
29 #include "clang/Lex/TokenLexer.h"
30 #include "llvm/ADT/ArrayRef.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/SmallString.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/StringSwitch.h"
36 #include "llvm/Support/CrashRecoveryContext.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Support/ErrorHandling.h"
46 using namespace clang;
48 // Out-of-line destructor to provide a home for the class.
49 PragmaHandler::~PragmaHandler() {
52 //===----------------------------------------------------------------------===//
53 // EmptyPragmaHandler Implementation.
54 //===----------------------------------------------------------------------===//
56 EmptyPragmaHandler::EmptyPragmaHandler(StringRef Name) : PragmaHandler(Name) {}
58 void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
59 PragmaIntroducerKind Introducer,
62 //===----------------------------------------------------------------------===//
63 // PragmaNamespace Implementation.
64 //===----------------------------------------------------------------------===//
66 PragmaNamespace::~PragmaNamespace() {
67 llvm::DeleteContainerSeconds(Handlers);
70 /// FindHandler - Check to see if there is already a handler for the
71 /// specified name. If not, return the handler for the null identifier if it
72 /// exists, otherwise return null. If IgnoreNull is true (the default) then
73 /// the null handler isn't returned on failure to match.
74 PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
75 bool IgnoreNull) const {
76 if (PragmaHandler *Handler = Handlers.lookup(Name))
78 return IgnoreNull ? nullptr : Handlers.lookup(StringRef());
81 void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
82 assert(!Handlers.lookup(Handler->getName()) &&
83 "A handler with this name is already registered in this namespace");
84 Handlers[Handler->getName()] = Handler;
87 void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
88 assert(Handlers.lookup(Handler->getName()) &&
89 "Handler not registered in this namespace");
90 Handlers.erase(Handler->getName());
93 void PragmaNamespace::HandlePragma(Preprocessor &PP,
94 PragmaIntroducerKind Introducer,
96 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
97 // expand it, the user can have a STDC #define, that should not affect this.
98 PP.LexUnexpandedToken(Tok);
100 // Get the handler for this token. If there is no handler, ignore the pragma.
101 PragmaHandler *Handler
102 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
104 /*IgnoreNull=*/false);
106 PP.Diag(Tok, diag::warn_pragma_ignored);
110 // Otherwise, pass it down.
111 Handler->HandlePragma(PP, Introducer, Tok);
114 //===----------------------------------------------------------------------===//
115 // Preprocessor Pragma Directive Handling.
116 //===----------------------------------------------------------------------===//
118 /// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the
119 /// rest of the pragma, passing it to the registered pragma handlers.
120 void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc,
121 PragmaIntroducerKind Introducer) {
123 Callbacks->PragmaDirective(IntroducerLoc, Introducer);
130 // Invoke the first level of pragma handlers which reads the namespace id.
132 PragmaHandlers->HandlePragma(*this, Introducer, Tok);
134 // If the pragma handler didn't read the rest of the line, consume it now.
135 if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
136 || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
137 DiscardUntilEndOfDirective();
142 /// \brief Helper class for \see Preprocessor::Handle_Pragma.
143 class LexingFor_PragmaRAII {
145 bool InMacroArgPreExpansion;
151 LexingFor_PragmaRAII(Preprocessor &PP, bool InMacroArgPreExpansion,
153 : PP(PP), InMacroArgPreExpansion(InMacroArgPreExpansion),
154 Failed(false), OutTok(Tok) {
155 if (InMacroArgPreExpansion) {
157 PP.EnableBacktrackAtThisPos();
161 ~LexingFor_PragmaRAII() {
162 if (InMacroArgPreExpansion) {
164 PP.CommitBacktrackedTokens();
177 } // end anonymous namespace
179 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
180 /// return the first token after the directive. The _Pragma token has just
181 /// been read into 'Tok'.
182 void Preprocessor::Handle_Pragma(Token &Tok) {
184 // This works differently if we are pre-expanding a macro argument.
185 // In that case we don't actually "activate" the pragma now, we only lex it
186 // until we are sure it is lexically correct and then we backtrack so that
187 // we activate the pragma whenever we encounter the tokens again in the token
188 // stream. This ensures that we will activate it in the correct location
189 // or that we will ignore it if it never enters the token stream, e.g:
192 // #define INACTIVE(x) EMPTY(x)
193 // INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\""))
195 LexingFor_PragmaRAII _PragmaLexing(*this, InMacroArgPreExpansion, Tok);
197 // Remember the pragma token location.
198 SourceLocation PragmaLoc = Tok.getLocation();
202 if (Tok.isNot(tok::l_paren)) {
203 Diag(PragmaLoc, diag::err__Pragma_malformed);
204 return _PragmaLexing.failed();
209 if (!tok::isStringLiteral(Tok.getKind())) {
210 Diag(PragmaLoc, diag::err__Pragma_malformed);
211 // Skip bad tokens, and the ')', if present.
212 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
214 while (Tok.isNot(tok::r_paren) &&
215 !Tok.isAtStartOfLine() &&
218 if (Tok.is(tok::r_paren))
220 return _PragmaLexing.failed();
223 if (Tok.hasUDSuffix()) {
224 Diag(Tok, diag::err_invalid_string_udl);
225 // Skip this token, and the ')', if present.
227 if (Tok.is(tok::r_paren))
229 return _PragmaLexing.failed();
232 // Remember the string.
237 if (Tok.isNot(tok::r_paren)) {
238 Diag(PragmaLoc, diag::err__Pragma_malformed);
239 return _PragmaLexing.failed();
242 if (InMacroArgPreExpansion)
245 SourceLocation RParenLoc = Tok.getLocation();
246 std::string StrVal = getSpelling(StrTok);
248 // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1:
249 // "The string literal is destringized by deleting any encoding prefix,
250 // deleting the leading and trailing double-quotes, replacing each escape
251 // sequence \" by a double-quote, and replacing each escape sequence \\ by a
252 // single backslash."
253 if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
254 (StrVal[0] == 'u' && StrVal[1] != '8'))
255 StrVal.erase(StrVal.begin());
256 else if (StrVal[0] == 'u')
257 StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
259 if (StrVal[0] == 'R') {
260 // FIXME: C++11 does not specify how to handle raw-string-literals here.
261 // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
262 assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
263 "Invalid raw string token!");
265 // Measure the length of the d-char-sequence.
266 unsigned NumDChars = 0;
267 while (StrVal[2 + NumDChars] != '(') {
268 assert(NumDChars < (StrVal.size() - 5) / 2 &&
269 "Invalid raw string token!");
272 assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
274 // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
276 StrVal.erase(0, 2 + NumDChars);
277 StrVal.erase(StrVal.size() - 1 - NumDChars);
279 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
280 "Invalid string token!");
282 // Remove escaped quotes and escapes.
283 unsigned ResultPos = 1;
284 for (size_t i = 1, e = StrVal.size() - 1; i != e; ++i) {
285 // Skip escapes. \\ -> '\' and \" -> '"'.
286 if (StrVal[i] == '\\' && i + 1 < e &&
287 (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
289 StrVal[ResultPos++] = StrVal[i];
291 StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
294 // Remove the front quote, replacing it with a space, so that the pragma
295 // contents appear to have a space before them.
298 // Replace the terminating quote with a \n.
299 StrVal[StrVal.size()-1] = '\n';
301 // Plop the string (including the newline and trailing null) into a buffer
302 // where we can lex it.
305 CreateString(StrVal, TmpTok);
306 SourceLocation TokLoc = TmpTok.getLocation();
308 // Make and enter a lexer object so that we lex and expand the tokens just
310 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
311 StrVal.size(), *this);
313 EnterSourceFileWithLexer(TL, nullptr);
315 // With everything set up, lex this as a #pragma directive.
316 HandlePragmaDirective(PragmaLoc, PIK__Pragma);
318 // Finally, return whatever came after the pragma directive.
322 /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
323 /// is not enclosed within a string literal.
324 void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
325 // Remember the pragma token location.
326 SourceLocation PragmaLoc = Tok.getLocation();
330 if (Tok.isNot(tok::l_paren)) {
331 Diag(PragmaLoc, diag::err__Pragma_malformed);
335 // Get the tokens enclosed within the __pragma(), as well as the final ')'.
336 SmallVector<Token, 32> PragmaToks;
339 while (Tok.isNot(tok::eof)) {
340 PragmaToks.push_back(Tok);
341 if (Tok.is(tok::l_paren))
343 else if (Tok.is(tok::r_paren) && NumParens-- == 0)
348 if (Tok.is(tok::eof)) {
349 Diag(PragmaLoc, diag::err_unterminated___pragma);
353 PragmaToks.front().setFlag(Token::LeadingSpace);
355 // Replace the ')' with an EOD to mark the end of the pragma.
356 PragmaToks.back().setKind(tok::eod);
358 Token *TokArray = new Token[PragmaToks.size()];
359 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
361 // Push the tokens onto the stack.
362 EnterTokenStream(TokArray, PragmaToks.size(), true, true);
364 // With everything set up, lex this as a #pragma directive.
365 HandlePragmaDirective(PragmaLoc, PIK___pragma);
367 // Finally, return whatever came after the pragma directive.
371 /// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
373 void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
374 // Don't honor the 'once' when handling the primary source file, unless
375 // this is a prefix to a TU, which indicates we're generating a PCH file, or
376 // when the main file is a header (e.g. when -xc-header is provided on the
378 if (isInPrimaryFile() && TUKind != TU_Prefix && !getLangOpts().IsHeaderFile) {
379 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
383 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
384 // Mark the file as a once-only file now.
385 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
388 void Preprocessor::HandlePragmaMark() {
389 assert(CurPPLexer && "No current lexer?");
391 CurLexer->ReadToEndOfLine();
393 CurPTHLexer->DiscardToEndOfLine();
396 /// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
398 void Preprocessor::HandlePragmaPoison() {
402 // Read the next token to poison. While doing this, pretend that we are
403 // skipping while reading the identifier to poison.
404 // This avoids errors on code like:
405 // #pragma GCC poison X
406 // #pragma GCC poison X
407 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
408 LexUnexpandedToken(Tok);
409 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
411 // If we reached the end of line, we're done.
412 if (Tok.is(tok::eod)) return;
414 // Can only poison identifiers.
415 if (Tok.isNot(tok::raw_identifier)) {
416 Diag(Tok, diag::err_pp_invalid_poison);
420 // Look up the identifier info for the token. We disabled identifier lookup
421 // by saying we're skipping contents, so we need to do this manually.
422 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
425 if (II->isPoisoned()) continue;
427 // If this is a macro identifier, emit a warning.
428 if (isMacroDefined(II))
429 Diag(Tok, diag::pp_poisoning_existing_macro);
431 // Finally, poison it!
434 II->setChangedSinceDeserialization();
438 /// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
439 /// that the whole directive has been parsed.
440 void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
441 if (isInPrimaryFile()) {
442 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
446 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
447 PreprocessorLexer *TheLexer = getCurrentFileLexer();
449 // Mark the file as a system header.
450 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
453 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
454 if (PLoc.isInvalid())
457 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
459 // Notify the client, if desired, that we are in a new source file.
461 Callbacks->FileChanged(SysHeaderTok.getLocation(),
462 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
464 // Emit a line marker. This will change any source locations from this point
465 // forward to realize they are in a system header.
466 // Create a line note with this information.
467 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine()+1,
468 FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
469 /*IsSystem=*/true, /*IsExternC=*/false);
472 /// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
474 void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
476 CurPPLexer->LexIncludeFilename(FilenameTok);
478 // If the token kind is EOD, the error has already been diagnosed.
479 if (FilenameTok.is(tok::eod))
482 // Reserve a buffer to get the spelling.
483 SmallString<128> FilenameBuffer;
484 bool Invalid = false;
485 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
490 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
491 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
493 if (Filename.empty())
496 // Search include directories for this file.
497 const DirectoryLookup *CurDir;
498 const FileEntry *File =
499 LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
500 nullptr, CurDir, nullptr, nullptr, nullptr);
502 if (!SuppressIncludeNotFoundError)
503 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
507 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
509 // If this file is older than the file it depends on, emit a diagnostic.
510 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
511 // Lex tokens at the end of the message and include them in the message.
514 while (DependencyTok.isNot(tok::eod)) {
515 Message += getSpelling(DependencyTok) + " ";
519 // Remove the trailing ' ' if present.
520 if (!Message.empty())
521 Message.erase(Message.end()-1);
522 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
526 /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
527 /// Return the IdentifierInfo* associated with the macro to push or pop.
528 IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
529 // Remember the pragma token location.
530 Token PragmaTok = Tok;
534 if (Tok.isNot(tok::l_paren)) {
535 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
536 << getSpelling(PragmaTok);
540 // Read the macro name string.
542 if (Tok.isNot(tok::string_literal)) {
543 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
544 << getSpelling(PragmaTok);
548 if (Tok.hasUDSuffix()) {
549 Diag(Tok, diag::err_invalid_string_udl);
553 // Remember the macro string.
554 std::string StrVal = getSpelling(Tok);
558 if (Tok.isNot(tok::r_paren)) {
559 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
560 << getSpelling(PragmaTok);
564 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
565 "Invalid string token!");
567 // Create a Token from the string.
569 MacroTok.startToken();
570 MacroTok.setKind(tok::raw_identifier);
571 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
573 // Get the IdentifierInfo of MacroToPushTok.
574 return LookUpIdentifierInfo(MacroTok);
577 /// \brief Handle \#pragma push_macro.
581 /// #pragma push_macro("macro")
583 void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
584 // Parse the pragma directive and get the macro IdentifierInfo*.
585 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
586 if (!IdentInfo) return;
588 // Get the MacroInfo associated with IdentInfo.
589 MacroInfo *MI = getMacroInfo(IdentInfo);
592 // Allow the original MacroInfo to be redefined later.
593 MI->setIsAllowRedefinitionsWithoutWarning(true);
596 // Push the cloned MacroInfo so we can retrieve it later.
597 PragmaPushMacroInfo[IdentInfo].push_back(MI);
600 /// \brief Handle \#pragma pop_macro.
604 /// #pragma pop_macro("macro")
606 void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
607 SourceLocation MessageLoc = PopMacroTok.getLocation();
609 // Parse the pragma directive and get the macro IdentifierInfo*.
610 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
611 if (!IdentInfo) return;
613 // Find the vector<MacroInfo*> associated with the macro.
614 llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
615 PragmaPushMacroInfo.find(IdentInfo);
616 if (iter != PragmaPushMacroInfo.end()) {
617 // Forget the MacroInfo currently associated with IdentInfo.
618 if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
619 if (MI->isWarnIfUnused())
620 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
621 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
624 // Get the MacroInfo we want to reinstall.
625 MacroInfo *MacroToReInstall = iter->second.back();
627 if (MacroToReInstall)
628 // Reinstall the previously pushed macro.
629 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
631 // Pop PragmaPushMacroInfo stack.
632 iter->second.pop_back();
633 if (iter->second.empty())
634 PragmaPushMacroInfo.erase(iter);
636 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
637 << IdentInfo->getName();
641 void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
642 // We will either get a quoted filename or a bracketed filename, and we
643 // have to track which we got. The first filename is the source name,
644 // and the second name is the mapped filename. If the first is quoted,
645 // the second must be as well (cannot mix and match quotes and brackets).
647 // Get the open paren
649 if (Tok.isNot(tok::l_paren)) {
650 Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
654 // We expect either a quoted string literal, or a bracketed name
655 Token SourceFilenameTok;
656 CurPPLexer->LexIncludeFilename(SourceFilenameTok);
657 if (SourceFilenameTok.is(tok::eod)) {
658 // The diagnostic has already been handled
662 StringRef SourceFileName;
663 SmallString<128> FileNameBuffer;
664 if (SourceFilenameTok.is(tok::string_literal) ||
665 SourceFilenameTok.is(tok::angle_string_literal)) {
666 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
667 } else if (SourceFilenameTok.is(tok::less)) {
668 // This could be a path instead of just a name
669 FileNameBuffer.push_back('<');
671 if (ConcatenateIncludeName(FileNameBuffer, End))
672 return; // Diagnostic already emitted
673 SourceFileName = FileNameBuffer;
675 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
678 FileNameBuffer.clear();
680 // Now we expect a comma, followed by another include name
682 if (Tok.isNot(tok::comma)) {
683 Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
687 Token ReplaceFilenameTok;
688 CurPPLexer->LexIncludeFilename(ReplaceFilenameTok);
689 if (ReplaceFilenameTok.is(tok::eod)) {
690 // The diagnostic has already been handled
694 StringRef ReplaceFileName;
695 if (ReplaceFilenameTok.is(tok::string_literal) ||
696 ReplaceFilenameTok.is(tok::angle_string_literal)) {
697 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
698 } else if (ReplaceFilenameTok.is(tok::less)) {
699 // This could be a path instead of just a name
700 FileNameBuffer.push_back('<');
702 if (ConcatenateIncludeName(FileNameBuffer, End))
703 return; // Diagnostic already emitted
704 ReplaceFileName = FileNameBuffer;
706 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
710 // Finally, we expect the closing paren
712 if (Tok.isNot(tok::r_paren)) {
713 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
717 // Now that we have the source and target filenames, we need to make sure
718 // they're both of the same type (angled vs non-angled)
719 StringRef OriginalSource = SourceFileName;
721 bool SourceIsAngled =
722 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
724 bool ReplaceIsAngled =
725 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
727 if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
728 (SourceIsAngled != ReplaceIsAngled)) {
731 DiagID = diag::warn_pragma_include_alias_mismatch_angle;
733 DiagID = diag::warn_pragma_include_alias_mismatch_quote;
735 Diag(SourceFilenameTok.getLocation(), DiagID)
742 // Now we can let the include handler know about this mapping
743 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
746 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
747 /// If 'Namespace' is non-null, then it is a token required to exist on the
748 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
749 void Preprocessor::AddPragmaHandler(StringRef Namespace,
750 PragmaHandler *Handler) {
751 PragmaNamespace *InsertNS = PragmaHandlers.get();
753 // If this is specified to be in a namespace, step down into it.
754 if (!Namespace.empty()) {
755 // If there is already a pragma handler with the name of this namespace,
756 // we either have an error (directive with the same name as a namespace) or
757 // we already have the namespace to insert into.
758 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
759 InsertNS = Existing->getIfNamespace();
760 assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
761 " handler with the same name!");
763 // Otherwise, this namespace doesn't exist yet, create and insert the
765 InsertNS = new PragmaNamespace(Namespace);
766 PragmaHandlers->AddPragma(InsertNS);
770 // Check to make sure we don't already have a pragma for this identifier.
771 assert(!InsertNS->FindHandler(Handler->getName()) &&
772 "Pragma handler already exists for this identifier!");
773 InsertNS->AddPragma(Handler);
776 /// RemovePragmaHandler - Remove the specific pragma handler from the
777 /// preprocessor. If \arg Namespace is non-null, then it should be the
778 /// namespace that \arg Handler was added to. It is an error to remove
779 /// a handler that has not been registered.
780 void Preprocessor::RemovePragmaHandler(StringRef Namespace,
781 PragmaHandler *Handler) {
782 PragmaNamespace *NS = PragmaHandlers.get();
784 // If this is specified to be in a namespace, step down into it.
785 if (!Namespace.empty()) {
786 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
787 assert(Existing && "Namespace containing handler does not exist!");
789 NS = Existing->getIfNamespace();
790 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
793 NS->RemovePragmaHandler(Handler);
795 // If this is a non-default namespace and it is now empty, remove it.
796 if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
797 PragmaHandlers->RemovePragmaHandler(NS);
802 bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
804 LexUnexpandedToken(Tok);
806 if (Tok.isNot(tok::identifier)) {
807 Diag(Tok, diag::ext_on_off_switch_syntax);
810 IdentifierInfo *II = Tok.getIdentifierInfo();
812 Result = tok::OOS_ON;
813 else if (II->isStr("OFF"))
814 Result = tok::OOS_OFF;
815 else if (II->isStr("DEFAULT"))
816 Result = tok::OOS_DEFAULT;
818 Diag(Tok, diag::ext_on_off_switch_syntax);
822 // Verify that this is followed by EOD.
823 LexUnexpandedToken(Tok);
824 if (Tok.isNot(tok::eod))
825 Diag(Tok, diag::ext_pragma_syntax_eod);
831 /// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
832 struct PragmaOnceHandler : public PragmaHandler {
833 PragmaOnceHandler() : PragmaHandler("once") {}
834 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
835 Token &OnceTok) override {
836 PP.CheckEndOfDirective("pragma once");
837 PP.HandlePragmaOnce(OnceTok);
841 /// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
842 /// rest of the line is not lexed.
843 struct PragmaMarkHandler : public PragmaHandler {
844 PragmaMarkHandler() : PragmaHandler("mark") {}
846 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
847 Token &MarkTok) override {
848 PP.HandlePragmaMark();
852 /// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
853 struct PragmaPoisonHandler : public PragmaHandler {
854 PragmaPoisonHandler() : PragmaHandler("poison") {}
856 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
857 Token &PoisonTok) override {
858 PP.HandlePragmaPoison();
862 /// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
863 /// as a system header, which silences warnings in it.
864 struct PragmaSystemHeaderHandler : public PragmaHandler {
865 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
867 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
868 Token &SHToken) override {
869 PP.HandlePragmaSystemHeader(SHToken);
870 PP.CheckEndOfDirective("pragma");
874 struct PragmaDependencyHandler : public PragmaHandler {
875 PragmaDependencyHandler() : PragmaHandler("dependency") {}
877 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
878 Token &DepToken) override {
879 PP.HandlePragmaDependency(DepToken);
883 struct PragmaDebugHandler : public PragmaHandler {
884 PragmaDebugHandler() : PragmaHandler("__debug") {}
886 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
887 Token &DepToken) override {
889 PP.LexUnexpandedToken(Tok);
890 if (Tok.isNot(tok::identifier)) {
891 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
894 IdentifierInfo *II = Tok.getIdentifierInfo();
896 if (II->isStr("assert")) {
897 llvm_unreachable("This is an assertion!");
898 } else if (II->isStr("crash")) {
900 } else if (II->isStr("parser_crash")) {
902 Crasher.startToken();
903 Crasher.setKind(tok::annot_pragma_parser_crash);
904 Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
905 PP.EnterToken(Crasher);
906 } else if (II->isStr("dump")) {
908 PP.LexUnexpandedToken(Identifier);
909 if (auto *DumpII = Identifier.getIdentifierInfo()) {
911 DumpAnnot.startToken();
912 DumpAnnot.setKind(tok::annot_pragma_dump);
913 DumpAnnot.setAnnotationRange(
914 SourceRange(Tok.getLocation(), Identifier.getLocation()));
915 DumpAnnot.setAnnotationValue(DumpII);
916 PP.DiscardUntilEndOfDirective();
917 PP.EnterToken(DumpAnnot);
919 PP.Diag(Identifier, diag::warn_pragma_debug_missing_argument)
922 } else if (II->isStr("llvm_fatal_error")) {
923 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
924 } else if (II->isStr("llvm_unreachable")) {
925 llvm_unreachable("#pragma clang __debug llvm_unreachable");
926 } else if (II->isStr("macro")) {
928 PP.LexUnexpandedToken(MacroName);
929 auto *MacroII = MacroName.getIdentifierInfo();
931 PP.dumpMacroInfo(MacroII);
933 PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument)
935 } else if (II->isStr("overflow_stack")) {
936 DebugOverflowStack();
937 } else if (II->isStr("handle_crash")) {
938 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
941 } else if (II->isStr("captured")) {
944 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
948 PPCallbacks *Callbacks = PP.getPPCallbacks();
950 Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
953 void HandleCaptured(Preprocessor &PP) {
954 // Skip if emitting preprocessed output.
955 if (PP.isPreprocessedOutput())
959 PP.LexUnexpandedToken(Tok);
961 if (Tok.isNot(tok::eod)) {
962 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
963 << "pragma clang __debug captured";
967 SourceLocation NameLoc = Tok.getLocation();
968 MutableArrayRef<Token> Toks(
969 PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
970 Toks[0].startToken();
971 Toks[0].setKind(tok::annot_pragma_captured);
972 Toks[0].setLocation(NameLoc);
974 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
977 // Disable MSVC warning about runtime stack overflow.
979 #pragma warning(disable : 4717)
981 static void DebugOverflowStack() {
982 void (*volatile Self)() = DebugOverflowStack;
986 #pragma warning(default : 4717)
991 /// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
992 struct PragmaDiagnosticHandler : public PragmaHandler {
994 const char *Namespace;
997 explicit PragmaDiagnosticHandler(const char *NS) :
998 PragmaHandler("diagnostic"), Namespace(NS) {}
1000 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1001 Token &DiagToken) override {
1002 SourceLocation DiagLoc = DiagToken.getLocation();
1004 PP.LexUnexpandedToken(Tok);
1005 if (Tok.isNot(tok::identifier)) {
1006 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1009 IdentifierInfo *II = Tok.getIdentifierInfo();
1010 PPCallbacks *Callbacks = PP.getPPCallbacks();
1012 if (II->isStr("pop")) {
1013 if (!PP.getDiagnostics().popMappings(DiagLoc))
1014 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
1016 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
1018 } else if (II->isStr("push")) {
1019 PP.getDiagnostics().pushMappings(DiagLoc);
1021 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
1025 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
1026 .Case("ignored", diag::Severity::Ignored)
1027 .Case("warning", diag::Severity::Warning)
1028 .Case("error", diag::Severity::Error)
1029 .Case("fatal", diag::Severity::Fatal)
1030 .Default(diag::Severity());
1032 if (SV == diag::Severity()) {
1033 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1037 PP.LexUnexpandedToken(Tok);
1038 SourceLocation StringLoc = Tok.getLocation();
1040 std::string WarningName;
1041 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
1042 /*MacroExpansion=*/false))
1045 if (Tok.isNot(tok::eod)) {
1046 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1050 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1051 (WarningName[1] != 'W' && WarningName[1] != 'R')) {
1052 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
1056 diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1057 : diag::Flavor::Remark;
1058 StringRef Group = StringRef(WarningName).substr(2);
1059 bool unknownDiag = false;
1060 if (Group == "everything") {
1061 // Special handling for pragma clang diagnostic ... "-Weverything".
1062 // There is no formal group named "everything", so there has to be a
1063 // special case for it.
1064 PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc);
1066 unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV,
1069 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1072 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
1076 /// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1077 /// diagnostics, so we don't really implement this pragma. We parse it and
1078 /// ignore it to avoid -Wunknown-pragma warnings.
1079 struct PragmaWarningHandler : public PragmaHandler {
1080 PragmaWarningHandler() : PragmaHandler("warning") {}
1082 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1083 Token &Tok) override {
1084 // Parse things like:
1087 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
1088 SourceLocation DiagLoc = Tok.getLocation();
1089 PPCallbacks *Callbacks = PP.getPPCallbacks();
1092 if (Tok.isNot(tok::l_paren)) {
1093 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1098 IdentifierInfo *II = Tok.getIdentifierInfo();
1100 if (II && II->isStr("push")) {
1101 // #pragma warning( push[ ,n ] )
1104 if (Tok.is(tok::comma)) {
1107 if (Tok.is(tok::numeric_constant) &&
1108 PP.parseSimpleIntegerLiteral(Tok, Value))
1110 if (Level < 0 || Level > 4) {
1111 PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1116 Callbacks->PragmaWarningPush(DiagLoc, Level);
1117 } else if (II && II->isStr("pop")) {
1118 // #pragma warning( pop )
1121 Callbacks->PragmaWarningPop(DiagLoc);
1123 // #pragma warning( warning-specifier : warning-number-list
1124 // [; warning-specifier : warning-number-list...] )
1126 II = Tok.getIdentifierInfo();
1127 if (!II && !Tok.is(tok::numeric_constant)) {
1128 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1132 // Figure out which warning specifier this is.
1133 bool SpecifierValid;
1134 StringRef Specifier;
1135 llvm::SmallString<1> SpecifierBuf;
1137 Specifier = II->getName();
1138 SpecifierValid = llvm::StringSwitch<bool>(Specifier)
1139 .Cases("default", "disable", "error", "once",
1142 // If we read a correct specifier, snatch next token (that should be
1143 // ":", checked later).
1147 // Token is a numeric constant. It should be either 1, 2, 3 or 4.
1149 Specifier = PP.getSpelling(Tok, SpecifierBuf);
1150 if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
1151 SpecifierValid = (Value >= 1) && (Value <= 4);
1153 SpecifierValid = false;
1154 // Next token already snatched by parseSimpleIntegerLiteral.
1157 if (!SpecifierValid) {
1158 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1161 if (Tok.isNot(tok::colon)) {
1162 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1166 // Collect the warning ids.
1167 SmallVector<int, 4> Ids;
1169 while (Tok.is(tok::numeric_constant)) {
1171 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
1172 Value > std::numeric_limits<int>::max()) {
1173 PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1176 Ids.push_back(int(Value));
1179 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1181 // Parse the next specifier if there is a semicolon.
1182 if (Tok.isNot(tok::semi))
1188 if (Tok.isNot(tok::r_paren)) {
1189 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1194 if (Tok.isNot(tok::eod))
1195 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1199 /// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
1200 struct PragmaIncludeAliasHandler : public PragmaHandler {
1201 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
1202 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1203 Token &IncludeAliasTok) override {
1204 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
1208 /// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1209 /// extension. The syntax is:
1211 /// #pragma message(string)
1213 /// OR, in GCC mode:
1215 /// #pragma message string
1217 /// string is a string, which is fully macro expanded, and permits string
1218 /// concatenation, embedded escape characters, etc... See MSDN for more details.
1219 /// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1220 /// form as \#pragma message.
1221 struct PragmaMessageHandler : public PragmaHandler {
1223 const PPCallbacks::PragmaMessageKind Kind;
1224 const StringRef Namespace;
1226 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1227 bool PragmaNameOnly = false) {
1229 case PPCallbacks::PMK_Message:
1230 return PragmaNameOnly ? "message" : "pragma message";
1231 case PPCallbacks::PMK_Warning:
1232 return PragmaNameOnly ? "warning" : "pragma warning";
1233 case PPCallbacks::PMK_Error:
1234 return PragmaNameOnly ? "error" : "pragma error";
1236 llvm_unreachable("Unknown PragmaMessageKind!");
1240 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1241 StringRef Namespace = StringRef())
1242 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), Namespace(Namespace) {}
1244 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1245 Token &Tok) override {
1246 SourceLocation MessageLoc = Tok.getLocation();
1248 bool ExpectClosingParen = false;
1249 switch (Tok.getKind()) {
1251 // We have a MSVC style pragma message.
1252 ExpectClosingParen = true;
1256 case tok::string_literal:
1257 // We have a GCC style pragma message, and we just read the string.
1260 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1264 std::string MessageString;
1265 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1266 /*MacroExpansion=*/true))
1269 if (ExpectClosingParen) {
1270 if (Tok.isNot(tok::r_paren)) {
1271 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1274 PP.Lex(Tok); // eat the r_paren.
1277 if (Tok.isNot(tok::eod)) {
1278 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1282 // Output the message.
1283 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1284 ? diag::err_pragma_message
1285 : diag::warn_pragma_message) << MessageString;
1287 // If the pragma is lexically sound, notify any interested PPCallbacks.
1288 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1289 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
1293 /// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
1294 /// macro on the top of the stack.
1295 struct PragmaPushMacroHandler : public PragmaHandler {
1296 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
1298 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1299 Token &PushMacroTok) override {
1300 PP.HandlePragmaPushMacro(PushMacroTok);
1304 /// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
1305 /// macro to the value on the top of the stack.
1306 struct PragmaPopMacroHandler : public PragmaHandler {
1307 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
1309 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1310 Token &PopMacroTok) override {
1311 PP.HandlePragmaPopMacro(PopMacroTok);
1315 // Pragma STDC implementations.
1317 /// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
1318 struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
1319 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
1321 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1322 Token &Tok) override {
1323 tok::OnOffSwitch OOS;
1324 if (PP.LexOnOffSwitch(OOS))
1326 if (OOS == tok::OOS_ON)
1327 PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
1331 /// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
1332 struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
1333 PragmaSTDC_CX_LIMITED_RANGEHandler()
1334 : PragmaHandler("CX_LIMITED_RANGE") {}
1336 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1337 Token &Tok) override {
1338 tok::OnOffSwitch OOS;
1339 PP.LexOnOffSwitch(OOS);
1343 /// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
1344 struct PragmaSTDC_UnknownHandler : public PragmaHandler {
1345 PragmaSTDC_UnknownHandler() {}
1347 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1348 Token &UnknownTok) override {
1349 // C99 6.10.6p2, unknown forms are not allowed.
1350 PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
1354 /// PragmaARCCFCodeAuditedHandler -
1355 /// \#pragma clang arc_cf_code_audited begin/end
1356 struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1357 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
1359 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1360 Token &NameTok) override {
1361 SourceLocation Loc = NameTok.getLocation();
1366 // Lex the 'begin' or 'end'.
1367 PP.LexUnexpandedToken(Tok);
1368 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1369 if (BeginEnd && BeginEnd->isStr("begin")) {
1371 } else if (BeginEnd && BeginEnd->isStr("end")) {
1374 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1378 // Verify that this is followed by EOD.
1379 PP.LexUnexpandedToken(Tok);
1380 if (Tok.isNot(tok::eod))
1381 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1383 // The start location of the active audit.
1384 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1386 // The start location we want after processing this.
1387 SourceLocation NewLoc;
1390 // Complain about attempts to re-enter an audit.
1391 if (BeginLoc.isValid()) {
1392 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1393 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1397 // Complain about attempts to leave an audit that doesn't exist.
1398 if (!BeginLoc.isValid()) {
1399 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1402 NewLoc = SourceLocation();
1405 PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1409 /// PragmaAssumeNonNullHandler -
1410 /// \#pragma clang assume_nonnull begin/end
1411 struct PragmaAssumeNonNullHandler : public PragmaHandler {
1412 PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
1414 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1415 Token &NameTok) override {
1416 SourceLocation Loc = NameTok.getLocation();
1421 // Lex the 'begin' or 'end'.
1422 PP.LexUnexpandedToken(Tok);
1423 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1424 if (BeginEnd && BeginEnd->isStr("begin")) {
1426 } else if (BeginEnd && BeginEnd->isStr("end")) {
1429 PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
1433 // Verify that this is followed by EOD.
1434 PP.LexUnexpandedToken(Tok);
1435 if (Tok.isNot(tok::eod))
1436 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1438 // The start location of the active audit.
1439 SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
1441 // The start location we want after processing this.
1442 SourceLocation NewLoc;
1445 // Complain about attempts to re-enter an audit.
1446 if (BeginLoc.isValid()) {
1447 PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
1448 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1452 // Complain about attempts to leave an audit that doesn't exist.
1453 if (!BeginLoc.isValid()) {
1454 PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
1457 NewLoc = SourceLocation();
1460 PP.setPragmaAssumeNonNullLoc(NewLoc);
1464 /// \brief Handle "\#pragma region [...]"
1468 /// #pragma region [optional name]
1469 /// #pragma endregion [optional comment]
1473 /// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1474 /// pragma, just skipped by compiler.
1475 struct PragmaRegionHandler : public PragmaHandler {
1476 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) { }
1478 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1479 Token &NameTok) override {
1480 // #pragma region: endregion matches can be verified
1481 // __pragma(region): no sense, but ignored by msvc
1482 // _Pragma is not valid for MSVC, but there isn't any point
1483 // to handle a _Pragma differently.
1487 } // end anonymous namespace
1489 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
1490 /// \#pragma GCC poison/system_header/dependency and \#pragma once.
1491 void Preprocessor::RegisterBuiltinPragmas() {
1492 AddPragmaHandler(new PragmaOnceHandler());
1493 AddPragmaHandler(new PragmaMarkHandler());
1494 AddPragmaHandler(new PragmaPushMacroHandler());
1495 AddPragmaHandler(new PragmaPopMacroHandler());
1496 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
1499 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1500 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1501 AddPragmaHandler("GCC", new PragmaDependencyHandler());
1502 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
1503 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1505 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1507 // #pragma clang ...
1508 AddPragmaHandler("clang", new PragmaPoisonHandler());
1509 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
1510 AddPragmaHandler("clang", new PragmaDebugHandler());
1511 AddPragmaHandler("clang", new PragmaDependencyHandler());
1512 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
1513 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
1514 AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
1516 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1517 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
1518 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
1521 if (LangOpts.MicrosoftExt) {
1522 AddPragmaHandler(new PragmaWarningHandler());
1523 AddPragmaHandler(new PragmaIncludeAliasHandler());
1524 AddPragmaHandler(new PragmaRegionHandler("region"));
1525 AddPragmaHandler(new PragmaRegionHandler("endregion"));
1528 // Pragmas added by plugins
1529 for (PragmaHandlerRegistry::iterator it = PragmaHandlerRegistry::begin(),
1530 ie = PragmaHandlerRegistry::end();
1532 AddPragmaHandler(it->instantiate().release());
1536 /// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
1537 /// warn about those pragmas being unknown.
1538 void Preprocessor::IgnorePragmas() {
1539 AddPragmaHandler(new EmptyPragmaHandler());
1540 // Also ignore all pragmas in all namespaces created
1541 // in Preprocessor::RegisterBuiltinPragmas().
1542 AddPragmaHandler("GCC", new EmptyPragmaHandler());
1543 AddPragmaHandler("clang", new EmptyPragmaHandler());
1544 if (PragmaHandler *NS = PragmaHandlers->FindHandler("STDC")) {
1545 // Preprocessor::RegisterBuiltinPragmas() already registers
1546 // PragmaSTDC_UnknownHandler as the empty handler, so remove it first,
1547 // otherwise there will be an assert about a duplicate handler.
1548 PragmaNamespace *STDCNamespace = NS->getIfNamespace();
1549 assert(STDCNamespace &&
1550 "Invalid namespace, registered as a regular pragma handler!");
1551 if (PragmaHandler *Existing = STDCNamespace->FindHandler("", false)) {
1552 RemovePragmaHandler("STDC", Existing);
1556 AddPragmaHandler("STDC", new EmptyPragmaHandler());