Pragma.cpp revision 221345
1162911Ssimon//===--- Pragma.cpp - Pragma registration and handling --------------------===//
2162911Ssimon//
3162911Ssimon//                     The LLVM Compiler Infrastructure
4162911Ssimon//
5162911Ssimon// This file is distributed under the University of Illinois Open Source
6162911Ssimon// License. See LICENSE.TXT for details.
7162911Ssimon//
8162911Ssimon//===----------------------------------------------------------------------===//
9162911Ssimon//
10162911Ssimon// This file implements the PragmaHandler/PragmaTable interfaces and implements
11162911Ssimon// pragma related methods of the Preprocessor class.
12162911Ssimon//
13162911Ssimon//===----------------------------------------------------------------------===//
14162911Ssimon
15162911Ssimon#include "clang/Lex/Pragma.h"
16162911Ssimon#include "clang/Lex/HeaderSearch.h"
17162911Ssimon#include "clang/Lex/LiteralSupport.h"
18162911Ssimon#include "clang/Lex/Preprocessor.h"
19162911Ssimon#include "clang/Lex/MacroInfo.h"
20162911Ssimon#include "clang/Lex/LexDiagnostic.h"
21162911Ssimon#include "clang/Basic/FileManager.h"
22162911Ssimon#include "clang/Basic/SourceManager.h"
23162911Ssimon#include "llvm/Support/CrashRecoveryContext.h"
24162911Ssimon#include "llvm/Support/ErrorHandling.h"
25162911Ssimon#include <algorithm>
26162911Ssimonusing namespace clang;
27162911Ssimon
28162911Ssimon// Out-of-line destructor to provide a home for the class.
29162911SsimonPragmaHandler::~PragmaHandler() {
30162911Ssimon}
31162911Ssimon
32162911Ssimon//===----------------------------------------------------------------------===//
33162911Ssimon// EmptyPragmaHandler Implementation.
34162911Ssimon//===----------------------------------------------------------------------===//
35162911Ssimon
36162911SsimonEmptyPragmaHandler::EmptyPragmaHandler() {}
37162911Ssimon
38162911Ssimonvoid EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
39162911Ssimon                                      PragmaIntroducerKind Introducer,
40162911Ssimon                                      Token &FirstToken) {}
41162911Ssimon
42162911Ssimon//===----------------------------------------------------------------------===//
43162911Ssimon// PragmaNamespace Implementation.
44162911Ssimon//===----------------------------------------------------------------------===//
45162911Ssimon
46162911Ssimon
47162911SsimonPragmaNamespace::~PragmaNamespace() {
48162911Ssimon  for (llvm::StringMap<PragmaHandler*>::iterator
49162911Ssimon         I = Handlers.begin(), E = Handlers.end(); I != E; ++I)
50162911Ssimon    delete I->second;
51162911Ssimon}
52162911Ssimon
53162911Ssimon/// FindHandler - Check to see if there is already a handler for the
54162911Ssimon/// specified name.  If not, return the handler for the null identifier if it
55162911Ssimon/// exists, otherwise return null.  If IgnoreNull is true (the default) then
56162911Ssimon/// the null handler isn't returned on failure to match.
57162911SsimonPragmaHandler *PragmaNamespace::FindHandler(llvm::StringRef Name,
58162911Ssimon                                            bool IgnoreNull) const {
59162911Ssimon  if (PragmaHandler *Handler = Handlers.lookup(Name))
60162911Ssimon    return Handler;
61162911Ssimon  return IgnoreNull ? 0 : Handlers.lookup(llvm::StringRef());
62162911Ssimon}
63162911Ssimon
64162911Ssimonvoid PragmaNamespace::AddPragma(PragmaHandler *Handler) {
65162911Ssimon  assert(!Handlers.lookup(Handler->getName()) &&
66162911Ssimon         "A handler with this name is already registered in this namespace");
67162911Ssimon  llvm::StringMapEntry<PragmaHandler *> &Entry =
68162911Ssimon    Handlers.GetOrCreateValue(Handler->getName());
69162911Ssimon  Entry.setValue(Handler);
70162911Ssimon}
71162911Ssimon
72162911Ssimonvoid PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
73162911Ssimon  assert(Handlers.lookup(Handler->getName()) &&
74162911Ssimon         "Handler not registered in this namespace");
75162911Ssimon  Handlers.erase(Handler->getName());
76162911Ssimon}
77162911Ssimon
78162911Ssimonvoid PragmaNamespace::HandlePragma(Preprocessor &PP,
79162911Ssimon                                   PragmaIntroducerKind Introducer,
80162911Ssimon                                   Token &Tok) {
81162911Ssimon  // Read the 'namespace' that the directive is in, e.g. STDC.  Do not macro
82162911Ssimon  // expand it, the user can have a STDC #define, that should not affect this.
83162911Ssimon  PP.LexUnexpandedToken(Tok);
84162911Ssimon
85162911Ssimon  // Get the handler for this token.  If there is no handler, ignore the pragma.
86162911Ssimon  PragmaHandler *Handler
87162911Ssimon    = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
88162911Ssimon                                          : llvm::StringRef(),
89162911Ssimon                  /*IgnoreNull=*/false);
90162911Ssimon  if (Handler == 0) {
91162911Ssimon    PP.Diag(Tok, diag::warn_pragma_ignored);
92162911Ssimon    return;
93162911Ssimon  }
94162911Ssimon
95162911Ssimon  // Otherwise, pass it down.
96162911Ssimon  Handler->HandlePragma(PP, Introducer, Tok);
97162911Ssimon}
98162911Ssimon
99162911Ssimon//===----------------------------------------------------------------------===//
100162911Ssimon// Preprocessor Pragma Directive Handling.
101162911Ssimon//===----------------------------------------------------------------------===//
102162911Ssimon
103162911Ssimon/// HandlePragmaDirective - The "#pragma" directive has been parsed.  Lex the
104162911Ssimon/// rest of the pragma, passing it to the registered pragma handlers.
105162911Ssimonvoid Preprocessor::HandlePragmaDirective(unsigned Introducer) {
106162911Ssimon  ++NumPragma;
107162911Ssimon
108162911Ssimon  // Invoke the first level of pragma handlers which reads the namespace id.
109162911Ssimon  Token Tok;
110162911Ssimon  PragmaHandlers->HandlePragma(*this, PragmaIntroducerKind(Introducer), Tok);
111162911Ssimon
112162911Ssimon  // If the pragma handler didn't read the rest of the line, consume it now.
113162911Ssimon  if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
114162911Ssimon   || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
115162911Ssimon    DiscardUntilEndOfDirective();
116162911Ssimon}
117162911Ssimon
118162911Ssimon/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
119162911Ssimon/// return the first token after the directive.  The _Pragma token has just
120162911Ssimon/// been read into 'Tok'.
121162911Ssimonvoid Preprocessor::Handle_Pragma(Token &Tok) {
122162911Ssimon  // Remember the pragma token location.
123162911Ssimon  SourceLocation PragmaLoc = Tok.getLocation();
124162911Ssimon
125162911Ssimon  // Read the '('.
126162911Ssimon  Lex(Tok);
127162911Ssimon  if (Tok.isNot(tok::l_paren)) {
128162911Ssimon    Diag(PragmaLoc, diag::err__Pragma_malformed);
129162911Ssimon    return;
130162911Ssimon  }
131162911Ssimon
132162911Ssimon  // Read the '"..."'.
133162911Ssimon  Lex(Tok);
134162911Ssimon  if (Tok.isNot(tok::string_literal) && Tok.isNot(tok::wide_string_literal)) {
135162911Ssimon    Diag(PragmaLoc, diag::err__Pragma_malformed);
136162911Ssimon    return;
137162911Ssimon  }
138162911Ssimon
139162911Ssimon  // Remember the string.
140162911Ssimon  std::string StrVal = getSpelling(Tok);
141162911Ssimon
142162911Ssimon  // Read the ')'.
143162911Ssimon  Lex(Tok);
144162911Ssimon  if (Tok.isNot(tok::r_paren)) {
145162911Ssimon    Diag(PragmaLoc, diag::err__Pragma_malformed);
146162911Ssimon    return;
147162911Ssimon  }
148162911Ssimon
149162911Ssimon  SourceLocation RParenLoc = Tok.getLocation();
150162911Ssimon
151162911Ssimon  // The _Pragma is lexically sound.  Destringize according to C99 6.10.9.1:
152162911Ssimon  // "The string literal is destringized by deleting the L prefix, if present,
153162911Ssimon  // deleting the leading and trailing double-quotes, replacing each escape
154162911Ssimon  // sequence \" by a double-quote, and replacing each escape sequence \\ by a
155162911Ssimon  // single backslash."
156162911Ssimon  if (StrVal[0] == 'L')  // Remove L prefix.
157162911Ssimon    StrVal.erase(StrVal.begin());
158162911Ssimon  assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
159162911Ssimon         "Invalid string token!");
160162911Ssimon
161162911Ssimon  // Remove the front quote, replacing it with a space, so that the pragma
162162911Ssimon  // contents appear to have a space before them.
163162911Ssimon  StrVal[0] = ' ';
164162911Ssimon
165162911Ssimon  // Replace the terminating quote with a \n.
166162911Ssimon  StrVal[StrVal.size()-1] = '\n';
167162911Ssimon
168162911Ssimon  // Remove escaped quotes and escapes.
169162911Ssimon  for (unsigned i = 0, e = StrVal.size(); i != e-1; ++i) {
170162911Ssimon    if (StrVal[i] == '\\' &&
171162911Ssimon        (StrVal[i+1] == '\\' || StrVal[i+1] == '"')) {
172162911Ssimon      // \\ -> '\' and \" -> '"'.
173162911Ssimon      StrVal.erase(StrVal.begin()+i);
174162911Ssimon      --e;
175162911Ssimon    }
176162911Ssimon  }
177162911Ssimon
178162911Ssimon  // Plop the string (including the newline and trailing null) into a buffer
179162911Ssimon  // where we can lex it.
180162911Ssimon  Token TmpTok;
181162911Ssimon  TmpTok.startToken();
182162911Ssimon  CreateString(&StrVal[0], StrVal.size(), TmpTok);
183162911Ssimon  SourceLocation TokLoc = TmpTok.getLocation();
184162911Ssimon
185162911Ssimon  // Make and enter a lexer object so that we lex and expand the tokens just
186162911Ssimon  // like any others.
187162911Ssimon  Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
188162911Ssimon                                        StrVal.size(), *this);
189162911Ssimon
190162911Ssimon  EnterSourceFileWithLexer(TL, 0);
191162911Ssimon
192162911Ssimon  // With everything set up, lex this as a #pragma directive.
193162911Ssimon  HandlePragmaDirective(PIK__Pragma);
194162911Ssimon
195162911Ssimon  // Finally, return whatever came after the pragma directive.
196162911Ssimon  return Lex(Tok);
197162911Ssimon}
198162911Ssimon
199162911Ssimon/// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
200162911Ssimon/// is not enclosed within a string literal.
201162911Ssimonvoid Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
202162911Ssimon  // Remember the pragma token location.
203162911Ssimon  SourceLocation PragmaLoc = Tok.getLocation();
204162911Ssimon
205162911Ssimon  // Read the '('.
206162911Ssimon  Lex(Tok);
207162911Ssimon  if (Tok.isNot(tok::l_paren)) {
208162911Ssimon    Diag(PragmaLoc, diag::err__Pragma_malformed);
209162911Ssimon    return;
210162911Ssimon  }
211162911Ssimon
212162911Ssimon  // Get the tokens enclosed within the __pragma(), as well as the final ')'.
213162911Ssimon  llvm::SmallVector<Token, 32> PragmaToks;
214162911Ssimon  int NumParens = 0;
215162911Ssimon  Lex(Tok);
216162911Ssimon  while (Tok.isNot(tok::eof)) {
217162911Ssimon    PragmaToks.push_back(Tok);
218162911Ssimon    if (Tok.is(tok::l_paren))
219162911Ssimon      NumParens++;
220162911Ssimon    else if (Tok.is(tok::r_paren) && NumParens-- == 0)
221162911Ssimon      break;
222162911Ssimon    Lex(Tok);
223162911Ssimon  }
224162911Ssimon
225162911Ssimon  if (Tok.is(tok::eof)) {
226162911Ssimon    Diag(PragmaLoc, diag::err_unterminated___pragma);
227162911Ssimon    return;
228162911Ssimon  }
229162911Ssimon
230162911Ssimon  PragmaToks.front().setFlag(Token::LeadingSpace);
231162911Ssimon
232162911Ssimon  // Replace the ')' with an EOD to mark the end of the pragma.
233162911Ssimon  PragmaToks.back().setKind(tok::eod);
234162911Ssimon
235  Token *TokArray = new Token[PragmaToks.size()];
236  std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
237
238  // Push the tokens onto the stack.
239  EnterTokenStream(TokArray, PragmaToks.size(), true, true);
240
241  // With everything set up, lex this as a #pragma directive.
242  HandlePragmaDirective(PIK___pragma);
243
244  // Finally, return whatever came after the pragma directive.
245  return Lex(Tok);
246}
247
248/// HandlePragmaOnce - Handle #pragma once.  OnceTok is the 'once'.
249///
250void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
251  if (isInPrimaryFile()) {
252    Diag(OnceTok, diag::pp_pragma_once_in_main_file);
253    return;
254  }
255
256  // Get the current file lexer we're looking at.  Ignore _Pragma 'files' etc.
257  // Mark the file as a once-only file now.
258  HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
259}
260
261void Preprocessor::HandlePragmaMark() {
262  assert(CurPPLexer && "No current lexer?");
263  if (CurLexer)
264    CurLexer->ReadToEndOfLine();
265  else
266    CurPTHLexer->DiscardToEndOfLine();
267}
268
269
270/// HandlePragmaPoison - Handle #pragma GCC poison.  PoisonTok is the 'poison'.
271///
272void Preprocessor::HandlePragmaPoison(Token &PoisonTok) {
273  Token Tok;
274
275  while (1) {
276    // Read the next token to poison.  While doing this, pretend that we are
277    // skipping while reading the identifier to poison.
278    // This avoids errors on code like:
279    //   #pragma GCC poison X
280    //   #pragma GCC poison X
281    if (CurPPLexer) CurPPLexer->LexingRawMode = true;
282    LexUnexpandedToken(Tok);
283    if (CurPPLexer) CurPPLexer->LexingRawMode = false;
284
285    // If we reached the end of line, we're done.
286    if (Tok.is(tok::eod)) return;
287
288    // Can only poison identifiers.
289    if (Tok.isNot(tok::raw_identifier)) {
290      Diag(Tok, diag::err_pp_invalid_poison);
291      return;
292    }
293
294    // Look up the identifier info for the token.  We disabled identifier lookup
295    // by saying we're skipping contents, so we need to do this manually.
296    IdentifierInfo *II = LookUpIdentifierInfo(Tok);
297
298    // Already poisoned.
299    if (II->isPoisoned()) continue;
300
301    // If this is a macro identifier, emit a warning.
302    if (II->hasMacroDefinition())
303      Diag(Tok, diag::pp_poisoning_existing_macro);
304
305    // Finally, poison it!
306    II->setIsPoisoned();
307  }
308}
309
310/// HandlePragmaSystemHeader - Implement #pragma GCC system_header.  We know
311/// that the whole directive has been parsed.
312void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
313  if (isInPrimaryFile()) {
314    Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
315    return;
316  }
317
318  // Get the current file lexer we're looking at.  Ignore _Pragma 'files' etc.
319  PreprocessorLexer *TheLexer = getCurrentFileLexer();
320
321  // Mark the file as a system header.
322  HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
323
324
325  PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
326  if (PLoc.isInvalid())
327    return;
328
329  unsigned FilenameLen = strlen(PLoc.getFilename());
330  unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename(),
331                                                         FilenameLen);
332
333  // Emit a line marker.  This will change any source locations from this point
334  // forward to realize they are in a system header.
335  // Create a line note with this information.
336  SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine(), FilenameID,
337                        false, false, true, false);
338
339  // Notify the client, if desired, that we are in a new source file.
340  if (Callbacks)
341    Callbacks->FileChanged(SysHeaderTok.getLocation(),
342                           PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
343}
344
345/// HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah.
346///
347void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
348  Token FilenameTok;
349  CurPPLexer->LexIncludeFilename(FilenameTok);
350
351  // If the token kind is EOD, the error has already been diagnosed.
352  if (FilenameTok.is(tok::eod))
353    return;
354
355  // Reserve a buffer to get the spelling.
356  llvm::SmallString<128> FilenameBuffer;
357  bool Invalid = false;
358  llvm::StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
359  if (Invalid)
360    return;
361
362  bool isAngled =
363    GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
364  // If GetIncludeFilenameSpelling set the start ptr to null, there was an
365  // error.
366  if (Filename.empty())
367    return;
368
369  // Search include directories for this file.
370  const DirectoryLookup *CurDir;
371  const FileEntry *File = LookupFile(Filename, isAngled, 0, CurDir, NULL, NULL);
372  if (File == 0) {
373    Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
374    return;
375  }
376
377  const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
378
379  // If this file is older than the file it depends on, emit a diagnostic.
380  if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
381    // Lex tokens at the end of the message and include them in the message.
382    std::string Message;
383    Lex(DependencyTok);
384    while (DependencyTok.isNot(tok::eod)) {
385      Message += getSpelling(DependencyTok) + " ";
386      Lex(DependencyTok);
387    }
388
389    // Remove the trailing ' ' if present.
390    if (!Message.empty())
391      Message.erase(Message.end()-1);
392    Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
393  }
394}
395
396/// HandlePragmaComment - Handle the microsoft #pragma comment extension.  The
397/// syntax is:
398///   #pragma comment(linker, "foo")
399/// 'linker' is one of five identifiers: compiler, exestr, lib, linker, user.
400/// "foo" is a string, which is fully macro expanded, and permits string
401/// concatenation, embedded escape characters etc.  See MSDN for more details.
402void Preprocessor::HandlePragmaComment(Token &Tok) {
403  SourceLocation CommentLoc = Tok.getLocation();
404  Lex(Tok);
405  if (Tok.isNot(tok::l_paren)) {
406    Diag(CommentLoc, diag::err_pragma_comment_malformed);
407    return;
408  }
409
410  // Read the identifier.
411  Lex(Tok);
412  if (Tok.isNot(tok::identifier)) {
413    Diag(CommentLoc, diag::err_pragma_comment_malformed);
414    return;
415  }
416
417  // Verify that this is one of the 5 whitelisted options.
418  // FIXME: warn that 'exestr' is deprecated.
419  const IdentifierInfo *II = Tok.getIdentifierInfo();
420  if (!II->isStr("compiler") && !II->isStr("exestr") && !II->isStr("lib") &&
421      !II->isStr("linker") && !II->isStr("user")) {
422    Diag(Tok.getLocation(), diag::err_pragma_comment_unknown_kind);
423    return;
424  }
425
426  // Read the optional string if present.
427  Lex(Tok);
428  std::string ArgumentString;
429  if (Tok.is(tok::comma)) {
430    Lex(Tok); // eat the comma.
431
432    // We need at least one string.
433    if (Tok.isNot(tok::string_literal)) {
434      Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
435      return;
436    }
437
438    // String concatenation allows multiple strings, which can even come from
439    // macro expansion.
440    // "foo " "bar" "Baz"
441    llvm::SmallVector<Token, 4> StrToks;
442    while (Tok.is(tok::string_literal)) {
443      StrToks.push_back(Tok);
444      Lex(Tok);
445    }
446
447    // Concatenate and parse the strings.
448    StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
449    assert(!Literal.AnyWide && "Didn't allow wide strings in");
450    if (Literal.hadError)
451      return;
452    if (Literal.Pascal) {
453      Diag(StrToks[0].getLocation(), diag::err_pragma_comment_malformed);
454      return;
455    }
456
457    ArgumentString = std::string(Literal.GetString(),
458                                 Literal.GetString()+Literal.GetStringLength());
459  }
460
461  // FIXME: If the kind is "compiler" warn if the string is present (it is
462  // ignored).
463  // FIXME: 'lib' requires a comment string.
464  // FIXME: 'linker' requires a comment string, and has a specific list of
465  // things that are allowable.
466
467  if (Tok.isNot(tok::r_paren)) {
468    Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
469    return;
470  }
471  Lex(Tok);  // eat the r_paren.
472
473  if (Tok.isNot(tok::eod)) {
474    Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
475    return;
476  }
477
478  // If the pragma is lexically sound, notify any interested PPCallbacks.
479  if (Callbacks)
480    Callbacks->PragmaComment(CommentLoc, II, ArgumentString);
481}
482
483/// HandlePragmaMessage - Handle the microsoft and gcc #pragma message
484/// extension.  The syntax is:
485///   #pragma message(string)
486/// OR, in GCC mode:
487///   #pragma message string
488/// string is a string, which is fully macro expanded, and permits string
489/// concatenation, embedded escape characters, etc... See MSDN for more details.
490void Preprocessor::HandlePragmaMessage(Token &Tok) {
491  SourceLocation MessageLoc = Tok.getLocation();
492  Lex(Tok);
493  bool ExpectClosingParen = false;
494  switch (Tok.getKind()) {
495  case tok::l_paren:
496    // We have a MSVC style pragma message.
497    ExpectClosingParen = true;
498    // Read the string.
499    Lex(Tok);
500    break;
501  case tok::string_literal:
502    // We have a GCC style pragma message, and we just read the string.
503    break;
504  default:
505    Diag(MessageLoc, diag::err_pragma_message_malformed);
506    return;
507  }
508
509  // We need at least one string.
510  if (Tok.isNot(tok::string_literal)) {
511    Diag(Tok.getLocation(), diag::err_pragma_message_malformed);
512    return;
513  }
514
515  // String concatenation allows multiple strings, which can even come from
516  // macro expansion.
517  // "foo " "bar" "Baz"
518  llvm::SmallVector<Token, 4> StrToks;
519  while (Tok.is(tok::string_literal)) {
520    StrToks.push_back(Tok);
521    Lex(Tok);
522  }
523
524  // Concatenate and parse the strings.
525  StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
526  assert(!Literal.AnyWide && "Didn't allow wide strings in");
527  if (Literal.hadError)
528    return;
529  if (Literal.Pascal) {
530    Diag(StrToks[0].getLocation(), diag::err_pragma_message_malformed);
531    return;
532  }
533
534  llvm::StringRef MessageString(Literal.GetString(), Literal.GetStringLength());
535
536  if (ExpectClosingParen) {
537    if (Tok.isNot(tok::r_paren)) {
538      Diag(Tok.getLocation(), diag::err_pragma_message_malformed);
539      return;
540    }
541    Lex(Tok);  // eat the r_paren.
542  }
543
544  if (Tok.isNot(tok::eod)) {
545    Diag(Tok.getLocation(), diag::err_pragma_message_malformed);
546    return;
547  }
548
549  // Output the message.
550  Diag(MessageLoc, diag::warn_pragma_message) << MessageString;
551
552  // If the pragma is lexically sound, notify any interested PPCallbacks.
553  if (Callbacks)
554    Callbacks->PragmaMessage(MessageLoc, MessageString);
555}
556
557/// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
558/// Return the IdentifierInfo* associated with the macro to push or pop.
559IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
560  // Remember the pragma token location.
561  Token PragmaTok = Tok;
562
563  // Read the '('.
564  Lex(Tok);
565  if (Tok.isNot(tok::l_paren)) {
566    Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
567      << getSpelling(PragmaTok);
568    return 0;
569  }
570
571  // Read the macro name string.
572  Lex(Tok);
573  if (Tok.isNot(tok::string_literal)) {
574    Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
575      << getSpelling(PragmaTok);
576    return 0;
577  }
578
579  // Remember the macro string.
580  std::string StrVal = getSpelling(Tok);
581
582  // Read the ')'.
583  Lex(Tok);
584  if (Tok.isNot(tok::r_paren)) {
585    Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
586      << getSpelling(PragmaTok);
587    return 0;
588  }
589
590  assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
591         "Invalid string token!");
592
593  // Create a Token from the string.
594  Token MacroTok;
595  MacroTok.startToken();
596  MacroTok.setKind(tok::raw_identifier);
597  CreateString(&StrVal[1], StrVal.size() - 2, MacroTok);
598
599  // Get the IdentifierInfo of MacroToPushTok.
600  return LookUpIdentifierInfo(MacroTok);
601}
602
603/// HandlePragmaPushMacro - Handle #pragma push_macro.
604/// The syntax is:
605///   #pragma push_macro("macro")
606void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
607  // Parse the pragma directive and get the macro IdentifierInfo*.
608  IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
609  if (!IdentInfo) return;
610
611  // Get the MacroInfo associated with IdentInfo.
612  MacroInfo *MI = getMacroInfo(IdentInfo);
613
614  MacroInfo *MacroCopyToPush = 0;
615  if (MI) {
616    // Make a clone of MI.
617    MacroCopyToPush = CloneMacroInfo(*MI);
618
619    // Allow the original MacroInfo to be redefined later.
620    MI->setIsAllowRedefinitionsWithoutWarning(true);
621  }
622
623  // Push the cloned MacroInfo so we can retrieve it later.
624  PragmaPushMacroInfo[IdentInfo].push_back(MacroCopyToPush);
625}
626
627/// HandlePragmaPopMacro - Handle #pragma pop_macro.
628/// The syntax is:
629///   #pragma pop_macro("macro")
630void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
631  SourceLocation MessageLoc = PopMacroTok.getLocation();
632
633  // Parse the pragma directive and get the macro IdentifierInfo*.
634  IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
635  if (!IdentInfo) return;
636
637  // Find the vector<MacroInfo*> associated with the macro.
638  llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
639    PragmaPushMacroInfo.find(IdentInfo);
640  if (iter != PragmaPushMacroInfo.end()) {
641    // Release the MacroInfo currently associated with IdentInfo.
642    MacroInfo *CurrentMI = getMacroInfo(IdentInfo);
643    if (CurrentMI) {
644      if (CurrentMI->isWarnIfUnused())
645        WarnUnusedMacroLocs.erase(CurrentMI->getDefinitionLoc());
646      ReleaseMacroInfo(CurrentMI);
647    }
648
649    // Get the MacroInfo we want to reinstall.
650    MacroInfo *MacroToReInstall = iter->second.back();
651
652    // Reinstall the previously pushed macro.
653    setMacroInfo(IdentInfo, MacroToReInstall);
654
655    // Pop PragmaPushMacroInfo stack.
656    iter->second.pop_back();
657    if (iter->second.size() == 0)
658      PragmaPushMacroInfo.erase(iter);
659  } else {
660    Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
661      << IdentInfo->getName();
662  }
663}
664
665/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
666/// If 'Namespace' is non-null, then it is a token required to exist on the
667/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
668void Preprocessor::AddPragmaHandler(llvm::StringRef Namespace,
669                                    PragmaHandler *Handler) {
670  PragmaNamespace *InsertNS = PragmaHandlers;
671
672  // If this is specified to be in a namespace, step down into it.
673  if (!Namespace.empty()) {
674    // If there is already a pragma handler with the name of this namespace,
675    // we either have an error (directive with the same name as a namespace) or
676    // we already have the namespace to insert into.
677    if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
678      InsertNS = Existing->getIfNamespace();
679      assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
680             " handler with the same name!");
681    } else {
682      // Otherwise, this namespace doesn't exist yet, create and insert the
683      // handler for it.
684      InsertNS = new PragmaNamespace(Namespace);
685      PragmaHandlers->AddPragma(InsertNS);
686    }
687  }
688
689  // Check to make sure we don't already have a pragma for this identifier.
690  assert(!InsertNS->FindHandler(Handler->getName()) &&
691         "Pragma handler already exists for this identifier!");
692  InsertNS->AddPragma(Handler);
693}
694
695/// RemovePragmaHandler - Remove the specific pragma handler from the
696/// preprocessor. If \arg Namespace is non-null, then it should be the
697/// namespace that \arg Handler was added to. It is an error to remove
698/// a handler that has not been registered.
699void Preprocessor::RemovePragmaHandler(llvm::StringRef Namespace,
700                                       PragmaHandler *Handler) {
701  PragmaNamespace *NS = PragmaHandlers;
702
703  // If this is specified to be in a namespace, step down into it.
704  if (!Namespace.empty()) {
705    PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
706    assert(Existing && "Namespace containing handler does not exist!");
707
708    NS = Existing->getIfNamespace();
709    assert(NS && "Invalid namespace, registered as a regular pragma handler!");
710  }
711
712  NS->RemovePragmaHandler(Handler);
713
714  // If this is a non-default namespace and it is now empty, remove
715  // it.
716  if (NS != PragmaHandlers && NS->IsEmpty())
717    PragmaHandlers->RemovePragmaHandler(NS);
718}
719
720bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
721  Token Tok;
722  LexUnexpandedToken(Tok);
723
724  if (Tok.isNot(tok::identifier)) {
725    Diag(Tok, diag::ext_on_off_switch_syntax);
726    return true;
727  }
728  IdentifierInfo *II = Tok.getIdentifierInfo();
729  if (II->isStr("ON"))
730    Result = tok::OOS_ON;
731  else if (II->isStr("OFF"))
732    Result = tok::OOS_OFF;
733  else if (II->isStr("DEFAULT"))
734    Result = tok::OOS_DEFAULT;
735  else {
736    Diag(Tok, diag::ext_on_off_switch_syntax);
737    return true;
738  }
739
740  // Verify that this is followed by EOD.
741  LexUnexpandedToken(Tok);
742  if (Tok.isNot(tok::eod))
743    Diag(Tok, diag::ext_pragma_syntax_eod);
744  return false;
745}
746
747namespace {
748/// PragmaOnceHandler - "#pragma once" marks the file as atomically included.
749struct PragmaOnceHandler : public PragmaHandler {
750  PragmaOnceHandler() : PragmaHandler("once") {}
751  virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
752                            Token &OnceTok) {
753    PP.CheckEndOfDirective("pragma once");
754    PP.HandlePragmaOnce(OnceTok);
755  }
756};
757
758/// PragmaMarkHandler - "#pragma mark ..." is ignored by the compiler, and the
759/// rest of the line is not lexed.
760struct PragmaMarkHandler : public PragmaHandler {
761  PragmaMarkHandler() : PragmaHandler("mark") {}
762  virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
763                            Token &MarkTok) {
764    PP.HandlePragmaMark();
765  }
766};
767
768/// PragmaPoisonHandler - "#pragma poison x" marks x as not usable.
769struct PragmaPoisonHandler : public PragmaHandler {
770  PragmaPoisonHandler() : PragmaHandler("poison") {}
771  virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
772                            Token &PoisonTok) {
773    PP.HandlePragmaPoison(PoisonTok);
774  }
775};
776
777/// PragmaSystemHeaderHandler - "#pragma system_header" marks the current file
778/// as a system header, which silences warnings in it.
779struct PragmaSystemHeaderHandler : public PragmaHandler {
780  PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
781  virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
782                            Token &SHToken) {
783    PP.HandlePragmaSystemHeader(SHToken);
784    PP.CheckEndOfDirective("pragma");
785  }
786};
787struct PragmaDependencyHandler : public PragmaHandler {
788  PragmaDependencyHandler() : PragmaHandler("dependency") {}
789  virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
790                            Token &DepToken) {
791    PP.HandlePragmaDependency(DepToken);
792  }
793};
794
795struct PragmaDebugHandler : public PragmaHandler {
796  PragmaDebugHandler() : PragmaHandler("__debug") {}
797  virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
798                            Token &DepToken) {
799    Token Tok;
800    PP.LexUnexpandedToken(Tok);
801    if (Tok.isNot(tok::identifier)) {
802      PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
803      return;
804    }
805    IdentifierInfo *II = Tok.getIdentifierInfo();
806
807    if (II->isStr("assert")) {
808      assert(0 && "This is an assertion!");
809    } else if (II->isStr("crash")) {
810      *(volatile int*) 0x11 = 0;
811    } else if (II->isStr("llvm_fatal_error")) {
812      llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
813    } else if (II->isStr("llvm_unreachable")) {
814      llvm_unreachable("#pragma clang __debug llvm_unreachable");
815    } else if (II->isStr("overflow_stack")) {
816      DebugOverflowStack();
817    } else if (II->isStr("handle_crash")) {
818      llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
819      if (CRC)
820        CRC->HandleCrash();
821    } else {
822      PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
823        << II->getName();
824    }
825  }
826
827  void DebugOverflowStack() {
828    DebugOverflowStack();
829  }
830};
831
832/// PragmaDiagnosticHandler - e.g. '#pragma GCC diagnostic ignored "-Wformat"'
833struct PragmaDiagnosticHandler : public PragmaHandler {
834public:
835  explicit PragmaDiagnosticHandler() : PragmaHandler("diagnostic") {}
836  virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
837                            Token &DiagToken) {
838    SourceLocation DiagLoc = DiagToken.getLocation();
839    Token Tok;
840    PP.LexUnexpandedToken(Tok);
841    if (Tok.isNot(tok::identifier)) {
842      PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
843      return;
844    }
845    IdentifierInfo *II = Tok.getIdentifierInfo();
846
847    diag::Mapping Map;
848    if (II->isStr("warning"))
849      Map = diag::MAP_WARNING;
850    else if (II->isStr("error"))
851      Map = diag::MAP_ERROR;
852    else if (II->isStr("ignored"))
853      Map = diag::MAP_IGNORE;
854    else if (II->isStr("fatal"))
855      Map = diag::MAP_FATAL;
856    else if (II->isStr("pop")) {
857      if (!PP.getDiagnostics().popMappings(DiagLoc))
858        PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
859
860      return;
861    } else if (II->isStr("push")) {
862      PP.getDiagnostics().pushMappings(DiagLoc);
863      return;
864    } else {
865      PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
866      return;
867    }
868
869    PP.LexUnexpandedToken(Tok);
870
871    // We need at least one string.
872    if (Tok.isNot(tok::string_literal)) {
873      PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
874      return;
875    }
876
877    // String concatenation allows multiple strings, which can even come from
878    // macro expansion.
879    // "foo " "bar" "Baz"
880    llvm::SmallVector<Token, 4> StrToks;
881    while (Tok.is(tok::string_literal)) {
882      StrToks.push_back(Tok);
883      PP.LexUnexpandedToken(Tok);
884    }
885
886    if (Tok.isNot(tok::eod)) {
887      PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
888      return;
889    }
890
891    // Concatenate and parse the strings.
892    StringLiteralParser Literal(&StrToks[0], StrToks.size(), PP);
893    assert(!Literal.AnyWide && "Didn't allow wide strings in");
894    if (Literal.hadError)
895      return;
896    if (Literal.Pascal) {
897      PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
898      return;
899    }
900
901    std::string WarningName(Literal.GetString(),
902                            Literal.GetString()+Literal.GetStringLength());
903
904    if (WarningName.size() < 3 || WarningName[0] != '-' ||
905        WarningName[1] != 'W') {
906      PP.Diag(StrToks[0].getLocation(),
907              diag::warn_pragma_diagnostic_invalid_option);
908      return;
909    }
910
911    if (PP.getDiagnostics().setDiagnosticGroupMapping(WarningName.c_str()+2,
912                                                      Map, DiagLoc))
913      PP.Diag(StrToks[0].getLocation(),
914              diag::warn_pragma_diagnostic_unknown_warning) << WarningName;
915  }
916};
917
918/// PragmaCommentHandler - "#pragma comment ...".
919struct PragmaCommentHandler : public PragmaHandler {
920  PragmaCommentHandler() : PragmaHandler("comment") {}
921  virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
922                            Token &CommentTok) {
923    PP.HandlePragmaComment(CommentTok);
924  }
925};
926
927/// PragmaMessageHandler - "#pragma message("...")".
928struct PragmaMessageHandler : public PragmaHandler {
929  PragmaMessageHandler() : PragmaHandler("message") {}
930  virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
931                            Token &CommentTok) {
932    PP.HandlePragmaMessage(CommentTok);
933  }
934};
935
936/// PragmaPushMacroHandler - "#pragma push_macro" saves the value of the
937/// macro on the top of the stack.
938struct PragmaPushMacroHandler : public PragmaHandler {
939  PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
940  virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
941                            Token &PushMacroTok) {
942    PP.HandlePragmaPushMacro(PushMacroTok);
943  }
944};
945
946
947/// PragmaPopMacroHandler - "#pragma pop_macro" sets the value of the
948/// macro to the value on the top of the stack.
949struct PragmaPopMacroHandler : public PragmaHandler {
950  PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
951  virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
952                            Token &PopMacroTok) {
953    PP.HandlePragmaPopMacro(PopMacroTok);
954  }
955};
956
957// Pragma STDC implementations.
958
959/// PragmaSTDC_FENV_ACCESSHandler - "#pragma STDC FENV_ACCESS ...".
960struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
961  PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
962  virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
963                            Token &Tok) {
964    tok::OnOffSwitch OOS;
965    if (PP.LexOnOffSwitch(OOS))
966     return;
967    if (OOS == tok::OOS_ON)
968      PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
969  }
970};
971
972/// PragmaSTDC_CX_LIMITED_RANGEHandler - "#pragma STDC CX_LIMITED_RANGE ...".
973struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
974  PragmaSTDC_CX_LIMITED_RANGEHandler()
975    : PragmaHandler("CX_LIMITED_RANGE") {}
976  virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
977                            Token &Tok) {
978    tok::OnOffSwitch OOS;
979    PP.LexOnOffSwitch(OOS);
980  }
981};
982
983/// PragmaSTDC_UnknownHandler - "#pragma STDC ...".
984struct PragmaSTDC_UnknownHandler : public PragmaHandler {
985  PragmaSTDC_UnknownHandler() {}
986  virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
987                            Token &UnknownTok) {
988    // C99 6.10.6p2, unknown forms are not allowed.
989    PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
990  }
991};
992
993}  // end anonymous namespace
994
995
996/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
997/// #pragma GCC poison/system_header/dependency and #pragma once.
998void Preprocessor::RegisterBuiltinPragmas() {
999  AddPragmaHandler(new PragmaOnceHandler());
1000  AddPragmaHandler(new PragmaMarkHandler());
1001  AddPragmaHandler(new PragmaPushMacroHandler());
1002  AddPragmaHandler(new PragmaPopMacroHandler());
1003  AddPragmaHandler(new PragmaMessageHandler());
1004
1005  // #pragma GCC ...
1006  AddPragmaHandler("GCC", new PragmaPoisonHandler());
1007  AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1008  AddPragmaHandler("GCC", new PragmaDependencyHandler());
1009  AddPragmaHandler("GCC", new PragmaDiagnosticHandler());
1010  // #pragma clang ...
1011  AddPragmaHandler("clang", new PragmaPoisonHandler());
1012  AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
1013  AddPragmaHandler("clang", new PragmaDebugHandler());
1014  AddPragmaHandler("clang", new PragmaDependencyHandler());
1015  AddPragmaHandler("clang", new PragmaDiagnosticHandler());
1016
1017  AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1018  AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
1019  AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
1020
1021  // MS extensions.
1022  if (Features.Microsoft) {
1023    AddPragmaHandler(new PragmaCommentHandler());
1024  }
1025}
1026