1 //===--- Pragma.cpp - Pragma registration and handling --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the PragmaHandler/PragmaTable interfaces and implements
11 // pragma related methods of the Preprocessor class.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Lex/Pragma.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "clang/Lex/HeaderSearch.h"
19 #include "clang/Lex/LexDiagnostic.h"
20 #include "clang/Lex/LiteralSupport.h"
21 #include "clang/Lex/MacroInfo.h"
22 #include "clang/Lex/Preprocessor.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 //===----------------------------------------------------------------------===//
46 PragmaNamespace::~PragmaNamespace() {
47 for (llvm::StringMap<PragmaHandler*>::iterator
48 I = Handlers.begin(), E = Handlers.end(); I != E; ++I)
52 /// FindHandler - Check to see if there is already a handler for the
53 /// specified name. If not, return the handler for the null identifier if it
54 /// exists, otherwise return null. If IgnoreNull is true (the default) then
55 /// the null handler isn't returned on failure to match.
56 PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
57 bool IgnoreNull) const {
58 if (PragmaHandler *Handler = Handlers.lookup(Name))
60 return IgnoreNull ? 0 : Handlers.lookup(StringRef());
63 void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
64 assert(!Handlers.lookup(Handler->getName()) &&
65 "A handler with this name is already registered in this namespace");
66 llvm::StringMapEntry<PragmaHandler *> &Entry =
67 Handlers.GetOrCreateValue(Handler->getName());
68 Entry.setValue(Handler);
71 void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
72 assert(Handlers.lookup(Handler->getName()) &&
73 "Handler not registered in this namespace");
74 Handlers.erase(Handler->getName());
77 void PragmaNamespace::HandlePragma(Preprocessor &PP,
78 PragmaIntroducerKind Introducer,
80 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
81 // expand it, the user can have a STDC #define, that should not affect this.
82 PP.LexUnexpandedToken(Tok);
84 // Get the handler for this token. If there is no handler, ignore the pragma.
85 PragmaHandler *Handler
86 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
88 /*IgnoreNull=*/false);
90 PP.Diag(Tok, diag::warn_pragma_ignored);
94 // Otherwise, pass it down.
95 Handler->HandlePragma(PP, Introducer, Tok);
98 //===----------------------------------------------------------------------===//
99 // Preprocessor Pragma Directive Handling.
100 //===----------------------------------------------------------------------===//
102 /// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the
103 /// rest of the pragma, passing it to the registered pragma handlers.
104 void Preprocessor::HandlePragmaDirective(unsigned Introducer) {
110 // Invoke the first level of pragma handlers which reads the namespace id.
112 PragmaHandlers->HandlePragma(*this, PragmaIntroducerKind(Introducer), Tok);
114 // If the pragma handler didn't read the rest of the line, consume it now.
115 if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
116 || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
117 DiscardUntilEndOfDirective();
121 /// \brief Helper class for \see Preprocessor::Handle_Pragma.
122 class LexingFor_PragmaRAII {
124 bool InMacroArgPreExpansion;
130 LexingFor_PragmaRAII(Preprocessor &PP, bool InMacroArgPreExpansion,
132 : PP(PP), InMacroArgPreExpansion(InMacroArgPreExpansion),
133 Failed(false), OutTok(Tok) {
134 if (InMacroArgPreExpansion) {
136 PP.EnableBacktrackAtThisPos();
140 ~LexingFor_PragmaRAII() {
141 if (InMacroArgPreExpansion) {
143 PP.CommitBacktrackedTokens();
157 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
158 /// return the first token after the directive. The _Pragma token has just
159 /// been read into 'Tok'.
160 void Preprocessor::Handle_Pragma(Token &Tok) {
162 // This works differently if we are pre-expanding a macro argument.
163 // In that case we don't actually "activate" the pragma now, we only lex it
164 // until we are sure it is lexically correct and then we backtrack so that
165 // we activate the pragma whenever we encounter the tokens again in the token
166 // stream. This ensures that we will activate it in the correct location
167 // or that we will ignore it if it never enters the token stream, e.g:
170 // #define INACTIVE(x) EMPTY(x)
171 // INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\""))
173 LexingFor_PragmaRAII _PragmaLexing(*this, InMacroArgPreExpansion, Tok);
175 // Remember the pragma token location.
176 SourceLocation PragmaLoc = Tok.getLocation();
180 if (Tok.isNot(tok::l_paren)) {
181 Diag(PragmaLoc, diag::err__Pragma_malformed);
182 return _PragmaLexing.failed();
187 if (!tok::isStringLiteral(Tok.getKind())) {
188 Diag(PragmaLoc, diag::err__Pragma_malformed);
189 // Skip this token, and the ')', if present.
190 if (Tok.isNot(tok::r_paren))
192 if (Tok.is(tok::r_paren))
194 return _PragmaLexing.failed();
197 if (Tok.hasUDSuffix()) {
198 Diag(Tok, diag::err_invalid_string_udl);
199 // Skip this token, and the ')', if present.
201 if (Tok.is(tok::r_paren))
203 return _PragmaLexing.failed();
206 // Remember the string.
211 if (Tok.isNot(tok::r_paren)) {
212 Diag(PragmaLoc, diag::err__Pragma_malformed);
213 return _PragmaLexing.failed();
216 if (InMacroArgPreExpansion)
219 SourceLocation RParenLoc = Tok.getLocation();
220 std::string StrVal = getSpelling(StrTok);
222 // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1:
223 // "The string literal is destringized by deleting any encoding prefix,
224 // deleting the leading and trailing double-quotes, replacing each escape
225 // sequence \" by a double-quote, and replacing each escape sequence \\ by a
226 // single backslash."
227 if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
228 (StrVal[0] == 'u' && StrVal[1] != '8'))
229 StrVal.erase(StrVal.begin());
230 else if (StrVal[0] == 'u')
231 StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
233 if (StrVal[0] == 'R') {
234 // FIXME: C++11 does not specify how to handle raw-string-literals here.
235 // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
236 assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
237 "Invalid raw string token!");
239 // Measure the length of the d-char-sequence.
240 unsigned NumDChars = 0;
241 while (StrVal[2 + NumDChars] != '(') {
242 assert(NumDChars < (StrVal.size() - 5) / 2 &&
243 "Invalid raw string token!");
246 assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
248 // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
250 StrVal.erase(0, 2 + NumDChars);
251 StrVal.erase(StrVal.size() - 1 - NumDChars);
253 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
254 "Invalid string token!");
256 // Remove escaped quotes and escapes.
257 unsigned ResultPos = 1;
258 for (unsigned i = 1, e = StrVal.size() - 2; i != e; ++i) {
259 if (StrVal[i] != '\\' ||
260 (StrVal[i + 1] != '\\' && StrVal[i + 1] != '"')) {
261 // \\ -> '\' and \" -> '"'.
262 StrVal[ResultPos++] = StrVal[i];
265 StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 2);
268 // Remove the front quote, replacing it with a space, so that the pragma
269 // contents appear to have a space before them.
272 // Replace the terminating quote with a \n.
273 StrVal[StrVal.size()-1] = '\n';
275 // Plop the string (including the newline and trailing null) into a buffer
276 // where we can lex it.
279 CreateString(StrVal, TmpTok);
280 SourceLocation TokLoc = TmpTok.getLocation();
282 // Make and enter a lexer object so that we lex and expand the tokens just
284 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
285 StrVal.size(), *this);
287 EnterSourceFileWithLexer(TL, 0);
289 // With everything set up, lex this as a #pragma directive.
290 HandlePragmaDirective(PIK__Pragma);
292 // Finally, return whatever came after the pragma directive.
296 /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
297 /// is not enclosed within a string literal.
298 void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
299 // Remember the pragma token location.
300 SourceLocation PragmaLoc = Tok.getLocation();
304 if (Tok.isNot(tok::l_paren)) {
305 Diag(PragmaLoc, diag::err__Pragma_malformed);
309 // Get the tokens enclosed within the __pragma(), as well as the final ')'.
310 SmallVector<Token, 32> PragmaToks;
313 while (Tok.isNot(tok::eof)) {
314 PragmaToks.push_back(Tok);
315 if (Tok.is(tok::l_paren))
317 else if (Tok.is(tok::r_paren) && NumParens-- == 0)
322 if (Tok.is(tok::eof)) {
323 Diag(PragmaLoc, diag::err_unterminated___pragma);
327 PragmaToks.front().setFlag(Token::LeadingSpace);
329 // Replace the ')' with an EOD to mark the end of the pragma.
330 PragmaToks.back().setKind(tok::eod);
332 Token *TokArray = new Token[PragmaToks.size()];
333 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
335 // Push the tokens onto the stack.
336 EnterTokenStream(TokArray, PragmaToks.size(), true, true);
338 // With everything set up, lex this as a #pragma directive.
339 HandlePragmaDirective(PIK___pragma);
341 // Finally, return whatever came after the pragma directive.
345 /// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
347 void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
348 if (isInPrimaryFile()) {
349 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
353 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
354 // Mark the file as a once-only file now.
355 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
358 void Preprocessor::HandlePragmaMark() {
359 assert(CurPPLexer && "No current lexer?");
361 CurLexer->ReadToEndOfLine();
363 CurPTHLexer->DiscardToEndOfLine();
367 /// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
369 void Preprocessor::HandlePragmaPoison(Token &PoisonTok) {
373 // Read the next token to poison. While doing this, pretend that we are
374 // skipping while reading the identifier to poison.
375 // This avoids errors on code like:
376 // #pragma GCC poison X
377 // #pragma GCC poison X
378 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
379 LexUnexpandedToken(Tok);
380 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
382 // If we reached the end of line, we're done.
383 if (Tok.is(tok::eod)) return;
385 // Can only poison identifiers.
386 if (Tok.isNot(tok::raw_identifier)) {
387 Diag(Tok, diag::err_pp_invalid_poison);
391 // Look up the identifier info for the token. We disabled identifier lookup
392 // by saying we're skipping contents, so we need to do this manually.
393 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
396 if (II->isPoisoned()) continue;
398 // If this is a macro identifier, emit a warning.
399 if (II->hasMacroDefinition())
400 Diag(Tok, diag::pp_poisoning_existing_macro);
402 // Finally, poison it!
405 II->setChangedSinceDeserialization();
409 /// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
410 /// that the whole directive has been parsed.
411 void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
412 if (isInPrimaryFile()) {
413 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
417 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
418 PreprocessorLexer *TheLexer = getCurrentFileLexer();
420 // Mark the file as a system header.
421 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
424 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
425 if (PLoc.isInvalid())
428 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
430 // Notify the client, if desired, that we are in a new source file.
432 Callbacks->FileChanged(SysHeaderTok.getLocation(),
433 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
435 // Emit a line marker. This will change any source locations from this point
436 // forward to realize they are in a system header.
437 // Create a line note with this information.
438 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine()+1,
439 FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
440 /*IsSystem=*/true, /*IsExternC=*/false);
443 /// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
445 void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
447 CurPPLexer->LexIncludeFilename(FilenameTok);
449 // If the token kind is EOD, the error has already been diagnosed.
450 if (FilenameTok.is(tok::eod))
453 // Reserve a buffer to get the spelling.
454 SmallString<128> FilenameBuffer;
455 bool Invalid = false;
456 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
461 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
462 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
464 if (Filename.empty())
467 // Search include directories for this file.
468 const DirectoryLookup *CurDir;
469 const FileEntry *File = LookupFile(Filename, isAngled, 0, CurDir, NULL, NULL,
472 if (!SuppressIncludeNotFoundError)
473 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
477 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
479 // If this file is older than the file it depends on, emit a diagnostic.
480 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
481 // Lex tokens at the end of the message and include them in the message.
484 while (DependencyTok.isNot(tok::eod)) {
485 Message += getSpelling(DependencyTok) + " ";
489 // Remove the trailing ' ' if present.
490 if (!Message.empty())
491 Message.erase(Message.end()-1);
492 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
496 /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
497 /// Return the IdentifierInfo* associated with the macro to push or pop.
498 IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
499 // Remember the pragma token location.
500 Token PragmaTok = Tok;
504 if (Tok.isNot(tok::l_paren)) {
505 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
506 << getSpelling(PragmaTok);
510 // Read the macro name string.
512 if (Tok.isNot(tok::string_literal)) {
513 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
514 << getSpelling(PragmaTok);
518 if (Tok.hasUDSuffix()) {
519 Diag(Tok, diag::err_invalid_string_udl);
523 // Remember the macro string.
524 std::string StrVal = getSpelling(Tok);
528 if (Tok.isNot(tok::r_paren)) {
529 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
530 << getSpelling(PragmaTok);
534 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
535 "Invalid string token!");
537 // Create a Token from the string.
539 MacroTok.startToken();
540 MacroTok.setKind(tok::raw_identifier);
541 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
543 // Get the IdentifierInfo of MacroToPushTok.
544 return LookUpIdentifierInfo(MacroTok);
547 /// \brief Handle \#pragma push_macro.
551 /// #pragma push_macro("macro")
553 void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
554 // Parse the pragma directive and get the macro IdentifierInfo*.
555 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
556 if (!IdentInfo) return;
558 // Get the MacroInfo associated with IdentInfo.
559 MacroInfo *MI = getMacroInfo(IdentInfo);
562 // Allow the original MacroInfo to be redefined later.
563 MI->setIsAllowRedefinitionsWithoutWarning(true);
566 // Push the cloned MacroInfo so we can retrieve it later.
567 PragmaPushMacroInfo[IdentInfo].push_back(MI);
570 /// \brief Handle \#pragma pop_macro.
574 /// #pragma pop_macro("macro")
576 void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
577 SourceLocation MessageLoc = PopMacroTok.getLocation();
579 // Parse the pragma directive and get the macro IdentifierInfo*.
580 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
581 if (!IdentInfo) return;
583 // Find the vector<MacroInfo*> associated with the macro.
584 llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
585 PragmaPushMacroInfo.find(IdentInfo);
586 if (iter != PragmaPushMacroInfo.end()) {
587 // Forget the MacroInfo currently associated with IdentInfo.
588 if (MacroDirective *CurrentMD = getMacroDirective(IdentInfo)) {
589 MacroInfo *MI = CurrentMD->getMacroInfo();
590 if (MI->isWarnIfUnused())
591 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
592 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
595 // Get the MacroInfo we want to reinstall.
596 MacroInfo *MacroToReInstall = iter->second.back();
598 if (MacroToReInstall) {
599 // Reinstall the previously pushed macro.
600 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc,
601 /*isImported=*/false);
604 // Pop PragmaPushMacroInfo stack.
605 iter->second.pop_back();
606 if (iter->second.size() == 0)
607 PragmaPushMacroInfo.erase(iter);
609 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
610 << IdentInfo->getName();
614 void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
615 // We will either get a quoted filename or a bracketed filename, and we
616 // have to track which we got. The first filename is the source name,
617 // and the second name is the mapped filename. If the first is quoted,
618 // the second must be as well (cannot mix and match quotes and brackets).
620 // Get the open paren
622 if (Tok.isNot(tok::l_paren)) {
623 Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
627 // We expect either a quoted string literal, or a bracketed name
628 Token SourceFilenameTok;
629 CurPPLexer->LexIncludeFilename(SourceFilenameTok);
630 if (SourceFilenameTok.is(tok::eod)) {
631 // The diagnostic has already been handled
635 StringRef SourceFileName;
636 SmallString<128> FileNameBuffer;
637 if (SourceFilenameTok.is(tok::string_literal) ||
638 SourceFilenameTok.is(tok::angle_string_literal)) {
639 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
640 } else if (SourceFilenameTok.is(tok::less)) {
641 // This could be a path instead of just a name
642 FileNameBuffer.push_back('<');
644 if (ConcatenateIncludeName(FileNameBuffer, End))
645 return; // Diagnostic already emitted
646 SourceFileName = FileNameBuffer.str();
648 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
651 FileNameBuffer.clear();
653 // Now we expect a comma, followed by another include name
655 if (Tok.isNot(tok::comma)) {
656 Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
660 Token ReplaceFilenameTok;
661 CurPPLexer->LexIncludeFilename(ReplaceFilenameTok);
662 if (ReplaceFilenameTok.is(tok::eod)) {
663 // The diagnostic has already been handled
667 StringRef ReplaceFileName;
668 if (ReplaceFilenameTok.is(tok::string_literal) ||
669 ReplaceFilenameTok.is(tok::angle_string_literal)) {
670 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
671 } else if (ReplaceFilenameTok.is(tok::less)) {
672 // This could be a path instead of just a name
673 FileNameBuffer.push_back('<');
675 if (ConcatenateIncludeName(FileNameBuffer, End))
676 return; // Diagnostic already emitted
677 ReplaceFileName = FileNameBuffer.str();
679 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
683 // Finally, we expect the closing paren
685 if (Tok.isNot(tok::r_paren)) {
686 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
690 // Now that we have the source and target filenames, we need to make sure
691 // they're both of the same type (angled vs non-angled)
692 StringRef OriginalSource = SourceFileName;
694 bool SourceIsAngled =
695 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
697 bool ReplaceIsAngled =
698 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
700 if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
701 (SourceIsAngled != ReplaceIsAngled)) {
704 DiagID = diag::warn_pragma_include_alias_mismatch_angle;
706 DiagID = diag::warn_pragma_include_alias_mismatch_quote;
708 Diag(SourceFilenameTok.getLocation(), DiagID)
715 // Now we can let the include handler know about this mapping
716 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
719 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
720 /// If 'Namespace' is non-null, then it is a token required to exist on the
721 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
722 void Preprocessor::AddPragmaHandler(StringRef Namespace,
723 PragmaHandler *Handler) {
724 PragmaNamespace *InsertNS = PragmaHandlers;
726 // If this is specified to be in a namespace, step down into it.
727 if (!Namespace.empty()) {
728 // If there is already a pragma handler with the name of this namespace,
729 // we either have an error (directive with the same name as a namespace) or
730 // we already have the namespace to insert into.
731 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
732 InsertNS = Existing->getIfNamespace();
733 assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
734 " handler with the same name!");
736 // Otherwise, this namespace doesn't exist yet, create and insert the
738 InsertNS = new PragmaNamespace(Namespace);
739 PragmaHandlers->AddPragma(InsertNS);
743 // Check to make sure we don't already have a pragma for this identifier.
744 assert(!InsertNS->FindHandler(Handler->getName()) &&
745 "Pragma handler already exists for this identifier!");
746 InsertNS->AddPragma(Handler);
749 /// RemovePragmaHandler - Remove the specific pragma handler from the
750 /// preprocessor. If \arg Namespace is non-null, then it should be the
751 /// namespace that \arg Handler was added to. It is an error to remove
752 /// a handler that has not been registered.
753 void Preprocessor::RemovePragmaHandler(StringRef Namespace,
754 PragmaHandler *Handler) {
755 PragmaNamespace *NS = PragmaHandlers;
757 // If this is specified to be in a namespace, step down into it.
758 if (!Namespace.empty()) {
759 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
760 assert(Existing && "Namespace containing handler does not exist!");
762 NS = Existing->getIfNamespace();
763 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
766 NS->RemovePragmaHandler(Handler);
768 // If this is a non-default namespace and it is now empty, remove
770 if (NS != PragmaHandlers && NS->IsEmpty()) {
771 PragmaHandlers->RemovePragmaHandler(NS);
776 bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
778 LexUnexpandedToken(Tok);
780 if (Tok.isNot(tok::identifier)) {
781 Diag(Tok, diag::ext_on_off_switch_syntax);
784 IdentifierInfo *II = Tok.getIdentifierInfo();
786 Result = tok::OOS_ON;
787 else if (II->isStr("OFF"))
788 Result = tok::OOS_OFF;
789 else if (II->isStr("DEFAULT"))
790 Result = tok::OOS_DEFAULT;
792 Diag(Tok, diag::ext_on_off_switch_syntax);
796 // Verify that this is followed by EOD.
797 LexUnexpandedToken(Tok);
798 if (Tok.isNot(tok::eod))
799 Diag(Tok, diag::ext_pragma_syntax_eod);
804 /// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
805 struct PragmaOnceHandler : public PragmaHandler {
806 PragmaOnceHandler() : PragmaHandler("once") {}
807 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
809 PP.CheckEndOfDirective("pragma once");
810 PP.HandlePragmaOnce(OnceTok);
814 /// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
815 /// rest of the line is not lexed.
816 struct PragmaMarkHandler : public PragmaHandler {
817 PragmaMarkHandler() : PragmaHandler("mark") {}
818 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
820 PP.HandlePragmaMark();
824 /// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
825 struct PragmaPoisonHandler : public PragmaHandler {
826 PragmaPoisonHandler() : PragmaHandler("poison") {}
827 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
829 PP.HandlePragmaPoison(PoisonTok);
833 /// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
834 /// as a system header, which silences warnings in it.
835 struct PragmaSystemHeaderHandler : public PragmaHandler {
836 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
837 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
839 PP.HandlePragmaSystemHeader(SHToken);
840 PP.CheckEndOfDirective("pragma");
843 struct PragmaDependencyHandler : public PragmaHandler {
844 PragmaDependencyHandler() : PragmaHandler("dependency") {}
845 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
847 PP.HandlePragmaDependency(DepToken);
851 struct PragmaDebugHandler : public PragmaHandler {
852 PragmaDebugHandler() : PragmaHandler("__debug") {}
853 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
856 PP.LexUnexpandedToken(Tok);
857 if (Tok.isNot(tok::identifier)) {
858 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
861 IdentifierInfo *II = Tok.getIdentifierInfo();
863 if (II->isStr("assert")) {
864 llvm_unreachable("This is an assertion!");
865 } else if (II->isStr("crash")) {
867 } else if (II->isStr("parser_crash")) {
869 Crasher.setKind(tok::annot_pragma_parser_crash);
870 PP.EnterToken(Crasher);
871 } else if (II->isStr("llvm_fatal_error")) {
872 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
873 } else if (II->isStr("llvm_unreachable")) {
874 llvm_unreachable("#pragma clang __debug llvm_unreachable");
875 } else if (II->isStr("overflow_stack")) {
876 DebugOverflowStack();
877 } else if (II->isStr("handle_crash")) {
878 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
881 } else if (II->isStr("captured")) {
884 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
888 PPCallbacks *Callbacks = PP.getPPCallbacks();
890 Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
893 void HandleCaptured(Preprocessor &PP) {
894 // Skip if emitting preprocessed output.
895 if (PP.isPreprocessedOutput())
899 PP.LexUnexpandedToken(Tok);
901 if (Tok.isNot(tok::eod)) {
902 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
903 << "pragma clang __debug captured";
907 SourceLocation NameLoc = Tok.getLocation();
908 Token *Toks = PP.getPreprocessorAllocator().Allocate<Token>(1);
910 Toks->setKind(tok::annot_pragma_captured);
911 Toks->setLocation(NameLoc);
913 PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true,
914 /*OwnsTokens=*/false);
917 // Disable MSVC warning about runtime stack overflow.
919 #pragma warning(disable : 4717)
921 void DebugOverflowStack() {
922 DebugOverflowStack();
925 #pragma warning(default : 4717)
930 /// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
931 struct PragmaDiagnosticHandler : public PragmaHandler {
933 const char *Namespace;
935 explicit PragmaDiagnosticHandler(const char *NS) :
936 PragmaHandler("diagnostic"), Namespace(NS) {}
937 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
939 SourceLocation DiagLoc = DiagToken.getLocation();
941 PP.LexUnexpandedToken(Tok);
942 if (Tok.isNot(tok::identifier)) {
943 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
946 IdentifierInfo *II = Tok.getIdentifierInfo();
947 PPCallbacks *Callbacks = PP.getPPCallbacks();
950 if (II->isStr("warning"))
951 Map = diag::MAP_WARNING;
952 else if (II->isStr("error"))
953 Map = diag::MAP_ERROR;
954 else if (II->isStr("ignored"))
955 Map = diag::MAP_IGNORE;
956 else if (II->isStr("fatal"))
957 Map = diag::MAP_FATAL;
958 else if (II->isStr("pop")) {
959 if (!PP.getDiagnostics().popMappings(DiagLoc))
960 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
962 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
964 } else if (II->isStr("push")) {
965 PP.getDiagnostics().pushMappings(DiagLoc);
967 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
970 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
974 PP.LexUnexpandedToken(Tok);
975 SourceLocation StringLoc = Tok.getLocation();
977 std::string WarningName;
978 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
979 /*MacroExpansion=*/false))
982 if (Tok.isNot(tok::eod)) {
983 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
987 if (WarningName.size() < 3 || WarningName[0] != '-' ||
988 WarningName[1] != 'W') {
989 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
993 if (PP.getDiagnostics().setDiagnosticGroupMapping(WarningName.substr(2),
995 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
998 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, Map, WarningName);
1002 /// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
1003 struct PragmaIncludeAliasHandler : public PragmaHandler {
1004 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
1005 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1006 Token &IncludeAliasTok) {
1007 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
1011 /// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1012 /// extension. The syntax is:
1014 /// #pragma message(string)
1016 /// OR, in GCC mode:
1018 /// #pragma message string
1020 /// string is a string, which is fully macro expanded, and permits string
1021 /// concatenation, embedded escape characters, etc... See MSDN for more details.
1022 /// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1023 /// form as \#pragma message.
1024 struct PragmaMessageHandler : public PragmaHandler {
1026 const PPCallbacks::PragmaMessageKind Kind;
1027 const StringRef Namespace;
1029 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1030 bool PragmaNameOnly = false) {
1032 case PPCallbacks::PMK_Message:
1033 return PragmaNameOnly ? "message" : "pragma message";
1034 case PPCallbacks::PMK_Warning:
1035 return PragmaNameOnly ? "warning" : "pragma warning";
1036 case PPCallbacks::PMK_Error:
1037 return PragmaNameOnly ? "error" : "pragma error";
1039 llvm_unreachable("Unknown PragmaMessageKind!");
1043 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1044 StringRef Namespace = StringRef())
1045 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), Namespace(Namespace) {}
1047 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1049 SourceLocation MessageLoc = Tok.getLocation();
1051 bool ExpectClosingParen = false;
1052 switch (Tok.getKind()) {
1054 // We have a MSVC style pragma message.
1055 ExpectClosingParen = true;
1059 case tok::string_literal:
1060 // We have a GCC style pragma message, and we just read the string.
1063 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1067 std::string MessageString;
1068 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1069 /*MacroExpansion=*/true))
1072 if (ExpectClosingParen) {
1073 if (Tok.isNot(tok::r_paren)) {
1074 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1077 PP.Lex(Tok); // eat the r_paren.
1080 if (Tok.isNot(tok::eod)) {
1081 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1085 // Output the message.
1086 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1087 ? diag::err_pragma_message
1088 : diag::warn_pragma_message) << MessageString;
1090 // If the pragma is lexically sound, notify any interested PPCallbacks.
1091 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1092 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
1096 /// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
1097 /// macro on the top of the stack.
1098 struct PragmaPushMacroHandler : public PragmaHandler {
1099 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
1100 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1101 Token &PushMacroTok) {
1102 PP.HandlePragmaPushMacro(PushMacroTok);
1107 /// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
1108 /// macro to the value on the top of the stack.
1109 struct PragmaPopMacroHandler : public PragmaHandler {
1110 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
1111 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1112 Token &PopMacroTok) {
1113 PP.HandlePragmaPopMacro(PopMacroTok);
1117 // Pragma STDC implementations.
1119 /// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
1120 struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
1121 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
1122 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1124 tok::OnOffSwitch OOS;
1125 if (PP.LexOnOffSwitch(OOS))
1127 if (OOS == tok::OOS_ON)
1128 PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
1132 /// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
1133 struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
1134 PragmaSTDC_CX_LIMITED_RANGEHandler()
1135 : PragmaHandler("CX_LIMITED_RANGE") {}
1136 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1138 tok::OnOffSwitch OOS;
1139 PP.LexOnOffSwitch(OOS);
1143 /// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
1144 struct PragmaSTDC_UnknownHandler : public PragmaHandler {
1145 PragmaSTDC_UnknownHandler() {}
1146 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1147 Token &UnknownTok) {
1148 // C99 6.10.6p2, unknown forms are not allowed.
1149 PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
1153 /// PragmaARCCFCodeAuditedHandler -
1154 /// \#pragma clang arc_cf_code_audited begin/end
1155 struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1156 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
1157 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1159 SourceLocation Loc = NameTok.getLocation();
1164 // Lex the 'begin' or 'end'.
1165 PP.LexUnexpandedToken(Tok);
1166 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1167 if (BeginEnd && BeginEnd->isStr("begin")) {
1169 } else if (BeginEnd && BeginEnd->isStr("end")) {
1172 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1176 // Verify that this is followed by EOD.
1177 PP.LexUnexpandedToken(Tok);
1178 if (Tok.isNot(tok::eod))
1179 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1181 // The start location of the active audit.
1182 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1184 // The start location we want after processing this.
1185 SourceLocation NewLoc;
1188 // Complain about attempts to re-enter an audit.
1189 if (BeginLoc.isValid()) {
1190 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1191 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1195 // Complain about attempts to leave an audit that doesn't exist.
1196 if (!BeginLoc.isValid()) {
1197 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1200 NewLoc = SourceLocation();
1203 PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1207 /// \brief Handle "\#pragma region [...]"
1211 /// #pragma region [optional name]
1212 /// #pragma endregion [optional comment]
1216 /// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1217 /// pragma, just skipped by compiler.
1218 struct PragmaRegionHandler : public PragmaHandler {
1219 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) { }
1221 virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1223 // #pragma region: endregion matches can be verified
1224 // __pragma(region): no sense, but ignored by msvc
1225 // _Pragma is not valid for MSVC, but there isn't any point
1226 // to handle a _Pragma differently.
1230 } // end anonymous namespace
1233 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
1234 /// \#pragma GCC poison/system_header/dependency and \#pragma once.
1235 void Preprocessor::RegisterBuiltinPragmas() {
1236 AddPragmaHandler(new PragmaOnceHandler());
1237 AddPragmaHandler(new PragmaMarkHandler());
1238 AddPragmaHandler(new PragmaPushMacroHandler());
1239 AddPragmaHandler(new PragmaPopMacroHandler());
1240 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
1243 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1244 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1245 AddPragmaHandler("GCC", new PragmaDependencyHandler());
1246 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
1247 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1249 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1251 // #pragma clang ...
1252 AddPragmaHandler("clang", new PragmaPoisonHandler());
1253 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
1254 AddPragmaHandler("clang", new PragmaDebugHandler());
1255 AddPragmaHandler("clang", new PragmaDependencyHandler());
1256 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
1257 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
1259 AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1260 AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
1261 AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
1264 if (LangOpts.MicrosoftExt) {
1265 AddPragmaHandler(new PragmaIncludeAliasHandler());
1266 AddPragmaHandler(new PragmaRegionHandler("region"));
1267 AddPragmaHandler(new PragmaRegionHandler("endregion"));