Home | History | Annotate | Download | only in Lex
      1 //===--- Pragma.cpp - Pragma registration and handling --------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements the PragmaHandler/PragmaTable interfaces and implements
     11 // pragma related methods of the Preprocessor class.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     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/ADT/STLExtras.h"
     24 #include "llvm/ADT/StringSwitch.h"
     25 #include "llvm/Support/CrashRecoveryContext.h"
     26 #include "llvm/Support/ErrorHandling.h"
     27 #include <algorithm>
     28 using namespace clang;
     29 
     30 #include "llvm/Support/raw_ostream.h"
     31 
     32 // Out-of-line destructor to provide a home for the class.
     33 PragmaHandler::~PragmaHandler() {
     34 }
     35 
     36 //===----------------------------------------------------------------------===//
     37 // EmptyPragmaHandler Implementation.
     38 //===----------------------------------------------------------------------===//
     39 
     40 EmptyPragmaHandler::EmptyPragmaHandler() {}
     41 
     42 void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
     43                                       PragmaIntroducerKind Introducer,
     44                                       Token &FirstToken) {}
     45 
     46 //===----------------------------------------------------------------------===//
     47 // PragmaNamespace Implementation.
     48 //===----------------------------------------------------------------------===//
     49 
     50 PragmaNamespace::~PragmaNamespace() {
     51   llvm::DeleteContainerSeconds(Handlers);
     52 }
     53 
     54 /// FindHandler - Check to see if there is already a handler for the
     55 /// specified name.  If not, return the handler for the null identifier if it
     56 /// exists, otherwise return null.  If IgnoreNull is true (the default) then
     57 /// the null handler isn't returned on failure to match.
     58 PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
     59                                             bool IgnoreNull) const {
     60   if (PragmaHandler *Handler = Handlers.lookup(Name))
     61     return Handler;
     62   return IgnoreNull ? nullptr : Handlers.lookup(StringRef());
     63 }
     64 
     65 void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
     66   assert(!Handlers.lookup(Handler->getName()) &&
     67          "A handler with this name is already registered in this namespace");
     68   llvm::StringMapEntry<PragmaHandler *> &Entry =
     69     Handlers.GetOrCreateValue(Handler->getName());
     70   Entry.setValue(Handler);
     71 }
     72 
     73 void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
     74   assert(Handlers.lookup(Handler->getName()) &&
     75          "Handler not registered in this namespace");
     76   Handlers.erase(Handler->getName());
     77 }
     78 
     79 void PragmaNamespace::HandlePragma(Preprocessor &PP,
     80                                    PragmaIntroducerKind Introducer,
     81                                    Token &Tok) {
     82   // Read the 'namespace' that the directive is in, e.g. STDC.  Do not macro
     83   // expand it, the user can have a STDC #define, that should not affect this.
     84   PP.LexUnexpandedToken(Tok);
     85 
     86   // Get the handler for this token.  If there is no handler, ignore the pragma.
     87   PragmaHandler *Handler
     88     = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
     89                                           : StringRef(),
     90                   /*IgnoreNull=*/false);
     91   if (!Handler) {
     92     PP.Diag(Tok, diag::warn_pragma_ignored);
     93     return;
     94   }
     95 
     96   // Otherwise, pass it down.
     97   Handler->HandlePragma(PP, Introducer, Tok);
     98 }
     99 
    100 //===----------------------------------------------------------------------===//
    101 // Preprocessor Pragma Directive Handling.
    102 //===----------------------------------------------------------------------===//
    103 
    104 /// HandlePragmaDirective - The "\#pragma" directive has been parsed.  Lex the
    105 /// rest of the pragma, passing it to the registered pragma handlers.
    106 void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc,
    107                                          PragmaIntroducerKind Introducer) {
    108   if (Callbacks)
    109     Callbacks->PragmaDirective(IntroducerLoc, Introducer);
    110 
    111   if (!PragmasEnabled)
    112     return;
    113 
    114   ++NumPragma;
    115 
    116   // Invoke the first level of pragma handlers which reads the namespace id.
    117   Token Tok;
    118   PragmaHandlers->HandlePragma(*this, Introducer, Tok);
    119 
    120   // If the pragma handler didn't read the rest of the line, consume it now.
    121   if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
    122    || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
    123     DiscardUntilEndOfDirective();
    124 }
    125 
    126 namespace {
    127 /// \brief Helper class for \see Preprocessor::Handle_Pragma.
    128 class LexingFor_PragmaRAII {
    129   Preprocessor &PP;
    130   bool InMacroArgPreExpansion;
    131   bool Failed;
    132   Token &OutTok;
    133   Token PragmaTok;
    134 
    135 public:
    136   LexingFor_PragmaRAII(Preprocessor &PP, bool InMacroArgPreExpansion,
    137                        Token &Tok)
    138     : PP(PP), InMacroArgPreExpansion(InMacroArgPreExpansion),
    139       Failed(false), OutTok(Tok) {
    140     if (InMacroArgPreExpansion) {
    141       PragmaTok = OutTok;
    142       PP.EnableBacktrackAtThisPos();
    143     }
    144   }
    145 
    146   ~LexingFor_PragmaRAII() {
    147     if (InMacroArgPreExpansion) {
    148       if (Failed) {
    149         PP.CommitBacktrackedTokens();
    150       } else {
    151         PP.Backtrack();
    152         OutTok = PragmaTok;
    153       }
    154     }
    155   }
    156 
    157   void failed() {
    158     Failed = true;
    159   }
    160 };
    161 }
    162 
    163 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
    164 /// return the first token after the directive.  The _Pragma token has just
    165 /// been read into 'Tok'.
    166 void Preprocessor::Handle_Pragma(Token &Tok) {
    167 
    168   // This works differently if we are pre-expanding a macro argument.
    169   // In that case we don't actually "activate" the pragma now, we only lex it
    170   // until we are sure it is lexically correct and then we backtrack so that
    171   // we activate the pragma whenever we encounter the tokens again in the token
    172   // stream. This ensures that we will activate it in the correct location
    173   // or that we will ignore it if it never enters the token stream, e.g:
    174   //
    175   //     #define EMPTY(x)
    176   //     #define INACTIVE(x) EMPTY(x)
    177   //     INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\""))
    178 
    179   LexingFor_PragmaRAII _PragmaLexing(*this, InMacroArgPreExpansion, Tok);
    180 
    181   // Remember the pragma token location.
    182   SourceLocation PragmaLoc = Tok.getLocation();
    183 
    184   // Read the '('.
    185   Lex(Tok);
    186   if (Tok.isNot(tok::l_paren)) {
    187     Diag(PragmaLoc, diag::err__Pragma_malformed);
    188     return _PragmaLexing.failed();
    189   }
    190 
    191   // Read the '"..."'.
    192   Lex(Tok);
    193   if (!tok::isStringLiteral(Tok.getKind())) {
    194     Diag(PragmaLoc, diag::err__Pragma_malformed);
    195     // Skip this token, and the ')', if present.
    196     if (Tok.isNot(tok::r_paren))
    197       Lex(Tok);
    198     if (Tok.is(tok::r_paren))
    199       Lex(Tok);
    200     return _PragmaLexing.failed();
    201   }
    202 
    203   if (Tok.hasUDSuffix()) {
    204     Diag(Tok, diag::err_invalid_string_udl);
    205     // Skip this token, and the ')', if present.
    206     Lex(Tok);
    207     if (Tok.is(tok::r_paren))
    208       Lex(Tok);
    209     return _PragmaLexing.failed();
    210   }
    211 
    212   // Remember the string.
    213   Token StrTok = Tok;
    214 
    215   // Read the ')'.
    216   Lex(Tok);
    217   if (Tok.isNot(tok::r_paren)) {
    218     Diag(PragmaLoc, diag::err__Pragma_malformed);
    219     return _PragmaLexing.failed();
    220   }
    221 
    222   if (InMacroArgPreExpansion)
    223     return;
    224 
    225   SourceLocation RParenLoc = Tok.getLocation();
    226   std::string StrVal = getSpelling(StrTok);
    227 
    228   // The _Pragma is lexically sound.  Destringize according to C11 6.10.9.1:
    229   // "The string literal is destringized by deleting any encoding prefix,
    230   // deleting the leading and trailing double-quotes, replacing each escape
    231   // sequence \" by a double-quote, and replacing each escape sequence \\ by a
    232   // single backslash."
    233   if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
    234       (StrVal[0] == 'u' && StrVal[1] != '8'))
    235     StrVal.erase(StrVal.begin());
    236   else if (StrVal[0] == 'u')
    237     StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
    238 
    239   if (StrVal[0] == 'R') {
    240     // FIXME: C++11 does not specify how to handle raw-string-literals here.
    241     // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
    242     assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
    243            "Invalid raw string token!");
    244 
    245     // Measure the length of the d-char-sequence.
    246     unsigned NumDChars = 0;
    247     while (StrVal[2 + NumDChars] != '(') {
    248       assert(NumDChars < (StrVal.size() - 5) / 2 &&
    249              "Invalid raw string token!");
    250       ++NumDChars;
    251     }
    252     assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
    253 
    254     // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
    255     // parens below.
    256     StrVal.erase(0, 2 + NumDChars);
    257     StrVal.erase(StrVal.size() - 1 - NumDChars);
    258   } else {
    259     assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
    260            "Invalid string token!");
    261 
    262     // Remove escaped quotes and escapes.
    263     unsigned ResultPos = 1;
    264     for (unsigned i = 1, e = StrVal.size() - 1; i != e; ++i) {
    265       // Skip escapes.  \\ -> '\' and \" -> '"'.
    266       if (StrVal[i] == '\\' && i + 1 < e &&
    267           (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
    268         ++i;
    269       StrVal[ResultPos++] = StrVal[i];
    270     }
    271     StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
    272   }
    273 
    274   // Remove the front quote, replacing it with a space, so that the pragma
    275   // contents appear to have a space before them.
    276   StrVal[0] = ' ';
    277 
    278   // Replace the terminating quote with a \n.
    279   StrVal[StrVal.size()-1] = '\n';
    280 
    281   // Plop the string (including the newline and trailing null) into a buffer
    282   // where we can lex it.
    283   Token TmpTok;
    284   TmpTok.startToken();
    285   CreateString(StrVal, TmpTok);
    286   SourceLocation TokLoc = TmpTok.getLocation();
    287 
    288   // Make and enter a lexer object so that we lex and expand the tokens just
    289   // like any others.
    290   Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
    291                                         StrVal.size(), *this);
    292 
    293   EnterSourceFileWithLexer(TL, nullptr);
    294 
    295   // With everything set up, lex this as a #pragma directive.
    296   HandlePragmaDirective(PragmaLoc, PIK__Pragma);
    297 
    298   // Finally, return whatever came after the pragma directive.
    299   return Lex(Tok);
    300 }
    301 
    302 /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
    303 /// is not enclosed within a string literal.
    304 void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
    305   // Remember the pragma token location.
    306   SourceLocation PragmaLoc = Tok.getLocation();
    307 
    308   // Read the '('.
    309   Lex(Tok);
    310   if (Tok.isNot(tok::l_paren)) {
    311     Diag(PragmaLoc, diag::err__Pragma_malformed);
    312     return;
    313   }
    314 
    315   // Get the tokens enclosed within the __pragma(), as well as the final ')'.
    316   SmallVector<Token, 32> PragmaToks;
    317   int NumParens = 0;
    318   Lex(Tok);
    319   while (Tok.isNot(tok::eof)) {
    320     PragmaToks.push_back(Tok);
    321     if (Tok.is(tok::l_paren))
    322       NumParens++;
    323     else if (Tok.is(tok::r_paren) && NumParens-- == 0)
    324       break;
    325     Lex(Tok);
    326   }
    327 
    328   if (Tok.is(tok::eof)) {
    329     Diag(PragmaLoc, diag::err_unterminated___pragma);
    330     return;
    331   }
    332 
    333   PragmaToks.front().setFlag(Token::LeadingSpace);
    334 
    335   // Replace the ')' with an EOD to mark the end of the pragma.
    336   PragmaToks.back().setKind(tok::eod);
    337 
    338   Token *TokArray = new Token[PragmaToks.size()];
    339   std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
    340 
    341   // Push the tokens onto the stack.
    342   EnterTokenStream(TokArray, PragmaToks.size(), true, true);
    343 
    344   // With everything set up, lex this as a #pragma directive.
    345   HandlePragmaDirective(PragmaLoc, PIK___pragma);
    346 
    347   // Finally, return whatever came after the pragma directive.
    348   return Lex(Tok);
    349 }
    350 
    351 /// HandlePragmaOnce - Handle \#pragma once.  OnceTok is the 'once'.
    352 ///
    353 void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
    354   if (isInPrimaryFile()) {
    355     Diag(OnceTok, diag::pp_pragma_once_in_main_file);
    356     return;
    357   }
    358 
    359   // Get the current file lexer we're looking at.  Ignore _Pragma 'files' etc.
    360   // Mark the file as a once-only file now.
    361   HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
    362 }
    363 
    364 void Preprocessor::HandlePragmaMark() {
    365   assert(CurPPLexer && "No current lexer?");
    366   if (CurLexer)
    367     CurLexer->ReadToEndOfLine();
    368   else
    369     CurPTHLexer->DiscardToEndOfLine();
    370 }
    371 
    372 
    373 /// HandlePragmaPoison - Handle \#pragma GCC poison.  PoisonTok is the 'poison'.
    374 ///
    375 void Preprocessor::HandlePragmaPoison(Token &PoisonTok) {
    376   Token Tok;
    377 
    378   while (1) {
    379     // Read the next token to poison.  While doing this, pretend that we are
    380     // skipping while reading the identifier to poison.
    381     // This avoids errors on code like:
    382     //   #pragma GCC poison X
    383     //   #pragma GCC poison X
    384     if (CurPPLexer) CurPPLexer->LexingRawMode = true;
    385     LexUnexpandedToken(Tok);
    386     if (CurPPLexer) CurPPLexer->LexingRawMode = false;
    387 
    388     // If we reached the end of line, we're done.
    389     if (Tok.is(tok::eod)) return;
    390 
    391     // Can only poison identifiers.
    392     if (Tok.isNot(tok::raw_identifier)) {
    393       Diag(Tok, diag::err_pp_invalid_poison);
    394       return;
    395     }
    396 
    397     // Look up the identifier info for the token.  We disabled identifier lookup
    398     // by saying we're skipping contents, so we need to do this manually.
    399     IdentifierInfo *II = LookUpIdentifierInfo(Tok);
    400 
    401     // Already poisoned.
    402     if (II->isPoisoned()) continue;
    403 
    404     // If this is a macro identifier, emit a warning.
    405     if (II->hasMacroDefinition())
    406       Diag(Tok, diag::pp_poisoning_existing_macro);
    407 
    408     // Finally, poison it!
    409     II->setIsPoisoned();
    410     if (II->isFromAST())
    411       II->setChangedSinceDeserialization();
    412   }
    413 }
    414 
    415 /// HandlePragmaSystemHeader - Implement \#pragma GCC system_header.  We know
    416 /// that the whole directive has been parsed.
    417 void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
    418   if (isInPrimaryFile()) {
    419     Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
    420     return;
    421   }
    422 
    423   // Get the current file lexer we're looking at.  Ignore _Pragma 'files' etc.
    424   PreprocessorLexer *TheLexer = getCurrentFileLexer();
    425 
    426   // Mark the file as a system header.
    427   HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
    428 
    429 
    430   PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
    431   if (PLoc.isInvalid())
    432     return;
    433 
    434   unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
    435 
    436   // Notify the client, if desired, that we are in a new source file.
    437   if (Callbacks)
    438     Callbacks->FileChanged(SysHeaderTok.getLocation(),
    439                            PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
    440 
    441   // Emit a line marker.  This will change any source locations from this point
    442   // forward to realize they are in a system header.
    443   // Create a line note with this information.
    444   SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine()+1,
    445                         FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
    446                         /*IsSystem=*/true, /*IsExternC=*/false);
    447 }
    448 
    449 /// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
    450 ///
    451 void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
    452   Token FilenameTok;
    453   CurPPLexer->LexIncludeFilename(FilenameTok);
    454 
    455   // If the token kind is EOD, the error has already been diagnosed.
    456   if (FilenameTok.is(tok::eod))
    457     return;
    458 
    459   // Reserve a buffer to get the spelling.
    460   SmallString<128> FilenameBuffer;
    461   bool Invalid = false;
    462   StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
    463   if (Invalid)
    464     return;
    465 
    466   bool isAngled =
    467     GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
    468   // If GetIncludeFilenameSpelling set the start ptr to null, there was an
    469   // error.
    470   if (Filename.empty())
    471     return;
    472 
    473   // Search include directories for this file.
    474   const DirectoryLookup *CurDir;
    475   const FileEntry *File = LookupFile(FilenameTok.getLocation(), Filename,
    476                                      isAngled, nullptr, CurDir, nullptr,
    477                                      nullptr, nullptr);
    478   if (!File) {
    479     if (!SuppressIncludeNotFoundError)
    480       Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
    481     return;
    482   }
    483 
    484   const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
    485 
    486   // If this file is older than the file it depends on, emit a diagnostic.
    487   if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
    488     // Lex tokens at the end of the message and include them in the message.
    489     std::string Message;
    490     Lex(DependencyTok);
    491     while (DependencyTok.isNot(tok::eod)) {
    492       Message += getSpelling(DependencyTok) + " ";
    493       Lex(DependencyTok);
    494     }
    495 
    496     // Remove the trailing ' ' if present.
    497     if (!Message.empty())
    498       Message.erase(Message.end()-1);
    499     Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
    500   }
    501 }
    502 
    503 /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
    504 /// Return the IdentifierInfo* associated with the macro to push or pop.
    505 IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
    506   // Remember the pragma token location.
    507   Token PragmaTok = Tok;
    508 
    509   // Read the '('.
    510   Lex(Tok);
    511   if (Tok.isNot(tok::l_paren)) {
    512     Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
    513       << getSpelling(PragmaTok);
    514     return nullptr;
    515   }
    516 
    517   // Read the macro name string.
    518   Lex(Tok);
    519   if (Tok.isNot(tok::string_literal)) {
    520     Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
    521       << getSpelling(PragmaTok);
    522     return nullptr;
    523   }
    524 
    525   if (Tok.hasUDSuffix()) {
    526     Diag(Tok, diag::err_invalid_string_udl);
    527     return nullptr;
    528   }
    529 
    530   // Remember the macro string.
    531   std::string StrVal = getSpelling(Tok);
    532 
    533   // Read the ')'.
    534   Lex(Tok);
    535   if (Tok.isNot(tok::r_paren)) {
    536     Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
    537       << getSpelling(PragmaTok);
    538     return nullptr;
    539   }
    540 
    541   assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
    542          "Invalid string token!");
    543 
    544   // Create a Token from the string.
    545   Token MacroTok;
    546   MacroTok.startToken();
    547   MacroTok.setKind(tok::raw_identifier);
    548   CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
    549 
    550   // Get the IdentifierInfo of MacroToPushTok.
    551   return LookUpIdentifierInfo(MacroTok);
    552 }
    553 
    554 /// \brief Handle \#pragma push_macro.
    555 ///
    556 /// The syntax is:
    557 /// \code
    558 ///   #pragma push_macro("macro")
    559 /// \endcode
    560 void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
    561   // Parse the pragma directive and get the macro IdentifierInfo*.
    562   IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
    563   if (!IdentInfo) return;
    564 
    565   // Get the MacroInfo associated with IdentInfo.
    566   MacroInfo *MI = getMacroInfo(IdentInfo);
    567 
    568   if (MI) {
    569     // Allow the original MacroInfo to be redefined later.
    570     MI->setIsAllowRedefinitionsWithoutWarning(true);
    571   }
    572 
    573   // Push the cloned MacroInfo so we can retrieve it later.
    574   PragmaPushMacroInfo[IdentInfo].push_back(MI);
    575 }
    576 
    577 /// \brief Handle \#pragma pop_macro.
    578 ///
    579 /// The syntax is:
    580 /// \code
    581 ///   #pragma pop_macro("macro")
    582 /// \endcode
    583 void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
    584   SourceLocation MessageLoc = PopMacroTok.getLocation();
    585 
    586   // Parse the pragma directive and get the macro IdentifierInfo*.
    587   IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
    588   if (!IdentInfo) return;
    589 
    590   // Find the vector<MacroInfo*> associated with the macro.
    591   llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
    592     PragmaPushMacroInfo.find(IdentInfo);
    593   if (iter != PragmaPushMacroInfo.end()) {
    594     // Forget the MacroInfo currently associated with IdentInfo.
    595     if (MacroDirective *CurrentMD = getMacroDirective(IdentInfo)) {
    596       MacroInfo *MI = CurrentMD->getMacroInfo();
    597       if (MI->isWarnIfUnused())
    598         WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
    599       appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
    600     }
    601 
    602     // Get the MacroInfo we want to reinstall.
    603     MacroInfo *MacroToReInstall = iter->second.back();
    604 
    605     if (MacroToReInstall) {
    606       // Reinstall the previously pushed macro.
    607       appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc,
    608                               /*isImported=*/false);
    609     }
    610 
    611     // Pop PragmaPushMacroInfo stack.
    612     iter->second.pop_back();
    613     if (iter->second.size() == 0)
    614       PragmaPushMacroInfo.erase(iter);
    615   } else {
    616     Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
    617       << IdentInfo->getName();
    618   }
    619 }
    620 
    621 void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
    622   // We will either get a quoted filename or a bracketed filename, and we
    623   // have to track which we got.  The first filename is the source name,
    624   // and the second name is the mapped filename.  If the first is quoted,
    625   // the second must be as well (cannot mix and match quotes and brackets).
    626 
    627   // Get the open paren
    628   Lex(Tok);
    629   if (Tok.isNot(tok::l_paren)) {
    630     Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
    631     return;
    632   }
    633 
    634   // We expect either a quoted string literal, or a bracketed name
    635   Token SourceFilenameTok;
    636   CurPPLexer->LexIncludeFilename(SourceFilenameTok);
    637   if (SourceFilenameTok.is(tok::eod)) {
    638     // The diagnostic has already been handled
    639     return;
    640   }
    641 
    642   StringRef SourceFileName;
    643   SmallString<128> FileNameBuffer;
    644   if (SourceFilenameTok.is(tok::string_literal) ||
    645       SourceFilenameTok.is(tok::angle_string_literal)) {
    646     SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
    647   } else if (SourceFilenameTok.is(tok::less)) {
    648     // This could be a path instead of just a name
    649     FileNameBuffer.push_back('<');
    650     SourceLocation End;
    651     if (ConcatenateIncludeName(FileNameBuffer, End))
    652       return; // Diagnostic already emitted
    653     SourceFileName = FileNameBuffer.str();
    654   } else {
    655     Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
    656     return;
    657   }
    658   FileNameBuffer.clear();
    659 
    660   // Now we expect a comma, followed by another include name
    661   Lex(Tok);
    662   if (Tok.isNot(tok::comma)) {
    663     Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
    664     return;
    665   }
    666 
    667   Token ReplaceFilenameTok;
    668   CurPPLexer->LexIncludeFilename(ReplaceFilenameTok);
    669   if (ReplaceFilenameTok.is(tok::eod)) {
    670     // The diagnostic has already been handled
    671     return;
    672   }
    673 
    674   StringRef ReplaceFileName;
    675   if (ReplaceFilenameTok.is(tok::string_literal) ||
    676       ReplaceFilenameTok.is(tok::angle_string_literal)) {
    677     ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
    678   } else if (ReplaceFilenameTok.is(tok::less)) {
    679     // This could be a path instead of just a name
    680     FileNameBuffer.push_back('<');
    681     SourceLocation End;
    682     if (ConcatenateIncludeName(FileNameBuffer, End))
    683       return; // Diagnostic already emitted
    684     ReplaceFileName = FileNameBuffer.str();
    685   } else {
    686     Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
    687     return;
    688   }
    689 
    690   // Finally, we expect the closing paren
    691   Lex(Tok);
    692   if (Tok.isNot(tok::r_paren)) {
    693     Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
    694     return;
    695   }
    696 
    697   // Now that we have the source and target filenames, we need to make sure
    698   // they're both of the same type (angled vs non-angled)
    699   StringRef OriginalSource = SourceFileName;
    700 
    701   bool SourceIsAngled =
    702     GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
    703                                 SourceFileName);
    704   bool ReplaceIsAngled =
    705     GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
    706                                 ReplaceFileName);
    707   if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
    708       (SourceIsAngled != ReplaceIsAngled)) {
    709     unsigned int DiagID;
    710     if (SourceIsAngled)
    711       DiagID = diag::warn_pragma_include_alias_mismatch_angle;
    712     else
    713       DiagID = diag::warn_pragma_include_alias_mismatch_quote;
    714 
    715     Diag(SourceFilenameTok.getLocation(), DiagID)
    716       << SourceFileName
    717       << ReplaceFileName;
    718 
    719     return;
    720   }
    721 
    722   // Now we can let the include handler know about this mapping
    723   getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
    724 }
    725 
    726 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
    727 /// If 'Namespace' is non-null, then it is a token required to exist on the
    728 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
    729 void Preprocessor::AddPragmaHandler(StringRef Namespace,
    730                                     PragmaHandler *Handler) {
    731   PragmaNamespace *InsertNS = PragmaHandlers;
    732 
    733   // If this is specified to be in a namespace, step down into it.
    734   if (!Namespace.empty()) {
    735     // If there is already a pragma handler with the name of this namespace,
    736     // we either have an error (directive with the same name as a namespace) or
    737     // we already have the namespace to insert into.
    738     if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
    739       InsertNS = Existing->getIfNamespace();
    740       assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
    741              " handler with the same name!");
    742     } else {
    743       // Otherwise, this namespace doesn't exist yet, create and insert the
    744       // handler for it.
    745       InsertNS = new PragmaNamespace(Namespace);
    746       PragmaHandlers->AddPragma(InsertNS);
    747     }
    748   }
    749 
    750   // Check to make sure we don't already have a pragma for this identifier.
    751   assert(!InsertNS->FindHandler(Handler->getName()) &&
    752          "Pragma handler already exists for this identifier!");
    753   InsertNS->AddPragma(Handler);
    754 }
    755 
    756 /// RemovePragmaHandler - Remove the specific pragma handler from the
    757 /// preprocessor. If \arg Namespace is non-null, then it should be the
    758 /// namespace that \arg Handler was added to. It is an error to remove
    759 /// a handler that has not been registered.
    760 void Preprocessor::RemovePragmaHandler(StringRef Namespace,
    761                                        PragmaHandler *Handler) {
    762   PragmaNamespace *NS = PragmaHandlers;
    763 
    764   // If this is specified to be in a namespace, step down into it.
    765   if (!Namespace.empty()) {
    766     PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
    767     assert(Existing && "Namespace containing handler does not exist!");
    768 
    769     NS = Existing->getIfNamespace();
    770     assert(NS && "Invalid namespace, registered as a regular pragma handler!");
    771   }
    772 
    773   NS->RemovePragmaHandler(Handler);
    774 
    775   // If this is a non-default namespace and it is now empty, remove
    776   // it.
    777   if (NS != PragmaHandlers && NS->IsEmpty()) {
    778     PragmaHandlers->RemovePragmaHandler(NS);
    779     delete NS;
    780   }
    781 }
    782 
    783 bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
    784   Token Tok;
    785   LexUnexpandedToken(Tok);
    786 
    787   if (Tok.isNot(tok::identifier)) {
    788     Diag(Tok, diag::ext_on_off_switch_syntax);
    789     return true;
    790   }
    791   IdentifierInfo *II = Tok.getIdentifierInfo();
    792   if (II->isStr("ON"))
    793     Result = tok::OOS_ON;
    794   else if (II->isStr("OFF"))
    795     Result = tok::OOS_OFF;
    796   else if (II->isStr("DEFAULT"))
    797     Result = tok::OOS_DEFAULT;
    798   else {
    799     Diag(Tok, diag::ext_on_off_switch_syntax);
    800     return true;
    801   }
    802 
    803   // Verify that this is followed by EOD.
    804   LexUnexpandedToken(Tok);
    805   if (Tok.isNot(tok::eod))
    806     Diag(Tok, diag::ext_pragma_syntax_eod);
    807   return false;
    808 }
    809 
    810 namespace {
    811 /// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
    812 struct PragmaOnceHandler : public PragmaHandler {
    813   PragmaOnceHandler() : PragmaHandler("once") {}
    814   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
    815                     Token &OnceTok) override {
    816     PP.CheckEndOfDirective("pragma once");
    817     PP.HandlePragmaOnce(OnceTok);
    818   }
    819 };
    820 
    821 /// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
    822 /// rest of the line is not lexed.
    823 struct PragmaMarkHandler : public PragmaHandler {
    824   PragmaMarkHandler() : PragmaHandler("mark") {}
    825   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
    826                     Token &MarkTok) override {
    827     PP.HandlePragmaMark();
    828   }
    829 };
    830 
    831 /// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
    832 struct PragmaPoisonHandler : public PragmaHandler {
    833   PragmaPoisonHandler() : PragmaHandler("poison") {}
    834   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
    835                     Token &PoisonTok) override {
    836     PP.HandlePragmaPoison(PoisonTok);
    837   }
    838 };
    839 
    840 /// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
    841 /// as a system header, which silences warnings in it.
    842 struct PragmaSystemHeaderHandler : public PragmaHandler {
    843   PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
    844   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
    845                     Token &SHToken) override {
    846     PP.HandlePragmaSystemHeader(SHToken);
    847     PP.CheckEndOfDirective("pragma");
    848   }
    849 };
    850 struct PragmaDependencyHandler : public PragmaHandler {
    851   PragmaDependencyHandler() : PragmaHandler("dependency") {}
    852   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
    853                     Token &DepToken) override {
    854     PP.HandlePragmaDependency(DepToken);
    855   }
    856 };
    857 
    858 struct PragmaDebugHandler : public PragmaHandler {
    859   PragmaDebugHandler() : PragmaHandler("__debug") {}
    860   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
    861                     Token &DepToken) override {
    862     Token Tok;
    863     PP.LexUnexpandedToken(Tok);
    864     if (Tok.isNot(tok::identifier)) {
    865       PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
    866       return;
    867     }
    868     IdentifierInfo *II = Tok.getIdentifierInfo();
    869 
    870     if (II->isStr("assert")) {
    871       llvm_unreachable("This is an assertion!");
    872     } else if (II->isStr("crash")) {
    873       LLVM_BUILTIN_TRAP;
    874     } else if (II->isStr("parser_crash")) {
    875       Token Crasher;
    876       Crasher.setKind(tok::annot_pragma_parser_crash);
    877       PP.EnterToken(Crasher);
    878     } else if (II->isStr("llvm_fatal_error")) {
    879       llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
    880     } else if (II->isStr("llvm_unreachable")) {
    881       llvm_unreachable("#pragma clang __debug llvm_unreachable");
    882     } else if (II->isStr("overflow_stack")) {
    883       DebugOverflowStack();
    884     } else if (II->isStr("handle_crash")) {
    885       llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
    886       if (CRC)
    887         CRC->HandleCrash();
    888     } else if (II->isStr("captured")) {
    889       HandleCaptured(PP);
    890     } else {
    891       PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
    892         << II->getName();
    893     }
    894 
    895     PPCallbacks *Callbacks = PP.getPPCallbacks();
    896     if (Callbacks)
    897       Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
    898   }
    899 
    900   void HandleCaptured(Preprocessor &PP) {
    901     // Skip if emitting preprocessed output.
    902     if (PP.isPreprocessedOutput())
    903       return;
    904 
    905     Token Tok;
    906     PP.LexUnexpandedToken(Tok);
    907 
    908     if (Tok.isNot(tok::eod)) {
    909       PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
    910         << "pragma clang __debug captured";
    911       return;
    912     }
    913 
    914     SourceLocation NameLoc = Tok.getLocation();
    915     Token *Toks = PP.getPreprocessorAllocator().Allocate<Token>(1);
    916     Toks->startToken();
    917     Toks->setKind(tok::annot_pragma_captured);
    918     Toks->setLocation(NameLoc);
    919 
    920     PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true,
    921                         /*OwnsTokens=*/false);
    922   }
    923 
    924 // Disable MSVC warning about runtime stack overflow.
    925 #ifdef _MSC_VER
    926     #pragma warning(disable : 4717)
    927 #endif
    928   static void DebugOverflowStack() {
    929     void (*volatile Self)() = DebugOverflowStack;
    930     Self();
    931   }
    932 #ifdef _MSC_VER
    933     #pragma warning(default : 4717)
    934 #endif
    935 
    936 };
    937 
    938 /// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
    939 struct PragmaDiagnosticHandler : public PragmaHandler {
    940 private:
    941   const char *Namespace;
    942 public:
    943   explicit PragmaDiagnosticHandler(const char *NS) :
    944     PragmaHandler("diagnostic"), Namespace(NS) {}
    945   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
    946                     Token &DiagToken) override {
    947     SourceLocation DiagLoc = DiagToken.getLocation();
    948     Token Tok;
    949     PP.LexUnexpandedToken(Tok);
    950     if (Tok.isNot(tok::identifier)) {
    951       PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
    952       return;
    953     }
    954     IdentifierInfo *II = Tok.getIdentifierInfo();
    955     PPCallbacks *Callbacks = PP.getPPCallbacks();
    956 
    957     if (II->isStr("pop")) {
    958       if (!PP.getDiagnostics().popMappings(DiagLoc))
    959         PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
    960       else if (Callbacks)
    961         Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
    962       return;
    963     } else if (II->isStr("push")) {
    964       PP.getDiagnostics().pushMappings(DiagLoc);
    965       if (Callbacks)
    966         Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
    967       return;
    968     }
    969 
    970     diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
    971                             .Case("ignored", diag::Severity::Ignored)
    972                             .Case("warning", diag::Severity::Warning)
    973                             .Case("error", diag::Severity::Error)
    974                             .Case("fatal", diag::Severity::Fatal)
    975                             .Default(diag::Severity());
    976 
    977     if (SV == diag::Severity()) {
    978       PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
    979       return;
    980     }
    981 
    982     PP.LexUnexpandedToken(Tok);
    983     SourceLocation StringLoc = Tok.getLocation();
    984 
    985     std::string WarningName;
    986     if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
    987                                    /*MacroExpansion=*/false))
    988       return;
    989 
    990     if (Tok.isNot(tok::eod)) {
    991       PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
    992       return;
    993     }
    994 
    995     if (WarningName.size() < 3 || WarningName[0] != '-' ||
    996         WarningName[1] != 'W') {
    997       PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
    998       return;
    999     }
   1000 
   1001     if (PP.getDiagnostics().setSeverityForGroup(WarningName.substr(2), SV,
   1002                                                 DiagLoc))
   1003       PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
   1004         << WarningName;
   1005     else if (Callbacks)
   1006       Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
   1007   }
   1008 };
   1009 
   1010 /// "\#pragma warning(...)".  MSVC's diagnostics do not map cleanly to clang's
   1011 /// diagnostics, so we don't really implement this pragma.  We parse it and
   1012 /// ignore it to avoid -Wunknown-pragma warnings.
   1013 struct PragmaWarningHandler : public PragmaHandler {
   1014   PragmaWarningHandler() : PragmaHandler("warning") {}
   1015 
   1016   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
   1017                     Token &Tok) override {
   1018     // Parse things like:
   1019     // warning(push, 1)
   1020     // warning(pop)
   1021     // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
   1022     SourceLocation DiagLoc = Tok.getLocation();
   1023     PPCallbacks *Callbacks = PP.getPPCallbacks();
   1024 
   1025     PP.Lex(Tok);
   1026     if (Tok.isNot(tok::l_paren)) {
   1027       PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
   1028       return;
   1029     }
   1030 
   1031     PP.Lex(Tok);
   1032     IdentifierInfo *II = Tok.getIdentifierInfo();
   1033     if (!II) {
   1034       PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
   1035       return;
   1036     }
   1037 
   1038     if (II->isStr("push")) {
   1039       // #pragma warning( push[ ,n ] )
   1040       int Level = -1;
   1041       PP.Lex(Tok);
   1042       if (Tok.is(tok::comma)) {
   1043         PP.Lex(Tok);
   1044         uint64_t Value;
   1045         if (Tok.is(tok::numeric_constant) &&
   1046             PP.parseSimpleIntegerLiteral(Tok, Value))
   1047           Level = int(Value);
   1048         if (Level < 0 || Level > 4) {
   1049           PP.Diag(Tok, diag::warn_pragma_warning_push_level);
   1050           return;
   1051         }
   1052       }
   1053       if (Callbacks)
   1054         Callbacks->PragmaWarningPush(DiagLoc, Level);
   1055     } else if (II->isStr("pop")) {
   1056       // #pragma warning( pop )
   1057       PP.Lex(Tok);
   1058       if (Callbacks)
   1059         Callbacks->PragmaWarningPop(DiagLoc);
   1060     } else {
   1061       // #pragma warning( warning-specifier : warning-number-list
   1062       //                  [; warning-specifier : warning-number-list...] )
   1063       while (true) {
   1064         II = Tok.getIdentifierInfo();
   1065         if (!II) {
   1066           PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
   1067           return;
   1068         }
   1069 
   1070         // Figure out which warning specifier this is.
   1071         StringRef Specifier = II->getName();
   1072         bool SpecifierValid =
   1073             llvm::StringSwitch<bool>(Specifier)
   1074                 .Cases("1", "2", "3", "4", true)
   1075                 .Cases("default", "disable", "error", "once", "suppress", true)
   1076                 .Default(false);
   1077         if (!SpecifierValid) {
   1078           PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
   1079           return;
   1080         }
   1081         PP.Lex(Tok);
   1082         if (Tok.isNot(tok::colon)) {
   1083           PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
   1084           return;
   1085         }
   1086 
   1087         // Collect the warning ids.
   1088         SmallVector<int, 4> Ids;
   1089         PP.Lex(Tok);
   1090         while (Tok.is(tok::numeric_constant)) {
   1091           uint64_t Value;
   1092           if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
   1093               Value > INT_MAX) {
   1094             PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
   1095             return;
   1096           }
   1097           Ids.push_back(int(Value));
   1098         }
   1099         if (Callbacks)
   1100           Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
   1101 
   1102         // Parse the next specifier if there is a semicolon.
   1103         if (Tok.isNot(tok::semi))
   1104           break;
   1105         PP.Lex(Tok);
   1106       }
   1107     }
   1108 
   1109     if (Tok.isNot(tok::r_paren)) {
   1110       PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
   1111       return;
   1112     }
   1113 
   1114     PP.Lex(Tok);
   1115     if (Tok.isNot(tok::eod))
   1116       PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
   1117   }
   1118 };
   1119 
   1120 /// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
   1121 struct PragmaIncludeAliasHandler : public PragmaHandler {
   1122   PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
   1123   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
   1124                     Token &IncludeAliasTok) override {
   1125     PP.HandlePragmaIncludeAlias(IncludeAliasTok);
   1126   }
   1127 };
   1128 
   1129 /// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
   1130 /// extension.  The syntax is:
   1131 /// \code
   1132 ///   #pragma message(string)
   1133 /// \endcode
   1134 /// OR, in GCC mode:
   1135 /// \code
   1136 ///   #pragma message string
   1137 /// \endcode
   1138 /// string is a string, which is fully macro expanded, and permits string
   1139 /// concatenation, embedded escape characters, etc... See MSDN for more details.
   1140 /// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
   1141 /// form as \#pragma message.
   1142 struct PragmaMessageHandler : public PragmaHandler {
   1143 private:
   1144   const PPCallbacks::PragmaMessageKind Kind;
   1145   const StringRef Namespace;
   1146 
   1147   static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
   1148                                 bool PragmaNameOnly = false) {
   1149     switch (Kind) {
   1150       case PPCallbacks::PMK_Message:
   1151         return PragmaNameOnly ? "message" : "pragma message";
   1152       case PPCallbacks::PMK_Warning:
   1153         return PragmaNameOnly ? "warning" : "pragma warning";
   1154       case PPCallbacks::PMK_Error:
   1155         return PragmaNameOnly ? "error" : "pragma error";
   1156     }
   1157     llvm_unreachable("Unknown PragmaMessageKind!");
   1158   }
   1159 
   1160 public:
   1161   PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
   1162                        StringRef Namespace = StringRef())
   1163     : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), Namespace(Namespace) {}
   1164 
   1165   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
   1166                     Token &Tok) override {
   1167     SourceLocation MessageLoc = Tok.getLocation();
   1168     PP.Lex(Tok);
   1169     bool ExpectClosingParen = false;
   1170     switch (Tok.getKind()) {
   1171     case tok::l_paren:
   1172       // We have a MSVC style pragma message.
   1173       ExpectClosingParen = true;
   1174       // Read the string.
   1175       PP.Lex(Tok);
   1176       break;
   1177     case tok::string_literal:
   1178       // We have a GCC style pragma message, and we just read the string.
   1179       break;
   1180     default:
   1181       PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
   1182       return;
   1183     }
   1184 
   1185     std::string MessageString;
   1186     if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
   1187                                    /*MacroExpansion=*/true))
   1188       return;
   1189 
   1190     if (ExpectClosingParen) {
   1191       if (Tok.isNot(tok::r_paren)) {
   1192         PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
   1193         return;
   1194       }
   1195       PP.Lex(Tok);  // eat the r_paren.
   1196     }
   1197 
   1198     if (Tok.isNot(tok::eod)) {
   1199       PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
   1200       return;
   1201     }
   1202 
   1203     // Output the message.
   1204     PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
   1205                           ? diag::err_pragma_message
   1206                           : diag::warn_pragma_message) << MessageString;
   1207 
   1208     // If the pragma is lexically sound, notify any interested PPCallbacks.
   1209     if (PPCallbacks *Callbacks = PP.getPPCallbacks())
   1210       Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
   1211   }
   1212 };
   1213 
   1214 /// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
   1215 /// macro on the top of the stack.
   1216 struct PragmaPushMacroHandler : public PragmaHandler {
   1217   PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
   1218   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
   1219                     Token &PushMacroTok) override {
   1220     PP.HandlePragmaPushMacro(PushMacroTok);
   1221   }
   1222 };
   1223 
   1224 
   1225 /// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
   1226 /// macro to the value on the top of the stack.
   1227 struct PragmaPopMacroHandler : public PragmaHandler {
   1228   PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
   1229   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
   1230                     Token &PopMacroTok) override {
   1231     PP.HandlePragmaPopMacro(PopMacroTok);
   1232   }
   1233 };
   1234 
   1235 // Pragma STDC implementations.
   1236 
   1237 /// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
   1238 struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
   1239   PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
   1240   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
   1241                     Token &Tok) override {
   1242     tok::OnOffSwitch OOS;
   1243     if (PP.LexOnOffSwitch(OOS))
   1244      return;
   1245     if (OOS == tok::OOS_ON)
   1246       PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
   1247   }
   1248 };
   1249 
   1250 /// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
   1251 struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
   1252   PragmaSTDC_CX_LIMITED_RANGEHandler()
   1253     : PragmaHandler("CX_LIMITED_RANGE") {}
   1254   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
   1255                     Token &Tok) override {
   1256     tok::OnOffSwitch OOS;
   1257     PP.LexOnOffSwitch(OOS);
   1258   }
   1259 };
   1260 
   1261 /// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
   1262 struct PragmaSTDC_UnknownHandler : public PragmaHandler {
   1263   PragmaSTDC_UnknownHandler() {}
   1264   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
   1265                     Token &UnknownTok) override {
   1266     // C99 6.10.6p2, unknown forms are not allowed.
   1267     PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
   1268   }
   1269 };
   1270 
   1271 /// PragmaARCCFCodeAuditedHandler -
   1272 ///   \#pragma clang arc_cf_code_audited begin/end
   1273 struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
   1274   PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
   1275   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
   1276                     Token &NameTok) override {
   1277     SourceLocation Loc = NameTok.getLocation();
   1278     bool IsBegin;
   1279 
   1280     Token Tok;
   1281 
   1282     // Lex the 'begin' or 'end'.
   1283     PP.LexUnexpandedToken(Tok);
   1284     const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
   1285     if (BeginEnd && BeginEnd->isStr("begin")) {
   1286       IsBegin = true;
   1287     } else if (BeginEnd && BeginEnd->isStr("end")) {
   1288       IsBegin = false;
   1289     } else {
   1290       PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
   1291       return;
   1292     }
   1293 
   1294     // Verify that this is followed by EOD.
   1295     PP.LexUnexpandedToken(Tok);
   1296     if (Tok.isNot(tok::eod))
   1297       PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
   1298 
   1299     // The start location of the active audit.
   1300     SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
   1301 
   1302     // The start location we want after processing this.
   1303     SourceLocation NewLoc;
   1304 
   1305     if (IsBegin) {
   1306       // Complain about attempts to re-enter an audit.
   1307       if (BeginLoc.isValid()) {
   1308         PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
   1309         PP.Diag(BeginLoc, diag::note_pragma_entered_here);
   1310       }
   1311       NewLoc = Loc;
   1312     } else {
   1313       // Complain about attempts to leave an audit that doesn't exist.
   1314       if (!BeginLoc.isValid()) {
   1315         PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
   1316         return;
   1317       }
   1318       NewLoc = SourceLocation();
   1319     }
   1320 
   1321     PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
   1322   }
   1323 };
   1324 
   1325 /// \brief Handle "\#pragma region [...]"
   1326 ///
   1327 /// The syntax is
   1328 /// \code
   1329 ///   #pragma region [optional name]
   1330 ///   #pragma endregion [optional comment]
   1331 /// \endcode
   1332 ///
   1333 /// \note This is
   1334 /// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
   1335 /// pragma, just skipped by compiler.
   1336 struct PragmaRegionHandler : public PragmaHandler {
   1337   PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) { }
   1338 
   1339   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
   1340                     Token &NameTok) override {
   1341     // #pragma region: endregion matches can be verified
   1342     // __pragma(region): no sense, but ignored by msvc
   1343     // _Pragma is not valid for MSVC, but there isn't any point
   1344     // to handle a _Pragma differently.
   1345   }
   1346 };
   1347 
   1348 }  // end anonymous namespace
   1349 
   1350 
   1351 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
   1352 /// \#pragma GCC poison/system_header/dependency and \#pragma once.
   1353 void Preprocessor::RegisterBuiltinPragmas() {
   1354   AddPragmaHandler(new PragmaOnceHandler());
   1355   AddPragmaHandler(new PragmaMarkHandler());
   1356   AddPragmaHandler(new PragmaPushMacroHandler());
   1357   AddPragmaHandler(new PragmaPopMacroHandler());
   1358   AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
   1359 
   1360   // #pragma GCC ...
   1361   AddPragmaHandler("GCC", new PragmaPoisonHandler());
   1362   AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
   1363   AddPragmaHandler("GCC", new PragmaDependencyHandler());
   1364   AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
   1365   AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
   1366                                                    "GCC"));
   1367   AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
   1368                                                    "GCC"));
   1369   // #pragma clang ...
   1370   AddPragmaHandler("clang", new PragmaPoisonHandler());
   1371   AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
   1372   AddPragmaHandler("clang", new PragmaDebugHandler());
   1373   AddPragmaHandler("clang", new PragmaDependencyHandler());
   1374   AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
   1375   AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
   1376 
   1377   AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
   1378   AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
   1379   AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
   1380 
   1381   // MS extensions.
   1382   if (LangOpts.MicrosoftExt) {
   1383     AddPragmaHandler(new PragmaWarningHandler());
   1384     AddPragmaHandler(new PragmaIncludeAliasHandler());
   1385     AddPragmaHandler(new PragmaRegionHandler("region"));
   1386     AddPragmaHandler(new PragmaRegionHandler("endregion"));
   1387   }
   1388 }
   1389 
   1390 /// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
   1391 /// warn about those pragmas being unknown.
   1392 void Preprocessor::IgnorePragmas() {
   1393   AddPragmaHandler(new EmptyPragmaHandler());
   1394   // Also ignore all pragmas in all namespaces created
   1395   // in Preprocessor::RegisterBuiltinPragmas().
   1396   AddPragmaHandler("GCC", new EmptyPragmaHandler());
   1397   AddPragmaHandler("clang", new EmptyPragmaHandler());
   1398   if (PragmaHandler *NS = PragmaHandlers->FindHandler("STDC")) {
   1399     // Preprocessor::RegisterBuiltinPragmas() already registers
   1400     // PragmaSTDC_UnknownHandler as the empty handler, so remove it first,
   1401     // otherwise there will be an assert about a duplicate handler.
   1402     PragmaNamespace *STDCNamespace = NS->getIfNamespace();
   1403     assert(STDCNamespace &&
   1404            "Invalid namespace, registered as a regular pragma handler!");
   1405     if (PragmaHandler *Existing = STDCNamespace->FindHandler("", false)) {
   1406       RemovePragmaHandler("STDC", Existing);
   1407       delete Existing;
   1408     }
   1409   }
   1410   AddPragmaHandler("STDC", new EmptyPragmaHandler());
   1411 }
   1412