clang API Documentation

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