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 // Don't honor the 'once' when handling the primary source file, unless
358 // this is a prefix to a TU, which indicates we're generating a PCH file.
359 if (isInPrimaryFile() && TUKind != TU_Prefix) {
360 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
364 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
365 // Mark the file as a once-only file now.
366 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
369 void Preprocessor::HandlePragmaMark() {
370 assert(CurPPLexer && "No current lexer?");
372 CurLexer->ReadToEndOfLine();
374 CurPTHLexer->DiscardToEndOfLine();
378 /// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
380 void Preprocessor::HandlePragmaPoison(Token &PoisonTok) {
384 // Read the next token to poison. While doing this, pretend that we are
385 // skipping while reading the identifier to poison.
386 // This avoids errors on code like:
387 // #pragma GCC poison X
388 // #pragma GCC poison X
389 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
390 LexUnexpandedToken(Tok);
391 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
393 // If we reached the end of line, we're done.
394 if (Tok.is(tok::eod)) return;
396 // Can only poison identifiers.
397 if (Tok.isNot(tok::raw_identifier)) {
398 Diag(Tok, diag::err_pp_invalid_poison);
402 // Look up the identifier info for the token. We disabled identifier lookup
403 // by saying we're skipping contents, so we need to do this manually.
404 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
407 if (II->isPoisoned()) continue;
409 // If this is a macro identifier, emit a warning.
410 if (isMacroDefined(II))
411 Diag(Tok, diag::pp_poisoning_existing_macro);
413 // Finally, poison it!
416 II->setChangedSinceDeserialization();
420 /// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
421 /// that the whole directive has been parsed.
422 void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
423 if (isInPrimaryFile()) {
424 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
428 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
429 PreprocessorLexer *TheLexer = getCurrentFileLexer();
431 // Mark the file as a system header.
432 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
435 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
436 if (PLoc.isInvalid())
439 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
441 // Notify the client, if desired, that we are in a new source file.
443 Callbacks->FileChanged(SysHeaderTok.getLocation(),
444 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
446 // Emit a line marker. This will change any source locations from this point
447 // forward to realize they are in a system header.
448 // Create a line note with this information.
449 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine()+1,
450 FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
451 /*IsSystem=*/true, /*IsExternC=*/false);
454 /// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
456 void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
458 CurPPLexer->LexIncludeFilename(FilenameTok);
460 // If the token kind is EOD, the error has already been diagnosed.
461 if (FilenameTok.is(tok::eod))
464 // Reserve a buffer to get the spelling.
465 SmallString<128> FilenameBuffer;
466 bool Invalid = false;
467 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
472 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
473 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
475 if (Filename.empty())
478 // Search include directories for this file.
479 const DirectoryLookup *CurDir;
480 const FileEntry *File =
481 LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
482 nullptr, CurDir, nullptr, nullptr, nullptr);
484 if (!SuppressIncludeNotFoundError)
485 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
489 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
491 // If this file is older than the file it depends on, emit a diagnostic.
492 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
493 // Lex tokens at the end of the message and include them in the message.
496 while (DependencyTok.isNot(tok::eod)) {
497 Message += getSpelling(DependencyTok) + " ";
501 // Remove the trailing ' ' if present.
502 if (!Message.empty())
503 Message.erase(Message.end()-1);
504 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
508 /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
509 /// Return the IdentifierInfo* associated with the macro to push or pop.
510 IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
511 // Remember the pragma token location.
512 Token PragmaTok = Tok;
516 if (Tok.isNot(tok::l_paren)) {
517 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
518 << getSpelling(PragmaTok);
522 // Read the macro name string.
524 if (Tok.isNot(tok::string_literal)) {
525 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
526 << getSpelling(PragmaTok);
530 if (Tok.hasUDSuffix()) {
531 Diag(Tok, diag::err_invalid_string_udl);
535 // Remember the macro string.
536 std::string StrVal = getSpelling(Tok);
540 if (Tok.isNot(tok::r_paren)) {
541 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
542 << getSpelling(PragmaTok);
546 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
547 "Invalid string token!");
549 // Create a Token from the string.
551 MacroTok.startToken();
552 MacroTok.setKind(tok::raw_identifier);
553 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
555 // Get the IdentifierInfo of MacroToPushTok.
556 return LookUpIdentifierInfo(MacroTok);
559 /// \brief Handle \#pragma push_macro.
563 /// #pragma push_macro("macro")
565 void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
566 // Parse the pragma directive and get the macro IdentifierInfo*.
567 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
568 if (!IdentInfo) return;
570 // Get the MacroInfo associated with IdentInfo.
571 MacroInfo *MI = getMacroInfo(IdentInfo);
574 // Allow the original MacroInfo to be redefined later.
575 MI->setIsAllowRedefinitionsWithoutWarning(true);
578 // Push the cloned MacroInfo so we can retrieve it later.
579 PragmaPushMacroInfo[IdentInfo].push_back(MI);
582 /// \brief Handle \#pragma pop_macro.
586 /// #pragma pop_macro("macro")
588 void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
589 SourceLocation MessageLoc = PopMacroTok.getLocation();
591 // Parse the pragma directive and get the macro IdentifierInfo*.
592 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
593 if (!IdentInfo) return;
595 // Find the vector<MacroInfo*> associated with the macro.
596 llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
597 PragmaPushMacroInfo.find(IdentInfo);
598 if (iter != PragmaPushMacroInfo.end()) {
599 // Forget the MacroInfo currently associated with IdentInfo.
600 if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
601 if (MI->isWarnIfUnused())
602 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
603 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
606 // Get the MacroInfo we want to reinstall.
607 MacroInfo *MacroToReInstall = iter->second.back();
609 if (MacroToReInstall)
610 // Reinstall the previously pushed macro.
611 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
613 // Pop PragmaPushMacroInfo stack.
614 iter->second.pop_back();
615 if (iter->second.size() == 0)
616 PragmaPushMacroInfo.erase(iter);
618 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
619 << IdentInfo->getName();
623 void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
624 // We will either get a quoted filename or a bracketed filename, and we
625 // have to track which we got. The first filename is the source name,
626 // and the second name is the mapped filename. If the first is quoted,
627 // the second must be as well (cannot mix and match quotes and brackets).
629 // Get the open paren
631 if (Tok.isNot(tok::l_paren)) {
632 Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
636 // We expect either a quoted string literal, or a bracketed name
637 Token SourceFilenameTok;
638 CurPPLexer->LexIncludeFilename(SourceFilenameTok);
639 if (SourceFilenameTok.is(tok::eod)) {
640 // The diagnostic has already been handled
644 StringRef SourceFileName;
645 SmallString<128> FileNameBuffer;
646 if (SourceFilenameTok.is(tok::string_literal) ||
647 SourceFilenameTok.is(tok::angle_string_literal)) {
648 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
649 } else if (SourceFilenameTok.is(tok::less)) {
650 // This could be a path instead of just a name
651 FileNameBuffer.push_back('<');
653 if (ConcatenateIncludeName(FileNameBuffer, End))
654 return; // Diagnostic already emitted
655 SourceFileName = FileNameBuffer;
657 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
660 FileNameBuffer.clear();
662 // Now we expect a comma, followed by another include name
664 if (Tok.isNot(tok::comma)) {
665 Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
669 Token ReplaceFilenameTok;
670 CurPPLexer->LexIncludeFilename(ReplaceFilenameTok);
671 if (ReplaceFilenameTok.is(tok::eod)) {
672 // The diagnostic has already been handled
676 StringRef ReplaceFileName;
677 if (ReplaceFilenameTok.is(tok::string_literal) ||
678 ReplaceFilenameTok.is(tok::angle_string_literal)) {
679 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
680 } else if (ReplaceFilenameTok.is(tok::less)) {
681 // This could be a path instead of just a name
682 FileNameBuffer.push_back('<');
684 if (ConcatenateIncludeName(FileNameBuffer, End))
685 return; // Diagnostic already emitted
686 ReplaceFileName = FileNameBuffer;
688 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
692 // Finally, we expect the closing paren
694 if (Tok.isNot(tok::r_paren)) {
695 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
699 // Now that we have the source and target filenames, we need to make sure
700 // they're both of the same type (angled vs non-angled)
701 StringRef OriginalSource = SourceFileName;
703 bool SourceIsAngled =
704 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
706 bool ReplaceIsAngled =
707 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
709 if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
710 (SourceIsAngled != ReplaceIsAngled)) {
713 DiagID = diag::warn_pragma_include_alias_mismatch_angle;
715 DiagID = diag::warn_pragma_include_alias_mismatch_quote;
717 Diag(SourceFilenameTok.getLocation(), DiagID)
724 // Now we can let the include handler know about this mapping
725 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
728 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
729 /// If 'Namespace' is non-null, then it is a token required to exist on the
730 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
731 void Preprocessor::AddPragmaHandler(StringRef Namespace,
732 PragmaHandler *Handler) {
733 PragmaNamespace *InsertNS = PragmaHandlers.get();
735 // If this is specified to be in a namespace, step down into it.
736 if (!Namespace.empty()) {
737 // If there is already a pragma handler with the name of this namespace,
738 // we either have an error (directive with the same name as a namespace) or
739 // we already have the namespace to insert into.
740 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
741 InsertNS = Existing->getIfNamespace();
742 assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
743 " handler with the same name!");
745 // Otherwise, this namespace doesn't exist yet, create and insert the
747 InsertNS = new PragmaNamespace(Namespace);
748 PragmaHandlers->AddPragma(InsertNS);
752 // Check to make sure we don't already have a pragma for this identifier.
753 assert(!InsertNS->FindHandler(Handler->getName()) &&
754 "Pragma handler already exists for this identifier!");
755 InsertNS->AddPragma(Handler);
758 /// RemovePragmaHandler - Remove the specific pragma handler from the
759 /// preprocessor. If \arg Namespace is non-null, then it should be the
760 /// namespace that \arg Handler was added to. It is an error to remove
761 /// a handler that has not been registered.
762 void Preprocessor::RemovePragmaHandler(StringRef Namespace,
763 PragmaHandler *Handler) {
764 PragmaNamespace *NS = PragmaHandlers.get();
766 // If this is specified to be in a namespace, step down into it.
767 if (!Namespace.empty()) {
768 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
769 assert(Existing && "Namespace containing handler does not exist!");
771 NS = Existing->getIfNamespace();
772 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
775 NS->RemovePragmaHandler(Handler);
777 // If this is a non-default namespace and it is now empty, remove it.
778 if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
779 PragmaHandlers->RemovePragmaHandler(NS);
784 bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
786 LexUnexpandedToken(Tok);
788 if (Tok.isNot(tok::identifier)) {
789 Diag(Tok, diag::ext_on_off_switch_syntax);
792 IdentifierInfo *II = Tok.getIdentifierInfo();
794 Result = tok::OOS_ON;
795 else if (II->isStr("OFF"))
796 Result = tok::OOS_OFF;
797 else if (II->isStr("DEFAULT"))
798 Result = tok::OOS_DEFAULT;
800 Diag(Tok, diag::ext_on_off_switch_syntax);
804 // Verify that this is followed by EOD.
805 LexUnexpandedToken(Tok);
806 if (Tok.isNot(tok::eod))
807 Diag(Tok, diag::ext_pragma_syntax_eod);
812 /// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
813 struct PragmaOnceHandler : public PragmaHandler {
814 PragmaOnceHandler() : PragmaHandler("once") {}
815 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
816 Token &OnceTok) override {
817 PP.CheckEndOfDirective("pragma once");
818 PP.HandlePragmaOnce(OnceTok);
822 /// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
823 /// rest of the line is not lexed.
824 struct PragmaMarkHandler : public PragmaHandler {
825 PragmaMarkHandler() : PragmaHandler("mark") {}
826 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
827 Token &MarkTok) override {
828 PP.HandlePragmaMark();
832 /// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
833 struct PragmaPoisonHandler : public PragmaHandler {
834 PragmaPoisonHandler() : PragmaHandler("poison") {}
835 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
836 Token &PoisonTok) override {
837 PP.HandlePragmaPoison(PoisonTok);
841 /// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
842 /// as a system header, which silences warnings in it.
843 struct PragmaSystemHeaderHandler : public PragmaHandler {
844 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
845 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
846 Token &SHToken) override {
847 PP.HandlePragmaSystemHeader(SHToken);
848 PP.CheckEndOfDirective("pragma");
851 struct PragmaDependencyHandler : public PragmaHandler {
852 PragmaDependencyHandler() : PragmaHandler("dependency") {}
853 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
854 Token &DepToken) override {
855 PP.HandlePragmaDependency(DepToken);
859 struct PragmaDebugHandler : public PragmaHandler {
860 PragmaDebugHandler() : PragmaHandler("__debug") {}
861 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
862 Token &DepToken) override {
864 PP.LexUnexpandedToken(Tok);
865 if (Tok.isNot(tok::identifier)) {
866 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
869 IdentifierInfo *II = Tok.getIdentifierInfo();
871 if (II->isStr("assert")) {
872 llvm_unreachable("This is an assertion!");
873 } else if (II->isStr("crash")) {
875 } else if (II->isStr("parser_crash")) {
877 Crasher.startToken();
878 Crasher.setKind(tok::annot_pragma_parser_crash);
879 Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
880 PP.EnterToken(Crasher);
881 } else if (II->isStr("dump")) {
883 PP.LexUnexpandedToken(Identifier);
884 if (auto *DumpII = Identifier.getIdentifierInfo()) {
886 DumpAnnot.startToken();
887 DumpAnnot.setKind(tok::annot_pragma_dump);
888 DumpAnnot.setAnnotationRange(
889 SourceRange(Tok.getLocation(), Identifier.getLocation()));
890 DumpAnnot.setAnnotationValue(DumpII);
891 PP.DiscardUntilEndOfDirective();
892 PP.EnterToken(DumpAnnot);
894 PP.Diag(Identifier, diag::warn_pragma_debug_missing_argument)
897 } else if (II->isStr("llvm_fatal_error")) {
898 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
899 } else if (II->isStr("llvm_unreachable")) {
900 llvm_unreachable("#pragma clang __debug llvm_unreachable");
901 } else if (II->isStr("macro")) {
903 PP.LexUnexpandedToken(MacroName);
904 auto *MacroII = MacroName.getIdentifierInfo();
906 PP.dumpMacroInfo(MacroII);
908 PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument)
910 } else if (II->isStr("overflow_stack")) {
911 DebugOverflowStack();
912 } else if (II->isStr("handle_crash")) {
913 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
916 } else if (II->isStr("captured")) {
919 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
923 PPCallbacks *Callbacks = PP.getPPCallbacks();
925 Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
928 void HandleCaptured(Preprocessor &PP) {
929 // Skip if emitting preprocessed output.
930 if (PP.isPreprocessedOutput())
934 PP.LexUnexpandedToken(Tok);
936 if (Tok.isNot(tok::eod)) {
937 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
938 << "pragma clang __debug captured";
942 SourceLocation NameLoc = Tok.getLocation();
943 MutableArrayRef<Token> Toks(
944 PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
945 Toks[0].startToken();
946 Toks[0].setKind(tok::annot_pragma_captured);
947 Toks[0].setLocation(NameLoc);
949 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
952 // Disable MSVC warning about runtime stack overflow.
954 #pragma warning(disable : 4717)
956 static void DebugOverflowStack() {
957 void (*volatile Self)() = DebugOverflowStack;
961 #pragma warning(default : 4717)
966 /// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
967 struct PragmaDiagnosticHandler : public PragmaHandler {
969 const char *Namespace;
971 explicit PragmaDiagnosticHandler(const char *NS) :
972 PragmaHandler("diagnostic"), Namespace(NS) {}
973 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
974 Token &DiagToken) override {
975 SourceLocation DiagLoc = DiagToken.getLocation();
977 PP.LexUnexpandedToken(Tok);
978 if (Tok.isNot(tok::identifier)) {
979 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
982 IdentifierInfo *II = Tok.getIdentifierInfo();
983 PPCallbacks *Callbacks = PP.getPPCallbacks();
985 if (II->isStr("pop")) {
986 if (!PP.getDiagnostics().popMappings(DiagLoc))
987 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
989 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
991 } else if (II->isStr("push")) {
992 PP.getDiagnostics().pushMappings(DiagLoc);
994 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
998 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
999 .Case("ignored", diag::Severity::Ignored)
1000 .Case("warning", diag::Severity::Warning)
1001 .Case("error", diag::Severity::Error)
1002 .Case("fatal", diag::Severity::Fatal)
1003 .Default(diag::Severity());
1005 if (SV == diag::Severity()) {
1006 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1010 PP.LexUnexpandedToken(Tok);
1011 SourceLocation StringLoc = Tok.getLocation();
1013 std::string WarningName;
1014 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
1015 /*MacroExpansion=*/false))
1018 if (Tok.isNot(tok::eod)) {
1019 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1023 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1024 (WarningName[1] != 'W' && WarningName[1] != 'R')) {
1025 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
1029 diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1030 : diag::Flavor::Remark;
1031 StringRef Group = StringRef(WarningName).substr(2);
1032 bool unknownDiag = false;
1033 if (Group == "everything") {
1034 // Special handling for pragma clang diagnostic ... "-Weverything".
1035 // There is no formal group named "everything", so there has to be a
1036 // special case for it.
1037 PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc);
1039 unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV,
1042 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1045 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
1049 /// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1050 /// diagnostics, so we don't really implement this pragma. We parse it and
1051 /// ignore it to avoid -Wunknown-pragma warnings.
1052 struct PragmaWarningHandler : public PragmaHandler {
1053 PragmaWarningHandler() : PragmaHandler("warning") {}
1055 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1056 Token &Tok) override {
1057 // Parse things like:
1060 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
1061 SourceLocation DiagLoc = Tok.getLocation();
1062 PPCallbacks *Callbacks = PP.getPPCallbacks();
1065 if (Tok.isNot(tok::l_paren)) {
1066 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1071 IdentifierInfo *II = Tok.getIdentifierInfo();
1073 if (II && II->isStr("push")) {
1074 // #pragma warning( push[ ,n ] )
1077 if (Tok.is(tok::comma)) {
1080 if (Tok.is(tok::numeric_constant) &&
1081 PP.parseSimpleIntegerLiteral(Tok, Value))
1083 if (Level < 0 || Level > 4) {
1084 PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1089 Callbacks->PragmaWarningPush(DiagLoc, Level);
1090 } else if (II && II->isStr("pop")) {
1091 // #pragma warning( pop )
1094 Callbacks->PragmaWarningPop(DiagLoc);
1096 // #pragma warning( warning-specifier : warning-number-list
1097 // [; warning-specifier : warning-number-list...] )
1099 II = Tok.getIdentifierInfo();
1100 if (!II && !Tok.is(tok::numeric_constant)) {
1101 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1105 // Figure out which warning specifier this is.
1106 bool SpecifierValid;
1107 StringRef Specifier;
1108 llvm::SmallString<1> SpecifierBuf;
1110 Specifier = II->getName();
1111 SpecifierValid = llvm::StringSwitch<bool>(Specifier)
1112 .Cases("default", "disable", "error", "once",
1115 // If we read a correct specifier, snatch next token (that should be
1116 // ":", checked later).
1120 // Token is a numeric constant. It should be either 1, 2, 3 or 4.
1122 Specifier = PP.getSpelling(Tok, SpecifierBuf);
1123 if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
1124 SpecifierValid = (Value >= 1) && (Value <= 4);
1126 SpecifierValid = false;
1127 // Next token already snatched by parseSimpleIntegerLiteral.
1130 if (!SpecifierValid) {
1131 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1134 if (Tok.isNot(tok::colon)) {
1135 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1139 // Collect the warning ids.
1140 SmallVector<int, 4> Ids;
1142 while (Tok.is(tok::numeric_constant)) {
1144 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
1146 PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1149 Ids.push_back(int(Value));
1152 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1154 // Parse the next specifier if there is a semicolon.
1155 if (Tok.isNot(tok::semi))
1161 if (Tok.isNot(tok::r_paren)) {
1162 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1167 if (Tok.isNot(tok::eod))
1168 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1172 /// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
1173 struct PragmaIncludeAliasHandler : public PragmaHandler {
1174 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
1175 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1176 Token &IncludeAliasTok) override {
1177 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
1181 /// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1182 /// extension. The syntax is:
1184 /// #pragma message(string)
1186 /// OR, in GCC mode:
1188 /// #pragma message string
1190 /// string is a string, which is fully macro expanded, and permits string
1191 /// concatenation, embedded escape characters, etc... See MSDN for more details.
1192 /// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1193 /// form as \#pragma message.
1194 struct PragmaMessageHandler : public PragmaHandler {
1196 const PPCallbacks::PragmaMessageKind Kind;
1197 const StringRef Namespace;
1199 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1200 bool PragmaNameOnly = false) {
1202 case PPCallbacks::PMK_Message:
1203 return PragmaNameOnly ? "message" : "pragma message";
1204 case PPCallbacks::PMK_Warning:
1205 return PragmaNameOnly ? "warning" : "pragma warning";
1206 case PPCallbacks::PMK_Error:
1207 return PragmaNameOnly ? "error" : "pragma error";
1209 llvm_unreachable("Unknown PragmaMessageKind!");
1213 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1214 StringRef Namespace = StringRef())
1215 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), Namespace(Namespace) {}
1217 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1218 Token &Tok) override {
1219 SourceLocation MessageLoc = Tok.getLocation();
1221 bool ExpectClosingParen = false;
1222 switch (Tok.getKind()) {
1224 // We have a MSVC style pragma message.
1225 ExpectClosingParen = true;
1229 case tok::string_literal:
1230 // We have a GCC style pragma message, and we just read the string.
1233 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1237 std::string MessageString;
1238 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1239 /*MacroExpansion=*/true))
1242 if (ExpectClosingParen) {
1243 if (Tok.isNot(tok::r_paren)) {
1244 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1247 PP.Lex(Tok); // eat the r_paren.
1250 if (Tok.isNot(tok::eod)) {
1251 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1255 // Output the message.
1256 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1257 ? diag::err_pragma_message
1258 : diag::warn_pragma_message) << MessageString;
1260 // If the pragma is lexically sound, notify any interested PPCallbacks.
1261 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1262 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
1266 /// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
1267 /// macro on the top of the stack.
1268 struct PragmaPushMacroHandler : public PragmaHandler {
1269 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
1270 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1271 Token &PushMacroTok) override {
1272 PP.HandlePragmaPushMacro(PushMacroTok);
1277 /// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
1278 /// macro to the value on the top of the stack.
1279 struct PragmaPopMacroHandler : public PragmaHandler {
1280 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
1281 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1282 Token &PopMacroTok) override {
1283 PP.HandlePragmaPopMacro(PopMacroTok);
1287 // Pragma STDC implementations.
1289 /// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
1290 struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
1291 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
1292 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1293 Token &Tok) override {
1294 tok::OnOffSwitch OOS;
1295 if (PP.LexOnOffSwitch(OOS))
1297 if (OOS == tok::OOS_ON)
1298 PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
1302 /// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
1303 struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
1304 PragmaSTDC_CX_LIMITED_RANGEHandler()
1305 : PragmaHandler("CX_LIMITED_RANGE") {}
1306 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1307 Token &Tok) override {
1308 tok::OnOffSwitch OOS;
1309 PP.LexOnOffSwitch(OOS);
1313 /// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
1314 struct PragmaSTDC_UnknownHandler : public PragmaHandler {
1315 PragmaSTDC_UnknownHandler() {}
1316 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1317 Token &UnknownTok) override {
1318 // C99 6.10.6p2, unknown forms are not allowed.
1319 PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
1323 /// PragmaARCCFCodeAuditedHandler -
1324 /// \#pragma clang arc_cf_code_audited begin/end
1325 struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1326 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
1327 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1328 Token &NameTok) override {
1329 SourceLocation Loc = NameTok.getLocation();
1334 // Lex the 'begin' or 'end'.
1335 PP.LexUnexpandedToken(Tok);
1336 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1337 if (BeginEnd && BeginEnd->isStr("begin")) {
1339 } else if (BeginEnd && BeginEnd->isStr("end")) {
1342 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1346 // Verify that this is followed by EOD.
1347 PP.LexUnexpandedToken(Tok);
1348 if (Tok.isNot(tok::eod))
1349 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1351 // The start location of the active audit.
1352 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1354 // The start location we want after processing this.
1355 SourceLocation NewLoc;
1358 // Complain about attempts to re-enter an audit.
1359 if (BeginLoc.isValid()) {
1360 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1361 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1365 // Complain about attempts to leave an audit that doesn't exist.
1366 if (!BeginLoc.isValid()) {
1367 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1370 NewLoc = SourceLocation();
1373 PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1377 /// PragmaAssumeNonNullHandler -
1378 /// \#pragma clang assume_nonnull begin/end
1379 struct PragmaAssumeNonNullHandler : public PragmaHandler {
1380 PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
1381 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1382 Token &NameTok) override {
1383 SourceLocation Loc = NameTok.getLocation();
1388 // Lex the 'begin' or 'end'.
1389 PP.LexUnexpandedToken(Tok);
1390 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1391 if (BeginEnd && BeginEnd->isStr("begin")) {
1393 } else if (BeginEnd && BeginEnd->isStr("end")) {
1396 PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
1400 // Verify that this is followed by EOD.
1401 PP.LexUnexpandedToken(Tok);
1402 if (Tok.isNot(tok::eod))
1403 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1405 // The start location of the active audit.
1406 SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
1408 // The start location we want after processing this.
1409 SourceLocation NewLoc;
1412 // Complain about attempts to re-enter an audit.
1413 if (BeginLoc.isValid()) {
1414 PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
1415 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1419 // Complain about attempts to leave an audit that doesn't exist.
1420 if (!BeginLoc.isValid()) {
1421 PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
1424 NewLoc = SourceLocation();
1427 PP.setPragmaAssumeNonNullLoc(NewLoc);
1431 /// \brief Handle "\#pragma region [...]"
1435 /// #pragma region [optional name]
1436 /// #pragma endregion [optional comment]
1440 /// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1441 /// pragma, just skipped by compiler.
1442 struct PragmaRegionHandler : public PragmaHandler {
1443 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) { }
1445 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1446 Token &NameTok) override {
1447 // #pragma region: endregion matches can be verified
1448 // __pragma(region): no sense, but ignored by msvc
1449 // _Pragma is not valid for MSVC, but there isn't any point
1450 // to handle a _Pragma differently.
1454 } // end anonymous namespace
1457 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
1458 /// \#pragma GCC poison/system_header/dependency and \#pragma once.
1459 void Preprocessor::RegisterBuiltinPragmas() {
1460 AddPragmaHandler(new PragmaOnceHandler());
1461 AddPragmaHandler(new PragmaMarkHandler());
1462 AddPragmaHandler(new PragmaPushMacroHandler());
1463 AddPragmaHandler(new PragmaPopMacroHandler());
1464 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
1467 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1468 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1469 AddPragmaHandler("GCC", new PragmaDependencyHandler());
1470 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
1471 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1473 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1475 // #pragma clang ...
1476 AddPragmaHandler("clang", new PragmaPoisonHandler());
1477 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
1478 AddPragmaHandler("clang", new PragmaDebugHandler());
1479 AddPragmaHandler("clang", new PragmaDependencyHandler());
1480 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
1481 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
1482 AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
1484 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1485 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
1486 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
1489 if (LangOpts.MicrosoftExt) {
1490 AddPragmaHandler(new PragmaWarningHandler());
1491 AddPragmaHandler(new PragmaIncludeAliasHandler());
1492 AddPragmaHandler(new PragmaRegionHandler("region"));
1493 AddPragmaHandler(new PragmaRegionHandler("endregion"));
1496 // Pragmas added by plugins
1497 for (PragmaHandlerRegistry::iterator it = PragmaHandlerRegistry::begin(),
1498 ie = PragmaHandlerRegistry::end();
1500 AddPragmaHandler(it->instantiate().release());
1504 /// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
1505 /// warn about those pragmas being unknown.
1506 void Preprocessor::IgnorePragmas() {
1507 AddPragmaHandler(new EmptyPragmaHandler());
1508 // Also ignore all pragmas in all namespaces created
1509 // in Preprocessor::RegisterBuiltinPragmas().
1510 AddPragmaHandler("GCC", new EmptyPragmaHandler());
1511 AddPragmaHandler("clang", new EmptyPragmaHandler());
1512 if (PragmaHandler *NS = PragmaHandlers->FindHandler("STDC")) {
1513 // Preprocessor::RegisterBuiltinPragmas() already registers
1514 // PragmaSTDC_UnknownHandler as the empty handler, so remove it first,
1515 // otherwise there will be an assert about a duplicate handler.
1516 PragmaNamespace *STDCNamespace = NS->getIfNamespace();
1517 assert(STDCNamespace &&
1518 "Invalid namespace, registered as a regular pragma handler!");
1519 if (PragmaHandler *Existing = STDCNamespace->FindHandler("", false)) {
1520 RemovePragmaHandler("STDC", Existing);
1524 AddPragmaHandler("STDC", new EmptyPragmaHandler());