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