blob: cd7e3a00af7a0554d887a300f491b738fa6bb4e8 [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
28void PragmaNamespace::HandlePragma(Preprocessor &PP, LexerToken &Tok) {
29 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
30 // expand it, the user can have a STDC #define, that should not affect this.
31 PP.LexUnexpandedToken(Tok);
32
33 // Get the handler for this token. If there is no handler, ignore the pragma.
34 PragmaHandler *Handler = FindHandler(Tok.getIdentifierInfo(), false);
35 if (Handler == 0) return;
36
37 // Otherwise, pass it down.
38 Handler->HandlePragma(PP, Tok);
39}
Chris Lattnerb694ba72006-07-02 22:41:36 +000040
41
42//===----------------------------------------------------------------------===//
43// Preprocessor Pragma Directive Handling.
44//===----------------------------------------------------------------------===//
45
46/// HandlePragmaDirective - The "#pragma" directive has been parsed. Lex the
47/// rest of the pragma, passing it to the registered pragma handlers.
48void Preprocessor::HandlePragmaDirective() {
49 ++NumPragma;
50
51 // Invoke the first level of pragma handlers which reads the namespace id.
52 LexerToken Tok;
53 PragmaHandlers->HandlePragma(*this, Tok);
54
55 // If the pragma handler didn't read the rest of the line, consume it now.
56 if (CurLexer->ParsingPreprocessorDirective)
57 DiscardUntilEndOfDirective();
58}
59
60/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
61/// return the first token after the directive. The _Pragma token has just
62/// been read into 'Tok'.
63void Preprocessor::Handle_Pragma(LexerToken &Tok) {
64 // Remember the pragma token location.
65 SourceLocation PragmaLoc = Tok.getLocation();
66
67 // Read the '('.
68 Lex(Tok);
69 if (Tok.getKind() != tok::l_paren)
70 return Diag(PragmaLoc, diag::err__Pragma_malformed);
71
72 // Read the '"..."'.
73 Lex(Tok);
74 if (Tok.getKind() != tok::string_literal)
75 return Diag(PragmaLoc, diag::err__Pragma_malformed);
76
77 // Remember the string.
78 std::string StrVal = getSpelling(Tok);
79 SourceLocation StrLoc = Tok.getLocation();
80
81 // Read the ')'.
82 Lex(Tok);
83 if (Tok.getKind() != tok::r_paren)
84 return Diag(PragmaLoc, diag::err__Pragma_malformed);
85
86 // The _Pragma is lexically sound. Destringize according to C99 6.10.9.1.
87 if (StrVal[0] == 'L') // Remove L prefix.
88 StrVal.erase(StrVal.begin());
89 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
90 "Invalid string token!");
91
92 // Remove the front quote, replacing it with a space, so that the pragma
93 // contents appear to have a space before them.
94 StrVal[0] = ' ';
95
96 // Replace the terminating quote with a \n\0.
97 StrVal[StrVal.size()-1] = '\n';
98 StrVal += '\0';
99
100 // Remove escaped quotes and escapes.
101 for (unsigned i = 0, e = StrVal.size(); i != e-1; ++i) {
102 if (StrVal[i] == '\\' &&
103 (StrVal[i+1] == '\\' || StrVal[i+1] == '"')) {
104 // \\ -> '\' and \" -> '"'.
105 StrVal.erase(StrVal.begin()+i);
106 --e;
107 }
108 }
109
110 // Plop the string (including the trailing null) into a buffer where we can
111 // lex it.
112 SourceLocation TokLoc = ScratchBuf->getToken(&StrVal[0], StrVal.size());
113 const char *StrData = SourceMgr.getCharacterData(TokLoc);
114
115 // FIXME: Create appropriate mapping info for this FileID, so that we know the
116 // tokens are coming out of the input string (StrLoc).
117 unsigned FileID = TokLoc.getFileID();
118 assert(FileID && "Could not create FileID for predefines?");
119
120 // Make and enter a lexer object so that we lex and expand the tokens just
121 // like any others.
122 Lexer *TL = new Lexer(SourceMgr.getBuffer(FileID), FileID, *this,
123 StrData, StrData+StrVal.size()-1 /* no null */);
124 EnterSourceFileWithLexer(TL, 0);
125
126 // Ensure that the lexer thinks it is inside a directive, so that end \n will
127 // return an EOM token.
128 TL->ParsingPreprocessorDirective = true;
129
130 // This lexer really is for _Pragma.
131 TL->Is_PragmaLexer = true;
132
133 // With everything set up, lex this as a #pragma directive.
134 HandlePragmaDirective();
135
136 // Finally, return whatever came after the pragma directive.
137 return Lex(Tok);
138}
139
140
141
142/// HandlePragmaOnce - Handle #pragma once. OnceTok is the 'once'.
143///
144void Preprocessor::HandlePragmaOnce(LexerToken &OnceTok) {
145 if (isInPrimaryFile()) {
146 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
147 return;
148 }
149
150 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
151 unsigned FileID = getCurrentFileLexer()->getCurFileID();
152
153 // Mark the file as a once-only file now.
154 getFileInfo(SourceMgr.getFileEntryForFileID(FileID)).isImport = true;
155}
156
157/// HandlePragmaPoison - Handle #pragma GCC poison. PoisonTok is the 'poison'.
158///
159void Preprocessor::HandlePragmaPoison(LexerToken &PoisonTok) {
160 LexerToken Tok;
161 assert(!SkippingContents && "Why are we handling pragmas while skipping?");
162 while (1) {
163 // Read the next token to poison. While doing this, pretend that we are
164 // skipping while reading the identifier to poison.
165 // This avoids errors on code like:
166 // #pragma GCC poison X
167 // #pragma GCC poison X
168 SkippingContents = true;
169 LexUnexpandedToken(Tok);
170 SkippingContents = false;
171
172 // If we reached the end of line, we're done.
173 if (Tok.getKind() == tok::eom) return;
174
175 // Can only poison identifiers.
176 if (Tok.getKind() != tok::identifier) {
177 Diag(Tok, diag::err_pp_invalid_poison);
178 return;
179 }
180
181 // Look up the identifier info for the token.
182 std::string TokStr = getSpelling(Tok);
183 IdentifierTokenInfo *II =
184 getIdentifierInfo(&TokStr[0], &TokStr[0]+TokStr.size());
185
186 // Already poisoned.
187 if (II->isPoisoned()) continue;
188
189 // If this is a macro identifier, emit a warning.
190 if (II->getMacroInfo())
191 Diag(Tok, diag::pp_poisoning_existing_macro);
192
193 // Finally, poison it!
194 II->setIsPoisoned();
195 }
196}
197
198/// HandlePragmaSystemHeader - Implement #pragma GCC system_header. We know
199/// that the whole directive has been parsed.
200void Preprocessor::HandlePragmaSystemHeader(LexerToken &SysHeaderTok) {
201 if (isInPrimaryFile()) {
202 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
203 return;
204 }
205
206 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
207 Lexer *TheLexer = getCurrentFileLexer();
208
209 // Mark the file as a system header.
210 const FileEntry *File =
211 SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
212 getFileInfo(File).DirInfo = DirectoryLookup::SystemHeaderDir;
213
214 // Notify the client, if desired, that we are in a new source file.
215 if (FileChangeHandler)
216 FileChangeHandler(TheLexer->getSourceLocation(TheLexer->BufferPtr),
217 SystemHeaderPragma, DirectoryLookup::SystemHeaderDir);
218}
219
220/// HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah.
221///
222void Preprocessor::HandlePragmaDependency(LexerToken &DependencyTok) {
223 LexerToken FilenameTok;
224 std::string Filename = CurLexer->LexIncludeFilename(FilenameTok);
225
226 // If the token kind is EOM, the error has already been diagnosed.
227 if (FilenameTok.getKind() == tok::eom)
228 return;
229
230 // Find out whether the filename is <x> or "x".
231 bool isAngled = Filename[0] == '<';
232
233 // Remove the quotes.
234 Filename = std::string(Filename.begin()+1, Filename.end()-1);
235
236 // Search include directories.
237 const DirectoryLookup *CurDir;
238 const FileEntry *File = LookupFile(Filename, isAngled, 0, CurDir);
239 if (File == 0)
240 return Diag(FilenameTok, diag::err_pp_file_not_found);
241
242 unsigned FileID = getCurrentFileLexer()->getCurFileID();
243 const FileEntry *CurFile = SourceMgr.getFileEntryForFileID(FileID);
244
245 // If this file is older than the file it depends on, emit a diagnostic.
246 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
247 // Lex tokens at the end of the message and include them in the message.
248 std::string Message;
249 Lex(DependencyTok);
250 while (DependencyTok.getKind() != tok::eom) {
251 Message += getSpelling(DependencyTok) + " ";
252 Lex(DependencyTok);
253 }
254
255 Message.erase(Message.end()-1);
256 Diag(FilenameTok, diag::pp_out_of_date_dependency, Message);
257 }
258}
259
260
261/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
262/// If 'Namespace' is non-null, then it is a token required to exist on the
263/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
264void Preprocessor::AddPragmaHandler(const char *Namespace,
265 PragmaHandler *Handler) {
266 PragmaNamespace *InsertNS = PragmaHandlers;
267
268 // If this is specified to be in a namespace, step down into it.
269 if (Namespace) {
270 IdentifierTokenInfo *NSID = getIdentifierInfo(Namespace);
271
272 // If there is already a pragma handler with the name of this namespace,
273 // we either have an error (directive with the same name as a namespace) or
274 // we already have the namespace to insert into.
275 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(NSID)) {
276 InsertNS = Existing->getIfNamespace();
277 assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
278 " handler with the same name!");
279 } else {
280 // Otherwise, this namespace doesn't exist yet, create and insert the
281 // handler for it.
282 InsertNS = new PragmaNamespace(NSID);
283 PragmaHandlers->AddPragma(InsertNS);
284 }
285 }
286
287 // Check to make sure we don't already have a pragma for this identifier.
288 assert(!InsertNS->FindHandler(Handler->getName()) &&
289 "Pragma handler already exists for this identifier!");
290 InsertNS->AddPragma(Handler);
291}
292
293namespace {
294struct PragmaOnceHandler : public PragmaHandler {
295 PragmaOnceHandler(const IdentifierTokenInfo *OnceID) : PragmaHandler(OnceID){}
296 virtual void HandlePragma(Preprocessor &PP, LexerToken &OnceTok) {
297 PP.CheckEndOfDirective("#pragma once");
298 PP.HandlePragmaOnce(OnceTok);
299 }
300};
301
302struct PragmaPoisonHandler : public PragmaHandler {
303 PragmaPoisonHandler(const IdentifierTokenInfo *ID) : PragmaHandler(ID) {}
304 virtual void HandlePragma(Preprocessor &PP, LexerToken &PoisonTok) {
305 PP.HandlePragmaPoison(PoisonTok);
306 }
307};
308
309struct PragmaSystemHeaderHandler : public PragmaHandler {
310 PragmaSystemHeaderHandler(const IdentifierTokenInfo *ID) : PragmaHandler(ID){}
311 virtual void HandlePragma(Preprocessor &PP, LexerToken &SHToken) {
312 PP.HandlePragmaSystemHeader(SHToken);
313 PP.CheckEndOfDirective("#pragma");
314 }
315};
316struct PragmaDependencyHandler : public PragmaHandler {
317 PragmaDependencyHandler(const IdentifierTokenInfo *ID) : PragmaHandler(ID) {}
318 virtual void HandlePragma(Preprocessor &PP, LexerToken &DepToken) {
319 PP.HandlePragmaDependency(DepToken);
320 }
321};
322} // end anonymous namespace
323
324
325/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
326/// #pragma GCC poison/system_header/dependency and #pragma once.
327void Preprocessor::RegisterBuiltinPragmas() {
328 AddPragmaHandler(0, new PragmaOnceHandler(getIdentifierInfo("once")));
329 AddPragmaHandler("GCC", new PragmaPoisonHandler(getIdentifierInfo("poison")));
330 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler(
331 getIdentifierInfo("system_header")));
332 AddPragmaHandler("GCC", new PragmaDependencyHandler(
333 getIdentifierInfo("dependency")));
334}