1 //===--- Pragma.cpp - Pragma registration and handling --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the PragmaHandler/PragmaTable interfaces and implements
11 // pragma related methods of the Preprocessor class.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Lex/Pragma.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/IdentifierTable.h"
18 #include "clang/Basic/SourceLocation.h"
19 #include "clang/Basic/SourceManager.h"
20 #include "clang/Basic/TokenKinds.h"
21 #include "clang/Lex/HeaderSearch.h"
22 #include "clang/Lex/LexDiagnostic.h"
23 #include "clang/Lex/LiteralSupport.h"
24 #include "clang/Lex/MacroInfo.h"
25 #include "clang/Lex/PPCallbacks.h"
26 #include "clang/Lex/Preprocessor.h"
27 #include "clang/Lex/PreprocessorLexer.h"
28 #include "clang/Lex/PTHLexer.h"
29 #include "clang/Lex/Token.h"
30 #include "clang/Lex/TokenLexer.h"
31 #include "llvm/ADT/ArrayRef.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallString.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/Support/CrashRecoveryContext.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/ErrorHandling.h"
47 using namespace clang;
49 // Out-of-line destructor to provide a home for the class.
50 PragmaHandler::~PragmaHandler() {
53 //===----------------------------------------------------------------------===//
54 // EmptyPragmaHandler Implementation.
55 //===----------------------------------------------------------------------===//
57 EmptyPragmaHandler::EmptyPragmaHandler(StringRef Name) : PragmaHandler(Name) {}
59 void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
60 PragmaIntroducerKind Introducer,
63 //===----------------------------------------------------------------------===//
64 // PragmaNamespace Implementation.
65 //===----------------------------------------------------------------------===//
67 PragmaNamespace::~PragmaNamespace() {
68 llvm::DeleteContainerSeconds(Handlers);
71 /// FindHandler - Check to see if there is already a handler for the
72 /// specified name. If not, return the handler for the null identifier if it
73 /// exists, otherwise return null. If IgnoreNull is true (the default) then
74 /// the null handler isn't returned on failure to match.
75 PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
76 bool IgnoreNull) const {
77 if (PragmaHandler *Handler = Handlers.lookup(Name))
79 return IgnoreNull ? nullptr : Handlers.lookup(StringRef());
82 void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
83 assert(!Handlers.lookup(Handler->getName()) &&
84 "A handler with this name is already registered in this namespace");
85 Handlers[Handler->getName()] = Handler;
88 void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
89 assert(Handlers.lookup(Handler->getName()) &&
90 "Handler not registered in this namespace");
91 Handlers.erase(Handler->getName());
94 void PragmaNamespace::HandlePragma(Preprocessor &PP,
95 PragmaIntroducerKind Introducer,
97 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
98 // expand it, the user can have a STDC #define, that should not affect this.
99 PP.LexUnexpandedToken(Tok);
101 // Get the handler for this token. If there is no handler, ignore the pragma.
102 PragmaHandler *Handler
103 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
105 /*IgnoreNull=*/false);
107 PP.Diag(Tok, diag::warn_pragma_ignored);
111 // Otherwise, pass it down.
112 Handler->HandlePragma(PP, Introducer, Tok);
115 //===----------------------------------------------------------------------===//
116 // Preprocessor Pragma Directive Handling.
117 //===----------------------------------------------------------------------===//
119 /// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the
120 /// rest of the pragma, passing it to the registered pragma handlers.
121 void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc,
122 PragmaIntroducerKind Introducer) {
124 Callbacks->PragmaDirective(IntroducerLoc, Introducer);
131 // Invoke the first level of pragma handlers which reads the namespace id.
133 PragmaHandlers->HandlePragma(*this, Introducer, Tok);
135 // If the pragma handler didn't read the rest of the line, consume it now.
136 if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
137 || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
138 DiscardUntilEndOfDirective();
143 /// \brief Helper class for \see Preprocessor::Handle_Pragma.
144 class LexingFor_PragmaRAII {
146 bool InMacroArgPreExpansion;
152 LexingFor_PragmaRAII(Preprocessor &PP, bool InMacroArgPreExpansion,
154 : PP(PP), InMacroArgPreExpansion(InMacroArgPreExpansion),
155 Failed(false), OutTok(Tok) {
156 if (InMacroArgPreExpansion) {
158 PP.EnableBacktrackAtThisPos();
162 ~LexingFor_PragmaRAII() {
163 if (InMacroArgPreExpansion) {
164 // When committing/backtracking the cached pragma tokens in a macro
165 // argument pre-expansion we want to ensure that either the tokens which
166 // have been committed will be removed from the cache or that the tokens
167 // over which we just backtracked won't remain in the cache after they're
168 // consumed and that the caching will stop after consuming them.
169 // Otherwise the caching will interfere with the way macro expansion
170 // works, because we will continue to cache tokens after consuming the
171 // backtracked tokens, which shouldn't happen when we're dealing with
172 // macro argument pre-expansion.
173 auto CachedTokenRange = PP.LastCachedTokenRange();
175 PP.CommitBacktrackedTokens();
180 PP.EraseCachedTokens(CachedTokenRange);
189 } // end anonymous namespace
191 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
192 /// return the first token after the directive. The _Pragma token has just
193 /// been read into 'Tok'.
194 void Preprocessor::Handle_Pragma(Token &Tok) {
196 // This works differently if we are pre-expanding a macro argument.
197 // In that case we don't actually "activate" the pragma now, we only lex it
198 // until we are sure it is lexically correct and then we backtrack so that
199 // we activate the pragma whenever we encounter the tokens again in the token
200 // stream. This ensures that we will activate it in the correct location
201 // or that we will ignore it if it never enters the token stream, e.g:
204 // #define INACTIVE(x) EMPTY(x)
205 // INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\""))
207 LexingFor_PragmaRAII _PragmaLexing(*this, InMacroArgPreExpansion, Tok);
209 // Remember the pragma token location.
210 SourceLocation PragmaLoc = Tok.getLocation();
214 if (Tok.isNot(tok::l_paren)) {
215 Diag(PragmaLoc, diag::err__Pragma_malformed);
216 return _PragmaLexing.failed();
221 if (!tok::isStringLiteral(Tok.getKind())) {
222 Diag(PragmaLoc, diag::err__Pragma_malformed);
223 // Skip bad tokens, and the ')', if present.
224 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
226 while (Tok.isNot(tok::r_paren) &&
227 !Tok.isAtStartOfLine() &&
230 if (Tok.is(tok::r_paren))
232 return _PragmaLexing.failed();
235 if (Tok.hasUDSuffix()) {
236 Diag(Tok, diag::err_invalid_string_udl);
237 // Skip this token, and the ')', if present.
239 if (Tok.is(tok::r_paren))
241 return _PragmaLexing.failed();
244 // Remember the string.
249 if (Tok.isNot(tok::r_paren)) {
250 Diag(PragmaLoc, diag::err__Pragma_malformed);
251 return _PragmaLexing.failed();
254 if (InMacroArgPreExpansion)
257 SourceLocation RParenLoc = Tok.getLocation();
258 std::string StrVal = getSpelling(StrTok);
260 // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1:
261 // "The string literal is destringized by deleting any encoding prefix,
262 // deleting the leading and trailing double-quotes, replacing each escape
263 // sequence \" by a double-quote, and replacing each escape sequence \\ by a
264 // single backslash."
265 if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
266 (StrVal[0] == 'u' && StrVal[1] != '8'))
267 StrVal.erase(StrVal.begin());
268 else if (StrVal[0] == 'u')
269 StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
271 if (StrVal[0] == 'R') {
272 // FIXME: C++11 does not specify how to handle raw-string-literals here.
273 // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
274 assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
275 "Invalid raw string token!");
277 // Measure the length of the d-char-sequence.
278 unsigned NumDChars = 0;
279 while (StrVal[2 + NumDChars] != '(') {
280 assert(NumDChars < (StrVal.size() - 5) / 2 &&
281 "Invalid raw string token!");
284 assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
286 // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
288 StrVal.erase(0, 2 + NumDChars);
289 StrVal.erase(StrVal.size() - 1 - NumDChars);
291 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
292 "Invalid string token!");
294 // Remove escaped quotes and escapes.
295 unsigned ResultPos = 1;
296 for (size_t i = 1, e = StrVal.size() - 1; i != e; ++i) {
297 // Skip escapes. \\ -> '\' and \" -> '"'.
298 if (StrVal[i] == '\\' && i + 1 < e &&
299 (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
301 StrVal[ResultPos++] = StrVal[i];
303 StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
306 // Remove the front quote, replacing it with a space, so that the pragma
307 // contents appear to have a space before them.
310 // Replace the terminating quote with a \n.
311 StrVal[StrVal.size()-1] = '\n';
313 // Plop the string (including the newline and trailing null) into a buffer
314 // where we can lex it.
317 CreateString(StrVal, TmpTok);
318 SourceLocation TokLoc = TmpTok.getLocation();
320 // Make and enter a lexer object so that we lex and expand the tokens just
322 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
323 StrVal.size(), *this);
325 EnterSourceFileWithLexer(TL, nullptr);
327 // With everything set up, lex this as a #pragma directive.
328 HandlePragmaDirective(PragmaLoc, PIK__Pragma);
330 // Finally, return whatever came after the pragma directive.
334 /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
335 /// is not enclosed within a string literal.
336 void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
337 // Remember the pragma token location.
338 SourceLocation PragmaLoc = Tok.getLocation();
342 if (Tok.isNot(tok::l_paren)) {
343 Diag(PragmaLoc, diag::err__Pragma_malformed);
347 // Get the tokens enclosed within the __pragma(), as well as the final ')'.
348 SmallVector<Token, 32> PragmaToks;
351 while (Tok.isNot(tok::eof)) {
352 PragmaToks.push_back(Tok);
353 if (Tok.is(tok::l_paren))
355 else if (Tok.is(tok::r_paren) && NumParens-- == 0)
360 if (Tok.is(tok::eof)) {
361 Diag(PragmaLoc, diag::err_unterminated___pragma);
365 PragmaToks.front().setFlag(Token::LeadingSpace);
367 // Replace the ')' with an EOD to mark the end of the pragma.
368 PragmaToks.back().setKind(tok::eod);
370 Token *TokArray = new Token[PragmaToks.size()];
371 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
373 // Push the tokens onto the stack.
374 EnterTokenStream(TokArray, PragmaToks.size(), true, true);
376 // With everything set up, lex this as a #pragma directive.
377 HandlePragmaDirective(PragmaLoc, PIK___pragma);
379 // Finally, return whatever came after the pragma directive.
383 /// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
385 void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
386 // Don't honor the 'once' when handling the primary source file, unless
387 // this is a prefix to a TU, which indicates we're generating a PCH file, or
388 // when the main file is a header (e.g. when -xc-header is provided on the
390 if (isInPrimaryFile() && TUKind != TU_Prefix && !getLangOpts().IsHeaderFile) {
391 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
395 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
396 // Mark the file as a once-only file now.
397 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
400 void Preprocessor::HandlePragmaMark() {
401 assert(CurPPLexer && "No current lexer?");
403 CurLexer->ReadToEndOfLine();
405 CurPTHLexer->DiscardToEndOfLine();
408 /// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
410 void Preprocessor::HandlePragmaPoison() {
414 // Read the next token to poison. While doing this, pretend that we are
415 // skipping while reading the identifier to poison.
416 // This avoids errors on code like:
417 // #pragma GCC poison X
418 // #pragma GCC poison X
419 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
420 LexUnexpandedToken(Tok);
421 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
423 // If we reached the end of line, we're done.
424 if (Tok.is(tok::eod)) return;
426 // Can only poison identifiers.
427 if (Tok.isNot(tok::raw_identifier)) {
428 Diag(Tok, diag::err_pp_invalid_poison);
432 // Look up the identifier info for the token. We disabled identifier lookup
433 // by saying we're skipping contents, so we need to do this manually.
434 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
437 if (II->isPoisoned()) continue;
439 // If this is a macro identifier, emit a warning.
440 if (isMacroDefined(II))
441 Diag(Tok, diag::pp_poisoning_existing_macro);
443 // Finally, poison it!
446 II->setChangedSinceDeserialization();
450 /// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
451 /// that the whole directive has been parsed.
452 void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
453 if (isInPrimaryFile()) {
454 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
458 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
459 PreprocessorLexer *TheLexer = getCurrentFileLexer();
461 // Mark the file as a system header.
462 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
465 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
466 if (PLoc.isInvalid())
469 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
471 // Notify the client, if desired, that we are in a new source file.
473 Callbacks->FileChanged(SysHeaderTok.getLocation(),
474 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
476 // Emit a line marker. This will change any source locations from this point
477 // forward to realize they are in a system header.
478 // Create a line note with this information.
479 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine() + 1,
480 FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
484 /// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
486 void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
488 CurPPLexer->LexIncludeFilename(FilenameTok);
490 // If the token kind is EOD, the error has already been diagnosed.
491 if (FilenameTok.is(tok::eod))
494 // Reserve a buffer to get the spelling.
495 SmallString<128> FilenameBuffer;
496 bool Invalid = false;
497 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
502 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
503 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
505 if (Filename.empty())
508 // Search include directories for this file.
509 const DirectoryLookup *CurDir;
510 const FileEntry *File =
511 LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
512 nullptr, CurDir, nullptr, nullptr, nullptr, nullptr);
514 if (!SuppressIncludeNotFoundError)
515 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
519 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
521 // If this file is older than the file it depends on, emit a diagnostic.
522 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
523 // Lex tokens at the end of the message and include them in the message.
526 while (DependencyTok.isNot(tok::eod)) {
527 Message += getSpelling(DependencyTok) + " ";
531 // Remove the trailing ' ' if present.
532 if (!Message.empty())
533 Message.erase(Message.end()-1);
534 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
538 /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
539 /// Return the IdentifierInfo* associated with the macro to push or pop.
540 IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
541 // Remember the pragma token location.
542 Token PragmaTok = Tok;
546 if (Tok.isNot(tok::l_paren)) {
547 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
548 << getSpelling(PragmaTok);
552 // Read the macro name string.
554 if (Tok.isNot(tok::string_literal)) {
555 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
556 << getSpelling(PragmaTok);
560 if (Tok.hasUDSuffix()) {
561 Diag(Tok, diag::err_invalid_string_udl);
565 // Remember the macro string.
566 std::string StrVal = getSpelling(Tok);
570 if (Tok.isNot(tok::r_paren)) {
571 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
572 << getSpelling(PragmaTok);
576 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
577 "Invalid string token!");
579 // Create a Token from the string.
581 MacroTok.startToken();
582 MacroTok.setKind(tok::raw_identifier);
583 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
585 // Get the IdentifierInfo of MacroToPushTok.
586 return LookUpIdentifierInfo(MacroTok);
589 /// \brief Handle \#pragma push_macro.
593 /// #pragma push_macro("macro")
595 void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
596 // Parse the pragma directive and get the macro IdentifierInfo*.
597 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
598 if (!IdentInfo) return;
600 // Get the MacroInfo associated with IdentInfo.
601 MacroInfo *MI = getMacroInfo(IdentInfo);
604 // Allow the original MacroInfo to be redefined later.
605 MI->setIsAllowRedefinitionsWithoutWarning(true);
608 // Push the cloned MacroInfo so we can retrieve it later.
609 PragmaPushMacroInfo[IdentInfo].push_back(MI);
612 /// \brief Handle \#pragma pop_macro.
616 /// #pragma pop_macro("macro")
618 void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
619 SourceLocation MessageLoc = PopMacroTok.getLocation();
621 // Parse the pragma directive and get the macro IdentifierInfo*.
622 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
623 if (!IdentInfo) return;
625 // Find the vector<MacroInfo*> associated with the macro.
626 llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
627 PragmaPushMacroInfo.find(IdentInfo);
628 if (iter != PragmaPushMacroInfo.end()) {
629 // Forget the MacroInfo currently associated with IdentInfo.
630 if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
631 if (MI->isWarnIfUnused())
632 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
633 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
636 // Get the MacroInfo we want to reinstall.
637 MacroInfo *MacroToReInstall = iter->second.back();
639 if (MacroToReInstall)
640 // Reinstall the previously pushed macro.
641 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
643 // Pop PragmaPushMacroInfo stack.
644 iter->second.pop_back();
645 if (iter->second.empty())
646 PragmaPushMacroInfo.erase(iter);
648 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
649 << IdentInfo->getName();
653 void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
654 // We will either get a quoted filename or a bracketed filename, and we
655 // have to track which we got. The first filename is the source name,
656 // and the second name is the mapped filename. If the first is quoted,
657 // the second must be as well (cannot mix and match quotes and brackets).
659 // Get the open paren
661 if (Tok.isNot(tok::l_paren)) {
662 Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
666 // We expect either a quoted string literal, or a bracketed name
667 Token SourceFilenameTok;
668 CurPPLexer->LexIncludeFilename(SourceFilenameTok);
669 if (SourceFilenameTok.is(tok::eod)) {
670 // The diagnostic has already been handled
674 StringRef SourceFileName;
675 SmallString<128> FileNameBuffer;
676 if (SourceFilenameTok.is(tok::string_literal) ||
677 SourceFilenameTok.is(tok::angle_string_literal)) {
678 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
679 } else if (SourceFilenameTok.is(tok::less)) {
680 // This could be a path instead of just a name
681 FileNameBuffer.push_back('<');
683 if (ConcatenateIncludeName(FileNameBuffer, End))
684 return; // Diagnostic already emitted
685 SourceFileName = FileNameBuffer;
687 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
690 FileNameBuffer.clear();
692 // Now we expect a comma, followed by another include name
694 if (Tok.isNot(tok::comma)) {
695 Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
699 Token ReplaceFilenameTok;
700 CurPPLexer->LexIncludeFilename(ReplaceFilenameTok);
701 if (ReplaceFilenameTok.is(tok::eod)) {
702 // The diagnostic has already been handled
706 StringRef ReplaceFileName;
707 if (ReplaceFilenameTok.is(tok::string_literal) ||
708 ReplaceFilenameTok.is(tok::angle_string_literal)) {
709 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
710 } else if (ReplaceFilenameTok.is(tok::less)) {
711 // This could be a path instead of just a name
712 FileNameBuffer.push_back('<');
714 if (ConcatenateIncludeName(FileNameBuffer, End))
715 return; // Diagnostic already emitted
716 ReplaceFileName = FileNameBuffer;
718 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
722 // Finally, we expect the closing paren
724 if (Tok.isNot(tok::r_paren)) {
725 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
729 // Now that we have the source and target filenames, we need to make sure
730 // they're both of the same type (angled vs non-angled)
731 StringRef OriginalSource = SourceFileName;
733 bool SourceIsAngled =
734 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
736 bool ReplaceIsAngled =
737 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
739 if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
740 (SourceIsAngled != ReplaceIsAngled)) {
743 DiagID = diag::warn_pragma_include_alias_mismatch_angle;
745 DiagID = diag::warn_pragma_include_alias_mismatch_quote;
747 Diag(SourceFilenameTok.getLocation(), DiagID)
754 // Now we can let the include handler know about this mapping
755 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
758 // Lex a component of a module name: either an identifier or a string literal;
759 // for components that can be expressed both ways, the two forms are equivalent.
760 static bool LexModuleNameComponent(
761 Preprocessor &PP, Token &Tok,
762 std::pair<IdentifierInfo *, SourceLocation> &ModuleNameComponent,
764 PP.LexUnexpandedToken(Tok);
765 if (Tok.is(tok::string_literal) && !Tok.hasUDSuffix()) {
766 StringLiteralParser Literal(Tok, PP);
767 if (Literal.hadError)
769 ModuleNameComponent = std::make_pair(
770 PP.getIdentifierInfo(Literal.GetString()), Tok.getLocation());
771 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) {
772 ModuleNameComponent =
773 std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation());
775 PP.Diag(Tok.getLocation(), diag::err_pp_expected_module_name) << First;
781 static bool LexModuleName(
782 Preprocessor &PP, Token &Tok,
783 llvm::SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>>
786 std::pair<IdentifierInfo*, SourceLocation> NameComponent;
787 if (LexModuleNameComponent(PP, Tok, NameComponent, ModuleName.empty()))
789 ModuleName.push_back(NameComponent);
791 PP.LexUnexpandedToken(Tok);
792 if (Tok.isNot(tok::period))
797 void Preprocessor::HandlePragmaModuleBuild(Token &Tok) {
798 SourceLocation Loc = Tok.getLocation();
800 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
801 if (LexModuleNameComponent(*this, Tok, ModuleNameLoc, true))
803 IdentifierInfo *ModuleName = ModuleNameLoc.first;
805 LexUnexpandedToken(Tok);
806 if (Tok.isNot(tok::eod)) {
807 Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
808 DiscardUntilEndOfDirective();
812 // FIXME: Support this somehow?
813 Diag(Loc, diag::err_pp_module_build_pth);
817 CurLexer->LexingRawMode = true;
819 auto TryConsumeIdentifier = [&](StringRef Ident) -> bool {
820 if (Tok.getKind() != tok::raw_identifier ||
821 Tok.getRawIdentifier() != Ident)
827 // Scan forward looking for the end of the module.
828 const char *Start = CurLexer->getBufferLocation();
829 const char *End = nullptr;
830 unsigned NestingLevel = 1;
832 End = CurLexer->getBufferLocation();
835 if (Tok.is(tok::eof)) {
836 Diag(Loc, diag::err_pp_module_build_missing_end);
840 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) {
841 // Token was part of module; keep going.
845 // We hit something directive-shaped; check to see if this is the end
846 // of the module build.
847 CurLexer->ParsingPreprocessorDirective = true;
849 if (TryConsumeIdentifier("pragma") && TryConsumeIdentifier("clang") &&
850 TryConsumeIdentifier("module")) {
851 if (TryConsumeIdentifier("build"))
852 // #pragma clang module build -> entering a nested module build.
854 else if (TryConsumeIdentifier("endbuild")) {
855 // #pragma clang module endbuild -> leaving a module build.
856 if (--NestingLevel == 0)
859 // We should either be looking at the EOD or more of the current directive
860 // preceding the EOD. Either way we can ignore this token and keep going.
861 assert(Tok.getKind() != tok::eof && "missing EOD before EOF");
865 CurLexer->LexingRawMode = false;
867 // Load the extracted text as a preprocessed module.
868 assert(CurLexer->getBuffer().begin() <= Start &&
869 Start <= CurLexer->getBuffer().end() &&
870 CurLexer->getBuffer().begin() <= End &&
871 End <= CurLexer->getBuffer().end() &&
872 "module source range not contained within same file buffer");
873 TheModuleLoader.loadModuleFromSource(Loc, ModuleName->getName(),
874 StringRef(Start, End - Start));
877 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
878 /// If 'Namespace' is non-null, then it is a token required to exist on the
879 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
880 void Preprocessor::AddPragmaHandler(StringRef Namespace,
881 PragmaHandler *Handler) {
882 PragmaNamespace *InsertNS = PragmaHandlers.get();
884 // If this is specified to be in a namespace, step down into it.
885 if (!Namespace.empty()) {
886 // If there is already a pragma handler with the name of this namespace,
887 // we either have an error (directive with the same name as a namespace) or
888 // we already have the namespace to insert into.
889 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
890 InsertNS = Existing->getIfNamespace();
891 assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
892 " handler with the same name!");
894 // Otherwise, this namespace doesn't exist yet, create and insert the
896 InsertNS = new PragmaNamespace(Namespace);
897 PragmaHandlers->AddPragma(InsertNS);
901 // Check to make sure we don't already have a pragma for this identifier.
902 assert(!InsertNS->FindHandler(Handler->getName()) &&
903 "Pragma handler already exists for this identifier!");
904 InsertNS->AddPragma(Handler);
907 /// RemovePragmaHandler - Remove the specific pragma handler from the
908 /// preprocessor. If \arg Namespace is non-null, then it should be the
909 /// namespace that \arg Handler was added to. It is an error to remove
910 /// a handler that has not been registered.
911 void Preprocessor::RemovePragmaHandler(StringRef Namespace,
912 PragmaHandler *Handler) {
913 PragmaNamespace *NS = PragmaHandlers.get();
915 // If this is specified to be in a namespace, step down into it.
916 if (!Namespace.empty()) {
917 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
918 assert(Existing && "Namespace containing handler does not exist!");
920 NS = Existing->getIfNamespace();
921 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
924 NS->RemovePragmaHandler(Handler);
926 // If this is a non-default namespace and it is now empty, remove it.
927 if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
928 PragmaHandlers->RemovePragmaHandler(NS);
933 bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
935 LexUnexpandedToken(Tok);
937 if (Tok.isNot(tok::identifier)) {
938 Diag(Tok, diag::ext_on_off_switch_syntax);
941 IdentifierInfo *II = Tok.getIdentifierInfo();
943 Result = tok::OOS_ON;
944 else if (II->isStr("OFF"))
945 Result = tok::OOS_OFF;
946 else if (II->isStr("DEFAULT"))
947 Result = tok::OOS_DEFAULT;
949 Diag(Tok, diag::ext_on_off_switch_syntax);
953 // Verify that this is followed by EOD.
954 LexUnexpandedToken(Tok);
955 if (Tok.isNot(tok::eod))
956 Diag(Tok, diag::ext_pragma_syntax_eod);
962 /// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
963 struct PragmaOnceHandler : public PragmaHandler {
964 PragmaOnceHandler() : PragmaHandler("once") {}
965 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
966 Token &OnceTok) override {
967 PP.CheckEndOfDirective("pragma once");
968 PP.HandlePragmaOnce(OnceTok);
972 /// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
973 /// rest of the line is not lexed.
974 struct PragmaMarkHandler : public PragmaHandler {
975 PragmaMarkHandler() : PragmaHandler("mark") {}
977 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
978 Token &MarkTok) override {
979 PP.HandlePragmaMark();
983 /// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
984 struct PragmaPoisonHandler : public PragmaHandler {
985 PragmaPoisonHandler() : PragmaHandler("poison") {}
987 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
988 Token &PoisonTok) override {
989 PP.HandlePragmaPoison();
993 /// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
994 /// as a system header, which silences warnings in it.
995 struct PragmaSystemHeaderHandler : public PragmaHandler {
996 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
998 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
999 Token &SHToken) override {
1000 PP.HandlePragmaSystemHeader(SHToken);
1001 PP.CheckEndOfDirective("pragma");
1005 struct PragmaDependencyHandler : public PragmaHandler {
1006 PragmaDependencyHandler() : PragmaHandler("dependency") {}
1008 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1009 Token &DepToken) override {
1010 PP.HandlePragmaDependency(DepToken);
1014 struct PragmaDebugHandler : public PragmaHandler {
1015 PragmaDebugHandler() : PragmaHandler("__debug") {}
1017 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1018 Token &DepToken) override {
1020 PP.LexUnexpandedToken(Tok);
1021 if (Tok.isNot(tok::identifier)) {
1022 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1025 IdentifierInfo *II = Tok.getIdentifierInfo();
1027 if (II->isStr("assert")) {
1028 llvm_unreachable("This is an assertion!");
1029 } else if (II->isStr("crash")) {
1031 } else if (II->isStr("parser_crash")) {
1033 Crasher.startToken();
1034 Crasher.setKind(tok::annot_pragma_parser_crash);
1035 Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
1036 PP.EnterToken(Crasher);
1037 } else if (II->isStr("dump")) {
1039 PP.LexUnexpandedToken(Identifier);
1040 if (auto *DumpII = Identifier.getIdentifierInfo()) {
1042 DumpAnnot.startToken();
1043 DumpAnnot.setKind(tok::annot_pragma_dump);
1044 DumpAnnot.setAnnotationRange(
1045 SourceRange(Tok.getLocation(), Identifier.getLocation()));
1046 DumpAnnot.setAnnotationValue(DumpII);
1047 PP.DiscardUntilEndOfDirective();
1048 PP.EnterToken(DumpAnnot);
1050 PP.Diag(Identifier, diag::warn_pragma_debug_missing_argument)
1053 } else if (II->isStr("llvm_fatal_error")) {
1054 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
1055 } else if (II->isStr("llvm_unreachable")) {
1056 llvm_unreachable("#pragma clang __debug llvm_unreachable");
1057 } else if (II->isStr("macro")) {
1059 PP.LexUnexpandedToken(MacroName);
1060 auto *MacroII = MacroName.getIdentifierInfo();
1062 PP.dumpMacroInfo(MacroII);
1064 PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument)
1066 } else if (II->isStr("overflow_stack")) {
1067 DebugOverflowStack();
1068 } else if (II->isStr("handle_crash")) {
1069 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
1072 } else if (II->isStr("captured")) {
1075 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
1079 PPCallbacks *Callbacks = PP.getPPCallbacks();
1081 Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
1084 void HandleCaptured(Preprocessor &PP) {
1085 // Skip if emitting preprocessed output.
1086 if (PP.isPreprocessedOutput())
1090 PP.LexUnexpandedToken(Tok);
1092 if (Tok.isNot(tok::eod)) {
1093 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
1094 << "pragma clang __debug captured";
1098 SourceLocation NameLoc = Tok.getLocation();
1099 MutableArrayRef<Token> Toks(
1100 PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
1101 Toks[0].startToken();
1102 Toks[0].setKind(tok::annot_pragma_captured);
1103 Toks[0].setLocation(NameLoc);
1105 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
1108 // Disable MSVC warning about runtime stack overflow.
1110 #pragma warning(disable : 4717)
1112 static void DebugOverflowStack(void (*P)() = nullptr) {
1113 void (*volatile Self)(void(*P)()) = DebugOverflowStack;
1114 Self(reinterpret_cast<void(*)()>(Self));
1117 #pragma warning(default : 4717)
1122 /// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
1123 struct PragmaDiagnosticHandler : public PragmaHandler {
1125 const char *Namespace;
1128 explicit PragmaDiagnosticHandler(const char *NS) :
1129 PragmaHandler("diagnostic"), Namespace(NS) {}
1131 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1132 Token &DiagToken) override {
1133 SourceLocation DiagLoc = DiagToken.getLocation();
1135 PP.LexUnexpandedToken(Tok);
1136 if (Tok.isNot(tok::identifier)) {
1137 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1140 IdentifierInfo *II = Tok.getIdentifierInfo();
1141 PPCallbacks *Callbacks = PP.getPPCallbacks();
1143 if (II->isStr("pop")) {
1144 if (!PP.getDiagnostics().popMappings(DiagLoc))
1145 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
1147 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
1149 } else if (II->isStr("push")) {
1150 PP.getDiagnostics().pushMappings(DiagLoc);
1152 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
1156 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
1157 .Case("ignored", diag::Severity::Ignored)
1158 .Case("warning", diag::Severity::Warning)
1159 .Case("error", diag::Severity::Error)
1160 .Case("fatal", diag::Severity::Fatal)
1161 .Default(diag::Severity());
1163 if (SV == diag::Severity()) {
1164 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1168 PP.LexUnexpandedToken(Tok);
1169 SourceLocation StringLoc = Tok.getLocation();
1171 std::string WarningName;
1172 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
1173 /*MacroExpansion=*/false))
1176 if (Tok.isNot(tok::eod)) {
1177 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1181 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1182 (WarningName[1] != 'W' && WarningName[1] != 'R')) {
1183 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
1187 diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1188 : diag::Flavor::Remark;
1189 StringRef Group = StringRef(WarningName).substr(2);
1190 bool unknownDiag = false;
1191 if (Group == "everything") {
1192 // Special handling for pragma clang diagnostic ... "-Weverything".
1193 // There is no formal group named "everything", so there has to be a
1194 // special case for it.
1195 PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc);
1197 unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV,
1200 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1203 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
1207 /// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1208 /// diagnostics, so we don't really implement this pragma. We parse it and
1209 /// ignore it to avoid -Wunknown-pragma warnings.
1210 struct PragmaWarningHandler : public PragmaHandler {
1211 PragmaWarningHandler() : PragmaHandler("warning") {}
1213 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1214 Token &Tok) override {
1215 // Parse things like:
1218 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
1219 SourceLocation DiagLoc = Tok.getLocation();
1220 PPCallbacks *Callbacks = PP.getPPCallbacks();
1223 if (Tok.isNot(tok::l_paren)) {
1224 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1229 IdentifierInfo *II = Tok.getIdentifierInfo();
1231 if (II && II->isStr("push")) {
1232 // #pragma warning( push[ ,n ] )
1235 if (Tok.is(tok::comma)) {
1238 if (Tok.is(tok::numeric_constant) &&
1239 PP.parseSimpleIntegerLiteral(Tok, Value))
1241 if (Level < 0 || Level > 4) {
1242 PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1247 Callbacks->PragmaWarningPush(DiagLoc, Level);
1248 } else if (II && II->isStr("pop")) {
1249 // #pragma warning( pop )
1252 Callbacks->PragmaWarningPop(DiagLoc);
1254 // #pragma warning( warning-specifier : warning-number-list
1255 // [; warning-specifier : warning-number-list...] )
1257 II = Tok.getIdentifierInfo();
1258 if (!II && !Tok.is(tok::numeric_constant)) {
1259 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1263 // Figure out which warning specifier this is.
1264 bool SpecifierValid;
1265 StringRef Specifier;
1266 llvm::SmallString<1> SpecifierBuf;
1268 Specifier = II->getName();
1269 SpecifierValid = llvm::StringSwitch<bool>(Specifier)
1270 .Cases("default", "disable", "error", "once",
1273 // If we read a correct specifier, snatch next token (that should be
1274 // ":", checked later).
1278 // Token is a numeric constant. It should be either 1, 2, 3 or 4.
1280 Specifier = PP.getSpelling(Tok, SpecifierBuf);
1281 if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
1282 SpecifierValid = (Value >= 1) && (Value <= 4);
1284 SpecifierValid = false;
1285 // Next token already snatched by parseSimpleIntegerLiteral.
1288 if (!SpecifierValid) {
1289 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1292 if (Tok.isNot(tok::colon)) {
1293 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1297 // Collect the warning ids.
1298 SmallVector<int, 4> Ids;
1300 while (Tok.is(tok::numeric_constant)) {
1302 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
1303 Value > std::numeric_limits<int>::max()) {
1304 PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1307 Ids.push_back(int(Value));
1310 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1312 // Parse the next specifier if there is a semicolon.
1313 if (Tok.isNot(tok::semi))
1319 if (Tok.isNot(tok::r_paren)) {
1320 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1325 if (Tok.isNot(tok::eod))
1326 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1330 /// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
1331 struct PragmaIncludeAliasHandler : public PragmaHandler {
1332 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
1333 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1334 Token &IncludeAliasTok) override {
1335 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
1339 /// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1340 /// extension. The syntax is:
1342 /// #pragma message(string)
1344 /// OR, in GCC mode:
1346 /// #pragma message string
1348 /// string is a string, which is fully macro expanded, and permits string
1349 /// concatenation, embedded escape characters, etc... See MSDN for more details.
1350 /// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1351 /// form as \#pragma message.
1352 struct PragmaMessageHandler : public PragmaHandler {
1354 const PPCallbacks::PragmaMessageKind Kind;
1355 const StringRef Namespace;
1357 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1358 bool PragmaNameOnly = false) {
1360 case PPCallbacks::PMK_Message:
1361 return PragmaNameOnly ? "message" : "pragma message";
1362 case PPCallbacks::PMK_Warning:
1363 return PragmaNameOnly ? "warning" : "pragma warning";
1364 case PPCallbacks::PMK_Error:
1365 return PragmaNameOnly ? "error" : "pragma error";
1367 llvm_unreachable("Unknown PragmaMessageKind!");
1371 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1372 StringRef Namespace = StringRef())
1373 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), Namespace(Namespace) {}
1375 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1376 Token &Tok) override {
1377 SourceLocation MessageLoc = Tok.getLocation();
1379 bool ExpectClosingParen = false;
1380 switch (Tok.getKind()) {
1382 // We have a MSVC style pragma message.
1383 ExpectClosingParen = true;
1387 case tok::string_literal:
1388 // We have a GCC style pragma message, and we just read the string.
1391 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1395 std::string MessageString;
1396 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1397 /*MacroExpansion=*/true))
1400 if (ExpectClosingParen) {
1401 if (Tok.isNot(tok::r_paren)) {
1402 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1405 PP.Lex(Tok); // eat the r_paren.
1408 if (Tok.isNot(tok::eod)) {
1409 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1413 // Output the message.
1414 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1415 ? diag::err_pragma_message
1416 : diag::warn_pragma_message) << MessageString;
1418 // If the pragma is lexically sound, notify any interested PPCallbacks.
1419 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1420 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
1424 /// Handle the clang \#pragma module import extension. The syntax is:
1426 /// #pragma clang module import some.module.name
1428 struct PragmaModuleImportHandler : public PragmaHandler {
1429 PragmaModuleImportHandler() : PragmaHandler("import") {}
1431 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1432 Token &Tok) override {
1433 SourceLocation ImportLoc = Tok.getLocation();
1435 // Read the module name.
1436 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1438 if (LexModuleName(PP, Tok, ModuleName))
1441 if (Tok.isNot(tok::eod))
1442 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1444 // If we have a non-empty module path, load the named module.
1446 PP.getModuleLoader().loadModule(ImportLoc, ModuleName, Module::Hidden,
1447 /*IsIncludeDirective=*/false);
1451 PP.makeModuleVisible(Imported, ImportLoc);
1452 PP.EnterAnnotationToken(SourceRange(ImportLoc, ModuleName.back().second),
1453 tok::annot_module_include, Imported);
1454 if (auto *CB = PP.getPPCallbacks())
1455 CB->moduleImport(ImportLoc, ModuleName, Imported);
1459 /// Handle the clang \#pragma module begin extension. The syntax is:
1461 /// #pragma clang module begin some.module.name
1463 /// #pragma clang module end
1465 struct PragmaModuleBeginHandler : public PragmaHandler {
1466 PragmaModuleBeginHandler() : PragmaHandler("begin") {}
1468 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1469 Token &Tok) override {
1470 SourceLocation BeginLoc = Tok.getLocation();
1472 // Read the module name.
1473 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1475 if (LexModuleName(PP, Tok, ModuleName))
1478 if (Tok.isNot(tok::eod))
1479 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1481 // We can only enter submodules of the current module.
1482 StringRef Current = PP.getLangOpts().CurrentModule;
1483 if (ModuleName.front().first->getName() != Current) {
1484 PP.Diag(ModuleName.front().second, diag::err_pp_module_begin_wrong_module)
1485 << ModuleName.front().first << (ModuleName.size() > 1)
1486 << Current.empty() << Current;
1490 // Find the module we're entering. We require that a module map for it
1491 // be loaded or implicitly loadable.
1492 // FIXME: We could create the submodule here. We'd need to know whether
1493 // it's supposed to be explicit, but not much else.
1494 Module *M = PP.getHeaderSearchInfo().lookupModule(Current);
1496 PP.Diag(ModuleName.front().second,
1497 diag::err_pp_module_begin_no_module_map) << Current;
1500 for (unsigned I = 1; I != ModuleName.size(); ++I) {
1501 auto *NewM = M->findSubmodule(ModuleName[I].first->getName());
1503 PP.Diag(ModuleName[I].second, diag::err_pp_module_begin_no_submodule)
1504 << M->getFullModuleName() << ModuleName[I].first;
1510 // If the module isn't available, it doesn't make sense to enter it.
1511 if (Preprocessor::checkModuleIsAvailable(
1512 PP.getLangOpts(), PP.getTargetInfo(), PP.getDiagnostics(), M)) {
1513 PP.Diag(BeginLoc, diag::note_pp_module_begin_here)
1514 << M->getTopLevelModuleName();
1518 // Enter the scope of the submodule.
1519 PP.EnterSubmodule(M, BeginLoc, /*ForPragma*/true);
1520 PP.EnterAnnotationToken(SourceRange(BeginLoc, ModuleName.back().second),
1521 tok::annot_module_begin, M);
1525 /// Handle the clang \#pragma module end extension.
1526 struct PragmaModuleEndHandler : public PragmaHandler {
1527 PragmaModuleEndHandler() : PragmaHandler("end") {}
1529 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1530 Token &Tok) override {
1531 SourceLocation Loc = Tok.getLocation();
1533 PP.LexUnexpandedToken(Tok);
1534 if (Tok.isNot(tok::eod))
1535 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1537 Module *M = PP.LeaveSubmodule(/*ForPragma*/true);
1539 PP.EnterAnnotationToken(SourceRange(Loc), tok::annot_module_end, M);
1541 PP.Diag(Loc, diag::err_pp_module_end_without_module_begin);
1545 /// Handle the clang \#pragma module build extension.
1546 struct PragmaModuleBuildHandler : public PragmaHandler {
1547 PragmaModuleBuildHandler() : PragmaHandler("build") {}
1549 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1550 Token &Tok) override {
1551 PP.HandlePragmaModuleBuild(Tok);
1555 /// Handle the clang \#pragma module load extension.
1556 struct PragmaModuleLoadHandler : public PragmaHandler {
1557 PragmaModuleLoadHandler() : PragmaHandler("load") {}
1559 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1560 Token &Tok) override {
1561 SourceLocation Loc = Tok.getLocation();
1563 // Read the module name.
1564 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1566 if (LexModuleName(PP, Tok, ModuleName))
1569 if (Tok.isNot(tok::eod))
1570 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1572 // Load the module, don't make it visible.
1573 PP.getModuleLoader().loadModule(Loc, ModuleName, Module::Hidden,
1574 /*IsIncludeDirective=*/false);
1578 /// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
1579 /// macro on the top of the stack.
1580 struct PragmaPushMacroHandler : public PragmaHandler {
1581 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
1583 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1584 Token &PushMacroTok) override {
1585 PP.HandlePragmaPushMacro(PushMacroTok);
1589 /// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
1590 /// macro to the value on the top of the stack.
1591 struct PragmaPopMacroHandler : public PragmaHandler {
1592 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
1594 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1595 Token &PopMacroTok) override {
1596 PP.HandlePragmaPopMacro(PopMacroTok);
1600 // Pragma STDC implementations.
1602 /// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
1603 struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
1604 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
1606 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1607 Token &Tok) override {
1608 tok::OnOffSwitch OOS;
1609 if (PP.LexOnOffSwitch(OOS))
1611 if (OOS == tok::OOS_ON)
1612 PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
1616 /// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
1617 struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
1618 PragmaSTDC_CX_LIMITED_RANGEHandler()
1619 : PragmaHandler("CX_LIMITED_RANGE") {}
1621 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1622 Token &Tok) override {
1623 tok::OnOffSwitch OOS;
1624 PP.LexOnOffSwitch(OOS);
1628 /// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
1629 struct PragmaSTDC_UnknownHandler : public PragmaHandler {
1630 PragmaSTDC_UnknownHandler() {}
1632 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1633 Token &UnknownTok) override {
1634 // C99 6.10.6p2, unknown forms are not allowed.
1635 PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
1639 /// PragmaARCCFCodeAuditedHandler -
1640 /// \#pragma clang arc_cf_code_audited begin/end
1641 struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1642 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
1644 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1645 Token &NameTok) override {
1646 SourceLocation Loc = NameTok.getLocation();
1651 // Lex the 'begin' or 'end'.
1652 PP.LexUnexpandedToken(Tok);
1653 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1654 if (BeginEnd && BeginEnd->isStr("begin")) {
1656 } else if (BeginEnd && BeginEnd->isStr("end")) {
1659 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1663 // Verify that this is followed by EOD.
1664 PP.LexUnexpandedToken(Tok);
1665 if (Tok.isNot(tok::eod))
1666 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1668 // The start location of the active audit.
1669 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1671 // The start location we want after processing this.
1672 SourceLocation NewLoc;
1675 // Complain about attempts to re-enter an audit.
1676 if (BeginLoc.isValid()) {
1677 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1678 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1682 // Complain about attempts to leave an audit that doesn't exist.
1683 if (!BeginLoc.isValid()) {
1684 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1687 NewLoc = SourceLocation();
1690 PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1694 /// PragmaAssumeNonNullHandler -
1695 /// \#pragma clang assume_nonnull begin/end
1696 struct PragmaAssumeNonNullHandler : public PragmaHandler {
1697 PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
1699 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1700 Token &NameTok) override {
1701 SourceLocation Loc = NameTok.getLocation();
1706 // Lex the 'begin' or 'end'.
1707 PP.LexUnexpandedToken(Tok);
1708 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1709 if (BeginEnd && BeginEnd->isStr("begin")) {
1711 } else if (BeginEnd && BeginEnd->isStr("end")) {
1714 PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
1718 // Verify that this is followed by EOD.
1719 PP.LexUnexpandedToken(Tok);
1720 if (Tok.isNot(tok::eod))
1721 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1723 // The start location of the active audit.
1724 SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
1726 // The start location we want after processing this.
1727 SourceLocation NewLoc;
1730 // Complain about attempts to re-enter an audit.
1731 if (BeginLoc.isValid()) {
1732 PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
1733 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1737 // Complain about attempts to leave an audit that doesn't exist.
1738 if (!BeginLoc.isValid()) {
1739 PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
1742 NewLoc = SourceLocation();
1745 PP.setPragmaAssumeNonNullLoc(NewLoc);
1749 /// \brief Handle "\#pragma region [...]"
1753 /// #pragma region [optional name]
1754 /// #pragma endregion [optional comment]
1758 /// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1759 /// pragma, just skipped by compiler.
1760 struct PragmaRegionHandler : public PragmaHandler {
1761 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) { }
1763 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1764 Token &NameTok) override {
1765 // #pragma region: endregion matches can be verified
1766 // __pragma(region): no sense, but ignored by msvc
1767 // _Pragma is not valid for MSVC, but there isn't any point
1768 // to handle a _Pragma differently.
1772 } // end anonymous namespace
1774 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
1775 /// \#pragma GCC poison/system_header/dependency and \#pragma once.
1776 void Preprocessor::RegisterBuiltinPragmas() {
1777 AddPragmaHandler(new PragmaOnceHandler());
1778 AddPragmaHandler(new PragmaMarkHandler());
1779 AddPragmaHandler(new PragmaPushMacroHandler());
1780 AddPragmaHandler(new PragmaPopMacroHandler());
1781 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
1784 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1785 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1786 AddPragmaHandler("GCC", new PragmaDependencyHandler());
1787 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
1788 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1790 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1792 // #pragma clang ...
1793 AddPragmaHandler("clang", new PragmaPoisonHandler());
1794 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
1795 AddPragmaHandler("clang", new PragmaDebugHandler());
1796 AddPragmaHandler("clang", new PragmaDependencyHandler());
1797 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
1798 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
1799 AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
1801 // #pragma clang module ...
1802 auto *ModuleHandler = new PragmaNamespace("module");
1803 AddPragmaHandler("clang", ModuleHandler);
1804 ModuleHandler->AddPragma(new PragmaModuleImportHandler());
1805 ModuleHandler->AddPragma(new PragmaModuleBeginHandler());
1806 ModuleHandler->AddPragma(new PragmaModuleEndHandler());
1807 ModuleHandler->AddPragma(new PragmaModuleBuildHandler());
1808 ModuleHandler->AddPragma(new PragmaModuleLoadHandler());
1810 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1811 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
1812 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
1815 if (LangOpts.MicrosoftExt) {
1816 AddPragmaHandler(new PragmaWarningHandler());
1817 AddPragmaHandler(new PragmaIncludeAliasHandler());
1818 AddPragmaHandler(new PragmaRegionHandler("region"));
1819 AddPragmaHandler(new PragmaRegionHandler("endregion"));
1822 // Pragmas added by plugins
1823 for (PragmaHandlerRegistry::iterator it = PragmaHandlerRegistry::begin(),
1824 ie = PragmaHandlerRegistry::end();
1826 AddPragmaHandler(it->instantiate().release());
1830 /// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
1831 /// warn about those pragmas being unknown.
1832 void Preprocessor::IgnorePragmas() {
1833 AddPragmaHandler(new EmptyPragmaHandler());
1834 // Also ignore all pragmas in all namespaces created
1835 // in Preprocessor::RegisterBuiltinPragmas().
1836 AddPragmaHandler("GCC", new EmptyPragmaHandler());
1837 AddPragmaHandler("clang", new EmptyPragmaHandler());
1838 if (PragmaHandler *NS = PragmaHandlers->FindHandler("STDC")) {
1839 // Preprocessor::RegisterBuiltinPragmas() already registers
1840 // PragmaSTDC_UnknownHandler as the empty handler, so remove it first,
1841 // otherwise there will be an assert about a duplicate handler.
1842 PragmaNamespace *STDCNamespace = NS->getIfNamespace();
1843 assert(STDCNamespace &&
1844 "Invalid namespace, registered as a regular pragma handler!");
1845 if (PragmaHandler *Existing = STDCNamespace->FindHandler("", false)) {
1846 RemovePragmaHandler("STDC", Existing);
1850 AddPragmaHandler("STDC", new EmptyPragmaHandler());