blob: 9b0fe5f495af7db1ed25fe9321e94565460f8833 [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.
42PragmaHandler *PragmaNamespace::FindHandler(const IdentifierTokenInfo *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
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
207 // Look up the identifier info for the token.
208 std::string TokStr = getSpelling(Tok);
209 IdentifierTokenInfo *II =
210 getIdentifierInfo(&TokStr[0], &TokStr[0]+TokStr.size());
211
212 // Already poisoned.
213 if (II->isPoisoned()) continue;
214
215 // If this is a macro identifier, emit a warning.
216 if (II->getMacroInfo())
217 Diag(Tok, diag::pp_poisoning_existing_macro);
218
219 // Finally, poison it!
220 II->setIsPoisoned();
221 }
222}
223
224/// HandlePragmaSystemHeader - Implement #pragma GCC system_header. We know
225/// that the whole directive has been parsed.
226void Preprocessor::HandlePragmaSystemHeader(LexerToken &SysHeaderTok) {
227 if (isInPrimaryFile()) {
228 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
229 return;
230 }
231
232 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
233 Lexer *TheLexer = getCurrentFileLexer();
234
235 // Mark the file as a system header.
236 const FileEntry *File =
237 SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
238 getFileInfo(File).DirInfo = DirectoryLookup::SystemHeaderDir;
239
240 // Notify the client, if desired, that we are in a new source file.
241 if (FileChangeHandler)
242 FileChangeHandler(TheLexer->getSourceLocation(TheLexer->BufferPtr),
243 SystemHeaderPragma, DirectoryLookup::SystemHeaderDir);
244}
245
246/// HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah.
247///
248void Preprocessor::HandlePragmaDependency(LexerToken &DependencyTok) {
249 LexerToken FilenameTok;
250 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
251
252 // If the token kind is EOM, the error has already been diagnosed.
253 if (FilenameTok.getKind() == tok::eom)
254 return;
255
256 // Find out whether the filename is <x> or "x".
257 bool isAngled = Filename[0] == '<';
258
259 // Remove the quotes.
260 Filename = std::string(Filename.begin()+1, Filename.end()-1);
261
262 // Search include directories.
263 const DirectoryLookup *CurDir;
264 const FileEntry *File = LookupFile(Filename, isAngled, 0, CurDir);
265 if (File == 0)
266 return Diag(FilenameTok, diag::err_pp_file_not_found);
267
268 unsigned FileID = getCurrentFileLexer()->getCurFileID();
269 const FileEntry *CurFile = SourceMgr.getFileEntryForFileID(FileID);
270
271 // If this file is older than the file it depends on, emit a diagnostic.
272 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
273 // Lex tokens at the end of the message and include them in the message.
274 std::string Message;
275 Lex(DependencyTok);
276 while (DependencyTok.getKind() != tok::eom) {
277 Message += getSpelling(DependencyTok) + " ";
278 Lex(DependencyTok);
279 }
280
281 Message.erase(Message.end()-1);
282 Diag(FilenameTok, diag::pp_out_of_date_dependency, Message);
283 }
284}
285
286
287/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
288/// If 'Namespace' is non-null, then it is a token required to exist on the
289/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
290void Preprocessor::AddPragmaHandler(const char *Namespace,
291 PragmaHandler *Handler) {
292 PragmaNamespace *InsertNS = PragmaHandlers;
293
294 // If this is specified to be in a namespace, step down into it.
295 if (Namespace) {
296 IdentifierTokenInfo *NSID = getIdentifierInfo(Namespace);
297
298 // If there is already a pragma handler with the name of this namespace,
299 // we either have an error (directive with the same name as a namespace) or
300 // we already have the namespace to insert into.
301 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(NSID)) {
302 InsertNS = Existing->getIfNamespace();
303 assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
304 " handler with the same name!");
305 } else {
306 // Otherwise, this namespace doesn't exist yet, create and insert the
307 // handler for it.
308 InsertNS = new PragmaNamespace(NSID);
309 PragmaHandlers->AddPragma(InsertNS);
310 }
311 }
312
313 // Check to make sure we don't already have a pragma for this identifier.
314 assert(!InsertNS->FindHandler(Handler->getName()) &&
315 "Pragma handler already exists for this identifier!");
316 InsertNS->AddPragma(Handler);
317}
318
319namespace {
320struct PragmaOnceHandler : public PragmaHandler {
321 PragmaOnceHandler(const IdentifierTokenInfo *OnceID) : PragmaHandler(OnceID){}
322 virtual void HandlePragma(Preprocessor &PP, LexerToken &OnceTok) {
323 PP.CheckEndOfDirective("#pragma once");
324 PP.HandlePragmaOnce(OnceTok);
325 }
326};
327
328struct PragmaPoisonHandler : public PragmaHandler {
329 PragmaPoisonHandler(const IdentifierTokenInfo *ID) : PragmaHandler(ID) {}
330 virtual void HandlePragma(Preprocessor &PP, LexerToken &PoisonTok) {
331 PP.HandlePragmaPoison(PoisonTok);
332 }
333};
334
335struct PragmaSystemHeaderHandler : public PragmaHandler {
336 PragmaSystemHeaderHandler(const IdentifierTokenInfo *ID) : PragmaHandler(ID){}
337 virtual void HandlePragma(Preprocessor &PP, LexerToken &SHToken) {
338 PP.HandlePragmaSystemHeader(SHToken);
339 PP.CheckEndOfDirective("#pragma");
340 }
341};
342struct PragmaDependencyHandler : public PragmaHandler {
343 PragmaDependencyHandler(const IdentifierTokenInfo *ID) : PragmaHandler(ID) {}
344 virtual void HandlePragma(Preprocessor &PP, LexerToken &DepToken) {
345 PP.HandlePragmaDependency(DepToken);
346 }
347};
348} // end anonymous namespace
349
350
351/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
352/// #pragma GCC poison/system_header/dependency and #pragma once.
353void Preprocessor::RegisterBuiltinPragmas() {
354 AddPragmaHandler(0, new PragmaOnceHandler(getIdentifierInfo("once")));
355 AddPragmaHandler("GCC", new PragmaPoisonHandler(getIdentifierInfo("poison")));
356 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler(
357 getIdentifierInfo("system_header")));
358 AddPragmaHandler("GCC", new PragmaDependencyHandler(
359 getIdentifierInfo("dependency")));
360}