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