blob: 74d47ab29407a3d84090a00609913512171faf5d [file] [log] [blame]
Chris Lattner87414e82008-03-09 04:10:46 +00001//===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements pieces of the Preprocessor interface that manage the
11// current lexer stack.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
16#include "clang/Lex/HeaderSearch.h"
17#include "clang/Lex/MacroInfo.h"
18#include "clang/Lex/PPCallbacks.h"
19#include "clang/Basic/Diagnostic.h"
20#include "clang/Basic/SourceManager.h"
21using namespace clang;
22
23PPCallbacks::~PPCallbacks() {
24}
25
26
27//===----------------------------------------------------------------------===//
28// Source File Location Methods.
29//===----------------------------------------------------------------------===//
30
31/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
32/// return null on failure. isAngled indicates whether the file reference is
33/// for system #include's or not (i.e. using <> instead of "").
34const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
35 const char *FilenameEnd,
36 bool isAngled,
37 const DirectoryLookup *FromDir,
38 const DirectoryLookup *&CurDir) {
39 // If the header lookup mechanism may be relative to the current file, pass in
40 // info about where the current file is.
41 const FileEntry *CurFileEnt = 0;
42 if (!FromDir) {
43 SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc();
44 CurFileEnt = SourceMgr.getFileEntryForLoc(FileLoc);
45 }
46
47 // Do a standard file entry lookup.
48 CurDir = CurDirLookup;
49 const FileEntry *FE =
50 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
51 isAngled, FromDir, CurDir, CurFileEnt);
52 if (FE) return FE;
53
54 // Otherwise, see if this is a subframework header. If so, this is relative
55 // to one of the headers on the #include stack. Walk the list of the current
56 // headers on the #include stack and pass them to HeaderInfo.
57 if (CurLexer && !CurLexer->Is_PragmaLexer) {
58 if ((CurFileEnt = SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc())))
59 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
60 CurFileEnt)))
61 return FE;
62 }
63
64 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
65 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
66 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
67 if ((CurFileEnt =
68 SourceMgr.getFileEntryForLoc(ISEntry.TheLexer->getFileLoc())))
69 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart,
70 FilenameEnd, CurFileEnt)))
71 return FE;
72 }
73 }
74
75 // Otherwise, we really couldn't find the file.
76 return 0;
77}
78
79/// isInPrimaryFile - Return true if we're in the top-level file, not in a
80/// #include.
81bool Preprocessor::isInPrimaryFile() const {
82 if (CurLexer && !CurLexer->Is_PragmaLexer)
83 return IncludeMacroStack.empty();
84
85 // If there are any stacked lexers, we're in a #include.
86 assert(IncludeMacroStack[0].TheLexer &&
87 !IncludeMacroStack[0].TheLexer->Is_PragmaLexer &&
88 "Top level include stack isn't our primary lexer?");
89 for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
90 if (IncludeMacroStack[i].TheLexer &&
91 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
92 return false;
93 return true;
94}
95
96/// getCurrentLexer - Return the current file lexer being lexed from. Note
97/// that this ignores any potentially active macro expansions and _Pragma
98/// expansions going on at the time.
99Lexer *Preprocessor::getCurrentFileLexer() const {
100 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
101
102 // Look for a stacked lexer.
103 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
104 Lexer *L = IncludeMacroStack[i-1].TheLexer;
105 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
106 return L;
107 }
108 return 0;
109}
110
111
112/// EnterSourceFile - Add a source file to the top of the include stack and
113/// start lexing tokens from it instead of the current buffer. Return true
114/// on failure.
115void Preprocessor::EnterSourceFile(unsigned FileID,
116 const DirectoryLookup *CurDir) {
117 assert(CurTokenLexer == 0 && "Cannot #include a file inside a macro!");
118 ++NumEnteredSourceFiles;
119
120 if (MaxIncludeStackDepth < IncludeMacroStack.size())
121 MaxIncludeStackDepth = IncludeMacroStack.size();
122
123 Lexer *TheLexer = new Lexer(SourceLocation::getFileLoc(FileID, 0), *this);
124 EnterSourceFileWithLexer(TheLexer, CurDir);
125}
126
127/// EnterSourceFile - Add a source file to the top of the include stack and
128/// start lexing tokens from it instead of the current buffer.
129void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
130 const DirectoryLookup *CurDir) {
131
132 // Add the current lexer to the include stack.
133 if (CurLexer || CurTokenLexer)
134 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
135 CurTokenLexer));
136
137 CurLexer = TheLexer;
138 CurDirLookup = CurDir;
139 CurTokenLexer = 0;
140
141 // Notify the client, if desired, that we are in a new source file.
142 if (Callbacks && !CurLexer->Is_PragmaLexer) {
143 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
144
145 // Get the file entry for the current file.
146 if (const FileEntry *FE =
147 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
148 FileType = HeaderInfo.getFileDirFlavor(FE);
149
150 Callbacks->FileChanged(CurLexer->getFileLoc(),
151 PPCallbacks::EnterFile, FileType);
152 }
153}
154
155
156
157/// EnterMacro - Add a Macro to the top of the include stack and start lexing
158/// tokens from it instead of the current buffer.
159void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
160 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
161 CurTokenLexer));
162 CurLexer = 0;
163 CurDirLookup = 0;
164
165 if (NumCachedTokenLexers == 0) {
166 CurTokenLexer = new TokenLexer(Tok, Args, *this);
167 } else {
168 CurTokenLexer = TokenLexerCache[--NumCachedTokenLexers];
169 CurTokenLexer->Init(Tok, Args);
170 }
171}
172
173/// EnterTokenStream - Add a "macro" context to the top of the include stack,
174/// which will cause the lexer to start returning the specified tokens. Note
175/// that these tokens will be re-macro-expanded when/if expansion is enabled.
176/// This method assumes that the specified stream of tokens has a permanent
177/// owner somewhere, so they do not need to be copied.
178void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks) {
179 // Save our current state.
180 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
181 CurTokenLexer));
182 CurLexer = 0;
183 CurDirLookup = 0;
184
185 // Create a macro expander to expand from the specified token stream.
186 if (NumCachedTokenLexers == 0) {
187 CurTokenLexer = new TokenLexer(Toks, NumToks, *this);
188 } else {
189 CurTokenLexer = TokenLexerCache[--NumCachedTokenLexers];
190 CurTokenLexer->Init(Toks, NumToks);
191 }
192}
193
194/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
195/// the current file. This either returns the EOF token or pops a level off
196/// the include stack and keeps going.
197bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
198 assert(!CurTokenLexer &&
199 "Ending a file when currently in a macro!");
200
201 // See if this file had a controlling macro.
202 if (CurLexer) { // Not ending a macro, ignore it.
203 if (const IdentifierInfo *ControllingMacro =
204 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
205 // Okay, this has a controlling macro, remember in PerFileInfo.
206 if (const FileEntry *FE =
207 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
208 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
209 }
210 }
211
212 // If this is a #include'd file, pop it off the include stack and continue
213 // lexing the #includer file.
214 if (!IncludeMacroStack.empty()) {
215 // We're done with the #included file.
216 RemoveTopOfLexerStack();
217
218 // Notify the client, if desired, that we are in a new source file.
219 if (Callbacks && !isEndOfMacro && CurLexer) {
220 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
221
222 // Get the file entry for the current file.
223 if (const FileEntry *FE =
224 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
225 FileType = HeaderInfo.getFileDirFlavor(FE);
226
227 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
228 PPCallbacks::ExitFile, FileType);
229 }
230
231 // Client should lex another token.
232 return false;
233 }
234
235 // If the file ends with a newline, form the EOF token on the newline itself,
236 // rather than "on the line following it", which doesn't exist. This makes
237 // diagnostics relating to the end of file include the last file that the user
238 // actually typed, which is goodness.
239 const char *EndPos = CurLexer->BufferEnd;
240 if (EndPos != CurLexer->BufferStart &&
241 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
242 --EndPos;
243
244 // Handle \n\r and \r\n:
245 if (EndPos != CurLexer->BufferStart &&
246 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
247 EndPos[-1] != EndPos[0])
248 --EndPos;
249 }
250
251 Result.startToken();
252 CurLexer->BufferPtr = EndPos;
253 CurLexer->FormTokenWithChars(Result, EndPos);
254 Result.setKind(tok::eof);
255
256 // We're done with the #included file.
257 delete CurLexer;
258 CurLexer = 0;
259
260 // This is the end of the top-level file. If the diag::pp_macro_not_used
261 // diagnostic is enabled, look for macros that have not been used.
262 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
263 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
264 Macros.begin(), E = Macros.end(); I != E; ++I) {
265 if (!I->second->isUsed())
266 Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
267 }
268 }
269 return true;
270}
271
272/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
273/// hits the end of its token stream.
274bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
275 assert(CurTokenLexer && !CurLexer &&
276 "Ending a macro when currently in a #include file!");
277
278 // Delete or cache the now-dead macro expander.
279 if (NumCachedTokenLexers == TokenLexerCacheSize)
280 delete CurTokenLexer;
281 else
282 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer;
283
284 // Handle this like a #include file being popped off the stack.
285 CurTokenLexer = 0;
286 return HandleEndOfFile(Result, true);
287}
288
289/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
290/// lexer stack. This should only be used in situations where the current
291/// state of the top-of-stack lexer is unknown.
292void Preprocessor::RemoveTopOfLexerStack() {
293 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
294
295 if (CurTokenLexer) {
296 // Delete or cache the now-dead macro expander.
297 if (NumCachedTokenLexers == TokenLexerCacheSize)
298 delete CurTokenLexer;
299 else
300 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer;
301 } else {
302 delete CurLexer;
303 }
304 CurLexer = IncludeMacroStack.back().TheLexer;
305 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
306 CurTokenLexer = IncludeMacroStack.back().TheTokenLexer;
307 IncludeMacroStack.pop_back();
308}
309
310/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
311/// comment (/##/) in microsoft mode, this method handles updating the current
312/// state, returning the token on the next source line.
313void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
314 assert(CurTokenLexer && !CurLexer &&
315 "Pasted comment can only be formed from macro");
316
317 // We handle this by scanning for the closest real lexer, switching it to
318 // raw mode and preprocessor mode. This will cause it to return \n as an
319 // explicit EOM token.
320 Lexer *FoundLexer = 0;
321 bool LexerWasInPPMode = false;
322 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
323 IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
324 if (ISI.TheLexer == 0) continue; // Scan for a real lexer.
325
326 // Once we find a real lexer, mark it as raw mode (disabling macro
327 // expansions) and preprocessor mode (return EOM). We know that the lexer
328 // was *not* in raw mode before, because the macro that the comment came
329 // from was expanded. However, it could have already been in preprocessor
330 // mode (#if COMMENT) in which case we have to return it to that mode and
331 // return EOM.
332 FoundLexer = ISI.TheLexer;
333 FoundLexer->LexingRawMode = true;
334 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
335 FoundLexer->ParsingPreprocessorDirective = true;
336 break;
337 }
338
339 // Okay, we either found and switched over the lexer, or we didn't find a
340 // lexer. In either case, finish off the macro the comment came from, getting
341 // the next token.
342 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
343
344 // Discarding comments as long as we don't have EOF or EOM. This 'comments
345 // out' the rest of the line, including any tokens that came from other macros
346 // that were active, as in:
347 // #define submacro a COMMENT b
348 // submacro c
349 // which should lex to 'a' only: 'b' and 'c' should be removed.
350 while (Tok.isNot(tok::eom) && Tok.isNot(tok::eof))
351 Lex(Tok);
352
353 // If we got an eom token, then we successfully found the end of the line.
354 if (Tok.is(tok::eom)) {
355 assert(FoundLexer && "Can't get end of line without an active lexer");
356 // Restore the lexer back to normal mode instead of raw mode.
357 FoundLexer->LexingRawMode = false;
358
359 // If the lexer was already in preprocessor mode, just return the EOM token
360 // to finish the preprocessor line.
361 if (LexerWasInPPMode) return;
362
363 // Otherwise, switch out of PP mode and return the next lexed token.
364 FoundLexer->ParsingPreprocessorDirective = false;
365 return Lex(Tok);
366 }
367
368 // If we got an EOF token, then we reached the end of the token stream but
369 // didn't find an explicit \n. This can only happen if there was no lexer
370 // active (an active lexer would return EOM at EOF if there was no \n in
371 // preprocessor directive mode), so just return EOF as our token.
372 assert(!FoundLexer && "Lexer should return EOM before EOF in PP mode");
373}