blob: 87330983d658ff5b0bf9d1084bac9a8db825a75e [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
Ted Kremenek2df37b82008-11-19 01:54:47 +000028static inline bool IsNonPragmaNonMacroLexer(const Lexer* L,
29 const PreprocessorLexer* P) {
30 if (L)
31 return !L->isPragmaLexer();
32 else
33 return P != 0;
34}
35
Chris Lattner8c32b1a2008-03-09 04:10:46 +000036/// isInPrimaryFile - Return true if we're in the top-level file, not in a
Chris Lattner7d39d742008-03-09 04:49:35 +000037/// #include. This looks through macro expansions and active _Pragma lexers.
Chris Lattner8c32b1a2008-03-09 04:10:46 +000038bool Preprocessor::isInPrimaryFile() const {
Ted Kremenek2df37b82008-11-19 01:54:47 +000039 if (IsNonPragmaNonMacroLexer(CurLexer.get(), CurPPLexer))
Chris Lattner8c32b1a2008-03-09 04:10:46 +000040 return IncludeMacroStack.empty();
41
42 // If there are any stacked lexers, we're in a #include.
Ted Kremenek2df37b82008-11-19 01:54:47 +000043 assert(IsNonPragmaNonMacroLexer(IncludeMacroStack[0].TheLexer,
44 IncludeMacroStack[0].ThePPLexer) &&
Chris Lattner8c32b1a2008-03-09 04:10:46 +000045 "Top level include stack isn't our primary lexer?");
46 for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
Ted Kremenek2df37b82008-11-19 01:54:47 +000047 if (IsNonPragmaNonMacroLexer(IncludeMacroStack[i].TheLexer,
48 IncludeMacroStack[i].ThePPLexer))
Chris Lattner8c32b1a2008-03-09 04:10:46 +000049 return false;
50 return true;
51}
52
53/// getCurrentLexer - Return the current file lexer being lexed from. Note
54/// that this ignores any potentially active macro expansions and _Pragma
55/// expansions going on at the time.
56Lexer *Preprocessor::getCurrentFileLexer() const {
Ted Kremenekcaaa7df2008-11-13 17:11:24 +000057 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer.get();
Chris Lattner8c32b1a2008-03-09 04:10:46 +000058
59 // Look for a stacked lexer.
60 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
61 Lexer *L = IncludeMacroStack[i-1].TheLexer;
62 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
63 return L;
64 }
65 return 0;
66}
67
Chris Lattner6b884502008-03-10 06:06:04 +000068
69//===----------------------------------------------------------------------===//
70// Methods for Entering and Callbacks for leaving various contexts
71//===----------------------------------------------------------------------===//
Chris Lattner8c32b1a2008-03-09 04:10:46 +000072
73/// EnterSourceFile - Add a source file to the top of the include stack and
74/// start lexing tokens from it instead of the current buffer. Return true
75/// on failure.
76void Preprocessor::EnterSourceFile(unsigned FileID,
77 const DirectoryLookup *CurDir) {
78 assert(CurTokenLexer == 0 && "Cannot #include a file inside a macro!");
79 ++NumEnteredSourceFiles;
80
81 if (MaxIncludeStackDepth < IncludeMacroStack.size())
82 MaxIncludeStackDepth = IncludeMacroStack.size();
83
84 Lexer *TheLexer = new Lexer(SourceLocation::getFileLoc(FileID, 0), *this);
85 EnterSourceFileWithLexer(TheLexer, CurDir);
86}
Chris Lattner72181832008-09-26 20:12:23 +000087
Chris Lattner8c32b1a2008-03-09 04:10:46 +000088/// EnterSourceFile - Add a source file to the top of the include stack and
89/// start lexing tokens from it instead of the current buffer.
90void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
91 const DirectoryLookup *CurDir) {
92
93 // Add the current lexer to the include stack.
Ted Kremenek2df37b82008-11-19 01:54:47 +000094 if (CurLexer || CurTokenLexer)
Ted Kremeneked04c4c2008-11-13 16:51:03 +000095 PushIncludeMacroStack();
96
Ted Kremenekcaaa7df2008-11-13 17:11:24 +000097 CurLexer.reset(TheLexer);
Ted Kremenek9c1b7502008-11-18 00:12:49 +000098 CurPPLexer = TheLexer;
Chris Lattner8c32b1a2008-03-09 04:10:46 +000099 CurDirLookup = CurDir;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000100
101 // Notify the client, if desired, that we are in a new source file.
102 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattner9d728512008-10-27 01:19:25 +0000103 SrcMgr::CharacteristicKind FileType =
Chris Lattner0b9e7362008-09-26 21:18:42 +0000104 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000105
106 Callbacks->FileChanged(CurLexer->getFileLoc(),
107 PPCallbacks::EnterFile, FileType);
108 }
109}
110
111
112
113/// EnterMacro - Add a Macro to the top of the include stack and start lexing
114/// tokens from it instead of the current buffer.
115void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
Ted Kremeneked04c4c2008-11-13 16:51:03 +0000116 PushIncludeMacroStack();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000117 CurDirLookup = 0;
118
119 if (NumCachedTokenLexers == 0) {
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000120 CurTokenLexer.reset(new TokenLexer(Tok, Args, *this));
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000121 } else {
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000122 CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000123 CurTokenLexer->Init(Tok, Args);
124 }
125}
126
127/// EnterTokenStream - Add a "macro" context to the top of the include stack,
Chris Lattner6b884502008-03-10 06:06:04 +0000128/// which will cause the lexer to start returning the specified tokens.
129///
130/// If DisableMacroExpansion is true, tokens lexed from the token stream will
131/// not be subject to further macro expansion. Otherwise, these tokens will
132/// be re-macro-expanded when/if expansion is enabled.
133///
134/// If OwnsTokens is false, this method assumes that the specified stream of
135/// tokens has a permanent owner somewhere, so they do not need to be copied.
136/// If it is true, it assumes the array of tokens is allocated with new[] and
137/// must be freed.
138///
139void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
140 bool DisableMacroExpansion,
141 bool OwnsTokens) {
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000142 // Save our current state.
Ted Kremeneked04c4c2008-11-13 16:51:03 +0000143 PushIncludeMacroStack();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000144 CurDirLookup = 0;
145
146 // Create a macro expander to expand from the specified token stream.
147 if (NumCachedTokenLexers == 0) {
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000148 CurTokenLexer.reset(new TokenLexer(Toks, NumToks, DisableMacroExpansion,
149 OwnsTokens, *this));
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000150 } else {
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000151 CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
Chris Lattner6b884502008-03-10 06:06:04 +0000152 CurTokenLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000153 }
154}
155
156/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
157/// the current file. This either returns the EOF token or pops a level off
158/// the include stack and keeps going.
159bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
160 assert(!CurTokenLexer &&
161 "Ending a file when currently in a macro!");
162
163 // See if this file had a controlling macro.
164 if (CurLexer) { // Not ending a macro, ignore it.
165 if (const IdentifierInfo *ControllingMacro =
166 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
167 // Okay, this has a controlling macro, remember in PerFileInfo.
168 if (const FileEntry *FE =
169 SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))
170 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
171 }
172 }
173
174 // If this is a #include'd file, pop it off the include stack and continue
175 // lexing the #includer file.
176 if (!IncludeMacroStack.empty()) {
177 // We're done with the #included file.
178 RemoveTopOfLexerStack();
179
180 // Notify the client, if desired, that we are in a new source file.
181 if (Callbacks && !isEndOfMacro && CurLexer) {
Chris Lattner9d728512008-10-27 01:19:25 +0000182 SrcMgr::CharacteristicKind FileType =
Chris Lattner0b9e7362008-09-26 21:18:42 +0000183 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000184
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000185 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
186 PPCallbacks::ExitFile, FileType);
187 }
188
189 // Client should lex another token.
190 return false;
191 }
192
193 // If the file ends with a newline, form the EOF token on the newline itself,
194 // rather than "on the line following it", which doesn't exist. This makes
195 // diagnostics relating to the end of file include the last file that the user
196 // actually typed, which is goodness.
197 const char *EndPos = CurLexer->BufferEnd;
198 if (EndPos != CurLexer->BufferStart &&
199 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
200 --EndPos;
201
202 // Handle \n\r and \r\n:
203 if (EndPos != CurLexer->BufferStart &&
204 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
205 EndPos[-1] != EndPos[0])
206 --EndPos;
207 }
208
209 Result.startToken();
210 CurLexer->BufferPtr = EndPos;
Chris Lattner9e6293d2008-10-12 04:51:35 +0000211 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000212
213 // We're done with the #included file.
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000214 CurLexer.reset();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000215
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)
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000236 CurTokenLexer.reset();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000237 else
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000238 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000239
240 // Handle this like a #include file being popped off the stack.
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000241 return HandleEndOfFile(Result, true);
242}
243
244/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
245/// lexer stack. This should only be used in situations where the current
246/// state of the top-of-stack lexer is unknown.
247void Preprocessor::RemoveTopOfLexerStack() {
248 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
249
250 if (CurTokenLexer) {
251 // Delete or cache the now-dead macro expander.
252 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000253 CurTokenLexer.reset();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000254 else
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000255 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000256 } else {
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000257 CurLexer.reset();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000258 }
Ted Kremeneked04c4c2008-11-13 16:51:03 +0000259
260 PopIncludeMacroStack();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000261}
262
263/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
264/// comment (/##/) in microsoft mode, this method handles updating the current
265/// state, returning the token on the next source line.
266void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
267 assert(CurTokenLexer && !CurLexer &&
268 "Pasted comment can only be formed from macro");
269
270 // We handle this by scanning for the closest real lexer, switching it to
271 // raw mode and preprocessor mode. This will cause it to return \n as an
272 // explicit EOM token.
273 Lexer *FoundLexer = 0;
274 bool LexerWasInPPMode = false;
275 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
276 IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
277 if (ISI.TheLexer == 0) continue; // Scan for a real lexer.
278
279 // Once we find a real lexer, mark it as raw mode (disabling macro
280 // expansions) and preprocessor mode (return EOM). We know that the lexer
281 // was *not* in raw mode before, because the macro that the comment came
282 // from was expanded. However, it could have already been in preprocessor
283 // mode (#if COMMENT) in which case we have to return it to that mode and
284 // return EOM.
285 FoundLexer = ISI.TheLexer;
286 FoundLexer->LexingRawMode = true;
287 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
288 FoundLexer->ParsingPreprocessorDirective = true;
289 break;
290 }
291
292 // Okay, we either found and switched over the lexer, or we didn't find a
293 // lexer. In either case, finish off the macro the comment came from, getting
294 // the next token.
295 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
296
297 // Discarding comments as long as we don't have EOF or EOM. This 'comments
298 // out' the rest of the line, including any tokens that came from other macros
299 // that were active, as in:
300 // #define submacro a COMMENT b
301 // submacro c
302 // which should lex to 'a' only: 'b' and 'c' should be removed.
303 while (Tok.isNot(tok::eom) && Tok.isNot(tok::eof))
304 Lex(Tok);
305
306 // If we got an eom token, then we successfully found the end of the line.
307 if (Tok.is(tok::eom)) {
308 assert(FoundLexer && "Can't get end of line without an active lexer");
309 // Restore the lexer back to normal mode instead of raw mode.
310 FoundLexer->LexingRawMode = false;
311
312 // If the lexer was already in preprocessor mode, just return the EOM token
313 // to finish the preprocessor line.
314 if (LexerWasInPPMode) return;
315
316 // Otherwise, switch out of PP mode and return the next lexed token.
317 FoundLexer->ParsingPreprocessorDirective = false;
318 return Lex(Tok);
319 }
320
321 // If we got an EOF token, then we reached the end of the token stream but
322 // didn't find an explicit \n. This can only happen if there was no lexer
323 // active (an active lexer would return EOM at EOF if there was no \n in
324 // preprocessor directive mode), so just return EOF as our token.
325 assert(!FoundLexer && "Lexer should return EOM before EOF in PP mode");
326}