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