blob: 05e524c0c1342ba34df096a01af5ddedb9aea245 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- Pragma.cpp - Pragma registration and handling --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source 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/PPCallbacks.h"
17#include "clang/Lex/HeaderSearch.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"
22#include "llvm/ADT/SmallVector.h"
23using namespace clang;
24
25// Out-of-line destructor to provide a home for the class.
26PragmaHandler::~PragmaHandler() {
27}
28
29//===----------------------------------------------------------------------===//
30// PragmaNamespace Implementation.
31//===----------------------------------------------------------------------===//
32
33
34PragmaNamespace::~PragmaNamespace() {
35 for (unsigned i = 0, e = Handlers.size(); i != e; ++i)
36 delete Handlers[i];
37}
38
39/// FindHandler - Check to see if there is already a handler for the
40/// specified name. If not, return the handler for the null identifier if it
41/// exists, otherwise return null. If IgnoreNull is true (the default) then
42/// the null handler isn't returned on failure to match.
43PragmaHandler *PragmaNamespace::FindHandler(const IdentifierInfo *Name,
44 bool IgnoreNull) const {
45 PragmaHandler *NullHandler = 0;
46 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
47 if (Handlers[i]->getName() == Name)
48 return Handlers[i];
49
50 if (Handlers[i]->getName() == 0)
51 NullHandler = Handlers[i];
52 }
53 return IgnoreNull ? 0 : NullHandler;
54}
55
56void PragmaNamespace::HandlePragma(Preprocessor &PP, Token &Tok) {
57 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
58 // expand it, the user can have a STDC #define, that should not affect this.
59 PP.LexUnexpandedToken(Tok);
60
61 // Get the handler for this token. If there is no handler, ignore the pragma.
62 PragmaHandler *Handler = FindHandler(Tok.getIdentifierInfo(), false);
63 if (Handler == 0) return;
64
65 // Otherwise, pass it down.
66 Handler->HandlePragma(PP, Tok);
67}
68
69//===----------------------------------------------------------------------===//
70// Preprocessor Pragma Directive Handling.
71//===----------------------------------------------------------------------===//
72
73/// HandlePragmaDirective - The "#pragma" directive has been parsed. Lex the
74/// rest of the pragma, passing it to the registered pragma handlers.
75void Preprocessor::HandlePragmaDirective() {
76 ++NumPragma;
77
78 // Invoke the first level of pragma handlers which reads the namespace id.
79 Token Tok;
80 PragmaHandlers->HandlePragma(*this, Tok);
81
82 // If the pragma handler didn't read the rest of the line, consume it now.
83 if (CurLexer->ParsingPreprocessorDirective)
84 DiscardUntilEndOfDirective();
85}
86
87/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
88/// return the first token after the directive. The _Pragma token has just
89/// been read into 'Tok'.
90void Preprocessor::Handle_Pragma(Token &Tok) {
91 // Remember the pragma token location.
92 SourceLocation PragmaLoc = Tok.getLocation();
93
94 // Read the '('.
95 Lex(Tok);
Chris Lattnercb8e41c2007-10-09 18:02:16 +000096 if (Tok.isNot(tok::l_paren))
Chris Lattner4b009652007-07-25 00:24:17 +000097 return Diag(PragmaLoc, diag::err__Pragma_malformed);
98
99 // Read the '"..."'.
100 Lex(Tok);
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000101 if (Tok.isNot(tok::string_literal) && Tok.isNot(tok::wide_string_literal))
Chris Lattner4b009652007-07-25 00:24:17 +0000102 return Diag(PragmaLoc, diag::err__Pragma_malformed);
103
104 // Remember the string.
105 std::string StrVal = getSpelling(Tok);
106 SourceLocation StrLoc = Tok.getLocation();
107
108 // Read the ')'.
109 Lex(Tok);
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000110 if (Tok.isNot(tok::r_paren))
Chris Lattner4b009652007-07-25 00:24:17 +0000111 return Diag(PragmaLoc, diag::err__Pragma_malformed);
112
113 // The _Pragma is lexically sound. Destringize according to C99 6.10.9.1.
114 if (StrVal[0] == 'L') // Remove L prefix.
115 StrVal.erase(StrVal.begin());
116 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
117 "Invalid string token!");
118
119 // Remove the front quote, replacing it with a space, so that the pragma
120 // contents appear to have a space before them.
121 StrVal[0] = ' ';
122
123 // Replace the terminating quote with a \n\0.
124 StrVal[StrVal.size()-1] = '\n';
125 StrVal += '\0';
126
127 // Remove escaped quotes and escapes.
128 for (unsigned i = 0, e = StrVal.size(); i != e-1; ++i) {
129 if (StrVal[i] == '\\' &&
130 (StrVal[i+1] == '\\' || StrVal[i+1] == '"')) {
131 // \\ -> '\' and \" -> '"'.
132 StrVal.erase(StrVal.begin()+i);
133 --e;
134 }
135 }
136
137 // Plop the string (including the newline and trailing null) into a buffer
138 // where we can lex it.
139 SourceLocation TokLoc = CreateString(&StrVal[0], StrVal.size(), StrLoc);
140 const char *StrData = SourceMgr.getCharacterData(TokLoc);
141
142 // Make and enter a lexer object so that we lex and expand the tokens just
143 // like any others.
144 Lexer *TL = new Lexer(TokLoc, *this,
145 StrData, StrData+StrVal.size()-1 /* no null */);
146
147 // Ensure that the lexer thinks it is inside a directive, so that end \n will
148 // return an EOM token.
149 TL->ParsingPreprocessorDirective = true;
150
151 // This lexer really is for _Pragma.
152 TL->Is_PragmaLexer = true;
153
154 EnterSourceFileWithLexer(TL, 0);
155
156 // With everything set up, lex this as a #pragma directive.
157 HandlePragmaDirective();
158
159 // Finally, return whatever came after the pragma directive.
160 return Lex(Tok);
161}
162
163
164
165/// HandlePragmaOnce - Handle #pragma once. OnceTok is the 'once'.
166///
167void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
168 if (isInPrimaryFile()) {
169 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
170 return;
171 }
172
173 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
174 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
175
176 // Mark the file as a once-only file now.
177 HeaderInfo.MarkFileIncludeOnce(SourceMgr.getFileEntryForLoc(FileLoc));
178}
179
180/// HandlePragmaPoison - Handle #pragma GCC poison. PoisonTok is the 'poison'.
181///
182void Preprocessor::HandlePragmaPoison(Token &PoisonTok) {
183 Token Tok;
184
185 while (1) {
186 // Read the next token to poison. While doing this, pretend that we are
187 // skipping while reading the identifier to poison.
188 // This avoids errors on code like:
189 // #pragma GCC poison X
190 // #pragma GCC poison X
191 if (CurLexer) CurLexer->LexingRawMode = true;
192 LexUnexpandedToken(Tok);
193 if (CurLexer) CurLexer->LexingRawMode = false;
194
195 // If we reached the end of line, we're done.
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000196 if (Tok.is(tok::eom)) return;
Chris Lattner4b009652007-07-25 00:24:17 +0000197
198 // Can only poison identifiers.
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000199 if (Tok.isNot(tok::identifier)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000200 Diag(Tok, diag::err_pp_invalid_poison);
201 return;
202 }
203
204 // Look up the identifier info for the token. We disabled identifier lookup
205 // by saying we're skipping contents, so we need to do this manually.
206 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
207
208 // Already poisoned.
209 if (II->isPoisoned()) continue;
210
211 // If this is a macro identifier, emit a warning.
Chris Lattner3b56a012007-10-07 08:04:56 +0000212 if (II->hasMacroDefinition())
Chris Lattner4b009652007-07-25 00:24:17 +0000213 Diag(Tok, diag::pp_poisoning_existing_macro);
214
215 // Finally, poison it!
216 II->setIsPoisoned();
217 }
218}
219
220/// HandlePragmaSystemHeader - Implement #pragma GCC system_header. We know
221/// that the whole directive has been parsed.
222void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
223 if (isInPrimaryFile()) {
224 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
225 return;
226 }
227
228 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
229 Lexer *TheLexer = getCurrentFileLexer();
230
231 // Mark the file as a system header.
232 const FileEntry *File = SourceMgr.getFileEntryForLoc(TheLexer->getFileLoc());
233 HeaderInfo.MarkFileSystemHeader(File);
234
235 // Notify the client, if desired, that we are in a new source file.
236 if (Callbacks)
237 Callbacks->FileChanged(TheLexer->getSourceLocation(TheLexer->BufferPtr),
238 PPCallbacks::SystemHeaderPragma,
239 DirectoryLookup::SystemHeaderDir);
240}
241
242/// HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah.
243///
244void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
245 Token FilenameTok;
246 CurLexer->LexIncludeFilename(FilenameTok);
247
248 // If the token kind is EOM, the error has already been diagnosed.
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000249 if (FilenameTok.is(tok::eom))
Chris Lattner4b009652007-07-25 00:24:17 +0000250 return;
251
252 // Reserve a buffer to get the spelling.
253 llvm::SmallVector<char, 128> FilenameBuffer;
254 FilenameBuffer.resize(FilenameTok.getLength());
255
256 const char *FilenameStart = &FilenameBuffer[0];
257 unsigned Len = getSpelling(FilenameTok, FilenameStart);
258 const char *FilenameEnd = FilenameStart+Len;
259 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
260 FilenameStart, FilenameEnd);
261 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
262 // error.
263 if (FilenameStart == 0)
264 return;
265
266 // Search include directories for this file.
267 const DirectoryLookup *CurDir;
268 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
269 isAngled, 0, CurDir);
270 if (File == 0)
271 return Diag(FilenameTok, diag::err_pp_file_not_found,
272 std::string(FilenameStart, FilenameEnd));
273
274 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
275 const FileEntry *CurFile = SourceMgr.getFileEntryForLoc(FileLoc);
276
277 // If this file is older than the file it depends on, emit a diagnostic.
278 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
279 // Lex tokens at the end of the message and include them in the message.
280 std::string Message;
281 Lex(DependencyTok);
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000282 while (DependencyTok.isNot(tok::eom)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000283 Message += getSpelling(DependencyTok) + " ";
284 Lex(DependencyTok);
285 }
286
287 Message.erase(Message.end()-1);
288 Diag(FilenameTok, diag::pp_out_of_date_dependency, Message);
289 }
290}
291
292
293/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
294/// If 'Namespace' is non-null, then it is a token required to exist on the
295/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
296void Preprocessor::AddPragmaHandler(const char *Namespace,
297 PragmaHandler *Handler) {
298 PragmaNamespace *InsertNS = PragmaHandlers;
299
300 // If this is specified to be in a namespace, step down into it.
301 if (Namespace) {
302 IdentifierInfo *NSID = getIdentifierInfo(Namespace);
303
304 // If there is already a pragma handler with the name of this namespace,
305 // we either have an error (directive with the same name as a namespace) or
306 // we already have the namespace to insert into.
307 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(NSID)) {
308 InsertNS = Existing->getIfNamespace();
309 assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
310 " handler with the same name!");
311 } else {
312 // Otherwise, this namespace doesn't exist yet, create and insert the
313 // handler for it.
314 InsertNS = new PragmaNamespace(NSID);
315 PragmaHandlers->AddPragma(InsertNS);
316 }
317 }
318
319 // Check to make sure we don't already have a pragma for this identifier.
320 assert(!InsertNS->FindHandler(Handler->getName()) &&
321 "Pragma handler already exists for this identifier!");
322 InsertNS->AddPragma(Handler);
323}
324
325namespace {
326struct PragmaOnceHandler : public PragmaHandler {
327 PragmaOnceHandler(const IdentifierInfo *OnceID) : PragmaHandler(OnceID) {}
328 virtual void HandlePragma(Preprocessor &PP, Token &OnceTok) {
329 PP.CheckEndOfDirective("#pragma once");
330 PP.HandlePragmaOnce(OnceTok);
331 }
332};
333
334struct PragmaPoisonHandler : public PragmaHandler {
335 PragmaPoisonHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
336 virtual void HandlePragma(Preprocessor &PP, Token &PoisonTok) {
337 PP.HandlePragmaPoison(PoisonTok);
338 }
339};
340
341struct PragmaSystemHeaderHandler : public PragmaHandler {
342 PragmaSystemHeaderHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
343 virtual void HandlePragma(Preprocessor &PP, Token &SHToken) {
344 PP.HandlePragmaSystemHeader(SHToken);
345 PP.CheckEndOfDirective("#pragma");
346 }
347};
348struct PragmaDependencyHandler : public PragmaHandler {
349 PragmaDependencyHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
350 virtual void HandlePragma(Preprocessor &PP, Token &DepToken) {
351 PP.HandlePragmaDependency(DepToken);
352 }
353};
354} // end anonymous namespace
355
356
357/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
358/// #pragma GCC poison/system_header/dependency and #pragma once.
359void Preprocessor::RegisterBuiltinPragmas() {
360 AddPragmaHandler(0, new PragmaOnceHandler(getIdentifierInfo("once")));
361 AddPragmaHandler("GCC", new PragmaPoisonHandler(getIdentifierInfo("poison")));
362 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler(
363 getIdentifierInfo("system_header")));
364 AddPragmaHandler("GCC", new PragmaDependencyHandler(
365 getIdentifierInfo("dependency")));
366}