Pragma.cpp revision 35410d5cbbb18735d76e00496540d416dc49b577
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/Lex/HeaderSearch.h"
17#include "clang/Lex/LiteralSupport.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Lex/LexDiagnostic.h"
20#include "clang/Basic/FileManager.h"
21#include "clang/Basic/SourceManager.h"
22using namespace clang;
23
24// Out-of-line destructor to provide a home for the class.
25PragmaHandler::~PragmaHandler() {
26}
27
28//===----------------------------------------------------------------------===//
29// PragmaNamespace Implementation.
30//===----------------------------------------------------------------------===//
31
32
33PragmaNamespace::~PragmaNamespace() {
34  for (unsigned i = 0, e = Handlers.size(); i != e; ++i)
35    delete Handlers[i];
36}
37
38/// FindHandler - Check to see if there is already a handler for the
39/// specified name.  If not, return the handler for the null identifier if it
40/// exists, otherwise return null.  If IgnoreNull is true (the default) then
41/// the null handler isn't returned on failure to match.
42PragmaHandler *PragmaNamespace::FindHandler(const IdentifierInfo *Name,
43                                            bool IgnoreNull) const {
44  PragmaHandler *NullHandler = 0;
45  for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
46    if (Handlers[i]->getName() == Name)
47      return Handlers[i];
48
49    if (Handlers[i]->getName() == 0)
50      NullHandler = Handlers[i];
51  }
52  return IgnoreNull ? 0 : NullHandler;
53}
54
55void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
56  for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
57    if (Handlers[i] == Handler) {
58      Handlers[i] = Handlers.back();
59      Handlers.pop_back();
60      return;
61    }
62  }
63  assert(0 && "Handler not registered in this namespace");
64}
65
66void PragmaNamespace::HandlePragma(Preprocessor &PP, Token &Tok) {
67  // Read the 'namespace' that the directive is in, e.g. STDC.  Do not macro
68  // expand it, the user can have a STDC #define, that should not affect this.
69  PP.LexUnexpandedToken(Tok);
70
71  // Get the handler for this token.  If there is no handler, ignore the pragma.
72  PragmaHandler *Handler = FindHandler(Tok.getIdentifierInfo(), false);
73  if (Handler == 0) return;
74
75  // Otherwise, pass it down.
76  Handler->HandlePragma(PP, Tok);
77}
78
79//===----------------------------------------------------------------------===//
80// Preprocessor Pragma Directive Handling.
81//===----------------------------------------------------------------------===//
82
83/// HandlePragmaDirective - The "#pragma" directive has been parsed.  Lex the
84/// rest of the pragma, passing it to the registered pragma handlers.
85void Preprocessor::HandlePragmaDirective() {
86  ++NumPragma;
87
88  // Invoke the first level of pragma handlers which reads the namespace id.
89  Token Tok;
90  PragmaHandlers->HandlePragma(*this, Tok);
91
92  // If the pragma handler didn't read the rest of the line, consume it now.
93  if (CurPPLexer->ParsingPreprocessorDirective)
94    DiscardUntilEndOfDirective();
95}
96
97/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
98/// return the first token after the directive.  The _Pragma token has just
99/// been read into 'Tok'.
100void Preprocessor::Handle_Pragma(Token &Tok) {
101  // Remember the pragma token location.
102  SourceLocation PragmaLoc = Tok.getLocation();
103
104  // Read the '('.
105  Lex(Tok);
106  if (Tok.isNot(tok::l_paren)) {
107    Diag(PragmaLoc, diag::err__Pragma_malformed);
108    return;
109  }
110
111  // Read the '"..."'.
112  Lex(Tok);
113  if (Tok.isNot(tok::string_literal) && Tok.isNot(tok::wide_string_literal)) {
114    Diag(PragmaLoc, diag::err__Pragma_malformed);
115    return;
116  }
117
118  // Remember the string.
119  std::string StrVal = getSpelling(Tok);
120
121  // Read the ')'.
122  Lex(Tok);
123  if (Tok.isNot(tok::r_paren)) {
124    Diag(PragmaLoc, diag::err__Pragma_malformed);
125    return;
126  }
127
128  SourceLocation RParenLoc = Tok.getLocation();
129
130  // The _Pragma is lexically sound.  Destringize according to C99 6.10.9.1:
131  // "The string literal is destringized by deleting the L prefix, if present,
132  // deleting the leading and trailing double-quotes, replacing each escape
133  // sequence \" by a double-quote, and replacing each escape sequence \\ by a
134  // single backslash."
135  if (StrVal[0] == 'L')  // Remove L prefix.
136    StrVal.erase(StrVal.begin());
137  assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
138         "Invalid string token!");
139
140  // Remove the front quote, replacing it with a space, so that the pragma
141  // contents appear to have a space before them.
142  StrVal[0] = ' ';
143
144  // Replace the terminating quote with a \n.
145  StrVal[StrVal.size()-1] = '\n';
146
147  // Remove escaped quotes and escapes.
148  for (unsigned i = 0, e = StrVal.size(); i != e-1; ++i) {
149    if (StrVal[i] == '\\' &&
150        (StrVal[i+1] == '\\' || StrVal[i+1] == '"')) {
151      // \\ -> '\' and \" -> '"'.
152      StrVal.erase(StrVal.begin()+i);
153      --e;
154    }
155  }
156
157  // Plop the string (including the newline and trailing null) into a buffer
158  // where we can lex it.
159  Token TmpTok;
160  TmpTok.startToken();
161  CreateString(&StrVal[0], StrVal.size(), TmpTok);
162  SourceLocation TokLoc = TmpTok.getLocation();
163
164  // Make and enter a lexer object so that we lex and expand the tokens just
165  // like any others.
166  Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
167                                        StrVal.size(), *this);
168
169  EnterSourceFileWithLexer(TL, 0);
170
171  // With everything set up, lex this as a #pragma directive.
172  HandlePragmaDirective();
173
174  // Finally, return whatever came after the pragma directive.
175  return Lex(Tok);
176}
177
178
179
180/// HandlePragmaOnce - Handle #pragma once.  OnceTok is the 'once'.
181///
182void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
183  if (isInPrimaryFile()) {
184    Diag(OnceTok, diag::pp_pragma_once_in_main_file);
185    return;
186  }
187
188  // Get the current file lexer we're looking at.  Ignore _Pragma 'files' etc.
189  // Mark the file as a once-only file now.
190  HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
191}
192
193void Preprocessor::HandlePragmaMark() {
194  assert(CurPPLexer && "No current lexer?");
195  if (CurLexer) CurLexer->ReadToEndOfLine();
196  else CurPTHLexer->DiscardToEndOfLine();
197}
198
199
200/// HandlePragmaPoison - Handle #pragma GCC poison.  PoisonTok is the 'poison'.
201///
202void Preprocessor::HandlePragmaPoison(Token &PoisonTok) {
203  Token Tok;
204
205  while (1) {
206    // Read the next token to poison.  While doing this, pretend that we are
207    // skipping while reading the identifier to poison.
208    // This avoids errors on code like:
209    //   #pragma GCC poison X
210    //   #pragma GCC poison X
211    if (CurPPLexer) CurPPLexer->LexingRawMode = true;
212    LexUnexpandedToken(Tok);
213    if (CurPPLexer) CurPPLexer->LexingRawMode = false;
214
215    // If we reached the end of line, we're done.
216    if (Tok.is(tok::eom)) return;
217
218    // Can only poison identifiers.
219    if (Tok.isNot(tok::identifier)) {
220      Diag(Tok, diag::err_pp_invalid_poison);
221      return;
222    }
223
224    // Look up the identifier info for the token.  We disabled identifier lookup
225    // by saying we're skipping contents, so we need to do this manually.
226    IdentifierInfo *II = LookUpIdentifierInfo(Tok);
227
228    // Already poisoned.
229    if (II->isPoisoned()) continue;
230
231    // If this is a macro identifier, emit a warning.
232    if (II->hasMacroDefinition())
233      Diag(Tok, diag::pp_poisoning_existing_macro);
234
235    // Finally, poison it!
236    II->setIsPoisoned();
237  }
238}
239
240/// HandlePragmaSystemHeader - Implement #pragma GCC system_header.  We know
241/// that the whole directive has been parsed.
242void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
243  if (isInPrimaryFile()) {
244    Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
245    return;
246  }
247
248  // Get the current file lexer we're looking at.  Ignore _Pragma 'files' etc.
249  PreprocessorLexer *TheLexer = getCurrentFileLexer();
250
251  // Mark the file as a system header.
252  HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
253
254  // Notify the client, if desired, that we are in a new source file.
255  if (Callbacks)
256    Callbacks->FileChanged(SysHeaderTok.getLocation(),
257                           PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
258}
259
260/// HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah.
261///
262void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
263  Token FilenameTok;
264  CurPPLexer->LexIncludeFilename(FilenameTok);
265
266  // If the token kind is EOM, the error has already been diagnosed.
267  if (FilenameTok.is(tok::eom))
268    return;
269
270  // Reserve a buffer to get the spelling.
271  llvm::SmallVector<char, 128> FilenameBuffer;
272  FilenameBuffer.resize(FilenameTok.getLength());
273
274  const char *FilenameStart = &FilenameBuffer[0];
275  unsigned Len = getSpelling(FilenameTok, FilenameStart);
276  const char *FilenameEnd = FilenameStart+Len;
277  bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
278                                             FilenameStart, FilenameEnd);
279  // If GetIncludeFilenameSpelling set the start ptr to null, there was an
280  // error.
281  if (FilenameStart == 0)
282    return;
283
284  // Search include directories for this file.
285  const DirectoryLookup *CurDir;
286  const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
287                                     isAngled, 0, CurDir);
288  if (File == 0) {
289    Diag(FilenameTok, diag::err_pp_file_not_found)
290      << std::string(FilenameStart, FilenameEnd);
291    return;
292  }
293
294  const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
295
296  // If this file is older than the file it depends on, emit a diagnostic.
297  if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
298    // Lex tokens at the end of the message and include them in the message.
299    std::string Message;
300    Lex(DependencyTok);
301    while (DependencyTok.isNot(tok::eom)) {
302      Message += getSpelling(DependencyTok) + " ";
303      Lex(DependencyTok);
304    }
305
306    Message.erase(Message.end()-1);
307    Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
308  }
309}
310
311/// HandlePragmaComment - Handle the microsoft #pragma comment extension.  The
312/// syntax is:
313///   #pragma comment(linker, "foo")
314/// 'linker' is one of five identifiers: compiler, exestr, lib, linker, user.
315/// "foo" is a string, which is fully macro expanded, and permits string
316/// concatenation, embedded escape characters etc.  See MSDN for more details.
317void Preprocessor::HandlePragmaComment(Token &Tok) {
318  SourceLocation CommentLoc = Tok.getLocation();
319  Lex(Tok);
320  if (Tok.isNot(tok::l_paren)) {
321    Diag(CommentLoc, diag::err_pragma_comment_malformed);
322    return;
323  }
324
325  // Read the identifier.
326  Lex(Tok);
327  if (Tok.isNot(tok::identifier)) {
328    Diag(CommentLoc, diag::err_pragma_comment_malformed);
329    return;
330  }
331
332  // Verify that this is one of the 5 whitelisted options.
333  // FIXME: warn that 'exestr' is deprecated.
334  const IdentifierInfo *II = Tok.getIdentifierInfo();
335  if (!II->isStr("compiler") && !II->isStr("exestr") && !II->isStr("lib") &&
336      !II->isStr("linker") && !II->isStr("user")) {
337    Diag(Tok.getLocation(), diag::err_pragma_comment_unknown_kind);
338    return;
339  }
340
341  // Read the optional string if present.
342  Lex(Tok);
343  std::string ArgumentString;
344  if (Tok.is(tok::comma)) {
345    Lex(Tok); // eat the comma.
346
347    // We need at least one string.
348    if (Tok.getKind() != tok::string_literal) {
349      Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
350      return;
351    }
352
353    // String concatenation allows multiple strings, which can even come from
354    // macro expansion.
355    // "foo " "bar" "Baz"
356    llvm::SmallVector<Token, 4> StrToks;
357    while (Tok.getKind() == tok::string_literal) {
358      StrToks.push_back(Tok);
359      Lex(Tok);
360    }
361
362    // Concatenate and parse the strings.
363    StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
364    assert(!Literal.AnyWide && "Didn't allow wide strings in");
365    if (Literal.hadError)
366      return;
367    if (Literal.Pascal) {
368      Diag(StrToks[0].getLocation(), diag::err_pragma_comment_malformed);
369      return;
370    }
371
372    ArgumentString = std::string(Literal.GetString(),
373                                 Literal.GetString()+Literal.GetStringLength());
374  }
375
376  // FIXME: If the kind is "compiler" warn if the string is present (it is
377  // ignored).
378  // FIXME: 'lib' requires a comment string.
379  // FIXME: 'linker' requires a comment string, and has a specific list of
380  // things that are allowable.
381
382  if (Tok.isNot(tok::r_paren)) {
383    Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
384    return;
385  }
386  Lex(Tok);  // eat the r_paren.
387
388  if (Tok.isNot(tok::eom)) {
389    Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
390    return;
391  }
392
393  // If the pragma is lexically sound, notify any interested PPCallbacks.
394  if (Callbacks)
395    Callbacks->PragmaComment(CommentLoc, II, ArgumentString);
396}
397
398
399
400
401/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
402/// If 'Namespace' is non-null, then it is a token required to exist on the
403/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
404void Preprocessor::AddPragmaHandler(const char *Namespace,
405                                    PragmaHandler *Handler) {
406  PragmaNamespace *InsertNS = PragmaHandlers;
407
408  // If this is specified to be in a namespace, step down into it.
409  if (Namespace) {
410    IdentifierInfo *NSID = getIdentifierInfo(Namespace);
411
412    // If there is already a pragma handler with the name of this namespace,
413    // we either have an error (directive with the same name as a namespace) or
414    // we already have the namespace to insert into.
415    if (PragmaHandler *Existing = PragmaHandlers->FindHandler(NSID)) {
416      InsertNS = Existing->getIfNamespace();
417      assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
418             " handler with the same name!");
419    } else {
420      // Otherwise, this namespace doesn't exist yet, create and insert the
421      // handler for it.
422      InsertNS = new PragmaNamespace(NSID);
423      PragmaHandlers->AddPragma(InsertNS);
424    }
425  }
426
427  // Check to make sure we don't already have a pragma for this identifier.
428  assert(!InsertNS->FindHandler(Handler->getName()) &&
429         "Pragma handler already exists for this identifier!");
430  InsertNS->AddPragma(Handler);
431}
432
433/// RemovePragmaHandler - Remove the specific pragma handler from the
434/// preprocessor. If \arg Namespace is non-null, then it should be the
435/// namespace that \arg Handler was added to. It is an error to remove
436/// a handler that has not been registered.
437void Preprocessor::RemovePragmaHandler(const char *Namespace,
438                                       PragmaHandler *Handler) {
439  PragmaNamespace *NS = PragmaHandlers;
440
441  // If this is specified to be in a namespace, step down into it.
442  if (Namespace) {
443    IdentifierInfo *NSID = getIdentifierInfo(Namespace);
444    PragmaHandler *Existing = PragmaHandlers->FindHandler(NSID);
445    assert(Existing && "Namespace containing handler does not exist!");
446
447    NS = Existing->getIfNamespace();
448    assert(NS && "Invalid namespace, registered as a regular pragma handler!");
449  }
450
451  NS->RemovePragmaHandler(Handler);
452
453  // If this is a non-default namespace and it is now empty, remove
454  // it.
455  if (NS != PragmaHandlers && NS->IsEmpty())
456    PragmaHandlers->RemovePragmaHandler(NS);
457}
458
459namespace {
460/// PragmaOnceHandler - "#pragma once" marks the file as atomically included.
461struct PragmaOnceHandler : public PragmaHandler {
462  PragmaOnceHandler(const IdentifierInfo *OnceID) : PragmaHandler(OnceID) {}
463  virtual void HandlePragma(Preprocessor &PP, Token &OnceTok) {
464    PP.CheckEndOfDirective("pragma once");
465    PP.HandlePragmaOnce(OnceTok);
466  }
467};
468
469/// PragmaMarkHandler - "#pragma mark ..." is ignored by the compiler, and the
470/// rest of the line is not lexed.
471struct PragmaMarkHandler : public PragmaHandler {
472  PragmaMarkHandler(const IdentifierInfo *MarkID) : PragmaHandler(MarkID) {}
473  virtual void HandlePragma(Preprocessor &PP, Token &MarkTok) {
474    PP.HandlePragmaMark();
475  }
476};
477
478/// PragmaPoisonHandler - "#pragma poison x" marks x as not usable.
479struct PragmaPoisonHandler : public PragmaHandler {
480  PragmaPoisonHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
481  virtual void HandlePragma(Preprocessor &PP, Token &PoisonTok) {
482    PP.HandlePragmaPoison(PoisonTok);
483  }
484};
485
486/// PragmaSystemHeaderHandler - "#pragma system_header" marks the current file
487/// as a system header, which silences warnings in it.
488struct PragmaSystemHeaderHandler : public PragmaHandler {
489  PragmaSystemHeaderHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
490  virtual void HandlePragma(Preprocessor &PP, Token &SHToken) {
491    PP.HandlePragmaSystemHeader(SHToken);
492    PP.CheckEndOfDirective("pragma");
493  }
494};
495struct PragmaDependencyHandler : public PragmaHandler {
496  PragmaDependencyHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
497  virtual void HandlePragma(Preprocessor &PP, Token &DepToken) {
498    PP.HandlePragmaDependency(DepToken);
499  }
500};
501
502/// PragmaCommentHandler - "#pragma comment ...".
503struct PragmaCommentHandler : public PragmaHandler {
504  PragmaCommentHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
505  virtual void HandlePragma(Preprocessor &PP, Token &CommentTok) {
506    PP.HandlePragmaComment(CommentTok);
507  }
508};
509}  // end anonymous namespace
510
511
512/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
513/// #pragma GCC poison/system_header/dependency and #pragma once.
514void Preprocessor::RegisterBuiltinPragmas() {
515  AddPragmaHandler(0, new PragmaOnceHandler(getIdentifierInfo("once")));
516  AddPragmaHandler(0, new PragmaMarkHandler(getIdentifierInfo("mark")));
517  AddPragmaHandler("GCC", new PragmaPoisonHandler(getIdentifierInfo("poison")));
518  AddPragmaHandler("GCC", new PragmaSystemHeaderHandler(
519                                          getIdentifierInfo("system_header")));
520  AddPragmaHandler("GCC", new PragmaDependencyHandler(
521                                          getIdentifierInfo("dependency")));
522
523  // MS extensions.
524  if (Features.Microsoft)
525    AddPragmaHandler(0, new PragmaCommentHandler(getIdentifierInfo("comment")));
526}
527