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 // Returns -1 on failure.
1012 static int LexSimpleInt(Preprocessor &PP, Token &Tok) {
1013   assert(Tok.is(tok::numeric_constant));
1014   SmallString<8> IntegerBuffer;
1015   bool NumberInvalid = false;
1016   StringRef Spelling = PP.getSpelling(Tok, IntegerBuffer, &NumberInvalid);
1017   if (NumberInvalid)
1018     return -1;
1019   NumericLiteralParser Literal(Spelling, Tok.getLocation(), PP);
1020   if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
1021     return -1;
1022   llvm::APInt APVal(32, 0);
1023   if (Literal.GetIntegerValue(APVal))
1024     return -1;
1025   PP.Lex(Tok);
1026   return int(APVal.getLimitedValue(INT_MAX));
1027 }
1028 
1029 /// "\#pragma warning(...)".  MSVC's diagnostics do not map cleanly to clang's
1030 /// diagnostics, so we don't really implement this pragma.  We parse it and
1031 /// ignore it to avoid -Wunknown-pragma warnings.
1032 struct PragmaWarningHandler : public PragmaHandler {
1033   PragmaWarningHandler() : PragmaHandler("warning") {}
1034 
1035   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1036                             Token &Tok) {
1037     // Parse things like:
1038     // warning(push, 1)
1039     // warning(pop)
1040     // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
1041     SourceLocation DiagLoc = Tok.getLocation();
1042     PPCallbacks *Callbacks = PP.getPPCallbacks();
1043 
1044     PP.Lex(Tok);
1045     if (Tok.isNot(tok::l_paren)) {
1046       PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1047       return;
1048     }
1049 
1050     PP.Lex(Tok);
1051     IdentifierInfo *II = Tok.getIdentifierInfo();
1052     if (!II) {
1053       PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1054       return;
1055     }
1056 
1057     if (II->isStr("push")) {
1058       // #pragma warning( push[ ,n ] )
1059       int Level = -1;
1060       PP.Lex(Tok);
1061       if (Tok.is(tok::comma)) {
1062         PP.Lex(Tok);
1063         if (Tok.is(tok::numeric_constant))
1064           Level = LexSimpleInt(PP, Tok);
1065         if (Level < 0 || Level > 4) {
1066           PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1067           return;
1068         }
1069       }
1070       if (Callbacks)
1071         Callbacks->PragmaWarningPush(DiagLoc, Level);
1072     } else if (II->isStr("pop")) {
1073       // #pragma warning( pop )
1074       PP.Lex(Tok);
1075       if (Callbacks)
1076         Callbacks->PragmaWarningPop(DiagLoc);
1077     } else {
1078       // #pragma warning( warning-specifier : warning-number-list
1079       //                  [; warning-specifier : warning-number-list...] )
1080       while (true) {
1081         II = Tok.getIdentifierInfo();
1082         if (!II) {
1083           PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1084           return;
1085         }
1086 
1087         // Figure out which warning specifier this is.
1088         StringRef Specifier = II->getName();
1089         bool SpecifierValid =
1090             llvm::StringSwitch<bool>(Specifier)
1091                 .Cases("1", "2", "3", "4", true)
1092                 .Cases("default", "disable", "error", "once", "suppress", true)
1093                 .Default(false);
1094         if (!SpecifierValid) {
1095           PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1096           return;
1097         }
1098         PP.Lex(Tok);
1099         if (Tok.isNot(tok::colon)) {
1100           PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1101           return;
1102         }
1103 
1104         // Collect the warning ids.
1105         SmallVector<int, 4> Ids;
1106         PP.Lex(Tok);
1107         while (Tok.is(tok::numeric_constant)) {
1108           int Id = LexSimpleInt(PP, Tok);
1109           if (Id <= 0) {
1110             PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1111             return;
1112           }
1113           Ids.push_back(Id);
1114         }
1115         if (Callbacks)
1116           Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1117 
1118         // Parse the next specifier if there is a semicolon.
1119         if (Tok.isNot(tok::semi))
1120           break;
1121         PP.Lex(Tok);
1122       }
1123     }
1124 
1125     if (Tok.isNot(tok::r_paren)) {
1126       PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1127       return;
1128     }
1129 
1130     PP.Lex(Tok);
1131     if (Tok.isNot(tok::eod))
1132       PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1133   }
1134 };
1135 
1136 /// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
1137 struct PragmaIncludeAliasHandler : public PragmaHandler {
1138   PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
1139   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1140                             Token &IncludeAliasTok) {
1141     PP.HandlePragmaIncludeAlias(IncludeAliasTok);
1142   }
1143 };
1144 
1145 /// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1146 /// extension.  The syntax is:
1147 /// \code
1148 ///   #pragma message(string)
1149 /// \endcode
1150 /// OR, in GCC mode:
1151 /// \code
1152 ///   #pragma message string
1153 /// \endcode
1154 /// string is a string, which is fully macro expanded, and permits string
1155 /// concatenation, embedded escape characters, etc... See MSDN for more details.
1156 /// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1157 /// form as \#pragma message.
1158 struct PragmaMessageHandler : public PragmaHandler {
1159 private:
1160   const PPCallbacks::PragmaMessageKind Kind;
1161   const StringRef Namespace;
1162 
1163   static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1164                                 bool PragmaNameOnly = false) {
1165     switch (Kind) {
1166       case PPCallbacks::PMK_Message:
1167         return PragmaNameOnly ? "message" : "pragma message";
1168       case PPCallbacks::PMK_Warning:
1169         return PragmaNameOnly ? "warning" : "pragma warning";
1170       case PPCallbacks::PMK_Error:
1171         return PragmaNameOnly ? "error" : "pragma error";
1172     }
1173     llvm_unreachable("Unknown PragmaMessageKind!");
1174   }
1175 
1176 public:
1177   PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1178                        StringRef Namespace = StringRef())
1179     : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), Namespace(Namespace) {}
1180 
1181   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1182                             Token &Tok) {
1183     SourceLocation MessageLoc = Tok.getLocation();
1184     PP.Lex(Tok);
1185     bool ExpectClosingParen = false;
1186     switch (Tok.getKind()) {
1187     case tok::l_paren:
1188       // We have a MSVC style pragma message.
1189       ExpectClosingParen = true;
1190       // Read the string.
1191       PP.Lex(Tok);
1192       break;
1193     case tok::string_literal:
1194       // We have a GCC style pragma message, and we just read the string.
1195       break;
1196     default:
1197       PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1198       return;
1199     }
1200 
1201     std::string MessageString;
1202     if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1203                                    /*MacroExpansion=*/true))
1204       return;
1205 
1206     if (ExpectClosingParen) {
1207       if (Tok.isNot(tok::r_paren)) {
1208         PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1209         return;
1210       }
1211       PP.Lex(Tok);  // eat the r_paren.
1212     }
1213 
1214     if (Tok.isNot(tok::eod)) {
1215       PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1216       return;
1217     }
1218 
1219     // Output the message.
1220     PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1221                           ? diag::err_pragma_message
1222                           : diag::warn_pragma_message) << MessageString;
1223 
1224     // If the pragma is lexically sound, notify any interested PPCallbacks.
1225     if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1226       Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
1227   }
1228 };
1229 
1230 /// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
1231 /// macro on the top of the stack.
1232 struct PragmaPushMacroHandler : public PragmaHandler {
1233   PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
1234   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1235                             Token &PushMacroTok) {
1236     PP.HandlePragmaPushMacro(PushMacroTok);
1237   }
1238 };
1239 
1240 
1241 /// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
1242 /// macro to the value on the top of the stack.
1243 struct PragmaPopMacroHandler : public PragmaHandler {
1244   PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
1245   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1246                             Token &PopMacroTok) {
1247     PP.HandlePragmaPopMacro(PopMacroTok);
1248   }
1249 };
1250 
1251 // Pragma STDC implementations.
1252 
1253 /// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
1254 struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
1255   PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
1256   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1257                             Token &Tok) {
1258     tok::OnOffSwitch OOS;
1259     if (PP.LexOnOffSwitch(OOS))
1260      return;
1261     if (OOS == tok::OOS_ON)
1262       PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
1263   }
1264 };
1265 
1266 /// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
1267 struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
1268   PragmaSTDC_CX_LIMITED_RANGEHandler()
1269     : PragmaHandler("CX_LIMITED_RANGE") {}
1270   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1271                             Token &Tok) {
1272     tok::OnOffSwitch OOS;
1273     PP.LexOnOffSwitch(OOS);
1274   }
1275 };
1276 
1277 /// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
1278 struct PragmaSTDC_UnknownHandler : public PragmaHandler {
1279   PragmaSTDC_UnknownHandler() {}
1280   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1281                             Token &UnknownTok) {
1282     // C99 6.10.6p2, unknown forms are not allowed.
1283     PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
1284   }
1285 };
1286 
1287 /// PragmaARCCFCodeAuditedHandler -
1288 ///   \#pragma clang arc_cf_code_audited begin/end
1289 struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1290   PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
1291   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1292                             Token &NameTok) {
1293     SourceLocation Loc = NameTok.getLocation();
1294     bool IsBegin;
1295 
1296     Token Tok;
1297 
1298     // Lex the 'begin' or 'end'.
1299     PP.LexUnexpandedToken(Tok);
1300     const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1301     if (BeginEnd && BeginEnd->isStr("begin")) {
1302       IsBegin = true;
1303     } else if (BeginEnd && BeginEnd->isStr("end")) {
1304       IsBegin = false;
1305     } else {
1306       PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1307       return;
1308     }
1309 
1310     // Verify that this is followed by EOD.
1311     PP.LexUnexpandedToken(Tok);
1312     if (Tok.isNot(tok::eod))
1313       PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1314 
1315     // The start location of the active audit.
1316     SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1317 
1318     // The start location we want after processing this.
1319     SourceLocation NewLoc;
1320 
1321     if (IsBegin) {
1322       // Complain about attempts to re-enter an audit.
1323       if (BeginLoc.isValid()) {
1324         PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1325         PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1326       }
1327       NewLoc = Loc;
1328     } else {
1329       // Complain about attempts to leave an audit that doesn't exist.
1330       if (!BeginLoc.isValid()) {
1331         PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1332         return;
1333       }
1334       NewLoc = SourceLocation();
1335     }
1336 
1337     PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1338   }
1339 };
1340 
1341 /// \brief Handle "\#pragma region [...]"
1342 ///
1343 /// The syntax is
1344 /// \code
1345 ///   #pragma region [optional name]
1346 ///   #pragma endregion [optional comment]
1347 /// \endcode
1348 ///
1349 /// \note This is
1350 /// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1351 /// pragma, just skipped by compiler.
1352 struct PragmaRegionHandler : public PragmaHandler {
1353   PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) { }
1354 
1355   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1356                             Token &NameTok) {
1357     // #pragma region: endregion matches can be verified
1358     // __pragma(region): no sense, but ignored by msvc
1359     // _Pragma is not valid for MSVC, but there isn't any point
1360     // to handle a _Pragma differently.
1361   }
1362 };
1363 
1364 }  // end anonymous namespace
1365 
1366 
1367 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
1368 /// \#pragma GCC poison/system_header/dependency and \#pragma once.
1369 void Preprocessor::RegisterBuiltinPragmas() {
1370   AddPragmaHandler(new PragmaOnceHandler());
1371   AddPragmaHandler(new PragmaMarkHandler());
1372   AddPragmaHandler(new PragmaPushMacroHandler());
1373   AddPragmaHandler(new PragmaPopMacroHandler());
1374   AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
1375 
1376   // #pragma GCC ...
1377   AddPragmaHandler("GCC", new PragmaPoisonHandler());
1378   AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1379   AddPragmaHandler("GCC", new PragmaDependencyHandler());
1380   AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
1381   AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1382                                                    "GCC"));
1383   AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1384                                                    "GCC"));
1385   // #pragma clang ...
1386   AddPragmaHandler("clang", new PragmaPoisonHandler());
1387   AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
1388   AddPragmaHandler("clang", new PragmaDebugHandler());
1389   AddPragmaHandler("clang", new PragmaDependencyHandler());
1390   AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
1391   AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
1392 
1393   AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1394   AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
1395   AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
1396 
1397   // MS extensions.
1398   if (LangOpts.MicrosoftExt) {
1399     AddPragmaHandler(new PragmaWarningHandler());
1400     AddPragmaHandler(new PragmaIncludeAliasHandler());
1401     AddPragmaHandler(new PragmaRegionHandler("region"));
1402     AddPragmaHandler(new PragmaRegionHandler("endregion"));
1403   }
1404 }
1405