blob: 596b7e76e46b60fbdb36a4504a227a292295d6c4 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +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//
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"
16#include "clang/Lex/PPCallbacks.h"
17#include "clang/Lex/HeaderSearch.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Basic/Diagnostic.h"
20#include "clang/Basic/FileManager.h"
21#include "clang/Basic/SourceManager.h"
22#include "llvm/ADT/SmallVector.h"
23using namespace clang;
24
25// Out-of-line destructor to provide a home for the class.
26PragmaHandler::~PragmaHandler() {
27}
28
29//===----------------------------------------------------------------------===//
30// PragmaNamespace Implementation.
31//===----------------------------------------------------------------------===//
32
33
34PragmaNamespace::~PragmaNamespace() {
35 for (unsigned i = 0, e = Handlers.size(); i != e; ++i)
36 delete Handlers[i];
37}
38
39/// FindHandler - Check to see if there is already a handler for the
40/// specified name. If not, return the handler for the null identifier if it
41/// exists, otherwise return null. If IgnoreNull is true (the default) then
42/// the null handler isn't returned on failure to match.
43PragmaHandler *PragmaNamespace::FindHandler(const IdentifierInfo *Name,
44 bool IgnoreNull) const {
45 PragmaHandler *NullHandler = 0;
46 for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
47 if (Handlers[i]->getName() == Name)
48 return Handlers[i];
49
50 if (Handlers[i]->getName() == 0)
51 NullHandler = Handlers[i];
52 }
53 return IgnoreNull ? 0 : NullHandler;
54}
55
56void PragmaNamespace::HandlePragma(Preprocessor &PP, LexerToken &Tok) {
57 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
58 // expand it, the user can have a STDC #define, that should not affect this.
59 PP.LexUnexpandedToken(Tok);
60
61 // Get the handler for this token. If there is no handler, ignore the pragma.
62 PragmaHandler *Handler = FindHandler(Tok.getIdentifierInfo(), false);
63 if (Handler == 0) return;
64
65 // Otherwise, pass it down.
66 Handler->HandlePragma(PP, Tok);
67}
68
69//===----------------------------------------------------------------------===//
70// Preprocessor Pragma Directive Handling.
71//===----------------------------------------------------------------------===//
72
73/// HandlePragmaDirective - The "#pragma" directive has been parsed. Lex the
74/// rest of the pragma, passing it to the registered pragma handlers.
75void Preprocessor::HandlePragmaDirective() {
76 ++NumPragma;
77
78 // Invoke the first level of pragma handlers which reads the namespace id.
79 LexerToken Tok;
80 PragmaHandlers->HandlePragma(*this, Tok);
81
82 // If the pragma handler didn't read the rest of the line, consume it now.
83 if (CurLexer->ParsingPreprocessorDirective)
84 DiscardUntilEndOfDirective();
85}
86
87/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
88/// return the first token after the directive. The _Pragma token has just
89/// been read into 'Tok'.
90void Preprocessor::Handle_Pragma(LexerToken &Tok) {
91 // Remember the pragma token location.
92 SourceLocation PragmaLoc = Tok.getLocation();
93
94 // Read the '('.
95 Lex(Tok);
96 if (Tok.getKind() != tok::l_paren)
97 return Diag(PragmaLoc, diag::err__Pragma_malformed);
98
99 // Read the '"..."'.
100 Lex(Tok);
101 if (Tok.getKind() != tok::string_literal &&
102 Tok.getKind() != tok::wide_string_literal)
103 return Diag(PragmaLoc, diag::err__Pragma_malformed);
104
105 // Remember the string.
106 std::string StrVal = getSpelling(Tok);
107 SourceLocation StrLoc = Tok.getLocation();
108
109 // Read the ')'.
110 Lex(Tok);
111 if (Tok.getKind() != tok::r_paren)
112 return Diag(PragmaLoc, diag::err__Pragma_malformed);
113
114 // The _Pragma is lexically sound. Destringize according to C99 6.10.9.1.
115 if (StrVal[0] == 'L') // Remove L prefix.
116 StrVal.erase(StrVal.begin());
117 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
118 "Invalid string token!");
119
120 // Remove the front quote, replacing it with a space, so that the pragma
121 // contents appear to have a space before them.
122 StrVal[0] = ' ';
123
124 // Replace the terminating quote with a \n\0.
125 StrVal[StrVal.size()-1] = '\n';
126 StrVal += '\0';
127
128 // Remove escaped quotes and escapes.
129 for (unsigned i = 0, e = StrVal.size(); i != e-1; ++i) {
130 if (StrVal[i] == '\\' &&
131 (StrVal[i+1] == '\\' || StrVal[i+1] == '"')) {
132 // \\ -> '\' and \" -> '"'.
133 StrVal.erase(StrVal.begin()+i);
134 --e;
135 }
136 }
137
138 // Plop the string (including the newline and trailing null) into a buffer
139 // where we can lex it.
140 SourceLocation TokLoc = CreateString(&StrVal[0], StrVal.size(), StrLoc);
141 const char *StrData = SourceMgr.getCharacterData(TokLoc);
142
Chris Lattner9dc1f532007-07-20 16:37:10 +0000143 unsigned FileID = SourceMgr.getPhysicalLoc(TokLoc).getFileID();
Reid Spencer5f016e22007-07-11 17:01:13 +0000144 assert(FileID && "Could not get FileID for _Pragma?");
145
146 // Make and enter a lexer object so that we lex and expand the tokens just
147 // like any others.
Chris Lattner9dc1f532007-07-20 16:37:10 +0000148 Lexer *TL = new Lexer(SourceMgr.getBuffer(FileID), TokLoc, *this,
Reid Spencer5f016e22007-07-11 17:01:13 +0000149 StrData, StrData+StrVal.size()-1 /* no null */);
150
151 // Ensure that the lexer thinks it is inside a directive, so that end \n will
152 // return an EOM token.
153 TL->ParsingPreprocessorDirective = true;
154
155 // This lexer really is for _Pragma.
156 TL->Is_PragmaLexer = true;
157
158 EnterSourceFileWithLexer(TL, 0);
159
160 // With everything set up, lex this as a #pragma directive.
161 HandlePragmaDirective();
162
163 // Finally, return whatever came after the pragma directive.
164 return Lex(Tok);
165}
166
167
168
169/// HandlePragmaOnce - Handle #pragma once. OnceTok is the 'once'.
170///
171void Preprocessor::HandlePragmaOnce(LexerToken &OnceTok) {
172 if (isInPrimaryFile()) {
173 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
174 return;
175 }
176
177 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Chris Lattner9dc1f532007-07-20 16:37:10 +0000178 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
Reid Spencer5f016e22007-07-11 17:01:13 +0000179
180 // Mark the file as a once-only file now.
Chris Lattner9dc1f532007-07-20 16:37:10 +0000181 HeaderInfo.MarkFileIncludeOnce(SourceMgr.getFileEntryForLoc(FileLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000182}
183
184/// HandlePragmaPoison - Handle #pragma GCC poison. PoisonTok is the 'poison'.
185///
186void Preprocessor::HandlePragmaPoison(LexerToken &PoisonTok) {
187 LexerToken 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.
200 if (Tok.getKind() == tok::eom) return;
201
202 // Can only poison identifiers.
203 if (Tok.getKind() != tok::identifier) {
204 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.
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.
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///
248void Preprocessor::HandlePragmaDependency(LexerToken &DependencyTok) {
249 LexerToken FilenameTok;
250 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 // Reserve a buffer to get the spelling.
257 llvm::SmallVector<char, 128> FilenameBuffer;
258 FilenameBuffer.resize(FilenameTok.getLength());
259
260 const char *FilenameStart = &FilenameBuffer[0], *FilenameEnd;
261 bool isAngled = GetIncludeFilenameSpelling(FilenameTok,
262 FilenameStart, FilenameEnd);
263 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
264 // error.
265 if (FilenameStart == 0)
266 return;
267
268 // Search include directories for this file.
269 const DirectoryLookup *CurDir;
270 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
271 isAngled, 0, CurDir);
272 if (File == 0)
273 return Diag(FilenameTok, diag::err_pp_file_not_found,
274 std::string(FilenameStart, FilenameEnd));
275
Chris Lattner9dc1f532007-07-20 16:37:10 +0000276 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
277 const FileEntry *CurFile = SourceMgr.getFileEntryForLoc(FileLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000278
279 // If this file is older than the file it depends on, emit a diagnostic.
280 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
281 // Lex tokens at the end of the message and include them in the message.
282 std::string Message;
283 Lex(DependencyTok);
284 while (DependencyTok.getKind() != tok::eom) {
285 Message += getSpelling(DependencyTok) + " ";
286 Lex(DependencyTok);
287 }
288
289 Message.erase(Message.end()-1);
290 Diag(FilenameTok, diag::pp_out_of_date_dependency, Message);
291 }
292}
293
294
295/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
296/// If 'Namespace' is non-null, then it is a token required to exist on the
297/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
298void Preprocessor::AddPragmaHandler(const char *Namespace,
299 PragmaHandler *Handler) {
300 PragmaNamespace *InsertNS = PragmaHandlers;
301
302 // If this is specified to be in a namespace, step down into it.
303 if (Namespace) {
304 IdentifierInfo *NSID = getIdentifierInfo(Namespace);
305
306 // If there is already a pragma handler with the name of this namespace,
307 // we either have an error (directive with the same name as a namespace) or
308 // we already have the namespace to insert into.
309 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(NSID)) {
310 InsertNS = Existing->getIfNamespace();
311 assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
312 " handler with the same name!");
313 } else {
314 // Otherwise, this namespace doesn't exist yet, create and insert the
315 // handler for it.
316 InsertNS = new PragmaNamespace(NSID);
317 PragmaHandlers->AddPragma(InsertNS);
318 }
319 }
320
321 // Check to make sure we don't already have a pragma for this identifier.
322 assert(!InsertNS->FindHandler(Handler->getName()) &&
323 "Pragma handler already exists for this identifier!");
324 InsertNS->AddPragma(Handler);
325}
326
327namespace {
328struct PragmaOnceHandler : public PragmaHandler {
329 PragmaOnceHandler(const IdentifierInfo *OnceID) : PragmaHandler(OnceID) {}
330 virtual void HandlePragma(Preprocessor &PP, LexerToken &OnceTok) {
331 PP.CheckEndOfDirective("#pragma once");
332 PP.HandlePragmaOnce(OnceTok);
333 }
334};
335
336struct PragmaPoisonHandler : public PragmaHandler {
337 PragmaPoisonHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
338 virtual void HandlePragma(Preprocessor &PP, LexerToken &PoisonTok) {
339 PP.HandlePragmaPoison(PoisonTok);
340 }
341};
342
343struct PragmaSystemHeaderHandler : public PragmaHandler {
344 PragmaSystemHeaderHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
345 virtual void HandlePragma(Preprocessor &PP, LexerToken &SHToken) {
346 PP.HandlePragmaSystemHeader(SHToken);
347 PP.CheckEndOfDirective("#pragma");
348 }
349};
350struct PragmaDependencyHandler : public PragmaHandler {
351 PragmaDependencyHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
352 virtual void HandlePragma(Preprocessor &PP, LexerToken &DepToken) {
353 PP.HandlePragmaDependency(DepToken);
354 }
355};
356} // end anonymous namespace
357
358
359/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
360/// #pragma GCC poison/system_header/dependency and #pragma once.
361void Preprocessor::RegisterBuiltinPragmas() {
362 AddPragmaHandler(0, new PragmaOnceHandler(getIdentifierInfo("once")));
363 AddPragmaHandler("GCC", new PragmaPoisonHandler(getIdentifierInfo("poison")));
364 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler(
365 getIdentifierInfo("system_header")));
366 AddPragmaHandler("GCC", new PragmaDependencyHandler(
367 getIdentifierInfo("dependency")));
368}