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(llvm::StringRef Name,
58 bool IgnoreNull) const {
59 if (PragmaHandler *Handler = Handlers.lookup(Name))
61 return IgnoreNull ? 0 : Handlers.lookup(llvm::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 llvm::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 llvm::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);
371 Diag(FilenameTok, diag::warn_pp_file_not_found) << Filename;
375 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
377 // If this file is older than the file it depends on, emit a diagnostic.
378 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
379 // Lex tokens at the end of the message and include them in the message.
382 while (DependencyTok.isNot(tok::eod)) {
383 Message += getSpelling(DependencyTok) + " ";
387 // Remove the trailing ' ' if present.
388 if (!Message.empty())
389 Message.erase(Message.end()-1);
390 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
394 /// HandlePragmaComment - Handle the microsoft #pragma comment extension. The
396 /// #pragma comment(linker, "foo")
397 /// 'linker' is one of five identifiers: compiler, exestr, lib, linker, user.
398 /// "foo" is a string, which is fully macro expanded, and permits string
399 /// concatenation, embedded escape characters etc. See MSDN for more details.
400 void Preprocessor::HandlePragmaComment(Token &Tok) {
401 SourceLocation CommentLoc = Tok.getLocation();
403 if (Tok.isNot(tok::l_paren)) {
404 Diag(CommentLoc, diag::err_pragma_comment_malformed);
408 // Read the identifier.
410 if (Tok.isNot(tok::identifier)) {
411 Diag(CommentLoc, diag::err_pragma_comment_malformed);
415 // Verify that this is one of the 5 whitelisted options.
416 // FIXME: warn that 'exestr' is deprecated.
417 const IdentifierInfo *II = Tok.getIdentifierInfo();
418 if (!II->isStr("compiler") && !II->isStr("exestr") && !II->isStr("lib") &&
419 !II->isStr("linker") && !II->isStr("user")) {
420 Diag(Tok.getLocation(), diag::err_pragma_comment_unknown_kind);
424 // Read the optional string if present.
426 std::string ArgumentString;
427 if (Tok.is(tok::comma)) {
428 Lex(Tok); // eat the comma.
430 // We need at least one string.
431 if (Tok.isNot(tok::string_literal)) {
432 Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
436 // String concatenation allows multiple strings, which can even come from
438 // "foo " "bar" "Baz"
439 llvm::SmallVector<Token, 4> StrToks;
440 while (Tok.is(tok::string_literal)) {
441 StrToks.push_back(Tok);
445 // Concatenate and parse the strings.
446 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
447 assert(!Literal.AnyWide && "Didn't allow wide strings in");
448 if (Literal.hadError)
450 if (Literal.Pascal) {
451 Diag(StrToks[0].getLocation(), diag::err_pragma_comment_malformed);
455 ArgumentString = Literal.GetString();
458 // FIXME: If the kind is "compiler" warn if the string is present (it is
460 // FIXME: 'lib' requires a comment string.
461 // FIXME: 'linker' requires a comment string, and has a specific list of
462 // things that are allowable.
464 if (Tok.isNot(tok::r_paren)) {
465 Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
468 Lex(Tok); // eat the r_paren.
470 if (Tok.isNot(tok::eod)) {
471 Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
475 // If the pragma is lexically sound, notify any interested PPCallbacks.
477 Callbacks->PragmaComment(CommentLoc, II, ArgumentString);
480 /// HandlePragmaMessage - Handle the microsoft and gcc #pragma message
481 /// extension. The syntax is:
482 /// #pragma message(string)
484 /// #pragma message string
485 /// string is a string, which is fully macro expanded, and permits string
486 /// concatenation, embedded escape characters, etc... See MSDN for more details.
487 void Preprocessor::HandlePragmaMessage(Token &Tok) {
488 SourceLocation MessageLoc = Tok.getLocation();
490 bool ExpectClosingParen = false;
491 switch (Tok.getKind()) {
493 // We have a MSVC style pragma message.
494 ExpectClosingParen = true;
498 case tok::string_literal:
499 // We have a GCC style pragma message, and we just read the string.
502 Diag(MessageLoc, diag::err_pragma_message_malformed);
506 // We need at least one string.
507 if (Tok.isNot(tok::string_literal)) {
508 Diag(Tok.getLocation(), diag::err_pragma_message_malformed);
512 // String concatenation allows multiple strings, which can even come from
514 // "foo " "bar" "Baz"
515 llvm::SmallVector<Token, 4> StrToks;
516 while (Tok.is(tok::string_literal)) {
517 StrToks.push_back(Tok);
521 // Concatenate and parse the strings.
522 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
523 assert(!Literal.AnyWide && "Didn't allow wide strings in");
524 if (Literal.hadError)
526 if (Literal.Pascal) {
527 Diag(StrToks[0].getLocation(), diag::err_pragma_message_malformed);
531 llvm::StringRef MessageString(Literal.GetString());
533 if (ExpectClosingParen) {
534 if (Tok.isNot(tok::r_paren)) {
535 Diag(Tok.getLocation(), diag::err_pragma_message_malformed);
538 Lex(Tok); // eat the r_paren.
541 if (Tok.isNot(tok::eod)) {
542 Diag(Tok.getLocation(), diag::err_pragma_message_malformed);
546 // Output the message.
547 Diag(MessageLoc, diag::warn_pragma_message) << MessageString;
549 // If the pragma is lexically sound, notify any interested PPCallbacks.
551 Callbacks->PragmaMessage(MessageLoc, MessageString);
554 /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
555 /// Return the IdentifierInfo* associated with the macro to push or pop.
556 IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
557 // Remember the pragma token location.
558 Token PragmaTok = Tok;
562 if (Tok.isNot(tok::l_paren)) {
563 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
564 << getSpelling(PragmaTok);
568 // Read the macro name string.
570 if (Tok.isNot(tok::string_literal)) {
571 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
572 << getSpelling(PragmaTok);
576 // Remember the macro string.
577 std::string StrVal = getSpelling(Tok);
581 if (Tok.isNot(tok::r_paren)) {
582 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
583 << getSpelling(PragmaTok);
587 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
588 "Invalid string token!");
590 // Create a Token from the string.
592 MacroTok.startToken();
593 MacroTok.setKind(tok::raw_identifier);
594 CreateString(&StrVal[1], StrVal.size() - 2, MacroTok);
596 // Get the IdentifierInfo of MacroToPushTok.
597 return LookUpIdentifierInfo(MacroTok);
600 /// HandlePragmaPushMacro - Handle #pragma push_macro.
602 /// #pragma push_macro("macro")
603 void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
604 // Parse the pragma directive and get the macro IdentifierInfo*.
605 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
606 if (!IdentInfo) return;
608 // Get the MacroInfo associated with IdentInfo.
609 MacroInfo *MI = getMacroInfo(IdentInfo);
611 MacroInfo *MacroCopyToPush = 0;
613 // Make a clone of MI.
614 MacroCopyToPush = CloneMacroInfo(*MI);
616 // Allow the original MacroInfo to be redefined later.
617 MI->setIsAllowRedefinitionsWithoutWarning(true);
620 // Push the cloned MacroInfo so we can retrieve it later.
621 PragmaPushMacroInfo[IdentInfo].push_back(MacroCopyToPush);
624 /// HandlePragmaPopMacro - Handle #pragma pop_macro.
626 /// #pragma pop_macro("macro")
627 void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
628 SourceLocation MessageLoc = PopMacroTok.getLocation();
630 // Parse the pragma directive and get the macro IdentifierInfo*.
631 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
632 if (!IdentInfo) return;
634 // Find the vector<MacroInfo*> associated with the macro.
635 llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
636 PragmaPushMacroInfo.find(IdentInfo);
637 if (iter != PragmaPushMacroInfo.end()) {
638 // Release the MacroInfo currently associated with IdentInfo.
639 MacroInfo *CurrentMI = getMacroInfo(IdentInfo);
641 if (CurrentMI->isWarnIfUnused())
642 WarnUnusedMacroLocs.erase(CurrentMI->getDefinitionLoc());
643 ReleaseMacroInfo(CurrentMI);
646 // Get the MacroInfo we want to reinstall.
647 MacroInfo *MacroToReInstall = iter->second.back();
649 // Reinstall the previously pushed macro.
650 setMacroInfo(IdentInfo, MacroToReInstall);
652 // Pop PragmaPushMacroInfo stack.
653 iter->second.pop_back();
654 if (iter->second.size() == 0)
655 PragmaPushMacroInfo.erase(iter);
657 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
658 << IdentInfo->getName();
662 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
663 /// If 'Namespace' is non-null, then it is a token required to exist on the
664 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
665 void Preprocessor::AddPragmaHandler(llvm::StringRef Namespace,
666 PragmaHandler *Handler) {
667 PragmaNamespace *InsertNS = PragmaHandlers;
669 // If this is specified to be in a namespace, step down into it.
670 if (!Namespace.empty()) {
671 // If there is already a pragma handler with the name of this namespace,
672 // we either have an error (directive with the same name as a namespace) or
673 // we already have the namespace to insert into.
674 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
675 InsertNS = Existing->getIfNamespace();
676 assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
677 " handler with the same name!");
679 // Otherwise, this namespace doesn't exist yet, create and insert the
681 InsertNS = new PragmaNamespace(Namespace);
682 PragmaHandlers->AddPragma(InsertNS);
686 // Check to make sure we don't already have a pragma for this identifier.
687 assert(!InsertNS->FindHandler(Handler->getName()) &&
688 "Pragma handler already exists for this identifier!");
689 InsertNS->AddPragma(Handler);
692 /// RemovePragmaHandler - Remove the specific pragma handler from the
693 /// preprocessor. If \arg Namespace is non-null, then it should be the
694 /// namespace that \arg Handler was added to. It is an error to remove
695 /// a handler that has not been registered.
696 void Preprocessor::RemovePragmaHandler(llvm::StringRef Namespace,
697 PragmaHandler *Handler) {
698 PragmaNamespace *NS = PragmaHandlers;
700 // If this is specified to be in a namespace, step down into it.
701 if (!Namespace.empty()) {
702 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
703 assert(Existing && "Namespace containing handler does not exist!");
705 NS = Existing->getIfNamespace();
706 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
709 NS->RemovePragmaHandler(Handler);
711 // If this is a non-default namespace and it is now empty, remove
713 if (NS != PragmaHandlers && NS->IsEmpty())
714 PragmaHandlers->RemovePragmaHandler(NS);
717 bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
719 LexUnexpandedToken(Tok);
721 if (Tok.isNot(tok::identifier)) {
722 Diag(Tok, diag::ext_on_off_switch_syntax);
725 IdentifierInfo *II = Tok.getIdentifierInfo();
727 Result = tok::OOS_ON;
728 else if (II->isStr("OFF"))
729 Result = tok::OOS_OFF;
730 else if (II->isStr("DEFAULT"))
731 Result = tok::OOS_DEFAULT;
733 Diag(Tok, diag::ext_on_off_switch_syntax);
737 // Verify that this is followed by EOD.
738 LexUnexpandedToken(Tok);
739 if (Tok.isNot(tok::eod))
740 Diag(Tok, diag::ext_pragma_syntax_eod);
745 /// PragmaOnceHandler - "#pragma once" marks the file as atomically included.
746 struct PragmaOnceHandler : public PragmaHandler {
747 PragmaOnceHandler() : PragmaHandler("once") {}
748 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
750 PP.CheckEndOfDirective("pragma once");
751 PP.HandlePragmaOnce(OnceTok);
755 /// PragmaMarkHandler - "#pragma mark ..." is ignored by the compiler, and the
756 /// rest of the line is not lexed.
757 struct PragmaMarkHandler : public PragmaHandler {
758 PragmaMarkHandler() : PragmaHandler("mark") {}
759 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
761 PP.HandlePragmaMark();
765 /// PragmaPoisonHandler - "#pragma poison x" marks x as not usable.
766 struct PragmaPoisonHandler : public PragmaHandler {
767 PragmaPoisonHandler() : PragmaHandler("poison") {}
768 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
770 PP.HandlePragmaPoison(PoisonTok);
774 /// PragmaSystemHeaderHandler - "#pragma system_header" marks the current file
775 /// as a system header, which silences warnings in it.
776 struct PragmaSystemHeaderHandler : public PragmaHandler {
777 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
778 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
780 PP.HandlePragmaSystemHeader(SHToken);
781 PP.CheckEndOfDirective("pragma");
784 struct PragmaDependencyHandler : public PragmaHandler {
785 PragmaDependencyHandler() : PragmaHandler("dependency") {}
786 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
788 PP.HandlePragmaDependency(DepToken);
792 struct PragmaDebugHandler : public PragmaHandler {
793 PragmaDebugHandler() : PragmaHandler("__debug") {}
794 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
797 PP.LexUnexpandedToken(Tok);
798 if (Tok.isNot(tok::identifier)) {
799 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
802 IdentifierInfo *II = Tok.getIdentifierInfo();
804 if (II->isStr("assert")) {
805 assert(0 && "This is an assertion!");
806 } else if (II->isStr("crash")) {
807 *(volatile int*) 0x11 = 0;
808 } else if (II->isStr("llvm_fatal_error")) {
809 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
810 } else if (II->isStr("llvm_unreachable")) {
811 llvm_unreachable("#pragma clang __debug llvm_unreachable");
812 } else if (II->isStr("overflow_stack")) {
813 DebugOverflowStack();
814 } else if (II->isStr("handle_crash")) {
815 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
819 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
824 // Disable MSVC warning about runtime stack overflow.
826 #pragma warning(disable : 4717)
828 void DebugOverflowStack() {
829 DebugOverflowStack();
832 #pragma warning(default : 4717)
837 /// PragmaDiagnosticHandler - e.g. '#pragma GCC diagnostic ignored "-Wformat"'
838 struct PragmaDiagnosticHandler : public PragmaHandler {
840 const char *Namespace;
842 explicit PragmaDiagnosticHandler(const char *NS) :
843 PragmaHandler("diagnostic"), Namespace(NS) {}
844 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
846 SourceLocation DiagLoc = DiagToken.getLocation();
848 PP.LexUnexpandedToken(Tok);
849 if (Tok.isNot(tok::identifier)) {
850 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
853 IdentifierInfo *II = Tok.getIdentifierInfo();
854 PPCallbacks *Callbacks = PP.getPPCallbacks();
857 if (II->isStr("warning"))
858 Map = diag::MAP_WARNING;
859 else if (II->isStr("error"))
860 Map = diag::MAP_ERROR;
861 else if (II->isStr("ignored"))
862 Map = diag::MAP_IGNORE;
863 else if (II->isStr("fatal"))
864 Map = diag::MAP_FATAL;
865 else if (II->isStr("pop")) {
866 if (!PP.getDiagnostics().popMappings(DiagLoc))
867 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
869 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
871 } else if (II->isStr("push")) {
872 PP.getDiagnostics().pushMappings(DiagLoc);
874 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
877 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
881 PP.LexUnexpandedToken(Tok);
883 // We need at least one string.
884 if (Tok.isNot(tok::string_literal)) {
885 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
889 // String concatenation allows multiple strings, which can even come from
891 // "foo " "bar" "Baz"
892 llvm::SmallVector<Token, 4> StrToks;
893 while (Tok.is(tok::string_literal)) {
894 StrToks.push_back(Tok);
895 PP.LexUnexpandedToken(Tok);
898 if (Tok.isNot(tok::eod)) {
899 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
903 // Concatenate and parse the strings.
904 StringLiteralParser Literal(&StrToks[0], StrToks.size(), PP);
905 assert(!Literal.AnyWide && "Didn't allow wide strings in");
906 if (Literal.hadError)
908 if (Literal.Pascal) {
909 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
913 llvm::StringRef WarningName(Literal.GetString());
915 if (WarningName.size() < 3 || WarningName[0] != '-' ||
916 WarningName[1] != 'W') {
917 PP.Diag(StrToks[0].getLocation(),
918 diag::warn_pragma_diagnostic_invalid_option);
922 if (PP.getDiagnostics().setDiagnosticGroupMapping(WarningName.substr(2),
924 PP.Diag(StrToks[0].getLocation(),
925 diag::warn_pragma_diagnostic_unknown_warning) << WarningName;
927 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, Map, WarningName);
931 /// PragmaCommentHandler - "#pragma comment ...".
932 struct PragmaCommentHandler : public PragmaHandler {
933 PragmaCommentHandler() : PragmaHandler("comment") {}
934 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
936 PP.HandlePragmaComment(CommentTok);
940 /// PragmaMessageHandler - "#pragma message("...")".
941 struct PragmaMessageHandler : public PragmaHandler {
942 PragmaMessageHandler() : PragmaHandler("message") {}
943 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
945 PP.HandlePragmaMessage(CommentTok);
949 /// PragmaPushMacroHandler - "#pragma push_macro" saves the value of the
950 /// macro on the top of the stack.
951 struct PragmaPushMacroHandler : public PragmaHandler {
952 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
953 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
954 Token &PushMacroTok) {
955 PP.HandlePragmaPushMacro(PushMacroTok);
960 /// PragmaPopMacroHandler - "#pragma pop_macro" sets the value of the
961 /// macro to the value on the top of the stack.
962 struct PragmaPopMacroHandler : public PragmaHandler {
963 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
964 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
965 Token &PopMacroTok) {
966 PP.HandlePragmaPopMacro(PopMacroTok);
970 // Pragma STDC implementations.
972 /// PragmaSTDC_FENV_ACCESSHandler - "#pragma STDC FENV_ACCESS ...".
973 struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
974 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
975 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
977 tok::OnOffSwitch OOS;
978 if (PP.LexOnOffSwitch(OOS))
980 if (OOS == tok::OOS_ON)
981 PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
985 /// PragmaSTDC_CX_LIMITED_RANGEHandler - "#pragma STDC CX_LIMITED_RANGE ...".
986 struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
987 PragmaSTDC_CX_LIMITED_RANGEHandler()
988 : PragmaHandler("CX_LIMITED_RANGE") {}
989 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
991 tok::OnOffSwitch OOS;
992 PP.LexOnOffSwitch(OOS);
996 /// PragmaSTDC_UnknownHandler - "#pragma STDC ...".
997 struct PragmaSTDC_UnknownHandler : public PragmaHandler {
998 PragmaSTDC_UnknownHandler() {}
999 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1000 Token &UnknownTok) {
1001 // C99 6.10.6p2, unknown forms are not allowed.
1002 PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
1006 } // end anonymous namespace
1009 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
1010 /// #pragma GCC poison/system_header/dependency and #pragma once.
1011 void Preprocessor::RegisterBuiltinPragmas() {
1012 AddPragmaHandler(new PragmaOnceHandler());
1013 AddPragmaHandler(new PragmaMarkHandler());
1014 AddPragmaHandler(new PragmaPushMacroHandler());
1015 AddPragmaHandler(new PragmaPopMacroHandler());
1016 AddPragmaHandler(new PragmaMessageHandler());
1019 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1020 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1021 AddPragmaHandler("GCC", new PragmaDependencyHandler());
1022 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
1023 // #pragma clang ...
1024 AddPragmaHandler("clang", new PragmaPoisonHandler());
1025 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
1026 AddPragmaHandler("clang", new PragmaDebugHandler());
1027 AddPragmaHandler("clang", new PragmaDependencyHandler());
1028 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
1030 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1031 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
1032 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
1035 if (Features.Microsoft) {
1036 AddPragmaHandler(new PragmaCommentHandler());