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