clang  3.9.0
Pragma.cpp
Go to the documentation of this file.
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"
18 #include "clang/Lex/HeaderSearch.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.
35 }
36 
37 //===----------------------------------------------------------------------===//
38 // EmptyPragmaHandler Implementation.
39 //===----------------------------------------------------------------------===//
40 
42 
44  PragmaIntroducerKind Introducer,
45  Token &FirstToken) {}
46 
47 //===----------------------------------------------------------------------===//
48 // PragmaNamespace Implementation.
49 //===----------------------------------------------------------------------===//
50 
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.
60  bool IgnoreNull) const {
61  if (PragmaHandler *Handler = Handlers.lookup(Name))
62  return Handler;
63  return IgnoreNull ? nullptr : Handlers.lookup(StringRef());
64 }
65 
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 
73  assert(Handlers.lookup(Handler->getName()) &&
74  "Handler not registered in this namespace");
75  Handlers.erase(Handler->getName());
76 }
77 
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
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.
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))
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:
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;
142  }
143  }
144 
145  ~LexingFor_PragmaRAII() {
146  if (InMacroArgPreExpansion) {
147  if (Failed) {
149  } else {
150  PP.Backtrack();
151  OutTok = PragmaTok;
152  }
153  }
154  }
155 
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'.
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 bad tokens, and the ')', if present.
195  if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
196  Lex(Tok);
197  while (Tok.isNot(tok::r_paren) &&
198  !Tok.isAtStartOfLine() &&
199  Tok.isNot(tok::eof))
200  Lex(Tok);
201  if (Tok.is(tok::r_paren))
202  Lex(Tok);
203  return _PragmaLexing.failed();
204  }
205 
206  if (Tok.hasUDSuffix()) {
207  Diag(Tok, diag::err_invalid_string_udl);
208  // Skip this token, and the ')', if present.
209  Lex(Tok);
210  if (Tok.is(tok::r_paren))
211  Lex(Tok);
212  return _PragmaLexing.failed();
213  }
214 
215  // Remember the string.
216  Token StrTok = Tok;
217 
218  // Read the ')'.
219  Lex(Tok);
220  if (Tok.isNot(tok::r_paren)) {
221  Diag(PragmaLoc, diag::err__Pragma_malformed);
222  return _PragmaLexing.failed();
223  }
224 
225  if (InMacroArgPreExpansion)
226  return;
227 
228  SourceLocation RParenLoc = Tok.getLocation();
229  std::string StrVal = getSpelling(StrTok);
230 
231  // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1:
232  // "The string literal is destringized by deleting any encoding prefix,
233  // deleting the leading and trailing double-quotes, replacing each escape
234  // sequence \" by a double-quote, and replacing each escape sequence \\ by a
235  // single backslash."
236  if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
237  (StrVal[0] == 'u' && StrVal[1] != '8'))
238  StrVal.erase(StrVal.begin());
239  else if (StrVal[0] == 'u')
240  StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
241 
242  if (StrVal[0] == 'R') {
243  // FIXME: C++11 does not specify how to handle raw-string-literals here.
244  // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
245  assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
246  "Invalid raw string token!");
247 
248  // Measure the length of the d-char-sequence.
249  unsigned NumDChars = 0;
250  while (StrVal[2 + NumDChars] != '(') {
251  assert(NumDChars < (StrVal.size() - 5) / 2 &&
252  "Invalid raw string token!");
253  ++NumDChars;
254  }
255  assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
256 
257  // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
258  // parens below.
259  StrVal.erase(0, 2 + NumDChars);
260  StrVal.erase(StrVal.size() - 1 - NumDChars);
261  } else {
262  assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
263  "Invalid string token!");
264 
265  // Remove escaped quotes and escapes.
266  unsigned ResultPos = 1;
267  for (unsigned i = 1, e = StrVal.size() - 1; i != e; ++i) {
268  // Skip escapes. \\ -> '\' and \" -> '"'.
269  if (StrVal[i] == '\\' && i + 1 < e &&
270  (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
271  ++i;
272  StrVal[ResultPos++] = StrVal[i];
273  }
274  StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
275  }
276 
277  // Remove the front quote, replacing it with a space, so that the pragma
278  // contents appear to have a space before them.
279  StrVal[0] = ' ';
280 
281  // Replace the terminating quote with a \n.
282  StrVal[StrVal.size()-1] = '\n';
283 
284  // Plop the string (including the newline and trailing null) into a buffer
285  // where we can lex it.
286  Token TmpTok;
287  TmpTok.startToken();
288  CreateString(StrVal, TmpTok);
289  SourceLocation TokLoc = TmpTok.getLocation();
290 
291  // Make and enter a lexer object so that we lex and expand the tokens just
292  // like any others.
293  Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
294  StrVal.size(), *this);
295 
296  EnterSourceFileWithLexer(TL, nullptr);
297 
298  // With everything set up, lex this as a #pragma directive.
299  HandlePragmaDirective(PragmaLoc, PIK__Pragma);
300 
301  // Finally, return whatever came after the pragma directive.
302  return Lex(Tok);
303 }
304 
305 /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
306 /// is not enclosed within a string literal.
307 void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
308  // Remember the pragma token location.
309  SourceLocation PragmaLoc = Tok.getLocation();
310 
311  // Read the '('.
312  Lex(Tok);
313  if (Tok.isNot(tok::l_paren)) {
314  Diag(PragmaLoc, diag::err__Pragma_malformed);
315  return;
316  }
317 
318  // Get the tokens enclosed within the __pragma(), as well as the final ')'.
319  SmallVector<Token, 32> PragmaToks;
320  int NumParens = 0;
321  Lex(Tok);
322  while (Tok.isNot(tok::eof)) {
323  PragmaToks.push_back(Tok);
324  if (Tok.is(tok::l_paren))
325  NumParens++;
326  else if (Tok.is(tok::r_paren) && NumParens-- == 0)
327  break;
328  Lex(Tok);
329  }
330 
331  if (Tok.is(tok::eof)) {
332  Diag(PragmaLoc, diag::err_unterminated___pragma);
333  return;
334  }
335 
336  PragmaToks.front().setFlag(Token::LeadingSpace);
337 
338  // Replace the ')' with an EOD to mark the end of the pragma.
339  PragmaToks.back().setKind(tok::eod);
340 
341  Token *TokArray = new Token[PragmaToks.size()];
342  std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
343 
344  // Push the tokens onto the stack.
345  EnterTokenStream(TokArray, PragmaToks.size(), true, true);
346 
347  // With everything set up, lex this as a #pragma directive.
348  HandlePragmaDirective(PragmaLoc, PIK___pragma);
349 
350  // Finally, return whatever came after the pragma directive.
351  return Lex(Tok);
352 }
353 
354 /// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
355 ///
357  // Don't honor the 'once' when handling the primary source file, unless
358  // this is a prefix to a TU, which indicates we're generating a PCH file.
359  if (isInPrimaryFile() && TUKind != TU_Prefix) {
360  Diag(OnceTok, diag::pp_pragma_once_in_main_file);
361  return;
362  }
363 
364  // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
365  // Mark the file as a once-only file now.
366  HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
367 }
368 
370  assert(CurPPLexer && "No current lexer?");
371  if (CurLexer)
372  CurLexer->ReadToEndOfLine();
373  else
374  CurPTHLexer->DiscardToEndOfLine();
375 }
376 
377 
378 /// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
379 ///
381  Token Tok;
382 
383  while (1) {
384  // Read the next token to poison. While doing this, pretend that we are
385  // skipping while reading the identifier to poison.
386  // This avoids errors on code like:
387  // #pragma GCC poison X
388  // #pragma GCC poison X
389  if (CurPPLexer) CurPPLexer->LexingRawMode = true;
390  LexUnexpandedToken(Tok);
391  if (CurPPLexer) CurPPLexer->LexingRawMode = false;
392 
393  // If we reached the end of line, we're done.
394  if (Tok.is(tok::eod)) return;
395 
396  // Can only poison identifiers.
397  if (Tok.isNot(tok::raw_identifier)) {
398  Diag(Tok, diag::err_pp_invalid_poison);
399  return;
400  }
401 
402  // Look up the identifier info for the token. We disabled identifier lookup
403  // by saying we're skipping contents, so we need to do this manually.
405 
406  // Already poisoned.
407  if (II->isPoisoned()) continue;
408 
409  // If this is a macro identifier, emit a warning.
410  if (isMacroDefined(II))
411  Diag(Tok, diag::pp_poisoning_existing_macro);
412 
413  // Finally, poison it!
414  II->setIsPoisoned();
415  if (II->isFromAST())
417  }
418 }
419 
420 /// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
421 /// that the whole directive has been parsed.
423  if (isInPrimaryFile()) {
424  Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
425  return;
426  }
427 
428  // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
430 
431  // Mark the file as a system header.
432  HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
433 
434 
435  PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
436  if (PLoc.isInvalid())
437  return;
438 
439  unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
440 
441  // Notify the client, if desired, that we are in a new source file.
442  if (Callbacks)
443  Callbacks->FileChanged(SysHeaderTok.getLocation(),
445 
446  // Emit a line marker. This will change any source locations from this point
447  // forward to realize they are in a system header.
448  // Create a line note with this information.
449  SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine()+1,
450  FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
451  /*IsSystem=*/true, /*IsExternC=*/false);
452 }
453 
454 /// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
455 ///
457  Token FilenameTok;
458  CurPPLexer->LexIncludeFilename(FilenameTok);
459 
460  // If the token kind is EOD, the error has already been diagnosed.
461  if (FilenameTok.is(tok::eod))
462  return;
463 
464  // Reserve a buffer to get the spelling.
465  SmallString<128> FilenameBuffer;
466  bool Invalid = false;
467  StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
468  if (Invalid)
469  return;
470 
471  bool isAngled =
473  // If GetIncludeFilenameSpelling set the start ptr to null, there was an
474  // error.
475  if (Filename.empty())
476  return;
477 
478  // Search include directories for this file.
479  const DirectoryLookup *CurDir;
480  const FileEntry *File =
481  LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
482  nullptr, CurDir, nullptr, nullptr, nullptr);
483  if (!File) {
484  if (!SuppressIncludeNotFoundError)
485  Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
486  return;
487  }
488 
489  const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
490 
491  // If this file is older than the file it depends on, emit a diagnostic.
492  if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
493  // Lex tokens at the end of the message and include them in the message.
494  std::string Message;
495  Lex(DependencyTok);
496  while (DependencyTok.isNot(tok::eod)) {
497  Message += getSpelling(DependencyTok) + " ";
498  Lex(DependencyTok);
499  }
500 
501  // Remove the trailing ' ' if present.
502  if (!Message.empty())
503  Message.erase(Message.end()-1);
504  Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
505  }
506 }
507 
508 /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
509 /// Return the IdentifierInfo* associated with the macro to push or pop.
511  // Remember the pragma token location.
512  Token PragmaTok = Tok;
513 
514  // Read the '('.
515  Lex(Tok);
516  if (Tok.isNot(tok::l_paren)) {
517  Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
518  << getSpelling(PragmaTok);
519  return nullptr;
520  }
521 
522  // Read the macro name string.
523  Lex(Tok);
524  if (Tok.isNot(tok::string_literal)) {
525  Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
526  << getSpelling(PragmaTok);
527  return nullptr;
528  }
529 
530  if (Tok.hasUDSuffix()) {
531  Diag(Tok, diag::err_invalid_string_udl);
532  return nullptr;
533  }
534 
535  // Remember the macro string.
536  std::string StrVal = getSpelling(Tok);
537 
538  // Read the ')'.
539  Lex(Tok);
540  if (Tok.isNot(tok::r_paren)) {
541  Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
542  << getSpelling(PragmaTok);
543  return nullptr;
544  }
545 
546  assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
547  "Invalid string token!");
548 
549  // Create a Token from the string.
550  Token MacroTok;
551  MacroTok.startToken();
552  MacroTok.setKind(tok::raw_identifier);
553  CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
554 
555  // Get the IdentifierInfo of MacroToPushTok.
556  return LookUpIdentifierInfo(MacroTok);
557 }
558 
559 /// \brief Handle \#pragma push_macro.
560 ///
561 /// The syntax is:
562 /// \code
563 /// #pragma push_macro("macro")
564 /// \endcode
566  // Parse the pragma directive and get the macro IdentifierInfo*.
567  IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
568  if (!IdentInfo) return;
569 
570  // Get the MacroInfo associated with IdentInfo.
571  MacroInfo *MI = getMacroInfo(IdentInfo);
572 
573  if (MI) {
574  // Allow the original MacroInfo to be redefined later.
576  }
577 
578  // Push the cloned MacroInfo so we can retrieve it later.
579  PragmaPushMacroInfo[IdentInfo].push_back(MI);
580 }
581 
582 /// \brief Handle \#pragma pop_macro.
583 ///
584 /// The syntax is:
585 /// \code
586 /// #pragma pop_macro("macro")
587 /// \endcode
589  SourceLocation MessageLoc = PopMacroTok.getLocation();
590 
591  // Parse the pragma directive and get the macro IdentifierInfo*.
592  IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
593  if (!IdentInfo) return;
594 
595  // Find the vector<MacroInfo*> associated with the macro.
596  llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
597  PragmaPushMacroInfo.find(IdentInfo);
598  if (iter != PragmaPushMacroInfo.end()) {
599  // Forget the MacroInfo currently associated with IdentInfo.
600  if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
601  if (MI->isWarnIfUnused())
602  WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
603  appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
604  }
605 
606  // Get the MacroInfo we want to reinstall.
607  MacroInfo *MacroToReInstall = iter->second.back();
608 
609  if (MacroToReInstall)
610  // Reinstall the previously pushed macro.
611  appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
612 
613  // Pop PragmaPushMacroInfo stack.
614  iter->second.pop_back();
615  if (iter->second.size() == 0)
616  PragmaPushMacroInfo.erase(iter);
617  } else {
618  Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
619  << IdentInfo->getName();
620  }
621 }
622 
624  // We will either get a quoted filename or a bracketed filename, and we
625  // have to track which we got. The first filename is the source name,
626  // and the second name is the mapped filename. If the first is quoted,
627  // the second must be as well (cannot mix and match quotes and brackets).
628 
629  // Get the open paren
630  Lex(Tok);
631  if (Tok.isNot(tok::l_paren)) {
632  Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
633  return;
634  }
635 
636  // We expect either a quoted string literal, or a bracketed name
637  Token SourceFilenameTok;
638  CurPPLexer->LexIncludeFilename(SourceFilenameTok);
639  if (SourceFilenameTok.is(tok::eod)) {
640  // The diagnostic has already been handled
641  return;
642  }
643 
644  StringRef SourceFileName;
645  SmallString<128> FileNameBuffer;
646  if (SourceFilenameTok.is(tok::string_literal) ||
647  SourceFilenameTok.is(tok::angle_string_literal)) {
648  SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
649  } else if (SourceFilenameTok.is(tok::less)) {
650  // This could be a path instead of just a name
651  FileNameBuffer.push_back('<');
653  if (ConcatenateIncludeName(FileNameBuffer, End))
654  return; // Diagnostic already emitted
655  SourceFileName = FileNameBuffer;
656  } else {
657  Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
658  return;
659  }
660  FileNameBuffer.clear();
661 
662  // Now we expect a comma, followed by another include name
663  Lex(Tok);
664  if (Tok.isNot(tok::comma)) {
665  Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
666  return;
667  }
668 
669  Token ReplaceFilenameTok;
670  CurPPLexer->LexIncludeFilename(ReplaceFilenameTok);
671  if (ReplaceFilenameTok.is(tok::eod)) {
672  // The diagnostic has already been handled
673  return;
674  }
675 
676  StringRef ReplaceFileName;
677  if (ReplaceFilenameTok.is(tok::string_literal) ||
678  ReplaceFilenameTok.is(tok::angle_string_literal)) {
679  ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
680  } else if (ReplaceFilenameTok.is(tok::less)) {
681  // This could be a path instead of just a name
682  FileNameBuffer.push_back('<');
684  if (ConcatenateIncludeName(FileNameBuffer, End))
685  return; // Diagnostic already emitted
686  ReplaceFileName = FileNameBuffer;
687  } else {
688  Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
689  return;
690  }
691 
692  // Finally, we expect the closing paren
693  Lex(Tok);
694  if (Tok.isNot(tok::r_paren)) {
695  Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
696  return;
697  }
698 
699  // Now that we have the source and target filenames, we need to make sure
700  // they're both of the same type (angled vs non-angled)
701  StringRef OriginalSource = SourceFileName;
702 
703  bool SourceIsAngled =
704  GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
705  SourceFileName);
706  bool ReplaceIsAngled =
707  GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
708  ReplaceFileName);
709  if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
710  (SourceIsAngled != ReplaceIsAngled)) {
711  unsigned int DiagID;
712  if (SourceIsAngled)
713  DiagID = diag::warn_pragma_include_alias_mismatch_angle;
714  else
715  DiagID = diag::warn_pragma_include_alias_mismatch_quote;
716 
717  Diag(SourceFilenameTok.getLocation(), DiagID)
718  << SourceFileName
719  << ReplaceFileName;
720 
721  return;
722  }
723 
724  // Now we can let the include handler know about this mapping
725  getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
726 }
727 
728 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
729 /// If 'Namespace' is non-null, then it is a token required to exist on the
730 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
731 void Preprocessor::AddPragmaHandler(StringRef Namespace,
732  PragmaHandler *Handler) {
733  PragmaNamespace *InsertNS = PragmaHandlers.get();
734 
735  // If this is specified to be in a namespace, step down into it.
736  if (!Namespace.empty()) {
737  // If there is already a pragma handler with the name of this namespace,
738  // we either have an error (directive with the same name as a namespace) or
739  // we already have the namespace to insert into.
740  if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
741  InsertNS = Existing->getIfNamespace();
742  assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
743  " handler with the same name!");
744  } else {
745  // Otherwise, this namespace doesn't exist yet, create and insert the
746  // handler for it.
747  InsertNS = new PragmaNamespace(Namespace);
748  PragmaHandlers->AddPragma(InsertNS);
749  }
750  }
751 
752  // Check to make sure we don't already have a pragma for this identifier.
753  assert(!InsertNS->FindHandler(Handler->getName()) &&
754  "Pragma handler already exists for this identifier!");
755  InsertNS->AddPragma(Handler);
756 }
757 
758 /// RemovePragmaHandler - Remove the specific pragma handler from the
759 /// preprocessor. If \arg Namespace is non-null, then it should be the
760 /// namespace that \arg Handler was added to. It is an error to remove
761 /// a handler that has not been registered.
762 void Preprocessor::RemovePragmaHandler(StringRef Namespace,
763  PragmaHandler *Handler) {
764  PragmaNamespace *NS = PragmaHandlers.get();
765 
766  // If this is specified to be in a namespace, step down into it.
767  if (!Namespace.empty()) {
768  PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
769  assert(Existing && "Namespace containing handler does not exist!");
770 
771  NS = Existing->getIfNamespace();
772  assert(NS && "Invalid namespace, registered as a regular pragma handler!");
773  }
774 
775  NS->RemovePragmaHandler(Handler);
776 
777  // If this is a non-default namespace and it is now empty, remove it.
778  if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
779  PragmaHandlers->RemovePragmaHandler(NS);
780  delete NS;
781  }
782 }
783 
785  Token Tok;
786  LexUnexpandedToken(Tok);
787 
788  if (Tok.isNot(tok::identifier)) {
789  Diag(Tok, diag::ext_on_off_switch_syntax);
790  return true;
791  }
792  IdentifierInfo *II = Tok.getIdentifierInfo();
793  if (II->isStr("ON"))
794  Result = tok::OOS_ON;
795  else if (II->isStr("OFF"))
796  Result = tok::OOS_OFF;
797  else if (II->isStr("DEFAULT"))
798  Result = tok::OOS_DEFAULT;
799  else {
800  Diag(Tok, diag::ext_on_off_switch_syntax);
801  return true;
802  }
803 
804  // Verify that this is followed by EOD.
805  LexUnexpandedToken(Tok);
806  if (Tok.isNot(tok::eod))
807  Diag(Tok, diag::ext_pragma_syntax_eod);
808  return false;
809 }
810 
811 namespace {
812 /// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
813 struct PragmaOnceHandler : public PragmaHandler {
814  PragmaOnceHandler() : PragmaHandler("once") {}
815  void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
816  Token &OnceTok) override {
817  PP.CheckEndOfDirective("pragma once");
818  PP.HandlePragmaOnce(OnceTok);
819  }
820 };
821 
822 /// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
823 /// rest of the line is not lexed.
824 struct PragmaMarkHandler : public PragmaHandler {
825  PragmaMarkHandler() : PragmaHandler("mark") {}
826  void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
827  Token &MarkTok) override {
828  PP.HandlePragmaMark();
829  }
830 };
831 
832 /// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
833 struct PragmaPoisonHandler : public PragmaHandler {
834  PragmaPoisonHandler() : PragmaHandler("poison") {}
835  void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
836  Token &PoisonTok) override {
837  PP.HandlePragmaPoison(PoisonTok);
838  }
839 };
840 
841 /// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
842 /// as a system header, which silences warnings in it.
843 struct PragmaSystemHeaderHandler : public PragmaHandler {
844  PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
845  void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
846  Token &SHToken) override {
847  PP.HandlePragmaSystemHeader(SHToken);
848  PP.CheckEndOfDirective("pragma");
849  }
850 };
851 struct PragmaDependencyHandler : public PragmaHandler {
852  PragmaDependencyHandler() : PragmaHandler("dependency") {}
853  void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
854  Token &DepToken) override {
855  PP.HandlePragmaDependency(DepToken);
856  }
857 };
858 
859 struct PragmaDebugHandler : public PragmaHandler {
860  PragmaDebugHandler() : PragmaHandler("__debug") {}
861  void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
862  Token &DepToken) override {
863  Token Tok;
864  PP.LexUnexpandedToken(Tok);
865  if (Tok.isNot(tok::identifier)) {
866  PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
867  return;
868  }
869  IdentifierInfo *II = Tok.getIdentifierInfo();
870 
871  if (II->isStr("assert")) {
872  llvm_unreachable("This is an assertion!");
873  } else if (II->isStr("crash")) {
874  LLVM_BUILTIN_TRAP;
875  } else if (II->isStr("parser_crash")) {
876  Token Crasher;
877  Crasher.startToken();
878  Crasher.setKind(tok::annot_pragma_parser_crash);
880  PP.EnterToken(Crasher);
881  } else if (II->isStr("dump")) {
882  Token Identifier;
883  PP.LexUnexpandedToken(Identifier);
884  if (auto *DumpII = Identifier.getIdentifierInfo()) {
885  Token DumpAnnot;
886  DumpAnnot.startToken();
887  DumpAnnot.setKind(tok::annot_pragma_dump);
888  DumpAnnot.setAnnotationRange(
889  SourceRange(Tok.getLocation(), Identifier.getLocation()));
890  DumpAnnot.setAnnotationValue(DumpII);
892  PP.EnterToken(DumpAnnot);
893  } else {
894  PP.Diag(Identifier, diag::warn_pragma_debug_missing_argument)
895  << II->getName();
896  }
897  } else if (II->isStr("llvm_fatal_error")) {
898  llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
899  } else if (II->isStr("llvm_unreachable")) {
900  llvm_unreachable("#pragma clang __debug llvm_unreachable");
901  } else if (II->isStr("macro")) {
902  Token MacroName;
903  PP.LexUnexpandedToken(MacroName);
904  auto *MacroII = MacroName.getIdentifierInfo();
905  if (MacroII)
906  PP.dumpMacroInfo(MacroII);
907  else
908  PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument)
909  << II->getName();
910  } else if (II->isStr("overflow_stack")) {
911  DebugOverflowStack();
912  } else if (II->isStr("handle_crash")) {
913  llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
914  if (CRC)
915  CRC->HandleCrash();
916  } else if (II->isStr("captured")) {
917  HandleCaptured(PP);
918  } else {
919  PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
920  << II->getName();
921  }
922 
923  PPCallbacks *Callbacks = PP.getPPCallbacks();
924  if (Callbacks)
925  Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
926  }
927 
928  void HandleCaptured(Preprocessor &PP) {
929  // Skip if emitting preprocessed output.
930  if (PP.isPreprocessedOutput())
931  return;
932 
933  Token Tok;
934  PP.LexUnexpandedToken(Tok);
935 
936  if (Tok.isNot(tok::eod)) {
937  PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
938  << "pragma clang __debug captured";
939  return;
940  }
941 
942  SourceLocation NameLoc = Tok.getLocation();
944  PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
945  Toks[0].startToken();
946  Toks[0].setKind(tok::annot_pragma_captured);
947  Toks[0].setLocation(NameLoc);
948 
949  PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
950  }
951 
952 // Disable MSVC warning about runtime stack overflow.
953 #ifdef _MSC_VER
954  #pragma warning(disable : 4717)
955 #endif
956  static void DebugOverflowStack() {
957  void (*volatile Self)() = DebugOverflowStack;
958  Self();
959  }
960 #ifdef _MSC_VER
961  #pragma warning(default : 4717)
962 #endif
963 
964 };
965 
966 /// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
967 struct PragmaDiagnosticHandler : public PragmaHandler {
968 private:
969  const char *Namespace;
970 public:
971  explicit PragmaDiagnosticHandler(const char *NS) :
972  PragmaHandler("diagnostic"), Namespace(NS) {}
973  void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
974  Token &DiagToken) override {
975  SourceLocation DiagLoc = DiagToken.getLocation();
976  Token Tok;
977  PP.LexUnexpandedToken(Tok);
978  if (Tok.isNot(tok::identifier)) {
979  PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
980  return;
981  }
982  IdentifierInfo *II = Tok.getIdentifierInfo();
983  PPCallbacks *Callbacks = PP.getPPCallbacks();
984 
985  if (II->isStr("pop")) {
986  if (!PP.getDiagnostics().popMappings(DiagLoc))
987  PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
988  else if (Callbacks)
989  Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
990  return;
991  } else if (II->isStr("push")) {
992  PP.getDiagnostics().pushMappings(DiagLoc);
993  if (Callbacks)
994  Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
995  return;
996  }
997 
998  diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
999  .Case("ignored", diag::Severity::Ignored)
1000  .Case("warning", diag::Severity::Warning)
1001  .Case("error", diag::Severity::Error)
1002  .Case("fatal", diag::Severity::Fatal)
1003  .Default(diag::Severity());
1004 
1005  if (SV == diag::Severity()) {
1006  PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1007  return;
1008  }
1009 
1010  PP.LexUnexpandedToken(Tok);
1011  SourceLocation StringLoc = Tok.getLocation();
1012 
1013  std::string WarningName;
1014  if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
1015  /*MacroExpansion=*/false))
1016  return;
1017 
1018  if (Tok.isNot(tok::eod)) {
1019  PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1020  return;
1021  }
1022 
1023  if (WarningName.size() < 3 || WarningName[0] != '-' ||
1024  (WarningName[1] != 'W' && WarningName[1] != 'R')) {
1025  PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
1026  return;
1027  }
1028 
1029  diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1031  StringRef Group = StringRef(WarningName).substr(2);
1032  bool unknownDiag = false;
1033  if (Group == "everything") {
1034  // Special handling for pragma clang diagnostic ... "-Weverything".
1035  // There is no formal group named "everything", so there has to be a
1036  // special case for it.
1037  PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc);
1038  } else
1039  unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV,
1040  DiagLoc);
1041  if (unknownDiag)
1042  PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1043  << WarningName;
1044  else if (Callbacks)
1045  Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
1046  }
1047 };
1048 
1049 /// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1050 /// diagnostics, so we don't really implement this pragma. We parse it and
1051 /// ignore it to avoid -Wunknown-pragma warnings.
1052 struct PragmaWarningHandler : public PragmaHandler {
1053  PragmaWarningHandler() : PragmaHandler("warning") {}
1054 
1055  void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1056  Token &Tok) override {
1057  // Parse things like:
1058  // warning(push, 1)
1059  // warning(pop)
1060  // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
1061  SourceLocation DiagLoc = Tok.getLocation();
1062  PPCallbacks *Callbacks = PP.getPPCallbacks();
1063 
1064  PP.Lex(Tok);
1065  if (Tok.isNot(tok::l_paren)) {
1066  PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1067  return;
1068  }
1069 
1070  PP.Lex(Tok);
1071  IdentifierInfo *II = Tok.getIdentifierInfo();
1072 
1073  if (II && II->isStr("push")) {
1074  // #pragma warning( push[ ,n ] )
1075  int Level = -1;
1076  PP.Lex(Tok);
1077  if (Tok.is(tok::comma)) {
1078  PP.Lex(Tok);
1079  uint64_t Value;
1080  if (Tok.is(tok::numeric_constant) &&
1081  PP.parseSimpleIntegerLiteral(Tok, Value))
1082  Level = int(Value);
1083  if (Level < 0 || Level > 4) {
1084  PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1085  return;
1086  }
1087  }
1088  if (Callbacks)
1089  Callbacks->PragmaWarningPush(DiagLoc, Level);
1090  } else if (II && II->isStr("pop")) {
1091  // #pragma warning( pop )
1092  PP.Lex(Tok);
1093  if (Callbacks)
1094  Callbacks->PragmaWarningPop(DiagLoc);
1095  } else {
1096  // #pragma warning( warning-specifier : warning-number-list
1097  // [; warning-specifier : warning-number-list...] )
1098  while (true) {
1099  II = Tok.getIdentifierInfo();
1100  if (!II && !Tok.is(tok::numeric_constant)) {
1101  PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1102  return;
1103  }
1104 
1105  // Figure out which warning specifier this is.
1106  bool SpecifierValid;
1107  StringRef Specifier;
1108  llvm::SmallString<1> SpecifierBuf;
1109  if (II) {
1110  Specifier = II->getName();
1111  SpecifierValid = llvm::StringSwitch<bool>(Specifier)
1112  .Cases("default", "disable", "error", "once",
1113  "suppress", true)
1114  .Default(false);
1115  // If we read a correct specifier, snatch next token (that should be
1116  // ":", checked later).
1117  if (SpecifierValid)
1118  PP.Lex(Tok);
1119  } else {
1120  // Token is a numeric constant. It should be either 1, 2, 3 or 4.
1121  uint64_t Value;
1122  Specifier = PP.getSpelling(Tok, SpecifierBuf);
1123  if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
1124  SpecifierValid = (Value >= 1) && (Value <= 4);
1125  } else
1126  SpecifierValid = false;
1127  // Next token already snatched by parseSimpleIntegerLiteral.
1128  }
1129 
1130  if (!SpecifierValid) {
1131  PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1132  return;
1133  }
1134  if (Tok.isNot(tok::colon)) {
1135  PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1136  return;
1137  }
1138 
1139  // Collect the warning ids.
1140  SmallVector<int, 4> Ids;
1141  PP.Lex(Tok);
1142  while (Tok.is(tok::numeric_constant)) {
1143  uint64_t Value;
1144  if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
1145  Value > INT_MAX) {
1146  PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1147  return;
1148  }
1149  Ids.push_back(int(Value));
1150  }
1151  if (Callbacks)
1152  Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1153 
1154  // Parse the next specifier if there is a semicolon.
1155  if (Tok.isNot(tok::semi))
1156  break;
1157  PP.Lex(Tok);
1158  }
1159  }
1160 
1161  if (Tok.isNot(tok::r_paren)) {
1162  PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1163  return;
1164  }
1165 
1166  PP.Lex(Tok);
1167  if (Tok.isNot(tok::eod))
1168  PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1169  }
1170 };
1171 
1172 /// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
1173 struct PragmaIncludeAliasHandler : public PragmaHandler {
1174  PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
1175  void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1176  Token &IncludeAliasTok) override {
1177  PP.HandlePragmaIncludeAlias(IncludeAliasTok);
1178  }
1179 };
1180 
1181 /// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1182 /// extension. The syntax is:
1183 /// \code
1184 /// #pragma message(string)
1185 /// \endcode
1186 /// OR, in GCC mode:
1187 /// \code
1188 /// #pragma message string
1189 /// \endcode
1190 /// string is a string, which is fully macro expanded, and permits string
1191 /// concatenation, embedded escape characters, etc... See MSDN for more details.
1192 /// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1193 /// form as \#pragma message.
1194 struct PragmaMessageHandler : public PragmaHandler {
1195 private:
1197  const StringRef Namespace;
1198 
1199  static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1200  bool PragmaNameOnly = false) {
1201  switch (Kind) {
1203  return PragmaNameOnly ? "message" : "pragma message";
1205  return PragmaNameOnly ? "warning" : "pragma warning";
1207  return PragmaNameOnly ? "error" : "pragma error";
1208  }
1209  llvm_unreachable("Unknown PragmaMessageKind!");
1210  }
1211 
1212 public:
1213  PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1214  StringRef Namespace = StringRef())
1215  : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), Namespace(Namespace) {}
1216 
1217  void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1218  Token &Tok) override {
1219  SourceLocation MessageLoc = Tok.getLocation();
1220  PP.Lex(Tok);
1221  bool ExpectClosingParen = false;
1222  switch (Tok.getKind()) {
1223  case tok::l_paren:
1224  // We have a MSVC style pragma message.
1225  ExpectClosingParen = true;
1226  // Read the string.
1227  PP.Lex(Tok);
1228  break;
1229  case tok::string_literal:
1230  // We have a GCC style pragma message, and we just read the string.
1231  break;
1232  default:
1233  PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1234  return;
1235  }
1236 
1237  std::string MessageString;
1238  if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1239  /*MacroExpansion=*/true))
1240  return;
1241 
1242  if (ExpectClosingParen) {
1243  if (Tok.isNot(tok::r_paren)) {
1244  PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1245  return;
1246  }
1247  PP.Lex(Tok); // eat the r_paren.
1248  }
1249 
1250  if (Tok.isNot(tok::eod)) {
1251  PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1252  return;
1253  }
1254 
1255  // Output the message.
1256  PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1257  ? diag::err_pragma_message
1258  : diag::warn_pragma_message) << MessageString;
1259 
1260  // If the pragma is lexically sound, notify any interested PPCallbacks.
1261  if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1262  Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
1263  }
1264 };
1265 
1266 /// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
1267 /// macro on the top of the stack.
1268 struct PragmaPushMacroHandler : public PragmaHandler {
1269  PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
1270  void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1271  Token &PushMacroTok) override {
1272  PP.HandlePragmaPushMacro(PushMacroTok);
1273  }
1274 };
1275 
1276 
1277 /// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
1278 /// macro to the value on the top of the stack.
1279 struct PragmaPopMacroHandler : public PragmaHandler {
1280  PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
1281  void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1282  Token &PopMacroTok) override {
1283  PP.HandlePragmaPopMacro(PopMacroTok);
1284  }
1285 };
1286 
1287 // Pragma STDC implementations.
1288 
1289 /// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
1290 struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
1291  PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
1292  void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1293  Token &Tok) override {
1294  tok::OnOffSwitch OOS;
1295  if (PP.LexOnOffSwitch(OOS))
1296  return;
1297  if (OOS == tok::OOS_ON)
1298  PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
1299  }
1300 };
1301 
1302 /// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
1303 struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
1304  PragmaSTDC_CX_LIMITED_RANGEHandler()
1305  : PragmaHandler("CX_LIMITED_RANGE") {}
1306  void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1307  Token &Tok) override {
1308  tok::OnOffSwitch OOS;
1309  PP.LexOnOffSwitch(OOS);
1310  }
1311 };
1312 
1313 /// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
1314 struct PragmaSTDC_UnknownHandler : public PragmaHandler {
1315  PragmaSTDC_UnknownHandler() {}
1316  void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1317  Token &UnknownTok) override {
1318  // C99 6.10.6p2, unknown forms are not allowed.
1319  PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
1320  }
1321 };
1322 
1323 /// PragmaARCCFCodeAuditedHandler -
1324 /// \#pragma clang arc_cf_code_audited begin/end
1325 struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1326  PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
1327  void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1328  Token &NameTok) override {
1329  SourceLocation Loc = NameTok.getLocation();
1330  bool IsBegin;
1331 
1332  Token Tok;
1333 
1334  // Lex the 'begin' or 'end'.
1335  PP.LexUnexpandedToken(Tok);
1336  const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1337  if (BeginEnd && BeginEnd->isStr("begin")) {
1338  IsBegin = true;
1339  } else if (BeginEnd && BeginEnd->isStr("end")) {
1340  IsBegin = false;
1341  } else {
1342  PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1343  return;
1344  }
1345 
1346  // Verify that this is followed by EOD.
1347  PP.LexUnexpandedToken(Tok);
1348  if (Tok.isNot(tok::eod))
1349  PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1350 
1351  // The start location of the active audit.
1353 
1354  // The start location we want after processing this.
1355  SourceLocation NewLoc;
1356 
1357  if (IsBegin) {
1358  // Complain about attempts to re-enter an audit.
1359  if (BeginLoc.isValid()) {
1360  PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1361  PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1362  }
1363  NewLoc = Loc;
1364  } else {
1365  // Complain about attempts to leave an audit that doesn't exist.
1366  if (!BeginLoc.isValid()) {
1367  PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1368  return;
1369  }
1370  NewLoc = SourceLocation();
1371  }
1372 
1373  PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1374  }
1375 };
1376 
1377 /// PragmaAssumeNonNullHandler -
1378 /// \#pragma clang assume_nonnull begin/end
1379 struct PragmaAssumeNonNullHandler : public PragmaHandler {
1380  PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
1381  void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1382  Token &NameTok) override {
1383  SourceLocation Loc = NameTok.getLocation();
1384  bool IsBegin;
1385 
1386  Token Tok;
1387 
1388  // Lex the 'begin' or 'end'.
1389  PP.LexUnexpandedToken(Tok);
1390  const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1391  if (BeginEnd && BeginEnd->isStr("begin")) {
1392  IsBegin = true;
1393  } else if (BeginEnd && BeginEnd->isStr("end")) {
1394  IsBegin = false;
1395  } else {
1396  PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
1397  return;
1398  }
1399 
1400  // Verify that this is followed by EOD.
1401  PP.LexUnexpandedToken(Tok);
1402  if (Tok.isNot(tok::eod))
1403  PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1404 
1405  // The start location of the active audit.
1406  SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
1407 
1408  // The start location we want after processing this.
1409  SourceLocation NewLoc;
1410 
1411  if (IsBegin) {
1412  // Complain about attempts to re-enter an audit.
1413  if (BeginLoc.isValid()) {
1414  PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
1415  PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1416  }
1417  NewLoc = Loc;
1418  } else {
1419  // Complain about attempts to leave an audit that doesn't exist.
1420  if (!BeginLoc.isValid()) {
1421  PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
1422  return;
1423  }
1424  NewLoc = SourceLocation();
1425  }
1426 
1427  PP.setPragmaAssumeNonNullLoc(NewLoc);
1428  }
1429 };
1430 
1431 /// \brief Handle "\#pragma region [...]"
1432 ///
1433 /// The syntax is
1434 /// \code
1435 /// #pragma region [optional name]
1436 /// #pragma endregion [optional comment]
1437 /// \endcode
1438 ///
1439 /// \note This is
1440 /// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1441 /// pragma, just skipped by compiler.
1442 struct PragmaRegionHandler : public PragmaHandler {
1443  PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) { }
1444 
1445  void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1446  Token &NameTok) override {
1447  // #pragma region: endregion matches can be verified
1448  // __pragma(region): no sense, but ignored by msvc
1449  // _Pragma is not valid for MSVC, but there isn't any point
1450  // to handle a _Pragma differently.
1451  }
1452 };
1453 
1454 } // end anonymous namespace
1455 
1456 
1457 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
1458 /// \#pragma GCC poison/system_header/dependency and \#pragma once.
1459 void Preprocessor::RegisterBuiltinPragmas() {
1460  AddPragmaHandler(new PragmaOnceHandler());
1461  AddPragmaHandler(new PragmaMarkHandler());
1462  AddPragmaHandler(new PragmaPushMacroHandler());
1463  AddPragmaHandler(new PragmaPopMacroHandler());
1464  AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
1465 
1466  // #pragma GCC ...
1467  AddPragmaHandler("GCC", new PragmaPoisonHandler());
1468  AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1469  AddPragmaHandler("GCC", new PragmaDependencyHandler());
1470  AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
1471  AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1472  "GCC"));
1473  AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1474  "GCC"));
1475  // #pragma clang ...
1476  AddPragmaHandler("clang", new PragmaPoisonHandler());
1477  AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
1478  AddPragmaHandler("clang", new PragmaDebugHandler());
1479  AddPragmaHandler("clang", new PragmaDependencyHandler());
1480  AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
1481  AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
1482  AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
1483 
1484  AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1485  AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
1486  AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
1487 
1488  // MS extensions.
1489  if (LangOpts.MicrosoftExt) {
1490  AddPragmaHandler(new PragmaWarningHandler());
1491  AddPragmaHandler(new PragmaIncludeAliasHandler());
1492  AddPragmaHandler(new PragmaRegionHandler("region"));
1493  AddPragmaHandler(new PragmaRegionHandler("endregion"));
1494  }
1495 
1496  // Pragmas added by plugins
1499  it != ie; ++it) {
1500  AddPragmaHandler(it->instantiate().release());
1501  }
1502 }
1503 
1504 /// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
1505 /// warn about those pragmas being unknown.
1508  // Also ignore all pragmas in all namespaces created
1509  // in Preprocessor::RegisterBuiltinPragmas().
1510  AddPragmaHandler("GCC", new EmptyPragmaHandler());
1511  AddPragmaHandler("clang", new EmptyPragmaHandler());
1512  if (PragmaHandler *NS = PragmaHandlers->FindHandler("STDC")) {
1513  // Preprocessor::RegisterBuiltinPragmas() already registers
1514  // PragmaSTDC_UnknownHandler as the empty handler, so remove it first,
1515  // otherwise there will be an assert about a duplicate handler.
1516  PragmaNamespace *STDCNamespace = NS->getIfNamespace();
1517  assert(STDCNamespace &&
1518  "Invalid namespace, registered as a regular pragma handler!");
1519  if (PragmaHandler *Existing = STDCNamespace->FindHandler("", false)) {
1520  RemovePragmaHandler("STDC", Existing);
1521  delete Existing;
1522  }
1523  }
1524  AddPragmaHandler("STDC", new EmptyPragmaHandler());
1525 }
A diagnostic that indicates a problem or potential problem.
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition: Token.h:265
StringRef getName() const
Definition: Pragma.h:66
bool isPoisoned() const
Return true if this token has been poisoned.
void setSeverityForAll(diag::Flavor Flavor, diag::Severity Map, SourceLocation Loc=SourceLocation())
Add the specified mapping to all diagnostics of the specified flavor.
Definition: Diagnostic.cpp:325
llvm::BumpPtrAllocator & getPreprocessorAllocator()
Definition: Preprocessor.h:701
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens...
Definition: Lexer.h:46
virtual void PragmaDiagnosticPop(SourceLocation Loc, StringRef Namespace)
Callback invoked when a #pragma gcc diagnostic pop directive is read.
Definition: PPCallbacks.h:212
bool ConcatenateIncludeName(SmallString< 128 > &FilenameBuffer, SourceLocation &End)
Handle cases where the #include name is expanded from a macro as multiple tokens, which need to be gl...
void setChangedSinceDeserialization()
Note that this identifier has changed since it was loaded from an AST file.
void pushMappings(SourceLocation Loc)
Copies the current DiagMappings and pushes the new copy onto the top of the stack.
Definition: Diagnostic.cpp:99
Defines the clang::FileManager interface and associated types.
void AddPragmaHandler(StringRef Namespace, PragmaHandler *Handler)
Add the specified pragma handler to this preprocessor.
Definition: Pragma.cpp:731
#pragma GCC error has been invoked.
Definition: PPCallbacks.h:192
bool isInvalid() const
Return true if this object is invalid or uninitialized.
Defines the SourceManager interface.
virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken)=0
void dumpMacroInfo(const IdentifierInfo *II)
The translation unit is a prefix to a translation unit, and is not complete.
Definition: LangOptions.h:177
Defines the clang::MacroInfo and clang::MacroDirective classes.
The pragma was introduced via the Microsoft __pragma(token-string).
Definition: Pragma.h:47
void AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID)
Add a line note to the line table for the FileID and offset specified by Loc.
virtual void PragmaWarningPush(SourceLocation Loc, int Level)
Callback invoked when a #pragma warning(push) directive is read.
Definition: PPCallbacks.h:233
virtual void PragmaWarningPop(SourceLocation Loc)
Callback invoked when a #pragma warning(pop) directive is read.
Definition: PPCallbacks.h:237
bool parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value)
Parses a simple integer literal to get its numeric value.
void EnterToken(const Token &Tok)
Enters a token in the token stream to be lexed next.
void IgnorePragmas()
Install empty handlers for all pragmas (making them ignored).
Definition: Pragma.cpp:1506
Severity
Enum values that allow the client to map NOTEs, WARNINGs, and EXTENSIONs to either Ignore (nothing)...
Definition: DiagnosticIDs.h:62
bool isStringLiteral(TokenKind K)
Return true if this is a C or C++ string-literal (or C++11 user-defined-string-literal) token...
Definition: TokenKinds.h:79
The pragma was introduced via the C99 _Pragma(string-literal).
Definition: Pragma.h:41
bool isInPrimaryFile() const
Return true if we're in the top-level file, not in a #include.
static Lexer * Create_PragmaLexer(SourceLocation SpellingLoc, SourceLocation ExpansionLocStart, SourceLocation ExpansionLocEnd, unsigned TokLen, Preprocessor &PP)
Create_PragmaLexer: Lexer constructor - Create a new lexer object for _Pragma expansion.
Definition: Lexer.cpp:164
This interface provides a way to observe the actions of the preprocessor as it does its thing...
Definition: PPCallbacks.h:38
iterator begin() const
Definition: Type.h:4235
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
SourceLocation getPragmaAssumeNonNullLoc() const
The location of the currently-active #pragma clang assume_nonnull begin.
DefMacroDirective * appendDefMacroDirective(IdentifierInfo *II, MacroInfo *MI, SourceLocation Loc)
Definition: Preprocessor.h:879
One of these records is kept for each identifier that is lexed.
virtual void PragmaDebug(SourceLocation Loc, StringRef DebugType)
Callback invoked when a #pragma clang __debug directive is read.
Definition: PPCallbacks.h:180
bool ParsingPreprocessorDirective
True when parsing #XXX; turns '\n' into a tok::eod token.
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:4549
bool isFromAST() const
Return true if the identifier in its current state was loaded from an AST file.
void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override
Definition: Pragma.cpp:78
EmptyPragmaHandler(StringRef Name=StringRef())
Definition: Pragma.cpp:41
void AddPragma(PragmaHandler *Handler)
AddPragma - Add a pragma to this namespace.
Definition: Pragma.cpp:66
void HandlePragmaPushMacro(Token &Tok)
Handle #pragma push_macro.
Definition: Pragma.cpp:565
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
Definition: Preprocessor.h:858
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
void setKind(tok::TokenKind K)
Definition: Token.h:90
void CheckEndOfDirective(const char *Directive, bool EnableMacros=false)
Ensure that the next token is a tok::eod token.
void AddIncludeAlias(StringRef Source, StringRef Dest)
Map the source include name to the dest include name.
Definition: HeaderSearch.h:296
void setIsAllowRedefinitionsWithoutWarning(bool Val)
Set the value of the IsAllowRedefinitionsWithoutWarning flag.
Definition: MacroInfo.h:152
HeaderSearch & getHeaderSearchInfo() const
Definition: Preprocessor.h:695
bool setSeverityForGroup(diag::Flavor Flavor, StringRef Group, diag::Severity Map, SourceLocation Loc=SourceLocation())
Change an entire diagnostic group (e.g.
Definition: Diagnostic.cpp:249
void CommitBacktrackedTokens()
Disable the last EnableBacktrackAtThisPos call.
Definition: PPCaching.cpp:32
Present this diagnostic as an error.
tok::TokenKind getKind() const
Definition: Token.h:89
iterator end() const
unsigned getLine() const
Return the presumed line number of this location.
const FileEntry * getFileEntry() const
getFileEntry - Return the FileEntry corresponding to this FileID.
PragmaIntroducerKind
Describes how the pragma was introduced, e.g., with #pragma, _Pragma, or __pragma.
Definition: Pragma.h:32
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
void appendMacroDirective(IdentifierInfo *II, MacroDirective *MD)
Add a directive to the macro directive history for this identifier.
void LexUnexpandedToken(Token &Result)
Just like Lex, but disables macro expansion of identifier tokens.
PragmaMessageKind
Determines the kind of #pragma invoking a call to PragmaMessage.
Definition: PPCallbacks.h:184
void HandlePragmaIncludeAlias(Token &Tok)
Definition: Pragma.cpp:623
StringRef Filename
Definition: Format.cpp:1194
#pragma GCC warning has been invoked.
Definition: PPCallbacks.h:189
void Backtrack()
Make Preprocessor re-lex the tokens that were lexed since EnableBacktrackAtThisPos() was previously c...
Definition: PPCaching.cpp:40
EmptyPragmaHandler - A pragma handler which takes no action, which can be used to ignore particular p...
Definition: Pragma.h:77
const SmallVectorImpl< AnnotatedLine * >::const_iterator End
virtual void PragmaWarning(SourceLocation Loc, StringRef WarningSpec, ArrayRef< int > Ids)
Callback invoked when a #pragma warning directive is read.
Definition: PPCallbacks.h:228
void setAnnotationRange(SourceRange R)
Definition: Token.h:160
void HandlePragmaOnce(Token &OnceTok)
HandlePragmaOnce - Handle #pragma once.
Definition: Pragma.cpp:356
void setAnnotationValue(void *val)
Definition: Token.h:227
bool LexingRawMode
True if in raw mode.
StringRef getName() const
Return the actual identifier string.
PragmaNamespace * getIfNamespace() override
getIfNamespace - If this is a namespace, return it.
Definition: Pragma.h:120
void EnableBacktrackAtThisPos()
From the point that this method is called, and until CommitBacktrackedTokens() or Backtrack() is call...
Definition: PPCaching.cpp:26
bool LexOnOffSwitch(tok::OnOffSwitch &OOS)
Lex an on-off-switch (C99 6.10.6p2) and verify that it is followed by EOD.
Definition: Pragma.cpp:784
Defines the clang::Preprocessor interface.
bool hasUDSuffix() const
Return true if this token is a string or character literal which has a ud-suffix. ...
Definition: Token.h:290
void setIsPoisoned(bool Value=true)
setIsPoisoned - Mark this identifier as poisoned.
void RemovePragmaHandler(StringRef Namespace, PragmaHandler *Handler)
Remove the specific pragma handler from this preprocessor.
Definition: Pragma.cpp:762
void setPragmaAssumeNonNullLoc(SourceLocation Loc)
Set the location of the currently-active #pragma clang assume_nonnull begin.
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
Definition: Token.h:123
void HandlePragmaDependency(Token &DependencyTok)
HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah.
Definition: Pragma.cpp:456
bool isNot(tok::TokenKind K) const
Definition: Token.h:95
virtual ~PragmaHandler()
Definition: Pragma.cpp:34
Represents an unpacked "presumed" location which can be presented to the user.
DirectoryLookup - This class represents one entry in the search list that specifies the search order ...
PragmaHandler * FindHandler(StringRef Name, bool IgnoreNull=true) const
FindHandler - Check to see if there is already a handler for the specified name.
Definition: Pragma.cpp:59
#define false
Definition: stdbool.h:33
Kind
const char * getFilename() const
Return the presumed filename of this location.
Encodes a location in the source.
const TemplateArgument * iterator
Definition: Type.h:4233
void setPragmaARCCFCodeAuditedLoc(SourceLocation Loc)
Set the location of the currently-active #pragma clang arc_cf_code_audited begin. ...
#pragma message has been invoked.
Definition: PPCallbacks.h:186
bool isValid() const
Return true if this is a valid SourceLocation object.
Cached information about one file (either on disk or in the virtual file system). ...
Definition: FileManager.h:53
void Lex(Token &Result)
Lex the next token for this preprocessor.
PPCallbacks * getPPCallbacks() const
Accessors for preprocessor callbacks.
Definition: Preprocessor.h:784
Flavor
Flavors of diagnostics we can emit.
Definition: DiagnosticIDs.h:73
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {...
Definition: Token.h:94
virtual void PragmaMessage(SourceLocation Loc, StringRef Namespace, PragmaMessageKind Kind, StringRef Str)
Callback invoked when a #pragma message directive is read.
Definition: PPCallbacks.h:200
DiagnosticsEngine & getDiagnostics() const
Definition: Preprocessor.h:687
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
bool isMacroDefined(StringRef Id)
Definition: Preprocessor.h:793
Represents a template argument.
Definition: TemplateBase.h:40
~PragmaNamespace() override
Definition: Pragma.cpp:51
unsigned getLineTableFilenameID(StringRef Str)
Return the uniqued ID for the specified filename.
void HandlePragmaPopMacro(Token &Tok)
Handle #pragma pop_macro.
Definition: Pragma.cpp:588
virtual PragmaNamespace * getIfNamespace()
getIfNamespace - If this is a namespace, return it.
Definition: Pragma.h:72
PragmaHandler - Instances of this interface defined to handle the various pragmas that the language f...
Definition: Pragma.h:59
PreprocessorLexer * getCurrentFileLexer() const
Return the current file lexer being lexed from.
void RemovePragmaHandler(PragmaHandler *Handler)
RemovePragmaHandler - Remove the given handler from the namespace.
Definition: Pragma.cpp:72
Encapsulates the data about a macro definition (e.g.
Definition: MacroInfo.h:34
OnOffSwitch
Defines the possible values of an on-off-switch (C99 6.10.6p2).
Definition: TokenKinds.h:49
time_t getModificationTime() const
Definition: FileManager.h:92
PragmaNamespace - This PragmaHandler subdivides the namespace of pragmas, allowing hierarchical pragm...
Definition: Pragma.h:89
bool GetIncludeFilenameSpelling(SourceLocation Loc, StringRef &Filename)
Turn the specified lexer token into a fully checked and spelled filename, e.g.
bool FinishLexStringLiteral(Token &Result, std::string &String, const char *DiagnosticTag, bool AllowMacroExpansion)
Complete the lexing of a string literal where the first token has already been lexed (see LexStringLi...
void CreateString(StringRef Str, Token &Tok, SourceLocation ExpansionLocStart=SourceLocation(), SourceLocation ExpansionLocEnd=SourceLocation())
Plop the specified string into a scratch buffer and set the specified token's location and length to ...
bool popMappings(SourceLocation Loc)
Pops the current DiagMappings off the top of the stack, causing the new top of the stack to be the ac...
Definition: Diagnostic.cpp:103
IdentifierInfo * ParsePragmaPushOrPopMacro(Token &Tok)
ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
Definition: Pragma.cpp:510
void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override
Definition: Pragma.cpp:43
void LexIncludeFilename(Token &Result)
After the preprocessor has parsed a #include, lex and (potentially) macro expand the filename...
const FileEntry * LookupFile(SourceLocation FilenameLoc, StringRef Filename, bool isAngled, const DirectoryLookup *FromDir, const FileEntry *FromFile, const DirectoryLookup *&CurDir, SmallVectorImpl< char > *SearchPath, SmallVectorImpl< char > *RelativePath, ModuleMap::KnownHeader *SuggestedModule, bool SkipCache=false)
Given a "foo" or <foo> reference, look up the indicated file.
#define INT_MAX
Definition: limits.h:62
Do not present this diagnostic, ignore it.
void HandlePragmaPoison(Token &PoisonTok)
HandlePragmaPoison - Handle #pragma GCC poison.
Definition: Pragma.cpp:380
virtual void PragmaDiagnosticPush(SourceLocation Loc, StringRef Namespace)
Callback invoked when a #pragma gcc diagnostic push directive is read.
Definition: PPCallbacks.h:206
A diagnostic that indicates normal progress through compilation.
IdentifierInfo * LookUpIdentifierInfo(Token &Identifier) const
Given a tok::raw_identifier token, look up the identifier information for the token and install it in...
void HandlePragmaSystemHeader(Token &SysHeaderTok)
HandlePragmaSystemHeader - Implement #pragma GCC system_header.
Definition: Pragma.cpp:422
void DiscardUntilEndOfDirective()
Read and discard all tokens remaining on the current line until the tok::eod token is found...
bool isPreprocessedOutput() const
Returns true if the preprocessor is responsible for generating output, false if it is producing token...
Definition: Preprocessor.h:754
Present this diagnostic as a fatal error.
void MarkFileSystemHeader(const FileEntry *File)
Mark the specified file as a system header, e.g.
Definition: HeaderSearch.h:427
virtual void PragmaDiagnostic(SourceLocation Loc, StringRef Namespace, diag::Severity mapping, StringRef Str)
Callback invoked when a #pragma gcc diagnostic directive is read.
Definition: PPCallbacks.h:217
#define true
Definition: stdbool.h:32
A trivial tuple used to represent a source range.
void HandlePragmaMark()
Definition: Pragma.cpp:369
Present this diagnostic as a warning.
void MarkFileIncludeOnce(const FileEntry *File)
Mark the specified file as a "once only" file, e.g.
Definition: HeaderSearch.h:419
SourceLocation getPragmaARCCFCodeAuditedLoc() const
The location of the currently-active #pragma clang arc_cf_code_audited begin.
void startToken()
Reset all flags to cleared.
Definition: Token.h:168
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:97
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:176
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.