blob: c16abf43130633cebbf55fcf7db655b4dd7f6b72 [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
Ted Kremenek4b391082008-11-18 01:33:13 +000022PPCallbacks::~PPCallbacks() {}
Chris Lattner8c32b1a2008-03-09 04:10:46 +000023
24//===----------------------------------------------------------------------===//
Chris Lattner6b884502008-03-10 06:06:04 +000025// Miscellaneous Methods.
Chris Lattner8c32b1a2008-03-09 04:10:46 +000026//===----------------------------------------------------------------------===//
27
Chris Lattner8c32b1a2008-03-09 04:10:46 +000028/// isInPrimaryFile - Return true if we're in the top-level file, not in a
Chris Lattner7d39d742008-03-09 04:49:35 +000029/// #include. This looks through macro expansions and active _Pragma lexers.
Chris Lattner8c32b1a2008-03-09 04:10:46 +000030bool Preprocessor::isInPrimaryFile() const {
Ted Kremenek0a362642008-11-19 00:46:18 +000031 if (IsNonPragmaNonMacroLexer())
Chris Lattner8c32b1a2008-03-09 04:10:46 +000032 return IncludeMacroStack.empty();
33
34 // If there are any stacked lexers, we're in a #include.
Ted Kremenek0a362642008-11-19 00:46:18 +000035 assert(IsNonPragmaNonMacroLexer(IncludeMacroStack[0]) &&
Chris Lattner8c32b1a2008-03-09 04:10:46 +000036 "Top level include stack isn't our primary lexer?");
37 for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
Ted Kremenek0a362642008-11-19 00:46:18 +000038 if (IsNonPragmaNonMacroLexer(IncludeMacroStack[i]))
Chris Lattner8c32b1a2008-03-09 04:10:46 +000039 return false;
Ted Kremenek0a362642008-11-19 00:46:18 +000040
Chris Lattner8c32b1a2008-03-09 04:10:46 +000041 return true;
42}
43
44/// getCurrentLexer - Return the current file lexer being lexed from. Note
45/// that this ignores any potentially active macro expansions and _Pragma
46/// expansions going on at the time.
47Lexer *Preprocessor::getCurrentFileLexer() const {
Ted Kremenekcaaa7df2008-11-13 17:11:24 +000048 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer.get();
Chris Lattner8c32b1a2008-03-09 04:10:46 +000049
50 // Look for a stacked lexer.
51 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
52 Lexer *L = IncludeMacroStack[i-1].TheLexer;
53 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
54 return L;
55 }
56 return 0;
57}
58
Chris Lattner6b884502008-03-10 06:06:04 +000059
60//===----------------------------------------------------------------------===//
61// Methods for Entering and Callbacks for leaving various contexts
62//===----------------------------------------------------------------------===//
Chris Lattner8c32b1a2008-03-09 04:10:46 +000063
64/// EnterSourceFile - Add a source file to the top of the include stack and
65/// start lexing tokens from it instead of the current buffer. Return true
66/// on failure.
67void Preprocessor::EnterSourceFile(unsigned FileID,
68 const DirectoryLookup *CurDir) {
69 assert(CurTokenLexer == 0 && "Cannot #include a file inside a macro!");
70 ++NumEnteredSourceFiles;
71
72 if (MaxIncludeStackDepth < IncludeMacroStack.size())
73 MaxIncludeStackDepth = IncludeMacroStack.size();
74
75 Lexer *TheLexer = new Lexer(SourceLocation::getFileLoc(FileID, 0), *this);
76 EnterSourceFileWithLexer(TheLexer, CurDir);
77}
Chris Lattner72181832008-09-26 20:12:23 +000078
Chris Lattner8c32b1a2008-03-09 04:10:46 +000079/// EnterSourceFile - Add a source file to the top of the include stack and
80/// start lexing tokens from it instead of the current buffer.
81void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
82 const DirectoryLookup *CurDir) {
83
84 // Add the current lexer to the include stack.
Ted Kremenek0a362642008-11-19 00:46:18 +000085 if (CurPPLexer || CurTokenLexer)
Ted Kremeneked04c4c2008-11-13 16:51:03 +000086 PushIncludeMacroStack();
87
Ted Kremenekcaaa7df2008-11-13 17:11:24 +000088 CurLexer.reset(TheLexer);
Ted Kremenek9c1b7502008-11-18 00:12:49 +000089 CurPPLexer = TheLexer;
Chris Lattner8c32b1a2008-03-09 04:10:46 +000090 CurDirLookup = CurDir;
Chris Lattner8c32b1a2008-03-09 04:10:46 +000091
92 // Notify the client, if desired, that we are in a new source file.
93 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattner9d728512008-10-27 01:19:25 +000094 SrcMgr::CharacteristicKind FileType =
Chris Lattner0b9e7362008-09-26 21:18:42 +000095 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
Chris Lattner8c32b1a2008-03-09 04:10:46 +000096
97 Callbacks->FileChanged(CurLexer->getFileLoc(),
98 PPCallbacks::EnterFile, FileType);
99 }
100}
101
102
103
104/// EnterMacro - Add a Macro to the top of the include stack and start lexing
105/// tokens from it instead of the current buffer.
106void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
Ted Kremeneked04c4c2008-11-13 16:51:03 +0000107 PushIncludeMacroStack();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000108 CurDirLookup = 0;
109
110 if (NumCachedTokenLexers == 0) {
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000111 CurTokenLexer.reset(new TokenLexer(Tok, Args, *this));
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000112 } else {
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000113 CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000114 CurTokenLexer->Init(Tok, Args);
115 }
116}
117
118/// EnterTokenStream - Add a "macro" context to the top of the include stack,
Chris Lattner6b884502008-03-10 06:06:04 +0000119/// which will cause the lexer to start returning the specified tokens.
120///
121/// If DisableMacroExpansion is true, tokens lexed from the token stream will
122/// not be subject to further macro expansion. Otherwise, these tokens will
123/// be re-macro-expanded when/if expansion is enabled.
124///
125/// If OwnsTokens is false, this method assumes that the specified stream of
126/// tokens has a permanent owner somewhere, so they do not need to be copied.
127/// If it is true, it assumes the array of tokens is allocated with new[] and
128/// must be freed.
129///
130void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
131 bool DisableMacroExpansion,
132 bool OwnsTokens) {
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000133 // Save our current state.
Ted Kremeneked04c4c2008-11-13 16:51:03 +0000134 PushIncludeMacroStack();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000135 CurDirLookup = 0;
136
137 // Create a macro expander to expand from the specified token stream.
138 if (NumCachedTokenLexers == 0) {
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000139 CurTokenLexer.reset(new TokenLexer(Toks, NumToks, DisableMacroExpansion,
140 OwnsTokens, *this));
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000141 } else {
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000142 CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
Chris Lattner6b884502008-03-10 06:06:04 +0000143 CurTokenLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000144 }
145}
146
147/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
148/// the current file. This either returns the EOF token or pops a level off
149/// the include stack and keeps going.
150bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
151 assert(!CurTokenLexer &&
152 "Ending a file when currently in a macro!");
153
154 // See if this file had a controlling macro.
155 if (CurLexer) { // Not ending a macro, ignore it.
156 if (const IdentifierInfo *ControllingMacro =
157 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
158 // Okay, this has a controlling macro, remember in PerFileInfo.
159 if (const FileEntry *FE =
160 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
161 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
162 }
163 }
164
165 // If this is a #include'd file, pop it off the include stack and continue
166 // lexing the #includer file.
167 if (!IncludeMacroStack.empty()) {
168 // We're done with the #included file.
169 RemoveTopOfLexerStack();
170
171 // Notify the client, if desired, that we are in a new source file.
172 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattner9d728512008-10-27 01:19:25 +0000173 SrcMgr::CharacteristicKind FileType =
Chris Lattner0b9e7362008-09-26 21:18:42 +0000174 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000175
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000176 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
177 PPCallbacks::ExitFile, FileType);
178 }
179
180 // Client should lex another token.
181 return false;
182 }
183
184 // If the file ends with a newline, form the EOF token on the newline itself,
185 // rather than "on the line following it", which doesn't exist. This makes
186 // diagnostics relating to the end of file include the last file that the user
187 // actually typed, which is goodness.
188 const char *EndPos = CurLexer->BufferEnd;
189 if (EndPos != CurLexer->BufferStart &&
190 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
191 --EndPos;
192
193 // Handle \n\r and \r\n:
194 if (EndPos != CurLexer->BufferStart &&
195 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
196 EndPos[-1] != EndPos[0])
197 --EndPos;
198 }
199
200 Result.startToken();
201 CurLexer->BufferPtr = EndPos;
Chris Lattner9e6293d2008-10-12 04:51:35 +0000202 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000203
204 // We're done with the #included file.
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000205 CurLexer.reset();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000206
207 // This is the end of the top-level file. If the diag::pp_macro_not_used
208 // diagnostic is enabled, look for macros that have not been used.
209 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
210 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
211 Macros.begin(), E = Macros.end(); I != E; ++I) {
212 if (!I->second->isUsed())
213 Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
214 }
215 }
216 return true;
217}
218
219/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
220/// hits the end of its token stream.
221bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
222 assert(CurTokenLexer && !CurLexer &&
223 "Ending a macro when currently in a #include file!");
224
225 // Delete or cache the now-dead macro expander.
226 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000227 CurTokenLexer.reset();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000228 else
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000229 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000230
231 // Handle this like a #include file being popped off the stack.
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000232 return HandleEndOfFile(Result, true);
233}
234
235/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
236/// lexer stack. This should only be used in situations where the current
237/// state of the top-of-stack lexer is unknown.
238void Preprocessor::RemoveTopOfLexerStack() {
239 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
240
241 if (CurTokenLexer) {
242 // Delete or cache the now-dead macro expander.
243 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000244 CurTokenLexer.reset();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000245 else
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000246 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000247 } else {
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000248 CurLexer.reset();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000249 }
Ted Kremeneked04c4c2008-11-13 16:51:03 +0000250
251 PopIncludeMacroStack();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000252}
253
254/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
255/// comment (/##/) in microsoft mode, this method handles updating the current
256/// state, returning the token on the next source line.
257void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
258 assert(CurTokenLexer && !CurLexer &&
259 "Pasted comment can only be formed from macro");
260
261 // We handle this by scanning for the closest real lexer, switching it to
262 // raw mode and preprocessor mode. This will cause it to return \n as an
263 // explicit EOM token.
264 Lexer *FoundLexer = 0;
265 bool LexerWasInPPMode = false;
266 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
267 IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
268 if (ISI.TheLexer == 0) continue; // Scan for a real lexer.
269
270 // Once we find a real lexer, mark it as raw mode (disabling macro
271 // expansions) and preprocessor mode (return EOM). We know that the lexer
272 // was *not* in raw mode before, because the macro that the comment came
273 // from was expanded. However, it could have already been in preprocessor
274 // mode (#if COMMENT) in which case we have to return it to that mode and
275 // return EOM.
276 FoundLexer = ISI.TheLexer;
277 FoundLexer->LexingRawMode = true;
278 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
279 FoundLexer->ParsingPreprocessorDirective = true;
280 break;
281 }
282
283 // Okay, we either found and switched over the lexer, or we didn't find a
284 // lexer. In either case, finish off the macro the comment came from, getting
285 // the next token.
286 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
287
288 // Discarding comments as long as we don't have EOF or EOM. This 'comments
289 // out' the rest of the line, including any tokens that came from other macros
290 // that were active, as in:
291 // #define submacro a COMMENT b
292 // submacro c
293 // which should lex to 'a' only: 'b' and 'c' should be removed.
294 while (Tok.isNot(tok::eom) && Tok.isNot(tok::eof))
295 Lex(Tok);
296
297 // If we got an eom token, then we successfully found the end of the line.
298 if (Tok.is(tok::eom)) {
299 assert(FoundLexer && "Can't get end of line without an active lexer");
300 // Restore the lexer back to normal mode instead of raw mode.
301 FoundLexer->LexingRawMode = false;
302
303 // If the lexer was already in preprocessor mode, just return the EOM token
304 // to finish the preprocessor line.
305 if (LexerWasInPPMode) return;
306
307 // Otherwise, switch out of PP mode and return the next lexed token.
308 FoundLexer->ParsingPreprocessorDirective = false;
309 return Lex(Tok);
310 }
311
312 // If we got an EOF token, then we reached the end of the token stream but
313 // didn't find an explicit \n. This can only happen if there was no lexer
314 // active (an active lexer would return EOM at EOF if there was no \n in
315 // preprocessor directive mode), so just return EOF as our token.
316 assert(!FoundLexer && "Lexer should return EOM before EOF in PP mode");
317}