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/SourceManager.h"
18 #include "clang/Lex/HeaderSearch.h"
19 #include "clang/Lex/LexDiagnostic.h"
20 #include "clang/Lex/LiteralSupport.h"
21 #include "clang/Lex/MacroInfo.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/Support/CrashRecoveryContext.h"
27 #include "llvm/Support/ErrorHandling.h"
29 using namespace clang;
31 #include "llvm/Support/raw_ostream.h"
33 // Out-of-line destructor to provide a home for the class.
34 PragmaHandler::~PragmaHandler() {
37 //===----------------------------------------------------------------------===//
38 // EmptyPragmaHandler Implementation.
39 //===----------------------------------------------------------------------===//
41 EmptyPragmaHandler::EmptyPragmaHandler(StringRef Name) : PragmaHandler(Name) {}
43 void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
44 PragmaIntroducerKind Introducer,
47 //===----------------------------------------------------------------------===//
48 // PragmaNamespace Implementation.
49 //===----------------------------------------------------------------------===//
51 PragmaNamespace::~PragmaNamespace() {
52 llvm::DeleteContainerSeconds(Handlers);
55 /// FindHandler - Check to see if there is already a handler for the
56 /// specified name. If not, return the handler for the null identifier if it
57 /// exists, otherwise return null. If IgnoreNull is true (the default) then
58 /// the null handler isn't returned on failure to match.
59 PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
60 bool IgnoreNull) const {
61 if (PragmaHandler *Handler = Handlers.lookup(Name))
63 return IgnoreNull ? nullptr : Handlers.lookup(StringRef());
66 void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
67 assert(!Handlers.lookup(Handler->getName()) &&
68 "A handler with this name is already registered in this namespace");
69 Handlers[Handler->getName()] = Handler;
72 void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
73 assert(Handlers.lookup(Handler->getName()) &&
74 "Handler not registered in this namespace");
75 Handlers.erase(Handler->getName());
78 void PragmaNamespace::HandlePragma(Preprocessor &PP,
79 PragmaIntroducerKind Introducer,
81 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
82 // expand it, the user can have a STDC #define, that should not affect this.
83 PP.LexUnexpandedToken(Tok);
85 // Get the handler for this token. If there is no handler, ignore the pragma.
86 PragmaHandler *Handler
87 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
89 /*IgnoreNull=*/false);
91 PP.Diag(Tok, diag::warn_pragma_ignored);
95 // Otherwise, pass it down.
96 Handler->HandlePragma(PP, Introducer, Tok);
99 //===----------------------------------------------------------------------===//
100 // Preprocessor Pragma Directive Handling.
101 //===----------------------------------------------------------------------===//
103 /// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the
104 /// rest of the pragma, passing it to the registered pragma handlers.
105 void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc,
106 PragmaIntroducerKind Introducer) {
108 Callbacks->PragmaDirective(IntroducerLoc, Introducer);
115 // Invoke the first level of pragma handlers which reads the namespace id.
117 PragmaHandlers->HandlePragma(*this, Introducer, Tok);
119 // If the pragma handler didn't read the rest of the line, consume it now.
120 if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
121 || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
122 DiscardUntilEndOfDirective();
126 /// \brief Helper class for \see Preprocessor::Handle_Pragma.
127 class LexingFor_PragmaRAII {
129 bool InMacroArgPreExpansion;
135 LexingFor_PragmaRAII(Preprocessor &PP, bool InMacroArgPreExpansion,
137 : PP(PP), InMacroArgPreExpansion(InMacroArgPreExpansion),
138 Failed(false), OutTok(Tok) {
139 if (InMacroArgPreExpansion) {
141 PP.EnableBacktrackAtThisPos();
145 ~LexingFor_PragmaRAII() {
146 if (InMacroArgPreExpansion) {
148 PP.CommitBacktrackedTokens();
162 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
163 /// return the first token after the directive. The _Pragma token has just
164 /// been read into 'Tok'.
165 void Preprocessor::Handle_Pragma(Token &Tok) {
167 // This works differently if we are pre-expanding a macro argument.
168 // In that case we don't actually "activate" the pragma now, we only lex it
169 // until we are sure it is lexically correct and then we backtrack so that
170 // we activate the pragma whenever we encounter the tokens again in the token
171 // stream. This ensures that we will activate it in the correct location
172 // or that we will ignore it if it never enters the token stream, e.g:
175 // #define INACTIVE(x) EMPTY(x)
176 // INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\""))
178 LexingFor_PragmaRAII _PragmaLexing(*this, InMacroArgPreExpansion, Tok);
180 // Remember the pragma token location.
181 SourceLocation PragmaLoc = Tok.getLocation();
185 if (Tok.isNot(tok::l_paren)) {
186 Diag(PragmaLoc, diag::err__Pragma_malformed);
187 return _PragmaLexing.failed();
192 if (!tok::isStringLiteral(Tok.getKind())) {
193 Diag(PragmaLoc, diag::err__Pragma_malformed);
194 // Skip bad tokens, and the ')', if present.
195 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
197 while (Tok.isNot(tok::r_paren) &&
198 !Tok.isAtStartOfLine() &&
201 if (Tok.is(tok::r_paren))
203 return _PragmaLexing.failed();
206 if (Tok.hasUDSuffix()) {
207 Diag(Tok, diag::err_invalid_string_udl);
208 // Skip this token, and the ')', if present.
210 if (Tok.is(tok::r_paren))
212 return _PragmaLexing.failed();
215 // Remember the string.
220 if (Tok.isNot(tok::r_paren)) {
221 Diag(PragmaLoc, diag::err__Pragma_malformed);
222 return _PragmaLexing.failed();
225 if (InMacroArgPreExpansion)
228 SourceLocation RParenLoc = Tok.getLocation();
229 std::string StrVal = getSpelling(StrTok);
231 // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1:
232 // "The string literal is destringized by deleting any encoding prefix,
233 // deleting the leading and trailing double-quotes, replacing each escape
234 // sequence \" by a double-quote, and replacing each escape sequence \\ by a
235 // single backslash."
236 if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
237 (StrVal[0] == 'u' && StrVal[1] != '8'))
238 StrVal.erase(StrVal.begin());
239 else if (StrVal[0] == 'u')
240 StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
242 if (StrVal[0] == 'R') {
243 // FIXME: C++11 does not specify how to handle raw-string-literals here.
244 // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
245 assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
246 "Invalid raw string token!");
248 // Measure the length of the d-char-sequence.
249 unsigned NumDChars = 0;
250 while (StrVal[2 + NumDChars] != '(') {
251 assert(NumDChars < (StrVal.size() - 5) / 2 &&
252 "Invalid raw string token!");
255 assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
257 // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
259 StrVal.erase(0, 2 + NumDChars);
260 StrVal.erase(StrVal.size() - 1 - NumDChars);
262 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
263 "Invalid string token!");
265 // Remove escaped quotes and escapes.
266 unsigned ResultPos = 1;
267 for (unsigned i = 1, e = StrVal.size() - 1; i != e; ++i) {
268 // Skip escapes. \\ -> '\' and \" -> '"'.
269 if (StrVal[i] == '\\' && i + 1 < e &&
270 (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
272 StrVal[ResultPos++] = StrVal[i];
274 StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
277 // Remove the front quote, replacing it with a space, so that the pragma
278 // contents appear to have a space before them.
281 // Replace the terminating quote with a \n.
282 StrVal[StrVal.size()-1] = '\n';
284 // Plop the string (including the newline and trailing null) into a buffer
285 // where we can lex it.
288 CreateString(StrVal, TmpTok);
289 SourceLocation TokLoc = TmpTok.getLocation();
291 // Make and enter a lexer object so that we lex and expand the tokens just
293 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
294 StrVal.size(), *this);
296 EnterSourceFileWithLexer(TL, nullptr);
298 // With everything set up, lex this as a #pragma directive.
299 HandlePragmaDirective(PragmaLoc, PIK__Pragma);
301 // Finally, return whatever came after the pragma directive.
305 /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
306 /// is not enclosed within a string literal.
307 void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
308 // Remember the pragma token location.
309 SourceLocation PragmaLoc = Tok.getLocation();
313 if (Tok.isNot(tok::l_paren)) {
314 Diag(PragmaLoc, diag::err__Pragma_malformed);
318 // Get the tokens enclosed within the __pragma(), as well as the final ')'.
319 SmallVector<Token, 32> PragmaToks;
322 while (Tok.isNot(tok::eof)) {
323 PragmaToks.push_back(Tok);
324 if (Tok.is(tok::l_paren))
326 else if (Tok.is(tok::r_paren) && NumParens-- == 0)
331 if (Tok.is(tok::eof)) {
332 Diag(PragmaLoc, diag::err_unterminated___pragma);
336 PragmaToks.front().setFlag(Token::LeadingSpace);
338 // Replace the ')' with an EOD to mark the end of the pragma.
339 PragmaToks.back().setKind(tok::eod);
341 Token *TokArray = new Token[PragmaToks.size()];
342 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
344 // Push the tokens onto the stack.
345 EnterTokenStream(TokArray, PragmaToks.size(), true, true);
347 // With everything set up, lex this as a #pragma directive.
348 HandlePragmaDirective(PragmaLoc, PIK___pragma);
350 // Finally, return whatever came after the pragma directive.
354 /// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
356 void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
357 if (isInPrimaryFile()) {
358 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
362 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
363 // Mark the file as a once-only file now.
364 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
367 void Preprocessor::HandlePragmaMark() {
368 assert(CurPPLexer && "No current lexer?");
370 CurLexer->ReadToEndOfLine();
372 CurPTHLexer->DiscardToEndOfLine();
376 /// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
378 void Preprocessor::HandlePragmaPoison(Token &PoisonTok) {
382 // Read the next token to poison. While doing this, pretend that we are
383 // skipping while reading the identifier to poison.
384 // This avoids errors on code like:
385 // #pragma GCC poison X
386 // #pragma GCC poison X
387 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
388 LexUnexpandedToken(Tok);
389 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
391 // If we reached the end of line, we're done.
392 if (Tok.is(tok::eod)) return;
394 // Can only poison identifiers.
395 if (Tok.isNot(tok::raw_identifier)) {
396 Diag(Tok, diag::err_pp_invalid_poison);
400 // Look up the identifier info for the token. We disabled identifier lookup
401 // by saying we're skipping contents, so we need to do this manually.
402 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
405 if (II->isPoisoned()) continue;
407 // If this is a macro identifier, emit a warning.
408 if (isMacroDefined(II))
409 Diag(Tok, diag::pp_poisoning_existing_macro);
411 // Finally, poison it!
414 II->setChangedSinceDeserialization();
418 /// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
419 /// that the whole directive has been parsed.
420 void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
421 if (isInPrimaryFile()) {
422 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
426 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
427 PreprocessorLexer *TheLexer = getCurrentFileLexer();
429 // Mark the file as a system header.
430 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
433 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
434 if (PLoc.isInvalid())
437 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
439 // Notify the client, if desired, that we are in a new source file.
441 Callbacks->FileChanged(SysHeaderTok.getLocation(),
442 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
444 // Emit a line marker. This will change any source locations from this point
445 // forward to realize they are in a system header.
446 // Create a line note with this information.
447 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine()+1,
448 FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
449 /*IsSystem=*/true, /*IsExternC=*/false);
452 /// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
454 void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
456 CurPPLexer->LexIncludeFilename(FilenameTok);
458 // If the token kind is EOD, the error has already been diagnosed.
459 if (FilenameTok.is(tok::eod))
462 // Reserve a buffer to get the spelling.
463 SmallString<128> FilenameBuffer;
464 bool Invalid = false;
465 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
470 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
471 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
473 if (Filename.empty())
476 // Search include directories for this file.
477 const DirectoryLookup *CurDir;
478 const FileEntry *File =
479 LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
480 nullptr, CurDir, nullptr, nullptr, nullptr);
482 if (!SuppressIncludeNotFoundError)
483 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
487 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
489 // If this file is older than the file it depends on, emit a diagnostic.
490 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
491 // Lex tokens at the end of the message and include them in the message.
494 while (DependencyTok.isNot(tok::eod)) {
495 Message += getSpelling(DependencyTok) + " ";
499 // Remove the trailing ' ' if present.
500 if (!Message.empty())
501 Message.erase(Message.end()-1);
502 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
506 /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
507 /// Return the IdentifierInfo* associated with the macro to push or pop.
508 IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
509 // Remember the pragma token location.
510 Token PragmaTok = Tok;
514 if (Tok.isNot(tok::l_paren)) {
515 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
516 << getSpelling(PragmaTok);
520 // Read the macro name string.
522 if (Tok.isNot(tok::string_literal)) {
523 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
524 << getSpelling(PragmaTok);
528 if (Tok.hasUDSuffix()) {
529 Diag(Tok, diag::err_invalid_string_udl);
533 // Remember the macro string.
534 std::string StrVal = getSpelling(Tok);
538 if (Tok.isNot(tok::r_paren)) {
539 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
540 << getSpelling(PragmaTok);
544 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
545 "Invalid string token!");
547 // Create a Token from the string.
549 MacroTok.startToken();
550 MacroTok.setKind(tok::raw_identifier);
551 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
553 // Get the IdentifierInfo of MacroToPushTok.
554 return LookUpIdentifierInfo(MacroTok);
557 /// \brief Handle \#pragma push_macro.
561 /// #pragma push_macro("macro")
563 void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
564 // Parse the pragma directive and get the macro IdentifierInfo*.
565 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
566 if (!IdentInfo) return;
568 // Get the MacroInfo associated with IdentInfo.
569 MacroInfo *MI = getMacroInfo(IdentInfo);
572 // Allow the original MacroInfo to be redefined later.
573 MI->setIsAllowRedefinitionsWithoutWarning(true);
576 // Push the cloned MacroInfo so we can retrieve it later.
577 PragmaPushMacroInfo[IdentInfo].push_back(MI);
580 /// \brief Handle \#pragma pop_macro.
584 /// #pragma pop_macro("macro")
586 void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
587 SourceLocation MessageLoc = PopMacroTok.getLocation();
589 // Parse the pragma directive and get the macro IdentifierInfo*.
590 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
591 if (!IdentInfo) return;
593 // Find the vector<MacroInfo*> associated with the macro.
594 llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
595 PragmaPushMacroInfo.find(IdentInfo);
596 if (iter != PragmaPushMacroInfo.end()) {
597 // Forget the MacroInfo currently associated with IdentInfo.
598 if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
599 if (MI->isWarnIfUnused())
600 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
601 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
604 // Get the MacroInfo we want to reinstall.
605 MacroInfo *MacroToReInstall = iter->second.back();
607 if (MacroToReInstall)
608 // Reinstall the previously pushed macro.
609 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
611 // Pop PragmaPushMacroInfo stack.
612 iter->second.pop_back();
613 if (iter->second.size() == 0)
614 PragmaPushMacroInfo.erase(iter);
616 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
617 << IdentInfo->getName();
621 void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
622 // We will either get a quoted filename or a bracketed filename, and we
623 // have to track which we got. The first filename is the source name,
624 // and the second name is the mapped filename. If the first is quoted,
625 // the second must be as well (cannot mix and match quotes and brackets).
627 // Get the open paren
629 if (Tok.isNot(tok::l_paren)) {
630 Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
634 // We expect either a quoted string literal, or a bracketed name
635 Token SourceFilenameTok;
636 CurPPLexer->LexIncludeFilename(SourceFilenameTok);
637 if (SourceFilenameTok.is(tok::eod)) {
638 // The diagnostic has already been handled
642 StringRef SourceFileName;
643 SmallString<128> FileNameBuffer;
644 if (SourceFilenameTok.is(tok::string_literal) ||
645 SourceFilenameTok.is(tok::angle_string_literal)) {
646 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
647 } else if (SourceFilenameTok.is(tok::less)) {
648 // This could be a path instead of just a name
649 FileNameBuffer.push_back('<');
651 if (ConcatenateIncludeName(FileNameBuffer, End))
652 return; // Diagnostic already emitted
653 SourceFileName = FileNameBuffer;
655 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
658 FileNameBuffer.clear();
660 // Now we expect a comma, followed by another include name
662 if (Tok.isNot(tok::comma)) {
663 Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
667 Token ReplaceFilenameTok;
668 CurPPLexer->LexIncludeFilename(ReplaceFilenameTok);
669 if (ReplaceFilenameTok.is(tok::eod)) {
670 // The diagnostic has already been handled
674 StringRef ReplaceFileName;
675 if (ReplaceFilenameTok.is(tok::string_literal) ||
676 ReplaceFilenameTok.is(tok::angle_string_literal)) {
677 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
678 } else if (ReplaceFilenameTok.is(tok::less)) {
679 // This could be a path instead of just a name
680 FileNameBuffer.push_back('<');
682 if (ConcatenateIncludeName(FileNameBuffer, End))
683 return; // Diagnostic already emitted
684 ReplaceFileName = FileNameBuffer;
686 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
690 // Finally, we expect the closing paren
692 if (Tok.isNot(tok::r_paren)) {
693 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
697 // Now that we have the source and target filenames, we need to make sure
698 // they're both of the same type (angled vs non-angled)
699 StringRef OriginalSource = SourceFileName;
701 bool SourceIsAngled =
702 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
704 bool ReplaceIsAngled =
705 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
707 if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
708 (SourceIsAngled != ReplaceIsAngled)) {
711 DiagID = diag::warn_pragma_include_alias_mismatch_angle;
713 DiagID = diag::warn_pragma_include_alias_mismatch_quote;
715 Diag(SourceFilenameTok.getLocation(), DiagID)
722 // Now we can let the include handler know about this mapping
723 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
726 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
727 /// If 'Namespace' is non-null, then it is a token required to exist on the
728 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
729 void Preprocessor::AddPragmaHandler(StringRef Namespace,
730 PragmaHandler *Handler) {
731 PragmaNamespace *InsertNS = PragmaHandlers.get();
733 // If this is specified to be in a namespace, step down into it.
734 if (!Namespace.empty()) {
735 // If there is already a pragma handler with the name of this namespace,
736 // we either have an error (directive with the same name as a namespace) or
737 // we already have the namespace to insert into.
738 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
739 InsertNS = Existing->getIfNamespace();
740 assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
741 " handler with the same name!");
743 // Otherwise, this namespace doesn't exist yet, create and insert the
745 InsertNS = new PragmaNamespace(Namespace);
746 PragmaHandlers->AddPragma(InsertNS);
750 // Check to make sure we don't already have a pragma for this identifier.
751 assert(!InsertNS->FindHandler(Handler->getName()) &&
752 "Pragma handler already exists for this identifier!");
753 InsertNS->AddPragma(Handler);
756 /// RemovePragmaHandler - Remove the specific pragma handler from the
757 /// preprocessor. If \arg Namespace is non-null, then it should be the
758 /// namespace that \arg Handler was added to. It is an error to remove
759 /// a handler that has not been registered.
760 void Preprocessor::RemovePragmaHandler(StringRef Namespace,
761 PragmaHandler *Handler) {
762 PragmaNamespace *NS = PragmaHandlers.get();
764 // If this is specified to be in a namespace, step down into it.
765 if (!Namespace.empty()) {
766 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
767 assert(Existing && "Namespace containing handler does not exist!");
769 NS = Existing->getIfNamespace();
770 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
773 NS->RemovePragmaHandler(Handler);
775 // If this is a non-default namespace and it is now empty, remove it.
776 if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
777 PragmaHandlers->RemovePragmaHandler(NS);
782 bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
784 LexUnexpandedToken(Tok);
786 if (Tok.isNot(tok::identifier)) {
787 Diag(Tok, diag::ext_on_off_switch_syntax);
790 IdentifierInfo *II = Tok.getIdentifierInfo();
792 Result = tok::OOS_ON;
793 else if (II->isStr("OFF"))
794 Result = tok::OOS_OFF;
795 else if (II->isStr("DEFAULT"))
796 Result = tok::OOS_DEFAULT;
798 Diag(Tok, diag::ext_on_off_switch_syntax);
802 // Verify that this is followed by EOD.
803 LexUnexpandedToken(Tok);
804 if (Tok.isNot(tok::eod))
805 Diag(Tok, diag::ext_pragma_syntax_eod);
810 /// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
811 struct PragmaOnceHandler : public PragmaHandler {
812 PragmaOnceHandler() : PragmaHandler("once") {}
813 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
814 Token &OnceTok) override {
815 PP.CheckEndOfDirective("pragma once");
816 PP.HandlePragmaOnce(OnceTok);
820 /// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
821 /// rest of the line is not lexed.
822 struct PragmaMarkHandler : public PragmaHandler {
823 PragmaMarkHandler() : PragmaHandler("mark") {}
824 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
825 Token &MarkTok) override {
826 PP.HandlePragmaMark();
830 /// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
831 struct PragmaPoisonHandler : public PragmaHandler {
832 PragmaPoisonHandler() : PragmaHandler("poison") {}
833 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
834 Token &PoisonTok) override {
835 PP.HandlePragmaPoison(PoisonTok);
839 /// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
840 /// as a system header, which silences warnings in it.
841 struct PragmaSystemHeaderHandler : public PragmaHandler {
842 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
843 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
844 Token &SHToken) override {
845 PP.HandlePragmaSystemHeader(SHToken);
846 PP.CheckEndOfDirective("pragma");
849 struct PragmaDependencyHandler : public PragmaHandler {
850 PragmaDependencyHandler() : PragmaHandler("dependency") {}
851 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
852 Token &DepToken) override {
853 PP.HandlePragmaDependency(DepToken);
857 struct PragmaDebugHandler : public PragmaHandler {
858 PragmaDebugHandler() : PragmaHandler("__debug") {}
859 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
860 Token &DepToken) override {
862 PP.LexUnexpandedToken(Tok);
863 if (Tok.isNot(tok::identifier)) {
864 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
867 IdentifierInfo *II = Tok.getIdentifierInfo();
869 if (II->isStr("assert")) {
870 llvm_unreachable("This is an assertion!");
871 } else if (II->isStr("crash")) {
873 } else if (II->isStr("parser_crash")) {
875 Crasher.startToken();
876 Crasher.setKind(tok::annot_pragma_parser_crash);
877 Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
878 PP.EnterToken(Crasher);
879 } else if (II->isStr("dump")) {
881 PP.LexUnexpandedToken(Identifier);
882 if (auto *DumpII = Identifier.getIdentifierInfo()) {
884 DumpAnnot.startToken();
885 DumpAnnot.setKind(tok::annot_pragma_dump);
886 DumpAnnot.setAnnotationRange(
887 SourceRange(Tok.getLocation(), Identifier.getLocation()));
888 DumpAnnot.setAnnotationValue(DumpII);
889 PP.DiscardUntilEndOfDirective();
890 PP.EnterToken(DumpAnnot);
892 PP.Diag(Identifier, diag::warn_pragma_debug_missing_argument)
895 } else if (II->isStr("llvm_fatal_error")) {
896 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
897 } else if (II->isStr("llvm_unreachable")) {
898 llvm_unreachable("#pragma clang __debug llvm_unreachable");
899 } else if (II->isStr("macro")) {
901 PP.LexUnexpandedToken(MacroName);
902 auto *MacroII = MacroName.getIdentifierInfo();
904 PP.dumpMacroInfo(MacroII);
906 PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument)
908 } else if (II->isStr("overflow_stack")) {
909 DebugOverflowStack();
910 } else if (II->isStr("handle_crash")) {
911 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
914 } else if (II->isStr("captured")) {
917 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
921 PPCallbacks *Callbacks = PP.getPPCallbacks();
923 Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
926 void HandleCaptured(Preprocessor &PP) {
927 // Skip if emitting preprocessed output.
928 if (PP.isPreprocessedOutput())
932 PP.LexUnexpandedToken(Tok);
934 if (Tok.isNot(tok::eod)) {
935 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
936 << "pragma clang __debug captured";
940 SourceLocation NameLoc = Tok.getLocation();
941 MutableArrayRef<Token> Toks(
942 PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
943 Toks[0].startToken();
944 Toks[0].setKind(tok::annot_pragma_captured);
945 Toks[0].setLocation(NameLoc);
947 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
950 // Disable MSVC warning about runtime stack overflow.
952 #pragma warning(disable : 4717)
954 static void DebugOverflowStack() {
955 void (*volatile Self)() = DebugOverflowStack;
959 #pragma warning(default : 4717)
964 /// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
965 struct PragmaDiagnosticHandler : public PragmaHandler {
967 const char *Namespace;
969 explicit PragmaDiagnosticHandler(const char *NS) :
970 PragmaHandler("diagnostic"), Namespace(NS) {}
971 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
972 Token &DiagToken) override {
973 SourceLocation DiagLoc = DiagToken.getLocation();
975 PP.LexUnexpandedToken(Tok);
976 if (Tok.isNot(tok::identifier)) {
977 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
980 IdentifierInfo *II = Tok.getIdentifierInfo();
981 PPCallbacks *Callbacks = PP.getPPCallbacks();
983 if (II->isStr("pop")) {
984 if (!PP.getDiagnostics().popMappings(DiagLoc))
985 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
987 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
989 } else if (II->isStr("push")) {
990 PP.getDiagnostics().pushMappings(DiagLoc);
992 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
996 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
997 .Case("ignored", diag::Severity::Ignored)
998 .Case("warning", diag::Severity::Warning)
999 .Case("error", diag::Severity::Error)
1000 .Case("fatal", diag::Severity::Fatal)
1001 .Default(diag::Severity());
1003 if (SV == diag::Severity()) {
1004 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1008 PP.LexUnexpandedToken(Tok);
1009 SourceLocation StringLoc = Tok.getLocation();
1011 std::string WarningName;
1012 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
1013 /*MacroExpansion=*/false))
1016 if (Tok.isNot(tok::eod)) {
1017 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1021 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1022 (WarningName[1] != 'W' && WarningName[1] != 'R')) {
1023 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
1027 diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1028 : diag::Flavor::Remark;
1029 StringRef Group = StringRef(WarningName).substr(2);
1030 bool unknownDiag = false;
1031 if (Group == "everything") {
1032 // Special handling for pragma clang diagnostic ... "-Weverything".
1033 // There is no formal group named "everything", so there has to be a
1034 // special case for it.
1035 PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc);
1037 unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV,
1040 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1043 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
1047 /// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1048 /// diagnostics, so we don't really implement this pragma. We parse it and
1049 /// ignore it to avoid -Wunknown-pragma warnings.
1050 struct PragmaWarningHandler : public PragmaHandler {
1051 PragmaWarningHandler() : PragmaHandler("warning") {}
1053 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1054 Token &Tok) override {
1055 // Parse things like:
1058 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
1059 SourceLocation DiagLoc = Tok.getLocation();
1060 PPCallbacks *Callbacks = PP.getPPCallbacks();
1063 if (Tok.isNot(tok::l_paren)) {
1064 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1069 IdentifierInfo *II = Tok.getIdentifierInfo();
1071 if (II && II->isStr("push")) {
1072 // #pragma warning( push[ ,n ] )
1075 if (Tok.is(tok::comma)) {
1078 if (Tok.is(tok::numeric_constant) &&
1079 PP.parseSimpleIntegerLiteral(Tok, Value))
1081 if (Level < 0 || Level > 4) {
1082 PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1087 Callbacks->PragmaWarningPush(DiagLoc, Level);
1088 } else if (II && II->isStr("pop")) {
1089 // #pragma warning( pop )
1092 Callbacks->PragmaWarningPop(DiagLoc);
1094 // #pragma warning( warning-specifier : warning-number-list
1095 // [; warning-specifier : warning-number-list...] )
1097 II = Tok.getIdentifierInfo();
1098 if (!II && !Tok.is(tok::numeric_constant)) {
1099 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1103 // Figure out which warning specifier this is.
1104 bool SpecifierValid;
1105 StringRef Specifier;
1106 llvm::SmallString<1> SpecifierBuf;
1108 Specifier = II->getName();
1109 SpecifierValid = llvm::StringSwitch<bool>(Specifier)
1110 .Cases("default", "disable", "error", "once",
1113 // If we read a correct specifier, snatch next token (that should be
1114 // ":", checked later).
1118 // Token is a numeric constant. It should be either 1, 2, 3 or 4.
1120 Specifier = PP.getSpelling(Tok, SpecifierBuf);
1121 if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
1122 SpecifierValid = (Value >= 1) && (Value <= 4);
1124 SpecifierValid = false;
1125 // Next token already snatched by parseSimpleIntegerLiteral.
1128 if (!SpecifierValid) {
1129 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1132 if (Tok.isNot(tok::colon)) {
1133 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1137 // Collect the warning ids.
1138 SmallVector<int, 4> Ids;
1140 while (Tok.is(tok::numeric_constant)) {
1142 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
1144 PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1147 Ids.push_back(int(Value));
1150 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1152 // Parse the next specifier if there is a semicolon.
1153 if (Tok.isNot(tok::semi))
1159 if (Tok.isNot(tok::r_paren)) {
1160 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1165 if (Tok.isNot(tok::eod))
1166 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1170 /// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
1171 struct PragmaIncludeAliasHandler : public PragmaHandler {
1172 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
1173 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1174 Token &IncludeAliasTok) override {
1175 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
1179 /// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1180 /// extension. The syntax is:
1182 /// #pragma message(string)
1184 /// OR, in GCC mode:
1186 /// #pragma message string
1188 /// string is a string, which is fully macro expanded, and permits string
1189 /// concatenation, embedded escape characters, etc... See MSDN for more details.
1190 /// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1191 /// form as \#pragma message.
1192 struct PragmaMessageHandler : public PragmaHandler {
1194 const PPCallbacks::PragmaMessageKind Kind;
1195 const StringRef Namespace;
1197 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1198 bool PragmaNameOnly = false) {
1200 case PPCallbacks::PMK_Message:
1201 return PragmaNameOnly ? "message" : "pragma message";
1202 case PPCallbacks::PMK_Warning:
1203 return PragmaNameOnly ? "warning" : "pragma warning";
1204 case PPCallbacks::PMK_Error:
1205 return PragmaNameOnly ? "error" : "pragma error";
1207 llvm_unreachable("Unknown PragmaMessageKind!");
1211 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1212 StringRef Namespace = StringRef())
1213 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), Namespace(Namespace) {}
1215 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1216 Token &Tok) override {
1217 SourceLocation MessageLoc = Tok.getLocation();
1219 bool ExpectClosingParen = false;
1220 switch (Tok.getKind()) {
1222 // We have a MSVC style pragma message.
1223 ExpectClosingParen = true;
1227 case tok::string_literal:
1228 // We have a GCC style pragma message, and we just read the string.
1231 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1235 std::string MessageString;
1236 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1237 /*MacroExpansion=*/true))
1240 if (ExpectClosingParen) {
1241 if (Tok.isNot(tok::r_paren)) {
1242 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1245 PP.Lex(Tok); // eat the r_paren.
1248 if (Tok.isNot(tok::eod)) {
1249 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1253 // Output the message.
1254 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1255 ? diag::err_pragma_message
1256 : diag::warn_pragma_message) << MessageString;
1258 // If the pragma is lexically sound, notify any interested PPCallbacks.
1259 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1260 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
1264 /// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
1265 /// macro on the top of the stack.
1266 struct PragmaPushMacroHandler : public PragmaHandler {
1267 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
1268 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1269 Token &PushMacroTok) override {
1270 PP.HandlePragmaPushMacro(PushMacroTok);
1275 /// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
1276 /// macro to the value on the top of the stack.
1277 struct PragmaPopMacroHandler : public PragmaHandler {
1278 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
1279 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1280 Token &PopMacroTok) override {
1281 PP.HandlePragmaPopMacro(PopMacroTok);
1285 // Pragma STDC implementations.
1287 /// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
1288 struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
1289 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
1290 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1291 Token &Tok) override {
1292 tok::OnOffSwitch OOS;
1293 if (PP.LexOnOffSwitch(OOS))
1295 if (OOS == tok::OOS_ON)
1296 PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
1300 /// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
1301 struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
1302 PragmaSTDC_CX_LIMITED_RANGEHandler()
1303 : PragmaHandler("CX_LIMITED_RANGE") {}
1304 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1305 Token &Tok) override {
1306 tok::OnOffSwitch OOS;
1307 PP.LexOnOffSwitch(OOS);
1311 /// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
1312 struct PragmaSTDC_UnknownHandler : public PragmaHandler {
1313 PragmaSTDC_UnknownHandler() {}
1314 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1315 Token &UnknownTok) override {
1316 // C99 6.10.6p2, unknown forms are not allowed.
1317 PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
1321 /// PragmaARCCFCodeAuditedHandler -
1322 /// \#pragma clang arc_cf_code_audited begin/end
1323 struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1324 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
1325 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1326 Token &NameTok) override {
1327 SourceLocation Loc = NameTok.getLocation();
1332 // Lex the 'begin' or 'end'.
1333 PP.LexUnexpandedToken(Tok);
1334 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1335 if (BeginEnd && BeginEnd->isStr("begin")) {
1337 } else if (BeginEnd && BeginEnd->isStr("end")) {
1340 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1344 // Verify that this is followed by EOD.
1345 PP.LexUnexpandedToken(Tok);
1346 if (Tok.isNot(tok::eod))
1347 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1349 // The start location of the active audit.
1350 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1352 // The start location we want after processing this.
1353 SourceLocation NewLoc;
1356 // Complain about attempts to re-enter an audit.
1357 if (BeginLoc.isValid()) {
1358 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1359 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1363 // Complain about attempts to leave an audit that doesn't exist.
1364 if (!BeginLoc.isValid()) {
1365 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1368 NewLoc = SourceLocation();
1371 PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1375 /// PragmaAssumeNonNullHandler -
1376 /// \#pragma clang assume_nonnull begin/end
1377 struct PragmaAssumeNonNullHandler : public PragmaHandler {
1378 PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
1379 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1380 Token &NameTok) override {
1381 SourceLocation Loc = NameTok.getLocation();
1386 // Lex the 'begin' or 'end'.
1387 PP.LexUnexpandedToken(Tok);
1388 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1389 if (BeginEnd && BeginEnd->isStr("begin")) {
1391 } else if (BeginEnd && BeginEnd->isStr("end")) {
1394 PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
1398 // Verify that this is followed by EOD.
1399 PP.LexUnexpandedToken(Tok);
1400 if (Tok.isNot(tok::eod))
1401 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1403 // The start location of the active audit.
1404 SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
1406 // The start location we want after processing this.
1407 SourceLocation NewLoc;
1410 // Complain about attempts to re-enter an audit.
1411 if (BeginLoc.isValid()) {
1412 PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
1413 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1417 // Complain about attempts to leave an audit that doesn't exist.
1418 if (!BeginLoc.isValid()) {
1419 PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
1422 NewLoc = SourceLocation();
1425 PP.setPragmaAssumeNonNullLoc(NewLoc);
1429 /// \brief Handle "\#pragma region [...]"
1433 /// #pragma region [optional name]
1434 /// #pragma endregion [optional comment]
1438 /// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1439 /// pragma, just skipped by compiler.
1440 struct PragmaRegionHandler : public PragmaHandler {
1441 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) { }
1443 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1444 Token &NameTok) override {
1445 // #pragma region: endregion matches can be verified
1446 // __pragma(region): no sense, but ignored by msvc
1447 // _Pragma is not valid for MSVC, but there isn't any point
1448 // to handle a _Pragma differently.
1452 } // end anonymous namespace
1455 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
1456 /// \#pragma GCC poison/system_header/dependency and \#pragma once.
1457 void Preprocessor::RegisterBuiltinPragmas() {
1458 AddPragmaHandler(new PragmaOnceHandler());
1459 AddPragmaHandler(new PragmaMarkHandler());
1460 AddPragmaHandler(new PragmaPushMacroHandler());
1461 AddPragmaHandler(new PragmaPopMacroHandler());
1462 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
1465 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1466 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1467 AddPragmaHandler("GCC", new PragmaDependencyHandler());
1468 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
1469 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1471 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1473 // #pragma clang ...
1474 AddPragmaHandler("clang", new PragmaPoisonHandler());
1475 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
1476 AddPragmaHandler("clang", new PragmaDebugHandler());
1477 AddPragmaHandler("clang", new PragmaDependencyHandler());
1478 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
1479 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
1480 AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
1482 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1483 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
1484 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
1487 if (LangOpts.MicrosoftExt) {
1488 AddPragmaHandler(new PragmaWarningHandler());
1489 AddPragmaHandler(new PragmaIncludeAliasHandler());
1490 AddPragmaHandler(new PragmaRegionHandler("region"));
1491 AddPragmaHandler(new PragmaRegionHandler("endregion"));
1494 // Pragmas added by plugins
1495 for (PragmaHandlerRegistry::iterator it = PragmaHandlerRegistry::begin(),
1496 ie = PragmaHandlerRegistry::end();
1498 AddPragmaHandler(it->instantiate().release());
1502 /// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
1503 /// warn about those pragmas being unknown.
1504 void Preprocessor::IgnorePragmas() {
1505 AddPragmaHandler(new EmptyPragmaHandler());
1506 // Also ignore all pragmas in all namespaces created
1507 // in Preprocessor::RegisterBuiltinPragmas().
1508 AddPragmaHandler("GCC", new EmptyPragmaHandler());
1509 AddPragmaHandler("clang", new EmptyPragmaHandler());
1510 if (PragmaHandler *NS = PragmaHandlers->FindHandler("STDC")) {
1511 // Preprocessor::RegisterBuiltinPragmas() already registers
1512 // PragmaSTDC_UnknownHandler as the empty handler, so remove it first,
1513 // otherwise there will be an assert about a duplicate handler.
1514 PragmaNamespace *STDCNamespace = NS->getIfNamespace();
1515 assert(STDCNamespace &&
1516 "Invalid namespace, registered as a regular pragma handler!");
1517 if (PragmaHandler *Existing = STDCNamespace->FindHandler("", false)) {
1518 RemovePragmaHandler("STDC", Existing);
1522 AddPragmaHandler("STDC", new EmptyPragmaHandler());