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();
118 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
119 /// return the first token after the directive. The _Pragma token has just
120 /// been read into 'Tok'.
121 void Preprocessor::Handle_Pragma(Token &Tok) {
122 // Remember the pragma token location.
123 SourceLocation PragmaLoc = Tok.getLocation();
127 if (Tok.isNot(tok::l_paren)) {
128 Diag(PragmaLoc, diag::err__Pragma_malformed);
134 if (Tok.isNot(tok::string_literal) && Tok.isNot(tok::wide_string_literal)) {
135 Diag(PragmaLoc, diag::err__Pragma_malformed);
139 // Remember the string.
140 std::string StrVal = getSpelling(Tok);
144 if (Tok.isNot(tok::r_paren)) {
145 Diag(PragmaLoc, diag::err__Pragma_malformed);
149 SourceLocation RParenLoc = Tok.getLocation();
151 // The _Pragma is lexically sound. Destringize according to C99 6.10.9.1:
152 // "The string literal is destringized by deleting the L prefix, if present,
153 // deleting the leading and trailing double-quotes, replacing each escape
154 // sequence \" by a double-quote, and replacing each escape sequence \\ by a
155 // single backslash."
156 if (StrVal[0] == 'L') // Remove L prefix.
157 StrVal.erase(StrVal.begin());
158 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
159 "Invalid string token!");
161 // Remove the front quote, replacing it with a space, so that the pragma
162 // contents appear to have a space before them.
165 // Replace the terminating quote with a \n.
166 StrVal[StrVal.size()-1] = '\n';
168 // Remove escaped quotes and escapes.
169 for (unsigned i = 0, e = StrVal.size(); i != e-1; ++i) {
170 if (StrVal[i] == '\\' &&
171 (StrVal[i+1] == '\\' || StrVal[i+1] == '"')) {
172 // \\ -> '\' and \" -> '"'.
173 StrVal.erase(StrVal.begin()+i);
178 // Plop the string (including the newline and trailing null) into a buffer
179 // where we can lex it.
182 CreateString(&StrVal[0], StrVal.size(), TmpTok);
183 SourceLocation TokLoc = TmpTok.getLocation();
185 // Make and enter a lexer object so that we lex and expand the tokens just
187 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
188 StrVal.size(), *this);
190 EnterSourceFileWithLexer(TL, 0);
192 // With everything set up, lex this as a #pragma directive.
193 HandlePragmaDirective(PIK__Pragma);
195 // Finally, return whatever came after the pragma directive.
199 /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
200 /// is not enclosed within a string literal.
201 void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
202 // Remember the pragma token location.
203 SourceLocation PragmaLoc = Tok.getLocation();
207 if (Tok.isNot(tok::l_paren)) {
208 Diag(PragmaLoc, diag::err__Pragma_malformed);
212 // Get the tokens enclosed within the __pragma(), as well as the final ')'.
213 SmallVector<Token, 32> PragmaToks;
216 while (Tok.isNot(tok::eof)) {
217 PragmaToks.push_back(Tok);
218 if (Tok.is(tok::l_paren))
220 else if (Tok.is(tok::r_paren) && NumParens-- == 0)
225 if (Tok.is(tok::eof)) {
226 Diag(PragmaLoc, diag::err_unterminated___pragma);
230 PragmaToks.front().setFlag(Token::LeadingSpace);
232 // Replace the ')' with an EOD to mark the end of the pragma.
233 PragmaToks.back().setKind(tok::eod);
235 Token *TokArray = new Token[PragmaToks.size()];
236 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
238 // Push the tokens onto the stack.
239 EnterTokenStream(TokArray, PragmaToks.size(), true, true);
241 // With everything set up, lex this as a #pragma directive.
242 HandlePragmaDirective(PIK___pragma);
244 // Finally, return whatever came after the pragma directive.
248 /// HandlePragmaOnce - Handle #pragma once. OnceTok is the 'once'.
250 void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
251 if (isInPrimaryFile()) {
252 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
256 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
257 // Mark the file as a once-only file now.
258 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
261 void Preprocessor::HandlePragmaMark() {
262 assert(CurPPLexer && "No current lexer?");
264 CurLexer->ReadToEndOfLine();
266 CurPTHLexer->DiscardToEndOfLine();
270 /// HandlePragmaPoison - Handle #pragma GCC poison. PoisonTok is the 'poison'.
272 void Preprocessor::HandlePragmaPoison(Token &PoisonTok) {
276 // Read the next token to poison. While doing this, pretend that we are
277 // skipping while reading the identifier to poison.
278 // This avoids errors on code like:
279 // #pragma GCC poison X
280 // #pragma GCC poison X
281 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
282 LexUnexpandedToken(Tok);
283 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
285 // If we reached the end of line, we're done.
286 if (Tok.is(tok::eod)) return;
288 // Can only poison identifiers.
289 if (Tok.isNot(tok::raw_identifier)) {
290 Diag(Tok, diag::err_pp_invalid_poison);
294 // Look up the identifier info for the token. We disabled identifier lookup
295 // by saying we're skipping contents, so we need to do this manually.
296 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
299 if (II->isPoisoned()) continue;
301 // If this is a macro identifier, emit a warning.
302 if (II->hasMacroDefinition())
303 Diag(Tok, diag::pp_poisoning_existing_macro);
305 // Finally, poison it!
310 /// HandlePragmaSystemHeader - Implement #pragma GCC system_header. We know
311 /// that the whole directive has been parsed.
312 void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
313 if (isInPrimaryFile()) {
314 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
318 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
319 PreprocessorLexer *TheLexer = getCurrentFileLexer();
321 // Mark the file as a system header.
322 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
325 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
326 if (PLoc.isInvalid())
329 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
331 // Notify the client, if desired, that we are in a new source file.
333 Callbacks->FileChanged(SysHeaderTok.getLocation(),
334 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
336 // Emit a line marker. This will change any source locations from this point
337 // forward to realize they are in a system header.
338 // Create a line note with this information.
339 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine(), FilenameID,
340 false, false, true, false);
343 /// HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah.
345 void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
347 CurPPLexer->LexIncludeFilename(FilenameTok);
349 // If the token kind is EOD, the error has already been diagnosed.
350 if (FilenameTok.is(tok::eod))
353 // Reserve a buffer to get the spelling.
354 llvm::SmallString<128> FilenameBuffer;
355 bool Invalid = false;
356 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
361 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
362 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
364 if (Filename.empty())
367 // Search include directories for this file.
368 const DirectoryLookup *CurDir;
369 const FileEntry *File = LookupFile(Filename, isAngled, 0, CurDir, NULL, NULL,
372 if (!SuppressIncludeNotFoundError)
373 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
377 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
379 // If this file is older than the file it depends on, emit a diagnostic.
380 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
381 // Lex tokens at the end of the message and include them in the message.
384 while (DependencyTok.isNot(tok::eod)) {
385 Message += getSpelling(DependencyTok) + " ";
389 // Remove the trailing ' ' if present.
390 if (!Message.empty())
391 Message.erase(Message.end()-1);
392 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
396 /// HandlePragmaComment - Handle the microsoft #pragma comment extension. The
398 /// #pragma comment(linker, "foo")
399 /// 'linker' is one of five identifiers: compiler, exestr, lib, linker, user.
400 /// "foo" is a string, which is fully macro expanded, and permits string
401 /// concatenation, embedded escape characters etc. See MSDN for more details.
402 void Preprocessor::HandlePragmaComment(Token &Tok) {
403 SourceLocation CommentLoc = Tok.getLocation();
405 if (Tok.isNot(tok::l_paren)) {
406 Diag(CommentLoc, diag::err_pragma_comment_malformed);
410 // Read the identifier.
412 if (Tok.isNot(tok::identifier)) {
413 Diag(CommentLoc, diag::err_pragma_comment_malformed);
417 // Verify that this is one of the 5 whitelisted options.
418 // FIXME: warn that 'exestr' is deprecated.
419 const IdentifierInfo *II = Tok.getIdentifierInfo();
420 if (!II->isStr("compiler") && !II->isStr("exestr") && !II->isStr("lib") &&
421 !II->isStr("linker") && !II->isStr("user")) {
422 Diag(Tok.getLocation(), diag::err_pragma_comment_unknown_kind);
426 // Read the optional string if present.
428 std::string ArgumentString;
429 if (Tok.is(tok::comma)) {
430 Lex(Tok); // eat the comma.
432 // We need at least one string.
433 if (Tok.isNot(tok::string_literal)) {
434 Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
438 // String concatenation allows multiple strings, which can even come from
440 // "foo " "bar" "Baz"
441 SmallVector<Token, 4> StrToks;
442 while (Tok.is(tok::string_literal)) {
443 StrToks.push_back(Tok);
447 // Concatenate and parse the strings.
448 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
449 assert(Literal.isAscii() && "Didn't allow wide strings in");
450 if (Literal.hadError)
452 if (Literal.Pascal) {
453 Diag(StrToks[0].getLocation(), diag::err_pragma_comment_malformed);
457 ArgumentString = Literal.GetString();
460 // FIXME: If the kind is "compiler" warn if the string is present (it is
462 // FIXME: 'lib' requires a comment string.
463 // FIXME: 'linker' requires a comment string, and has a specific list of
464 // things that are allowable.
466 if (Tok.isNot(tok::r_paren)) {
467 Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
470 Lex(Tok); // eat the r_paren.
472 if (Tok.isNot(tok::eod)) {
473 Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
477 // If the pragma is lexically sound, notify any interested PPCallbacks.
479 Callbacks->PragmaComment(CommentLoc, II, ArgumentString);
482 /// HandlePragmaMessage - Handle the microsoft and gcc #pragma message
483 /// extension. The syntax is:
484 /// #pragma message(string)
486 /// #pragma message string
487 /// string is a string, which is fully macro expanded, and permits string
488 /// concatenation, embedded escape characters, etc... See MSDN for more details.
489 void Preprocessor::HandlePragmaMessage(Token &Tok) {
490 SourceLocation MessageLoc = Tok.getLocation();
492 bool ExpectClosingParen = false;
493 switch (Tok.getKind()) {
495 // We have a MSVC style pragma message.
496 ExpectClosingParen = true;
500 case tok::string_literal:
501 // We have a GCC style pragma message, and we just read the string.
504 Diag(MessageLoc, diag::err_pragma_message_malformed);
508 // We need at least one string.
509 if (Tok.isNot(tok::string_literal)) {
510 Diag(Tok.getLocation(), diag::err_pragma_message_malformed);
514 // String concatenation allows multiple strings, which can even come from
516 // "foo " "bar" "Baz"
517 SmallVector<Token, 4> StrToks;
518 while (Tok.is(tok::string_literal)) {
519 StrToks.push_back(Tok);
523 // Concatenate and parse the strings.
524 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
525 assert(Literal.isAscii() && "Didn't allow wide strings in");
526 if (Literal.hadError)
528 if (Literal.Pascal) {
529 Diag(StrToks[0].getLocation(), diag::err_pragma_message_malformed);
533 StringRef MessageString(Literal.GetString());
535 if (ExpectClosingParen) {
536 if (Tok.isNot(tok::r_paren)) {
537 Diag(Tok.getLocation(), diag::err_pragma_message_malformed);
540 Lex(Tok); // eat the r_paren.
543 if (Tok.isNot(tok::eod)) {
544 Diag(Tok.getLocation(), diag::err_pragma_message_malformed);
548 // Output the message.
549 Diag(MessageLoc, diag::warn_pragma_message) << MessageString;
551 // If the pragma is lexically sound, notify any interested PPCallbacks.
553 Callbacks->PragmaMessage(MessageLoc, MessageString);
556 /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
557 /// Return the IdentifierInfo* associated with the macro to push or pop.
558 IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
559 // Remember the pragma token location.
560 Token PragmaTok = Tok;
564 if (Tok.isNot(tok::l_paren)) {
565 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
566 << getSpelling(PragmaTok);
570 // Read the macro name string.
572 if (Tok.isNot(tok::string_literal)) {
573 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
574 << getSpelling(PragmaTok);
578 // Remember the macro string.
579 std::string StrVal = getSpelling(Tok);
583 if (Tok.isNot(tok::r_paren)) {
584 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
585 << getSpelling(PragmaTok);
589 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
590 "Invalid string token!");
592 // Create a Token from the string.
594 MacroTok.startToken();
595 MacroTok.setKind(tok::raw_identifier);
596 CreateString(&StrVal[1], StrVal.size() - 2, MacroTok);
598 // Get the IdentifierInfo of MacroToPushTok.
599 return LookUpIdentifierInfo(MacroTok);
602 /// HandlePragmaPushMacro - Handle #pragma push_macro.
604 /// #pragma push_macro("macro")
605 void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
606 // Parse the pragma directive and get the macro IdentifierInfo*.
607 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
608 if (!IdentInfo) return;
610 // Get the MacroInfo associated with IdentInfo.
611 MacroInfo *MI = getMacroInfo(IdentInfo);
613 MacroInfo *MacroCopyToPush = 0;
615 // Make a clone of MI.
616 MacroCopyToPush = CloneMacroInfo(*MI);
618 // Allow the original MacroInfo to be redefined later.
619 MI->setIsAllowRedefinitionsWithoutWarning(true);
622 // Push the cloned MacroInfo so we can retrieve it later.
623 PragmaPushMacroInfo[IdentInfo].push_back(MacroCopyToPush);
626 /// HandlePragmaPopMacro - Handle #pragma pop_macro.
628 /// #pragma pop_macro("macro")
629 void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
630 SourceLocation MessageLoc = PopMacroTok.getLocation();
632 // Parse the pragma directive and get the macro IdentifierInfo*.
633 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
634 if (!IdentInfo) return;
636 // Find the vector<MacroInfo*> associated with the macro.
637 llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
638 PragmaPushMacroInfo.find(IdentInfo);
639 if (iter != PragmaPushMacroInfo.end()) {
640 // Release the MacroInfo currently associated with IdentInfo.
641 MacroInfo *CurrentMI = getMacroInfo(IdentInfo);
643 if (CurrentMI->isWarnIfUnused())
644 WarnUnusedMacroLocs.erase(CurrentMI->getDefinitionLoc());
645 ReleaseMacroInfo(CurrentMI);
648 // Get the MacroInfo we want to reinstall.
649 MacroInfo *MacroToReInstall = iter->second.back();
651 // Reinstall the previously pushed macro.
652 setMacroInfo(IdentInfo, MacroToReInstall);
654 // Pop PragmaPushMacroInfo stack.
655 iter->second.pop_back();
656 if (iter->second.size() == 0)
657 PragmaPushMacroInfo.erase(iter);
659 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
660 << IdentInfo->getName();
664 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
665 /// If 'Namespace' is non-null, then it is a token required to exist on the
666 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
667 void Preprocessor::AddPragmaHandler(StringRef Namespace,
668 PragmaHandler *Handler) {
669 PragmaNamespace *InsertNS = PragmaHandlers;
671 // If this is specified to be in a namespace, step down into it.
672 if (!Namespace.empty()) {
673 // If there is already a pragma handler with the name of this namespace,
674 // we either have an error (directive with the same name as a namespace) or
675 // we already have the namespace to insert into.
676 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
677 InsertNS = Existing->getIfNamespace();
678 assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
679 " handler with the same name!");
681 // Otherwise, this namespace doesn't exist yet, create and insert the
683 InsertNS = new PragmaNamespace(Namespace);
684 PragmaHandlers->AddPragma(InsertNS);
688 // Check to make sure we don't already have a pragma for this identifier.
689 assert(!InsertNS->FindHandler(Handler->getName()) &&
690 "Pragma handler already exists for this identifier!");
691 InsertNS->AddPragma(Handler);
694 /// RemovePragmaHandler - Remove the specific pragma handler from the
695 /// preprocessor. If \arg Namespace is non-null, then it should be the
696 /// namespace that \arg Handler was added to. It is an error to remove
697 /// a handler that has not been registered.
698 void Preprocessor::RemovePragmaHandler(StringRef Namespace,
699 PragmaHandler *Handler) {
700 PragmaNamespace *NS = PragmaHandlers;
702 // If this is specified to be in a namespace, step down into it.
703 if (!Namespace.empty()) {
704 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
705 assert(Existing && "Namespace containing handler does not exist!");
707 NS = Existing->getIfNamespace();
708 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
711 NS->RemovePragmaHandler(Handler);
713 // If this is a non-default namespace and it is now empty, remove
715 if (NS != PragmaHandlers && NS->IsEmpty())
716 PragmaHandlers->RemovePragmaHandler(NS);
719 bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
721 LexUnexpandedToken(Tok);
723 if (Tok.isNot(tok::identifier)) {
724 Diag(Tok, diag::ext_on_off_switch_syntax);
727 IdentifierInfo *II = Tok.getIdentifierInfo();
729 Result = tok::OOS_ON;
730 else if (II->isStr("OFF"))
731 Result = tok::OOS_OFF;
732 else if (II->isStr("DEFAULT"))
733 Result = tok::OOS_DEFAULT;
735 Diag(Tok, diag::ext_on_off_switch_syntax);
739 // Verify that this is followed by EOD.
740 LexUnexpandedToken(Tok);
741 if (Tok.isNot(tok::eod))
742 Diag(Tok, diag::ext_pragma_syntax_eod);
747 /// PragmaOnceHandler - "#pragma once" marks the file as atomically included.
748 struct PragmaOnceHandler : public PragmaHandler {
749 PragmaOnceHandler() : PragmaHandler("once") {}
750 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
752 PP.CheckEndOfDirective("pragma once");
753 PP.HandlePragmaOnce(OnceTok);
757 /// PragmaMarkHandler - "#pragma mark ..." is ignored by the compiler, and the
758 /// rest of the line is not lexed.
759 struct PragmaMarkHandler : public PragmaHandler {
760 PragmaMarkHandler() : PragmaHandler("mark") {}
761 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
763 PP.HandlePragmaMark();
767 /// PragmaPoisonHandler - "#pragma poison x" marks x as not usable.
768 struct PragmaPoisonHandler : public PragmaHandler {
769 PragmaPoisonHandler() : PragmaHandler("poison") {}
770 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
772 PP.HandlePragmaPoison(PoisonTok);
776 /// PragmaSystemHeaderHandler - "#pragma system_header" marks the current file
777 /// as a system header, which silences warnings in it.
778 struct PragmaSystemHeaderHandler : public PragmaHandler {
779 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
780 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
782 PP.HandlePragmaSystemHeader(SHToken);
783 PP.CheckEndOfDirective("pragma");
786 struct PragmaDependencyHandler : public PragmaHandler {
787 PragmaDependencyHandler() : PragmaHandler("dependency") {}
788 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
790 PP.HandlePragmaDependency(DepToken);
794 struct PragmaDebugHandler : public PragmaHandler {
795 PragmaDebugHandler() : PragmaHandler("__debug") {}
796 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
799 PP.LexUnexpandedToken(Tok);
800 if (Tok.isNot(tok::identifier)) {
801 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
804 IdentifierInfo *II = Tok.getIdentifierInfo();
806 if (II->isStr("assert")) {
807 llvm_unreachable("This is an assertion!");
808 } else if (II->isStr("crash")) {
809 *(volatile int*) 0x11 = 0;
810 } else if (II->isStr("llvm_fatal_error")) {
811 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
812 } else if (II->isStr("llvm_unreachable")) {
813 llvm_unreachable("#pragma clang __debug llvm_unreachable");
814 } else if (II->isStr("overflow_stack")) {
815 DebugOverflowStack();
816 } else if (II->isStr("handle_crash")) {
817 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
821 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
826 // Disable MSVC warning about runtime stack overflow.
828 #pragma warning(disable : 4717)
830 void DebugOverflowStack() {
831 DebugOverflowStack();
834 #pragma warning(default : 4717)
839 /// PragmaDiagnosticHandler - e.g. '#pragma GCC diagnostic ignored "-Wformat"'
840 struct PragmaDiagnosticHandler : public PragmaHandler {
842 const char *Namespace;
844 explicit PragmaDiagnosticHandler(const char *NS) :
845 PragmaHandler("diagnostic"), Namespace(NS) {}
846 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
848 SourceLocation DiagLoc = DiagToken.getLocation();
850 PP.LexUnexpandedToken(Tok);
851 if (Tok.isNot(tok::identifier)) {
852 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
855 IdentifierInfo *II = Tok.getIdentifierInfo();
856 PPCallbacks *Callbacks = PP.getPPCallbacks();
859 if (II->isStr("warning"))
860 Map = diag::MAP_WARNING;
861 else if (II->isStr("error"))
862 Map = diag::MAP_ERROR;
863 else if (II->isStr("ignored"))
864 Map = diag::MAP_IGNORE;
865 else if (II->isStr("fatal"))
866 Map = diag::MAP_FATAL;
867 else if (II->isStr("pop")) {
868 if (!PP.getDiagnostics().popMappings(DiagLoc))
869 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
871 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
873 } else if (II->isStr("push")) {
874 PP.getDiagnostics().pushMappings(DiagLoc);
876 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
879 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
883 PP.LexUnexpandedToken(Tok);
885 // We need at least one string.
886 if (Tok.isNot(tok::string_literal)) {
887 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
891 // String concatenation allows multiple strings, which can even come from
893 // "foo " "bar" "Baz"
894 SmallVector<Token, 4> StrToks;
895 while (Tok.is(tok::string_literal)) {
896 StrToks.push_back(Tok);
897 PP.LexUnexpandedToken(Tok);
900 if (Tok.isNot(tok::eod)) {
901 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
905 // Concatenate and parse the strings.
906 StringLiteralParser Literal(&StrToks[0], StrToks.size(), PP);
907 assert(Literal.isAscii() && "Didn't allow wide strings in");
908 if (Literal.hadError)
910 if (Literal.Pascal) {
911 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
915 StringRef WarningName(Literal.GetString());
917 if (WarningName.size() < 3 || WarningName[0] != '-' ||
918 WarningName[1] != 'W') {
919 PP.Diag(StrToks[0].getLocation(),
920 diag::warn_pragma_diagnostic_invalid_option);
924 if (PP.getDiagnostics().setDiagnosticGroupMapping(WarningName.substr(2),
926 PP.Diag(StrToks[0].getLocation(),
927 diag::warn_pragma_diagnostic_unknown_warning) << WarningName;
929 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, Map, WarningName);
933 /// PragmaCommentHandler - "#pragma comment ...".
934 struct PragmaCommentHandler : public PragmaHandler {
935 PragmaCommentHandler() : PragmaHandler("comment") {}
936 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
938 PP.HandlePragmaComment(CommentTok);
942 /// PragmaMessageHandler - "#pragma message("...")".
943 struct PragmaMessageHandler : public PragmaHandler {
944 PragmaMessageHandler() : PragmaHandler("message") {}
945 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
947 PP.HandlePragmaMessage(CommentTok);
951 /// PragmaPushMacroHandler - "#pragma push_macro" saves the value of the
952 /// macro on the top of the stack.
953 struct PragmaPushMacroHandler : public PragmaHandler {
954 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
955 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
956 Token &PushMacroTok) {
957 PP.HandlePragmaPushMacro(PushMacroTok);
962 /// PragmaPopMacroHandler - "#pragma pop_macro" sets the value of the
963 /// macro to the value on the top of the stack.
964 struct PragmaPopMacroHandler : public PragmaHandler {
965 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
966 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
967 Token &PopMacroTok) {
968 PP.HandlePragmaPopMacro(PopMacroTok);
972 // Pragma STDC implementations.
974 /// PragmaSTDC_FENV_ACCESSHandler - "#pragma STDC FENV_ACCESS ...".
975 struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
976 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
977 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
979 tok::OnOffSwitch OOS;
980 if (PP.LexOnOffSwitch(OOS))
982 if (OOS == tok::OOS_ON)
983 PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
987 /// PragmaSTDC_CX_LIMITED_RANGEHandler - "#pragma STDC CX_LIMITED_RANGE ...".
988 struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
989 PragmaSTDC_CX_LIMITED_RANGEHandler()
990 : PragmaHandler("CX_LIMITED_RANGE") {}
991 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
993 tok::OnOffSwitch OOS;
994 PP.LexOnOffSwitch(OOS);
998 /// PragmaSTDC_UnknownHandler - "#pragma STDC ...".
999 struct PragmaSTDC_UnknownHandler : public PragmaHandler {
1000 PragmaSTDC_UnknownHandler() {}
1001 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1002 Token &UnknownTok) {
1003 // C99 6.10.6p2, unknown forms are not allowed.
1004 PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
1008 /// PragmaARCCFCodeAuditedHandler -
1009 /// #pragma clang arc_cf_code_audited begin/end
1010 struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1011 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
1012 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1014 SourceLocation Loc = NameTok.getLocation();
1019 // Lex the 'begin' or 'end'.
1020 PP.LexUnexpandedToken(Tok);
1021 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1022 if (BeginEnd && BeginEnd->isStr("begin")) {
1024 } else if (BeginEnd && BeginEnd->isStr("end")) {
1027 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1031 // Verify that this is followed by EOD.
1032 PP.LexUnexpandedToken(Tok);
1033 if (Tok.isNot(tok::eod))
1034 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1036 // The start location of the active audit.
1037 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1039 // The start location we want after processing this.
1040 SourceLocation NewLoc;
1043 // Complain about attempts to re-enter an audit.
1044 if (BeginLoc.isValid()) {
1045 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1046 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1050 // Complain about attempts to leave an audit that doesn't exist.
1051 if (!BeginLoc.isValid()) {
1052 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1055 NewLoc = SourceLocation();
1058 PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1062 } // end anonymous namespace
1065 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
1066 /// #pragma GCC poison/system_header/dependency and #pragma once.
1067 void Preprocessor::RegisterBuiltinPragmas() {
1068 AddPragmaHandler(new PragmaOnceHandler());
1069 AddPragmaHandler(new PragmaMarkHandler());
1070 AddPragmaHandler(new PragmaPushMacroHandler());
1071 AddPragmaHandler(new PragmaPopMacroHandler());
1072 AddPragmaHandler(new PragmaMessageHandler());
1075 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1076 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1077 AddPragmaHandler("GCC", new PragmaDependencyHandler());
1078 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
1079 // #pragma clang ...
1080 AddPragmaHandler("clang", new PragmaPoisonHandler());
1081 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
1082 AddPragmaHandler("clang", new PragmaDebugHandler());
1083 AddPragmaHandler("clang", new PragmaDependencyHandler());
1084 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
1085 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
1087 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1088 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
1089 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
1092 if (Features.MicrosoftExt) {
1093 AddPragmaHandler(new PragmaCommentHandler());