blob: 1522bf5e8cadec2b5ac27e315407fbd42398f54f [file] [log] [blame]
Chris Lattner8c32b1a2008-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"
Chris Lattner8c32b1a2008-03-09 04:10:46 +000018#include "clang/Basic/Diagnostic.h"
19#include "clang/Basic/SourceManager.h"
20using namespace clang;
21
22PPCallbacks::~PPCallbacks() {
23}
24
25
26//===----------------------------------------------------------------------===//
Chris Lattner6b884502008-03-10 06:06:04 +000027// Miscellaneous Methods.
Chris Lattner8c32b1a2008-03-09 04:10:46 +000028//===----------------------------------------------------------------------===//
29
Chris Lattner8c32b1a2008-03-09 04:10:46 +000030/// isInPrimaryFile - Return true if we're in the top-level file, not in a
Chris Lattner7d39d742008-03-09 04:49:35 +000031/// #include. This looks through macro expansions and active _Pragma lexers.
Chris Lattner8c32b1a2008-03-09 04:10:46 +000032bool Preprocessor::isInPrimaryFile() const {
33 if (CurLexer && !CurLexer->Is_PragmaLexer)
34 return IncludeMacroStack.empty();
35
36 // If there are any stacked lexers, we're in a #include.
37 assert(IncludeMacroStack[0].TheLexer &&
38 !IncludeMacroStack[0].TheLexer->Is_PragmaLexer &&
39 "Top level include stack isn't our primary lexer?");
40 for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
41 if (IncludeMacroStack[i].TheLexer &&
42 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
43 return false;
44 return true;
45}
46
47/// getCurrentLexer - Return the current file lexer being lexed from. Note
48/// that this ignores any potentially active macro expansions and _Pragma
49/// expansions going on at the time.
50Lexer *Preprocessor::getCurrentFileLexer() const {
51 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
52
53 // Look for a stacked lexer.
54 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
55 Lexer *L = IncludeMacroStack[i-1].TheLexer;
56 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
57 return L;
58 }
59 return 0;
60}
61
Chris Lattner6b884502008-03-10 06:06:04 +000062
63//===----------------------------------------------------------------------===//
64// Methods for Entering and Callbacks for leaving various contexts
65//===----------------------------------------------------------------------===//
Chris Lattner8c32b1a2008-03-09 04:10:46 +000066
67/// EnterSourceFile - Add a source file to the top of the include stack and
68/// start lexing tokens from it instead of the current buffer. Return true
69/// on failure.
70void Preprocessor::EnterSourceFile(unsigned FileID,
71 const DirectoryLookup *CurDir) {
72 assert(CurTokenLexer == 0 && "Cannot #include a file inside a macro!");
73 ++NumEnteredSourceFiles;
74
75 if (MaxIncludeStackDepth < IncludeMacroStack.size())
76 MaxIncludeStackDepth = IncludeMacroStack.size();
77
78 Lexer *TheLexer = new Lexer(SourceLocation::getFileLoc(FileID, 0), *this);
79 EnterSourceFileWithLexer(TheLexer, CurDir);
80}
Chris Lattner72181832008-09-26 20:12:23 +000081
Chris Lattner8c32b1a2008-03-09 04:10:46 +000082/// EnterSourceFile - Add a source file to the top of the include stack and
83/// start lexing tokens from it instead of the current buffer.
84void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
85 const DirectoryLookup *CurDir) {
86
87 // Add the current lexer to the include stack.
88 if (CurLexer || CurTokenLexer)
89 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
90 CurTokenLexer));
91
92 CurLexer = TheLexer;
93 CurDirLookup = CurDir;
94 CurTokenLexer = 0;
95
96 // Notify the client, if desired, that we are in a new source file.
97 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattner72181832008-09-26 20:12:23 +000098 DirectoryLookup::DirType FileType =
99 // FIXME:
100 (DirectoryLookup::DirType)
101 SourceMgr.getDirCharacteristic(CurLexer->getFileLoc());
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000102
103 Callbacks->FileChanged(CurLexer->getFileLoc(),
104 PPCallbacks::EnterFile, FileType);
105 }
106}
107
108
109
110/// EnterMacro - Add a Macro to the top of the include stack and start lexing
111/// tokens from it instead of the current buffer.
112void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
113 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
114 CurTokenLexer));
115 CurLexer = 0;
116 CurDirLookup = 0;
117
118 if (NumCachedTokenLexers == 0) {
119 CurTokenLexer = new TokenLexer(Tok, Args, *this);
120 } else {
121 CurTokenLexer = TokenLexerCache[--NumCachedTokenLexers];
122 CurTokenLexer->Init(Tok, Args);
123 }
124}
125
126/// EnterTokenStream - Add a "macro" context to the top of the include stack,
Chris Lattner6b884502008-03-10 06:06:04 +0000127/// which will cause the lexer to start returning the specified tokens.
128///
129/// If DisableMacroExpansion is true, tokens lexed from the token stream will
130/// not be subject to further macro expansion. Otherwise, these tokens will
131/// be re-macro-expanded when/if expansion is enabled.
132///
133/// If OwnsTokens is false, this method assumes that the specified stream of
134/// tokens has a permanent owner somewhere, so they do not need to be copied.
135/// If it is true, it assumes the array of tokens is allocated with new[] and
136/// must be freed.
137///
138void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
139 bool DisableMacroExpansion,
140 bool OwnsTokens) {
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000141 // Save our current state.
142 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
143 CurTokenLexer));
144 CurLexer = 0;
145 CurDirLookup = 0;
146
147 // Create a macro expander to expand from the specified token stream.
148 if (NumCachedTokenLexers == 0) {
Chris Lattner6b884502008-03-10 06:06:04 +0000149 CurTokenLexer = new TokenLexer(Toks, NumToks, DisableMacroExpansion,
150 OwnsTokens, *this);
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000151 } else {
152 CurTokenLexer = TokenLexerCache[--NumCachedTokenLexers];
Chris Lattner6b884502008-03-10 06:06:04 +0000153 CurTokenLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000154 }
155}
156
157/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
158/// the current file. This either returns the EOF token or pops a level off
159/// the include stack and keeps going.
160bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
161 assert(!CurTokenLexer &&
162 "Ending a file when currently in a macro!");
163
164 // See if this file had a controlling macro.
165 if (CurLexer) { // Not ending a macro, ignore it.
166 if (const IdentifierInfo *ControllingMacro =
167 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
168 // Okay, this has a controlling macro, remember in PerFileInfo.
169 if (const FileEntry *FE =
170 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
171 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
172 }
173 }
174
175 // If this is a #include'd file, pop it off the include stack and continue
176 // lexing the #includer file.
177 if (!IncludeMacroStack.empty()) {
178 // We're done with the #included file.
179 RemoveTopOfLexerStack();
180
181 // Notify the client, if desired, that we are in a new source file.
182 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattner72181832008-09-26 20:12:23 +0000183 DirectoryLookup::DirType FileType =
184 // FIXME:
185 (DirectoryLookup::DirType)
186 SourceMgr.getDirCharacteristic(CurLexer->getFileLoc());
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000187
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000188 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
189 PPCallbacks::ExitFile, FileType);
190 }
191
192 // Client should lex another token.
193 return false;
194 }
195
196 // If the file ends with a newline, form the EOF token on the newline itself,
197 // rather than "on the line following it", which doesn't exist. This makes
198 // diagnostics relating to the end of file include the last file that the user
199 // actually typed, which is goodness.
200 const char *EndPos = CurLexer->BufferEnd;
201 if (EndPos != CurLexer->BufferStart &&
202 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
203 --EndPos;
204
205 // Handle \n\r and \r\n:
206 if (EndPos != CurLexer->BufferStart &&
207 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
208 EndPos[-1] != EndPos[0])
209 --EndPos;
210 }
211
212 Result.startToken();
213 CurLexer->BufferPtr = EndPos;
214 CurLexer->FormTokenWithChars(Result, EndPos);
215 Result.setKind(tok::eof);
216
217 // We're done with the #included file.
218 delete CurLexer;
219 CurLexer = 0;
220
221 // This is the end of the top-level file. If the diag::pp_macro_not_used
222 // diagnostic is enabled, look for macros that have not been used.
223 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
224 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
225 Macros.begin(), E = Macros.end(); I != E; ++I) {
226 if (!I->second->isUsed())
227 Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
228 }
229 }
230 return true;
231}
232
233/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
234/// hits the end of its token stream.
235bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
236 assert(CurTokenLexer && !CurLexer &&
237 "Ending a macro when currently in a #include file!");
238
239 // Delete or cache the now-dead macro expander.
240 if (NumCachedTokenLexers == TokenLexerCacheSize)
241 delete CurTokenLexer;
242 else
243 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer;
244
245 // Handle this like a #include file being popped off the stack.
246 CurTokenLexer = 0;
247 return HandleEndOfFile(Result, true);
248}
249
250/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
251/// lexer stack. This should only be used in situations where the current
252/// state of the top-of-stack lexer is unknown.
253void Preprocessor::RemoveTopOfLexerStack() {
254 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
255
256 if (CurTokenLexer) {
257 // Delete or cache the now-dead macro expander.
258 if (NumCachedTokenLexers == TokenLexerCacheSize)
259 delete CurTokenLexer;
260 else
261 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer;
262 } else {
263 delete CurLexer;
264 }
265 CurLexer = IncludeMacroStack.back().TheLexer;
266 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
267 CurTokenLexer = IncludeMacroStack.back().TheTokenLexer;
268 IncludeMacroStack.pop_back();
269}
270
271/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
272/// comment (/##/) in microsoft mode, this method handles updating the current
273/// state, returning the token on the next source line.
274void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
275 assert(CurTokenLexer && !CurLexer &&
276 "Pasted comment can only be formed from macro");
277
278 // We handle this by scanning for the closest real lexer, switching it to
279 // raw mode and preprocessor mode. This will cause it to return \n as an
280 // explicit EOM token.
281 Lexer *FoundLexer = 0;
282 bool LexerWasInPPMode = false;
283 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
284 IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
285 if (ISI.TheLexer == 0) continue; // Scan for a real lexer.
286
287 // Once we find a real lexer, mark it as raw mode (disabling macro
288 // expansions) and preprocessor mode (return EOM). We know that the lexer
289 // was *not* in raw mode before, because the macro that the comment came
290 // from was expanded. However, it could have already been in preprocessor
291 // mode (#if COMMENT) in which case we have to return it to that mode and
292 // return EOM.
293 FoundLexer = ISI.TheLexer;
294 FoundLexer->LexingRawMode = true;
295 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
296 FoundLexer->ParsingPreprocessorDirective = true;
297 break;
298 }
299
300 // Okay, we either found and switched over the lexer, or we didn't find a
301 // lexer. In either case, finish off the macro the comment came from, getting
302 // the next token.
303 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
304
305 // Discarding comments as long as we don't have EOF or EOM. This 'comments
306 // out' the rest of the line, including any tokens that came from other macros
307 // that were active, as in:
308 // #define submacro a COMMENT b
309 // submacro c
310 // which should lex to 'a' only: 'b' and 'c' should be removed.
311 while (Tok.isNot(tok::eom) && Tok.isNot(tok::eof))
312 Lex(Tok);
313
314 // If we got an eom token, then we successfully found the end of the line.
315 if (Tok.is(tok::eom)) {
316 assert(FoundLexer && "Can't get end of line without an active lexer");
317 // Restore the lexer back to normal mode instead of raw mode.
318 FoundLexer->LexingRawMode = false;
319
320 // If the lexer was already in preprocessor mode, just return the EOM token
321 // to finish the preprocessor line.
322 if (LexerWasInPPMode) return;
323
324 // Otherwise, switch out of PP mode and return the next lexed token.
325 FoundLexer->ParsingPreprocessorDirective = false;
326 return Lex(Tok);
327 }
328
329 // If we got an EOF token, then we reached the end of the token stream but
330 // didn't find an explicit \n. This can only happen if there was no lexer
331 // active (an active lexer would return EOM at EOF if there was no \n in
332 // preprocessor directive mode), so just return EOF as our token.
333 assert(!FoundLexer && "Lexer should return EOM before EOF in PP mode");
334}