blob: 99d1ca0a91fbc24c721871d56c7f628bb54b9336 [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 {
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 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
Chris Lattner87414e82008-03-09 04:10:46 +000091 CurLexer = TheLexer;
92 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) {
113 CurTokenLexer = new TokenLexer(Tok, Args, *this);
114 } else {
115 CurTokenLexer = TokenLexerCache[--NumCachedTokenLexers];
116 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) {
Chris Lattner80712392008-03-10 06:06:04 +0000141 CurTokenLexer = new TokenLexer(Toks, NumToks, DisableMacroExpansion,
142 OwnsTokens, *this);
Chris Lattner87414e82008-03-09 04:10:46 +0000143 } else {
144 CurTokenLexer = 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.
207 delete CurLexer;
208 CurLexer = 0;
209
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)
230 delete CurTokenLexer;
231 else
232 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer;
233
234 // Handle this like a #include file being popped off the stack.
235 CurTokenLexer = 0;
236 return HandleEndOfFile(Result, true);
237}
238
239/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
240/// lexer stack. This should only be used in situations where the current
241/// state of the top-of-stack lexer is unknown.
242void Preprocessor::RemoveTopOfLexerStack() {
243 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
244
245 if (CurTokenLexer) {
246 // Delete or cache the now-dead macro expander.
247 if (NumCachedTokenLexers == TokenLexerCacheSize)
248 delete CurTokenLexer;
249 else
250 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer;
251 } else {
252 delete CurLexer;
253 }
Ted Kremenek383ad382008-11-13 16:51:03 +0000254
255 PopIncludeMacroStack();
Chris Lattner87414e82008-03-09 04:10:46 +0000256}
257
258/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
259/// comment (/##/) in microsoft mode, this method handles updating the current
260/// state, returning the token on the next source line.
261void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
262 assert(CurTokenLexer && !CurLexer &&
263 "Pasted comment can only be formed from macro");
264
265 // We handle this by scanning for the closest real lexer, switching it to
266 // raw mode and preprocessor mode. This will cause it to return \n as an
267 // explicit EOM token.
268 Lexer *FoundLexer = 0;
269 bool LexerWasInPPMode = false;
270 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
271 IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
272 if (ISI.TheLexer == 0) continue; // Scan for a real lexer.
273
274 // Once we find a real lexer, mark it as raw mode (disabling macro
275 // expansions) and preprocessor mode (return EOM). We know that the lexer
276 // was *not* in raw mode before, because the macro that the comment came
277 // from was expanded. However, it could have already been in preprocessor
278 // mode (#if COMMENT) in which case we have to return it to that mode and
279 // return EOM.
280 FoundLexer = ISI.TheLexer;
281 FoundLexer->LexingRawMode = true;
282 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
283 FoundLexer->ParsingPreprocessorDirective = true;
284 break;
285 }
286
287 // Okay, we either found and switched over the lexer, or we didn't find a
288 // lexer. In either case, finish off the macro the comment came from, getting
289 // the next token.
290 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
291
292 // Discarding comments as long as we don't have EOF or EOM. This 'comments
293 // out' the rest of the line, including any tokens that came from other macros
294 // that were active, as in:
295 // #define submacro a COMMENT b
296 // submacro c
297 // which should lex to 'a' only: 'b' and 'c' should be removed.
298 while (Tok.isNot(tok::eom) && Tok.isNot(tok::eof))
299 Lex(Tok);
300
301 // If we got an eom token, then we successfully found the end of the line.
302 if (Tok.is(tok::eom)) {
303 assert(FoundLexer && "Can't get end of line without an active lexer");
304 // Restore the lexer back to normal mode instead of raw mode.
305 FoundLexer->LexingRawMode = false;
306
307 // If the lexer was already in preprocessor mode, just return the EOM token
308 // to finish the preprocessor line.
309 if (LexerWasInPPMode) return;
310
311 // Otherwise, switch out of PP mode and return the next lexed token.
312 FoundLexer->ParsingPreprocessorDirective = false;
313 return Lex(Tok);
314 }
315
316 // If we got an EOF token, then we reached the end of the token stream but
317 // didn't find an explicit \n. This can only happen if there was no lexer
318 // active (an active lexer would return EOM at EOF if there was no \n in
319 // preprocessor directive mode), so just return EOF as our token.
320 assert(!FoundLexer && "Lexer should return EOM before EOF in PP mode");
321}