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/MacroInfo.h"
24 #include "clang/Lex/PPCallbacks.h"
25 #include "clang/Lex/Preprocessor.h"
26 #include "clang/Lex/PreprocessorLexer.h"
27 #include "clang/Lex/PTHLexer.h"
28 #include "clang/Lex/Token.h"
29 #include "clang/Lex/TokenLexer.h"
30 #include "llvm/ADT/ArrayRef.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/SmallString.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/StringSwitch.h"
36 #include "llvm/Support/CrashRecoveryContext.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Support/ErrorHandling.h"
46 using namespace clang;
48 // Out-of-line destructor to provide a home for the class.
49 PragmaHandler::~PragmaHandler() {
52 //===----------------------------------------------------------------------===//
53 // EmptyPragmaHandler Implementation.
54 //===----------------------------------------------------------------------===//
56 EmptyPragmaHandler::EmptyPragmaHandler(StringRef Name) : PragmaHandler(Name) {}
58 void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
59 PragmaIntroducerKind Introducer,
62 //===----------------------------------------------------------------------===//
63 // PragmaNamespace Implementation.
64 //===----------------------------------------------------------------------===//
66 PragmaNamespace::~PragmaNamespace() {
67 llvm::DeleteContainerSeconds(Handlers);
70 /// FindHandler - Check to see if there is already a handler for the
71 /// specified name. If not, return the handler for the null identifier if it
72 /// exists, otherwise return null. If IgnoreNull is true (the default) then
73 /// the null handler isn't returned on failure to match.
74 PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
75 bool IgnoreNull) const {
76 if (PragmaHandler *Handler = Handlers.lookup(Name))
78 return IgnoreNull ? nullptr : Handlers.lookup(StringRef());
81 void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
82 assert(!Handlers.lookup(Handler->getName()) &&
83 "A handler with this name is already registered in this namespace");
84 Handlers[Handler->getName()] = Handler;
87 void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
88 assert(Handlers.lookup(Handler->getName()) &&
89 "Handler not registered in this namespace");
90 Handlers.erase(Handler->getName());
93 void PragmaNamespace::HandlePragma(Preprocessor &PP,
94 PragmaIntroducerKind Introducer,
96 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
97 // expand it, the user can have a STDC #define, that should not affect this.
98 PP.LexUnexpandedToken(Tok);
100 // Get the handler for this token. If there is no handler, ignore the pragma.
101 PragmaHandler *Handler
102 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
104 /*IgnoreNull=*/false);
106 PP.Diag(Tok, diag::warn_pragma_ignored);
110 // Otherwise, pass it down.
111 Handler->HandlePragma(PP, Introducer, Tok);
114 //===----------------------------------------------------------------------===//
115 // Preprocessor Pragma Directive Handling.
116 //===----------------------------------------------------------------------===//
118 /// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the
119 /// rest of the pragma, passing it to the registered pragma handlers.
120 void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc,
121 PragmaIntroducerKind Introducer) {
123 Callbacks->PragmaDirective(IntroducerLoc, Introducer);
130 // Invoke the first level of pragma handlers which reads the namespace id.
132 PragmaHandlers->HandlePragma(*this, Introducer, Tok);
134 // If the pragma handler didn't read the rest of the line, consume it now.
135 if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
136 || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
137 DiscardUntilEndOfDirective();
142 /// \brief Helper class for \see Preprocessor::Handle_Pragma.
143 class LexingFor_PragmaRAII {
145 bool InMacroArgPreExpansion;
151 LexingFor_PragmaRAII(Preprocessor &PP, bool InMacroArgPreExpansion,
153 : PP(PP), InMacroArgPreExpansion(InMacroArgPreExpansion),
154 Failed(false), OutTok(Tok) {
155 if (InMacroArgPreExpansion) {
157 PP.EnableBacktrackAtThisPos();
161 ~LexingFor_PragmaRAII() {
162 if (InMacroArgPreExpansion) {
163 // When committing/backtracking the cached pragma tokens in a macro
164 // argument pre-expansion we want to ensure that either the tokens which
165 // have been committed will be removed from the cache or that the tokens
166 // over which we just backtracked won't remain in the cache after they're
167 // consumed and that the caching will stop after consuming them.
168 // Otherwise the caching will interfere with the way macro expansion
169 // works, because we will continue to cache tokens after consuming the
170 // backtracked tokens, which shouldn't happen when we're dealing with
171 // macro argument pre-expansion.
172 auto CachedTokenRange = PP.LastCachedTokenRange();
174 PP.CommitBacktrackedTokens();
179 PP.EraseCachedTokens(CachedTokenRange);
188 } // end anonymous namespace
190 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
191 /// return the first token after the directive. The _Pragma token has just
192 /// been read into 'Tok'.
193 void Preprocessor::Handle_Pragma(Token &Tok) {
195 // This works differently if we are pre-expanding a macro argument.
196 // In that case we don't actually "activate" the pragma now, we only lex it
197 // until we are sure it is lexically correct and then we backtrack so that
198 // we activate the pragma whenever we encounter the tokens again in the token
199 // stream. This ensures that we will activate it in the correct location
200 // or that we will ignore it if it never enters the token stream, e.g:
203 // #define INACTIVE(x) EMPTY(x)
204 // INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\""))
206 LexingFor_PragmaRAII _PragmaLexing(*this, InMacroArgPreExpansion, Tok);
208 // Remember the pragma token location.
209 SourceLocation PragmaLoc = Tok.getLocation();
213 if (Tok.isNot(tok::l_paren)) {
214 Diag(PragmaLoc, diag::err__Pragma_malformed);
215 return _PragmaLexing.failed();
220 if (!tok::isStringLiteral(Tok.getKind())) {
221 Diag(PragmaLoc, diag::err__Pragma_malformed);
222 // Skip bad tokens, and the ')', if present.
223 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
225 while (Tok.isNot(tok::r_paren) &&
226 !Tok.isAtStartOfLine() &&
229 if (Tok.is(tok::r_paren))
231 return _PragmaLexing.failed();
234 if (Tok.hasUDSuffix()) {
235 Diag(Tok, diag::err_invalid_string_udl);
236 // Skip this token, and the ')', if present.
238 if (Tok.is(tok::r_paren))
240 return _PragmaLexing.failed();
243 // Remember the string.
248 if (Tok.isNot(tok::r_paren)) {
249 Diag(PragmaLoc, diag::err__Pragma_malformed);
250 return _PragmaLexing.failed();
253 if (InMacroArgPreExpansion)
256 SourceLocation RParenLoc = Tok.getLocation();
257 std::string StrVal = getSpelling(StrTok);
259 // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1:
260 // "The string literal is destringized by deleting any encoding prefix,
261 // deleting the leading and trailing double-quotes, replacing each escape
262 // sequence \" by a double-quote, and replacing each escape sequence \\ by a
263 // single backslash."
264 if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
265 (StrVal[0] == 'u' && StrVal[1] != '8'))
266 StrVal.erase(StrVal.begin());
267 else if (StrVal[0] == 'u')
268 StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
270 if (StrVal[0] == 'R') {
271 // FIXME: C++11 does not specify how to handle raw-string-literals here.
272 // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
273 assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
274 "Invalid raw string token!");
276 // Measure the length of the d-char-sequence.
277 unsigned NumDChars = 0;
278 while (StrVal[2 + NumDChars] != '(') {
279 assert(NumDChars < (StrVal.size() - 5) / 2 &&
280 "Invalid raw string token!");
283 assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
285 // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
287 StrVal.erase(0, 2 + NumDChars);
288 StrVal.erase(StrVal.size() - 1 - NumDChars);
290 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
291 "Invalid string token!");
293 // Remove escaped quotes and escapes.
294 unsigned ResultPos = 1;
295 for (size_t i = 1, e = StrVal.size() - 1; i != e; ++i) {
296 // Skip escapes. \\ -> '\' and \" -> '"'.
297 if (StrVal[i] == '\\' && i + 1 < e &&
298 (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
300 StrVal[ResultPos++] = StrVal[i];
302 StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
305 // Remove the front quote, replacing it with a space, so that the pragma
306 // contents appear to have a space before them.
309 // Replace the terminating quote with a \n.
310 StrVal[StrVal.size()-1] = '\n';
312 // Plop the string (including the newline and trailing null) into a buffer
313 // where we can lex it.
316 CreateString(StrVal, TmpTok);
317 SourceLocation TokLoc = TmpTok.getLocation();
319 // Make and enter a lexer object so that we lex and expand the tokens just
321 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
322 StrVal.size(), *this);
324 EnterSourceFileWithLexer(TL, nullptr);
326 // With everything set up, lex this as a #pragma directive.
327 HandlePragmaDirective(PragmaLoc, PIK__Pragma);
329 // Finally, return whatever came after the pragma directive.
333 /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
334 /// is not enclosed within a string literal.
335 void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
336 // Remember the pragma token location.
337 SourceLocation PragmaLoc = Tok.getLocation();
341 if (Tok.isNot(tok::l_paren)) {
342 Diag(PragmaLoc, diag::err__Pragma_malformed);
346 // Get the tokens enclosed within the __pragma(), as well as the final ')'.
347 SmallVector<Token, 32> PragmaToks;
350 while (Tok.isNot(tok::eof)) {
351 PragmaToks.push_back(Tok);
352 if (Tok.is(tok::l_paren))
354 else if (Tok.is(tok::r_paren) && NumParens-- == 0)
359 if (Tok.is(tok::eof)) {
360 Diag(PragmaLoc, diag::err_unterminated___pragma);
364 PragmaToks.front().setFlag(Token::LeadingSpace);
366 // Replace the ')' with an EOD to mark the end of the pragma.
367 PragmaToks.back().setKind(tok::eod);
369 Token *TokArray = new Token[PragmaToks.size()];
370 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
372 // Push the tokens onto the stack.
373 EnterTokenStream(TokArray, PragmaToks.size(), true, true);
375 // With everything set up, lex this as a #pragma directive.
376 HandlePragmaDirective(PragmaLoc, PIK___pragma);
378 // Finally, return whatever came after the pragma directive.
382 /// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
384 void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
385 // Don't honor the 'once' when handling the primary source file, unless
386 // this is a prefix to a TU, which indicates we're generating a PCH file, or
387 // when the main file is a header (e.g. when -xc-header is provided on the
389 if (isInPrimaryFile() && TUKind != TU_Prefix && !getLangOpts().IsHeaderFile) {
390 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
394 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
395 // Mark the file as a once-only file now.
396 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
399 void Preprocessor::HandlePragmaMark() {
400 assert(CurPPLexer && "No current lexer?");
402 CurLexer->ReadToEndOfLine();
404 CurPTHLexer->DiscardToEndOfLine();
407 /// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
409 void Preprocessor::HandlePragmaPoison() {
413 // Read the next token to poison. While doing this, pretend that we are
414 // skipping while reading the identifier to poison.
415 // This avoids errors on code like:
416 // #pragma GCC poison X
417 // #pragma GCC poison X
418 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
419 LexUnexpandedToken(Tok);
420 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
422 // If we reached the end of line, we're done.
423 if (Tok.is(tok::eod)) return;
425 // Can only poison identifiers.
426 if (Tok.isNot(tok::raw_identifier)) {
427 Diag(Tok, diag::err_pp_invalid_poison);
431 // Look up the identifier info for the token. We disabled identifier lookup
432 // by saying we're skipping contents, so we need to do this manually.
433 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
436 if (II->isPoisoned()) continue;
438 // If this is a macro identifier, emit a warning.
439 if (isMacroDefined(II))
440 Diag(Tok, diag::pp_poisoning_existing_macro);
442 // Finally, poison it!
445 II->setChangedSinceDeserialization();
449 /// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
450 /// that the whole directive has been parsed.
451 void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
452 if (isInPrimaryFile()) {
453 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
457 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
458 PreprocessorLexer *TheLexer = getCurrentFileLexer();
460 // Mark the file as a system header.
461 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
464 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
465 if (PLoc.isInvalid())
468 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
470 // Notify the client, if desired, that we are in a new source file.
472 Callbacks->FileChanged(SysHeaderTok.getLocation(),
473 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
475 // Emit a line marker. This will change any source locations from this point
476 // forward to realize they are in a system header.
477 // Create a line note with this information.
478 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine() + 1,
479 FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
483 /// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
485 void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
487 CurPPLexer->LexIncludeFilename(FilenameTok);
489 // If the token kind is EOD, the error has already been diagnosed.
490 if (FilenameTok.is(tok::eod))
493 // Reserve a buffer to get the spelling.
494 SmallString<128> FilenameBuffer;
495 bool Invalid = false;
496 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
501 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
502 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
504 if (Filename.empty())
507 // Search include directories for this file.
508 const DirectoryLookup *CurDir;
509 const FileEntry *File =
510 LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
511 nullptr, CurDir, nullptr, nullptr, nullptr, nullptr);
513 if (!SuppressIncludeNotFoundError)
514 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
518 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
520 // If this file is older than the file it depends on, emit a diagnostic.
521 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
522 // Lex tokens at the end of the message and include them in the message.
525 while (DependencyTok.isNot(tok::eod)) {
526 Message += getSpelling(DependencyTok) + " ";
530 // Remove the trailing ' ' if present.
531 if (!Message.empty())
532 Message.erase(Message.end()-1);
533 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
537 /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
538 /// Return the IdentifierInfo* associated with the macro to push or pop.
539 IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
540 // Remember the pragma token location.
541 Token PragmaTok = Tok;
545 if (Tok.isNot(tok::l_paren)) {
546 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
547 << getSpelling(PragmaTok);
551 // Read the macro name string.
553 if (Tok.isNot(tok::string_literal)) {
554 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
555 << getSpelling(PragmaTok);
559 if (Tok.hasUDSuffix()) {
560 Diag(Tok, diag::err_invalid_string_udl);
564 // Remember the macro string.
565 std::string StrVal = getSpelling(Tok);
569 if (Tok.isNot(tok::r_paren)) {
570 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
571 << getSpelling(PragmaTok);
575 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
576 "Invalid string token!");
578 // Create a Token from the string.
580 MacroTok.startToken();
581 MacroTok.setKind(tok::raw_identifier);
582 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
584 // Get the IdentifierInfo of MacroToPushTok.
585 return LookUpIdentifierInfo(MacroTok);
588 /// \brief Handle \#pragma push_macro.
592 /// #pragma push_macro("macro")
594 void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
595 // Parse the pragma directive and get the macro IdentifierInfo*.
596 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
597 if (!IdentInfo) return;
599 // Get the MacroInfo associated with IdentInfo.
600 MacroInfo *MI = getMacroInfo(IdentInfo);
603 // Allow the original MacroInfo to be redefined later.
604 MI->setIsAllowRedefinitionsWithoutWarning(true);
607 // Push the cloned MacroInfo so we can retrieve it later.
608 PragmaPushMacroInfo[IdentInfo].push_back(MI);
611 /// \brief Handle \#pragma pop_macro.
615 /// #pragma pop_macro("macro")
617 void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
618 SourceLocation MessageLoc = PopMacroTok.getLocation();
620 // Parse the pragma directive and get the macro IdentifierInfo*.
621 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
622 if (!IdentInfo) return;
624 // Find the vector<MacroInfo*> associated with the macro.
625 llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
626 PragmaPushMacroInfo.find(IdentInfo);
627 if (iter != PragmaPushMacroInfo.end()) {
628 // Forget the MacroInfo currently associated with IdentInfo.
629 if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
630 if (MI->isWarnIfUnused())
631 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
632 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
635 // Get the MacroInfo we want to reinstall.
636 MacroInfo *MacroToReInstall = iter->second.back();
638 if (MacroToReInstall)
639 // Reinstall the previously pushed macro.
640 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
642 // Pop PragmaPushMacroInfo stack.
643 iter->second.pop_back();
644 if (iter->second.empty())
645 PragmaPushMacroInfo.erase(iter);
647 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
648 << IdentInfo->getName();
652 void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
653 // We will either get a quoted filename or a bracketed filename, and we
654 // have to track which we got. The first filename is the source name,
655 // and the second name is the mapped filename. If the first is quoted,
656 // the second must be as well (cannot mix and match quotes and brackets).
658 // Get the open paren
660 if (Tok.isNot(tok::l_paren)) {
661 Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
665 // We expect either a quoted string literal, or a bracketed name
666 Token SourceFilenameTok;
667 CurPPLexer->LexIncludeFilename(SourceFilenameTok);
668 if (SourceFilenameTok.is(tok::eod)) {
669 // The diagnostic has already been handled
673 StringRef SourceFileName;
674 SmallString<128> FileNameBuffer;
675 if (SourceFilenameTok.is(tok::string_literal) ||
676 SourceFilenameTok.is(tok::angle_string_literal)) {
677 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
678 } else if (SourceFilenameTok.is(tok::less)) {
679 // This could be a path instead of just a name
680 FileNameBuffer.push_back('<');
682 if (ConcatenateIncludeName(FileNameBuffer, End))
683 return; // Diagnostic already emitted
684 SourceFileName = FileNameBuffer;
686 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
689 FileNameBuffer.clear();
691 // Now we expect a comma, followed by another include name
693 if (Tok.isNot(tok::comma)) {
694 Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
698 Token ReplaceFilenameTok;
699 CurPPLexer->LexIncludeFilename(ReplaceFilenameTok);
700 if (ReplaceFilenameTok.is(tok::eod)) {
701 // The diagnostic has already been handled
705 StringRef ReplaceFileName;
706 if (ReplaceFilenameTok.is(tok::string_literal) ||
707 ReplaceFilenameTok.is(tok::angle_string_literal)) {
708 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
709 } else if (ReplaceFilenameTok.is(tok::less)) {
710 // This could be a path instead of just a name
711 FileNameBuffer.push_back('<');
713 if (ConcatenateIncludeName(FileNameBuffer, End))
714 return; // Diagnostic already emitted
715 ReplaceFileName = FileNameBuffer;
717 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
721 // Finally, we expect the closing paren
723 if (Tok.isNot(tok::r_paren)) {
724 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
728 // Now that we have the source and target filenames, we need to make sure
729 // they're both of the same type (angled vs non-angled)
730 StringRef OriginalSource = SourceFileName;
732 bool SourceIsAngled =
733 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
735 bool ReplaceIsAngled =
736 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
738 if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
739 (SourceIsAngled != ReplaceIsAngled)) {
742 DiagID = diag::warn_pragma_include_alias_mismatch_angle;
744 DiagID = diag::warn_pragma_include_alias_mismatch_quote;
746 Diag(SourceFilenameTok.getLocation(), DiagID)
753 // Now we can let the include handler know about this mapping
754 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
757 void Preprocessor::HandlePragmaModuleBuild(Token &Tok) {
758 SourceLocation Loc = Tok.getLocation();
760 LexUnexpandedToken(Tok);
761 if (Tok.isAnnotation() || !Tok.getIdentifierInfo()) {
762 Diag(Tok.getLocation(), diag::err_pp_expected_module_name) << true;
765 IdentifierInfo *ModuleName = Tok.getIdentifierInfo();
767 LexUnexpandedToken(Tok);
768 if (Tok.isNot(tok::eod)) {
769 Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
770 DiscardUntilEndOfDirective();
774 // FIXME: Support this somehow?
775 Diag(Loc, diag::err_pp_module_build_pth);
779 CurLexer->LexingRawMode = true;
781 auto TryConsumeIdentifier = [&](StringRef Ident) -> bool {
782 if (Tok.getKind() != tok::raw_identifier ||
783 Tok.getRawIdentifier() != Ident)
789 // Scan forward looking for the end of the module.
790 const char *Start = CurLexer->getBufferLocation();
791 const char *End = nullptr;
792 unsigned NestingLevel = 1;
794 End = CurLexer->getBufferLocation();
797 if (Tok.is(tok::eof)) {
798 Diag(Loc, diag::err_pp_module_build_missing_end);
802 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) {
803 // Token was part of module; keep going.
807 // We hit something directive-shaped; check to see if this is the end
808 // of the module build.
809 CurLexer->ParsingPreprocessorDirective = true;
811 if (TryConsumeIdentifier("pragma") && TryConsumeIdentifier("clang") &&
812 TryConsumeIdentifier("module")) {
813 if (TryConsumeIdentifier("build"))
814 // #pragma clang module build -> entering a nested module build.
816 else if (TryConsumeIdentifier("endbuild")) {
817 // #pragma clang module endbuild -> leaving a module build.
818 if (--NestingLevel == 0)
821 // We should either be looking at the EOD or more of the current directive
822 // preceding the EOD. Either way we can ignore this token and keep going.
823 assert(Tok.getKind() != tok::eof && "missing EOD before EOF");
827 CurLexer->LexingRawMode = false;
829 // Load the extracted text as a preprocessed module.
830 assert(CurLexer->getBuffer().begin() <= Start &&
831 Start <= CurLexer->getBuffer().end() &&
832 CurLexer->getBuffer().begin() <= End &&
833 End <= CurLexer->getBuffer().end() &&
834 "module source range not contained within same file buffer");
835 TheModuleLoader.loadModuleFromSource(Loc, ModuleName->getName(),
836 StringRef(Start, End - Start));
839 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
840 /// If 'Namespace' is non-null, then it is a token required to exist on the
841 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
842 void Preprocessor::AddPragmaHandler(StringRef Namespace,
843 PragmaHandler *Handler) {
844 PragmaNamespace *InsertNS = PragmaHandlers.get();
846 // If this is specified to be in a namespace, step down into it.
847 if (!Namespace.empty()) {
848 // If there is already a pragma handler with the name of this namespace,
849 // we either have an error (directive with the same name as a namespace) or
850 // we already have the namespace to insert into.
851 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
852 InsertNS = Existing->getIfNamespace();
853 assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
854 " handler with the same name!");
856 // Otherwise, this namespace doesn't exist yet, create and insert the
858 InsertNS = new PragmaNamespace(Namespace);
859 PragmaHandlers->AddPragma(InsertNS);
863 // Check to make sure we don't already have a pragma for this identifier.
864 assert(!InsertNS->FindHandler(Handler->getName()) &&
865 "Pragma handler already exists for this identifier!");
866 InsertNS->AddPragma(Handler);
869 /// RemovePragmaHandler - Remove the specific pragma handler from the
870 /// preprocessor. If \arg Namespace is non-null, then it should be the
871 /// namespace that \arg Handler was added to. It is an error to remove
872 /// a handler that has not been registered.
873 void Preprocessor::RemovePragmaHandler(StringRef Namespace,
874 PragmaHandler *Handler) {
875 PragmaNamespace *NS = PragmaHandlers.get();
877 // If this is specified to be in a namespace, step down into it.
878 if (!Namespace.empty()) {
879 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
880 assert(Existing && "Namespace containing handler does not exist!");
882 NS = Existing->getIfNamespace();
883 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
886 NS->RemovePragmaHandler(Handler);
888 // If this is a non-default namespace and it is now empty, remove it.
889 if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
890 PragmaHandlers->RemovePragmaHandler(NS);
895 bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
897 LexUnexpandedToken(Tok);
899 if (Tok.isNot(tok::identifier)) {
900 Diag(Tok, diag::ext_on_off_switch_syntax);
903 IdentifierInfo *II = Tok.getIdentifierInfo();
905 Result = tok::OOS_ON;
906 else if (II->isStr("OFF"))
907 Result = tok::OOS_OFF;
908 else if (II->isStr("DEFAULT"))
909 Result = tok::OOS_DEFAULT;
911 Diag(Tok, diag::ext_on_off_switch_syntax);
915 // Verify that this is followed by EOD.
916 LexUnexpandedToken(Tok);
917 if (Tok.isNot(tok::eod))
918 Diag(Tok, diag::ext_pragma_syntax_eod);
924 /// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
925 struct PragmaOnceHandler : public PragmaHandler {
926 PragmaOnceHandler() : PragmaHandler("once") {}
927 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
928 Token &OnceTok) override {
929 PP.CheckEndOfDirective("pragma once");
930 PP.HandlePragmaOnce(OnceTok);
934 /// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
935 /// rest of the line is not lexed.
936 struct PragmaMarkHandler : public PragmaHandler {
937 PragmaMarkHandler() : PragmaHandler("mark") {}
939 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
940 Token &MarkTok) override {
941 PP.HandlePragmaMark();
945 /// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
946 struct PragmaPoisonHandler : public PragmaHandler {
947 PragmaPoisonHandler() : PragmaHandler("poison") {}
949 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
950 Token &PoisonTok) override {
951 PP.HandlePragmaPoison();
955 /// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
956 /// as a system header, which silences warnings in it.
957 struct PragmaSystemHeaderHandler : public PragmaHandler {
958 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
960 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
961 Token &SHToken) override {
962 PP.HandlePragmaSystemHeader(SHToken);
963 PP.CheckEndOfDirective("pragma");
967 struct PragmaDependencyHandler : public PragmaHandler {
968 PragmaDependencyHandler() : PragmaHandler("dependency") {}
970 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
971 Token &DepToken) override {
972 PP.HandlePragmaDependency(DepToken);
976 struct PragmaDebugHandler : public PragmaHandler {
977 PragmaDebugHandler() : PragmaHandler("__debug") {}
979 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
980 Token &DepToken) override {
982 PP.LexUnexpandedToken(Tok);
983 if (Tok.isNot(tok::identifier)) {
984 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
987 IdentifierInfo *II = Tok.getIdentifierInfo();
989 if (II->isStr("assert")) {
990 llvm_unreachable("This is an assertion!");
991 } else if (II->isStr("crash")) {
993 } else if (II->isStr("parser_crash")) {
995 Crasher.startToken();
996 Crasher.setKind(tok::annot_pragma_parser_crash);
997 Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
998 PP.EnterToken(Crasher);
999 } else if (II->isStr("dump")) {
1001 PP.LexUnexpandedToken(Identifier);
1002 if (auto *DumpII = Identifier.getIdentifierInfo()) {
1004 DumpAnnot.startToken();
1005 DumpAnnot.setKind(tok::annot_pragma_dump);
1006 DumpAnnot.setAnnotationRange(
1007 SourceRange(Tok.getLocation(), Identifier.getLocation()));
1008 DumpAnnot.setAnnotationValue(DumpII);
1009 PP.DiscardUntilEndOfDirective();
1010 PP.EnterToken(DumpAnnot);
1012 PP.Diag(Identifier, diag::warn_pragma_debug_missing_argument)
1015 } else if (II->isStr("llvm_fatal_error")) {
1016 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
1017 } else if (II->isStr("llvm_unreachable")) {
1018 llvm_unreachable("#pragma clang __debug llvm_unreachable");
1019 } else if (II->isStr("macro")) {
1021 PP.LexUnexpandedToken(MacroName);
1022 auto *MacroII = MacroName.getIdentifierInfo();
1024 PP.dumpMacroInfo(MacroII);
1026 PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument)
1028 } else if (II->isStr("overflow_stack")) {
1029 DebugOverflowStack();
1030 } else if (II->isStr("handle_crash")) {
1031 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
1034 } else if (II->isStr("captured")) {
1037 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
1041 PPCallbacks *Callbacks = PP.getPPCallbacks();
1043 Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
1046 void HandleCaptured(Preprocessor &PP) {
1047 // Skip if emitting preprocessed output.
1048 if (PP.isPreprocessedOutput())
1052 PP.LexUnexpandedToken(Tok);
1054 if (Tok.isNot(tok::eod)) {
1055 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
1056 << "pragma clang __debug captured";
1060 SourceLocation NameLoc = Tok.getLocation();
1061 MutableArrayRef<Token> Toks(
1062 PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
1063 Toks[0].startToken();
1064 Toks[0].setKind(tok::annot_pragma_captured);
1065 Toks[0].setLocation(NameLoc);
1067 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
1070 // Disable MSVC warning about runtime stack overflow.
1072 #pragma warning(disable : 4717)
1074 static void DebugOverflowStack(void (*P)() = nullptr) {
1075 void (*volatile Self)(void(*P)()) = DebugOverflowStack;
1076 Self(reinterpret_cast<void(*)()>(Self));
1079 #pragma warning(default : 4717)
1084 /// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
1085 struct PragmaDiagnosticHandler : public PragmaHandler {
1087 const char *Namespace;
1090 explicit PragmaDiagnosticHandler(const char *NS) :
1091 PragmaHandler("diagnostic"), Namespace(NS) {}
1093 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1094 Token &DiagToken) override {
1095 SourceLocation DiagLoc = DiagToken.getLocation();
1097 PP.LexUnexpandedToken(Tok);
1098 if (Tok.isNot(tok::identifier)) {
1099 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1102 IdentifierInfo *II = Tok.getIdentifierInfo();
1103 PPCallbacks *Callbacks = PP.getPPCallbacks();
1105 if (II->isStr("pop")) {
1106 if (!PP.getDiagnostics().popMappings(DiagLoc))
1107 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
1109 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
1111 } else if (II->isStr("push")) {
1112 PP.getDiagnostics().pushMappings(DiagLoc);
1114 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
1118 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
1119 .Case("ignored", diag::Severity::Ignored)
1120 .Case("warning", diag::Severity::Warning)
1121 .Case("error", diag::Severity::Error)
1122 .Case("fatal", diag::Severity::Fatal)
1123 .Default(diag::Severity());
1125 if (SV == diag::Severity()) {
1126 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1130 PP.LexUnexpandedToken(Tok);
1131 SourceLocation StringLoc = Tok.getLocation();
1133 std::string WarningName;
1134 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
1135 /*MacroExpansion=*/false))
1138 if (Tok.isNot(tok::eod)) {
1139 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1143 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1144 (WarningName[1] != 'W' && WarningName[1] != 'R')) {
1145 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
1149 diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1150 : diag::Flavor::Remark;
1151 StringRef Group = StringRef(WarningName).substr(2);
1152 bool unknownDiag = false;
1153 if (Group == "everything") {
1154 // Special handling for pragma clang diagnostic ... "-Weverything".
1155 // There is no formal group named "everything", so there has to be a
1156 // special case for it.
1157 PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc);
1159 unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV,
1162 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1165 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
1169 /// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1170 /// diagnostics, so we don't really implement this pragma. We parse it and
1171 /// ignore it to avoid -Wunknown-pragma warnings.
1172 struct PragmaWarningHandler : public PragmaHandler {
1173 PragmaWarningHandler() : PragmaHandler("warning") {}
1175 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1176 Token &Tok) override {
1177 // Parse things like:
1180 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
1181 SourceLocation DiagLoc = Tok.getLocation();
1182 PPCallbacks *Callbacks = PP.getPPCallbacks();
1185 if (Tok.isNot(tok::l_paren)) {
1186 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1191 IdentifierInfo *II = Tok.getIdentifierInfo();
1193 if (II && II->isStr("push")) {
1194 // #pragma warning( push[ ,n ] )
1197 if (Tok.is(tok::comma)) {
1200 if (Tok.is(tok::numeric_constant) &&
1201 PP.parseSimpleIntegerLiteral(Tok, Value))
1203 if (Level < 0 || Level > 4) {
1204 PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1209 Callbacks->PragmaWarningPush(DiagLoc, Level);
1210 } else if (II && II->isStr("pop")) {
1211 // #pragma warning( pop )
1214 Callbacks->PragmaWarningPop(DiagLoc);
1216 // #pragma warning( warning-specifier : warning-number-list
1217 // [; warning-specifier : warning-number-list...] )
1219 II = Tok.getIdentifierInfo();
1220 if (!II && !Tok.is(tok::numeric_constant)) {
1221 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1225 // Figure out which warning specifier this is.
1226 bool SpecifierValid;
1227 StringRef Specifier;
1228 llvm::SmallString<1> SpecifierBuf;
1230 Specifier = II->getName();
1231 SpecifierValid = llvm::StringSwitch<bool>(Specifier)
1232 .Cases("default", "disable", "error", "once",
1235 // If we read a correct specifier, snatch next token (that should be
1236 // ":", checked later).
1240 // Token is a numeric constant. It should be either 1, 2, 3 or 4.
1242 Specifier = PP.getSpelling(Tok, SpecifierBuf);
1243 if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
1244 SpecifierValid = (Value >= 1) && (Value <= 4);
1246 SpecifierValid = false;
1247 // Next token already snatched by parseSimpleIntegerLiteral.
1250 if (!SpecifierValid) {
1251 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1254 if (Tok.isNot(tok::colon)) {
1255 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1259 // Collect the warning ids.
1260 SmallVector<int, 4> Ids;
1262 while (Tok.is(tok::numeric_constant)) {
1264 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
1265 Value > std::numeric_limits<int>::max()) {
1266 PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1269 Ids.push_back(int(Value));
1272 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1274 // Parse the next specifier if there is a semicolon.
1275 if (Tok.isNot(tok::semi))
1281 if (Tok.isNot(tok::r_paren)) {
1282 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1287 if (Tok.isNot(tok::eod))
1288 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1292 /// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
1293 struct PragmaIncludeAliasHandler : public PragmaHandler {
1294 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
1295 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1296 Token &IncludeAliasTok) override {
1297 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
1301 /// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1302 /// extension. The syntax is:
1304 /// #pragma message(string)
1306 /// OR, in GCC mode:
1308 /// #pragma message string
1310 /// string is a string, which is fully macro expanded, and permits string
1311 /// concatenation, embedded escape characters, etc... See MSDN for more details.
1312 /// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1313 /// form as \#pragma message.
1314 struct PragmaMessageHandler : public PragmaHandler {
1316 const PPCallbacks::PragmaMessageKind Kind;
1317 const StringRef Namespace;
1319 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1320 bool PragmaNameOnly = false) {
1322 case PPCallbacks::PMK_Message:
1323 return PragmaNameOnly ? "message" : "pragma message";
1324 case PPCallbacks::PMK_Warning:
1325 return PragmaNameOnly ? "warning" : "pragma warning";
1326 case PPCallbacks::PMK_Error:
1327 return PragmaNameOnly ? "error" : "pragma error";
1329 llvm_unreachable("Unknown PragmaMessageKind!");
1333 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1334 StringRef Namespace = StringRef())
1335 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), Namespace(Namespace) {}
1337 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1338 Token &Tok) override {
1339 SourceLocation MessageLoc = Tok.getLocation();
1341 bool ExpectClosingParen = false;
1342 switch (Tok.getKind()) {
1344 // We have a MSVC style pragma message.
1345 ExpectClosingParen = true;
1349 case tok::string_literal:
1350 // We have a GCC style pragma message, and we just read the string.
1353 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1357 std::string MessageString;
1358 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1359 /*MacroExpansion=*/true))
1362 if (ExpectClosingParen) {
1363 if (Tok.isNot(tok::r_paren)) {
1364 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1367 PP.Lex(Tok); // eat the r_paren.
1370 if (Tok.isNot(tok::eod)) {
1371 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1375 // Output the message.
1376 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1377 ? diag::err_pragma_message
1378 : diag::warn_pragma_message) << MessageString;
1380 // If the pragma is lexically sound, notify any interested PPCallbacks.
1381 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1382 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
1386 static bool LexModuleName(
1387 Preprocessor &PP, Token &Tok,
1388 llvm::SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>>
1391 PP.LexUnexpandedToken(Tok);
1392 if (Tok.isAnnotation() || !Tok.getIdentifierInfo()) {
1393 PP.Diag(Tok.getLocation(), diag::err_pp_expected_module_name)
1394 << ModuleName.empty();
1398 ModuleName.emplace_back(Tok.getIdentifierInfo(), Tok.getLocation());
1400 PP.LexUnexpandedToken(Tok);
1401 if (Tok.isNot(tok::period))
1406 /// Handle the clang \#pragma module import extension. The syntax is:
1408 /// #pragma clang module import some.module.name
1410 struct PragmaModuleImportHandler : public PragmaHandler {
1411 PragmaModuleImportHandler() : PragmaHandler("import") {}
1413 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1414 Token &Tok) override {
1415 SourceLocation ImportLoc = Tok.getLocation();
1417 // Read the module name.
1418 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1420 if (LexModuleName(PP, Tok, ModuleName))
1423 if (Tok.isNot(tok::eod))
1424 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1426 // If we have a non-empty module path, load the named module.
1428 PP.getModuleLoader().loadModule(ImportLoc, ModuleName, Module::Hidden,
1429 /*IsIncludeDirective=*/false);
1433 PP.makeModuleVisible(Imported, ImportLoc);
1434 PP.EnterAnnotationToken(SourceRange(ImportLoc, ModuleName.back().second),
1435 tok::annot_module_include, Imported);
1436 if (auto *CB = PP.getPPCallbacks())
1437 CB->moduleImport(ImportLoc, ModuleName, Imported);
1441 /// Handle the clang \#pragma module begin extension. The syntax is:
1443 /// #pragma clang module begin some.module.name
1445 /// #pragma clang module end
1447 struct PragmaModuleBeginHandler : public PragmaHandler {
1448 PragmaModuleBeginHandler() : PragmaHandler("begin") {}
1450 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1451 Token &Tok) override {
1452 SourceLocation BeginLoc = Tok.getLocation();
1454 // Read the module name.
1455 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1457 if (LexModuleName(PP, Tok, ModuleName))
1460 if (Tok.isNot(tok::eod))
1461 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1463 // We can only enter submodules of the current module.
1464 StringRef Current = PP.getLangOpts().CurrentModule;
1465 if (ModuleName.front().first->getName() != Current) {
1466 PP.Diag(ModuleName.front().second, diag::err_pp_module_begin_wrong_module)
1467 << ModuleName.front().first << (ModuleName.size() > 1)
1468 << Current.empty() << Current;
1472 // Find the module we're entering. We require that a module map for it
1473 // be loaded or implicitly loadable.
1474 // FIXME: We could create the submodule here. We'd need to know whether
1475 // it's supposed to be explicit, but not much else.
1476 Module *M = PP.getHeaderSearchInfo().getModuleMap().findModule(Current);
1478 PP.Diag(ModuleName.front().second,
1479 diag::err_pp_module_begin_no_module_map) << Current;
1482 for (unsigned I = 1; I != ModuleName.size(); ++I) {
1483 auto *NewM = M->findSubmodule(ModuleName[I].first->getName());
1485 PP.Diag(ModuleName[I].second, diag::err_pp_module_begin_no_submodule)
1486 << M->getFullModuleName() << ModuleName[I].first;
1492 // If the module isn't available, it doesn't make sense to enter it.
1493 if (Preprocessor::checkModuleIsAvailable(
1494 PP.getLangOpts(), PP.getTargetInfo(), PP.getDiagnostics(), M)) {
1495 PP.Diag(BeginLoc, diag::note_pp_module_begin_here)
1496 << M->getTopLevelModuleName();
1500 // Enter the scope of the submodule.
1501 PP.EnterSubmodule(M, BeginLoc, /*ForPragma*/true);
1502 PP.EnterAnnotationToken(SourceRange(BeginLoc, ModuleName.back().second),
1503 tok::annot_module_begin, M);
1507 /// Handle the clang \#pragma module end extension.
1508 struct PragmaModuleEndHandler : public PragmaHandler {
1509 PragmaModuleEndHandler() : PragmaHandler("end") {}
1511 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1512 Token &Tok) override {
1513 SourceLocation Loc = Tok.getLocation();
1515 PP.LexUnexpandedToken(Tok);
1516 if (Tok.isNot(tok::eod))
1517 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1519 Module *M = PP.LeaveSubmodule(/*ForPragma*/true);
1521 PP.EnterAnnotationToken(SourceRange(Loc), tok::annot_module_end, M);
1523 PP.Diag(Loc, diag::err_pp_module_end_without_module_begin);
1527 /// Handle the clang \#pragma module build extension.
1528 struct PragmaModuleBuildHandler : public PragmaHandler {
1529 PragmaModuleBuildHandler() : PragmaHandler("build") {}
1531 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1532 Token &Tok) override {
1533 PP.HandlePragmaModuleBuild(Tok);
1537 /// Handle the clang \#pragma module load extension.
1538 struct PragmaModuleLoadHandler : public PragmaHandler {
1539 PragmaModuleLoadHandler() : PragmaHandler("load") {}
1541 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1542 Token &Tok) override {
1543 SourceLocation Loc = Tok.getLocation();
1545 // Read the module name.
1546 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1548 if (LexModuleName(PP, Tok, ModuleName))
1551 if (Tok.isNot(tok::eod))
1552 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1554 // Load the module, don't make it visible.
1555 PP.getModuleLoader().loadModule(Loc, ModuleName, Module::Hidden,
1556 /*IsIncludeDirective=*/false);
1560 /// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
1561 /// macro on the top of the stack.
1562 struct PragmaPushMacroHandler : public PragmaHandler {
1563 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
1565 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1566 Token &PushMacroTok) override {
1567 PP.HandlePragmaPushMacro(PushMacroTok);
1571 /// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
1572 /// macro to the value on the top of the stack.
1573 struct PragmaPopMacroHandler : public PragmaHandler {
1574 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
1576 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1577 Token &PopMacroTok) override {
1578 PP.HandlePragmaPopMacro(PopMacroTok);
1582 // Pragma STDC implementations.
1584 /// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
1585 struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
1586 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
1588 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1589 Token &Tok) override {
1590 tok::OnOffSwitch OOS;
1591 if (PP.LexOnOffSwitch(OOS))
1593 if (OOS == tok::OOS_ON)
1594 PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
1598 /// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
1599 struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
1600 PragmaSTDC_CX_LIMITED_RANGEHandler()
1601 : PragmaHandler("CX_LIMITED_RANGE") {}
1603 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1604 Token &Tok) override {
1605 tok::OnOffSwitch OOS;
1606 PP.LexOnOffSwitch(OOS);
1610 /// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
1611 struct PragmaSTDC_UnknownHandler : public PragmaHandler {
1612 PragmaSTDC_UnknownHandler() {}
1614 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1615 Token &UnknownTok) override {
1616 // C99 6.10.6p2, unknown forms are not allowed.
1617 PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
1621 /// PragmaARCCFCodeAuditedHandler -
1622 /// \#pragma clang arc_cf_code_audited begin/end
1623 struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1624 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
1626 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1627 Token &NameTok) override {
1628 SourceLocation Loc = NameTok.getLocation();
1633 // Lex the 'begin' or 'end'.
1634 PP.LexUnexpandedToken(Tok);
1635 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1636 if (BeginEnd && BeginEnd->isStr("begin")) {
1638 } else if (BeginEnd && BeginEnd->isStr("end")) {
1641 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1645 // Verify that this is followed by EOD.
1646 PP.LexUnexpandedToken(Tok);
1647 if (Tok.isNot(tok::eod))
1648 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1650 // The start location of the active audit.
1651 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1653 // The start location we want after processing this.
1654 SourceLocation NewLoc;
1657 // Complain about attempts to re-enter an audit.
1658 if (BeginLoc.isValid()) {
1659 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1660 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1664 // Complain about attempts to leave an audit that doesn't exist.
1665 if (!BeginLoc.isValid()) {
1666 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1669 NewLoc = SourceLocation();
1672 PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1676 /// PragmaAssumeNonNullHandler -
1677 /// \#pragma clang assume_nonnull begin/end
1678 struct PragmaAssumeNonNullHandler : public PragmaHandler {
1679 PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
1681 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1682 Token &NameTok) override {
1683 SourceLocation Loc = NameTok.getLocation();
1688 // Lex the 'begin' or 'end'.
1689 PP.LexUnexpandedToken(Tok);
1690 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1691 if (BeginEnd && BeginEnd->isStr("begin")) {
1693 } else if (BeginEnd && BeginEnd->isStr("end")) {
1696 PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
1700 // Verify that this is followed by EOD.
1701 PP.LexUnexpandedToken(Tok);
1702 if (Tok.isNot(tok::eod))
1703 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1705 // The start location of the active audit.
1706 SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
1708 // The start location we want after processing this.
1709 SourceLocation NewLoc;
1712 // Complain about attempts to re-enter an audit.
1713 if (BeginLoc.isValid()) {
1714 PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
1715 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1719 // Complain about attempts to leave an audit that doesn't exist.
1720 if (!BeginLoc.isValid()) {
1721 PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
1724 NewLoc = SourceLocation();
1727 PP.setPragmaAssumeNonNullLoc(NewLoc);
1731 /// \brief Handle "\#pragma region [...]"
1735 /// #pragma region [optional name]
1736 /// #pragma endregion [optional comment]
1740 /// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1741 /// pragma, just skipped by compiler.
1742 struct PragmaRegionHandler : public PragmaHandler {
1743 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) { }
1745 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1746 Token &NameTok) override {
1747 // #pragma region: endregion matches can be verified
1748 // __pragma(region): no sense, but ignored by msvc
1749 // _Pragma is not valid for MSVC, but there isn't any point
1750 // to handle a _Pragma differently.
1754 } // end anonymous namespace
1756 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
1757 /// \#pragma GCC poison/system_header/dependency and \#pragma once.
1758 void Preprocessor::RegisterBuiltinPragmas() {
1759 AddPragmaHandler(new PragmaOnceHandler());
1760 AddPragmaHandler(new PragmaMarkHandler());
1761 AddPragmaHandler(new PragmaPushMacroHandler());
1762 AddPragmaHandler(new PragmaPopMacroHandler());
1763 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
1766 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1767 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1768 AddPragmaHandler("GCC", new PragmaDependencyHandler());
1769 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
1770 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1772 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1774 // #pragma clang ...
1775 AddPragmaHandler("clang", new PragmaPoisonHandler());
1776 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
1777 AddPragmaHandler("clang", new PragmaDebugHandler());
1778 AddPragmaHandler("clang", new PragmaDependencyHandler());
1779 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
1780 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
1781 AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
1783 // #pragma clang module ...
1784 auto *ModuleHandler = new PragmaNamespace("module");
1785 AddPragmaHandler("clang", ModuleHandler);
1786 ModuleHandler->AddPragma(new PragmaModuleImportHandler());
1787 ModuleHandler->AddPragma(new PragmaModuleBeginHandler());
1788 ModuleHandler->AddPragma(new PragmaModuleEndHandler());
1789 ModuleHandler->AddPragma(new PragmaModuleBuildHandler());
1790 ModuleHandler->AddPragma(new PragmaModuleLoadHandler());
1792 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1793 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
1794 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
1797 if (LangOpts.MicrosoftExt) {
1798 AddPragmaHandler(new PragmaWarningHandler());
1799 AddPragmaHandler(new PragmaIncludeAliasHandler());
1800 AddPragmaHandler(new PragmaRegionHandler("region"));
1801 AddPragmaHandler(new PragmaRegionHandler("endregion"));
1804 // Pragmas added by plugins
1805 for (PragmaHandlerRegistry::iterator it = PragmaHandlerRegistry::begin(),
1806 ie = PragmaHandlerRegistry::end();
1808 AddPragmaHandler(it->instantiate().release());
1812 /// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
1813 /// warn about those pragmas being unknown.
1814 void Preprocessor::IgnorePragmas() {
1815 AddPragmaHandler(new EmptyPragmaHandler());
1816 // Also ignore all pragmas in all namespaces created
1817 // in Preprocessor::RegisterBuiltinPragmas().
1818 AddPragmaHandler("GCC", new EmptyPragmaHandler());
1819 AddPragmaHandler("clang", new EmptyPragmaHandler());
1820 if (PragmaHandler *NS = PragmaHandlers->FindHandler("STDC")) {
1821 // Preprocessor::RegisterBuiltinPragmas() already registers
1822 // PragmaSTDC_UnknownHandler as the empty handler, so remove it first,
1823 // otherwise there will be an assert about a duplicate handler.
1824 PragmaNamespace *STDCNamespace = NS->getIfNamespace();
1825 assert(STDCNamespace &&
1826 "Invalid namespace, registered as a regular pragma handler!");
1827 if (PragmaHandler *Existing = STDCNamespace->FindHandler("", false)) {
1828 RemovePragmaHandler("STDC", Existing);
1832 AddPragmaHandler("STDC", new EmptyPragmaHandler());