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