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/Support/CrashRecoveryContext.h"
26 #include "llvm/Support/ErrorHandling.h"
28 using namespace clang
;
30 #include "llvm/Support/raw_ostream.h"
32 // Out-of-line destructor to provide a home for the class.
33 PragmaHandler::~PragmaHandler() {
36 //===----------------------------------------------------------------------===//
37 // EmptyPragmaHandler Implementation.
38 //===----------------------------------------------------------------------===//
40 EmptyPragmaHandler::EmptyPragmaHandler() {}
42 void EmptyPragmaHandler::HandlePragma(Preprocessor
&PP
,
43 PragmaIntroducerKind Introducer
,
46 //===----------------------------------------------------------------------===//
47 // PragmaNamespace Implementation.
48 //===----------------------------------------------------------------------===//
50 PragmaNamespace::~PragmaNamespace() {
51 llvm::DeleteContainerSeconds(Handlers
);
54 /// FindHandler - Check to see if there is already a handler for the
55 /// specified name. If not, return the handler for the null identifier if it
56 /// exists, otherwise return null. If IgnoreNull is true (the default) then
57 /// the null handler isn't returned on failure to match.
58 PragmaHandler
*PragmaNamespace::FindHandler(StringRef Name
,
59 bool IgnoreNull
) const {
60 if (PragmaHandler
*Handler
= Handlers
.lookup(Name
))
62 return IgnoreNull
? nullptr : Handlers
.lookup(StringRef());
65 void PragmaNamespace::AddPragma(PragmaHandler
*Handler
) {
66 assert(!Handlers
.lookup(Handler
->getName()) &&
67 "A handler with this name is already registered in this namespace");
68 Handlers
[Handler
->getName()] = Handler
;
71 void PragmaNamespace::RemovePragmaHandler(PragmaHandler
*Handler
) {
72 assert(Handlers
.lookup(Handler
->getName()) &&
73 "Handler not registered in this namespace");
74 Handlers
.erase(Handler
->getName());
77 void PragmaNamespace::HandlePragma(Preprocessor
&PP
,
78 PragmaIntroducerKind Introducer
,
80 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
81 // expand it, the user can have a STDC #define, that should not affect this.
82 PP
.LexUnexpandedToken(Tok
);
84 // Get the handler for this token. If there is no handler, ignore the pragma.
85 PragmaHandler
*Handler
86 = FindHandler(Tok
.getIdentifierInfo() ? Tok
.getIdentifierInfo()->getName()
88 /*IgnoreNull=*/false);
90 PP
.Diag(Tok
, diag::warn_pragma_ignored
);
94 // Otherwise, pass it down.
95 Handler
->HandlePragma(PP
, Introducer
, Tok
);
98 //===----------------------------------------------------------------------===//
99 // Preprocessor Pragma Directive Handling.
100 //===----------------------------------------------------------------------===//
102 /// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the
103 /// rest of the pragma, passing it to the registered pragma handlers.
104 void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc
,
105 PragmaIntroducerKind Introducer
) {
107 Callbacks
->PragmaDirective(IntroducerLoc
, Introducer
);
114 // Invoke the first level of pragma handlers which reads the namespace id.
116 PragmaHandlers
->HandlePragma(*this, Introducer
, Tok
);
118 // If the pragma handler didn't read the rest of the line, consume it now.
119 if ((CurTokenLexer
&& CurTokenLexer
->isParsingPreprocessorDirective())
120 || (CurPPLexer
&& CurPPLexer
->ParsingPreprocessorDirective
))
121 DiscardUntilEndOfDirective();
125 /// \brief Helper class for \see Preprocessor::Handle_Pragma.
126 class LexingFor_PragmaRAII
{
128 bool InMacroArgPreExpansion
;
134 LexingFor_PragmaRAII(Preprocessor
&PP
, bool InMacroArgPreExpansion
,
136 : PP(PP
), InMacroArgPreExpansion(InMacroArgPreExpansion
),
137 Failed(false), OutTok(Tok
) {
138 if (InMacroArgPreExpansion
) {
140 PP
.EnableBacktrackAtThisPos();
144 ~LexingFor_PragmaRAII() {
145 if (InMacroArgPreExpansion
) {
147 PP
.CommitBacktrackedTokens();
161 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
162 /// return the first token after the directive. The _Pragma token has just
163 /// been read into 'Tok'.
164 void Preprocessor::Handle_Pragma(Token
&Tok
) {
166 // This works differently if we are pre-expanding a macro argument.
167 // In that case we don't actually "activate" the pragma now, we only lex it
168 // until we are sure it is lexically correct and then we backtrack so that
169 // we activate the pragma whenever we encounter the tokens again in the token
170 // stream. This ensures that we will activate it in the correct location
171 // or that we will ignore it if it never enters the token stream, e.g:
174 // #define INACTIVE(x) EMPTY(x)
175 // INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\""))
177 LexingFor_PragmaRAII
_PragmaLexing(*this, InMacroArgPreExpansion
, Tok
);
179 // Remember the pragma token location.
180 SourceLocation PragmaLoc
= Tok
.getLocation();
184 if (Tok
.isNot(tok::l_paren
)) {
185 Diag(PragmaLoc
, diag::err__Pragma_malformed
);
186 return _PragmaLexing
.failed();
191 if (!tok::isStringLiteral(Tok
.getKind())) {
192 Diag(PragmaLoc
, diag::err__Pragma_malformed
);
193 // Skip this token, and the ')', if present.
194 if (Tok
.isNot(tok::r_paren
) && Tok
.isNot(tok::eof
))
196 if (Tok
.is(tok::r_paren
))
198 return _PragmaLexing
.failed();
201 if (Tok
.hasUDSuffix()) {
202 Diag(Tok
, diag::err_invalid_string_udl
);
203 // Skip this token, and the ')', if present.
205 if (Tok
.is(tok::r_paren
))
207 return _PragmaLexing
.failed();
210 // Remember the string.
215 if (Tok
.isNot(tok::r_paren
)) {
216 Diag(PragmaLoc
, diag::err__Pragma_malformed
);
217 return _PragmaLexing
.failed();
220 if (InMacroArgPreExpansion
)
223 SourceLocation RParenLoc
= Tok
.getLocation();
224 std::string StrVal
= getSpelling(StrTok
);
226 // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1:
227 // "The string literal is destringized by deleting any encoding prefix,
228 // deleting the leading and trailing double-quotes, replacing each escape
229 // sequence \" by a double-quote, and replacing each escape sequence \\ by a
230 // single backslash."
231 if (StrVal
[0] == 'L' || StrVal
[0] == 'U' ||
232 (StrVal
[0] == 'u' && StrVal
[1] != '8'))
233 StrVal
.erase(StrVal
.begin());
234 else if (StrVal
[0] == 'u')
235 StrVal
.erase(StrVal
.begin(), StrVal
.begin() + 2);
237 if (StrVal
[0] == 'R') {
238 // FIXME: C++11 does not specify how to handle raw-string-literals here.
239 // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
240 assert(StrVal
[1] == '"' && StrVal
[StrVal
.size() - 1] == '"' &&
241 "Invalid raw string token!");
243 // Measure the length of the d-char-sequence.
244 unsigned NumDChars
= 0;
245 while (StrVal
[2 + NumDChars
] != '(') {
246 assert(NumDChars
< (StrVal
.size() - 5) / 2 &&
247 "Invalid raw string token!");
250 assert(StrVal
[StrVal
.size() - 2 - NumDChars
] == ')');
252 // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
254 StrVal
.erase(0, 2 + NumDChars
);
255 StrVal
.erase(StrVal
.size() - 1 - NumDChars
);
257 assert(StrVal
[0] == '"' && StrVal
[StrVal
.size()-1] == '"' &&
258 "Invalid string token!");
260 // Remove escaped quotes and escapes.
261 unsigned ResultPos
= 1;
262 for (unsigned i
= 1, e
= StrVal
.size() - 1; i
!= e
; ++i
) {
263 // Skip escapes. \\ -> '\' and \" -> '"'.
264 if (StrVal
[i
] == '\\' && i
+ 1 < e
&&
265 (StrVal
[i
+ 1] == '\\' || StrVal
[i
+ 1] == '"'))
267 StrVal
[ResultPos
++] = StrVal
[i
];
269 StrVal
.erase(StrVal
.begin() + ResultPos
, StrVal
.end() - 1);
272 // Remove the front quote, replacing it with a space, so that the pragma
273 // contents appear to have a space before them.
276 // Replace the terminating quote with a \n.
277 StrVal
[StrVal
.size()-1] = '\n';
279 // Plop the string (including the newline and trailing null) into a buffer
280 // where we can lex it.
283 CreateString(StrVal
, TmpTok
);
284 SourceLocation TokLoc
= TmpTok
.getLocation();
286 // Make and enter a lexer object so that we lex and expand the tokens just
288 Lexer
*TL
= Lexer::Create_PragmaLexer(TokLoc
, PragmaLoc
, RParenLoc
,
289 StrVal
.size(), *this);
291 EnterSourceFileWithLexer(TL
, nullptr);
293 // With everything set up, lex this as a #pragma directive.
294 HandlePragmaDirective(PragmaLoc
, PIK__Pragma
);
296 // Finally, return whatever came after the pragma directive.
300 /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
301 /// is not enclosed within a string literal.
302 void Preprocessor::HandleMicrosoft__pragma(Token
&Tok
) {
303 // Remember the pragma token location.
304 SourceLocation PragmaLoc
= Tok
.getLocation();
308 if (Tok
.isNot(tok::l_paren
)) {
309 Diag(PragmaLoc
, diag::err__Pragma_malformed
);
313 // Get the tokens enclosed within the __pragma(), as well as the final ')'.
314 SmallVector
<Token
, 32> PragmaToks
;
317 while (Tok
.isNot(tok::eof
)) {
318 PragmaToks
.push_back(Tok
);
319 if (Tok
.is(tok::l_paren
))
321 else if (Tok
.is(tok::r_paren
) && NumParens
-- == 0)
326 if (Tok
.is(tok::eof
)) {
327 Diag(PragmaLoc
, diag::err_unterminated___pragma
);
331 PragmaToks
.front().setFlag(Token::LeadingSpace
);
333 // Replace the ')' with an EOD to mark the end of the pragma.
334 PragmaToks
.back().setKind(tok::eod
);
336 Token
*TokArray
= new Token
[PragmaToks
.size()];
337 std::copy(PragmaToks
.begin(), PragmaToks
.end(), TokArray
);
339 // Push the tokens onto the stack.
340 EnterTokenStream(TokArray
, PragmaToks
.size(), true, true);
342 // With everything set up, lex this as a #pragma directive.
343 HandlePragmaDirective(PragmaLoc
, PIK___pragma
);
345 // Finally, return whatever came after the pragma directive.
349 /// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
351 void Preprocessor::HandlePragmaOnce(Token
&OnceTok
) {
352 if (isInPrimaryFile()) {
353 Diag(OnceTok
, diag::pp_pragma_once_in_main_file
);
357 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
358 // Mark the file as a once-only file now.
359 HeaderInfo
.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
362 void Preprocessor::HandlePragmaMark() {
363 assert(CurPPLexer
&& "No current lexer?");
365 CurLexer
->ReadToEndOfLine();
367 CurPTHLexer
->DiscardToEndOfLine();
371 /// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
373 void Preprocessor::HandlePragmaPoison(Token
&PoisonTok
) {
377 // Read the next token to poison. While doing this, pretend that we are
378 // skipping while reading the identifier to poison.
379 // This avoids errors on code like:
380 // #pragma GCC poison X
381 // #pragma GCC poison X
382 if (CurPPLexer
) CurPPLexer
->LexingRawMode
= true;
383 LexUnexpandedToken(Tok
);
384 if (CurPPLexer
) CurPPLexer
->LexingRawMode
= false;
386 // If we reached the end of line, we're done.
387 if (Tok
.is(tok::eod
)) return;
389 // Can only poison identifiers.
390 if (Tok
.isNot(tok::raw_identifier
)) {
391 Diag(Tok
, diag::err_pp_invalid_poison
);
395 // Look up the identifier info for the token. We disabled identifier lookup
396 // by saying we're skipping contents, so we need to do this manually.
397 IdentifierInfo
*II
= LookUpIdentifierInfo(Tok
);
400 if (II
->isPoisoned()) continue;
402 // If this is a macro identifier, emit a warning.
403 if (II
->hasMacroDefinition())
404 Diag(Tok
, diag::pp_poisoning_existing_macro
);
406 // Finally, poison it!
409 II
->setChangedSinceDeserialization();
413 /// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
414 /// that the whole directive has been parsed.
415 void Preprocessor::HandlePragmaSystemHeader(Token
&SysHeaderTok
) {
416 if (isInPrimaryFile()) {
417 Diag(SysHeaderTok
, diag::pp_pragma_sysheader_in_main_file
);
421 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
422 PreprocessorLexer
*TheLexer
= getCurrentFileLexer();
424 // Mark the file as a system header.
425 HeaderInfo
.MarkFileSystemHeader(TheLexer
->getFileEntry());
428 PresumedLoc PLoc
= SourceMgr
.getPresumedLoc(SysHeaderTok
.getLocation());
429 if (PLoc
.isInvalid())
432 unsigned FilenameID
= SourceMgr
.getLineTableFilenameID(PLoc
.getFilename());
434 // Notify the client, if desired, that we are in a new source file.
436 Callbacks
->FileChanged(SysHeaderTok
.getLocation(),
437 PPCallbacks::SystemHeaderPragma
, SrcMgr::C_System
);
439 // Emit a line marker. This will change any source locations from this point
440 // forward to realize they are in a system header.
441 // Create a line note with this information.
442 SourceMgr
.AddLineNote(SysHeaderTok
.getLocation(), PLoc
.getLine()+1,
443 FilenameID
, /*IsEntry=*/false, /*IsExit=*/false,
444 /*IsSystem=*/true, /*IsExternC=*/false);
447 /// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
449 void Preprocessor::HandlePragmaDependency(Token
&DependencyTok
) {
451 CurPPLexer
->LexIncludeFilename(FilenameTok
);
453 // If the token kind is EOD, the error has already been diagnosed.
454 if (FilenameTok
.is(tok::eod
))
457 // Reserve a buffer to get the spelling.
458 SmallString
<128> FilenameBuffer
;
459 bool Invalid
= false;
460 StringRef Filename
= getSpelling(FilenameTok
, FilenameBuffer
, &Invalid
);
465 GetIncludeFilenameSpelling(FilenameTok
.getLocation(), Filename
);
466 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
468 if (Filename
.empty())
471 // Search include directories for this file.
472 const DirectoryLookup
*CurDir
;
473 const FileEntry
*File
=
474 LookupFile(FilenameTok
.getLocation(), Filename
, isAngled
, nullptr,
475 nullptr, CurDir
, nullptr, nullptr, nullptr);
477 if (!SuppressIncludeNotFoundError
)
478 Diag(FilenameTok
, diag::err_pp_file_not_found
) << Filename
;
482 const FileEntry
*CurFile
= getCurrentFileLexer()->getFileEntry();
484 // If this file is older than the file it depends on, emit a diagnostic.
485 if (CurFile
&& CurFile
->getModificationTime() < File
->getModificationTime()) {
486 // Lex tokens at the end of the message and include them in the message.
489 while (DependencyTok
.isNot(tok::eod
)) {
490 Message
+= getSpelling(DependencyTok
) + " ";
494 // Remove the trailing ' ' if present.
495 if (!Message
.empty())
496 Message
.erase(Message
.end()-1);
497 Diag(FilenameTok
, diag::pp_out_of_date_dependency
) << Message
;
501 /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
502 /// Return the IdentifierInfo* associated with the macro to push or pop.
503 IdentifierInfo
*Preprocessor::ParsePragmaPushOrPopMacro(Token
&Tok
) {
504 // Remember the pragma token location.
505 Token PragmaTok
= Tok
;
509 if (Tok
.isNot(tok::l_paren
)) {
510 Diag(PragmaTok
.getLocation(), diag::err_pragma_push_pop_macro_malformed
)
511 << getSpelling(PragmaTok
);
515 // Read the macro name string.
517 if (Tok
.isNot(tok::string_literal
)) {
518 Diag(PragmaTok
.getLocation(), diag::err_pragma_push_pop_macro_malformed
)
519 << getSpelling(PragmaTok
);
523 if (Tok
.hasUDSuffix()) {
524 Diag(Tok
, diag::err_invalid_string_udl
);
528 // Remember the macro string.
529 std::string StrVal
= getSpelling(Tok
);
533 if (Tok
.isNot(tok::r_paren
)) {
534 Diag(PragmaTok
.getLocation(), diag::err_pragma_push_pop_macro_malformed
)
535 << getSpelling(PragmaTok
);
539 assert(StrVal
[0] == '"' && StrVal
[StrVal
.size()-1] == '"' &&
540 "Invalid string token!");
542 // Create a Token from the string.
544 MacroTok
.startToken();
545 MacroTok
.setKind(tok::raw_identifier
);
546 CreateString(StringRef(&StrVal
[1], StrVal
.size() - 2), MacroTok
);
548 // Get the IdentifierInfo of MacroToPushTok.
549 return LookUpIdentifierInfo(MacroTok
);
552 /// \brief Handle \#pragma push_macro.
556 /// #pragma push_macro("macro")
558 void Preprocessor::HandlePragmaPushMacro(Token
&PushMacroTok
) {
559 // Parse the pragma directive and get the macro IdentifierInfo*.
560 IdentifierInfo
*IdentInfo
= ParsePragmaPushOrPopMacro(PushMacroTok
);
561 if (!IdentInfo
) return;
563 // Get the MacroInfo associated with IdentInfo.
564 MacroInfo
*MI
= getMacroInfo(IdentInfo
);
567 // Allow the original MacroInfo to be redefined later.
568 MI
->setIsAllowRedefinitionsWithoutWarning(true);
571 // Push the cloned MacroInfo so we can retrieve it later.
572 PragmaPushMacroInfo
[IdentInfo
].push_back(MI
);
575 /// \brief Handle \#pragma pop_macro.
579 /// #pragma pop_macro("macro")
581 void Preprocessor::HandlePragmaPopMacro(Token
&PopMacroTok
) {
582 SourceLocation MessageLoc
= PopMacroTok
.getLocation();
584 // Parse the pragma directive and get the macro IdentifierInfo*.
585 IdentifierInfo
*IdentInfo
= ParsePragmaPushOrPopMacro(PopMacroTok
);
586 if (!IdentInfo
) return;
588 // Find the vector<MacroInfo*> associated with the macro.
589 llvm::DenseMap
<IdentifierInfo
*, std::vector
<MacroInfo
*> >::iterator iter
=
590 PragmaPushMacroInfo
.find(IdentInfo
);
591 if (iter
!= PragmaPushMacroInfo
.end()) {
592 // Forget the MacroInfo currently associated with IdentInfo.
593 if (MacroDirective
*CurrentMD
= getMacroDirective(IdentInfo
)) {
594 MacroInfo
*MI
= CurrentMD
->getMacroInfo();
595 if (MI
->isWarnIfUnused())
596 WarnUnusedMacroLocs
.erase(MI
->getDefinitionLoc());
597 appendMacroDirective(IdentInfo
, AllocateUndefMacroDirective(MessageLoc
));
600 // Get the MacroInfo we want to reinstall.
601 MacroInfo
*MacroToReInstall
= iter
->second
.back();
603 if (MacroToReInstall
) {
604 // Reinstall the previously pushed macro.
605 appendDefMacroDirective(IdentInfo
, MacroToReInstall
, MessageLoc
,
606 /*isImported=*/false, /*Overrides*/None
);
609 // Pop PragmaPushMacroInfo stack.
610 iter
->second
.pop_back();
611 if (iter
->second
.size() == 0)
612 PragmaPushMacroInfo
.erase(iter
);
614 Diag(MessageLoc
, diag::warn_pragma_pop_macro_no_push
)
615 << IdentInfo
->getName();
619 void Preprocessor::HandlePragmaIncludeAlias(Token
&Tok
) {
620 // We will either get a quoted filename or a bracketed filename, and we
621 // have to track which we got. The first filename is the source name,
622 // and the second name is the mapped filename. If the first is quoted,
623 // the second must be as well (cannot mix and match quotes and brackets).
625 // Get the open paren
627 if (Tok
.isNot(tok::l_paren
)) {
628 Diag(Tok
, diag::warn_pragma_include_alias_expected
) << "(";
632 // We expect either a quoted string literal, or a bracketed name
633 Token SourceFilenameTok
;
634 CurPPLexer
->LexIncludeFilename(SourceFilenameTok
);
635 if (SourceFilenameTok
.is(tok::eod
)) {
636 // The diagnostic has already been handled
640 StringRef SourceFileName
;
641 SmallString
<128> FileNameBuffer
;
642 if (SourceFilenameTok
.is(tok::string_literal
) ||
643 SourceFilenameTok
.is(tok::angle_string_literal
)) {
644 SourceFileName
= getSpelling(SourceFilenameTok
, FileNameBuffer
);
645 } else if (SourceFilenameTok
.is(tok::less
)) {
646 // This could be a path instead of just a name
647 FileNameBuffer
.push_back('<');
649 if (ConcatenateIncludeName(FileNameBuffer
, End
))
650 return; // Diagnostic already emitted
651 SourceFileName
= FileNameBuffer
.str();
653 Diag(Tok
, diag::warn_pragma_include_alias_expected_filename
);
656 FileNameBuffer
.clear();
658 // Now we expect a comma, followed by another include name
660 if (Tok
.isNot(tok::comma
)) {
661 Diag(Tok
, diag::warn_pragma_include_alias_expected
) << ",";
665 Token ReplaceFilenameTok
;
666 CurPPLexer
->LexIncludeFilename(ReplaceFilenameTok
);
667 if (ReplaceFilenameTok
.is(tok::eod
)) {
668 // The diagnostic has already been handled
672 StringRef ReplaceFileName
;
673 if (ReplaceFilenameTok
.is(tok::string_literal
) ||
674 ReplaceFilenameTok
.is(tok::angle_string_literal
)) {
675 ReplaceFileName
= getSpelling(ReplaceFilenameTok
, FileNameBuffer
);
676 } else if (ReplaceFilenameTok
.is(tok::less
)) {
677 // This could be a path instead of just a name
678 FileNameBuffer
.push_back('<');
680 if (ConcatenateIncludeName(FileNameBuffer
, End
))
681 return; // Diagnostic already emitted
682 ReplaceFileName
= FileNameBuffer
.str();
684 Diag(Tok
, diag::warn_pragma_include_alias_expected_filename
);
688 // Finally, we expect the closing paren
690 if (Tok
.isNot(tok::r_paren
)) {
691 Diag(Tok
, diag::warn_pragma_include_alias_expected
) << ")";
695 // Now that we have the source and target filenames, we need to make sure
696 // they're both of the same type (angled vs non-angled)
697 StringRef OriginalSource
= SourceFileName
;
699 bool SourceIsAngled
=
700 GetIncludeFilenameSpelling(SourceFilenameTok
.getLocation(),
702 bool ReplaceIsAngled
=
703 GetIncludeFilenameSpelling(ReplaceFilenameTok
.getLocation(),
705 if (!SourceFileName
.empty() && !ReplaceFileName
.empty() &&
706 (SourceIsAngled
!= ReplaceIsAngled
)) {
709 DiagID
= diag::warn_pragma_include_alias_mismatch_angle
;
711 DiagID
= diag::warn_pragma_include_alias_mismatch_quote
;
713 Diag(SourceFilenameTok
.getLocation(), DiagID
)
720 // Now we can let the include handler know about this mapping
721 getHeaderSearchInfo().AddIncludeAlias(OriginalSource
, ReplaceFileName
);
724 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
725 /// If 'Namespace' is non-null, then it is a token required to exist on the
726 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
727 void Preprocessor::AddPragmaHandler(StringRef Namespace
,
728 PragmaHandler
*Handler
) {
729 PragmaNamespace
*InsertNS
= PragmaHandlers
.get();
731 // If this is specified to be in a namespace, step down into it.
732 if (!Namespace
.empty()) {
733 // If there is already a pragma handler with the name of this namespace,
734 // we either have an error (directive with the same name as a namespace) or
735 // we already have the namespace to insert into.
736 if (PragmaHandler
*Existing
= PragmaHandlers
->FindHandler(Namespace
)) {
737 InsertNS
= Existing
->getIfNamespace();
738 assert(InsertNS
!= nullptr && "Cannot have a pragma namespace and pragma"
739 " handler with the same name!");
741 // Otherwise, this namespace doesn't exist yet, create and insert the
743 InsertNS
= new PragmaNamespace(Namespace
);
744 PragmaHandlers
->AddPragma(InsertNS
);
748 // Check to make sure we don't already have a pragma for this identifier.
749 assert(!InsertNS
->FindHandler(Handler
->getName()) &&
750 "Pragma handler already exists for this identifier!");
751 InsertNS
->AddPragma(Handler
);
754 /// RemovePragmaHandler - Remove the specific pragma handler from the
755 /// preprocessor. If \arg Namespace is non-null, then it should be the
756 /// namespace that \arg Handler was added to. It is an error to remove
757 /// a handler that has not been registered.
758 void Preprocessor::RemovePragmaHandler(StringRef Namespace
,
759 PragmaHandler
*Handler
) {
760 PragmaNamespace
*NS
= PragmaHandlers
.get();
762 // If this is specified to be in a namespace, step down into it.
763 if (!Namespace
.empty()) {
764 PragmaHandler
*Existing
= PragmaHandlers
->FindHandler(Namespace
);
765 assert(Existing
&& "Namespace containing handler does not exist!");
767 NS
= Existing
->getIfNamespace();
768 assert(NS
&& "Invalid namespace, registered as a regular pragma handler!");
771 NS
->RemovePragmaHandler(Handler
);
773 // If this is a non-default namespace and it is now empty, remove it.
774 if (NS
!= PragmaHandlers
.get() && NS
->IsEmpty()) {
775 PragmaHandlers
->RemovePragmaHandler(NS
);
780 bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch
&Result
) {
782 LexUnexpandedToken(Tok
);
784 if (Tok
.isNot(tok::identifier
)) {
785 Diag(Tok
, diag::ext_on_off_switch_syntax
);
788 IdentifierInfo
*II
= Tok
.getIdentifierInfo();
790 Result
= tok::OOS_ON
;
791 else if (II
->isStr("OFF"))
792 Result
= tok::OOS_OFF
;
793 else if (II
->isStr("DEFAULT"))
794 Result
= tok::OOS_DEFAULT
;
796 Diag(Tok
, diag::ext_on_off_switch_syntax
);
800 // Verify that this is followed by EOD.
801 LexUnexpandedToken(Tok
);
802 if (Tok
.isNot(tok::eod
))
803 Diag(Tok
, diag::ext_pragma_syntax_eod
);
808 /// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
809 struct PragmaOnceHandler
: public PragmaHandler
{
810 PragmaOnceHandler() : PragmaHandler("once") {}
811 void HandlePragma(Preprocessor
&PP
, PragmaIntroducerKind Introducer
,
812 Token
&OnceTok
) override
{
813 PP
.CheckEndOfDirective("pragma once");
814 PP
.HandlePragmaOnce(OnceTok
);
818 /// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
819 /// rest of the line is not lexed.
820 struct PragmaMarkHandler
: public PragmaHandler
{
821 PragmaMarkHandler() : PragmaHandler("mark") {}
822 void HandlePragma(Preprocessor
&PP
, PragmaIntroducerKind Introducer
,
823 Token
&MarkTok
) override
{
824 PP
.HandlePragmaMark();
828 /// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
829 struct PragmaPoisonHandler
: public PragmaHandler
{
830 PragmaPoisonHandler() : PragmaHandler("poison") {}
831 void HandlePragma(Preprocessor
&PP
, PragmaIntroducerKind Introducer
,
832 Token
&PoisonTok
) override
{
833 PP
.HandlePragmaPoison(PoisonTok
);
837 /// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
838 /// as a system header, which silences warnings in it.
839 struct PragmaSystemHeaderHandler
: public PragmaHandler
{
840 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
841 void HandlePragma(Preprocessor
&PP
, PragmaIntroducerKind Introducer
,
842 Token
&SHToken
) override
{
843 PP
.HandlePragmaSystemHeader(SHToken
);
844 PP
.CheckEndOfDirective("pragma");
847 struct PragmaDependencyHandler
: public PragmaHandler
{
848 PragmaDependencyHandler() : PragmaHandler("dependency") {}
849 void HandlePragma(Preprocessor
&PP
, PragmaIntroducerKind Introducer
,
850 Token
&DepToken
) override
{
851 PP
.HandlePragmaDependency(DepToken
);
855 struct PragmaDebugHandler
: public PragmaHandler
{
856 PragmaDebugHandler() : PragmaHandler("__debug") {}
857 void HandlePragma(Preprocessor
&PP
, PragmaIntroducerKind Introducer
,
858 Token
&DepToken
) override
{
860 PP
.LexUnexpandedToken(Tok
);
861 if (Tok
.isNot(tok::identifier
)) {
862 PP
.Diag(Tok
, diag::warn_pragma_diagnostic_invalid
);
865 IdentifierInfo
*II
= Tok
.getIdentifierInfo();
867 if (II
->isStr("assert")) {
868 llvm_unreachable("This is an assertion!");
869 } else if (II
->isStr("crash")) {
871 } else if (II
->isStr("parser_crash")) {
873 Crasher
.setKind(tok::annot_pragma_parser_crash
);
874 PP
.EnterToken(Crasher
);
875 } else if (II
->isStr("llvm_fatal_error")) {
876 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
877 } else if (II
->isStr("llvm_unreachable")) {
878 llvm_unreachable("#pragma clang __debug llvm_unreachable");
879 } else if (II
->isStr("overflow_stack")) {
880 DebugOverflowStack();
881 } else if (II
->isStr("handle_crash")) {
882 llvm::CrashRecoveryContext
*CRC
=llvm::CrashRecoveryContext::GetCurrent();
885 } else if (II
->isStr("captured")) {
888 PP
.Diag(Tok
, diag::warn_pragma_debug_unexpected_command
)
892 PPCallbacks
*Callbacks
= PP
.getPPCallbacks();
894 Callbacks
->PragmaDebug(Tok
.getLocation(), II
->getName());
897 void HandleCaptured(Preprocessor
&PP
) {
898 // Skip if emitting preprocessed output.
899 if (PP
.isPreprocessedOutput())
903 PP
.LexUnexpandedToken(Tok
);
905 if (Tok
.isNot(tok::eod
)) {
906 PP
.Diag(Tok
, diag::ext_pp_extra_tokens_at_eol
)
907 << "pragma clang __debug captured";
911 SourceLocation NameLoc
= Tok
.getLocation();
912 Token
*Toks
= PP
.getPreprocessorAllocator().Allocate
<Token
>(1);
914 Toks
->setKind(tok::annot_pragma_captured
);
915 Toks
->setLocation(NameLoc
);
917 PP
.EnterTokenStream(Toks
, 1, /*DisableMacroExpansion=*/true,
918 /*OwnsTokens=*/false);
921 // Disable MSVC warning about runtime stack overflow.
923 #pragma warning(disable : 4717)
925 static void DebugOverflowStack() {
926 void (*volatile Self
)() = DebugOverflowStack
;
930 #pragma warning(default : 4717)
935 /// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
936 struct PragmaDiagnosticHandler
: public PragmaHandler
{
938 const char *Namespace
;
940 explicit PragmaDiagnosticHandler(const char *NS
) :
941 PragmaHandler("diagnostic"), Namespace(NS
) {}
942 void HandlePragma(Preprocessor
&PP
, PragmaIntroducerKind Introducer
,
943 Token
&DiagToken
) override
{
944 SourceLocation DiagLoc
= DiagToken
.getLocation();
946 PP
.LexUnexpandedToken(Tok
);
947 if (Tok
.isNot(tok::identifier
)) {
948 PP
.Diag(Tok
, diag::warn_pragma_diagnostic_invalid
);
951 IdentifierInfo
*II
= Tok
.getIdentifierInfo();
952 PPCallbacks
*Callbacks
= PP
.getPPCallbacks();
954 if (II
->isStr("pop")) {
955 if (!PP
.getDiagnostics().popMappings(DiagLoc
))
956 PP
.Diag(Tok
, diag::warn_pragma_diagnostic_cannot_pop
);
958 Callbacks
->PragmaDiagnosticPop(DiagLoc
, Namespace
);
960 } else if (II
->isStr("push")) {
961 PP
.getDiagnostics().pushMappings(DiagLoc
);
963 Callbacks
->PragmaDiagnosticPush(DiagLoc
, Namespace
);
967 diag::Severity SV
= llvm::StringSwitch
<diag::Severity
>(II
->getName())
968 .Case("ignored", diag::Severity::Ignored
)
969 .Case("warning", diag::Severity::Warning
)
970 .Case("error", diag::Severity::Error
)
971 .Case("fatal", diag::Severity::Fatal
)
972 .Default(diag::Severity());
974 if (SV
== diag::Severity()) {
975 PP
.Diag(Tok
, diag::warn_pragma_diagnostic_invalid
);
979 PP
.LexUnexpandedToken(Tok
);
980 SourceLocation StringLoc
= Tok
.getLocation();
982 std::string WarningName
;
983 if (!PP
.FinishLexStringLiteral(Tok
, WarningName
, "pragma diagnostic",
984 /*MacroExpansion=*/false))
987 if (Tok
.isNot(tok::eod
)) {
988 PP
.Diag(Tok
.getLocation(), diag::warn_pragma_diagnostic_invalid_token
);
992 if (WarningName
.size() < 3 || WarningName
[0] != '-' ||
993 (WarningName
[1] != 'W' && WarningName
[1] != 'R')) {
994 PP
.Diag(StringLoc
, diag::warn_pragma_diagnostic_invalid_option
);
998 if (PP
.getDiagnostics().setSeverityForGroup(
999 WarningName
[1] == 'W' ? diag::Flavor::WarningOrError
1000 : diag::Flavor::Remark
,
1001 WarningName
.substr(2), SV
, DiagLoc
))
1002 PP
.Diag(StringLoc
, diag::warn_pragma_diagnostic_unknown_warning
)
1005 Callbacks
->PragmaDiagnostic(DiagLoc
, Namespace
, SV
, WarningName
);
1009 /// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1010 /// diagnostics, so we don't really implement this pragma. We parse it and
1011 /// ignore it to avoid -Wunknown-pragma warnings.
1012 struct PragmaWarningHandler
: public PragmaHandler
{
1013 PragmaWarningHandler() : PragmaHandler("warning") {}
1015 void HandlePragma(Preprocessor
&PP
, PragmaIntroducerKind Introducer
,
1016 Token
&Tok
) override
{
1017 // Parse things like:
1020 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
1021 SourceLocation DiagLoc
= Tok
.getLocation();
1022 PPCallbacks
*Callbacks
= PP
.getPPCallbacks();
1025 if (Tok
.isNot(tok::l_paren
)) {
1026 PP
.Diag(Tok
, diag::warn_pragma_warning_expected
) << "(";
1031 IdentifierInfo
*II
= Tok
.getIdentifierInfo();
1033 PP
.Diag(Tok
, diag::warn_pragma_warning_spec_invalid
);
1037 if (II
->isStr("push")) {
1038 // #pragma warning( push[ ,n ] )
1041 if (Tok
.is(tok::comma
)) {
1044 if (Tok
.is(tok::numeric_constant
) &&
1045 PP
.parseSimpleIntegerLiteral(Tok
, Value
))
1047 if (Level
< 0 || Level
> 4) {
1048 PP
.Diag(Tok
, diag::warn_pragma_warning_push_level
);
1053 Callbacks
->PragmaWarningPush(DiagLoc
, Level
);
1054 } else if (II
->isStr("pop")) {
1055 // #pragma warning( pop )
1058 Callbacks
->PragmaWarningPop(DiagLoc
);
1060 // #pragma warning( warning-specifier : warning-number-list
1061 // [; warning-specifier : warning-number-list...] )
1063 II
= Tok
.getIdentifierInfo();
1065 PP
.Diag(Tok
, diag::warn_pragma_warning_spec_invalid
);
1069 // Figure out which warning specifier this is.
1070 StringRef Specifier
= II
->getName();
1071 bool SpecifierValid
=
1072 llvm::StringSwitch
<bool>(Specifier
)
1073 .Cases("1", "2", "3", "4", true)
1074 .Cases("default", "disable", "error", "once", "suppress", true)
1076 if (!SpecifierValid
) {
1077 PP
.Diag(Tok
, diag::warn_pragma_warning_spec_invalid
);
1081 if (Tok
.isNot(tok::colon
)) {
1082 PP
.Diag(Tok
, diag::warn_pragma_warning_expected
) << ":";
1086 // Collect the warning ids.
1087 SmallVector
<int, 4> Ids
;
1089 while (Tok
.is(tok::numeric_constant
)) {
1091 if (!PP
.parseSimpleIntegerLiteral(Tok
, Value
) || Value
== 0 ||
1093 PP
.Diag(Tok
, diag::warn_pragma_warning_expected_number
);
1096 Ids
.push_back(int(Value
));
1099 Callbacks
->PragmaWarning(DiagLoc
, Specifier
, Ids
);
1101 // Parse the next specifier if there is a semicolon.
1102 if (Tok
.isNot(tok::semi
))
1108 if (Tok
.isNot(tok::r_paren
)) {
1109 PP
.Diag(Tok
, diag::warn_pragma_warning_expected
) << ")";
1114 if (Tok
.isNot(tok::eod
))
1115 PP
.Diag(Tok
, diag::ext_pp_extra_tokens_at_eol
) << "pragma warning";
1119 /// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
1120 struct PragmaIncludeAliasHandler
: public PragmaHandler
{
1121 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
1122 void HandlePragma(Preprocessor
&PP
, PragmaIntroducerKind Introducer
,
1123 Token
&IncludeAliasTok
) override
{
1124 PP
.HandlePragmaIncludeAlias(IncludeAliasTok
);
1128 /// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1129 /// extension. The syntax is:
1131 /// #pragma message(string)
1133 /// OR, in GCC mode:
1135 /// #pragma message string
1137 /// string is a string, which is fully macro expanded, and permits string
1138 /// concatenation, embedded escape characters, etc... See MSDN for more details.
1139 /// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1140 /// form as \#pragma message.
1141 struct PragmaMessageHandler
: public PragmaHandler
{
1143 const PPCallbacks::PragmaMessageKind Kind
;
1144 const StringRef Namespace
;
1146 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind
,
1147 bool PragmaNameOnly
= false) {
1149 case PPCallbacks::PMK_Message
:
1150 return PragmaNameOnly
? "message" : "pragma message";
1151 case PPCallbacks::PMK_Warning
:
1152 return PragmaNameOnly
? "warning" : "pragma warning";
1153 case PPCallbacks::PMK_Error
:
1154 return PragmaNameOnly
? "error" : "pragma error";
1156 llvm_unreachable("Unknown PragmaMessageKind!");
1160 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind
,
1161 StringRef Namespace
= StringRef())
1162 : PragmaHandler(PragmaKind(Kind
, true)), Kind(Kind
), Namespace(Namespace
) {}
1164 void HandlePragma(Preprocessor
&PP
, PragmaIntroducerKind Introducer
,
1165 Token
&Tok
) override
{
1166 SourceLocation MessageLoc
= Tok
.getLocation();
1168 bool ExpectClosingParen
= false;
1169 switch (Tok
.getKind()) {
1171 // We have a MSVC style pragma message.
1172 ExpectClosingParen
= true;
1176 case tok::string_literal
:
1177 // We have a GCC style pragma message, and we just read the string.
1180 PP
.Diag(MessageLoc
, diag::err_pragma_message_malformed
) << Kind
;
1184 std::string MessageString
;
1185 if (!PP
.FinishLexStringLiteral(Tok
, MessageString
, PragmaKind(Kind
),
1186 /*MacroExpansion=*/true))
1189 if (ExpectClosingParen
) {
1190 if (Tok
.isNot(tok::r_paren
)) {
1191 PP
.Diag(Tok
.getLocation(), diag::err_pragma_message_malformed
) << Kind
;
1194 PP
.Lex(Tok
); // eat the r_paren.
1197 if (Tok
.isNot(tok::eod
)) {
1198 PP
.Diag(Tok
.getLocation(), diag::err_pragma_message_malformed
) << Kind
;
1202 // Output the message.
1203 PP
.Diag(MessageLoc
, (Kind
== PPCallbacks::PMK_Error
)
1204 ? diag::err_pragma_message
1205 : diag::warn_pragma_message
) << MessageString
;
1207 // If the pragma is lexically sound, notify any interested PPCallbacks.
1208 if (PPCallbacks
*Callbacks
= PP
.getPPCallbacks())
1209 Callbacks
->PragmaMessage(MessageLoc
, Namespace
, Kind
, MessageString
);
1213 /// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
1214 /// macro on the top of the stack.
1215 struct PragmaPushMacroHandler
: public PragmaHandler
{
1216 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
1217 void HandlePragma(Preprocessor
&PP
, PragmaIntroducerKind Introducer
,
1218 Token
&PushMacroTok
) override
{
1219 PP
.HandlePragmaPushMacro(PushMacroTok
);
1224 /// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
1225 /// macro to the value on the top of the stack.
1226 struct PragmaPopMacroHandler
: public PragmaHandler
{
1227 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
1228 void HandlePragma(Preprocessor
&PP
, PragmaIntroducerKind Introducer
,
1229 Token
&PopMacroTok
) override
{
1230 PP
.HandlePragmaPopMacro(PopMacroTok
);
1234 // Pragma STDC implementations.
1236 /// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
1237 struct PragmaSTDC_FENV_ACCESSHandler
: public PragmaHandler
{
1238 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
1239 void HandlePragma(Preprocessor
&PP
, PragmaIntroducerKind Introducer
,
1240 Token
&Tok
) override
{
1241 tok::OnOffSwitch OOS
;
1242 if (PP
.LexOnOffSwitch(OOS
))
1244 if (OOS
== tok::OOS_ON
)
1245 PP
.Diag(Tok
, diag::warn_stdc_fenv_access_not_supported
);
1249 /// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
1250 struct PragmaSTDC_CX_LIMITED_RANGEHandler
: public PragmaHandler
{
1251 PragmaSTDC_CX_LIMITED_RANGEHandler()
1252 : PragmaHandler("CX_LIMITED_RANGE") {}
1253 void HandlePragma(Preprocessor
&PP
, PragmaIntroducerKind Introducer
,
1254 Token
&Tok
) override
{
1255 tok::OnOffSwitch OOS
;
1256 PP
.LexOnOffSwitch(OOS
);
1260 /// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
1261 struct PragmaSTDC_UnknownHandler
: public PragmaHandler
{
1262 PragmaSTDC_UnknownHandler() {}
1263 void HandlePragma(Preprocessor
&PP
, PragmaIntroducerKind Introducer
,
1264 Token
&UnknownTok
) override
{
1265 // C99 6.10.6p2, unknown forms are not allowed.
1266 PP
.Diag(UnknownTok
, diag::ext_stdc_pragma_ignored
);
1270 /// PragmaARCCFCodeAuditedHandler -
1271 /// \#pragma clang arc_cf_code_audited begin/end
1272 struct PragmaARCCFCodeAuditedHandler
: public PragmaHandler
{
1273 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
1274 void HandlePragma(Preprocessor
&PP
, PragmaIntroducerKind Introducer
,
1275 Token
&NameTok
) override
{
1276 SourceLocation Loc
= NameTok
.getLocation();
1281 // Lex the 'begin' or 'end'.
1282 PP
.LexUnexpandedToken(Tok
);
1283 const IdentifierInfo
*BeginEnd
= Tok
.getIdentifierInfo();
1284 if (BeginEnd
&& BeginEnd
->isStr("begin")) {
1286 } else if (BeginEnd
&& BeginEnd
->isStr("end")) {
1289 PP
.Diag(Tok
.getLocation(), diag::err_pp_arc_cf_code_audited_syntax
);
1293 // Verify that this is followed by EOD.
1294 PP
.LexUnexpandedToken(Tok
);
1295 if (Tok
.isNot(tok::eod
))
1296 PP
.Diag(Tok
, diag::ext_pp_extra_tokens_at_eol
) << "pragma";
1298 // The start location of the active audit.
1299 SourceLocation BeginLoc
= PP
.getPragmaARCCFCodeAuditedLoc();
1301 // The start location we want after processing this.
1302 SourceLocation NewLoc
;
1305 // Complain about attempts to re-enter an audit.
1306 if (BeginLoc
.isValid()) {
1307 PP
.Diag(Loc
, diag::err_pp_double_begin_of_arc_cf_code_audited
);
1308 PP
.Diag(BeginLoc
, diag::note_pragma_entered_here
);
1312 // Complain about attempts to leave an audit that doesn't exist.
1313 if (!BeginLoc
.isValid()) {
1314 PP
.Diag(Loc
, diag::err_pp_unmatched_end_of_arc_cf_code_audited
);
1317 NewLoc
= SourceLocation();
1320 PP
.setPragmaARCCFCodeAuditedLoc(NewLoc
);
1324 /// \brief Handle "\#pragma region [...]"
1328 /// #pragma region [optional name]
1329 /// #pragma endregion [optional comment]
1333 /// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1334 /// pragma, just skipped by compiler.
1335 struct PragmaRegionHandler
: public PragmaHandler
{
1336 PragmaRegionHandler(const char *pragma
) : PragmaHandler(pragma
) { }
1338 void HandlePragma(Preprocessor
&PP
, PragmaIntroducerKind Introducer
,
1339 Token
&NameTok
) override
{
1340 // #pragma region: endregion matches can be verified
1341 // __pragma(region): no sense, but ignored by msvc
1342 // _Pragma is not valid for MSVC, but there isn't any point
1343 // to handle a _Pragma differently.
1347 } // end anonymous namespace
1350 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
1351 /// \#pragma GCC poison/system_header/dependency and \#pragma once.
1352 void Preprocessor::RegisterBuiltinPragmas() {
1353 AddPragmaHandler(new PragmaOnceHandler());
1354 AddPragmaHandler(new PragmaMarkHandler());
1355 AddPragmaHandler(new PragmaPushMacroHandler());
1356 AddPragmaHandler(new PragmaPopMacroHandler());
1357 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message
));
1360 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1361 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1362 AddPragmaHandler("GCC", new PragmaDependencyHandler());
1363 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
1364 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning
,
1366 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error
,
1368 // #pragma clang ...
1369 AddPragmaHandler("clang", new PragmaPoisonHandler());
1370 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
1371 AddPragmaHandler("clang", new PragmaDebugHandler());
1372 AddPragmaHandler("clang", new PragmaDependencyHandler());
1373 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
1374 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
1376 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1377 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
1378 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
1381 if (LangOpts
.MicrosoftExt
) {
1382 AddPragmaHandler(new PragmaWarningHandler());
1383 AddPragmaHandler(new PragmaIncludeAliasHandler());
1384 AddPragmaHandler(new PragmaRegionHandler("region"));
1385 AddPragmaHandler(new PragmaRegionHandler("endregion"));
1389 /// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
1390 /// warn about those pragmas being unknown.
1391 void Preprocessor::IgnorePragmas() {
1392 AddPragmaHandler(new EmptyPragmaHandler());
1393 // Also ignore all pragmas in all namespaces created
1394 // in Preprocessor::RegisterBuiltinPragmas().
1395 AddPragmaHandler("GCC", new EmptyPragmaHandler());
1396 AddPragmaHandler("clang", new EmptyPragmaHandler());
1397 if (PragmaHandler
*NS
= PragmaHandlers
->FindHandler("STDC")) {
1398 // Preprocessor::RegisterBuiltinPragmas() already registers
1399 // PragmaSTDC_UnknownHandler as the empty handler, so remove it first,
1400 // otherwise there will be an assert about a duplicate handler.
1401 PragmaNamespace
*STDCNamespace
= NS
->getIfNamespace();
1402 assert(STDCNamespace
&&
1403 "Invalid namespace, registered as a regular pragma handler!");
1404 if (PragmaHandler
*Existing
= STDCNamespace
->FindHandler("", false)) {
1405 RemovePragmaHandler("STDC", Existing
);
1409 AddPragmaHandler("STDC", new EmptyPragmaHandler());