blob: f4269a84edaf0bbb38d460d78f1ff0ec3a82d22b [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/Lex/ScratchBuffer.h"
18#include "clang/Basic/Diagnostic.h"
19#include "clang/Basic/FileManager.h"
20#include "clang/Basic/SourceManager.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000021using namespace llvm;
22using namespace clang;
23
24// Out-of-line destructor to provide a home for the class.
25PragmaHandler::~PragmaHandler() {
26}
27
Chris Lattner2e155302006-07-03 05:34:41 +000028//===----------------------------------------------------------------------===//
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.
Chris Lattnerc79f6fb2006-07-04 17:53:21 +000042PragmaHandler *PragmaNamespace::FindHandler(const IdentifierInfo *Name,
Chris Lattner2e155302006-07-03 05:34:41 +000043 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
Chris Lattnerb8761832006-06-24 21:31:03 +000055void PragmaNamespace::HandlePragma(Preprocessor &PP, LexerToken &Tok) {
56 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
57 // expand it, the user can have a STDC #define, that should not affect this.
58 PP.LexUnexpandedToken(Tok);
59
60 // Get the handler for this token. If there is no handler, ignore the pragma.
61 PragmaHandler *Handler = FindHandler(Tok.getIdentifierInfo(), false);
62 if (Handler == 0) return;
63
64 // Otherwise, pass it down.
65 Handler->HandlePragma(PP, Tok);
66}
Chris Lattnerb694ba72006-07-02 22:41:36 +000067
Chris Lattnerb694ba72006-07-02 22:41:36 +000068//===----------------------------------------------------------------------===//
69// Preprocessor Pragma Directive Handling.
70//===----------------------------------------------------------------------===//
71
72/// HandlePragmaDirective - The "#pragma" directive has been parsed. Lex the
73/// rest of the pragma, passing it to the registered pragma handlers.
74void Preprocessor::HandlePragmaDirective() {
75 ++NumPragma;
76
77 // Invoke the first level of pragma handlers which reads the namespace id.
78 LexerToken Tok;
79 PragmaHandlers->HandlePragma(*this, Tok);
80
81 // If the pragma handler didn't read the rest of the line, consume it now.
82 if (CurLexer->ParsingPreprocessorDirective)
83 DiscardUntilEndOfDirective();
84}
85
86/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
87/// return the first token after the directive. The _Pragma token has just
88/// been read into 'Tok'.
89void Preprocessor::Handle_Pragma(LexerToken &Tok) {
90 // Remember the pragma token location.
91 SourceLocation PragmaLoc = Tok.getLocation();
92
93 // Read the '('.
94 Lex(Tok);
95 if (Tok.getKind() != tok::l_paren)
96 return Diag(PragmaLoc, diag::err__Pragma_malformed);
97
98 // Read the '"..."'.
99 Lex(Tok);
100 if (Tok.getKind() != tok::string_literal)
101 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
136 // Plop the string (including the trailing null) into a buffer where we can
137 // lex it.
Chris Lattner98a53122006-07-02 23:00:20 +0000138 SourceLocation TokLoc = ScratchBuf->getToken(&StrVal[0], StrVal.size(),
Chris Lattnerb085f932006-07-03 06:10:36 +0000139 StrLoc);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000140 const char *StrData = SourceMgr.getCharacterData(TokLoc);
141
Chris Lattnerb694ba72006-07-02 22:41:36 +0000142 unsigned FileID = TokLoc.getFileID();
143 assert(FileID && "Could not create FileID for predefines?");
144
145 // Make and enter a lexer object so that we lex and expand the tokens just
146 // like any others.
147 Lexer *TL = new Lexer(SourceMgr.getBuffer(FileID), FileID, *this,
148 StrData, StrData+StrVal.size()-1 /* no null */);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000149
150 // Ensure that the lexer thinks it is inside a directive, so that end \n will
151 // return an EOM token.
152 TL->ParsingPreprocessorDirective = true;
153
154 // This lexer really is for _Pragma.
155 TL->Is_PragmaLexer = true;
Chris Lattner98a53122006-07-02 23:00:20 +0000156
157 EnterSourceFileWithLexer(TL, 0);
158
Chris Lattnerb694ba72006-07-02 22:41:36 +0000159 // With everything set up, lex this as a #pragma directive.
160 HandlePragmaDirective();
161
162 // Finally, return whatever came after the pragma directive.
163 return Lex(Tok);
164}
165
166
167
168/// HandlePragmaOnce - Handle #pragma once. OnceTok is the 'once'.
169///
170void Preprocessor::HandlePragmaOnce(LexerToken &OnceTok) {
171 if (isInPrimaryFile()) {
172 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
173 return;
174 }
175
176 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
177 unsigned FileID = getCurrentFileLexer()->getCurFileID();
178
179 // Mark the file as a once-only file now.
180 getFileInfo(SourceMgr.getFileEntryForFileID(FileID)).isImport = true;
181}
182
183/// HandlePragmaPoison - Handle #pragma GCC poison. PoisonTok is the 'poison'.
184///
185void Preprocessor::HandlePragmaPoison(LexerToken &PoisonTok) {
186 LexerToken Tok;
187 assert(!SkippingContents && "Why are we handling pragmas while skipping?");
188 while (1) {
189 // Read the next token to poison. While doing this, pretend that we are
190 // skipping while reading the identifier to poison.
191 // This avoids errors on code like:
192 // #pragma GCC poison X
193 // #pragma GCC poison X
194 SkippingContents = true;
195 LexUnexpandedToken(Tok);
196 SkippingContents = false;
197
198 // If we reached the end of line, we're done.
199 if (Tok.getKind() == tok::eom) return;
200
201 // Can only poison identifiers.
202 if (Tok.getKind() != tok::identifier) {
203 Diag(Tok, diag::err_pp_invalid_poison);
204 return;
205 }
206
Chris Lattnercefc7682006-07-08 08:28:12 +0000207 // Look up the identifier info for the token. We disabled identifier lookup
208 // by saying we're skipping contents, so we need to do this manually.
209 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000210
211 // Already poisoned.
212 if (II->isPoisoned()) continue;
213
214 // If this is a macro identifier, emit a warning.
215 if (II->getMacroInfo())
216 Diag(Tok, diag::pp_poisoning_existing_macro);
217
218 // Finally, poison it!
219 II->setIsPoisoned();
220 }
221}
222
223/// HandlePragmaSystemHeader - Implement #pragma GCC system_header. We know
224/// that the whole directive has been parsed.
225void Preprocessor::HandlePragmaSystemHeader(LexerToken &SysHeaderTok) {
226 if (isInPrimaryFile()) {
227 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
228 return;
229 }
230
231 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
232 Lexer *TheLexer = getCurrentFileLexer();
233
234 // Mark the file as a system header.
235 const FileEntry *File =
236 SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
237 getFileInfo(File).DirInfo = DirectoryLookup::SystemHeaderDir;
238
239 // Notify the client, if desired, that we are in a new source file.
240 if (FileChangeHandler)
241 FileChangeHandler(TheLexer->getSourceLocation(TheLexer->BufferPtr),
242 SystemHeaderPragma, DirectoryLookup::SystemHeaderDir);
243}
244
245/// HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah.
246///
247void Preprocessor::HandlePragmaDependency(LexerToken &DependencyTok) {
248 LexerToken FilenameTok;
249 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
250
251 // If the token kind is EOM, the error has already been diagnosed.
252 if (FilenameTok.getKind() == tok::eom)
253 return;
254
255 // Find out whether the filename is <x> or "x".
256 bool isAngled = Filename[0] == '<';
257
258 // Remove the quotes.
259 Filename = std::string(Filename.begin()+1, Filename.end()-1);
260
261 // Search include directories.
262 const DirectoryLookup *CurDir;
263 const FileEntry *File = LookupFile(Filename, isAngled, 0, CurDir);
264 if (File == 0)
265 return Diag(FilenameTok, diag::err_pp_file_not_found);
266
267 unsigned FileID = getCurrentFileLexer()->getCurFileID();
268 const FileEntry *CurFile = SourceMgr.getFileEntryForFileID(FileID);
269
270 // If this file is older than the file it depends on, emit a diagnostic.
271 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
272 // Lex tokens at the end of the message and include them in the message.
273 std::string Message;
274 Lex(DependencyTok);
275 while (DependencyTok.getKind() != tok::eom) {
276 Message += getSpelling(DependencyTok) + " ";
277 Lex(DependencyTok);
278 }
279
280 Message.erase(Message.end()-1);
281 Diag(FilenameTok, diag::pp_out_of_date_dependency, Message);
282 }
283}
284
285
286/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
287/// If 'Namespace' is non-null, then it is a token required to exist on the
288/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
289void Preprocessor::AddPragmaHandler(const char *Namespace,
290 PragmaHandler *Handler) {
291 PragmaNamespace *InsertNS = PragmaHandlers;
292
293 // If this is specified to be in a namespace, step down into it.
294 if (Namespace) {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000295 IdentifierInfo *NSID = getIdentifierInfo(Namespace);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000296
297 // If there is already a pragma handler with the name of this namespace,
298 // we either have an error (directive with the same name as a namespace) or
299 // we already have the namespace to insert into.
300 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(NSID)) {
301 InsertNS = Existing->getIfNamespace();
302 assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
303 " handler with the same name!");
304 } else {
305 // Otherwise, this namespace doesn't exist yet, create and insert the
306 // handler for it.
307 InsertNS = new PragmaNamespace(NSID);
308 PragmaHandlers->AddPragma(InsertNS);
309 }
310 }
311
312 // Check to make sure we don't already have a pragma for this identifier.
313 assert(!InsertNS->FindHandler(Handler->getName()) &&
314 "Pragma handler already exists for this identifier!");
315 InsertNS->AddPragma(Handler);
316}
317
318namespace {
319struct PragmaOnceHandler : public PragmaHandler {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000320 PragmaOnceHandler(const IdentifierInfo *OnceID) : PragmaHandler(OnceID) {}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000321 virtual void HandlePragma(Preprocessor &PP, LexerToken &OnceTok) {
322 PP.CheckEndOfDirective("#pragma once");
323 PP.HandlePragmaOnce(OnceTok);
324 }
325};
326
327struct PragmaPoisonHandler : public PragmaHandler {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000328 PragmaPoisonHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000329 virtual void HandlePragma(Preprocessor &PP, LexerToken &PoisonTok) {
330 PP.HandlePragmaPoison(PoisonTok);
331 }
332};
333
334struct PragmaSystemHeaderHandler : public PragmaHandler {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000335 PragmaSystemHeaderHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000336 virtual void HandlePragma(Preprocessor &PP, LexerToken &SHToken) {
337 PP.HandlePragmaSystemHeader(SHToken);
338 PP.CheckEndOfDirective("#pragma");
339 }
340};
341struct PragmaDependencyHandler : public PragmaHandler {
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000342 PragmaDependencyHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000343 virtual void HandlePragma(Preprocessor &PP, LexerToken &DepToken) {
344 PP.HandlePragmaDependency(DepToken);
345 }
346};
347} // end anonymous namespace
348
349
350/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
351/// #pragma GCC poison/system_header/dependency and #pragma once.
352void Preprocessor::RegisterBuiltinPragmas() {
353 AddPragmaHandler(0, new PragmaOnceHandler(getIdentifierInfo("once")));
354 AddPragmaHandler("GCC", new PragmaPoisonHandler(getIdentifierInfo("poison")));
355 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler(
356 getIdentifierInfo("system_header")));
357 AddPragmaHandler("GCC", new PragmaDependencyHandler(
358 getIdentifierInfo("dependency")));
359}