blob: 3b63c9bb094cf24ea10f28adcac281c7035d442d [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"
Chris Lattner87414e82008-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 Lattner80712392008-03-10 06:06:04 +000027// Miscellaneous Methods.
Chris Lattner87414e82008-03-09 04:10:46 +000028//===----------------------------------------------------------------------===//
29
Chris Lattner87414e82008-03-09 04:10:46 +000030/// isInPrimaryFile - Return true if we're in the top-level file, not in a
Chris Lattnerb99dc1d2008-03-09 04:49:35 +000031/// #include. This looks through macro expansions and active _Pragma lexers.
Chris Lattner87414e82008-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 {
Ted Kremenekb0eef362008-11-13 17:11:24 +000051 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer.get();
Chris Lattner87414e82008-03-09 04:10:46 +000052
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 Lattner80712392008-03-10 06:06:04 +000062
63//===----------------------------------------------------------------------===//
64// Methods for Entering and Callbacks for leaving various contexts
65//===----------------------------------------------------------------------===//
Chris Lattner87414e82008-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 Lattner7257ce22008-09-26 20:12:23 +000081
Chris Lattner87414e82008-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)
Ted Kremenek383ad382008-11-13 16:51:03 +000089 PushIncludeMacroStack();
90
Ted Kremenekb0eef362008-11-13 17:11:24 +000091 CurLexer.reset(TheLexer);
Ted Kremenek306be5f2008-11-18 00:12:49 +000092 CurPPLexer = TheLexer;
Chris Lattner87414e82008-03-09 04:10:46 +000093 CurDirLookup = CurDir;
Chris Lattner87414e82008-03-09 04:10:46 +000094
95 // Notify the client, if desired, that we are in a new source file.
96 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattner7a4864e2008-10-27 01:19:25 +000097 SrcMgr::CharacteristicKind FileType =
Chris Lattner6f044062008-09-26 21:18:42 +000098 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
Chris Lattner87414e82008-03-09 04:10:46 +000099
100 Callbacks->FileChanged(CurLexer->getFileLoc(),
101 PPCallbacks::EnterFile, FileType);
102 }
103}
104
105
106
107/// EnterMacro - Add a Macro to the top of the include stack and start lexing
108/// tokens from it instead of the current buffer.
109void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
Ted Kremenek383ad382008-11-13 16:51:03 +0000110 PushIncludeMacroStack();
Chris Lattner87414e82008-03-09 04:10:46 +0000111 CurDirLookup = 0;
112
113 if (NumCachedTokenLexers == 0) {
Ted Kremenekb0eef362008-11-13 17:11:24 +0000114 CurTokenLexer.reset(new TokenLexer(Tok, Args, *this));
Chris Lattner87414e82008-03-09 04:10:46 +0000115 } else {
Ted Kremenekb0eef362008-11-13 17:11:24 +0000116 CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
Chris Lattner87414e82008-03-09 04:10:46 +0000117 CurTokenLexer->Init(Tok, Args);
118 }
119}
120
121/// EnterTokenStream - Add a "macro" context to the top of the include stack,
Chris Lattner80712392008-03-10 06:06:04 +0000122/// which will cause the lexer to start returning the specified tokens.
123///
124/// If DisableMacroExpansion is true, tokens lexed from the token stream will
125/// not be subject to further macro expansion. Otherwise, these tokens will
126/// be re-macro-expanded when/if expansion is enabled.
127///
128/// If OwnsTokens is false, this method assumes that the specified stream of
129/// tokens has a permanent owner somewhere, so they do not need to be copied.
130/// If it is true, it assumes the array of tokens is allocated with new[] and
131/// must be freed.
132///
133void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
134 bool DisableMacroExpansion,
135 bool OwnsTokens) {
Chris Lattner87414e82008-03-09 04:10:46 +0000136 // Save our current state.
Ted Kremenek383ad382008-11-13 16:51:03 +0000137 PushIncludeMacroStack();
Chris Lattner87414e82008-03-09 04:10:46 +0000138 CurDirLookup = 0;
139
140 // Create a macro expander to expand from the specified token stream.
141 if (NumCachedTokenLexers == 0) {
Ted Kremenekb0eef362008-11-13 17:11:24 +0000142 CurTokenLexer.reset(new TokenLexer(Toks, NumToks, DisableMacroExpansion,
143 OwnsTokens, *this));
Chris Lattner87414e82008-03-09 04:10:46 +0000144 } else {
Ted Kremenekb0eef362008-11-13 17:11:24 +0000145 CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
Chris Lattner80712392008-03-10 06:06:04 +0000146 CurTokenLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
Chris Lattner87414e82008-03-09 04:10:46 +0000147 }
148}
149
150/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
151/// the current file. This either returns the EOF token or pops a level off
152/// the include stack and keeps going.
153bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
154 assert(!CurTokenLexer &&
155 "Ending a file when currently in a macro!");
156
157 // See if this file had a controlling macro.
158 if (CurLexer) { // Not ending a macro, ignore it.
159 if (const IdentifierInfo *ControllingMacro =
160 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
161 // Okay, this has a controlling macro, remember in PerFileInfo.
162 if (const FileEntry *FE =
163 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
164 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
165 }
166 }
167
168 // If this is a #include'd file, pop it off the include stack and continue
169 // lexing the #includer file.
170 if (!IncludeMacroStack.empty()) {
171 // We're done with the #included file.
172 RemoveTopOfLexerStack();
173
174 // Notify the client, if desired, that we are in a new source file.
175 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattner7a4864e2008-10-27 01:19:25 +0000176 SrcMgr::CharacteristicKind FileType =
Chris Lattner6f044062008-09-26 21:18:42 +0000177 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
Chris Lattner87414e82008-03-09 04:10:46 +0000178
Chris Lattner87414e82008-03-09 04:10:46 +0000179 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
180 PPCallbacks::ExitFile, FileType);
181 }
182
183 // Client should lex another token.
184 return false;
185 }
186
187 // If the file ends with a newline, form the EOF token on the newline itself,
188 // rather than "on the line following it", which doesn't exist. This makes
189 // diagnostics relating to the end of file include the last file that the user
190 // actually typed, which is goodness.
191 const char *EndPos = CurLexer->BufferEnd;
192 if (EndPos != CurLexer->BufferStart &&
193 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
194 --EndPos;
195
196 // Handle \n\r and \r\n:
197 if (EndPos != CurLexer->BufferStart &&
198 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
199 EndPos[-1] != EndPos[0])
200 --EndPos;
201 }
202
203 Result.startToken();
204 CurLexer->BufferPtr = EndPos;
Chris Lattner0344cc72008-10-12 04:51:35 +0000205 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
Chris Lattner87414e82008-03-09 04:10:46 +0000206
207 // We're done with the #included file.
Ted Kremenekb0eef362008-11-13 17:11:24 +0000208 CurLexer.reset();
Chris Lattner87414e82008-03-09 04:10:46 +0000209
210 // This is the end of the top-level file. If the diag::pp_macro_not_used
211 // diagnostic is enabled, look for macros that have not been used.
212 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
213 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
214 Macros.begin(), E = Macros.end(); I != E; ++I) {
215 if (!I->second->isUsed())
216 Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
217 }
218 }
219 return true;
220}
221
222/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
223/// hits the end of its token stream.
224bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
225 assert(CurTokenLexer && !CurLexer &&
226 "Ending a macro when currently in a #include file!");
227
228 // Delete or cache the now-dead macro expander.
229 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremenekb0eef362008-11-13 17:11:24 +0000230 CurTokenLexer.reset();
Chris Lattner87414e82008-03-09 04:10:46 +0000231 else
Ted Kremenekb0eef362008-11-13 17:11:24 +0000232 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
Chris Lattner87414e82008-03-09 04:10:46 +0000233
234 // Handle this like a #include file being popped off the stack.
Chris Lattner87414e82008-03-09 04:10:46 +0000235 return HandleEndOfFile(Result, true);
236}
237
238/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
239/// lexer stack. This should only be used in situations where the current
240/// state of the top-of-stack lexer is unknown.
241void Preprocessor::RemoveTopOfLexerStack() {
242 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
243
244 if (CurTokenLexer) {
245 // Delete or cache the now-dead macro expander.
246 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremenekb0eef362008-11-13 17:11:24 +0000247 CurTokenLexer.reset();
Chris Lattner87414e82008-03-09 04:10:46 +0000248 else
Ted Kremenekb0eef362008-11-13 17:11:24 +0000249 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
Chris Lattner87414e82008-03-09 04:10:46 +0000250 } else {
Ted Kremenekb0eef362008-11-13 17:11:24 +0000251 CurLexer.reset();
Chris Lattner87414e82008-03-09 04:10:46 +0000252 }
Ted Kremenek383ad382008-11-13 16:51:03 +0000253
254 PopIncludeMacroStack();
Chris Lattner87414e82008-03-09 04:10:46 +0000255}
256
257/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
258/// comment (/##/) in microsoft mode, this method handles updating the current
259/// state, returning the token on the next source line.
260void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
261 assert(CurTokenLexer && !CurLexer &&
262 "Pasted comment can only be formed from macro");
263
264 // We handle this by scanning for the closest real lexer, switching it to
265 // raw mode and preprocessor mode. This will cause it to return \n as an
266 // explicit EOM token.
267 Lexer *FoundLexer = 0;
268 bool LexerWasInPPMode = false;
269 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
270 IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
271 if (ISI.TheLexer == 0) continue; // Scan for a real lexer.
272
273 // Once we find a real lexer, mark it as raw mode (disabling macro
274 // expansions) and preprocessor mode (return EOM). We know that the lexer
275 // was *not* in raw mode before, because the macro that the comment came
276 // from was expanded. However, it could have already been in preprocessor
277 // mode (#if COMMENT) in which case we have to return it to that mode and
278 // return EOM.
279 FoundLexer = ISI.TheLexer;
280 FoundLexer->LexingRawMode = true;
281 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
282 FoundLexer->ParsingPreprocessorDirective = true;
283 break;
284 }
285
286 // Okay, we either found and switched over the lexer, or we didn't find a
287 // lexer. In either case, finish off the macro the comment came from, getting
288 // the next token.
289 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
290
291 // Discarding comments as long as we don't have EOF or EOM. This 'comments
292 // out' the rest of the line, including any tokens that came from other macros
293 // that were active, as in:
294 // #define submacro a COMMENT b
295 // submacro c
296 // which should lex to 'a' only: 'b' and 'c' should be removed.
297 while (Tok.isNot(tok::eom) && Tok.isNot(tok::eof))
298 Lex(Tok);
299
300 // If we got an eom token, then we successfully found the end of the line.
301 if (Tok.is(tok::eom)) {
302 assert(FoundLexer && "Can't get end of line without an active lexer");
303 // Restore the lexer back to normal mode instead of raw mode.
304 FoundLexer->LexingRawMode = false;
305
306 // If the lexer was already in preprocessor mode, just return the EOM token
307 // to finish the preprocessor line.
308 if (LexerWasInPPMode) return;
309
310 // Otherwise, switch out of PP mode and return the next lexed token.
311 FoundLexer->ParsingPreprocessorDirective = false;
312 return Lex(Tok);
313 }
314
315 // If we got an EOF token, then we reached the end of the token stream but
316 // didn't find an explicit \n. This can only happen if there was no lexer
317 // active (an active lexer would return EOM at EOF if there was no \n in
318 // preprocessor directive mode), so just return EOF as our token.
319 assert(!FoundLexer && "Lexer should return EOM before EOF in PP mode");
320}