blob: b7e9132baab7da0a83e28f6fd8b890dee1cbd860 [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 Lattner0b9e7362008-09-26 21:18:42 +000098 SrcMgr::Characteristic_t FileType =
99 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000100
101 Callbacks->FileChanged(CurLexer->getFileLoc(),
102 PPCallbacks::EnterFile, FileType);
103 }
104}
105
106
107
108/// EnterMacro - Add a Macro to the top of the include stack and start lexing
109/// tokens from it instead of the current buffer.
110void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
111 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
112 CurTokenLexer));
113 CurLexer = 0;
114 CurDirLookup = 0;
115
116 if (NumCachedTokenLexers == 0) {
117 CurTokenLexer = new TokenLexer(Tok, Args, *this);
118 } else {
119 CurTokenLexer = TokenLexerCache[--NumCachedTokenLexers];
120 CurTokenLexer->Init(Tok, Args);
121 }
122}
123
124/// EnterTokenStream - Add a "macro" context to the top of the include stack,
Chris Lattner6b884502008-03-10 06:06:04 +0000125/// which will cause the lexer to start returning the specified tokens.
126///
127/// If DisableMacroExpansion is true, tokens lexed from the token stream will
128/// not be subject to further macro expansion. Otherwise, these tokens will
129/// be re-macro-expanded when/if expansion is enabled.
130///
131/// If OwnsTokens is false, this method assumes that the specified stream of
132/// tokens has a permanent owner somewhere, so they do not need to be copied.
133/// If it is true, it assumes the array of tokens is allocated with new[] and
134/// must be freed.
135///
136void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
137 bool DisableMacroExpansion,
138 bool OwnsTokens) {
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000139 // Save our current state.
140 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
141 CurTokenLexer));
142 CurLexer = 0;
143 CurDirLookup = 0;
144
145 // Create a macro expander to expand from the specified token stream.
146 if (NumCachedTokenLexers == 0) {
Chris Lattner6b884502008-03-10 06:06:04 +0000147 CurTokenLexer = new TokenLexer(Toks, NumToks, DisableMacroExpansion,
148 OwnsTokens, *this);
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000149 } else {
150 CurTokenLexer = TokenLexerCache[--NumCachedTokenLexers];
Chris Lattner6b884502008-03-10 06:06:04 +0000151 CurTokenLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000152 }
153}
154
155/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
156/// the current file. This either returns the EOF token or pops a level off
157/// the include stack and keeps going.
158bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
159 assert(!CurTokenLexer &&
160 "Ending a file when currently in a macro!");
161
162 // See if this file had a controlling macro.
163 if (CurLexer) { // Not ending a macro, ignore it.
164 if (const IdentifierInfo *ControllingMacro =
165 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
166 // Okay, this has a controlling macro, remember in PerFileInfo.
167 if (const FileEntry *FE =
168 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
169 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
170 }
171 }
172
173 // If this is a #include'd file, pop it off the include stack and continue
174 // lexing the #includer file.
175 if (!IncludeMacroStack.empty()) {
176 // We're done with the #included file.
177 RemoveTopOfLexerStack();
178
179 // Notify the client, if desired, that we are in a new source file.
180 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattner0b9e7362008-09-26 21:18:42 +0000181 SrcMgr::Characteristic_t FileType =
182 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000183
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000184 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
185 PPCallbacks::ExitFile, FileType);
186 }
187
188 // Client should lex another token.
189 return false;
190 }
191
192 // If the file ends with a newline, form the EOF token on the newline itself,
193 // rather than "on the line following it", which doesn't exist. This makes
194 // diagnostics relating to the end of file include the last file that the user
195 // actually typed, which is goodness.
196 const char *EndPos = CurLexer->BufferEnd;
197 if (EndPos != CurLexer->BufferStart &&
198 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
199 --EndPos;
200
201 // Handle \n\r and \r\n:
202 if (EndPos != CurLexer->BufferStart &&
203 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
204 EndPos[-1] != EndPos[0])
205 --EndPos;
206 }
207
208 Result.startToken();
209 CurLexer->BufferPtr = EndPos;
Chris Lattner9e6293d2008-10-12 04:51:35 +0000210 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000211
212 // We're done with the #included file.
213 delete CurLexer;
214 CurLexer = 0;
215
216 // This is the end of the top-level file. If the diag::pp_macro_not_used
217 // diagnostic is enabled, look for macros that have not been used.
218 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
219 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
220 Macros.begin(), E = Macros.end(); I != E; ++I) {
221 if (!I->second->isUsed())
222 Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
223 }
224 }
225 return true;
226}
227
228/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
229/// hits the end of its token stream.
230bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
231 assert(CurTokenLexer && !CurLexer &&
232 "Ending a macro when currently in a #include file!");
233
234 // Delete or cache the now-dead macro expander.
235 if (NumCachedTokenLexers == TokenLexerCacheSize)
236 delete CurTokenLexer;
237 else
238 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer;
239
240 // Handle this like a #include file being popped off the stack.
241 CurTokenLexer = 0;
242 return HandleEndOfFile(Result, true);
243}
244
245/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
246/// lexer stack. This should only be used in situations where the current
247/// state of the top-of-stack lexer is unknown.
248void Preprocessor::RemoveTopOfLexerStack() {
249 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
250
251 if (CurTokenLexer) {
252 // Delete or cache the now-dead macro expander.
253 if (NumCachedTokenLexers == TokenLexerCacheSize)
254 delete CurTokenLexer;
255 else
256 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer;
257 } else {
258 delete CurLexer;
259 }
260 CurLexer = IncludeMacroStack.back().TheLexer;
261 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
262 CurTokenLexer = IncludeMacroStack.back().TheTokenLexer;
263 IncludeMacroStack.pop_back();
264}
265
266/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
267/// comment (/##/) in microsoft mode, this method handles updating the current
268/// state, returning the token on the next source line.
269void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
270 assert(CurTokenLexer && !CurLexer &&
271 "Pasted comment can only be formed from macro");
272
273 // We handle this by scanning for the closest real lexer, switching it to
274 // raw mode and preprocessor mode. This will cause it to return \n as an
275 // explicit EOM token.
276 Lexer *FoundLexer = 0;
277 bool LexerWasInPPMode = false;
278 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
279 IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
280 if (ISI.TheLexer == 0) continue; // Scan for a real lexer.
281
282 // Once we find a real lexer, mark it as raw mode (disabling macro
283 // expansions) and preprocessor mode (return EOM). We know that the lexer
284 // was *not* in raw mode before, because the macro that the comment came
285 // from was expanded. However, it could have already been in preprocessor
286 // mode (#if COMMENT) in which case we have to return it to that mode and
287 // return EOM.
288 FoundLexer = ISI.TheLexer;
289 FoundLexer->LexingRawMode = true;
290 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
291 FoundLexer->ParsingPreprocessorDirective = true;
292 break;
293 }
294
295 // Okay, we either found and switched over the lexer, or we didn't find a
296 // lexer. In either case, finish off the macro the comment came from, getting
297 // the next token.
298 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
299
300 // Discarding comments as long as we don't have EOF or EOM. This 'comments
301 // out' the rest of the line, including any tokens that came from other macros
302 // that were active, as in:
303 // #define submacro a COMMENT b
304 // submacro c
305 // which should lex to 'a' only: 'b' and 'c' should be removed.
306 while (Tok.isNot(tok::eom) && Tok.isNot(tok::eof))
307 Lex(Tok);
308
309 // If we got an eom token, then we successfully found the end of the line.
310 if (Tok.is(tok::eom)) {
311 assert(FoundLexer && "Can't get end of line without an active lexer");
312 // Restore the lexer back to normal mode instead of raw mode.
313 FoundLexer->LexingRawMode = false;
314
315 // If the lexer was already in preprocessor mode, just return the EOM token
316 // to finish the preprocessor line.
317 if (LexerWasInPPMode) return;
318
319 // Otherwise, switch out of PP mode and return the next lexed token.
320 FoundLexer->ParsingPreprocessorDirective = false;
321 return Lex(Tok);
322 }
323
324 // If we got an EOF token, then we reached the end of the token stream but
325 // didn't find an explicit \n. This can only happen if there was no lexer
326 // active (an active lexer would return EOM at EOF if there was no \n in
327 // preprocessor directive mode), so just return EOF as our token.
328 assert(!FoundLexer && "Lexer should return EOM before EOF in PP mode");
329}