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