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/Lex/HeaderSearch.h"
17 #include "clang/Lex/LiteralSupport.h"
18 #include "clang/Lex/Preprocessor.h"
19 #include "clang/Lex/MacroInfo.h"
20 #include "clang/Lex/LexDiagnostic.h"
21 #include "clang/Basic/FileManager.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "llvm/Support/CrashRecoveryContext.h"
24 #include "llvm/Support/ErrorHandling.h"
26 using namespace clang;
28 // Out-of-line destructor to provide a home for the class.
29 PragmaHandler::~PragmaHandler() {
32 //===----------------------------------------------------------------------===//
33 // EmptyPragmaHandler Implementation.
34 //===----------------------------------------------------------------------===//
36 EmptyPragmaHandler::EmptyPragmaHandler() {}
38 void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
39 PragmaIntroducerKind Introducer,
42 //===----------------------------------------------------------------------===//
43 // PragmaNamespace Implementation.
44 //===----------------------------------------------------------------------===//
47 PragmaNamespace::~PragmaNamespace() {
48 for (llvm::StringMap<PragmaHandler*>::iterator
49 I = Handlers.begin(), E = Handlers.end(); I != E; ++I)
53 /// FindHandler - Check to see if there is already a handler for the
54 /// specified name. If not, return the handler for the null identifier if it
55 /// exists, otherwise return null. If IgnoreNull is true (the default) then
56 /// the null handler isn't returned on failure to match.
57 PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
58 bool IgnoreNull) const {
59 if (PragmaHandler *Handler = Handlers.lookup(Name))
61 return IgnoreNull ? 0 : Handlers.lookup(StringRef());
64 void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
65 assert(!Handlers.lookup(Handler->getName()) &&
66 "A handler with this name is already registered in this namespace");
67 llvm::StringMapEntry<PragmaHandler *> &Entry =
68 Handlers.GetOrCreateValue(Handler->getName());
69 Entry.setValue(Handler);
72 void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
73 assert(Handlers.lookup(Handler->getName()) &&
74 "Handler not registered in this namespace");
75 Handlers.erase(Handler->getName());
78 void PragmaNamespace::HandlePragma(Preprocessor &PP,
79 PragmaIntroducerKind Introducer,
81 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
82 // expand it, the user can have a STDC #define, that should not affect this.
83 PP.LexUnexpandedToken(Tok);
85 // Get the handler for this token. If there is no handler, ignore the pragma.
86 PragmaHandler *Handler
87 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
89 /*IgnoreNull=*/false);
91 PP.Diag(Tok, diag::warn_pragma_ignored);
95 // Otherwise, pass it down.
96 Handler->HandlePragma(PP, Introducer, Tok);
99 //===----------------------------------------------------------------------===//
100 // Preprocessor Pragma Directive Handling.
101 //===----------------------------------------------------------------------===//
103 /// HandlePragmaDirective - The "#pragma" directive has been parsed. Lex the
104 /// rest of the pragma, passing it to the registered pragma handlers.
105 void Preprocessor::HandlePragmaDirective(unsigned Introducer) {
108 // Invoke the first level of pragma handlers which reads the namespace id.
110 PragmaHandlers->HandlePragma(*this, PragmaIntroducerKind(Introducer), Tok);
112 // If the pragma handler didn't read the rest of the line, consume it now.
113 if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
114 || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
115 DiscardUntilEndOfDirective();
119 /// \brief Helper class for \see Preprocessor::Handle_Pragma.
120 class LexingFor_PragmaRAII {
122 bool InMacroArgPreExpansion;
128 LexingFor_PragmaRAII(Preprocessor &PP, bool InMacroArgPreExpansion,
130 : PP(PP), InMacroArgPreExpansion(InMacroArgPreExpansion),
131 Failed(false), OutTok(Tok) {
132 if (InMacroArgPreExpansion) {
134 PP.EnableBacktrackAtThisPos();
138 ~LexingFor_PragmaRAII() {
139 if (InMacroArgPreExpansion) {
141 PP.CommitBacktrackedTokens();
155 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
156 /// return the first token after the directive. The _Pragma token has just
157 /// been read into 'Tok'.
158 void Preprocessor::Handle_Pragma(Token &Tok) {
160 // This works differently if we are pre-expanding a macro argument.
161 // In that case we don't actually "activate" the pragma now, we only lex it
162 // until we are sure it is lexically correct and then we backtrack so that
163 // we activate the pragma whenever we encounter the tokens again in the token
164 // stream. This ensures that we will activate it in the correct location
165 // or that we will ignore it if it never enters the token stream, e.g:
168 // #define INACTIVE(x) EMPTY(x)
169 // INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\""))
171 LexingFor_PragmaRAII _PragmaLexing(*this, InMacroArgPreExpansion, Tok);
173 // Remember the pragma token location.
174 SourceLocation PragmaLoc = Tok.getLocation();
178 if (Tok.isNot(tok::l_paren)) {
179 Diag(PragmaLoc, diag::err__Pragma_malformed);
180 return _PragmaLexing.failed();
185 if (Tok.isNot(tok::string_literal) && Tok.isNot(tok::wide_string_literal)) {
186 Diag(PragmaLoc, diag::err__Pragma_malformed);
187 // Skip this token, and the ')', if present.
188 if (Tok.isNot(tok::r_paren))
190 if (Tok.is(tok::r_paren))
192 return _PragmaLexing.failed();
195 if (Tok.hasUDSuffix()) {
196 Diag(Tok, diag::err_invalid_string_udl);
197 // Skip this token, and the ')', if present.
199 if (Tok.is(tok::r_paren))
201 return _PragmaLexing.failed();
204 // Remember the string.
209 if (Tok.isNot(tok::r_paren)) {
210 Diag(PragmaLoc, diag::err__Pragma_malformed);
211 return _PragmaLexing.failed();
214 if (InMacroArgPreExpansion)
217 SourceLocation RParenLoc = Tok.getLocation();
218 std::string StrVal = getSpelling(StrTok);
220 // The _Pragma is lexically sound. Destringize according to C99 6.10.9.1:
221 // "The string literal is destringized by deleting the L prefix, if present,
222 // deleting the leading and trailing double-quotes, replacing each escape
223 // sequence \" by a double-quote, and replacing each escape sequence \\ by a
224 // single backslash."
225 if (StrVal[0] == 'L') // Remove L prefix.
226 StrVal.erase(StrVal.begin());
227 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
228 "Invalid string token!");
230 // Remove the front quote, replacing it with a space, so that the pragma
231 // contents appear to have a space before them.
234 // Replace the terminating quote with a \n.
235 StrVal[StrVal.size()-1] = '\n';
237 // Remove escaped quotes and escapes.
238 for (unsigned i = 0, e = StrVal.size(); i != e-1; ++i) {
239 if (StrVal[i] == '\\' &&
240 (StrVal[i+1] == '\\' || StrVal[i+1] == '"')) {
241 // \\ -> '\' and \" -> '"'.
242 StrVal.erase(StrVal.begin()+i);
247 // Plop the string (including the newline and trailing null) into a buffer
248 // where we can lex it.
251 CreateString(&StrVal[0], StrVal.size(), TmpTok);
252 SourceLocation TokLoc = TmpTok.getLocation();
254 // Make and enter a lexer object so that we lex and expand the tokens just
256 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
257 StrVal.size(), *this);
259 EnterSourceFileWithLexer(TL, 0);
261 // With everything set up, lex this as a #pragma directive.
262 HandlePragmaDirective(PIK__Pragma);
264 // Finally, return whatever came after the pragma directive.
268 /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
269 /// is not enclosed within a string literal.
270 void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
271 // Remember the pragma token location.
272 SourceLocation PragmaLoc = Tok.getLocation();
276 if (Tok.isNot(tok::l_paren)) {
277 Diag(PragmaLoc, diag::err__Pragma_malformed);
281 // Get the tokens enclosed within the __pragma(), as well as the final ')'.
282 SmallVector<Token, 32> PragmaToks;
285 while (Tok.isNot(tok::eof)) {
286 PragmaToks.push_back(Tok);
287 if (Tok.is(tok::l_paren))
289 else if (Tok.is(tok::r_paren) && NumParens-- == 0)
294 if (Tok.is(tok::eof)) {
295 Diag(PragmaLoc, diag::err_unterminated___pragma);
299 PragmaToks.front().setFlag(Token::LeadingSpace);
301 // Replace the ')' with an EOD to mark the end of the pragma.
302 PragmaToks.back().setKind(tok::eod);
304 Token *TokArray = new Token[PragmaToks.size()];
305 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
307 // Push the tokens onto the stack.
308 EnterTokenStream(TokArray, PragmaToks.size(), true, true);
310 // With everything set up, lex this as a #pragma directive.
311 HandlePragmaDirective(PIK___pragma);
313 // Finally, return whatever came after the pragma directive.
317 /// HandlePragmaOnce - Handle #pragma once. OnceTok is the 'once'.
319 void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
320 if (isInPrimaryFile()) {
321 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
325 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
326 // Mark the file as a once-only file now.
327 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
330 void Preprocessor::HandlePragmaMark() {
331 assert(CurPPLexer && "No current lexer?");
333 CurLexer->ReadToEndOfLine();
335 CurPTHLexer->DiscardToEndOfLine();
339 /// HandlePragmaPoison - Handle #pragma GCC poison. PoisonTok is the 'poison'.
341 void Preprocessor::HandlePragmaPoison(Token &PoisonTok) {
345 // Read the next token to poison. While doing this, pretend that we are
346 // skipping while reading the identifier to poison.
347 // This avoids errors on code like:
348 // #pragma GCC poison X
349 // #pragma GCC poison X
350 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
351 LexUnexpandedToken(Tok);
352 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
354 // If we reached the end of line, we're done.
355 if (Tok.is(tok::eod)) return;
357 // Can only poison identifiers.
358 if (Tok.isNot(tok::raw_identifier)) {
359 Diag(Tok, diag::err_pp_invalid_poison);
363 // Look up the identifier info for the token. We disabled identifier lookup
364 // by saying we're skipping contents, so we need to do this manually.
365 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
368 if (II->isPoisoned()) continue;
370 // If this is a macro identifier, emit a warning.
371 if (II->hasMacroDefinition())
372 Diag(Tok, diag::pp_poisoning_existing_macro);
374 // Finally, poison it!
377 II->setChangedSinceDeserialization();
381 /// HandlePragmaSystemHeader - Implement #pragma GCC system_header. We know
382 /// that the whole directive has been parsed.
383 void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
384 if (isInPrimaryFile()) {
385 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
389 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
390 PreprocessorLexer *TheLexer = getCurrentFileLexer();
392 // Mark the file as a system header.
393 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
396 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
397 if (PLoc.isInvalid())
400 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
402 // Notify the client, if desired, that we are in a new source file.
404 Callbacks->FileChanged(SysHeaderTok.getLocation(),
405 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
407 // Emit a line marker. This will change any source locations from this point
408 // forward to realize they are in a system header.
409 // Create a line note with this information.
410 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine(), FilenameID,
411 false, false, true, false);
414 /// HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah.
416 void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
418 CurPPLexer->LexIncludeFilename(FilenameTok);
420 // If the token kind is EOD, the error has already been diagnosed.
421 if (FilenameTok.is(tok::eod))
424 // Reserve a buffer to get the spelling.
425 SmallString<128> FilenameBuffer;
426 bool Invalid = false;
427 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
432 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
433 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
435 if (Filename.empty())
438 // Search include directories for this file.
439 const DirectoryLookup *CurDir;
440 const FileEntry *File = LookupFile(Filename, isAngled, 0, CurDir, NULL, NULL,
443 if (!SuppressIncludeNotFoundError)
444 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
448 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
450 // If this file is older than the file it depends on, emit a diagnostic.
451 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
452 // Lex tokens at the end of the message and include them in the message.
455 while (DependencyTok.isNot(tok::eod)) {
456 Message += getSpelling(DependencyTok) + " ";
460 // Remove the trailing ' ' if present.
461 if (!Message.empty())
462 Message.erase(Message.end()-1);
463 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
467 /// HandlePragmaComment - Handle the microsoft #pragma comment extension. The
469 /// #pragma comment(linker, "foo")
470 /// 'linker' is one of five identifiers: compiler, exestr, lib, linker, user.
471 /// "foo" is a string, which is fully macro expanded, and permits string
472 /// concatenation, embedded escape characters etc. See MSDN for more details.
473 void Preprocessor::HandlePragmaComment(Token &Tok) {
474 SourceLocation CommentLoc = Tok.getLocation();
476 if (Tok.isNot(tok::l_paren)) {
477 Diag(CommentLoc, diag::err_pragma_comment_malformed);
481 // Read the identifier.
483 if (Tok.isNot(tok::identifier)) {
484 Diag(CommentLoc, diag::err_pragma_comment_malformed);
488 // Verify that this is one of the 5 whitelisted options.
489 // FIXME: warn that 'exestr' is deprecated.
490 const IdentifierInfo *II = Tok.getIdentifierInfo();
491 if (!II->isStr("compiler") && !II->isStr("exestr") && !II->isStr("lib") &&
492 !II->isStr("linker") && !II->isStr("user")) {
493 Diag(Tok.getLocation(), diag::err_pragma_comment_unknown_kind);
497 // Read the optional string if present.
499 std::string ArgumentString;
500 if (Tok.is(tok::comma)) {
501 Lex(Tok); // eat the comma.
503 // We need at least one string.
504 if (Tok.isNot(tok::string_literal)) {
505 Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
509 // String concatenation allows multiple strings, which can even come from
511 // "foo " "bar" "Baz"
512 SmallVector<Token, 4> StrToks;
513 while (Tok.is(tok::string_literal)) {
514 if (Tok.hasUDSuffix())
515 Diag(Tok, diag::err_invalid_string_udl);
516 StrToks.push_back(Tok);
520 // Concatenate and parse the strings.
521 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
522 assert(Literal.isAscii() && "Didn't allow wide strings in");
523 if (Literal.hadError)
525 if (Literal.Pascal) {
526 Diag(StrToks[0].getLocation(), diag::err_pragma_comment_malformed);
530 ArgumentString = Literal.GetString();
533 // FIXME: If the kind is "compiler" warn if the string is present (it is
535 // FIXME: 'lib' requires a comment string.
536 // FIXME: 'linker' requires a comment string, and has a specific list of
537 // things that are allowable.
539 if (Tok.isNot(tok::r_paren)) {
540 Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
543 Lex(Tok); // eat the r_paren.
545 if (Tok.isNot(tok::eod)) {
546 Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
550 // If the pragma is lexically sound, notify any interested PPCallbacks.
552 Callbacks->PragmaComment(CommentLoc, II, ArgumentString);
555 /// HandlePragmaMessage - Handle the microsoft and gcc #pragma message
556 /// extension. The syntax is:
557 /// #pragma message(string)
559 /// #pragma message string
560 /// string is a string, which is fully macro expanded, and permits string
561 /// concatenation, embedded escape characters, etc... See MSDN for more details.
562 void Preprocessor::HandlePragmaMessage(Token &Tok) {
563 SourceLocation MessageLoc = Tok.getLocation();
565 bool ExpectClosingParen = false;
566 switch (Tok.getKind()) {
568 // We have a MSVC style pragma message.
569 ExpectClosingParen = true;
573 case tok::string_literal:
574 // We have a GCC style pragma message, and we just read the string.
577 Diag(MessageLoc, diag::err_pragma_message_malformed);
581 // We need at least one string.
582 if (Tok.isNot(tok::string_literal)) {
583 Diag(Tok.getLocation(), diag::err_pragma_message_malformed);
587 // String concatenation allows multiple strings, which can even come from
589 // "foo " "bar" "Baz"
590 SmallVector<Token, 4> StrToks;
591 while (Tok.is(tok::string_literal)) {
592 if (Tok.hasUDSuffix())
593 Diag(Tok, diag::err_invalid_string_udl);
594 StrToks.push_back(Tok);
598 // Concatenate and parse the strings.
599 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
600 assert(Literal.isAscii() && "Didn't allow wide strings in");
601 if (Literal.hadError)
603 if (Literal.Pascal) {
604 Diag(StrToks[0].getLocation(), diag::err_pragma_message_malformed);
608 StringRef MessageString(Literal.GetString());
610 if (ExpectClosingParen) {
611 if (Tok.isNot(tok::r_paren)) {
612 Diag(Tok.getLocation(), diag::err_pragma_message_malformed);
615 Lex(Tok); // eat the r_paren.
618 if (Tok.isNot(tok::eod)) {
619 Diag(Tok.getLocation(), diag::err_pragma_message_malformed);
623 // Output the message.
624 Diag(MessageLoc, diag::warn_pragma_message) << MessageString;
626 // If the pragma is lexically sound, notify any interested PPCallbacks.
628 Callbacks->PragmaMessage(MessageLoc, MessageString);
631 /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
632 /// Return the IdentifierInfo* associated with the macro to push or pop.
633 IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
634 // Remember the pragma token location.
635 Token PragmaTok = Tok;
639 if (Tok.isNot(tok::l_paren)) {
640 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
641 << getSpelling(PragmaTok);
645 // Read the macro name string.
647 if (Tok.isNot(tok::string_literal)) {
648 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
649 << getSpelling(PragmaTok);
653 if (Tok.hasUDSuffix()) {
654 Diag(Tok, diag::err_invalid_string_udl);
658 // Remember the macro string.
659 std::string StrVal = getSpelling(Tok);
663 if (Tok.isNot(tok::r_paren)) {
664 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
665 << getSpelling(PragmaTok);
669 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
670 "Invalid string token!");
672 // Create a Token from the string.
674 MacroTok.startToken();
675 MacroTok.setKind(tok::raw_identifier);
676 CreateString(&StrVal[1], StrVal.size() - 2, MacroTok);
678 // Get the IdentifierInfo of MacroToPushTok.
679 return LookUpIdentifierInfo(MacroTok);
682 /// HandlePragmaPushMacro - Handle #pragma push_macro.
684 /// #pragma push_macro("macro")
685 void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
686 // Parse the pragma directive and get the macro IdentifierInfo*.
687 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
688 if (!IdentInfo) return;
690 // Get the MacroInfo associated with IdentInfo.
691 MacroInfo *MI = getMacroInfo(IdentInfo);
693 MacroInfo *MacroCopyToPush = 0;
695 // Make a clone of MI.
696 MacroCopyToPush = CloneMacroInfo(*MI);
698 // Allow the original MacroInfo to be redefined later.
699 MI->setIsAllowRedefinitionsWithoutWarning(true);
702 // Push the cloned MacroInfo so we can retrieve it later.
703 PragmaPushMacroInfo[IdentInfo].push_back(MacroCopyToPush);
706 /// HandlePragmaPopMacro - Handle #pragma pop_macro.
708 /// #pragma pop_macro("macro")
709 void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
710 SourceLocation MessageLoc = PopMacroTok.getLocation();
712 // Parse the pragma directive and get the macro IdentifierInfo*.
713 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
714 if (!IdentInfo) return;
716 // Find the vector<MacroInfo*> associated with the macro.
717 llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
718 PragmaPushMacroInfo.find(IdentInfo);
719 if (iter != PragmaPushMacroInfo.end()) {
720 // Release the MacroInfo currently associated with IdentInfo.
721 MacroInfo *CurrentMI = getMacroInfo(IdentInfo);
723 if (CurrentMI->isWarnIfUnused())
724 WarnUnusedMacroLocs.erase(CurrentMI->getDefinitionLoc());
725 ReleaseMacroInfo(CurrentMI);
728 // Get the MacroInfo we want to reinstall.
729 MacroInfo *MacroToReInstall = iter->second.back();
731 // Reinstall the previously pushed macro.
732 setMacroInfo(IdentInfo, MacroToReInstall);
734 // Pop PragmaPushMacroInfo stack.
735 iter->second.pop_back();
736 if (iter->second.size() == 0)
737 PragmaPushMacroInfo.erase(iter);
739 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
740 << IdentInfo->getName();
744 void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
745 // We will either get a quoted filename or a bracketed filename, and we
746 // have to track which we got. The first filename is the source name,
747 // and the second name is the mapped filename. If the first is quoted,
748 // the second must be as well (cannot mix and match quotes and brackets).
750 // Get the open paren
752 if (Tok.isNot(tok::l_paren)) {
753 Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
757 // We expect either a quoted string literal, or a bracketed name
758 Token SourceFilenameTok;
759 CurPPLexer->LexIncludeFilename(SourceFilenameTok);
760 if (SourceFilenameTok.is(tok::eod)) {
761 // The diagnostic has already been handled
765 StringRef SourceFileName;
766 SmallString<128> FileNameBuffer;
767 if (SourceFilenameTok.is(tok::string_literal) ||
768 SourceFilenameTok.is(tok::angle_string_literal)) {
769 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
770 } else if (SourceFilenameTok.is(tok::less)) {
771 // This could be a path instead of just a name
772 FileNameBuffer.push_back('<');
774 if (ConcatenateIncludeName(FileNameBuffer, End))
775 return; // Diagnostic already emitted
776 SourceFileName = FileNameBuffer.str();
778 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
781 FileNameBuffer.clear();
783 // Now we expect a comma, followed by another include name
785 if (Tok.isNot(tok::comma)) {
786 Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
790 Token ReplaceFilenameTok;
791 CurPPLexer->LexIncludeFilename(ReplaceFilenameTok);
792 if (ReplaceFilenameTok.is(tok::eod)) {
793 // The diagnostic has already been handled
797 StringRef ReplaceFileName;
798 if (ReplaceFilenameTok.is(tok::string_literal) ||
799 ReplaceFilenameTok.is(tok::angle_string_literal)) {
800 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
801 } else if (ReplaceFilenameTok.is(tok::less)) {
802 // This could be a path instead of just a name
803 FileNameBuffer.push_back('<');
805 if (ConcatenateIncludeName(FileNameBuffer, End))
806 return; // Diagnostic already emitted
807 ReplaceFileName = FileNameBuffer.str();
809 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
813 // Finally, we expect the closing paren
815 if (Tok.isNot(tok::r_paren)) {
816 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
820 // Now that we have the source and target filenames, we need to make sure
821 // they're both of the same type (angled vs non-angled)
822 StringRef OriginalSource = SourceFileName;
824 bool SourceIsAngled =
825 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
827 bool ReplaceIsAngled =
828 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
830 if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
831 (SourceIsAngled != ReplaceIsAngled)) {
834 DiagID = diag::warn_pragma_include_alias_mismatch_angle;
836 DiagID = diag::warn_pragma_include_alias_mismatch_quote;
838 Diag(SourceFilenameTok.getLocation(), DiagID)
845 // Now we can let the include handler know about this mapping
846 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
849 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
850 /// If 'Namespace' is non-null, then it is a token required to exist on the
851 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
852 void Preprocessor::AddPragmaHandler(StringRef Namespace,
853 PragmaHandler *Handler) {
854 PragmaNamespace *InsertNS = PragmaHandlers;
856 // If this is specified to be in a namespace, step down into it.
857 if (!Namespace.empty()) {
858 // If there is already a pragma handler with the name of this namespace,
859 // we either have an error (directive with the same name as a namespace) or
860 // we already have the namespace to insert into.
861 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
862 InsertNS = Existing->getIfNamespace();
863 assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
864 " handler with the same name!");
866 // Otherwise, this namespace doesn't exist yet, create and insert the
868 InsertNS = new PragmaNamespace(Namespace);
869 PragmaHandlers->AddPragma(InsertNS);
873 // Check to make sure we don't already have a pragma for this identifier.
874 assert(!InsertNS->FindHandler(Handler->getName()) &&
875 "Pragma handler already exists for this identifier!");
876 InsertNS->AddPragma(Handler);
879 /// RemovePragmaHandler - Remove the specific pragma handler from the
880 /// preprocessor. If \arg Namespace is non-null, then it should be the
881 /// namespace that \arg Handler was added to. It is an error to remove
882 /// a handler that has not been registered.
883 void Preprocessor::RemovePragmaHandler(StringRef Namespace,
884 PragmaHandler *Handler) {
885 PragmaNamespace *NS = PragmaHandlers;
887 // If this is specified to be in a namespace, step down into it.
888 if (!Namespace.empty()) {
889 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
890 assert(Existing && "Namespace containing handler does not exist!");
892 NS = Existing->getIfNamespace();
893 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
896 NS->RemovePragmaHandler(Handler);
898 // If this is a non-default namespace and it is now empty, remove
900 if (NS != PragmaHandlers && NS->IsEmpty()) {
901 PragmaHandlers->RemovePragmaHandler(NS);
906 bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
908 LexUnexpandedToken(Tok);
910 if (Tok.isNot(tok::identifier)) {
911 Diag(Tok, diag::ext_on_off_switch_syntax);
914 IdentifierInfo *II = Tok.getIdentifierInfo();
916 Result = tok::OOS_ON;
917 else if (II->isStr("OFF"))
918 Result = tok::OOS_OFF;
919 else if (II->isStr("DEFAULT"))
920 Result = tok::OOS_DEFAULT;
922 Diag(Tok, diag::ext_on_off_switch_syntax);
926 // Verify that this is followed by EOD.
927 LexUnexpandedToken(Tok);
928 if (Tok.isNot(tok::eod))
929 Diag(Tok, diag::ext_pragma_syntax_eod);
934 /// PragmaOnceHandler - "#pragma once" marks the file as atomically included.
935 struct PragmaOnceHandler : public PragmaHandler {
936 PragmaOnceHandler() : PragmaHandler("once") {}
937 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
939 PP.CheckEndOfDirective("pragma once");
940 PP.HandlePragmaOnce(OnceTok);
944 /// PragmaMarkHandler - "#pragma mark ..." is ignored by the compiler, and the
945 /// rest of the line is not lexed.
946 struct PragmaMarkHandler : public PragmaHandler {
947 PragmaMarkHandler() : PragmaHandler("mark") {}
948 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
950 PP.HandlePragmaMark();
954 /// PragmaPoisonHandler - "#pragma poison x" marks x as not usable.
955 struct PragmaPoisonHandler : public PragmaHandler {
956 PragmaPoisonHandler() : PragmaHandler("poison") {}
957 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
959 PP.HandlePragmaPoison(PoisonTok);
963 /// PragmaSystemHeaderHandler - "#pragma system_header" marks the current file
964 /// as a system header, which silences warnings in it.
965 struct PragmaSystemHeaderHandler : public PragmaHandler {
966 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
967 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
969 PP.HandlePragmaSystemHeader(SHToken);
970 PP.CheckEndOfDirective("pragma");
973 struct PragmaDependencyHandler : public PragmaHandler {
974 PragmaDependencyHandler() : PragmaHandler("dependency") {}
975 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
977 PP.HandlePragmaDependency(DepToken);
981 struct PragmaDebugHandler : public PragmaHandler {
982 PragmaDebugHandler() : PragmaHandler("__debug") {}
983 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
986 PP.LexUnexpandedToken(Tok);
987 if (Tok.isNot(tok::identifier)) {
988 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
991 IdentifierInfo *II = Tok.getIdentifierInfo();
993 if (II->isStr("assert")) {
994 llvm_unreachable("This is an assertion!");
995 } else if (II->isStr("crash")) {
996 *(volatile int*) 0x11 = 0;
997 } else if (II->isStr("llvm_fatal_error")) {
998 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
999 } else if (II->isStr("llvm_unreachable")) {
1000 llvm_unreachable("#pragma clang __debug llvm_unreachable");
1001 } else if (II->isStr("overflow_stack")) {
1002 DebugOverflowStack();
1003 } else if (II->isStr("handle_crash")) {
1004 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
1008 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
1013 // Disable MSVC warning about runtime stack overflow.
1015 #pragma warning(disable : 4717)
1017 void DebugOverflowStack() {
1018 DebugOverflowStack();
1021 #pragma warning(default : 4717)
1026 /// PragmaDiagnosticHandler - e.g. '#pragma GCC diagnostic ignored "-Wformat"'
1027 struct PragmaDiagnosticHandler : public PragmaHandler {
1029 const char *Namespace;
1031 explicit PragmaDiagnosticHandler(const char *NS) :
1032 PragmaHandler("diagnostic"), Namespace(NS) {}
1033 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1035 SourceLocation DiagLoc = DiagToken.getLocation();
1037 PP.LexUnexpandedToken(Tok);
1038 if (Tok.isNot(tok::identifier)) {
1039 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1042 IdentifierInfo *II = Tok.getIdentifierInfo();
1043 PPCallbacks *Callbacks = PP.getPPCallbacks();
1046 if (II->isStr("warning"))
1047 Map = diag::MAP_WARNING;
1048 else if (II->isStr("error"))
1049 Map = diag::MAP_ERROR;
1050 else if (II->isStr("ignored"))
1051 Map = diag::MAP_IGNORE;
1052 else if (II->isStr("fatal"))
1053 Map = diag::MAP_FATAL;
1054 else if (II->isStr("pop")) {
1055 if (!PP.getDiagnostics().popMappings(DiagLoc))
1056 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
1058 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
1060 } else if (II->isStr("push")) {
1061 PP.getDiagnostics().pushMappings(DiagLoc);
1063 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
1066 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1070 PP.LexUnexpandedToken(Tok);
1072 // We need at least one string.
1073 if (Tok.isNot(tok::string_literal)) {
1074 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1078 // String concatenation allows multiple strings, which can even come from
1080 // "foo " "bar" "Baz"
1081 SmallVector<Token, 4> StrToks;
1082 while (Tok.is(tok::string_literal)) {
1083 StrToks.push_back(Tok);
1084 PP.LexUnexpandedToken(Tok);
1087 if (Tok.isNot(tok::eod)) {
1088 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1092 // Concatenate and parse the strings.
1093 StringLiteralParser Literal(&StrToks[0], StrToks.size(), PP);
1094 assert(Literal.isAscii() && "Didn't allow wide strings in");
1095 if (Literal.hadError)
1097 if (Literal.Pascal) {
1098 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1102 StringRef WarningName(Literal.GetString());
1104 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1105 WarningName[1] != 'W') {
1106 PP.Diag(StrToks[0].getLocation(),
1107 diag::warn_pragma_diagnostic_invalid_option);
1111 if (PP.getDiagnostics().setDiagnosticGroupMapping(WarningName.substr(2),
1113 PP.Diag(StrToks[0].getLocation(),
1114 diag::warn_pragma_diagnostic_unknown_warning) << WarningName;
1116 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, Map, WarningName);
1120 /// PragmaCommentHandler - "#pragma comment ...".
1121 struct PragmaCommentHandler : public PragmaHandler {
1122 PragmaCommentHandler() : PragmaHandler("comment") {}
1123 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1124 Token &CommentTok) {
1125 PP.HandlePragmaComment(CommentTok);
1129 /// PragmaIncludeAliasHandler - "#pragma include_alias("...")".
1130 struct PragmaIncludeAliasHandler : public PragmaHandler {
1131 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
1132 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1133 Token &IncludeAliasTok) {
1134 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
1138 /// PragmaMessageHandler - "#pragma message("...")".
1139 struct PragmaMessageHandler : public PragmaHandler {
1140 PragmaMessageHandler() : PragmaHandler("message") {}
1141 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1142 Token &CommentTok) {
1143 PP.HandlePragmaMessage(CommentTok);
1147 /// PragmaPushMacroHandler - "#pragma push_macro" saves the value of the
1148 /// macro on the top of the stack.
1149 struct PragmaPushMacroHandler : public PragmaHandler {
1150 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
1151 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1152 Token &PushMacroTok) {
1153 PP.HandlePragmaPushMacro(PushMacroTok);
1158 /// PragmaPopMacroHandler - "#pragma pop_macro" sets the value of the
1159 /// macro to the value on the top of the stack.
1160 struct PragmaPopMacroHandler : public PragmaHandler {
1161 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
1162 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1163 Token &PopMacroTok) {
1164 PP.HandlePragmaPopMacro(PopMacroTok);
1168 // Pragma STDC implementations.
1170 /// PragmaSTDC_FENV_ACCESSHandler - "#pragma STDC FENV_ACCESS ...".
1171 struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
1172 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
1173 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1175 tok::OnOffSwitch OOS;
1176 if (PP.LexOnOffSwitch(OOS))
1178 if (OOS == tok::OOS_ON)
1179 PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
1183 /// PragmaSTDC_CX_LIMITED_RANGEHandler - "#pragma STDC CX_LIMITED_RANGE ...".
1184 struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
1185 PragmaSTDC_CX_LIMITED_RANGEHandler()
1186 : PragmaHandler("CX_LIMITED_RANGE") {}
1187 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1189 tok::OnOffSwitch OOS;
1190 PP.LexOnOffSwitch(OOS);
1194 /// PragmaSTDC_UnknownHandler - "#pragma STDC ...".
1195 struct PragmaSTDC_UnknownHandler : public PragmaHandler {
1196 PragmaSTDC_UnknownHandler() {}
1197 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1198 Token &UnknownTok) {
1199 // C99 6.10.6p2, unknown forms are not allowed.
1200 PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
1204 /// PragmaARCCFCodeAuditedHandler -
1205 /// #pragma clang arc_cf_code_audited begin/end
1206 struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1207 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
1208 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1210 SourceLocation Loc = NameTok.getLocation();
1215 // Lex the 'begin' or 'end'.
1216 PP.LexUnexpandedToken(Tok);
1217 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1218 if (BeginEnd && BeginEnd->isStr("begin")) {
1220 } else if (BeginEnd && BeginEnd->isStr("end")) {
1223 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1227 // Verify that this is followed by EOD.
1228 PP.LexUnexpandedToken(Tok);
1229 if (Tok.isNot(tok::eod))
1230 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1232 // The start location of the active audit.
1233 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1235 // The start location we want after processing this.
1236 SourceLocation NewLoc;
1239 // Complain about attempts to re-enter an audit.
1240 if (BeginLoc.isValid()) {
1241 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1242 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1246 // Complain about attempts to leave an audit that doesn't exist.
1247 if (!BeginLoc.isValid()) {
1248 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1251 NewLoc = SourceLocation();
1254 PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1258 } // end anonymous namespace
1261 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
1262 /// #pragma GCC poison/system_header/dependency and #pragma once.
1263 void Preprocessor::RegisterBuiltinPragmas() {
1264 AddPragmaHandler(new PragmaOnceHandler());
1265 AddPragmaHandler(new PragmaMarkHandler());
1266 AddPragmaHandler(new PragmaPushMacroHandler());
1267 AddPragmaHandler(new PragmaPopMacroHandler());
1268 AddPragmaHandler(new PragmaMessageHandler());
1271 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1272 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1273 AddPragmaHandler("GCC", new PragmaDependencyHandler());
1274 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
1275 // #pragma clang ...
1276 AddPragmaHandler("clang", new PragmaPoisonHandler());
1277 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
1278 AddPragmaHandler("clang", new PragmaDebugHandler());
1279 AddPragmaHandler("clang", new PragmaDependencyHandler());
1280 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
1281 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
1283 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1284 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
1285 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
1288 if (LangOpts.MicrosoftExt) {
1289 AddPragmaHandler(new PragmaCommentHandler());
1290 AddPragmaHandler(new PragmaIncludeAliasHandler());