clang API Documentation

Pragma.cpp
Go to the documentation of this file.
00001 //===--- Pragma.cpp - Pragma registration and handling --------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the PragmaHandler/PragmaTable interfaces and implements
00011 // pragma related methods of the Preprocessor class.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "clang/Lex/Pragma.h"
00016 #include "clang/Basic/FileManager.h"
00017 #include "clang/Basic/SourceManager.h"
00018 #include "clang/Lex/HeaderSearch.h"
00019 #include "clang/Lex/LexDiagnostic.h"
00020 #include "clang/Lex/LiteralSupport.h"
00021 #include "clang/Lex/MacroInfo.h"
00022 #include "clang/Lex/Preprocessor.h"
00023 #include "llvm/ADT/STLExtras.h"
00024 #include "llvm/ADT/StringSwitch.h"
00025 #include "llvm/Support/CrashRecoveryContext.h"
00026 #include "llvm/Support/ErrorHandling.h"
00027 #include <algorithm>
00028 using namespace clang;
00029 
00030 #include "llvm/Support/raw_ostream.h"
00031 
00032 // Out-of-line destructor to provide a home for the class.
00033 PragmaHandler::~PragmaHandler() {
00034 }
00035 
00036 //===----------------------------------------------------------------------===//
00037 // EmptyPragmaHandler Implementation.
00038 //===----------------------------------------------------------------------===//
00039 
00040 EmptyPragmaHandler::EmptyPragmaHandler() {}
00041 
00042 void EmptyPragmaHandler::HandlePragma(Preprocessor &PP, 
00043                                       PragmaIntroducerKind Introducer,
00044                                       Token &FirstToken) {}
00045 
00046 //===----------------------------------------------------------------------===//
00047 // PragmaNamespace Implementation.
00048 //===----------------------------------------------------------------------===//
00049 
00050 PragmaNamespace::~PragmaNamespace() {
00051   llvm::DeleteContainerSeconds(Handlers);
00052 }
00053 
00054 /// FindHandler - Check to see if there is already a handler for the
00055 /// specified name.  If not, return the handler for the null identifier if it
00056 /// exists, otherwise return null.  If IgnoreNull is true (the default) then
00057 /// the null handler isn't returned on failure to match.
00058 PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
00059                                             bool IgnoreNull) const {
00060   if (PragmaHandler *Handler = Handlers.lookup(Name))
00061     return Handler;
00062   return IgnoreNull ? nullptr : Handlers.lookup(StringRef());
00063 }
00064 
00065 void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
00066   assert(!Handlers.lookup(Handler->getName()) &&
00067          "A handler with this name is already registered in this namespace");
00068   llvm::StringMapEntry<PragmaHandler *> &Entry =
00069     Handlers.GetOrCreateValue(Handler->getName());
00070   Entry.setValue(Handler);
00071 }
00072 
00073 void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
00074   assert(Handlers.lookup(Handler->getName()) &&
00075          "Handler not registered in this namespace");
00076   Handlers.erase(Handler->getName());
00077 }
00078 
00079 void PragmaNamespace::HandlePragma(Preprocessor &PP, 
00080                                    PragmaIntroducerKind Introducer,
00081                                    Token &Tok) {
00082   // Read the 'namespace' that the directive is in, e.g. STDC.  Do not macro
00083   // expand it, the user can have a STDC #define, that should not affect this.
00084   PP.LexUnexpandedToken(Tok);
00085 
00086   // Get the handler for this token.  If there is no handler, ignore the pragma.
00087   PragmaHandler *Handler
00088     = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
00089                                           : StringRef(),
00090                   /*IgnoreNull=*/false);
00091   if (!Handler) {
00092     PP.Diag(Tok, diag::warn_pragma_ignored);
00093     return;
00094   }
00095 
00096   // Otherwise, pass it down.
00097   Handler->HandlePragma(PP, Introducer, Tok);
00098 }
00099 
00100 //===----------------------------------------------------------------------===//
00101 // Preprocessor Pragma Directive Handling.
00102 //===----------------------------------------------------------------------===//
00103 
00104 /// HandlePragmaDirective - The "\#pragma" directive has been parsed.  Lex the
00105 /// rest of the pragma, passing it to the registered pragma handlers.
00106 void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc,
00107                                          PragmaIntroducerKind Introducer) {
00108   if (Callbacks)
00109     Callbacks->PragmaDirective(IntroducerLoc, Introducer);
00110 
00111   if (!PragmasEnabled)
00112     return;
00113 
00114   ++NumPragma;
00115 
00116   // Invoke the first level of pragma handlers which reads the namespace id.
00117   Token Tok;
00118   PragmaHandlers->HandlePragma(*this, Introducer, Tok);
00119 
00120   // If the pragma handler didn't read the rest of the line, consume it now.
00121   if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective()) 
00122    || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
00123     DiscardUntilEndOfDirective();
00124 }
00125 
00126 namespace {
00127 /// \brief Helper class for \see Preprocessor::Handle_Pragma.
00128 class LexingFor_PragmaRAII {
00129   Preprocessor &PP;
00130   bool InMacroArgPreExpansion;
00131   bool Failed;
00132   Token &OutTok;
00133   Token PragmaTok;
00134 
00135 public:
00136   LexingFor_PragmaRAII(Preprocessor &PP, bool InMacroArgPreExpansion,
00137                        Token &Tok)
00138     : PP(PP), InMacroArgPreExpansion(InMacroArgPreExpansion),
00139       Failed(false), OutTok(Tok) {
00140     if (InMacroArgPreExpansion) {
00141       PragmaTok = OutTok;
00142       PP.EnableBacktrackAtThisPos();
00143     }
00144   }
00145 
00146   ~LexingFor_PragmaRAII() {
00147     if (InMacroArgPreExpansion) {
00148       if (Failed) {
00149         PP.CommitBacktrackedTokens();
00150       } else {
00151         PP.Backtrack();
00152         OutTok = PragmaTok;
00153       }
00154     }
00155   }
00156 
00157   void failed() {
00158     Failed = true;
00159   }
00160 };
00161 }
00162 
00163 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
00164 /// return the first token after the directive.  The _Pragma token has just
00165 /// been read into 'Tok'.
00166 void Preprocessor::Handle_Pragma(Token &Tok) {
00167 
00168   // This works differently if we are pre-expanding a macro argument.
00169   // In that case we don't actually "activate" the pragma now, we only lex it
00170   // until we are sure it is lexically correct and then we backtrack so that
00171   // we activate the pragma whenever we encounter the tokens again in the token
00172   // stream. This ensures that we will activate it in the correct location
00173   // or that we will ignore it if it never enters the token stream, e.g:
00174   //
00175   //     #define EMPTY(x)
00176   //     #define INACTIVE(x) EMPTY(x)
00177   //     INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\""))
00178 
00179   LexingFor_PragmaRAII _PragmaLexing(*this, InMacroArgPreExpansion, Tok);
00180 
00181   // Remember the pragma token location.
00182   SourceLocation PragmaLoc = Tok.getLocation();
00183 
00184   // Read the '('.
00185   Lex(Tok);
00186   if (Tok.isNot(tok::l_paren)) {
00187     Diag(PragmaLoc, diag::err__Pragma_malformed);
00188     return _PragmaLexing.failed();
00189   }
00190 
00191   // Read the '"..."'.
00192   Lex(Tok);
00193   if (!tok::isStringLiteral(Tok.getKind())) {
00194     Diag(PragmaLoc, diag::err__Pragma_malformed);
00195     // Skip this token, and the ')', if present.
00196     if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
00197       Lex(Tok);
00198     if (Tok.is(tok::r_paren))
00199       Lex(Tok);
00200     return _PragmaLexing.failed();
00201   }
00202 
00203   if (Tok.hasUDSuffix()) {
00204     Diag(Tok, diag::err_invalid_string_udl);
00205     // Skip this token, and the ')', if present.
00206     Lex(Tok);
00207     if (Tok.is(tok::r_paren))
00208       Lex(Tok);
00209     return _PragmaLexing.failed();
00210   }
00211 
00212   // Remember the string.
00213   Token StrTok = Tok;
00214 
00215   // Read the ')'.
00216   Lex(Tok);
00217   if (Tok.isNot(tok::r_paren)) {
00218     Diag(PragmaLoc, diag::err__Pragma_malformed);
00219     return _PragmaLexing.failed();
00220   }
00221 
00222   if (InMacroArgPreExpansion)
00223     return;
00224 
00225   SourceLocation RParenLoc = Tok.getLocation();
00226   std::string StrVal = getSpelling(StrTok);
00227 
00228   // The _Pragma is lexically sound.  Destringize according to C11 6.10.9.1:
00229   // "The string literal is destringized by deleting any encoding prefix,
00230   // deleting the leading and trailing double-quotes, replacing each escape
00231   // sequence \" by a double-quote, and replacing each escape sequence \\ by a
00232   // single backslash."
00233   if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
00234       (StrVal[0] == 'u' && StrVal[1] != '8'))
00235     StrVal.erase(StrVal.begin());
00236   else if (StrVal[0] == 'u')
00237     StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
00238 
00239   if (StrVal[0] == 'R') {
00240     // FIXME: C++11 does not specify how to handle raw-string-literals here.
00241     // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
00242     assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
00243            "Invalid raw string token!");
00244 
00245     // Measure the length of the d-char-sequence.
00246     unsigned NumDChars = 0;
00247     while (StrVal[2 + NumDChars] != '(') {
00248       assert(NumDChars < (StrVal.size() - 5) / 2 &&
00249              "Invalid raw string token!");
00250       ++NumDChars;
00251     }
00252     assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
00253 
00254     // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
00255     // parens below.
00256     StrVal.erase(0, 2 + NumDChars);
00257     StrVal.erase(StrVal.size() - 1 - NumDChars);
00258   } else {
00259     assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
00260            "Invalid string token!");
00261 
00262     // Remove escaped quotes and escapes.
00263     unsigned ResultPos = 1;
00264     for (unsigned i = 1, e = StrVal.size() - 1; i != e; ++i) {
00265       // Skip escapes.  \\ -> '\' and \" -> '"'.
00266       if (StrVal[i] == '\\' && i + 1 < e &&
00267           (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
00268         ++i;
00269       StrVal[ResultPos++] = StrVal[i];
00270     }
00271     StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
00272   }
00273 
00274   // Remove the front quote, replacing it with a space, so that the pragma
00275   // contents appear to have a space before them.
00276   StrVal[0] = ' ';
00277 
00278   // Replace the terminating quote with a \n.
00279   StrVal[StrVal.size()-1] = '\n';
00280 
00281   // Plop the string (including the newline and trailing null) into a buffer
00282   // where we can lex it.
00283   Token TmpTok;
00284   TmpTok.startToken();
00285   CreateString(StrVal, TmpTok);
00286   SourceLocation TokLoc = TmpTok.getLocation();
00287 
00288   // Make and enter a lexer object so that we lex and expand the tokens just
00289   // like any others.
00290   Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
00291                                         StrVal.size(), *this);
00292 
00293   EnterSourceFileWithLexer(TL, nullptr);
00294 
00295   // With everything set up, lex this as a #pragma directive.
00296   HandlePragmaDirective(PragmaLoc, PIK__Pragma);
00297 
00298   // Finally, return whatever came after the pragma directive.
00299   return Lex(Tok);
00300 }
00301 
00302 /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
00303 /// is not enclosed within a string literal.
00304 void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
00305   // Remember the pragma token location.
00306   SourceLocation PragmaLoc = Tok.getLocation();
00307 
00308   // Read the '('.
00309   Lex(Tok);
00310   if (Tok.isNot(tok::l_paren)) {
00311     Diag(PragmaLoc, diag::err__Pragma_malformed);
00312     return;
00313   }
00314 
00315   // Get the tokens enclosed within the __pragma(), as well as the final ')'.
00316   SmallVector<Token, 32> PragmaToks;
00317   int NumParens = 0;
00318   Lex(Tok);
00319   while (Tok.isNot(tok::eof)) {
00320     PragmaToks.push_back(Tok);
00321     if (Tok.is(tok::l_paren))
00322       NumParens++;
00323     else if (Tok.is(tok::r_paren) && NumParens-- == 0)
00324       break;
00325     Lex(Tok);
00326   }
00327 
00328   if (Tok.is(tok::eof)) {
00329     Diag(PragmaLoc, diag::err_unterminated___pragma);
00330     return;
00331   }
00332 
00333   PragmaToks.front().setFlag(Token::LeadingSpace);
00334 
00335   // Replace the ')' with an EOD to mark the end of the pragma.
00336   PragmaToks.back().setKind(tok::eod);
00337 
00338   Token *TokArray = new Token[PragmaToks.size()];
00339   std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
00340 
00341   // Push the tokens onto the stack.
00342   EnterTokenStream(TokArray, PragmaToks.size(), true, true);
00343 
00344   // With everything set up, lex this as a #pragma directive.
00345   HandlePragmaDirective(PragmaLoc, PIK___pragma);
00346 
00347   // Finally, return whatever came after the pragma directive.
00348   return Lex(Tok);
00349 }
00350 
00351 /// HandlePragmaOnce - Handle \#pragma once.  OnceTok is the 'once'.
00352 ///
00353 void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
00354   if (isInPrimaryFile()) {
00355     Diag(OnceTok, diag::pp_pragma_once_in_main_file);
00356     return;
00357   }
00358 
00359   // Get the current file lexer we're looking at.  Ignore _Pragma 'files' etc.
00360   // Mark the file as a once-only file now.
00361   HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
00362 }
00363 
00364 void Preprocessor::HandlePragmaMark() {
00365   assert(CurPPLexer && "No current lexer?");
00366   if (CurLexer)
00367     CurLexer->ReadToEndOfLine();
00368   else
00369     CurPTHLexer->DiscardToEndOfLine();
00370 }
00371 
00372 
00373 /// HandlePragmaPoison - Handle \#pragma GCC poison.  PoisonTok is the 'poison'.
00374 ///
00375 void Preprocessor::HandlePragmaPoison(Token &PoisonTok) {
00376   Token Tok;
00377 
00378   while (1) {
00379     // Read the next token to poison.  While doing this, pretend that we are
00380     // skipping while reading the identifier to poison.
00381     // This avoids errors on code like:
00382     //   #pragma GCC poison X
00383     //   #pragma GCC poison X
00384     if (CurPPLexer) CurPPLexer->LexingRawMode = true;
00385     LexUnexpandedToken(Tok);
00386     if (CurPPLexer) CurPPLexer->LexingRawMode = false;
00387 
00388     // If we reached the end of line, we're done.
00389     if (Tok.is(tok::eod)) return;
00390 
00391     // Can only poison identifiers.
00392     if (Tok.isNot(tok::raw_identifier)) {
00393       Diag(Tok, diag::err_pp_invalid_poison);
00394       return;
00395     }
00396 
00397     // Look up the identifier info for the token.  We disabled identifier lookup
00398     // by saying we're skipping contents, so we need to do this manually.
00399     IdentifierInfo *II = LookUpIdentifierInfo(Tok);
00400 
00401     // Already poisoned.
00402     if (II->isPoisoned()) continue;
00403 
00404     // If this is a macro identifier, emit a warning.
00405     if (II->hasMacroDefinition())
00406       Diag(Tok, diag::pp_poisoning_existing_macro);
00407 
00408     // Finally, poison it!
00409     II->setIsPoisoned();
00410     if (II->isFromAST())
00411       II->setChangedSinceDeserialization();
00412   }
00413 }
00414 
00415 /// HandlePragmaSystemHeader - Implement \#pragma GCC system_header.  We know
00416 /// that the whole directive has been parsed.
00417 void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
00418   if (isInPrimaryFile()) {
00419     Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
00420     return;
00421   }
00422 
00423   // Get the current file lexer we're looking at.  Ignore _Pragma 'files' etc.
00424   PreprocessorLexer *TheLexer = getCurrentFileLexer();
00425 
00426   // Mark the file as a system header.
00427   HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
00428 
00429 
00430   PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
00431   if (PLoc.isInvalid())
00432     return;
00433   
00434   unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
00435 
00436   // Notify the client, if desired, that we are in a new source file.
00437   if (Callbacks)
00438     Callbacks->FileChanged(SysHeaderTok.getLocation(),
00439                            PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
00440 
00441   // Emit a line marker.  This will change any source locations from this point
00442   // forward to realize they are in a system header.
00443   // Create a line note with this information.
00444   SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine()+1,
00445                         FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
00446                         /*IsSystem=*/true, /*IsExternC=*/false);
00447 }
00448 
00449 /// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
00450 ///
00451 void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
00452   Token FilenameTok;
00453   CurPPLexer->LexIncludeFilename(FilenameTok);
00454 
00455   // If the token kind is EOD, the error has already been diagnosed.
00456   if (FilenameTok.is(tok::eod))
00457     return;
00458 
00459   // Reserve a buffer to get the spelling.
00460   SmallString<128> FilenameBuffer;
00461   bool Invalid = false;
00462   StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
00463   if (Invalid)
00464     return;
00465 
00466   bool isAngled =
00467     GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
00468   // If GetIncludeFilenameSpelling set the start ptr to null, there was an
00469   // error.
00470   if (Filename.empty())
00471     return;
00472 
00473   // Search include directories for this file.
00474   const DirectoryLookup *CurDir;
00475   const FileEntry *File =
00476       LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
00477                  nullptr, CurDir, nullptr, nullptr, nullptr);
00478   if (!File) {
00479     if (!SuppressIncludeNotFoundError)
00480       Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
00481     return;
00482   }
00483 
00484   const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
00485 
00486   // If this file is older than the file it depends on, emit a diagnostic.
00487   if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
00488     // Lex tokens at the end of the message and include them in the message.
00489     std::string Message;
00490     Lex(DependencyTok);
00491     while (DependencyTok.isNot(tok::eod)) {
00492       Message += getSpelling(DependencyTok) + " ";
00493       Lex(DependencyTok);
00494     }
00495 
00496     // Remove the trailing ' ' if present.
00497     if (!Message.empty())
00498       Message.erase(Message.end()-1);
00499     Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
00500   }
00501 }
00502 
00503 /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
00504 /// Return the IdentifierInfo* associated with the macro to push or pop.
00505 IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
00506   // Remember the pragma token location.
00507   Token PragmaTok = Tok;
00508 
00509   // Read the '('.
00510   Lex(Tok);
00511   if (Tok.isNot(tok::l_paren)) {
00512     Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
00513       << getSpelling(PragmaTok);
00514     return nullptr;
00515   }
00516 
00517   // Read the macro name string.
00518   Lex(Tok);
00519   if (Tok.isNot(tok::string_literal)) {
00520     Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
00521       << getSpelling(PragmaTok);
00522     return nullptr;
00523   }
00524 
00525   if (Tok.hasUDSuffix()) {
00526     Diag(Tok, diag::err_invalid_string_udl);
00527     return nullptr;
00528   }
00529 
00530   // Remember the macro string.
00531   std::string StrVal = getSpelling(Tok);
00532 
00533   // Read the ')'.
00534   Lex(Tok);
00535   if (Tok.isNot(tok::r_paren)) {
00536     Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
00537       << getSpelling(PragmaTok);
00538     return nullptr;
00539   }
00540 
00541   assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
00542          "Invalid string token!");
00543 
00544   // Create a Token from the string.
00545   Token MacroTok;
00546   MacroTok.startToken();
00547   MacroTok.setKind(tok::raw_identifier);
00548   CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
00549 
00550   // Get the IdentifierInfo of MacroToPushTok.
00551   return LookUpIdentifierInfo(MacroTok);
00552 }
00553 
00554 /// \brief Handle \#pragma push_macro.
00555 ///
00556 /// The syntax is:
00557 /// \code
00558 ///   #pragma push_macro("macro")
00559 /// \endcode
00560 void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
00561   // Parse the pragma directive and get the macro IdentifierInfo*.
00562   IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
00563   if (!IdentInfo) return;
00564 
00565   // Get the MacroInfo associated with IdentInfo.
00566   MacroInfo *MI = getMacroInfo(IdentInfo);
00567  
00568   if (MI) {
00569     // Allow the original MacroInfo to be redefined later.
00570     MI->setIsAllowRedefinitionsWithoutWarning(true);
00571   }
00572 
00573   // Push the cloned MacroInfo so we can retrieve it later.
00574   PragmaPushMacroInfo[IdentInfo].push_back(MI);
00575 }
00576 
00577 /// \brief Handle \#pragma pop_macro.
00578 ///
00579 /// The syntax is:
00580 /// \code
00581 ///   #pragma pop_macro("macro")
00582 /// \endcode
00583 void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
00584   SourceLocation MessageLoc = PopMacroTok.getLocation();
00585 
00586   // Parse the pragma directive and get the macro IdentifierInfo*.
00587   IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
00588   if (!IdentInfo) return;
00589 
00590   // Find the vector<MacroInfo*> associated with the macro.
00591   llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
00592     PragmaPushMacroInfo.find(IdentInfo);
00593   if (iter != PragmaPushMacroInfo.end()) {
00594     // Forget the MacroInfo currently associated with IdentInfo.
00595     if (MacroDirective *CurrentMD = getMacroDirective(IdentInfo)) {
00596       MacroInfo *MI = CurrentMD->getMacroInfo();
00597       if (MI->isWarnIfUnused())
00598         WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
00599       appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
00600     }
00601 
00602     // Get the MacroInfo we want to reinstall.
00603     MacroInfo *MacroToReInstall = iter->second.back();
00604 
00605     if (MacroToReInstall) {
00606       // Reinstall the previously pushed macro.
00607       appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc,
00608                               /*isImported=*/false, /*Overrides*/None);
00609     }
00610 
00611     // Pop PragmaPushMacroInfo stack.
00612     iter->second.pop_back();
00613     if (iter->second.size() == 0)
00614       PragmaPushMacroInfo.erase(iter);
00615   } else {
00616     Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
00617       << IdentInfo->getName();
00618   }
00619 }
00620 
00621 void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
00622   // We will either get a quoted filename or a bracketed filename, and we 
00623   // have to track which we got.  The first filename is the source name,
00624   // and the second name is the mapped filename.  If the first is quoted,
00625   // the second must be as well (cannot mix and match quotes and brackets).
00626 
00627   // Get the open paren
00628   Lex(Tok);
00629   if (Tok.isNot(tok::l_paren)) {
00630     Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
00631     return;
00632   }
00633 
00634   // We expect either a quoted string literal, or a bracketed name
00635   Token SourceFilenameTok;
00636   CurPPLexer->LexIncludeFilename(SourceFilenameTok);
00637   if (SourceFilenameTok.is(tok::eod)) {
00638     // The diagnostic has already been handled
00639     return;
00640   }
00641 
00642   StringRef SourceFileName;
00643   SmallString<128> FileNameBuffer;
00644   if (SourceFilenameTok.is(tok::string_literal) || 
00645       SourceFilenameTok.is(tok::angle_string_literal)) {
00646     SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
00647   } else if (SourceFilenameTok.is(tok::less)) {
00648     // This could be a path instead of just a name
00649     FileNameBuffer.push_back('<');
00650     SourceLocation End;
00651     if (ConcatenateIncludeName(FileNameBuffer, End))
00652       return; // Diagnostic already emitted
00653     SourceFileName = FileNameBuffer.str();
00654   } else {
00655     Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
00656     return;
00657   }
00658   FileNameBuffer.clear();
00659 
00660   // Now we expect a comma, followed by another include name
00661   Lex(Tok);
00662   if (Tok.isNot(tok::comma)) {
00663     Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
00664     return;
00665   }
00666 
00667   Token ReplaceFilenameTok;
00668   CurPPLexer->LexIncludeFilename(ReplaceFilenameTok);
00669   if (ReplaceFilenameTok.is(tok::eod)) {
00670     // The diagnostic has already been handled
00671     return;
00672   }
00673 
00674   StringRef ReplaceFileName;
00675   if (ReplaceFilenameTok.is(tok::string_literal) || 
00676       ReplaceFilenameTok.is(tok::angle_string_literal)) {
00677     ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
00678   } else if (ReplaceFilenameTok.is(tok::less)) {
00679     // This could be a path instead of just a name
00680     FileNameBuffer.push_back('<');
00681     SourceLocation End;
00682     if (ConcatenateIncludeName(FileNameBuffer, End))
00683       return; // Diagnostic already emitted
00684     ReplaceFileName = FileNameBuffer.str();
00685   } else {
00686     Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
00687     return;
00688   }
00689 
00690   // Finally, we expect the closing paren
00691   Lex(Tok);
00692   if (Tok.isNot(tok::r_paren)) {
00693     Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
00694     return;
00695   }
00696 
00697   // Now that we have the source and target filenames, we need to make sure
00698   // they're both of the same type (angled vs non-angled)
00699   StringRef OriginalSource = SourceFileName;
00700 
00701   bool SourceIsAngled = 
00702     GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(), 
00703                                 SourceFileName);
00704   bool ReplaceIsAngled =
00705     GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
00706                                 ReplaceFileName);
00707   if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
00708       (SourceIsAngled != ReplaceIsAngled)) {
00709     unsigned int DiagID;
00710     if (SourceIsAngled)
00711       DiagID = diag::warn_pragma_include_alias_mismatch_angle;
00712     else
00713       DiagID = diag::warn_pragma_include_alias_mismatch_quote;
00714 
00715     Diag(SourceFilenameTok.getLocation(), DiagID)
00716       << SourceFileName 
00717       << ReplaceFileName;
00718 
00719     return;
00720   }
00721 
00722   // Now we can let the include handler know about this mapping
00723   getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
00724 }
00725 
00726 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
00727 /// If 'Namespace' is non-null, then it is a token required to exist on the
00728 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
00729 void Preprocessor::AddPragmaHandler(StringRef Namespace,
00730                                     PragmaHandler *Handler) {
00731   PragmaNamespace *InsertNS = PragmaHandlers.get();
00732 
00733   // If this is specified to be in a namespace, step down into it.
00734   if (!Namespace.empty()) {
00735     // If there is already a pragma handler with the name of this namespace,
00736     // we either have an error (directive with the same name as a namespace) or
00737     // we already have the namespace to insert into.
00738     if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
00739       InsertNS = Existing->getIfNamespace();
00740       assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
00741              " handler with the same name!");
00742     } else {
00743       // Otherwise, this namespace doesn't exist yet, create and insert the
00744       // handler for it.
00745       InsertNS = new PragmaNamespace(Namespace);
00746       PragmaHandlers->AddPragma(InsertNS);
00747     }
00748   }
00749 
00750   // Check to make sure we don't already have a pragma for this identifier.
00751   assert(!InsertNS->FindHandler(Handler->getName()) &&
00752          "Pragma handler already exists for this identifier!");
00753   InsertNS->AddPragma(Handler);
00754 }
00755 
00756 /// RemovePragmaHandler - Remove the specific pragma handler from the
00757 /// preprocessor. If \arg Namespace is non-null, then it should be the
00758 /// namespace that \arg Handler was added to. It is an error to remove
00759 /// a handler that has not been registered.
00760 void Preprocessor::RemovePragmaHandler(StringRef Namespace,
00761                                        PragmaHandler *Handler) {
00762   PragmaNamespace *NS = PragmaHandlers.get();
00763 
00764   // If this is specified to be in a namespace, step down into it.
00765   if (!Namespace.empty()) {
00766     PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
00767     assert(Existing && "Namespace containing handler does not exist!");
00768 
00769     NS = Existing->getIfNamespace();
00770     assert(NS && "Invalid namespace, registered as a regular pragma handler!");
00771   }
00772 
00773   NS->RemovePragmaHandler(Handler);
00774 
00775   // If this is a non-default namespace and it is now empty, remove it.
00776   if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
00777     PragmaHandlers->RemovePragmaHandler(NS);
00778     delete NS;
00779   }
00780 }
00781 
00782 bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
00783   Token Tok;
00784   LexUnexpandedToken(Tok);
00785 
00786   if (Tok.isNot(tok::identifier)) {
00787     Diag(Tok, diag::ext_on_off_switch_syntax);
00788     return true;
00789   }
00790   IdentifierInfo *II = Tok.getIdentifierInfo();
00791   if (II->isStr("ON"))
00792     Result = tok::OOS_ON;
00793   else if (II->isStr("OFF"))
00794     Result = tok::OOS_OFF;
00795   else if (II->isStr("DEFAULT"))
00796     Result = tok::OOS_DEFAULT;
00797   else {
00798     Diag(Tok, diag::ext_on_off_switch_syntax);
00799     return true;
00800   }
00801 
00802   // Verify that this is followed by EOD.
00803   LexUnexpandedToken(Tok);
00804   if (Tok.isNot(tok::eod))
00805     Diag(Tok, diag::ext_pragma_syntax_eod);
00806   return false;
00807 }
00808 
00809 namespace {
00810 /// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
00811 struct PragmaOnceHandler : public PragmaHandler {
00812   PragmaOnceHandler() : PragmaHandler("once") {}
00813   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
00814                     Token &OnceTok) override {
00815     PP.CheckEndOfDirective("pragma once");
00816     PP.HandlePragmaOnce(OnceTok);
00817   }
00818 };
00819 
00820 /// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
00821 /// rest of the line is not lexed.
00822 struct PragmaMarkHandler : public PragmaHandler {
00823   PragmaMarkHandler() : PragmaHandler("mark") {}
00824   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
00825                     Token &MarkTok) override {
00826     PP.HandlePragmaMark();
00827   }
00828 };
00829 
00830 /// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
00831 struct PragmaPoisonHandler : public PragmaHandler {
00832   PragmaPoisonHandler() : PragmaHandler("poison") {}
00833   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
00834                     Token &PoisonTok) override {
00835     PP.HandlePragmaPoison(PoisonTok);
00836   }
00837 };
00838 
00839 /// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
00840 /// as a system header, which silences warnings in it.
00841 struct PragmaSystemHeaderHandler : public PragmaHandler {
00842   PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
00843   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
00844                     Token &SHToken) override {
00845     PP.HandlePragmaSystemHeader(SHToken);
00846     PP.CheckEndOfDirective("pragma");
00847   }
00848 };
00849 struct PragmaDependencyHandler : public PragmaHandler {
00850   PragmaDependencyHandler() : PragmaHandler("dependency") {}
00851   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
00852                     Token &DepToken) override {
00853     PP.HandlePragmaDependency(DepToken);
00854   }
00855 };
00856 
00857 struct PragmaDebugHandler : public PragmaHandler {
00858   PragmaDebugHandler() : PragmaHandler("__debug") {}
00859   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
00860                     Token &DepToken) override {
00861     Token Tok;
00862     PP.LexUnexpandedToken(Tok);
00863     if (Tok.isNot(tok::identifier)) {
00864       PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
00865       return;
00866     }
00867     IdentifierInfo *II = Tok.getIdentifierInfo();
00868 
00869     if (II->isStr("assert")) {
00870       llvm_unreachable("This is an assertion!");
00871     } else if (II->isStr("crash")) {
00872       LLVM_BUILTIN_TRAP;
00873     } else if (II->isStr("parser_crash")) {
00874       Token Crasher;
00875       Crasher.setKind(tok::annot_pragma_parser_crash);
00876       PP.EnterToken(Crasher);
00877     } else if (II->isStr("llvm_fatal_error")) {
00878       llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
00879     } else if (II->isStr("llvm_unreachable")) {
00880       llvm_unreachable("#pragma clang __debug llvm_unreachable");
00881     } else if (II->isStr("overflow_stack")) {
00882       DebugOverflowStack();
00883     } else if (II->isStr("handle_crash")) {
00884       llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
00885       if (CRC)
00886         CRC->HandleCrash();
00887     } else if (II->isStr("captured")) {
00888       HandleCaptured(PP);
00889     } else {
00890       PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
00891         << II->getName();
00892     }
00893 
00894     PPCallbacks *Callbacks = PP.getPPCallbacks();
00895     if (Callbacks)
00896       Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
00897   }
00898 
00899   void HandleCaptured(Preprocessor &PP) {
00900     // Skip if emitting preprocessed output.
00901     if (PP.isPreprocessedOutput())
00902       return;
00903 
00904     Token Tok;
00905     PP.LexUnexpandedToken(Tok);
00906 
00907     if (Tok.isNot(tok::eod)) {
00908       PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
00909         << "pragma clang __debug captured";
00910       return;
00911     }
00912 
00913     SourceLocation NameLoc = Tok.getLocation();
00914     Token *Toks = PP.getPreprocessorAllocator().Allocate<Token>(1);
00915     Toks->startToken();
00916     Toks->setKind(tok::annot_pragma_captured);
00917     Toks->setLocation(NameLoc);
00918 
00919     PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true,
00920                         /*OwnsTokens=*/false);
00921   }
00922 
00923 // Disable MSVC warning about runtime stack overflow.
00924 #ifdef _MSC_VER
00925     #pragma warning(disable : 4717)
00926 #endif
00927   static void DebugOverflowStack() {
00928     void (*volatile Self)() = DebugOverflowStack;
00929     Self();
00930   }
00931 #ifdef _MSC_VER
00932     #pragma warning(default : 4717)
00933 #endif
00934 
00935 };
00936 
00937 /// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
00938 struct PragmaDiagnosticHandler : public PragmaHandler {
00939 private:
00940   const char *Namespace;
00941 public:
00942   explicit PragmaDiagnosticHandler(const char *NS) :
00943     PragmaHandler("diagnostic"), Namespace(NS) {}
00944   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
00945                     Token &DiagToken) override {
00946     SourceLocation DiagLoc = DiagToken.getLocation();
00947     Token Tok;
00948     PP.LexUnexpandedToken(Tok);
00949     if (Tok.isNot(tok::identifier)) {
00950       PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
00951       return;
00952     }
00953     IdentifierInfo *II = Tok.getIdentifierInfo();
00954     PPCallbacks *Callbacks = PP.getPPCallbacks();
00955 
00956     if (II->isStr("pop")) {
00957       if (!PP.getDiagnostics().popMappings(DiagLoc))
00958         PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
00959       else if (Callbacks)
00960         Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
00961       return;
00962     } else if (II->isStr("push")) {
00963       PP.getDiagnostics().pushMappings(DiagLoc);
00964       if (Callbacks)
00965         Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
00966       return;
00967     }
00968 
00969     diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
00970                             .Case("ignored", diag::Severity::Ignored)
00971                             .Case("warning", diag::Severity::Warning)
00972                             .Case("error", diag::Severity::Error)
00973                             .Case("fatal", diag::Severity::Fatal)
00974                             .Default(diag::Severity());
00975 
00976     if (SV == diag::Severity()) {
00977       PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
00978       return;
00979     }
00980 
00981     PP.LexUnexpandedToken(Tok);
00982     SourceLocation StringLoc = Tok.getLocation();
00983 
00984     std::string WarningName;
00985     if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
00986                                    /*MacroExpansion=*/false))
00987       return;
00988 
00989     if (Tok.isNot(tok::eod)) {
00990       PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
00991       return;
00992     }
00993 
00994     if (WarningName.size() < 3 || WarningName[0] != '-' ||
00995         (WarningName[1] != 'W' && WarningName[1] != 'R')) {
00996       PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
00997       return;
00998     }
00999 
01000     if (PP.getDiagnostics().setSeverityForGroup(
01001             WarningName[1] == 'W' ? diag::Flavor::WarningOrError
01002                                   : diag::Flavor::Remark,
01003             WarningName.substr(2), SV, DiagLoc))
01004       PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
01005         << WarningName;
01006     else if (Callbacks)
01007       Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
01008   }
01009 };
01010 
01011 /// "\#pragma warning(...)".  MSVC's diagnostics do not map cleanly to clang's
01012 /// diagnostics, so we don't really implement this pragma.  We parse it and
01013 /// ignore it to avoid -Wunknown-pragma warnings.
01014 struct PragmaWarningHandler : public PragmaHandler {
01015   PragmaWarningHandler() : PragmaHandler("warning") {}
01016 
01017   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
01018                     Token &Tok) override {
01019     // Parse things like:
01020     // warning(push, 1)
01021     // warning(pop)
01022     // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
01023     SourceLocation DiagLoc = Tok.getLocation();
01024     PPCallbacks *Callbacks = PP.getPPCallbacks();
01025 
01026     PP.Lex(Tok);
01027     if (Tok.isNot(tok::l_paren)) {
01028       PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
01029       return;
01030     }
01031 
01032     PP.Lex(Tok);
01033     IdentifierInfo *II = Tok.getIdentifierInfo();
01034     if (!II) {
01035       PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
01036       return;
01037     }
01038 
01039     if (II->isStr("push")) {
01040       // #pragma warning( push[ ,n ] )
01041       int Level = -1;
01042       PP.Lex(Tok);
01043       if (Tok.is(tok::comma)) {
01044         PP.Lex(Tok);
01045         uint64_t Value;
01046         if (Tok.is(tok::numeric_constant) &&
01047             PP.parseSimpleIntegerLiteral(Tok, Value))
01048           Level = int(Value);
01049         if (Level < 0 || Level > 4) {
01050           PP.Diag(Tok, diag::warn_pragma_warning_push_level);
01051           return;
01052         }
01053       }
01054       if (Callbacks)
01055         Callbacks->PragmaWarningPush(DiagLoc, Level);
01056     } else if (II->isStr("pop")) {
01057       // #pragma warning( pop )
01058       PP.Lex(Tok);
01059       if (Callbacks)
01060         Callbacks->PragmaWarningPop(DiagLoc);
01061     } else {
01062       // #pragma warning( warning-specifier : warning-number-list
01063       //                  [; warning-specifier : warning-number-list...] )
01064       while (true) {
01065         II = Tok.getIdentifierInfo();
01066         if (!II) {
01067           PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
01068           return;
01069         }
01070 
01071         // Figure out which warning specifier this is.
01072         StringRef Specifier = II->getName();
01073         bool SpecifierValid =
01074             llvm::StringSwitch<bool>(Specifier)
01075                 .Cases("1", "2", "3", "4", true)
01076                 .Cases("default", "disable", "error", "once", "suppress", true)
01077                 .Default(false);
01078         if (!SpecifierValid) {
01079           PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
01080           return;
01081         }
01082         PP.Lex(Tok);
01083         if (Tok.isNot(tok::colon)) {
01084           PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
01085           return;
01086         }
01087 
01088         // Collect the warning ids.
01089         SmallVector<int, 4> Ids;
01090         PP.Lex(Tok);
01091         while (Tok.is(tok::numeric_constant)) {
01092           uint64_t Value;
01093           if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
01094               Value > INT_MAX) {
01095             PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
01096             return;
01097           }
01098           Ids.push_back(int(Value));
01099         }
01100         if (Callbacks)
01101           Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
01102 
01103         // Parse the next specifier if there is a semicolon.
01104         if (Tok.isNot(tok::semi))
01105           break;
01106         PP.Lex(Tok);
01107       }
01108     }
01109 
01110     if (Tok.isNot(tok::r_paren)) {
01111       PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
01112       return;
01113     }
01114 
01115     PP.Lex(Tok);
01116     if (Tok.isNot(tok::eod))
01117       PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
01118   }
01119 };
01120 
01121 /// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
01122 struct PragmaIncludeAliasHandler : public PragmaHandler {
01123   PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
01124   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
01125                     Token &IncludeAliasTok) override {
01126     PP.HandlePragmaIncludeAlias(IncludeAliasTok);
01127   }
01128 };
01129 
01130 /// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
01131 /// extension.  The syntax is:
01132 /// \code
01133 ///   #pragma message(string)
01134 /// \endcode
01135 /// OR, in GCC mode:
01136 /// \code
01137 ///   #pragma message string
01138 /// \endcode
01139 /// string is a string, which is fully macro expanded, and permits string
01140 /// concatenation, embedded escape characters, etc... See MSDN for more details.
01141 /// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
01142 /// form as \#pragma message.
01143 struct PragmaMessageHandler : public PragmaHandler {
01144 private:
01145   const PPCallbacks::PragmaMessageKind Kind;
01146   const StringRef Namespace;
01147 
01148   static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
01149                                 bool PragmaNameOnly = false) {
01150     switch (Kind) {
01151       case PPCallbacks::PMK_Message:
01152         return PragmaNameOnly ? "message" : "pragma message";
01153       case PPCallbacks::PMK_Warning:
01154         return PragmaNameOnly ? "warning" : "pragma warning";
01155       case PPCallbacks::PMK_Error:
01156         return PragmaNameOnly ? "error" : "pragma error";
01157     }
01158     llvm_unreachable("Unknown PragmaMessageKind!");
01159   }
01160 
01161 public:
01162   PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
01163                        StringRef Namespace = StringRef())
01164     : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), Namespace(Namespace) {}
01165 
01166   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
01167                     Token &Tok) override {
01168     SourceLocation MessageLoc = Tok.getLocation();
01169     PP.Lex(Tok);
01170     bool ExpectClosingParen = false;
01171     switch (Tok.getKind()) {
01172     case tok::l_paren:
01173       // We have a MSVC style pragma message.
01174       ExpectClosingParen = true;
01175       // Read the string.
01176       PP.Lex(Tok);
01177       break;
01178     case tok::string_literal:
01179       // We have a GCC style pragma message, and we just read the string.
01180       break;
01181     default:
01182       PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
01183       return;
01184     }
01185 
01186     std::string MessageString;
01187     if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
01188                                    /*MacroExpansion=*/true))
01189       return;
01190 
01191     if (ExpectClosingParen) {
01192       if (Tok.isNot(tok::r_paren)) {
01193         PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
01194         return;
01195       }
01196       PP.Lex(Tok);  // eat the r_paren.
01197     }
01198 
01199     if (Tok.isNot(tok::eod)) {
01200       PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
01201       return;
01202     }
01203 
01204     // Output the message.
01205     PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
01206                           ? diag::err_pragma_message
01207                           : diag::warn_pragma_message) << MessageString;
01208 
01209     // If the pragma is lexically sound, notify any interested PPCallbacks.
01210     if (PPCallbacks *Callbacks = PP.getPPCallbacks())
01211       Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
01212   }
01213 };
01214 
01215 /// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
01216 /// macro on the top of the stack.
01217 struct PragmaPushMacroHandler : public PragmaHandler {
01218   PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
01219   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
01220                     Token &PushMacroTok) override {
01221     PP.HandlePragmaPushMacro(PushMacroTok);
01222   }
01223 };
01224 
01225 
01226 /// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
01227 /// macro to the value on the top of the stack.
01228 struct PragmaPopMacroHandler : public PragmaHandler {
01229   PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
01230   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
01231                     Token &PopMacroTok) override {
01232     PP.HandlePragmaPopMacro(PopMacroTok);
01233   }
01234 };
01235 
01236 // Pragma STDC implementations.
01237 
01238 /// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
01239 struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
01240   PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
01241   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
01242                     Token &Tok) override {
01243     tok::OnOffSwitch OOS;
01244     if (PP.LexOnOffSwitch(OOS))
01245      return;
01246     if (OOS == tok::OOS_ON)
01247       PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
01248   }
01249 };
01250 
01251 /// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
01252 struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
01253   PragmaSTDC_CX_LIMITED_RANGEHandler()
01254     : PragmaHandler("CX_LIMITED_RANGE") {}
01255   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
01256                     Token &Tok) override {
01257     tok::OnOffSwitch OOS;
01258     PP.LexOnOffSwitch(OOS);
01259   }
01260 };
01261 
01262 /// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
01263 struct PragmaSTDC_UnknownHandler : public PragmaHandler {
01264   PragmaSTDC_UnknownHandler() {}
01265   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
01266                     Token &UnknownTok) override {
01267     // C99 6.10.6p2, unknown forms are not allowed.
01268     PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
01269   }
01270 };
01271 
01272 /// PragmaARCCFCodeAuditedHandler - 
01273 ///   \#pragma clang arc_cf_code_audited begin/end
01274 struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
01275   PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
01276   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
01277                     Token &NameTok) override {
01278     SourceLocation Loc = NameTok.getLocation();
01279     bool IsBegin;
01280 
01281     Token Tok;
01282 
01283     // Lex the 'begin' or 'end'.
01284     PP.LexUnexpandedToken(Tok);
01285     const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
01286     if (BeginEnd && BeginEnd->isStr("begin")) {
01287       IsBegin = true;
01288     } else if (BeginEnd && BeginEnd->isStr("end")) {
01289       IsBegin = false;
01290     } else {
01291       PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
01292       return;
01293     }
01294 
01295     // Verify that this is followed by EOD.
01296     PP.LexUnexpandedToken(Tok);
01297     if (Tok.isNot(tok::eod))
01298       PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
01299 
01300     // The start location of the active audit.
01301     SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
01302 
01303     // The start location we want after processing this.
01304     SourceLocation NewLoc;
01305 
01306     if (IsBegin) {
01307       // Complain about attempts to re-enter an audit.
01308       if (BeginLoc.isValid()) {
01309         PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
01310         PP.Diag(BeginLoc, diag::note_pragma_entered_here);
01311       }
01312       NewLoc = Loc;
01313     } else {
01314       // Complain about attempts to leave an audit that doesn't exist.
01315       if (!BeginLoc.isValid()) {
01316         PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
01317         return;
01318       }
01319       NewLoc = SourceLocation();
01320     }
01321 
01322     PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
01323   }
01324 };
01325 
01326 /// \brief Handle "\#pragma region [...]"
01327 ///
01328 /// The syntax is
01329 /// \code
01330 ///   #pragma region [optional name]
01331 ///   #pragma endregion [optional comment]
01332 /// \endcode
01333 ///
01334 /// \note This is
01335 /// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
01336 /// pragma, just skipped by compiler.
01337 struct PragmaRegionHandler : public PragmaHandler {
01338   PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) { }
01339 
01340   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
01341                     Token &NameTok) override {
01342     // #pragma region: endregion matches can be verified
01343     // __pragma(region): no sense, but ignored by msvc
01344     // _Pragma is not valid for MSVC, but there isn't any point
01345     // to handle a _Pragma differently.
01346   }
01347 };
01348 
01349 }  // end anonymous namespace
01350 
01351 
01352 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
01353 /// \#pragma GCC poison/system_header/dependency and \#pragma once.
01354 void Preprocessor::RegisterBuiltinPragmas() {
01355   AddPragmaHandler(new PragmaOnceHandler());
01356   AddPragmaHandler(new PragmaMarkHandler());
01357   AddPragmaHandler(new PragmaPushMacroHandler());
01358   AddPragmaHandler(new PragmaPopMacroHandler());
01359   AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
01360 
01361   // #pragma GCC ...
01362   AddPragmaHandler("GCC", new PragmaPoisonHandler());
01363   AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
01364   AddPragmaHandler("GCC", new PragmaDependencyHandler());
01365   AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
01366   AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
01367                                                    "GCC"));
01368   AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
01369                                                    "GCC"));
01370   // #pragma clang ...
01371   AddPragmaHandler("clang", new PragmaPoisonHandler());
01372   AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
01373   AddPragmaHandler("clang", new PragmaDebugHandler());
01374   AddPragmaHandler("clang", new PragmaDependencyHandler());
01375   AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
01376   AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
01377 
01378   AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
01379   AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
01380   AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
01381 
01382   // MS extensions.
01383   if (LangOpts.MicrosoftExt) {
01384     AddPragmaHandler(new PragmaWarningHandler());
01385     AddPragmaHandler(new PragmaIncludeAliasHandler());
01386     AddPragmaHandler(new PragmaRegionHandler("region"));
01387     AddPragmaHandler(new PragmaRegionHandler("endregion"));
01388   }
01389 }
01390 
01391 /// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
01392 /// warn about those pragmas being unknown.
01393 void Preprocessor::IgnorePragmas() {
01394   AddPragmaHandler(new EmptyPragmaHandler());
01395   // Also ignore all pragmas in all namespaces created
01396   // in Preprocessor::RegisterBuiltinPragmas().
01397   AddPragmaHandler("GCC", new EmptyPragmaHandler());
01398   AddPragmaHandler("clang", new EmptyPragmaHandler());
01399   if (PragmaHandler *NS = PragmaHandlers->FindHandler("STDC")) {
01400     // Preprocessor::RegisterBuiltinPragmas() already registers
01401     // PragmaSTDC_UnknownHandler as the empty handler, so remove it first,
01402     // otherwise there will be an assert about a duplicate handler.
01403     PragmaNamespace *STDCNamespace = NS->getIfNamespace();
01404     assert(STDCNamespace &&
01405            "Invalid namespace, registered as a regular pragma handler!");
01406     if (PragmaHandler *Existing = STDCNamespace->FindHandler("", false)) {
01407       RemovePragmaHandler("STDC", Existing);
01408       delete Existing;
01409     }
01410   }
01411   AddPragmaHandler("STDC", new EmptyPragmaHandler());
01412 }