blob: b4013535f5f7e034cd23c301fc2c3e29937fd8a4 [file] [log] [blame]
Chris Lattnerb8761832006-06-24 21:31:03 +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//
Chris Lattnerb694ba72006-07-02 22:41:36 +000010// This file implements the PragmaHandler/PragmaTable interfaces and implements
11// pragma related methods of the Preprocessor class.
Chris Lattnerb8761832006-06-24 21:31:03 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Pragma.h"
16#include "clang/Lex/Preprocessor.h"
Chris Lattnerb694ba72006-07-02 22:41:36 +000017#include "clang/Basic/Diagnostic.h"
18#include "clang/Basic/FileManager.h"
19#include "clang/Basic/SourceManager.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000020using namespace llvm;
21using namespace clang;
22
23// Out-of-line destructor to provide a home for the class.
24PragmaHandler::~PragmaHandler() {
25}
26
Chris Lattner2e155302006-07-03 05:34:41 +000027//===----------------------------------------------------------------------===//
28// PragmaNamespace Implementation.
29//===----------------------------------------------------------------------===//
30
31
32PragmaNamespace::~PragmaNamespace() {
33 for (unsigned i = 0, e = Handlers.size(); i != e; ++i)
34 delete Handlers[i];
35}
36
37/// FindHandler - Check to see if there is already a handler for the
38/// specified name. If not, return the handler for the null identifier if it
39/// exists, otherwise return null. If IgnoreNull is true (the default) then
40/// the null handler isn't returned on failure to match.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +000041PragmaHandler *PragmaNamespace::FindHandler(const IdentifierInfo *Name,
Chris Lattner2e155302006-07-03 05:34:41 +000042 bool IgnoreNull) const {
43 PragmaHandler *NullHandler = 0;
44 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
45 if (Handlers[i]->getName() == Name)
46 return Handlers[i];
47
48 if (Handlers[i]->getName() == 0)
49 NullHandler = Handlers[i];
50 }
51 return IgnoreNull ? 0 : NullHandler;
52}
53
Chris Lattnerb8761832006-06-24 21:31:03 +000054void PragmaNamespace::HandlePragma(Preprocessor &PP, LexerToken &Tok) {
55 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
56 // expand it, the user can have a STDC #define, that should not affect this.
57 PP.LexUnexpandedToken(Tok);
58
59 // Get the handler for this token. If there is no handler, ignore the pragma.
60 PragmaHandler *Handler = FindHandler(Tok.getIdentifierInfo(), false);
61 if (Handler == 0) return;
62
63 // Otherwise, pass it down.
64 Handler->HandlePragma(PP, Tok);
65}
Chris Lattnerb694ba72006-07-02 22:41:36 +000066
Chris Lattnerb694ba72006-07-02 22:41:36 +000067//===----------------------------------------------------------------------===//
68// Preprocessor Pragma Directive Handling.
69//===----------------------------------------------------------------------===//
70
71/// HandlePragmaDirective - The "#pragma" directive has been parsed. Lex the
72/// rest of the pragma, passing it to the registered pragma handlers.
73void Preprocessor::HandlePragmaDirective() {
74 ++NumPragma;
75
76 // Invoke the first level of pragma handlers which reads the namespace id.
77 LexerToken Tok;
78 PragmaHandlers->HandlePragma(*this, Tok);
79
80 // If the pragma handler didn't read the rest of the line, consume it now.
81 if (CurLexer->ParsingPreprocessorDirective)
82 DiscardUntilEndOfDirective();
83}
84
85/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
86/// return the first token after the directive. The _Pragma token has just
87/// been read into 'Tok'.
88void Preprocessor::Handle_Pragma(LexerToken &Tok) {
89 // Remember the pragma token location.
90 SourceLocation PragmaLoc = Tok.getLocation();
91
92 // Read the '('.
93 Lex(Tok);
94 if (Tok.getKind() != tok::l_paren)
95 return Diag(PragmaLoc, diag::err__Pragma_malformed);
96
97 // Read the '"..."'.
98 Lex(Tok);
Chris Lattnerd3e98952006-10-06 05:22:26 +000099 if (Tok.getKind() != tok::string_literal &&
100 Tok.getKind() != tok::wide_string_literal)
Chris Lattnerb694ba72006-07-02 22:41:36 +0000101 return Diag(PragmaLoc, diag::err__Pragma_malformed);
102
103 // Remember the string.
104 std::string StrVal = getSpelling(Tok);
105 SourceLocation StrLoc = Tok.getLocation();
106
107 // Read the ')'.
108 Lex(Tok);
109 if (Tok.getKind() != tok::r_paren)
110 return Diag(PragmaLoc, diag::err__Pragma_malformed);
111
112 // The _Pragma is lexically sound. Destringize according to C99 6.10.9.1.
113 if (StrVal[0] == 'L') // Remove L prefix.
114 StrVal.erase(StrVal.begin());
115 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
116 "Invalid string token!");
117
118 // Remove the front quote, replacing it with a space, so that the pragma
119 // contents appear to have a space before them.
120 StrVal[0] = ' ';
121
122 // Replace the terminating quote with a \n\0.
123 StrVal[StrVal.size()-1] = '\n';
124 StrVal += '\0';
125
126 // Remove escaped quotes and escapes.
127 for (unsigned i = 0, e = StrVal.size(); i != e-1; ++i) {
128 if (StrVal[i] == '\\' &&
129 (StrVal[i+1] == '\\' || StrVal[i+1] == '"')) {
130 // \\ -> '\' and \" -> '"'.
131 StrVal.erase(StrVal.begin()+i);
132 --e;
133 }
134 }
135
Chris Lattnerf918bf72006-07-19 05:01:18 +0000136 // Plop the string (including the newline and trailing null) into a buffer
137 // where we can lex it.
Chris Lattnerda63bcd2006-07-19 04:36:03 +0000138 SourceLocation TokLoc = CreateString(&StrVal[0], StrVal.size(), StrLoc);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000139 const char *StrData = SourceMgr.getCharacterData(TokLoc);
140
Chris Lattnerb694ba72006-07-02 22:41:36 +0000141 unsigned FileID = TokLoc.getFileID();
Chris Lattnera0d9bf42006-07-19 05:42:09 +0000142 assert(FileID && "Could not get FileID for _Pragma?");
Chris Lattnerb694ba72006-07-02 22:41:36 +0000143
144 // Make and enter a lexer object so that we lex and expand the tokens just
145 // like any others.
146 Lexer *TL = new Lexer(SourceMgr.getBuffer(FileID), FileID, *this,
147 StrData, StrData+StrVal.size()-1 /* no null */);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000148
149 // Ensure that the lexer thinks it is inside a directive, so that end \n will
150 // return an EOM token.
151 TL->ParsingPreprocessorDirective = true;
152
153 // This lexer really is for _Pragma.
154 TL->Is_PragmaLexer = true;
Chris Lattner98a53122006-07-02 23:00:20 +0000155
156 EnterSourceFileWithLexer(TL, 0);
157
Chris Lattnerb694ba72006-07-02 22:41:36 +0000158 // With everything set up, lex this as a #pragma directive.
159 HandlePragmaDirective();
160
161 // Finally, return whatever came after the pragma directive.
162 return Lex(Tok);
163}
164
165
166
167/// HandlePragmaOnce - Handle #pragma once. OnceTok is the 'once'.
168///
169void Preprocessor::HandlePragmaOnce(LexerToken &OnceTok) {
170 if (isInPrimaryFile()) {
171 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
172 return;
173 }
174
175 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
176 unsigned FileID = getCurrentFileLexer()->getCurFileID();
177
178 // Mark the file as a once-only file now.
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000179 HeaderInfo.MarkFileIncludeOnce(SourceMgr.getFileEntryForFileID(FileID));
Chris Lattnerb694ba72006-07-02 22:41:36 +0000180}
181
182/// HandlePragmaPoison - Handle #pragma GCC poison. PoisonTok is the 'poison'.
183///
184void Preprocessor::HandlePragmaPoison(LexerToken &PoisonTok) {
185 LexerToken Tok;
Chris Lattner538d7f32006-07-20 04:31:52 +0000186
Chris Lattnerb694ba72006-07-02 22:41:36 +0000187 while (1) {
188 // Read the next token to poison. While doing this, pretend that we are
189 // skipping while reading the identifier to poison.
190 // This avoids errors on code like:
191 // #pragma GCC poison X
192 // #pragma GCC poison X
Chris Lattner3ebcf4e2006-07-11 05:39:23 +0000193 if (CurLexer) CurLexer->LexingRawMode = true;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000194 LexUnexpandedToken(Tok);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +0000195 if (CurLexer) CurLexer->LexingRawMode = false;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000196
197 // If we reached the end of line, we're done.
198 if (Tok.getKind() == tok::eom) return;
199
200 // Can only poison identifiers.
201 if (Tok.getKind() != tok::identifier) {
202 Diag(Tok, diag::err_pp_invalid_poison);
203 return;
204 }
205
Chris Lattnercefc7682006-07-08 08:28:12 +0000206 // Look up the identifier info for the token. We disabled identifier lookup
207 // by saying we're skipping contents, so we need to do this manually.
208 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000209
210 // Already poisoned.
211 if (II->isPoisoned()) continue;
212
213 // If this is a macro identifier, emit a warning.
214 if (II->getMacroInfo())
215 Diag(Tok, diag::pp_poisoning_existing_macro);
216
217 // Finally, poison it!
218 II->setIsPoisoned();
219 }
220}
221
222/// HandlePragmaSystemHeader - Implement #pragma GCC system_header. We know
223/// that the whole directive has been parsed.
224void Preprocessor::HandlePragmaSystemHeader(LexerToken &SysHeaderTok) {
225 if (isInPrimaryFile()) {
226 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
227 return;
228 }
229
230 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
231 Lexer *TheLexer = getCurrentFileLexer();
232
233 // Mark the file as a system header.
234 const FileEntry *File =
235 SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000236 HeaderInfo.MarkFileSystemHeader(File);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000237
238 // Notify the client, if desired, that we are in a new source file.
239 if (FileChangeHandler)
240 FileChangeHandler(TheLexer->getSourceLocation(TheLexer->BufferPtr),
241 SystemHeaderPragma, DirectoryLookup::SystemHeaderDir);
242}
243
244/// HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah.
245///
246void Preprocessor::HandlePragmaDependency(LexerToken &DependencyTok) {
247 LexerToken FilenameTok;
248 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
249
250 // If the token kind is EOM, the error has already been diagnosed.
251 if (FilenameTok.getKind() == tok::eom)
252 return;
253
254 // Find out whether the filename is <x> or "x".
255 bool isAngled = Filename[0] == '<';
256
257 // Remove the quotes.
258 Filename = std::string(Filename.begin()+1, Filename.end()-1);
259
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000260 // Search include directories for this file.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000261 const DirectoryLookup *CurDir;
262 const FileEntry *File = LookupFile(Filename, isAngled, 0, CurDir);
263 if (File == 0)
264 return Diag(FilenameTok, diag::err_pp_file_not_found);
265
266 unsigned FileID = getCurrentFileLexer()->getCurFileID();
267 const FileEntry *CurFile = SourceMgr.getFileEntryForFileID(FileID);
268
269 // If this file is older than the file it depends on, emit a diagnostic.
270 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
271 // Lex tokens at the end of the message and include them in the message.
272 std::string Message;
273 Lex(DependencyTok);
274 while (DependencyTok.getKind() != tok::eom) {
275 Message += getSpelling(DependencyTok) + " ";
276 Lex(DependencyTok);
277 }
278
279 Message.erase(Message.end()-1);
280 Diag(FilenameTok, diag::pp_out_of_date_dependency, Message);
281 }
282}
283
284
285/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
286/// If 'Namespace' is non-null, then it is a token required to exist on the
287/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
288void Preprocessor::AddPragmaHandler(const char *Namespace,
289 PragmaHandler *Handler) {
290 PragmaNamespace *InsertNS = PragmaHandlers;
291
292 // If this is specified to be in a namespace, step down into it.
293 if (Namespace) {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000294 IdentifierInfo *NSID = getIdentifierInfo(Namespace);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000295
296 // If there is already a pragma handler with the name of this namespace,
297 // we either have an error (directive with the same name as a namespace) or
298 // we already have the namespace to insert into.
299 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(NSID)) {
300 InsertNS = Existing->getIfNamespace();
301 assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
302 " handler with the same name!");
303 } else {
304 // Otherwise, this namespace doesn't exist yet, create and insert the
305 // handler for it.
306 InsertNS = new PragmaNamespace(NSID);
307 PragmaHandlers->AddPragma(InsertNS);
308 }
309 }
310
311 // Check to make sure we don't already have a pragma for this identifier.
312 assert(!InsertNS->FindHandler(Handler->getName()) &&
313 "Pragma handler already exists for this identifier!");
314 InsertNS->AddPragma(Handler);
315}
316
317namespace {
318struct PragmaOnceHandler : public PragmaHandler {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000319 PragmaOnceHandler(const IdentifierInfo *OnceID) : PragmaHandler(OnceID) {}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000320 virtual void HandlePragma(Preprocessor &PP, LexerToken &OnceTok) {
321 PP.CheckEndOfDirective("#pragma once");
322 PP.HandlePragmaOnce(OnceTok);
323 }
324};
325
326struct PragmaPoisonHandler : public PragmaHandler {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000327 PragmaPoisonHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000328 virtual void HandlePragma(Preprocessor &PP, LexerToken &PoisonTok) {
329 PP.HandlePragmaPoison(PoisonTok);
330 }
331};
332
333struct PragmaSystemHeaderHandler : public PragmaHandler {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000334 PragmaSystemHeaderHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000335 virtual void HandlePragma(Preprocessor &PP, LexerToken &SHToken) {
336 PP.HandlePragmaSystemHeader(SHToken);
337 PP.CheckEndOfDirective("#pragma");
338 }
339};
340struct PragmaDependencyHandler : public PragmaHandler {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000341 PragmaDependencyHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000342 virtual void HandlePragma(Preprocessor &PP, LexerToken &DepToken) {
343 PP.HandlePragmaDependency(DepToken);
344 }
345};
346} // end anonymous namespace
347
348
349/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
350/// #pragma GCC poison/system_header/dependency and #pragma once.
351void Preprocessor::RegisterBuiltinPragmas() {
352 AddPragmaHandler(0, new PragmaOnceHandler(getIdentifierInfo("once")));
353 AddPragmaHandler("GCC", new PragmaPoisonHandler(getIdentifierInfo("poison")));
354 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler(
355 getIdentifierInfo("system_header")));
356 AddPragmaHandler("GCC", new PragmaDependencyHandler(
357 getIdentifierInfo("dependency")));
358}