blob: 6d8e047056d9d098cc21b3630041a1f1a0ff4862 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- Pragma.cpp - Pragma registration and handling --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
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"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/Lex/HeaderSearch.h"
17#include "clang/Lex/Preprocessor.h"
18#include "clang/Basic/Diagnostic.h"
19#include "clang/Basic/FileManager.h"
20#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021using namespace clang;
22
23// Out-of-line destructor to provide a home for the class.
24PragmaHandler::~PragmaHandler() {
25}
26
27//===----------------------------------------------------------------------===//
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.
41PragmaHandler *PragmaNamespace::FindHandler(const IdentifierInfo *Name,
42 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
Daniel Dunbara65c00a2008-10-04 19:17:46 +000054void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
55 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
56 if (Handlers[i] == Handler) {
57 Handlers[i] = Handlers.back();
58 Handlers.pop_back();
59 return;
60 }
61 }
62 assert(0 && "Handler not registered in this namespace");
63}
64
Chris Lattner4b009652007-07-25 00:24:17 +000065void PragmaNamespace::HandlePragma(Preprocessor &PP, Token &Tok) {
66 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
67 // expand it, the user can have a STDC #define, that should not affect this.
68 PP.LexUnexpandedToken(Tok);
69
70 // Get the handler for this token. If there is no handler, ignore the pragma.
71 PragmaHandler *Handler = FindHandler(Tok.getIdentifierInfo(), false);
72 if (Handler == 0) return;
73
74 // Otherwise, pass it down.
75 Handler->HandlePragma(PP, Tok);
76}
77
78//===----------------------------------------------------------------------===//
79// Preprocessor Pragma Directive Handling.
80//===----------------------------------------------------------------------===//
81
82/// HandlePragmaDirective - The "#pragma" directive has been parsed. Lex the
83/// rest of the pragma, passing it to the registered pragma handlers.
84void Preprocessor::HandlePragmaDirective() {
85 ++NumPragma;
86
87 // Invoke the first level of pragma handlers which reads the namespace id.
88 Token Tok;
89 PragmaHandlers->HandlePragma(*this, Tok);
90
91 // If the pragma handler didn't read the rest of the line, consume it now.
92 if (CurLexer->ParsingPreprocessorDirective)
93 DiscardUntilEndOfDirective();
94}
95
96/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
97/// return the first token after the directive. The _Pragma token has just
98/// been read into 'Tok'.
99void Preprocessor::Handle_Pragma(Token &Tok) {
100 // Remember the pragma token location.
101 SourceLocation PragmaLoc = Tok.getLocation();
102
103 // Read the '('.
104 Lex(Tok);
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000105 if (Tok.isNot(tok::l_paren))
Chris Lattner4b009652007-07-25 00:24:17 +0000106 return Diag(PragmaLoc, diag::err__Pragma_malformed);
107
108 // Read the '"..."'.
109 Lex(Tok);
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000110 if (Tok.isNot(tok::string_literal) && Tok.isNot(tok::wide_string_literal))
Chris Lattner4b009652007-07-25 00:24:17 +0000111 return Diag(PragmaLoc, diag::err__Pragma_malformed);
112
113 // Remember the string.
114 std::string StrVal = getSpelling(Tok);
115 SourceLocation StrLoc = Tok.getLocation();
116
117 // Read the ')'.
118 Lex(Tok);
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000119 if (Tok.isNot(tok::r_paren))
Chris Lattner4b009652007-07-25 00:24:17 +0000120 return Diag(PragmaLoc, diag::err__Pragma_malformed);
121
122 // The _Pragma is lexically sound. Destringize according to C99 6.10.9.1.
123 if (StrVal[0] == 'L') // Remove L prefix.
124 StrVal.erase(StrVal.begin());
125 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
126 "Invalid string token!");
127
128 // Remove the front quote, replacing it with a space, so that the pragma
129 // contents appear to have a space before them.
130 StrVal[0] = ' ';
131
132 // Replace the terminating quote with a \n\0.
133 StrVal[StrVal.size()-1] = '\n';
134 StrVal += '\0';
135
136 // Remove escaped quotes and escapes.
137 for (unsigned i = 0, e = StrVal.size(); i != e-1; ++i) {
138 if (StrVal[i] == '\\' &&
139 (StrVal[i+1] == '\\' || StrVal[i+1] == '"')) {
140 // \\ -> '\' and \" -> '"'.
141 StrVal.erase(StrVal.begin()+i);
142 --e;
143 }
144 }
145
146 // Plop the string (including the newline and trailing null) into a buffer
147 // where we can lex it.
148 SourceLocation TokLoc = CreateString(&StrVal[0], StrVal.size(), StrLoc);
149 const char *StrData = SourceMgr.getCharacterData(TokLoc);
150
151 // Make and enter a lexer object so that we lex and expand the tokens just
152 // like any others.
153 Lexer *TL = new Lexer(TokLoc, *this,
154 StrData, StrData+StrVal.size()-1 /* no null */);
155
156 // Ensure that the lexer thinks it is inside a directive, so that end \n will
157 // return an EOM token.
158 TL->ParsingPreprocessorDirective = true;
159
160 // This lexer really is for _Pragma.
161 TL->Is_PragmaLexer = true;
162
163 EnterSourceFileWithLexer(TL, 0);
164
165 // With everything set up, lex this as a #pragma directive.
166 HandlePragmaDirective();
167
168 // Finally, return whatever came after the pragma directive.
169 return Lex(Tok);
170}
171
172
173
174/// HandlePragmaOnce - Handle #pragma once. OnceTok is the 'once'.
175///
176void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
177 if (isInPrimaryFile()) {
178 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
179 return;
180 }
181
182 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
183 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
184
185 // Mark the file as a once-only file now.
186 HeaderInfo.MarkFileIncludeOnce(SourceMgr.getFileEntryForLoc(FileLoc));
187}
188
Chris Lattnerc0f6b222007-12-19 19:38:36 +0000189void Preprocessor::HandlePragmaMark() {
190 assert(CurLexer && "No current lexer?");
191 CurLexer->ReadToEndOfLine();
192}
193
194
Chris Lattner4b009652007-07-25 00:24:17 +0000195/// HandlePragmaPoison - Handle #pragma GCC poison. PoisonTok is the 'poison'.
196///
197void Preprocessor::HandlePragmaPoison(Token &PoisonTok) {
198 Token Tok;
199
200 while (1) {
201 // Read the next token to poison. While doing this, pretend that we are
202 // skipping while reading the identifier to poison.
203 // This avoids errors on code like:
204 // #pragma GCC poison X
205 // #pragma GCC poison X
206 if (CurLexer) CurLexer->LexingRawMode = true;
207 LexUnexpandedToken(Tok);
208 if (CurLexer) CurLexer->LexingRawMode = false;
209
210 // If we reached the end of line, we're done.
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000211 if (Tok.is(tok::eom)) return;
Chris Lattner4b009652007-07-25 00:24:17 +0000212
213 // Can only poison identifiers.
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000214 if (Tok.isNot(tok::identifier)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000215 Diag(Tok, diag::err_pp_invalid_poison);
216 return;
217 }
218
219 // Look up the identifier info for the token. We disabled identifier lookup
220 // by saying we're skipping contents, so we need to do this manually.
221 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
222
223 // Already poisoned.
224 if (II->isPoisoned()) continue;
225
226 // If this is a macro identifier, emit a warning.
Chris Lattner3b56a012007-10-07 08:04:56 +0000227 if (II->hasMacroDefinition())
Chris Lattner4b009652007-07-25 00:24:17 +0000228 Diag(Tok, diag::pp_poisoning_existing_macro);
229
230 // Finally, poison it!
231 II->setIsPoisoned();
232 }
233}
234
235/// HandlePragmaSystemHeader - Implement #pragma GCC system_header. We know
236/// that the whole directive has been parsed.
237void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
238 if (isInPrimaryFile()) {
239 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
240 return;
241 }
242
243 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
244 Lexer *TheLexer = getCurrentFileLexer();
245
246 // Mark the file as a system header.
247 const FileEntry *File = SourceMgr.getFileEntryForLoc(TheLexer->getFileLoc());
248 HeaderInfo.MarkFileSystemHeader(File);
249
250 // Notify the client, if desired, that we are in a new source file.
251 if (Callbacks)
252 Callbacks->FileChanged(TheLexer->getSourceLocation(TheLexer->BufferPtr),
Chris Lattner6f044062008-09-26 21:18:42 +0000253 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
Chris Lattner4b009652007-07-25 00:24:17 +0000254}
255
256/// HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah.
257///
258void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
259 Token FilenameTok;
260 CurLexer->LexIncludeFilename(FilenameTok);
261
262 // If the token kind is EOM, the error has already been diagnosed.
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000263 if (FilenameTok.is(tok::eom))
Chris Lattner4b009652007-07-25 00:24:17 +0000264 return;
265
266 // Reserve a buffer to get the spelling.
267 llvm::SmallVector<char, 128> FilenameBuffer;
268 FilenameBuffer.resize(FilenameTok.getLength());
269
270 const char *FilenameStart = &FilenameBuffer[0];
271 unsigned Len = getSpelling(FilenameTok, FilenameStart);
272 const char *FilenameEnd = FilenameStart+Len;
273 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
274 FilenameStart, FilenameEnd);
275 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
276 // error.
277 if (FilenameStart == 0)
278 return;
279
280 // Search include directories for this file.
281 const DirectoryLookup *CurDir;
282 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
283 isAngled, 0, CurDir);
284 if (File == 0)
285 return Diag(FilenameTok, diag::err_pp_file_not_found,
286 std::string(FilenameStart, FilenameEnd));
287
288 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
289 const FileEntry *CurFile = SourceMgr.getFileEntryForLoc(FileLoc);
290
291 // If this file is older than the file it depends on, emit a diagnostic.
292 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
293 // Lex tokens at the end of the message and include them in the message.
294 std::string Message;
295 Lex(DependencyTok);
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000296 while (DependencyTok.isNot(tok::eom)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000297 Message += getSpelling(DependencyTok) + " ";
298 Lex(DependencyTok);
299 }
300
301 Message.erase(Message.end()-1);
302 Diag(FilenameTok, diag::pp_out_of_date_dependency, Message);
303 }
304}
305
306
307/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
308/// If 'Namespace' is non-null, then it is a token required to exist on the
309/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
310void Preprocessor::AddPragmaHandler(const char *Namespace,
311 PragmaHandler *Handler) {
312 PragmaNamespace *InsertNS = PragmaHandlers;
313
314 // If this is specified to be in a namespace, step down into it.
315 if (Namespace) {
316 IdentifierInfo *NSID = getIdentifierInfo(Namespace);
317
318 // If there is already a pragma handler with the name of this namespace,
319 // we either have an error (directive with the same name as a namespace) or
320 // we already have the namespace to insert into.
321 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(NSID)) {
322 InsertNS = Existing->getIfNamespace();
323 assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
324 " handler with the same name!");
325 } else {
326 // Otherwise, this namespace doesn't exist yet, create and insert the
327 // handler for it.
328 InsertNS = new PragmaNamespace(NSID);
329 PragmaHandlers->AddPragma(InsertNS);
330 }
331 }
332
333 // Check to make sure we don't already have a pragma for this identifier.
334 assert(!InsertNS->FindHandler(Handler->getName()) &&
335 "Pragma handler already exists for this identifier!");
336 InsertNS->AddPragma(Handler);
337}
338
Daniel Dunbara65c00a2008-10-04 19:17:46 +0000339/// RemovePragmaHandler - Remove the specific pragma handler from the
340/// preprocessor. If \arg Namespace is non-null, then it should be the
341/// namespace that \arg Handler was added to. It is an error to remove
342/// a handler that has not been registered.
343void Preprocessor::RemovePragmaHandler(const char *Namespace,
344 PragmaHandler *Handler) {
345 PragmaNamespace *NS = PragmaHandlers;
346
347 // If this is specified to be in a namespace, step down into it.
348 if (Namespace) {
349 IdentifierInfo *NSID = getIdentifierInfo(Namespace);
350 PragmaHandler *Existing = PragmaHandlers->FindHandler(NSID);
351 assert(Existing && "Namespace containing handler does not exist!");
352
353 NS = Existing->getIfNamespace();
354 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
355 }
356
357 NS->RemovePragmaHandler(Handler);
358
359 // If this is a non-default namespace and it is now empty, remove
360 // it.
361 if (NS != PragmaHandlers && NS->IsEmpty())
362 PragmaHandlers->RemovePragmaHandler(NS);
363}
364
Chris Lattner4b009652007-07-25 00:24:17 +0000365namespace {
Chris Lattnerc0f6b222007-12-19 19:38:36 +0000366/// PragmaOnceHandler - "#pragma once" marks the file as atomically included.
Chris Lattner4b009652007-07-25 00:24:17 +0000367struct PragmaOnceHandler : public PragmaHandler {
368 PragmaOnceHandler(const IdentifierInfo *OnceID) : PragmaHandler(OnceID) {}
369 virtual void HandlePragma(Preprocessor &PP, Token &OnceTok) {
370 PP.CheckEndOfDirective("#pragma once");
371 PP.HandlePragmaOnce(OnceTok);
372 }
373};
374
Chris Lattnerc0f6b222007-12-19 19:38:36 +0000375/// PragmaMarkHandler - "#pragma mark ..." is ignored by the compiler, and the
376/// rest of the line is not lexed.
377struct PragmaMarkHandler : public PragmaHandler {
378 PragmaMarkHandler(const IdentifierInfo *MarkID) : PragmaHandler(MarkID) {}
379 virtual void HandlePragma(Preprocessor &PP, Token &MarkTok) {
380 PP.HandlePragmaMark();
381 }
382};
383
384/// PragmaPoisonHandler - "#pragma poison x" marks x as not usable.
Chris Lattner4b009652007-07-25 00:24:17 +0000385struct PragmaPoisonHandler : public PragmaHandler {
386 PragmaPoisonHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
387 virtual void HandlePragma(Preprocessor &PP, Token &PoisonTok) {
388 PP.HandlePragmaPoison(PoisonTok);
389 }
390};
391
Chris Lattnerc0f6b222007-12-19 19:38:36 +0000392/// PragmaSystemHeaderHandler - "#pragma system_header" marks the current file
393/// as a system header, which silences warnings in it.
Chris Lattner4b009652007-07-25 00:24:17 +0000394struct PragmaSystemHeaderHandler : public PragmaHandler {
395 PragmaSystemHeaderHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
396 virtual void HandlePragma(Preprocessor &PP, Token &SHToken) {
397 PP.HandlePragmaSystemHeader(SHToken);
398 PP.CheckEndOfDirective("#pragma");
399 }
400};
401struct PragmaDependencyHandler : public PragmaHandler {
402 PragmaDependencyHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
403 virtual void HandlePragma(Preprocessor &PP, Token &DepToken) {
404 PP.HandlePragmaDependency(DepToken);
405 }
406};
407} // end anonymous namespace
408
409
410/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
411/// #pragma GCC poison/system_header/dependency and #pragma once.
412void Preprocessor::RegisterBuiltinPragmas() {
413 AddPragmaHandler(0, new PragmaOnceHandler(getIdentifierInfo("once")));
Chris Lattnerc0f6b222007-12-19 19:38:36 +0000414 AddPragmaHandler(0, new PragmaMarkHandler(getIdentifierInfo("mark")));
Chris Lattner4b009652007-07-25 00:24:17 +0000415 AddPragmaHandler("GCC", new PragmaPoisonHandler(getIdentifierInfo("poison")));
416 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler(
417 getIdentifierInfo("system_header")));
418 AddPragmaHandler("GCC", new PragmaDependencyHandler(
419 getIdentifierInfo("dependency")));
420}