blob: e6955d762fac2e756f47ef130449b93684379cb7 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Pragma.cpp - Pragma registration and handling --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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"
Reid Spencer5f016e22007-07-11 17:01:13 +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"
Reid Spencer5f016e22007-07-11 17:01:13 +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
Chris Lattnerd2177732007-07-20 16:59:19 +000054void PragmaNamespace::HandlePragma(Preprocessor &PP, Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +000055 // 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.
Chris Lattnerd2177732007-07-20 16:59:19 +000077 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +000078 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'.
Chris Lattnerd2177732007-07-20 16:59:19 +000088void Preprocessor::Handle_Pragma(Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +000089 // Remember the pragma token location.
90 SourceLocation PragmaLoc = Tok.getLocation();
91
92 // Read the '('.
93 Lex(Tok);
Chris Lattner22f6bbc2007-10-09 18:02:16 +000094 if (Tok.isNot(tok::l_paren))
Reid Spencer5f016e22007-07-11 17:01:13 +000095 return Diag(PragmaLoc, diag::err__Pragma_malformed);
96
97 // Read the '"..."'.
98 Lex(Tok);
Chris Lattner22f6bbc2007-10-09 18:02:16 +000099 if (Tok.isNot(tok::string_literal) && Tok.isNot(tok::wide_string_literal))
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner22f6bbc2007-10-09 18:02:16 +0000108 if (Tok.isNot(tok::r_paren))
Reid Spencer5f016e22007-07-11 17:01:13 +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
Reid Spencer5f016e22007-07-11 17:01:13 +0000140 // Make and enter a lexer object so that we lex and expand the tokens just
141 // like any others.
Chris Lattner25bdb512007-07-20 16:52:03 +0000142 Lexer *TL = new Lexer(TokLoc, *this,
Reid Spencer5f016e22007-07-11 17:01:13 +0000143 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///
Chris Lattnerd2177732007-07-20 16:59:19 +0000165void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000166 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.
Chris Lattner9dc1f532007-07-20 16:37:10 +0000172 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
Reid Spencer5f016e22007-07-11 17:01:13 +0000173
174 // Mark the file as a once-only file now.
Chris Lattner9dc1f532007-07-20 16:37:10 +0000175 HeaderInfo.MarkFileIncludeOnce(SourceMgr.getFileEntryForLoc(FileLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000176}
177
Chris Lattner22434492007-12-19 19:38:36 +0000178void Preprocessor::HandlePragmaMark() {
179 assert(CurLexer && "No current lexer?");
180 CurLexer->ReadToEndOfLine();
181}
182
183
Reid Spencer5f016e22007-07-11 17:01:13 +0000184/// HandlePragmaPoison - Handle #pragma GCC poison. PoisonTok is the 'poison'.
185///
Chris Lattnerd2177732007-07-20 16:59:19 +0000186void Preprocessor::HandlePragmaPoison(Token &PoisonTok) {
187 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000188
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 Lattner22f6bbc2007-10-09 18:02:16 +0000200 if (Tok.is(tok::eom)) return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000201
202 // Can only poison identifiers.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000203 if (Tok.isNot(tok::identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner0edde552007-10-07 08:04:56 +0000216 if (II->hasMacroDefinition())
Reid Spencer5f016e22007-07-11 17:01:13 +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.
Chris Lattnerd2177732007-07-20 16:59:19 +0000226void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000227 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.
Chris Lattner9dc1f532007-07-20 16:37:10 +0000236 const FileEntry *File = SourceMgr.getFileEntryForLoc(TheLexer->getFileLoc());
Reid Spencer5f016e22007-07-11 17:01:13 +0000237 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),
242 PPCallbacks::SystemHeaderPragma,
243 DirectoryLookup::SystemHeaderDir);
244}
245
246/// HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah.
247///
Chris Lattnerd2177732007-07-20 16:59:19 +0000248void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
249 Token FilenameTok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000250 CurLexer->LexIncludeFilename(FilenameTok);
251
252 // If the token kind is EOM, the error has already been diagnosed.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000253 if (FilenameTok.is(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +0000254 return;
255
256 // Reserve a buffer to get the spelling.
257 llvm::SmallVector<char, 128> FilenameBuffer;
258 FilenameBuffer.resize(FilenameTok.getLength());
259
Chris Lattnerf1c99ac2007-07-23 04:15:27 +0000260 const char *FilenameStart = &FilenameBuffer[0];
261 unsigned Len = getSpelling(FilenameTok, FilenameStart);
262 const char *FilenameEnd = FilenameStart+Len;
263 bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000264 FilenameStart, FilenameEnd);
265 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
266 // error.
267 if (FilenameStart == 0)
268 return;
269
270 // Search include directories for this file.
271 const DirectoryLookup *CurDir;
272 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
273 isAngled, 0, CurDir);
274 if (File == 0)
275 return Diag(FilenameTok, diag::err_pp_file_not_found,
276 std::string(FilenameStart, FilenameEnd));
277
Chris Lattner9dc1f532007-07-20 16:37:10 +0000278 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
279 const FileEntry *CurFile = SourceMgr.getFileEntryForLoc(FileLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000280
281 // If this file is older than the file it depends on, emit a diagnostic.
282 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
283 // Lex tokens at the end of the message and include them in the message.
284 std::string Message;
285 Lex(DependencyTok);
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000286 while (DependencyTok.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000287 Message += getSpelling(DependencyTok) + " ";
288 Lex(DependencyTok);
289 }
290
291 Message.erase(Message.end()-1);
292 Diag(FilenameTok, diag::pp_out_of_date_dependency, Message);
293 }
294}
295
296
297/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
298/// If 'Namespace' is non-null, then it is a token required to exist on the
299/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
300void Preprocessor::AddPragmaHandler(const char *Namespace,
301 PragmaHandler *Handler) {
302 PragmaNamespace *InsertNS = PragmaHandlers;
303
304 // If this is specified to be in a namespace, step down into it.
305 if (Namespace) {
306 IdentifierInfo *NSID = getIdentifierInfo(Namespace);
307
308 // If there is already a pragma handler with the name of this namespace,
309 // we either have an error (directive with the same name as a namespace) or
310 // we already have the namespace to insert into.
311 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(NSID)) {
312 InsertNS = Existing->getIfNamespace();
313 assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
314 " handler with the same name!");
315 } else {
316 // Otherwise, this namespace doesn't exist yet, create and insert the
317 // handler for it.
318 InsertNS = new PragmaNamespace(NSID);
319 PragmaHandlers->AddPragma(InsertNS);
320 }
321 }
322
323 // Check to make sure we don't already have a pragma for this identifier.
324 assert(!InsertNS->FindHandler(Handler->getName()) &&
325 "Pragma handler already exists for this identifier!");
326 InsertNS->AddPragma(Handler);
327}
328
329namespace {
Chris Lattner22434492007-12-19 19:38:36 +0000330/// PragmaOnceHandler - "#pragma once" marks the file as atomically included.
Reid Spencer5f016e22007-07-11 17:01:13 +0000331struct PragmaOnceHandler : public PragmaHandler {
332 PragmaOnceHandler(const IdentifierInfo *OnceID) : PragmaHandler(OnceID) {}
Chris Lattnerd2177732007-07-20 16:59:19 +0000333 virtual void HandlePragma(Preprocessor &PP, Token &OnceTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000334 PP.CheckEndOfDirective("#pragma once");
335 PP.HandlePragmaOnce(OnceTok);
336 }
337};
338
Chris Lattner22434492007-12-19 19:38:36 +0000339/// PragmaMarkHandler - "#pragma mark ..." is ignored by the compiler, and the
340/// rest of the line is not lexed.
341struct PragmaMarkHandler : public PragmaHandler {
342 PragmaMarkHandler(const IdentifierInfo *MarkID) : PragmaHandler(MarkID) {}
343 virtual void HandlePragma(Preprocessor &PP, Token &MarkTok) {
344 PP.HandlePragmaMark();
345 }
346};
347
348/// PragmaPoisonHandler - "#pragma poison x" marks x as not usable.
Reid Spencer5f016e22007-07-11 17:01:13 +0000349struct PragmaPoisonHandler : public PragmaHandler {
350 PragmaPoisonHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
Chris Lattnerd2177732007-07-20 16:59:19 +0000351 virtual void HandlePragma(Preprocessor &PP, Token &PoisonTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000352 PP.HandlePragmaPoison(PoisonTok);
353 }
354};
355
Chris Lattner22434492007-12-19 19:38:36 +0000356/// PragmaSystemHeaderHandler - "#pragma system_header" marks the current file
357/// as a system header, which silences warnings in it.
Reid Spencer5f016e22007-07-11 17:01:13 +0000358struct PragmaSystemHeaderHandler : public PragmaHandler {
359 PragmaSystemHeaderHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
Chris Lattnerd2177732007-07-20 16:59:19 +0000360 virtual void HandlePragma(Preprocessor &PP, Token &SHToken) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 PP.HandlePragmaSystemHeader(SHToken);
362 PP.CheckEndOfDirective("#pragma");
363 }
364};
365struct PragmaDependencyHandler : public PragmaHandler {
366 PragmaDependencyHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
Chris Lattnerd2177732007-07-20 16:59:19 +0000367 virtual void HandlePragma(Preprocessor &PP, Token &DepToken) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000368 PP.HandlePragmaDependency(DepToken);
369 }
370};
371} // end anonymous namespace
372
373
374/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
375/// #pragma GCC poison/system_header/dependency and #pragma once.
376void Preprocessor::RegisterBuiltinPragmas() {
377 AddPragmaHandler(0, new PragmaOnceHandler(getIdentifierInfo("once")));
Chris Lattner22434492007-12-19 19:38:36 +0000378 AddPragmaHandler(0, new PragmaMarkHandler(getIdentifierInfo("mark")));
Reid Spencer5f016e22007-07-11 17:01:13 +0000379 AddPragmaHandler("GCC", new PragmaPoisonHandler(getIdentifierInfo("poison")));
380 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler(
381 getIdentifierInfo("system_header")));
382 AddPragmaHandler("GCC", new PragmaDependencyHandler(
383 getIdentifierInfo("dependency")));
384}