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