blob: 2fb01a65f93a4c698b489876ff3eb32827d44aed [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);
99 if (Tok.getKind() != tok::string_literal)
100 return Diag(PragmaLoc, diag::err__Pragma_malformed);
101
102 // Remember the string.
103 std::string StrVal = getSpelling(Tok);
104 SourceLocation StrLoc = Tok.getLocation();
105
106 // Read the ')'.
107 Lex(Tok);
108 if (Tok.getKind() != tok::r_paren)
109 return Diag(PragmaLoc, diag::err__Pragma_malformed);
110
111 // The _Pragma is lexically sound. Destringize according to C99 6.10.9.1.
112 if (StrVal[0] == 'L') // Remove L prefix.
113 StrVal.erase(StrVal.begin());
114 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
115 "Invalid string token!");
116
117 // Remove the front quote, replacing it with a space, so that the pragma
118 // contents appear to have a space before them.
119 StrVal[0] = ' ';
120
121 // Replace the terminating quote with a \n\0.
122 StrVal[StrVal.size()-1] = '\n';
123 StrVal += '\0';
124
125 // Remove escaped quotes and escapes.
126 for (unsigned i = 0, e = StrVal.size(); i != e-1; ++i) {
127 if (StrVal[i] == '\\' &&
128 (StrVal[i+1] == '\\' || StrVal[i+1] == '"')) {
129 // \\ -> '\' and \" -> '"'.
130 StrVal.erase(StrVal.begin()+i);
131 --e;
132 }
133 }
134
Chris Lattnerf918bf72006-07-19 05:01:18 +0000135 // Plop the string (including the newline and trailing null) into a buffer
136 // where we can lex it.
Chris Lattnerda63bcd2006-07-19 04:36:03 +0000137 SourceLocation TokLoc = CreateString(&StrVal[0], StrVal.size(), StrLoc);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000138 const char *StrData = SourceMgr.getCharacterData(TokLoc);
139
Chris Lattnerb694ba72006-07-02 22:41:36 +0000140 unsigned FileID = TokLoc.getFileID();
141 assert(FileID && "Could not create FileID for predefines?");
142
143 // Make and enter a lexer object so that we lex and expand the tokens just
144 // like any others.
145 Lexer *TL = new Lexer(SourceMgr.getBuffer(FileID), FileID, *this,
146 StrData, StrData+StrVal.size()-1 /* no null */);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000147
148 // Ensure that the lexer thinks it is inside a directive, so that end \n will
149 // return an EOM token.
150 TL->ParsingPreprocessorDirective = true;
151
152 // This lexer really is for _Pragma.
153 TL->Is_PragmaLexer = true;
Chris Lattner98a53122006-07-02 23:00:20 +0000154
155 EnterSourceFileWithLexer(TL, 0);
156
Chris Lattnerb694ba72006-07-02 22:41:36 +0000157 // With everything set up, lex this as a #pragma directive.
158 HandlePragmaDirective();
159
160 // Finally, return whatever came after the pragma directive.
161 return Lex(Tok);
162}
163
164
165
166/// HandlePragmaOnce - Handle #pragma once. OnceTok is the 'once'.
167///
168void Preprocessor::HandlePragmaOnce(LexerToken &OnceTok) {
169 if (isInPrimaryFile()) {
170 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
171 return;
172 }
173
174 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
175 unsigned FileID = getCurrentFileLexer()->getCurFileID();
176
177 // Mark the file as a once-only file now.
178 getFileInfo(SourceMgr.getFileEntryForFileID(FileID)).isImport = true;
179}
180
181/// HandlePragmaPoison - Handle #pragma GCC poison. PoisonTok is the 'poison'.
182///
183void Preprocessor::HandlePragmaPoison(LexerToken &PoisonTok) {
184 LexerToken Tok;
Chris Lattner3ebcf4e2006-07-11 05:39:23 +0000185 assert(!isSkipping() && "Why are we handling pragmas while skipping?");
Chris Lattnerb694ba72006-07-02 22:41:36 +0000186 while (1) {
187 // Read the next token to poison. While doing this, pretend that we are
188 // skipping while reading the identifier to poison.
189 // This avoids errors on code like:
190 // #pragma GCC poison X
191 // #pragma GCC poison X
Chris Lattner3ebcf4e2006-07-11 05:39:23 +0000192 if (CurLexer) CurLexer->LexingRawMode = true;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000193 LexUnexpandedToken(Tok);
Chris Lattner3ebcf4e2006-07-11 05:39:23 +0000194 if (CurLexer) CurLexer->LexingRawMode = false;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000195
196 // If we reached the end of line, we're done.
197 if (Tok.getKind() == tok::eom) return;
198
199 // Can only poison identifiers.
200 if (Tok.getKind() != tok::identifier) {
201 Diag(Tok, diag::err_pp_invalid_poison);
202 return;
203 }
204
Chris Lattnercefc7682006-07-08 08:28:12 +0000205 // Look up the identifier info for the token. We disabled identifier lookup
206 // by saying we're skipping contents, so we need to do this manually.
207 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000208
209 // Already poisoned.
210 if (II->isPoisoned()) continue;
211
212 // If this is a macro identifier, emit a warning.
213 if (II->getMacroInfo())
214 Diag(Tok, diag::pp_poisoning_existing_macro);
215
216 // Finally, poison it!
217 II->setIsPoisoned();
218 }
219}
220
221/// HandlePragmaSystemHeader - Implement #pragma GCC system_header. We know
222/// that the whole directive has been parsed.
223void Preprocessor::HandlePragmaSystemHeader(LexerToken &SysHeaderTok) {
224 if (isInPrimaryFile()) {
225 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
226 return;
227 }
228
229 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
230 Lexer *TheLexer = getCurrentFileLexer();
231
232 // Mark the file as a system header.
233 const FileEntry *File =
234 SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
235 getFileInfo(File).DirInfo = DirectoryLookup::SystemHeaderDir;
236
237 // Notify the client, if desired, that we are in a new source file.
238 if (FileChangeHandler)
239 FileChangeHandler(TheLexer->getSourceLocation(TheLexer->BufferPtr),
240 SystemHeaderPragma, DirectoryLookup::SystemHeaderDir);
241}
242
243/// HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah.
244///
245void Preprocessor::HandlePragmaDependency(LexerToken &DependencyTok) {
246 LexerToken FilenameTok;
247 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
248
249 // If the token kind is EOM, the error has already been diagnosed.
250 if (FilenameTok.getKind() == tok::eom)
251 return;
252
253 // Find out whether the filename is <x> or "x".
254 bool isAngled = Filename[0] == '<';
255
256 // Remove the quotes.
257 Filename = std::string(Filename.begin()+1, Filename.end()-1);
258
259 // Search include directories.
260 const DirectoryLookup *CurDir;
261 const FileEntry *File = LookupFile(Filename, isAngled, 0, CurDir);
262 if (File == 0)
263 return Diag(FilenameTok, diag::err_pp_file_not_found);
264
265 unsigned FileID = getCurrentFileLexer()->getCurFileID();
266 const FileEntry *CurFile = SourceMgr.getFileEntryForFileID(FileID);
267
268 // If this file is older than the file it depends on, emit a diagnostic.
269 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
270 // Lex tokens at the end of the message and include them in the message.
271 std::string Message;
272 Lex(DependencyTok);
273 while (DependencyTok.getKind() != tok::eom) {
274 Message += getSpelling(DependencyTok) + " ";
275 Lex(DependencyTok);
276 }
277
278 Message.erase(Message.end()-1);
279 Diag(FilenameTok, diag::pp_out_of_date_dependency, Message);
280 }
281}
282
283
284/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
285/// If 'Namespace' is non-null, then it is a token required to exist on the
286/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
287void Preprocessor::AddPragmaHandler(const char *Namespace,
288 PragmaHandler *Handler) {
289 PragmaNamespace *InsertNS = PragmaHandlers;
290
291 // If this is specified to be in a namespace, step down into it.
292 if (Namespace) {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000293 IdentifierInfo *NSID = getIdentifierInfo(Namespace);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000294
295 // If there is already a pragma handler with the name of this namespace,
296 // we either have an error (directive with the same name as a namespace) or
297 // we already have the namespace to insert into.
298 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(NSID)) {
299 InsertNS = Existing->getIfNamespace();
300 assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
301 " handler with the same name!");
302 } else {
303 // Otherwise, this namespace doesn't exist yet, create and insert the
304 // handler for it.
305 InsertNS = new PragmaNamespace(NSID);
306 PragmaHandlers->AddPragma(InsertNS);
307 }
308 }
309
310 // Check to make sure we don't already have a pragma for this identifier.
311 assert(!InsertNS->FindHandler(Handler->getName()) &&
312 "Pragma handler already exists for this identifier!");
313 InsertNS->AddPragma(Handler);
314}
315
316namespace {
317struct PragmaOnceHandler : public PragmaHandler {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000318 PragmaOnceHandler(const IdentifierInfo *OnceID) : PragmaHandler(OnceID) {}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000319 virtual void HandlePragma(Preprocessor &PP, LexerToken &OnceTok) {
320 PP.CheckEndOfDirective("#pragma once");
321 PP.HandlePragmaOnce(OnceTok);
322 }
323};
324
325struct PragmaPoisonHandler : public PragmaHandler {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000326 PragmaPoisonHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000327 virtual void HandlePragma(Preprocessor &PP, LexerToken &PoisonTok) {
328 PP.HandlePragmaPoison(PoisonTok);
329 }
330};
331
332struct PragmaSystemHeaderHandler : public PragmaHandler {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000333 PragmaSystemHeaderHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000334 virtual void HandlePragma(Preprocessor &PP, LexerToken &SHToken) {
335 PP.HandlePragmaSystemHeader(SHToken);
336 PP.CheckEndOfDirective("#pragma");
337 }
338};
339struct PragmaDependencyHandler : public PragmaHandler {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000340 PragmaDependencyHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000341 virtual void HandlePragma(Preprocessor &PP, LexerToken &DepToken) {
342 PP.HandlePragmaDependency(DepToken);
343 }
344};
345} // end anonymous namespace
346
347
348/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
349/// #pragma GCC poison/system_header/dependency and #pragma once.
350void Preprocessor::RegisterBuiltinPragmas() {
351 AddPragmaHandler(0, new PragmaOnceHandler(getIdentifierInfo("once")));
352 AddPragmaHandler("GCC", new PragmaPoisonHandler(getIdentifierInfo("poison")));
353 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler(
354 getIdentifierInfo("system_header")));
355 AddPragmaHandler("GCC", new PragmaDependencyHandler(
356 getIdentifierInfo("dependency")));
357}