blob: ccaddf52ed5623ebd4da091ca3122fd84b4c9a6f [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;
210 CurLexer->FormTokenWithChars(Result, EndPos);
211 Result.setKind(tok::eof);
212
213 // We're done with the #included file.
214 delete CurLexer;
215 CurLexer = 0;
216
217 // This is the end of the top-level file. If the diag::pp_macro_not_used
218 // diagnostic is enabled, look for macros that have not been used.
219 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
220 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
221 Macros.begin(), E = Macros.end(); I != E; ++I) {
222 if (!I->second->isUsed())
223 Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
224 }
225 }
226 return true;
227}
228
229/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
230/// hits the end of its token stream.
231bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
232 assert(CurTokenLexer && !CurLexer &&
233 "Ending a macro when currently in a #include file!");
234
235 // Delete or cache the now-dead macro expander.
236 if (NumCachedTokenLexers == TokenLexerCacheSize)
237 delete CurTokenLexer;
238 else
239 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer;
240
241 // Handle this like a #include file being popped off the stack.
242 CurTokenLexer = 0;
243 return HandleEndOfFile(Result, true);
244}
245
246/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
247/// lexer stack. This should only be used in situations where the current
248/// state of the top-of-stack lexer is unknown.
249void Preprocessor::RemoveTopOfLexerStack() {
250 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
251
252 if (CurTokenLexer) {
253 // Delete or cache the now-dead macro expander.
254 if (NumCachedTokenLexers == TokenLexerCacheSize)
255 delete CurTokenLexer;
256 else
257 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer;
258 } else {
259 delete CurLexer;
260 }
261 CurLexer = IncludeMacroStack.back().TheLexer;
262 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
263 CurTokenLexer = IncludeMacroStack.back().TheTokenLexer;
264 IncludeMacroStack.pop_back();
265}
266
267/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
268/// comment (/##/) in microsoft mode, this method handles updating the current
269/// state, returning the token on the next source line.
270void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
271 assert(CurTokenLexer && !CurLexer &&
272 "Pasted comment can only be formed from macro");
273
274 // We handle this by scanning for the closest real lexer, switching it to
275 // raw mode and preprocessor mode. This will cause it to return \n as an
276 // explicit EOM token.
277 Lexer *FoundLexer = 0;
278 bool LexerWasInPPMode = false;
279 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
280 IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
281 if (ISI.TheLexer == 0) continue; // Scan for a real lexer.
282
283 // Once we find a real lexer, mark it as raw mode (disabling macro
284 // expansions) and preprocessor mode (return EOM). We know that the lexer
285 // was *not* in raw mode before, because the macro that the comment came
286 // from was expanded. However, it could have already been in preprocessor
287 // mode (#if COMMENT) in which case we have to return it to that mode and
288 // return EOM.
289 FoundLexer = ISI.TheLexer;
290 FoundLexer->LexingRawMode = true;
291 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
292 FoundLexer->ParsingPreprocessorDirective = true;
293 break;
294 }
295
296 // Okay, we either found and switched over the lexer, or we didn't find a
297 // lexer. In either case, finish off the macro the comment came from, getting
298 // the next token.
299 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
300
301 // Discarding comments as long as we don't have EOF or EOM. This 'comments
302 // out' the rest of the line, including any tokens that came from other macros
303 // that were active, as in:
304 // #define submacro a COMMENT b
305 // submacro c
306 // which should lex to 'a' only: 'b' and 'c' should be removed.
307 while (Tok.isNot(tok::eom) && Tok.isNot(tok::eof))
308 Lex(Tok);
309
310 // If we got an eom token, then we successfully found the end of the line.
311 if (Tok.is(tok::eom)) {
312 assert(FoundLexer && "Can't get end of line without an active lexer");
313 // Restore the lexer back to normal mode instead of raw mode.
314 FoundLexer->LexingRawMode = false;
315
316 // If the lexer was already in preprocessor mode, just return the EOM token
317 // to finish the preprocessor line.
318 if (LexerWasInPPMode) return;
319
320 // Otherwise, switch out of PP mode and return the next lexed token.
321 FoundLexer->ParsingPreprocessorDirective = false;
322 return Lex(Tok);
323 }
324
325 // If we got an EOF token, then we reached the end of the token stream but
326 // didn't find an explicit \n. This can only happen if there was no lexer
327 // active (an active lexer would return EOM at EOF if there was no \n in
328 // preprocessor directive mode), so just return EOF as our token.
329 assert(!FoundLexer && "Lexer should return EOM before EOF in PP mode");
330}