Pragma.cpp revision 3da92a9d21f707c164797dd967ba894b2282b343
1ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown//===--- Pragma.cpp - Pragma registration and handling --------------------===//
2ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown//
3ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown//                     The LLVM Compiler Infrastructure
4ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown//
5ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown// This file is distributed under the University of Illinois Open Source
6ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown// License. See LICENSE.TXT for details.
7ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown//
8ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown//===----------------------------------------------------------------------===//
9ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown//
10ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown// This file implements the PragmaHandler/PragmaTable interfaces and implements
11ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown// pragma related methods of the Preprocessor class.
12ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown//
13ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown//===----------------------------------------------------------------------===//
14ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown
15ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown#include "clang/Lex/Pragma.h"
16ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown#include "clang/Lex/HeaderSearch.h"
17ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown#include "clang/Lex/LiteralSupport.h"
18ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown#include "clang/Lex/Preprocessor.h"
19ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown#include "clang/Lex/MacroInfo.h"
20ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown#include "clang/Lex/LexDiagnostic.h"
21ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown#include "clang/Basic/FileManager.h"
22ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown#include "clang/Basic/SourceManager.h"
23ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown#include "llvm/Support/CrashRecoveryContext.h"
24ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown#include "llvm/Support/ErrorHandling.h"
25ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown#include <algorithm>
26ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brownusing namespace clang;
27ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown
28ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff Brown// Out-of-line destructor to provide a home for the class.
29ed07e00d438c74b7a23c01bfffde77e3968305e4Jeff BrownPragmaHandler::~PragmaHandler() {
30}
31
32//===----------------------------------------------------------------------===//
33// EmptyPragmaHandler Implementation.
34//===----------------------------------------------------------------------===//
35
36EmptyPragmaHandler::EmptyPragmaHandler() {}
37
38void EmptyPragmaHandler::HandlePragma(Preprocessor &PP, Token &FirstToken) {}
39
40//===----------------------------------------------------------------------===//
41// PragmaNamespace Implementation.
42//===----------------------------------------------------------------------===//
43
44
45PragmaNamespace::~PragmaNamespace() {
46  for (llvm::StringMap<PragmaHandler*>::iterator
47         I = Handlers.begin(), E = Handlers.end(); I != E; ++I)
48    delete I->second;
49}
50
51/// FindHandler - Check to see if there is already a handler for the
52/// specified name.  If not, return the handler for the null identifier if it
53/// exists, otherwise return null.  If IgnoreNull is true (the default) then
54/// the null handler isn't returned on failure to match.
55PragmaHandler *PragmaNamespace::FindHandler(llvm::StringRef Name,
56                                            bool IgnoreNull) const {
57  if (PragmaHandler *Handler = Handlers.lookup(Name))
58    return Handler;
59  return IgnoreNull ? 0 : Handlers.lookup(llvm::StringRef());
60}
61
62void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
63  assert(!Handlers.lookup(Handler->getName()) &&
64         "A handler with this name is already registered in this namespace");
65  llvm::StringMapEntry<PragmaHandler *> &Entry =
66    Handlers.GetOrCreateValue(Handler->getName());
67  Entry.setValue(Handler);
68}
69
70void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
71  assert(Handlers.lookup(Handler->getName()) &&
72         "Handler not registered in this namespace");
73  Handlers.erase(Handler->getName());
74}
75
76void PragmaNamespace::HandlePragma(Preprocessor &PP, Token &Tok) {
77  // Read the 'namespace' that the directive is in, e.g. STDC.  Do not macro
78  // expand it, the user can have a STDC #define, that should not affect this.
79  PP.LexUnexpandedToken(Tok);
80
81  // Get the handler for this token.  If there is no handler, ignore the pragma.
82  PragmaHandler *Handler
83    = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
84                                          : llvm::StringRef(),
85                  /*IgnoreNull=*/false);
86  if (Handler == 0) {
87    PP.Diag(Tok, diag::warn_pragma_ignored);
88    return;
89  }
90
91  // Otherwise, pass it down.
92  Handler->HandlePragma(PP, Tok);
93}
94
95//===----------------------------------------------------------------------===//
96// Preprocessor Pragma Directive Handling.
97//===----------------------------------------------------------------------===//
98
99/// HandlePragmaDirective - The "#pragma" directive has been parsed.  Lex the
100/// rest of the pragma, passing it to the registered pragma handlers.
101void Preprocessor::HandlePragmaDirective() {
102  ++NumPragma;
103
104  // Invoke the first level of pragma handlers which reads the namespace id.
105  Token Tok;
106  PragmaHandlers->HandlePragma(*this, Tok);
107
108  // If the pragma handler didn't read the rest of the line, consume it now.
109  if (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective)
110    DiscardUntilEndOfDirective();
111}
112
113/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
114/// return the first token after the directive.  The _Pragma token has just
115/// been read into 'Tok'.
116void Preprocessor::Handle_Pragma(Token &Tok) {
117  // Remember the pragma token location.
118  SourceLocation PragmaLoc = Tok.getLocation();
119
120  // Read the '('.
121  Lex(Tok);
122  if (Tok.isNot(tok::l_paren)) {
123    Diag(PragmaLoc, diag::err__Pragma_malformed);
124    return;
125  }
126
127  // Read the '"..."'.
128  Lex(Tok);
129  if (Tok.isNot(tok::string_literal) && Tok.isNot(tok::wide_string_literal)) {
130    Diag(PragmaLoc, diag::err__Pragma_malformed);
131    return;
132  }
133
134  // Remember the string.
135  std::string StrVal = getSpelling(Tok);
136
137  // Read the ')'.
138  Lex(Tok);
139  if (Tok.isNot(tok::r_paren)) {
140    Diag(PragmaLoc, diag::err__Pragma_malformed);
141    return;
142  }
143
144  SourceLocation RParenLoc = Tok.getLocation();
145
146  // The _Pragma is lexically sound.  Destringize according to C99 6.10.9.1:
147  // "The string literal is destringized by deleting the L prefix, if present,
148  // deleting the leading and trailing double-quotes, replacing each escape
149  // sequence \" by a double-quote, and replacing each escape sequence \\ by a
150  // single backslash."
151  if (StrVal[0] == 'L')  // Remove L prefix.
152    StrVal.erase(StrVal.begin());
153  assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
154         "Invalid string token!");
155
156  // Remove the front quote, replacing it with a space, so that the pragma
157  // contents appear to have a space before them.
158  StrVal[0] = ' ';
159
160  // Replace the terminating quote with a \n.
161  StrVal[StrVal.size()-1] = '\n';
162
163  // Remove escaped quotes and escapes.
164  for (unsigned i = 0, e = StrVal.size(); i != e-1; ++i) {
165    if (StrVal[i] == '\\' &&
166        (StrVal[i+1] == '\\' || StrVal[i+1] == '"')) {
167      // \\ -> '\' and \" -> '"'.
168      StrVal.erase(StrVal.begin()+i);
169      --e;
170    }
171  }
172
173  Handle_Pragma(StrVal, PragmaLoc, RParenLoc);
174
175  // Finally, return whatever came after the pragma directive.
176  return Lex(Tok);
177}
178
179/// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
180/// is not enclosed within a string literal.
181void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
182  // Remember the pragma token location.
183  SourceLocation PragmaLoc = Tok.getLocation();
184
185  // Read the '('.
186  Lex(Tok);
187  if (Tok.isNot(tok::l_paren)) {
188    Diag(PragmaLoc, diag::err__Pragma_malformed);
189    return;
190  }
191
192  // Get the tokens enclosed within the __pragma().
193  llvm::SmallVector<Token, 32> PragmaToks;
194  int NumParens = 0;
195  Lex(Tok);
196  while (Tok.isNot(tok::eof)) {
197    if (Tok.is(tok::l_paren))
198      NumParens++;
199    else if (Tok.is(tok::r_paren) && NumParens-- == 0)
200      break;
201    PragmaToks.push_back(Tok);
202    Lex(Tok);
203  }
204
205  if (Tok.is(tok::eof)) {
206    Diag(PragmaLoc, diag::err_unterminated___pragma);
207    return;
208  }
209
210  // Build the pragma string.
211  std::string StrVal = " ";
212  for (llvm::SmallVector<Token, 32>::iterator I =
213       PragmaToks.begin(), E = PragmaToks.end(); I != E; ++I) {
214    StrVal += getSpelling(*I);
215  }
216
217  SourceLocation RParenLoc = Tok.getLocation();
218
219  Handle_Pragma(StrVal, PragmaLoc, RParenLoc);
220
221  // Finally, return whatever came after the pragma directive.
222  return Lex(Tok);
223}
224
225void Preprocessor::Handle_Pragma(const std::string &StrVal,
226                                 SourceLocation PragmaLoc,
227                                 SourceLocation RParenLoc) {
228
229  // Plop the string (including the newline and trailing null) into a buffer
230  // where we can lex it.
231  Token TmpTok;
232  TmpTok.startToken();
233  CreateString(&StrVal[0], StrVal.size(), TmpTok);
234  SourceLocation TokLoc = TmpTok.getLocation();
235
236  // Make and enter a lexer object so that we lex and expand the tokens just
237  // like any others.
238  Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
239                                        StrVal.size(), *this);
240
241  EnterSourceFileWithLexer(TL, 0);
242
243  // With everything set up, lex this as a #pragma directive.
244  HandlePragmaDirective();
245}
246
247
248
249/// HandlePragmaOnce - Handle #pragma once.  OnceTok is the 'once'.
250///
251void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
252  if (isInPrimaryFile()) {
253    Diag(OnceTok, diag::pp_pragma_once_in_main_file);
254    return;
255  }
256
257  // Get the current file lexer we're looking at.  Ignore _Pragma 'files' etc.
258  // Mark the file as a once-only file now.
259  HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
260}
261
262void Preprocessor::HandlePragmaMark() {
263  assert(CurPPLexer && "No current lexer?");
264  if (CurLexer)
265    CurLexer->ReadToEndOfLine();
266  else
267    CurPTHLexer->DiscardToEndOfLine();
268}
269
270
271/// HandlePragmaPoison - Handle #pragma GCC poison.  PoisonTok is the 'poison'.
272///
273void Preprocessor::HandlePragmaPoison(Token &PoisonTok) {
274  Token Tok;
275
276  while (1) {
277    // Read the next token to poison.  While doing this, pretend that we are
278    // skipping while reading the identifier to poison.
279    // This avoids errors on code like:
280    //   #pragma GCC poison X
281    //   #pragma GCC poison X
282    if (CurPPLexer) CurPPLexer->LexingRawMode = true;
283    LexUnexpandedToken(Tok);
284    if (CurPPLexer) CurPPLexer->LexingRawMode = false;
285
286    // If we reached the end of line, we're done.
287    if (Tok.is(tok::eom)) return;
288
289    // Can only poison identifiers.
290    if (Tok.isNot(tok::identifier)) {
291      Diag(Tok, diag::err_pp_invalid_poison);
292      return;
293    }
294
295    // Look up the identifier info for the token.  We disabled identifier lookup
296    // by saying we're skipping contents, so we need to do this manually.
297    IdentifierInfo *II = LookUpIdentifierInfo(Tok);
298
299    // Already poisoned.
300    if (II->isPoisoned()) continue;
301
302    // If this is a macro identifier, emit a warning.
303    if (II->hasMacroDefinition())
304      Diag(Tok, diag::pp_poisoning_existing_macro);
305
306    // Finally, poison it!
307    II->setIsPoisoned();
308  }
309}
310
311/// HandlePragmaSystemHeader - Implement #pragma GCC system_header.  We know
312/// that the whole directive has been parsed.
313void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
314  if (isInPrimaryFile()) {
315    Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
316    return;
317  }
318
319  // Get the current file lexer we're looking at.  Ignore _Pragma 'files' etc.
320  PreprocessorLexer *TheLexer = getCurrentFileLexer();
321
322  // Mark the file as a system header.
323  HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
324
325
326  PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
327  unsigned FilenameLen = strlen(PLoc.getFilename());
328  unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename(),
329                                                         FilenameLen);
330
331  // Emit a line marker.  This will change any source locations from this point
332  // forward to realize they are in a system header.
333  // Create a line note with this information.
334  SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine(), FilenameID,
335                        false, false, true, false);
336
337  // Notify the client, if desired, that we are in a new source file.
338  if (Callbacks)
339    Callbacks->FileChanged(SysHeaderTok.getLocation(),
340                           PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
341}
342
343/// HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah.
344///
345void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
346  Token FilenameTok;
347  CurPPLexer->LexIncludeFilename(FilenameTok);
348
349  // If the token kind is EOM, the error has already been diagnosed.
350  if (FilenameTok.is(tok::eom))
351    return;
352
353  // Reserve a buffer to get the spelling.
354  llvm::SmallString<128> FilenameBuffer;
355  bool Invalid = false;
356  llvm::StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
357  if (Invalid)
358    return;
359
360  bool isAngled =
361    GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
362  // If GetIncludeFilenameSpelling set the start ptr to null, there was an
363  // error.
364  if (Filename.empty())
365    return;
366
367  // Search include directories for this file.
368  const DirectoryLookup *CurDir;
369  const FileEntry *File = LookupFile(Filename, isAngled, 0, CurDir);
370  if (File == 0) {
371    Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
372    return;
373  }
374
375  const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
376
377  // If this file is older than the file it depends on, emit a diagnostic.
378  if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
379    // Lex tokens at the end of the message and include them in the message.
380    std::string Message;
381    Lex(DependencyTok);
382    while (DependencyTok.isNot(tok::eom)) {
383      Message += getSpelling(DependencyTok) + " ";
384      Lex(DependencyTok);
385    }
386
387    Message.erase(Message.end()-1);
388    Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
389  }
390}
391
392/// HandlePragmaComment - Handle the microsoft #pragma comment extension.  The
393/// syntax is:
394///   #pragma comment(linker, "foo")
395/// 'linker' is one of five identifiers: compiler, exestr, lib, linker, user.
396/// "foo" is a string, which is fully macro expanded, and permits string
397/// concatenation, embedded escape characters etc.  See MSDN for more details.
398void Preprocessor::HandlePragmaComment(Token &Tok) {
399  SourceLocation CommentLoc = Tok.getLocation();
400  Lex(Tok);
401  if (Tok.isNot(tok::l_paren)) {
402    Diag(CommentLoc, diag::err_pragma_comment_malformed);
403    return;
404  }
405
406  // Read the identifier.
407  Lex(Tok);
408  if (Tok.isNot(tok::identifier)) {
409    Diag(CommentLoc, diag::err_pragma_comment_malformed);
410    return;
411  }
412
413  // Verify that this is one of the 5 whitelisted options.
414  // FIXME: warn that 'exestr' is deprecated.
415  const IdentifierInfo *II = Tok.getIdentifierInfo();
416  if (!II->isStr("compiler") && !II->isStr("exestr") && !II->isStr("lib") &&
417      !II->isStr("linker") && !II->isStr("user")) {
418    Diag(Tok.getLocation(), diag::err_pragma_comment_unknown_kind);
419    return;
420  }
421
422  // Read the optional string if present.
423  Lex(Tok);
424  std::string ArgumentString;
425  if (Tok.is(tok::comma)) {
426    Lex(Tok); // eat the comma.
427
428    // We need at least one string.
429    if (Tok.isNot(tok::string_literal)) {
430      Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
431      return;
432    }
433
434    // String concatenation allows multiple strings, which can even come from
435    // macro expansion.
436    // "foo " "bar" "Baz"
437    llvm::SmallVector<Token, 4> StrToks;
438    while (Tok.is(tok::string_literal)) {
439      StrToks.push_back(Tok);
440      Lex(Tok);
441    }
442
443    // Concatenate and parse the strings.
444    StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
445    assert(!Literal.AnyWide && "Didn't allow wide strings in");
446    if (Literal.hadError)
447      return;
448    if (Literal.Pascal) {
449      Diag(StrToks[0].getLocation(), diag::err_pragma_comment_malformed);
450      return;
451    }
452
453    ArgumentString = std::string(Literal.GetString(),
454                                 Literal.GetString()+Literal.GetStringLength());
455  }
456
457  // FIXME: If the kind is "compiler" warn if the string is present (it is
458  // ignored).
459  // FIXME: 'lib' requires a comment string.
460  // FIXME: 'linker' requires a comment string, and has a specific list of
461  // things that are allowable.
462
463  if (Tok.isNot(tok::r_paren)) {
464    Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
465    return;
466  }
467  Lex(Tok);  // eat the r_paren.
468
469  if (Tok.isNot(tok::eom)) {
470    Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
471    return;
472  }
473
474  // If the pragma is lexically sound, notify any interested PPCallbacks.
475  if (Callbacks)
476    Callbacks->PragmaComment(CommentLoc, II, ArgumentString);
477}
478
479/// HandlePragmaMessage - Handle the microsoft #pragma message extension.  The
480/// syntax is:
481///   #pragma message(messagestring)
482/// messagestring is a string, which is fully macro expanded, and permits string
483/// concatenation, embedded escape characters etc.  See MSDN for more details.
484void Preprocessor::HandlePragmaMessage(Token &Tok) {
485  SourceLocation MessageLoc = Tok.getLocation();
486  Lex(Tok);
487  if (Tok.isNot(tok::l_paren)) {
488    Diag(MessageLoc, diag::err_pragma_message_malformed);
489    return;
490  }
491
492  // Read the string.
493  Lex(Tok);
494
495
496  // We need at least one string.
497  if (Tok.isNot(tok::string_literal)) {
498    Diag(Tok.getLocation(), diag::err_pragma_message_malformed);
499    return;
500  }
501
502  // String concatenation allows multiple strings, which can even come from
503  // macro expansion.
504  // "foo " "bar" "Baz"
505  llvm::SmallVector<Token, 4> StrToks;
506  while (Tok.is(tok::string_literal)) {
507    StrToks.push_back(Tok);
508    Lex(Tok);
509  }
510
511  // Concatenate and parse the strings.
512  StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
513  assert(!Literal.AnyWide && "Didn't allow wide strings in");
514  if (Literal.hadError)
515    return;
516  if (Literal.Pascal) {
517    Diag(StrToks[0].getLocation(), diag::err_pragma_message_malformed);
518    return;
519  }
520
521  llvm::StringRef MessageString(Literal.GetString(), Literal.GetStringLength());
522
523  if (Tok.isNot(tok::r_paren)) {
524    Diag(Tok.getLocation(), diag::err_pragma_message_malformed);
525    return;
526  }
527  Lex(Tok);  // eat the r_paren.
528
529  if (Tok.isNot(tok::eom)) {
530    Diag(Tok.getLocation(), diag::err_pragma_message_malformed);
531    return;
532  }
533
534  // Output the message.
535  Diag(MessageLoc, diag::warn_pragma_message) << MessageString;
536
537  // If the pragma is lexically sound, notify any interested PPCallbacks.
538  if (Callbacks)
539    Callbacks->PragmaMessage(MessageLoc, MessageString);
540}
541
542/// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
543/// Return the IdentifierInfo* associated with the macro to push or pop.
544IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
545  // Remember the pragma token location.
546  Token PragmaTok = Tok;
547
548  // Read the '('.
549  Lex(Tok);
550  if (Tok.isNot(tok::l_paren)) {
551    Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
552      << getSpelling(PragmaTok);
553    return 0;
554  }
555
556  // Read the macro name string.
557  Lex(Tok);
558  if (Tok.isNot(tok::string_literal)) {
559    Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
560      << getSpelling(PragmaTok);
561    return 0;
562  }
563
564  // Remember the macro string.
565  std::string StrVal = getSpelling(Tok);
566
567  // Read the ')'.
568  Lex(Tok);
569  if (Tok.isNot(tok::r_paren)) {
570    Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
571      << getSpelling(PragmaTok);
572    return 0;
573  }
574
575  assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
576         "Invalid string token!");
577
578  // Create a Token from the string.
579  Token MacroTok;
580  MacroTok.startToken();
581  MacroTok.setKind(tok::identifier);
582  CreateString(&StrVal[1], StrVal.size() - 2, MacroTok);
583
584  // Get the IdentifierInfo of MacroToPushTok.
585  return LookUpIdentifierInfo(MacroTok);
586}
587
588/// HandlePragmaPushMacro - Handle #pragma push_macro.
589/// The syntax is:
590///   #pragma push_macro("macro")
591void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
592  // Parse the pragma directive and get the macro IdentifierInfo*.
593  IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
594  if (!IdentInfo) return;
595
596  // Get the MacroInfo associated with IdentInfo.
597  MacroInfo *MI = getMacroInfo(IdentInfo);
598
599  MacroInfo *MacroCopyToPush = 0;
600  if (MI) {
601    // Make a clone of MI.
602    MacroCopyToPush = CloneMacroInfo(*MI);
603
604    // Allow the original MacroInfo to be redefined later.
605    MI->setIsAllowRedefinitionsWithoutWarning(true);
606  }
607
608  // Push the cloned MacroInfo so we can retrieve it later.
609  PragmaPushMacroInfo[IdentInfo].push_back(MacroCopyToPush);
610}
611
612/// HandlePragmaPopMacro - Handle #pragma push_macro.
613/// The syntax is:
614///   #pragma pop_macro("macro")
615void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
616  SourceLocation MessageLoc = PopMacroTok.getLocation();
617
618  // Parse the pragma directive and get the macro IdentifierInfo*.
619  IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
620  if (!IdentInfo) return;
621
622  // Find the vector<MacroInfo*> associated with the macro.
623  llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
624    PragmaPushMacroInfo.find(IdentInfo);
625  if (iter != PragmaPushMacroInfo.end()) {
626    // Release the MacroInfo currently associated with IdentInfo.
627    MacroInfo *CurrentMI = getMacroInfo(IdentInfo);
628    if (CurrentMI) ReleaseMacroInfo(CurrentMI);
629
630    // Get the MacroInfo we want to reinstall.
631    MacroInfo *MacroToReInstall = iter->second.back();
632
633    // Reinstall the previously pushed macro.
634    setMacroInfo(IdentInfo, MacroToReInstall);
635
636    // Pop PragmaPushMacroInfo stack.
637    iter->second.pop_back();
638    if (iter->second.size() == 0)
639      PragmaPushMacroInfo.erase(iter);
640  } else {
641    Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
642      << IdentInfo->getName();
643  }
644}
645
646/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
647/// If 'Namespace' is non-null, then it is a token required to exist on the
648/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
649void Preprocessor::AddPragmaHandler(llvm::StringRef Namespace,
650                                    PragmaHandler *Handler) {
651  PragmaNamespace *InsertNS = PragmaHandlers;
652
653  // If this is specified to be in a namespace, step down into it.
654  if (!Namespace.empty()) {
655    // If there is already a pragma handler with the name of this namespace,
656    // we either have an error (directive with the same name as a namespace) or
657    // we already have the namespace to insert into.
658    if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
659      InsertNS = Existing->getIfNamespace();
660      assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
661             " handler with the same name!");
662    } else {
663      // Otherwise, this namespace doesn't exist yet, create and insert the
664      // handler for it.
665      InsertNS = new PragmaNamespace(Namespace);
666      PragmaHandlers->AddPragma(InsertNS);
667    }
668  }
669
670  // Check to make sure we don't already have a pragma for this identifier.
671  assert(!InsertNS->FindHandler(Handler->getName()) &&
672         "Pragma handler already exists for this identifier!");
673  InsertNS->AddPragma(Handler);
674}
675
676/// RemovePragmaHandler - Remove the specific pragma handler from the
677/// preprocessor. If \arg Namespace is non-null, then it should be the
678/// namespace that \arg Handler was added to. It is an error to remove
679/// a handler that has not been registered.
680void Preprocessor::RemovePragmaHandler(llvm::StringRef Namespace,
681                                       PragmaHandler *Handler) {
682  PragmaNamespace *NS = PragmaHandlers;
683
684  // If this is specified to be in a namespace, step down into it.
685  if (!Namespace.empty()) {
686    PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
687    assert(Existing && "Namespace containing handler does not exist!");
688
689    NS = Existing->getIfNamespace();
690    assert(NS && "Invalid namespace, registered as a regular pragma handler!");
691  }
692
693  NS->RemovePragmaHandler(Handler);
694
695  // If this is a non-default namespace and it is now empty, remove
696  // it.
697  if (NS != PragmaHandlers && NS->IsEmpty())
698    PragmaHandlers->RemovePragmaHandler(NS);
699}
700
701namespace {
702/// PragmaOnceHandler - "#pragma once" marks the file as atomically included.
703struct PragmaOnceHandler : public PragmaHandler {
704  PragmaOnceHandler() : PragmaHandler("once") {}
705  virtual void HandlePragma(Preprocessor &PP, Token &OnceTok) {
706    PP.CheckEndOfDirective("pragma once");
707    PP.HandlePragmaOnce(OnceTok);
708  }
709};
710
711/// PragmaMarkHandler - "#pragma mark ..." is ignored by the compiler, and the
712/// rest of the line is not lexed.
713struct PragmaMarkHandler : public PragmaHandler {
714  PragmaMarkHandler() : PragmaHandler("mark") {}
715  virtual void HandlePragma(Preprocessor &PP, Token &MarkTok) {
716    PP.HandlePragmaMark();
717  }
718};
719
720/// PragmaPoisonHandler - "#pragma poison x" marks x as not usable.
721struct PragmaPoisonHandler : public PragmaHandler {
722  PragmaPoisonHandler() : PragmaHandler("poison") {}
723  virtual void HandlePragma(Preprocessor &PP, Token &PoisonTok) {
724    PP.HandlePragmaPoison(PoisonTok);
725  }
726};
727
728/// PragmaSystemHeaderHandler - "#pragma system_header" marks the current file
729/// as a system header, which silences warnings in it.
730struct PragmaSystemHeaderHandler : public PragmaHandler {
731  PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
732  virtual void HandlePragma(Preprocessor &PP, Token &SHToken) {
733    PP.HandlePragmaSystemHeader(SHToken);
734    PP.CheckEndOfDirective("pragma");
735  }
736};
737struct PragmaDependencyHandler : public PragmaHandler {
738  PragmaDependencyHandler() : PragmaHandler("dependency") {}
739  virtual void HandlePragma(Preprocessor &PP, Token &DepToken) {
740    PP.HandlePragmaDependency(DepToken);
741  }
742};
743
744struct PragmaDebugHandler : public PragmaHandler {
745  PragmaDebugHandler() : PragmaHandler("__debug") {}
746  virtual void HandlePragma(Preprocessor &PP, Token &DepToken) {
747    Token Tok;
748    PP.LexUnexpandedToken(Tok);
749    if (Tok.isNot(tok::identifier)) {
750      PP.Diag(Tok, diag::warn_pragma_diagnostic_clang_invalid);
751      return;
752    }
753    IdentifierInfo *II = Tok.getIdentifierInfo();
754
755    if (II->isStr("assert")) {
756      assert(0 && "This is an assertion!");
757    } else if (II->isStr("crash")) {
758      *(volatile int*) 0x11 = 0;
759    } else if (II->isStr("llvm_fatal_error")) {
760      llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
761    } else if (II->isStr("llvm_unreachable")) {
762      llvm_unreachable("#pragma clang __debug llvm_unreachable");
763    } else if (II->isStr("overflow_stack")) {
764      DebugOverflowStack();
765    } else if (II->isStr("handle_crash")) {
766      llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
767      if (CRC)
768        CRC->HandleCrash();
769    } else {
770      PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
771        << II->getName();
772    }
773  }
774
775  void DebugOverflowStack() {
776    DebugOverflowStack();
777  }
778};
779
780/// PragmaDiagnosticHandler - e.g. '#pragma GCC diagnostic ignored "-Wformat"'
781/// Since clang's diagnostic supports extended functionality beyond GCC's
782/// the constructor takes a clangMode flag to tell it whether or not to allow
783/// clang's extended functionality, or whether to reject it.
784struct PragmaDiagnosticHandler : public PragmaHandler {
785private:
786  const bool ClangMode;
787public:
788  explicit PragmaDiagnosticHandler(const bool clangMode)
789    : PragmaHandler("diagnostic"), ClangMode(clangMode) {}
790
791  virtual void HandlePragma(Preprocessor &PP, Token &DiagToken) {
792    Token Tok;
793    PP.LexUnexpandedToken(Tok);
794    if (Tok.isNot(tok::identifier)) {
795      unsigned Diag = ClangMode ? diag::warn_pragma_diagnostic_clang_invalid
796                                 : diag::warn_pragma_diagnostic_gcc_invalid;
797      PP.Diag(Tok, Diag);
798      return;
799    }
800    IdentifierInfo *II = Tok.getIdentifierInfo();
801
802    diag::Mapping Map;
803    if (II->isStr("warning"))
804      Map = diag::MAP_WARNING;
805    else if (II->isStr("error"))
806      Map = diag::MAP_ERROR;
807    else if (II->isStr("ignored"))
808      Map = diag::MAP_IGNORE;
809    else if (II->isStr("fatal"))
810      Map = diag::MAP_FATAL;
811    else if (ClangMode) {
812      if (II->isStr("pop")) {
813        if (!PP.getDiagnostics().popMappings())
814          PP.Diag(Tok, diag::warn_pragma_diagnostic_clang_cannot_ppp);
815        return;
816      }
817
818      if (II->isStr("push")) {
819        PP.getDiagnostics().pushMappings();
820        return;
821      }
822
823      PP.Diag(Tok, diag::warn_pragma_diagnostic_clang_invalid);
824      return;
825    } else {
826      PP.Diag(Tok, diag::warn_pragma_diagnostic_gcc_invalid);
827      return;
828    }
829
830    PP.LexUnexpandedToken(Tok);
831
832    // We need at least one string.
833    if (Tok.isNot(tok::string_literal)) {
834      PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
835      return;
836    }
837
838    // String concatenation allows multiple strings, which can even come from
839    // macro expansion.
840    // "foo " "bar" "Baz"
841    llvm::SmallVector<Token, 4> StrToks;
842    while (Tok.is(tok::string_literal)) {
843      StrToks.push_back(Tok);
844      PP.LexUnexpandedToken(Tok);
845    }
846
847    if (Tok.isNot(tok::eom)) {
848      PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
849      return;
850    }
851
852    // Concatenate and parse the strings.
853    StringLiteralParser Literal(&StrToks[0], StrToks.size(), PP);
854    assert(!Literal.AnyWide && "Didn't allow wide strings in");
855    if (Literal.hadError)
856      return;
857    if (Literal.Pascal) {
858      unsigned Diag = ClangMode ? diag::warn_pragma_diagnostic_clang_invalid
859                                 : diag::warn_pragma_diagnostic_gcc_invalid;
860      PP.Diag(Tok, Diag);
861      return;
862    }
863
864    std::string WarningName(Literal.GetString(),
865                            Literal.GetString()+Literal.GetStringLength());
866
867    if (WarningName.size() < 3 || WarningName[0] != '-' ||
868        WarningName[1] != 'W') {
869      PP.Diag(StrToks[0].getLocation(),
870              diag::warn_pragma_diagnostic_invalid_option);
871      return;
872    }
873
874    if (PP.getDiagnostics().setDiagnosticGroupMapping(WarningName.c_str()+2,
875                                                      Map))
876      PP.Diag(StrToks[0].getLocation(),
877              diag::warn_pragma_diagnostic_unknown_warning) << WarningName;
878  }
879};
880
881/// PragmaCommentHandler - "#pragma comment ...".
882struct PragmaCommentHandler : public PragmaHandler {
883  PragmaCommentHandler() : PragmaHandler("comment") {}
884  virtual void HandlePragma(Preprocessor &PP, Token &CommentTok) {
885    PP.HandlePragmaComment(CommentTok);
886  }
887};
888
889/// PragmaMessageHandler - "#pragma message("...")".
890struct PragmaMessageHandler : public PragmaHandler {
891  PragmaMessageHandler() : PragmaHandler("message") {}
892  virtual void HandlePragma(Preprocessor &PP, Token &CommentTok) {
893    PP.HandlePragmaMessage(CommentTok);
894  }
895};
896
897/// PragmaPushMacroHandler - "#pragma push_macro" saves the value of the
898/// macro on the top of the stack.
899struct PragmaPushMacroHandler : public PragmaHandler {
900  PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
901  virtual void HandlePragma(Preprocessor &PP, Token &PushMacroTok) {
902    PP.HandlePragmaPushMacro(PushMacroTok);
903  }
904};
905
906
907/// PragmaPopMacroHandler - "#pragma pop_macro" sets the value of the
908/// macro to the value on the top of the stack.
909struct PragmaPopMacroHandler : public PragmaHandler {
910  PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
911  virtual void HandlePragma(Preprocessor &PP, Token &PopMacroTok) {
912    PP.HandlePragmaPopMacro(PopMacroTok);
913  }
914};
915
916// Pragma STDC implementations.
917
918enum STDCSetting {
919  STDC_ON, STDC_OFF, STDC_DEFAULT, STDC_INVALID
920};
921
922static STDCSetting LexOnOffSwitch(Preprocessor &PP) {
923  Token Tok;
924  PP.LexUnexpandedToken(Tok);
925
926  if (Tok.isNot(tok::identifier)) {
927    PP.Diag(Tok, diag::ext_stdc_pragma_syntax);
928    return STDC_INVALID;
929  }
930  IdentifierInfo *II = Tok.getIdentifierInfo();
931  STDCSetting Result;
932  if (II->isStr("ON"))
933    Result = STDC_ON;
934  else if (II->isStr("OFF"))
935    Result = STDC_OFF;
936  else if (II->isStr("DEFAULT"))
937    Result = STDC_DEFAULT;
938  else {
939    PP.Diag(Tok, diag::ext_stdc_pragma_syntax);
940    return STDC_INVALID;
941  }
942
943  // Verify that this is followed by EOM.
944  PP.LexUnexpandedToken(Tok);
945  if (Tok.isNot(tok::eom))
946    PP.Diag(Tok, diag::ext_stdc_pragma_syntax_eom);
947  return Result;
948}
949
950/// PragmaSTDC_FP_CONTRACTHandler - "#pragma STDC FP_CONTRACT ...".
951struct PragmaSTDC_FP_CONTRACTHandler : public PragmaHandler {
952  PragmaSTDC_FP_CONTRACTHandler() : PragmaHandler("FP_CONTRACT") {}
953  virtual void HandlePragma(Preprocessor &PP, Token &Tok) {
954    // We just ignore the setting of FP_CONTRACT. Since we don't do contractions
955    // at all, our default is OFF and setting it to ON is an optimization hint
956    // we can safely ignore.  When we support -ffma or something, we would need
957    // to diagnose that we are ignoring FMA.
958    LexOnOffSwitch(PP);
959  }
960};
961
962/// PragmaSTDC_FENV_ACCESSHandler - "#pragma STDC FENV_ACCESS ...".
963struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
964  PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
965  virtual void HandlePragma(Preprocessor &PP, Token &Tok) {
966    if (LexOnOffSwitch(PP) == STDC_ON)
967      PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
968  }
969};
970
971/// PragmaSTDC_CX_LIMITED_RANGEHandler - "#pragma STDC CX_LIMITED_RANGE ...".
972struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
973  PragmaSTDC_CX_LIMITED_RANGEHandler()
974    : PragmaHandler("CX_LIMITED_RANGE") {}
975  virtual void HandlePragma(Preprocessor &PP, Token &Tok) {
976    LexOnOffSwitch(PP);
977  }
978};
979
980/// PragmaSTDC_UnknownHandler - "#pragma STDC ...".
981struct PragmaSTDC_UnknownHandler : public PragmaHandler {
982  PragmaSTDC_UnknownHandler() {}
983  virtual void HandlePragma(Preprocessor &PP, Token &UnknownTok) {
984    // C99 6.10.6p2, unknown forms are not allowed.
985    PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
986  }
987};
988
989}  // end anonymous namespace
990
991
992/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
993/// #pragma GCC poison/system_header/dependency and #pragma once.
994void Preprocessor::RegisterBuiltinPragmas() {
995  AddPragmaHandler(new PragmaOnceHandler());
996  AddPragmaHandler(new PragmaMarkHandler());
997  AddPragmaHandler(new PragmaPushMacroHandler());
998  AddPragmaHandler(new PragmaPopMacroHandler());
999
1000  // #pragma GCC ...
1001  AddPragmaHandler("GCC", new PragmaPoisonHandler());
1002  AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1003  AddPragmaHandler("GCC", new PragmaDependencyHandler());
1004  AddPragmaHandler("GCC", new PragmaDiagnosticHandler(false));
1005  // #pragma clang ...
1006  AddPragmaHandler("clang", new PragmaPoisonHandler());
1007  AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
1008  AddPragmaHandler("clang", new PragmaDebugHandler());
1009  AddPragmaHandler("clang", new PragmaDependencyHandler());
1010  AddPragmaHandler("clang", new PragmaDiagnosticHandler(true));
1011
1012  AddPragmaHandler("STDC", new PragmaSTDC_FP_CONTRACTHandler());
1013  AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1014  AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
1015  AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
1016
1017  // MS extensions.
1018  if (Features.Microsoft) {
1019    AddPragmaHandler(new PragmaCommentHandler());
1020    AddPragmaHandler(new PragmaMessageHandler());
1021  }
1022}
1023