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/Diagnostic.h"
17 #include "clang/Basic/FileManager.h"
18 #include "clang/Basic/IdentifierTable.h"
19 #include "clang/Basic/LLVM.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Basic/Module.h"
22 #include "clang/Basic/SourceLocation.h"
23 #include "clang/Basic/SourceManager.h"
24 #include "clang/Basic/TokenKinds.h"
25 #include "clang/Lex/HeaderSearch.h"
26 #include "clang/Lex/LexDiagnostic.h"
27 #include "clang/Lex/Lexer.h"
28 #include "clang/Lex/LiteralSupport.h"
29 #include "clang/Lex/MacroInfo.h"
30 #include "clang/Lex/ModuleLoader.h"
31 #include "clang/Lex/PPCallbacks.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Lex/PreprocessorLexer.h"
34 #include "clang/Lex/PTHLexer.h"
35 #include "clang/Lex/Token.h"
36 #include "clang/Lex/TokenLexer.h"
37 #include "llvm/ADT/ArrayRef.h"
38 #include "llvm/ADT/DenseMap.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/ADT/SmallString.h"
41 #include "llvm/ADT/SmallVector.h"
42 #include "llvm/ADT/StringSwitch.h"
43 #include "llvm/ADT/StringRef.h"
44 #include "llvm/Support/CrashRecoveryContext.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/ErrorHandling.h"
56 using namespace clang;
58 // Out-of-line destructor to provide a home for the class.
59 PragmaHandler::~PragmaHandler() = default;
61 //===----------------------------------------------------------------------===//
62 // EmptyPragmaHandler Implementation.
63 //===----------------------------------------------------------------------===//
65 EmptyPragmaHandler::EmptyPragmaHandler(StringRef Name) : PragmaHandler(Name) {}
67 void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
68 PragmaIntroducerKind Introducer,
71 //===----------------------------------------------------------------------===//
72 // PragmaNamespace Implementation.
73 //===----------------------------------------------------------------------===//
75 PragmaNamespace::~PragmaNamespace() {
76 llvm::DeleteContainerSeconds(Handlers);
79 /// FindHandler - Check to see if there is already a handler for the
80 /// specified name. If not, return the handler for the null identifier if it
81 /// exists, otherwise return null. If IgnoreNull is true (the default) then
82 /// the null handler isn't returned on failure to match.
83 PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
84 bool IgnoreNull) const {
85 if (PragmaHandler *Handler = Handlers.lookup(Name))
87 return IgnoreNull ? nullptr : Handlers.lookup(StringRef());
90 void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
91 assert(!Handlers.lookup(Handler->getName()) &&
92 "A handler with this name is already registered in this namespace");
93 Handlers[Handler->getName()] = Handler;
96 void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
97 assert(Handlers.lookup(Handler->getName()) &&
98 "Handler not registered in this namespace");
99 Handlers.erase(Handler->getName());
102 void PragmaNamespace::HandlePragma(Preprocessor &PP,
103 PragmaIntroducerKind Introducer,
105 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
106 // expand it, the user can have a STDC #define, that should not affect this.
107 PP.LexUnexpandedToken(Tok);
109 // Get the handler for this token. If there is no handler, ignore the pragma.
110 PragmaHandler *Handler
111 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
113 /*IgnoreNull=*/false);
115 PP.Diag(Tok, diag::warn_pragma_ignored);
119 // Otherwise, pass it down.
120 Handler->HandlePragma(PP, Introducer, Tok);
123 //===----------------------------------------------------------------------===//
124 // Preprocessor Pragma Directive Handling.
125 //===----------------------------------------------------------------------===//
127 /// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the
128 /// rest of the pragma, passing it to the registered pragma handlers.
129 void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc,
130 PragmaIntroducerKind Introducer) {
132 Callbacks->PragmaDirective(IntroducerLoc, Introducer);
139 // Invoke the first level of pragma handlers which reads the namespace id.
141 PragmaHandlers->HandlePragma(*this, Introducer, Tok);
143 // If the pragma handler didn't read the rest of the line, consume it now.
144 if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
145 || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
146 DiscardUntilEndOfDirective();
151 /// \brief Helper class for \see Preprocessor::Handle_Pragma.
152 class LexingFor_PragmaRAII {
154 bool InMacroArgPreExpansion;
160 LexingFor_PragmaRAII(Preprocessor &PP, bool InMacroArgPreExpansion,
162 : PP(PP), InMacroArgPreExpansion(InMacroArgPreExpansion), OutTok(Tok) {
163 if (InMacroArgPreExpansion) {
165 PP.EnableBacktrackAtThisPos();
169 ~LexingFor_PragmaRAII() {
170 if (InMacroArgPreExpansion) {
171 // When committing/backtracking the cached pragma tokens in a macro
172 // argument pre-expansion we want to ensure that either the tokens which
173 // have been committed will be removed from the cache or that the tokens
174 // over which we just backtracked won't remain in the cache after they're
175 // consumed and that the caching will stop after consuming them.
176 // Otherwise the caching will interfere with the way macro expansion
177 // works, because we will continue to cache tokens after consuming the
178 // backtracked tokens, which shouldn't happen when we're dealing with
179 // macro argument pre-expansion.
180 auto CachedTokenRange = PP.LastCachedTokenRange();
182 PP.CommitBacktrackedTokens();
187 PP.EraseCachedTokens(CachedTokenRange);
198 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
199 /// return the first token after the directive. The _Pragma token has just
200 /// been read into 'Tok'.
201 void Preprocessor::Handle_Pragma(Token &Tok) {
202 // This works differently if we are pre-expanding a macro argument.
203 // In that case we don't actually "activate" the pragma now, we only lex it
204 // until we are sure it is lexically correct and then we backtrack so that
205 // we activate the pragma whenever we encounter the tokens again in the token
206 // stream. This ensures that we will activate it in the correct location
207 // or that we will ignore it if it never enters the token stream, e.g:
210 // #define INACTIVE(x) EMPTY(x)
211 // INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\""))
213 LexingFor_PragmaRAII _PragmaLexing(*this, InMacroArgPreExpansion, Tok);
215 // Remember the pragma token location.
216 SourceLocation PragmaLoc = Tok.getLocation();
220 if (Tok.isNot(tok::l_paren)) {
221 Diag(PragmaLoc, diag::err__Pragma_malformed);
222 return _PragmaLexing.failed();
227 if (!tok::isStringLiteral(Tok.getKind())) {
228 Diag(PragmaLoc, diag::err__Pragma_malformed);
229 // Skip bad tokens, and the ')', if present.
230 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
232 while (Tok.isNot(tok::r_paren) &&
233 !Tok.isAtStartOfLine() &&
236 if (Tok.is(tok::r_paren))
238 return _PragmaLexing.failed();
241 if (Tok.hasUDSuffix()) {
242 Diag(Tok, diag::err_invalid_string_udl);
243 // Skip this token, and the ')', if present.
245 if (Tok.is(tok::r_paren))
247 return _PragmaLexing.failed();
250 // Remember the string.
255 if (Tok.isNot(tok::r_paren)) {
256 Diag(PragmaLoc, diag::err__Pragma_malformed);
257 return _PragmaLexing.failed();
260 if (InMacroArgPreExpansion)
263 SourceLocation RParenLoc = Tok.getLocation();
264 std::string StrVal = getSpelling(StrTok);
266 // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1:
267 // "The string literal is destringized by deleting any encoding prefix,
268 // deleting the leading and trailing double-quotes, replacing each escape
269 // sequence \" by a double-quote, and replacing each escape sequence \\ by a
270 // single backslash."
271 if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
272 (StrVal[0] == 'u' && StrVal[1] != '8'))
273 StrVal.erase(StrVal.begin());
274 else if (StrVal[0] == 'u')
275 StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
277 if (StrVal[0] == 'R') {
278 // FIXME: C++11 does not specify how to handle raw-string-literals here.
279 // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
280 assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
281 "Invalid raw string token!");
283 // Measure the length of the d-char-sequence.
284 unsigned NumDChars = 0;
285 while (StrVal[2 + NumDChars] != '(') {
286 assert(NumDChars < (StrVal.size() - 5) / 2 &&
287 "Invalid raw string token!");
290 assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
292 // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
294 StrVal.erase(0, 2 + NumDChars);
295 StrVal.erase(StrVal.size() - 1 - NumDChars);
297 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
298 "Invalid string token!");
300 // Remove escaped quotes and escapes.
301 unsigned ResultPos = 1;
302 for (size_t i = 1, e = StrVal.size() - 1; i != e; ++i) {
303 // Skip escapes. \\ -> '\' and \" -> '"'.
304 if (StrVal[i] == '\\' && i + 1 < e &&
305 (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
307 StrVal[ResultPos++] = StrVal[i];
309 StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
312 // Remove the front quote, replacing it with a space, so that the pragma
313 // contents appear to have a space before them.
316 // Replace the terminating quote with a \n.
317 StrVal[StrVal.size()-1] = '\n';
319 // Plop the string (including the newline and trailing null) into a buffer
320 // where we can lex it.
323 CreateString(StrVal, TmpTok);
324 SourceLocation TokLoc = TmpTok.getLocation();
326 // Make and enter a lexer object so that we lex and expand the tokens just
328 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
329 StrVal.size(), *this);
331 EnterSourceFileWithLexer(TL, nullptr);
333 // With everything set up, lex this as a #pragma directive.
334 HandlePragmaDirective(PragmaLoc, PIK__Pragma);
336 // Finally, return whatever came after the pragma directive.
340 /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
341 /// is not enclosed within a string literal.
342 void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
343 // Remember the pragma token location.
344 SourceLocation PragmaLoc = Tok.getLocation();
348 if (Tok.isNot(tok::l_paren)) {
349 Diag(PragmaLoc, diag::err__Pragma_malformed);
353 // Get the tokens enclosed within the __pragma(), as well as the final ')'.
354 SmallVector<Token, 32> PragmaToks;
357 while (Tok.isNot(tok::eof)) {
358 PragmaToks.push_back(Tok);
359 if (Tok.is(tok::l_paren))
361 else if (Tok.is(tok::r_paren) && NumParens-- == 0)
366 if (Tok.is(tok::eof)) {
367 Diag(PragmaLoc, diag::err_unterminated___pragma);
371 PragmaToks.front().setFlag(Token::LeadingSpace);
373 // Replace the ')' with an EOD to mark the end of the pragma.
374 PragmaToks.back().setKind(tok::eod);
376 Token *TokArray = new Token[PragmaToks.size()];
377 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
379 // Push the tokens onto the stack.
380 EnterTokenStream(TokArray, PragmaToks.size(), true, true);
382 // With everything set up, lex this as a #pragma directive.
383 HandlePragmaDirective(PragmaLoc, PIK___pragma);
385 // Finally, return whatever came after the pragma directive.
389 /// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
390 void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
391 // Don't honor the 'once' when handling the primary source file, unless
392 // this is a prefix to a TU, which indicates we're generating a PCH file, or
393 // when the main file is a header (e.g. when -xc-header is provided on the
395 if (isInPrimaryFile() && TUKind != TU_Prefix && !getLangOpts().IsHeaderFile) {
396 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
400 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
401 // Mark the file as a once-only file now.
402 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
405 void Preprocessor::HandlePragmaMark() {
406 assert(CurPPLexer && "No current lexer?");
408 CurLexer->ReadToEndOfLine();
410 CurPTHLexer->DiscardToEndOfLine();
413 /// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
414 void Preprocessor::HandlePragmaPoison() {
418 // Read the next token to poison. While doing this, pretend that we are
419 // skipping while reading the identifier to poison.
420 // This avoids errors on code like:
421 // #pragma GCC poison X
422 // #pragma GCC poison X
423 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
424 LexUnexpandedToken(Tok);
425 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
427 // If we reached the end of line, we're done.
428 if (Tok.is(tok::eod)) return;
430 // Can only poison identifiers.
431 if (Tok.isNot(tok::raw_identifier)) {
432 Diag(Tok, diag::err_pp_invalid_poison);
436 // Look up the identifier info for the token. We disabled identifier lookup
437 // by saying we're skipping contents, so we need to do this manually.
438 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
441 if (II->isPoisoned()) continue;
443 // If this is a macro identifier, emit a warning.
444 if (isMacroDefined(II))
445 Diag(Tok, diag::pp_poisoning_existing_macro);
447 // Finally, poison it!
450 II->setChangedSinceDeserialization();
454 /// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
455 /// that the whole directive has been parsed.
456 void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
457 if (isInPrimaryFile()) {
458 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
462 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
463 PreprocessorLexer *TheLexer = getCurrentFileLexer();
465 // Mark the file as a system header.
466 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
468 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
469 if (PLoc.isInvalid())
472 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
474 // Notify the client, if desired, that we are in a new source file.
476 Callbacks->FileChanged(SysHeaderTok.getLocation(),
477 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
479 // Emit a line marker. This will change any source locations from this point
480 // forward to realize they are in a system header.
481 // Create a line note with this information.
482 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine() + 1,
483 FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
487 /// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
488 void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
490 CurPPLexer->LexIncludeFilename(FilenameTok);
492 // If the token kind is EOD, the error has already been diagnosed.
493 if (FilenameTok.is(tok::eod))
496 // Reserve a buffer to get the spelling.
497 SmallString<128> FilenameBuffer;
498 bool Invalid = false;
499 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
504 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
505 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
507 if (Filename.empty())
510 // Search include directories for this file.
511 const DirectoryLookup *CurDir;
512 const FileEntry *File =
513 LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
514 nullptr, CurDir, nullptr, nullptr, nullptr, nullptr);
516 if (!SuppressIncludeNotFoundError)
517 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
521 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
523 // If this file is older than the file it depends on, emit a diagnostic.
524 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
525 // Lex tokens at the end of the message and include them in the message.
528 while (DependencyTok.isNot(tok::eod)) {
529 Message += getSpelling(DependencyTok) + " ";
533 // Remove the trailing ' ' if present.
534 if (!Message.empty())
535 Message.erase(Message.end()-1);
536 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
540 /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
541 /// Return the IdentifierInfo* associated with the macro to push or pop.
542 IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
543 // Remember the pragma token location.
544 Token PragmaTok = Tok;
548 if (Tok.isNot(tok::l_paren)) {
549 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
550 << getSpelling(PragmaTok);
554 // Read the macro name string.
556 if (Tok.isNot(tok::string_literal)) {
557 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
558 << getSpelling(PragmaTok);
562 if (Tok.hasUDSuffix()) {
563 Diag(Tok, diag::err_invalid_string_udl);
567 // Remember the macro string.
568 std::string StrVal = getSpelling(Tok);
572 if (Tok.isNot(tok::r_paren)) {
573 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
574 << getSpelling(PragmaTok);
578 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
579 "Invalid string token!");
581 // Create a Token from the string.
583 MacroTok.startToken();
584 MacroTok.setKind(tok::raw_identifier);
585 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
587 // Get the IdentifierInfo of MacroToPushTok.
588 return LookUpIdentifierInfo(MacroTok);
591 /// \brief Handle \#pragma push_macro.
595 /// #pragma push_macro("macro")
597 void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
598 // Parse the pragma directive and get the macro IdentifierInfo*.
599 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
600 if (!IdentInfo) return;
602 // Get the MacroInfo associated with IdentInfo.
603 MacroInfo *MI = getMacroInfo(IdentInfo);
606 // Allow the original MacroInfo to be redefined later.
607 MI->setIsAllowRedefinitionsWithoutWarning(true);
610 // Push the cloned MacroInfo so we can retrieve it later.
611 PragmaPushMacroInfo[IdentInfo].push_back(MI);
614 /// \brief Handle \#pragma pop_macro.
618 /// #pragma pop_macro("macro")
620 void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
621 SourceLocation MessageLoc = PopMacroTok.getLocation();
623 // Parse the pragma directive and get the macro IdentifierInfo*.
624 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
625 if (!IdentInfo) return;
627 // Find the vector<MacroInfo*> associated with the macro.
628 llvm::DenseMap<IdentifierInfo *, std::vector<MacroInfo *>>::iterator iter =
629 PragmaPushMacroInfo.find(IdentInfo);
630 if (iter != PragmaPushMacroInfo.end()) {
631 // Forget the MacroInfo currently associated with IdentInfo.
632 if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
633 if (MI->isWarnIfUnused())
634 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
635 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
638 // Get the MacroInfo we want to reinstall.
639 MacroInfo *MacroToReInstall = iter->second.back();
641 if (MacroToReInstall)
642 // Reinstall the previously pushed macro.
643 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
645 // Pop PragmaPushMacroInfo stack.
646 iter->second.pop_back();
647 if (iter->second.empty())
648 PragmaPushMacroInfo.erase(iter);
650 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
651 << IdentInfo->getName();
655 void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
656 // We will either get a quoted filename or a bracketed filename, and we
657 // have to track which we got. The first filename is the source name,
658 // and the second name is the mapped filename. If the first is quoted,
659 // the second must be as well (cannot mix and match quotes and brackets).
661 // Get the open paren
663 if (Tok.isNot(tok::l_paren)) {
664 Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
668 // We expect either a quoted string literal, or a bracketed name
669 Token SourceFilenameTok;
670 CurPPLexer->LexIncludeFilename(SourceFilenameTok);
671 if (SourceFilenameTok.is(tok::eod)) {
672 // The diagnostic has already been handled
676 StringRef SourceFileName;
677 SmallString<128> FileNameBuffer;
678 if (SourceFilenameTok.is(tok::string_literal) ||
679 SourceFilenameTok.is(tok::angle_string_literal)) {
680 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
681 } else if (SourceFilenameTok.is(tok::less)) {
682 // This could be a path instead of just a name
683 FileNameBuffer.push_back('<');
685 if (ConcatenateIncludeName(FileNameBuffer, End))
686 return; // Diagnostic already emitted
687 SourceFileName = FileNameBuffer;
689 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
692 FileNameBuffer.clear();
694 // Now we expect a comma, followed by another include name
696 if (Tok.isNot(tok::comma)) {
697 Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
701 Token ReplaceFilenameTok;
702 CurPPLexer->LexIncludeFilename(ReplaceFilenameTok);
703 if (ReplaceFilenameTok.is(tok::eod)) {
704 // The diagnostic has already been handled
708 StringRef ReplaceFileName;
709 if (ReplaceFilenameTok.is(tok::string_literal) ||
710 ReplaceFilenameTok.is(tok::angle_string_literal)) {
711 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
712 } else if (ReplaceFilenameTok.is(tok::less)) {
713 // This could be a path instead of just a name
714 FileNameBuffer.push_back('<');
716 if (ConcatenateIncludeName(FileNameBuffer, End))
717 return; // Diagnostic already emitted
718 ReplaceFileName = FileNameBuffer;
720 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
724 // Finally, we expect the closing paren
726 if (Tok.isNot(tok::r_paren)) {
727 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
731 // Now that we have the source and target filenames, we need to make sure
732 // they're both of the same type (angled vs non-angled)
733 StringRef OriginalSource = SourceFileName;
735 bool SourceIsAngled =
736 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
738 bool ReplaceIsAngled =
739 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
741 if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
742 (SourceIsAngled != ReplaceIsAngled)) {
745 DiagID = diag::warn_pragma_include_alias_mismatch_angle;
747 DiagID = diag::warn_pragma_include_alias_mismatch_quote;
749 Diag(SourceFilenameTok.getLocation(), DiagID)
756 // Now we can let the include handler know about this mapping
757 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
760 // Lex a component of a module name: either an identifier or a string literal;
761 // for components that can be expressed both ways, the two forms are equivalent.
762 static bool LexModuleNameComponent(
763 Preprocessor &PP, Token &Tok,
764 std::pair<IdentifierInfo *, SourceLocation> &ModuleNameComponent,
766 PP.LexUnexpandedToken(Tok);
767 if (Tok.is(tok::string_literal) && !Tok.hasUDSuffix()) {
768 StringLiteralParser Literal(Tok, PP);
769 if (Literal.hadError)
771 ModuleNameComponent = std::make_pair(
772 PP.getIdentifierInfo(Literal.GetString()), Tok.getLocation());
773 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) {
774 ModuleNameComponent =
775 std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation());
777 PP.Diag(Tok.getLocation(), diag::err_pp_expected_module_name) << First;
783 static bool LexModuleName(
784 Preprocessor &PP, Token &Tok,
785 llvm::SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>>
788 std::pair<IdentifierInfo*, SourceLocation> NameComponent;
789 if (LexModuleNameComponent(PP, Tok, NameComponent, ModuleName.empty()))
791 ModuleName.push_back(NameComponent);
793 PP.LexUnexpandedToken(Tok);
794 if (Tok.isNot(tok::period))
799 void Preprocessor::HandlePragmaModuleBuild(Token &Tok) {
800 SourceLocation Loc = Tok.getLocation();
802 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
803 if (LexModuleNameComponent(*this, Tok, ModuleNameLoc, true))
805 IdentifierInfo *ModuleName = ModuleNameLoc.first;
807 LexUnexpandedToken(Tok);
808 if (Tok.isNot(tok::eod)) {
809 Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
810 DiscardUntilEndOfDirective();
814 // FIXME: Support this somehow?
815 Diag(Loc, diag::err_pp_module_build_pth);
819 CurLexer->LexingRawMode = true;
821 auto TryConsumeIdentifier = [&](StringRef Ident) -> bool {
822 if (Tok.getKind() != tok::raw_identifier ||
823 Tok.getRawIdentifier() != Ident)
829 // Scan forward looking for the end of the module.
830 const char *Start = CurLexer->getBufferLocation();
831 const char *End = nullptr;
832 unsigned NestingLevel = 1;
834 End = CurLexer->getBufferLocation();
837 if (Tok.is(tok::eof)) {
838 Diag(Loc, diag::err_pp_module_build_missing_end);
842 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) {
843 // Token was part of module; keep going.
847 // We hit something directive-shaped; check to see if this is the end
848 // of the module build.
849 CurLexer->ParsingPreprocessorDirective = true;
851 if (TryConsumeIdentifier("pragma") && TryConsumeIdentifier("clang") &&
852 TryConsumeIdentifier("module")) {
853 if (TryConsumeIdentifier("build"))
854 // #pragma clang module build -> entering a nested module build.
856 else if (TryConsumeIdentifier("endbuild")) {
857 // #pragma clang module endbuild -> leaving a module build.
858 if (--NestingLevel == 0)
861 // We should either be looking at the EOD or more of the current directive
862 // preceding the EOD. Either way we can ignore this token and keep going.
863 assert(Tok.getKind() != tok::eof && "missing EOD before EOF");
867 CurLexer->LexingRawMode = false;
869 // Load the extracted text as a preprocessed module.
870 assert(CurLexer->getBuffer().begin() <= Start &&
871 Start <= CurLexer->getBuffer().end() &&
872 CurLexer->getBuffer().begin() <= End &&
873 End <= CurLexer->getBuffer().end() &&
874 "module source range not contained within same file buffer");
875 TheModuleLoader.loadModuleFromSource(Loc, ModuleName->getName(),
876 StringRef(Start, End - Start));
879 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
880 /// If 'Namespace' is non-null, then it is a token required to exist on the
881 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
882 void Preprocessor::AddPragmaHandler(StringRef Namespace,
883 PragmaHandler *Handler) {
884 PragmaNamespace *InsertNS = PragmaHandlers.get();
886 // If this is specified to be in a namespace, step down into it.
887 if (!Namespace.empty()) {
888 // If there is already a pragma handler with the name of this namespace,
889 // we either have an error (directive with the same name as a namespace) or
890 // we already have the namespace to insert into.
891 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
892 InsertNS = Existing->getIfNamespace();
893 assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
894 " handler with the same name!");
896 // Otherwise, this namespace doesn't exist yet, create and insert the
898 InsertNS = new PragmaNamespace(Namespace);
899 PragmaHandlers->AddPragma(InsertNS);
903 // Check to make sure we don't already have a pragma for this identifier.
904 assert(!InsertNS->FindHandler(Handler->getName()) &&
905 "Pragma handler already exists for this identifier!");
906 InsertNS->AddPragma(Handler);
909 /// RemovePragmaHandler - Remove the specific pragma handler from the
910 /// preprocessor. If \arg Namespace is non-null, then it should be the
911 /// namespace that \arg Handler was added to. It is an error to remove
912 /// a handler that has not been registered.
913 void Preprocessor::RemovePragmaHandler(StringRef Namespace,
914 PragmaHandler *Handler) {
915 PragmaNamespace *NS = PragmaHandlers.get();
917 // If this is specified to be in a namespace, step down into it.
918 if (!Namespace.empty()) {
919 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
920 assert(Existing && "Namespace containing handler does not exist!");
922 NS = Existing->getIfNamespace();
923 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
926 NS->RemovePragmaHandler(Handler);
928 // If this is a non-default namespace and it is now empty, remove it.
929 if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
930 PragmaHandlers->RemovePragmaHandler(NS);
935 bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
937 LexUnexpandedToken(Tok);
939 if (Tok.isNot(tok::identifier)) {
940 Diag(Tok, diag::ext_on_off_switch_syntax);
943 IdentifierInfo *II = Tok.getIdentifierInfo();
945 Result = tok::OOS_ON;
946 else if (II->isStr("OFF"))
947 Result = tok::OOS_OFF;
948 else if (II->isStr("DEFAULT"))
949 Result = tok::OOS_DEFAULT;
951 Diag(Tok, diag::ext_on_off_switch_syntax);
955 // Verify that this is followed by EOD.
956 LexUnexpandedToken(Tok);
957 if (Tok.isNot(tok::eod))
958 Diag(Tok, diag::ext_pragma_syntax_eod);
964 /// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
965 struct PragmaOnceHandler : public PragmaHandler {
966 PragmaOnceHandler() : PragmaHandler("once") {}
968 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
969 Token &OnceTok) override {
970 PP.CheckEndOfDirective("pragma once");
971 PP.HandlePragmaOnce(OnceTok);
975 /// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
976 /// rest of the line is not lexed.
977 struct PragmaMarkHandler : public PragmaHandler {
978 PragmaMarkHandler() : PragmaHandler("mark") {}
980 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
981 Token &MarkTok) override {
982 PP.HandlePragmaMark();
986 /// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
987 struct PragmaPoisonHandler : public PragmaHandler {
988 PragmaPoisonHandler() : PragmaHandler("poison") {}
990 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
991 Token &PoisonTok) override {
992 PP.HandlePragmaPoison();
996 /// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
997 /// as a system header, which silences warnings in it.
998 struct PragmaSystemHeaderHandler : public PragmaHandler {
999 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
1001 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1002 Token &SHToken) override {
1003 PP.HandlePragmaSystemHeader(SHToken);
1004 PP.CheckEndOfDirective("pragma");
1008 struct PragmaDependencyHandler : public PragmaHandler {
1009 PragmaDependencyHandler() : PragmaHandler("dependency") {}
1011 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1012 Token &DepToken) override {
1013 PP.HandlePragmaDependency(DepToken);
1017 struct PragmaDebugHandler : public PragmaHandler {
1018 PragmaDebugHandler() : PragmaHandler("__debug") {}
1020 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1021 Token &DepToken) override {
1023 PP.LexUnexpandedToken(Tok);
1024 if (Tok.isNot(tok::identifier)) {
1025 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1028 IdentifierInfo *II = Tok.getIdentifierInfo();
1030 if (II->isStr("assert")) {
1031 llvm_unreachable("This is an assertion!");
1032 } else if (II->isStr("crash")) {
1034 } else if (II->isStr("parser_crash")) {
1036 Crasher.startToken();
1037 Crasher.setKind(tok::annot_pragma_parser_crash);
1038 Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
1039 PP.EnterToken(Crasher);
1040 } else if (II->isStr("dump")) {
1042 PP.LexUnexpandedToken(Identifier);
1043 if (auto *DumpII = Identifier.getIdentifierInfo()) {
1045 DumpAnnot.startToken();
1046 DumpAnnot.setKind(tok::annot_pragma_dump);
1047 DumpAnnot.setAnnotationRange(
1048 SourceRange(Tok.getLocation(), Identifier.getLocation()));
1049 DumpAnnot.setAnnotationValue(DumpII);
1050 PP.DiscardUntilEndOfDirective();
1051 PP.EnterToken(DumpAnnot);
1053 PP.Diag(Identifier, diag::warn_pragma_debug_missing_argument)
1056 } else if (II->isStr("llvm_fatal_error")) {
1057 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
1058 } else if (II->isStr("llvm_unreachable")) {
1059 llvm_unreachable("#pragma clang __debug llvm_unreachable");
1060 } else if (II->isStr("macro")) {
1062 PP.LexUnexpandedToken(MacroName);
1063 auto *MacroII = MacroName.getIdentifierInfo();
1065 PP.dumpMacroInfo(MacroII);
1067 PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument)
1069 } else if (II->isStr("overflow_stack")) {
1070 DebugOverflowStack();
1071 } else if (II->isStr("handle_crash")) {
1072 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
1075 } else if (II->isStr("captured")) {
1078 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
1082 PPCallbacks *Callbacks = PP.getPPCallbacks();
1084 Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
1087 void HandleCaptured(Preprocessor &PP) {
1088 // Skip if emitting preprocessed output.
1089 if (PP.isPreprocessedOutput())
1093 PP.LexUnexpandedToken(Tok);
1095 if (Tok.isNot(tok::eod)) {
1096 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
1097 << "pragma clang __debug captured";
1101 SourceLocation NameLoc = Tok.getLocation();
1102 MutableArrayRef<Token> Toks(
1103 PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
1104 Toks[0].startToken();
1105 Toks[0].setKind(tok::annot_pragma_captured);
1106 Toks[0].setLocation(NameLoc);
1108 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
1111 // Disable MSVC warning about runtime stack overflow.
1113 #pragma warning(disable : 4717)
1115 static void DebugOverflowStack(void (*P)() = nullptr) {
1116 void (*volatile Self)(void(*P)()) = DebugOverflowStack;
1117 Self(reinterpret_cast<void(*)()>(Self));
1120 #pragma warning(default : 4717)
1124 /// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
1125 struct PragmaDiagnosticHandler : public PragmaHandler {
1127 const char *Namespace;
1130 explicit PragmaDiagnosticHandler(const char *NS)
1131 : PragmaHandler("diagnostic"), Namespace(NS) {}
1133 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1134 Token &DiagToken) override {
1135 SourceLocation DiagLoc = DiagToken.getLocation();
1137 PP.LexUnexpandedToken(Tok);
1138 if (Tok.isNot(tok::identifier)) {
1139 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1142 IdentifierInfo *II = Tok.getIdentifierInfo();
1143 PPCallbacks *Callbacks = PP.getPPCallbacks();
1145 if (II->isStr("pop")) {
1146 if (!PP.getDiagnostics().popMappings(DiagLoc))
1147 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
1149 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
1151 } else if (II->isStr("push")) {
1152 PP.getDiagnostics().pushMappings(DiagLoc);
1154 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
1158 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
1159 .Case("ignored", diag::Severity::Ignored)
1160 .Case("warning", diag::Severity::Warning)
1161 .Case("error", diag::Severity::Error)
1162 .Case("fatal", diag::Severity::Fatal)
1163 .Default(diag::Severity());
1165 if (SV == diag::Severity()) {
1166 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1170 PP.LexUnexpandedToken(Tok);
1171 SourceLocation StringLoc = Tok.getLocation();
1173 std::string WarningName;
1174 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
1175 /*MacroExpansion=*/false))
1178 if (Tok.isNot(tok::eod)) {
1179 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1183 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1184 (WarningName[1] != 'W' && WarningName[1] != 'R')) {
1185 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
1189 diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1190 : diag::Flavor::Remark;
1191 StringRef Group = StringRef(WarningName).substr(2);
1192 bool unknownDiag = false;
1193 if (Group == "everything") {
1194 // Special handling for pragma clang diagnostic ... "-Weverything".
1195 // There is no formal group named "everything", so there has to be a
1196 // special case for it.
1197 PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc);
1199 unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV,
1202 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1205 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
1209 /// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1210 /// diagnostics, so we don't really implement this pragma. We parse it and
1211 /// ignore it to avoid -Wunknown-pragma warnings.
1212 struct PragmaWarningHandler : public PragmaHandler {
1213 PragmaWarningHandler() : PragmaHandler("warning") {}
1215 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1216 Token &Tok) override {
1217 // Parse things like:
1220 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
1221 SourceLocation DiagLoc = Tok.getLocation();
1222 PPCallbacks *Callbacks = PP.getPPCallbacks();
1225 if (Tok.isNot(tok::l_paren)) {
1226 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1231 IdentifierInfo *II = Tok.getIdentifierInfo();
1233 if (II && II->isStr("push")) {
1234 // #pragma warning( push[ ,n ] )
1237 if (Tok.is(tok::comma)) {
1240 if (Tok.is(tok::numeric_constant) &&
1241 PP.parseSimpleIntegerLiteral(Tok, Value))
1243 if (Level < 0 || Level > 4) {
1244 PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1249 Callbacks->PragmaWarningPush(DiagLoc, Level);
1250 } else if (II && II->isStr("pop")) {
1251 // #pragma warning( pop )
1254 Callbacks->PragmaWarningPop(DiagLoc);
1256 // #pragma warning( warning-specifier : warning-number-list
1257 // [; warning-specifier : warning-number-list...] )
1259 II = Tok.getIdentifierInfo();
1260 if (!II && !Tok.is(tok::numeric_constant)) {
1261 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1265 // Figure out which warning specifier this is.
1266 bool SpecifierValid;
1267 StringRef Specifier;
1268 llvm::SmallString<1> SpecifierBuf;
1270 Specifier = II->getName();
1271 SpecifierValid = llvm::StringSwitch<bool>(Specifier)
1272 .Cases("default", "disable", "error", "once",
1275 // If we read a correct specifier, snatch next token (that should be
1276 // ":", checked later).
1280 // Token is a numeric constant. It should be either 1, 2, 3 or 4.
1282 Specifier = PP.getSpelling(Tok, SpecifierBuf);
1283 if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
1284 SpecifierValid = (Value >= 1) && (Value <= 4);
1286 SpecifierValid = false;
1287 // Next token already snatched by parseSimpleIntegerLiteral.
1290 if (!SpecifierValid) {
1291 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1294 if (Tok.isNot(tok::colon)) {
1295 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1299 // Collect the warning ids.
1300 SmallVector<int, 4> Ids;
1302 while (Tok.is(tok::numeric_constant)) {
1304 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
1305 Value > std::numeric_limits<int>::max()) {
1306 PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1309 Ids.push_back(int(Value));
1312 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1314 // Parse the next specifier if there is a semicolon.
1315 if (Tok.isNot(tok::semi))
1321 if (Tok.isNot(tok::r_paren)) {
1322 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1327 if (Tok.isNot(tok::eod))
1328 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1332 /// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
1333 struct PragmaIncludeAliasHandler : public PragmaHandler {
1334 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
1336 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1337 Token &IncludeAliasTok) override {
1338 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
1342 /// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1343 /// extension. The syntax is:
1345 /// #pragma message(string)
1347 /// OR, in GCC mode:
1349 /// #pragma message string
1351 /// string is a string, which is fully macro expanded, and permits string
1352 /// concatenation, embedded escape characters, etc... See MSDN for more details.
1353 /// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1354 /// form as \#pragma message.
1355 struct PragmaMessageHandler : public PragmaHandler {
1357 const PPCallbacks::PragmaMessageKind Kind;
1358 const StringRef Namespace;
1360 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1361 bool PragmaNameOnly = false) {
1363 case PPCallbacks::PMK_Message:
1364 return PragmaNameOnly ? "message" : "pragma message";
1365 case PPCallbacks::PMK_Warning:
1366 return PragmaNameOnly ? "warning" : "pragma warning";
1367 case PPCallbacks::PMK_Error:
1368 return PragmaNameOnly ? "error" : "pragma error";
1370 llvm_unreachable("Unknown PragmaMessageKind!");
1374 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1375 StringRef Namespace = StringRef())
1376 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind),
1377 Namespace(Namespace) {}
1379 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1380 Token &Tok) override {
1381 SourceLocation MessageLoc = Tok.getLocation();
1383 bool ExpectClosingParen = false;
1384 switch (Tok.getKind()) {
1386 // We have a MSVC style pragma message.
1387 ExpectClosingParen = true;
1391 case tok::string_literal:
1392 // We have a GCC style pragma message, and we just read the string.
1395 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1399 std::string MessageString;
1400 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1401 /*MacroExpansion=*/true))
1404 if (ExpectClosingParen) {
1405 if (Tok.isNot(tok::r_paren)) {
1406 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1409 PP.Lex(Tok); // eat the r_paren.
1412 if (Tok.isNot(tok::eod)) {
1413 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1417 // Output the message.
1418 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1419 ? diag::err_pragma_message
1420 : diag::warn_pragma_message) << MessageString;
1422 // If the pragma is lexically sound, notify any interested PPCallbacks.
1423 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1424 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
1428 /// Handle the clang \#pragma module import extension. The syntax is:
1430 /// #pragma clang module import some.module.name
1432 struct PragmaModuleImportHandler : public PragmaHandler {
1433 PragmaModuleImportHandler() : PragmaHandler("import") {}
1435 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1436 Token &Tok) override {
1437 SourceLocation ImportLoc = Tok.getLocation();
1439 // Read the module name.
1440 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1442 if (LexModuleName(PP, Tok, ModuleName))
1445 if (Tok.isNot(tok::eod))
1446 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1448 // If we have a non-empty module path, load the named module.
1450 PP.getModuleLoader().loadModule(ImportLoc, ModuleName, Module::Hidden,
1451 /*IsIncludeDirective=*/false);
1455 PP.makeModuleVisible(Imported, ImportLoc);
1456 PP.EnterAnnotationToken(SourceRange(ImportLoc, ModuleName.back().second),
1457 tok::annot_module_include, Imported);
1458 if (auto *CB = PP.getPPCallbacks())
1459 CB->moduleImport(ImportLoc, ModuleName, Imported);
1463 /// Handle the clang \#pragma module begin extension. The syntax is:
1465 /// #pragma clang module begin some.module.name
1467 /// #pragma clang module end
1469 struct PragmaModuleBeginHandler : public PragmaHandler {
1470 PragmaModuleBeginHandler() : PragmaHandler("begin") {}
1472 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1473 Token &Tok) override {
1474 SourceLocation BeginLoc = Tok.getLocation();
1476 // Read the module name.
1477 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1479 if (LexModuleName(PP, Tok, ModuleName))
1482 if (Tok.isNot(tok::eod))
1483 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1485 // We can only enter submodules of the current module.
1486 StringRef Current = PP.getLangOpts().CurrentModule;
1487 if (ModuleName.front().first->getName() != Current) {
1488 PP.Diag(ModuleName.front().second, diag::err_pp_module_begin_wrong_module)
1489 << ModuleName.front().first << (ModuleName.size() > 1)
1490 << Current.empty() << Current;
1494 // Find the module we're entering. We require that a module map for it
1495 // be loaded or implicitly loadable.
1496 // FIXME: We could create the submodule here. We'd need to know whether
1497 // it's supposed to be explicit, but not much else.
1498 Module *M = PP.getHeaderSearchInfo().lookupModule(Current);
1500 PP.Diag(ModuleName.front().second,
1501 diag::err_pp_module_begin_no_module_map) << Current;
1504 for (unsigned I = 1; I != ModuleName.size(); ++I) {
1505 auto *NewM = M->findSubmodule(ModuleName[I].first->getName());
1507 PP.Diag(ModuleName[I].second, diag::err_pp_module_begin_no_submodule)
1508 << M->getFullModuleName() << ModuleName[I].first;
1514 // If the module isn't available, it doesn't make sense to enter it.
1515 if (Preprocessor::checkModuleIsAvailable(
1516 PP.getLangOpts(), PP.getTargetInfo(), PP.getDiagnostics(), M)) {
1517 PP.Diag(BeginLoc, diag::note_pp_module_begin_here)
1518 << M->getTopLevelModuleName();
1522 // Enter the scope of the submodule.
1523 PP.EnterSubmodule(M, BeginLoc, /*ForPragma*/true);
1524 PP.EnterAnnotationToken(SourceRange(BeginLoc, ModuleName.back().second),
1525 tok::annot_module_begin, M);
1529 /// Handle the clang \#pragma module end extension.
1530 struct PragmaModuleEndHandler : public PragmaHandler {
1531 PragmaModuleEndHandler() : PragmaHandler("end") {}
1533 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1534 Token &Tok) override {
1535 SourceLocation Loc = Tok.getLocation();
1537 PP.LexUnexpandedToken(Tok);
1538 if (Tok.isNot(tok::eod))
1539 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1541 Module *M = PP.LeaveSubmodule(/*ForPragma*/true);
1543 PP.EnterAnnotationToken(SourceRange(Loc), tok::annot_module_end, M);
1545 PP.Diag(Loc, diag::err_pp_module_end_without_module_begin);
1549 /// Handle the clang \#pragma module build extension.
1550 struct PragmaModuleBuildHandler : public PragmaHandler {
1551 PragmaModuleBuildHandler() : PragmaHandler("build") {}
1553 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1554 Token &Tok) override {
1555 PP.HandlePragmaModuleBuild(Tok);
1559 /// Handle the clang \#pragma module load extension.
1560 struct PragmaModuleLoadHandler : public PragmaHandler {
1561 PragmaModuleLoadHandler() : PragmaHandler("load") {}
1563 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1564 Token &Tok) override {
1565 SourceLocation Loc = Tok.getLocation();
1567 // Read the module name.
1568 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1570 if (LexModuleName(PP, Tok, ModuleName))
1573 if (Tok.isNot(tok::eod))
1574 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1576 // Load the module, don't make it visible.
1577 PP.getModuleLoader().loadModule(Loc, ModuleName, Module::Hidden,
1578 /*IsIncludeDirective=*/false);
1582 /// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
1583 /// macro on the top of the stack.
1584 struct PragmaPushMacroHandler : public PragmaHandler {
1585 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
1587 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1588 Token &PushMacroTok) override {
1589 PP.HandlePragmaPushMacro(PushMacroTok);
1593 /// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
1594 /// macro to the value on the top of the stack.
1595 struct PragmaPopMacroHandler : public PragmaHandler {
1596 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
1598 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1599 Token &PopMacroTok) override {
1600 PP.HandlePragmaPopMacro(PopMacroTok);
1604 // Pragma STDC implementations.
1606 /// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
1607 struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
1608 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
1610 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1611 Token &Tok) override {
1612 tok::OnOffSwitch OOS;
1613 if (PP.LexOnOffSwitch(OOS))
1615 if (OOS == tok::OOS_ON)
1616 PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
1620 /// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
1621 struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
1622 PragmaSTDC_CX_LIMITED_RANGEHandler() : PragmaHandler("CX_LIMITED_RANGE") {}
1624 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1625 Token &Tok) override {
1626 tok::OnOffSwitch OOS;
1627 PP.LexOnOffSwitch(OOS);
1631 /// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
1632 struct PragmaSTDC_UnknownHandler : public PragmaHandler {
1633 PragmaSTDC_UnknownHandler() = default;
1635 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1636 Token &UnknownTok) override {
1637 // C99 6.10.6p2, unknown forms are not allowed.
1638 PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
1642 /// PragmaARCCFCodeAuditedHandler -
1643 /// \#pragma clang arc_cf_code_audited begin/end
1644 struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1645 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
1647 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1648 Token &NameTok) override {
1649 SourceLocation Loc = NameTok.getLocation();
1654 // Lex the 'begin' or 'end'.
1655 PP.LexUnexpandedToken(Tok);
1656 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1657 if (BeginEnd && BeginEnd->isStr("begin")) {
1659 } else if (BeginEnd && BeginEnd->isStr("end")) {
1662 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1666 // Verify that this is followed by EOD.
1667 PP.LexUnexpandedToken(Tok);
1668 if (Tok.isNot(tok::eod))
1669 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1671 // The start location of the active audit.
1672 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1674 // The start location we want after processing this.
1675 SourceLocation NewLoc;
1678 // Complain about attempts to re-enter an audit.
1679 if (BeginLoc.isValid()) {
1680 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1681 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1685 // Complain about attempts to leave an audit that doesn't exist.
1686 if (!BeginLoc.isValid()) {
1687 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1690 NewLoc = SourceLocation();
1693 PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1697 /// PragmaAssumeNonNullHandler -
1698 /// \#pragma clang assume_nonnull begin/end
1699 struct PragmaAssumeNonNullHandler : public PragmaHandler {
1700 PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
1702 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1703 Token &NameTok) override {
1704 SourceLocation Loc = NameTok.getLocation();
1709 // Lex the 'begin' or 'end'.
1710 PP.LexUnexpandedToken(Tok);
1711 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1712 if (BeginEnd && BeginEnd->isStr("begin")) {
1714 } else if (BeginEnd && BeginEnd->isStr("end")) {
1717 PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
1721 // Verify that this is followed by EOD.
1722 PP.LexUnexpandedToken(Tok);
1723 if (Tok.isNot(tok::eod))
1724 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1726 // The start location of the active audit.
1727 SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
1729 // The start location we want after processing this.
1730 SourceLocation NewLoc;
1731 PPCallbacks *Callbacks = PP.getPPCallbacks();
1734 // Complain about attempts to re-enter an audit.
1735 if (BeginLoc.isValid()) {
1736 PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
1737 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1741 Callbacks->PragmaAssumeNonNullBegin(NewLoc);
1743 // Complain about attempts to leave an audit that doesn't exist.
1744 if (!BeginLoc.isValid()) {
1745 PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
1748 NewLoc = SourceLocation();
1750 Callbacks->PragmaAssumeNonNullEnd(NewLoc);
1753 PP.setPragmaAssumeNonNullLoc(NewLoc);
1757 /// \brief Handle "\#pragma region [...]"
1761 /// #pragma region [optional name]
1762 /// #pragma endregion [optional comment]
1766 /// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1767 /// pragma, just skipped by compiler.
1768 struct PragmaRegionHandler : public PragmaHandler {
1769 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) {}
1771 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1772 Token &NameTok) override {
1773 // #pragma region: endregion matches can be verified
1774 // __pragma(region): no sense, but ignored by msvc
1775 // _Pragma is not valid for MSVC, but there isn't any point
1776 // to handle a _Pragma differently.
1782 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
1783 /// \#pragma GCC poison/system_header/dependency and \#pragma once.
1784 void Preprocessor::RegisterBuiltinPragmas() {
1785 AddPragmaHandler(new PragmaOnceHandler());
1786 AddPragmaHandler(new PragmaMarkHandler());
1787 AddPragmaHandler(new PragmaPushMacroHandler());
1788 AddPragmaHandler(new PragmaPopMacroHandler());
1789 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
1792 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1793 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1794 AddPragmaHandler("GCC", new PragmaDependencyHandler());
1795 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
1796 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1798 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1800 // #pragma clang ...
1801 AddPragmaHandler("clang", new PragmaPoisonHandler());
1802 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
1803 AddPragmaHandler("clang", new PragmaDebugHandler());
1804 AddPragmaHandler("clang", new PragmaDependencyHandler());
1805 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
1806 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
1807 AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
1809 // #pragma clang module ...
1810 auto *ModuleHandler = new PragmaNamespace("module");
1811 AddPragmaHandler("clang", ModuleHandler);
1812 ModuleHandler->AddPragma(new PragmaModuleImportHandler());
1813 ModuleHandler->AddPragma(new PragmaModuleBeginHandler());
1814 ModuleHandler->AddPragma(new PragmaModuleEndHandler());
1815 ModuleHandler->AddPragma(new PragmaModuleBuildHandler());
1816 ModuleHandler->AddPragma(new PragmaModuleLoadHandler());
1818 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1819 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
1820 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
1823 if (LangOpts.MicrosoftExt) {
1824 AddPragmaHandler(new PragmaWarningHandler());
1825 AddPragmaHandler(new PragmaIncludeAliasHandler());
1826 AddPragmaHandler(new PragmaRegionHandler("region"));
1827 AddPragmaHandler(new PragmaRegionHandler("endregion"));
1830 // Pragmas added by plugins
1831 for (PragmaHandlerRegistry::iterator it = PragmaHandlerRegistry::begin(),
1832 ie = PragmaHandlerRegistry::end();
1834 AddPragmaHandler(it->instantiate().release());
1838 /// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
1839 /// warn about those pragmas being unknown.
1840 void Preprocessor::IgnorePragmas() {
1841 AddPragmaHandler(new EmptyPragmaHandler());
1842 // Also ignore all pragmas in all namespaces created
1843 // in Preprocessor::RegisterBuiltinPragmas().
1844 AddPragmaHandler("GCC", new EmptyPragmaHandler());
1845 AddPragmaHandler("clang", new EmptyPragmaHandler());
1846 if (PragmaHandler *NS = PragmaHandlers->FindHandler("STDC")) {
1847 // Preprocessor::RegisterBuiltinPragmas() already registers
1848 // PragmaSTDC_UnknownHandler as the empty handler, so remove it first,
1849 // otherwise there will be an assert about a duplicate handler.
1850 PragmaNamespace *STDCNamespace = NS->getIfNamespace();
1851 assert(STDCNamespace &&
1852 "Invalid namespace, registered as a regular pragma handler!");
1853 if (PragmaHandler *Existing = STDCNamespace->FindHandler("", false)) {
1854 RemovePragmaHandler("STDC", Existing);
1858 AddPragmaHandler("STDC", new EmptyPragmaHandler());