blob: b6f5ac49360ccb3eb81caecf6606626ea4fa09ee [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
54void PragmaNamespace::HandlePragma(Preprocessor &PP, Token &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}
66
67//===----------------------------------------------------------------------===//
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 Token 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(Token &Tok) {
89 // Remember the pragma token location.
90 SourceLocation PragmaLoc = Tok.getLocation();
91
92 // Read the '('.
93 Lex(Tok);
Chris Lattnercb8e41c2007-10-09 18:02:16 +000094 if (Tok.isNot(tok::l_paren))
Chris Lattner4b009652007-07-25 00:24:17 +000095 return Diag(PragmaLoc, diag::err__Pragma_malformed);
96
97 // Read the '"..."'.
98 Lex(Tok);
Chris Lattnercb8e41c2007-10-09 18:02:16 +000099 if (Tok.isNot(tok::string_literal) && Tok.isNot(tok::wide_string_literal))
Chris Lattner4b009652007-07-25 00:24:17 +0000100 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);
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000108 if (Tok.isNot(tok::r_paren))
Chris Lattner4b009652007-07-25 00:24:17 +0000109 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
135 // Plop the string (including the newline and trailing null) into a buffer
136 // where we can lex it.
137 SourceLocation TokLoc = CreateString(&StrVal[0], StrVal.size(), StrLoc);
138 const char *StrData = SourceMgr.getCharacterData(TokLoc);
139
140 // Make and enter a lexer object so that we lex and expand the tokens just
141 // like any others.
142 Lexer *TL = new Lexer(TokLoc, *this,
143 StrData, StrData+StrVal.size()-1 /* no null */);
144
145 // Ensure that the lexer thinks it is inside a directive, so that end \n will
146 // return an EOM token.
147 TL->ParsingPreprocessorDirective = true;
148
149 // This lexer really is for _Pragma.
150 TL->Is_PragmaLexer = true;
151
152 EnterSourceFileWithLexer(TL, 0);
153
154 // With everything set up, lex this as a #pragma directive.
155 HandlePragmaDirective();
156
157 // Finally, return whatever came after the pragma directive.
158 return Lex(Tok);
159}
160
161
162
163/// HandlePragmaOnce - Handle #pragma once. OnceTok is the 'once'.
164///
165void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
166 if (isInPrimaryFile()) {
167 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
168 return;
169 }
170
171 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
172 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
173
174 // Mark the file as a once-only file now.
175 HeaderInfo.MarkFileIncludeOnce(SourceMgr.getFileEntryForLoc(FileLoc));
176}
177
Chris Lattnerc0f6b222007-12-19 19:38:36 +0000178void Preprocessor::HandlePragmaMark() {
179 assert(CurLexer && "No current lexer?");
180 CurLexer->ReadToEndOfLine();
181}
182
183
Chris Lattner4b009652007-07-25 00:24:17 +0000184/// HandlePragmaPoison - Handle #pragma GCC poison. PoisonTok is the 'poison'.
185///
186void Preprocessor::HandlePragmaPoison(Token &PoisonTok) {
187 Token Tok;
188
189 while (1) {
190 // Read the next token to poison. While doing this, pretend that we are
191 // skipping while reading the identifier to poison.
192 // This avoids errors on code like:
193 // #pragma GCC poison X
194 // #pragma GCC poison X
195 if (CurLexer) CurLexer->LexingRawMode = true;
196 LexUnexpandedToken(Tok);
197 if (CurLexer) CurLexer->LexingRawMode = false;
198
199 // If we reached the end of line, we're done.
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000200 if (Tok.is(tok::eom)) return;
Chris Lattner4b009652007-07-25 00:24:17 +0000201
202 // Can only poison identifiers.
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000203 if (Tok.isNot(tok::identifier)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000204 Diag(Tok, diag::err_pp_invalid_poison);
205 return;
206 }
207
208 // Look up the identifier info for the token. We disabled identifier lookup
209 // by saying we're skipping contents, so we need to do this manually.
210 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
211
212 // Already poisoned.
213 if (II->isPoisoned()) continue;
214
215 // If this is a macro identifier, emit a warning.
Chris Lattner3b56a012007-10-07 08:04:56 +0000216 if (II->hasMacroDefinition())
Chris Lattner4b009652007-07-25 00:24:17 +0000217 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(Token &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 = SourceMgr.getFileEntryForLoc(TheLexer->getFileLoc());
237 HeaderInfo.MarkFileSystemHeader(File);
238
239 // Notify the client, if desired, that we are in a new source file.
240 if (Callbacks)
241 Callbacks->FileChanged(TheLexer->getSourceLocation(TheLexer->BufferPtr),
Chris Lattner6f044062008-09-26 21:18:42 +0000242 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
Chris Lattner4b009652007-07-25 00:24:17 +0000243}
244
245/// HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah.
246///
247void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
248 Token FilenameTok;
249 CurLexer->LexIncludeFilename(FilenameTok);
250
251 // If the token kind is EOM, the error has already been diagnosed.
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000252 if (FilenameTok.is(tok::eom))
Chris Lattner4b009652007-07-25 00:24:17 +0000253 return;
254
255 // Reserve a buffer to get the spelling.
256 llvm::SmallVector<char, 128> FilenameBuffer;
257 FilenameBuffer.resize(FilenameTok.getLength());
258
259 const char *FilenameStart = &FilenameBuffer[0];
260 unsigned Len = getSpelling(FilenameTok, FilenameStart);
261 const char *FilenameEnd = FilenameStart+Len;
262 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
263 FilenameStart, FilenameEnd);
264 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
265 // error.
266 if (FilenameStart == 0)
267 return;
268
269 // Search include directories for this file.
270 const DirectoryLookup *CurDir;
271 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
272 isAngled, 0, CurDir);
273 if (File == 0)
274 return Diag(FilenameTok, diag::err_pp_file_not_found,
275 std::string(FilenameStart, FilenameEnd));
276
277 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
278 const FileEntry *CurFile = SourceMgr.getFileEntryForLoc(FileLoc);
279
280 // If this file is older than the file it depends on, emit a diagnostic.
281 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
282 // Lex tokens at the end of the message and include them in the message.
283 std::string Message;
284 Lex(DependencyTok);
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000285 while (DependencyTok.isNot(tok::eom)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000286 Message += getSpelling(DependencyTok) + " ";
287 Lex(DependencyTok);
288 }
289
290 Message.erase(Message.end()-1);
291 Diag(FilenameTok, diag::pp_out_of_date_dependency, Message);
292 }
293}
294
295
296/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
297/// If 'Namespace' is non-null, then it is a token required to exist on the
298/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
299void Preprocessor::AddPragmaHandler(const char *Namespace,
300 PragmaHandler *Handler) {
301 PragmaNamespace *InsertNS = PragmaHandlers;
302
303 // If this is specified to be in a namespace, step down into it.
304 if (Namespace) {
305 IdentifierInfo *NSID = getIdentifierInfo(Namespace);
306
307 // If there is already a pragma handler with the name of this namespace,
308 // we either have an error (directive with the same name as a namespace) or
309 // we already have the namespace to insert into.
310 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(NSID)) {
311 InsertNS = Existing->getIfNamespace();
312 assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
313 " handler with the same name!");
314 } else {
315 // Otherwise, this namespace doesn't exist yet, create and insert the
316 // handler for it.
317 InsertNS = new PragmaNamespace(NSID);
318 PragmaHandlers->AddPragma(InsertNS);
319 }
320 }
321
322 // Check to make sure we don't already have a pragma for this identifier.
323 assert(!InsertNS->FindHandler(Handler->getName()) &&
324 "Pragma handler already exists for this identifier!");
325 InsertNS->AddPragma(Handler);
326}
327
328namespace {
Chris Lattnerc0f6b222007-12-19 19:38:36 +0000329/// PragmaOnceHandler - "#pragma once" marks the file as atomically included.
Chris Lattner4b009652007-07-25 00:24:17 +0000330struct PragmaOnceHandler : public PragmaHandler {
331 PragmaOnceHandler(const IdentifierInfo *OnceID) : PragmaHandler(OnceID) {}
332 virtual void HandlePragma(Preprocessor &PP, Token &OnceTok) {
333 PP.CheckEndOfDirective("#pragma once");
334 PP.HandlePragmaOnce(OnceTok);
335 }
336};
337
Chris Lattnerc0f6b222007-12-19 19:38:36 +0000338/// PragmaMarkHandler - "#pragma mark ..." is ignored by the compiler, and the
339/// rest of the line is not lexed.
340struct PragmaMarkHandler : public PragmaHandler {
341 PragmaMarkHandler(const IdentifierInfo *MarkID) : PragmaHandler(MarkID) {}
342 virtual void HandlePragma(Preprocessor &PP, Token &MarkTok) {
343 PP.HandlePragmaMark();
344 }
345};
346
347/// PragmaPoisonHandler - "#pragma poison x" marks x as not usable.
Chris Lattner4b009652007-07-25 00:24:17 +0000348struct PragmaPoisonHandler : public PragmaHandler {
349 PragmaPoisonHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
350 virtual void HandlePragma(Preprocessor &PP, Token &PoisonTok) {
351 PP.HandlePragmaPoison(PoisonTok);
352 }
353};
354
Chris Lattnerc0f6b222007-12-19 19:38:36 +0000355/// PragmaSystemHeaderHandler - "#pragma system_header" marks the current file
356/// as a system header, which silences warnings in it.
Chris Lattner4b009652007-07-25 00:24:17 +0000357struct PragmaSystemHeaderHandler : public PragmaHandler {
358 PragmaSystemHeaderHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
359 virtual void HandlePragma(Preprocessor &PP, Token &SHToken) {
360 PP.HandlePragmaSystemHeader(SHToken);
361 PP.CheckEndOfDirective("#pragma");
362 }
363};
364struct PragmaDependencyHandler : public PragmaHandler {
365 PragmaDependencyHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
366 virtual void HandlePragma(Preprocessor &PP, Token &DepToken) {
367 PP.HandlePragmaDependency(DepToken);
368 }
369};
370} // end anonymous namespace
371
372
373/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
374/// #pragma GCC poison/system_header/dependency and #pragma once.
375void Preprocessor::RegisterBuiltinPragmas() {
376 AddPragmaHandler(0, new PragmaOnceHandler(getIdentifierInfo("once")));
Chris Lattnerc0f6b222007-12-19 19:38:36 +0000377 AddPragmaHandler(0, new PragmaMarkHandler(getIdentifierInfo("mark")));
Chris Lattner4b009652007-07-25 00:24:17 +0000378 AddPragmaHandler("GCC", new PragmaPoisonHandler(getIdentifierInfo("poison")));
379 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler(
380 getIdentifierInfo("system_header")));
381 AddPragmaHandler("GCC", new PragmaDependencyHandler(
382 getIdentifierInfo("dependency")));
383}