blob: 0ecca3a8cc9dadb42d1f1a3035b41b4809641d65 [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"
Ted Kremenek15ba2af2008-11-20 07:56:33 +000020#include "llvm/Support/MemoryBuffer.h"
21
Chris Lattner8c32b1a2008-03-09 04:10:46 +000022using namespace clang;
23
Ted Kremenek4b391082008-11-18 01:33:13 +000024PPCallbacks::~PPCallbacks() {}
Chris Lattner8c32b1a2008-03-09 04:10:46 +000025
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 {
Ted Kremenek81d24e12008-11-20 16:19:53 +000033 if (IsFileLexer())
Chris Lattner8c32b1a2008-03-09 04:10:46 +000034 return IncludeMacroStack.empty();
35
36 // If there are any stacked lexers, we're in a #include.
Ted Kremenek81d24e12008-11-20 16:19:53 +000037 assert(IsFileLexer(IncludeMacroStack[0]) &&
Chris Lattner8c32b1a2008-03-09 04:10:46 +000038 "Top level include stack isn't our primary lexer?");
39 for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
Ted Kremenek81d24e12008-11-20 16:19:53 +000040 if (IsFileLexer(IncludeMacroStack[i]))
Chris Lattner8c32b1a2008-03-09 04:10:46 +000041 return false;
42 return true;
43}
44
45/// getCurrentLexer - Return the current file lexer being lexed from. Note
46/// that this ignores any potentially active macro expansions and _Pragma
47/// expansions going on at the time.
Ted Kremenek68e48e42008-11-20 01:49:44 +000048PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
Ted Kremenek81d24e12008-11-20 16:19:53 +000049 if (IsFileLexer())
Ted Kremenek68e48e42008-11-20 01:49:44 +000050 return CurPPLexer;
Chris Lattner8c32b1a2008-03-09 04:10:46 +000051
52 // Look for a stacked lexer.
53 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Ted Kremenek68e48e42008-11-20 01:49:44 +000054 const IncludeStackInfo& ISI = IncludeMacroStack[i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +000055 if (IsFileLexer(ISI))
Ted Kremenek68e48e42008-11-20 01:49:44 +000056 return ISI.ThePPLexer;
Chris Lattner8c32b1a2008-03-09 04:10:46 +000057 }
58 return 0;
59}
60
Chris Lattner6b884502008-03-10 06:06:04 +000061
62//===----------------------------------------------------------------------===//
63// Methods for Entering and Callbacks for leaving various contexts
64//===----------------------------------------------------------------------===//
Chris Lattner8c32b1a2008-03-09 04:10:46 +000065
66/// EnterSourceFile - Add a source file to the top of the include stack and
67/// start lexing tokens from it instead of the current buffer. Return true
68/// on failure.
69void Preprocessor::EnterSourceFile(unsigned FileID,
70 const DirectoryLookup *CurDir) {
71 assert(CurTokenLexer == 0 && "Cannot #include a file inside a macro!");
72 ++NumEnteredSourceFiles;
73
74 if (MaxIncludeStackDepth < IncludeMacroStack.size())
75 MaxIncludeStackDepth = IncludeMacroStack.size();
76
Ted Kremenek6137dc92008-12-02 19:46:31 +000077 if (PTH) {
78 PTHLexer* PL =
79 PTH->CreateLexer(FileID, getSourceManager().getFileEntryForID(FileID));
80
81 if (PL) {
82 EnterSourceFileWithPTH(PL, CurDir);
83 return;
84 }
85 }
86
Chris Lattner8c32b1a2008-03-09 04:10:46 +000087 Lexer *TheLexer = new Lexer(SourceLocation::getFileLoc(FileID, 0), *this);
88 EnterSourceFileWithLexer(TheLexer, CurDir);
89}
Chris Lattner72181832008-09-26 20:12:23 +000090
Ted Kremenek6137dc92008-12-02 19:46:31 +000091/// EnterSourceFileWithLexer - Add a source file to the top of the include stack
92/// and start lexing tokens from it instead of the current buffer.
Chris Lattner8c32b1a2008-03-09 04:10:46 +000093void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
94 const DirectoryLookup *CurDir) {
95
96 // Add the current lexer to the include stack.
Ted Kremenek41938c82008-11-19 21:57:25 +000097 if (CurPPLexer || CurTokenLexer)
Ted Kremeneked04c4c2008-11-13 16:51:03 +000098 PushIncludeMacroStack();
99
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000100 CurLexer.reset(TheLexer);
Ted Kremenek9c1b7502008-11-18 00:12:49 +0000101 CurPPLexer = TheLexer;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000102 CurDirLookup = CurDir;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000103
104 // Notify the client, if desired, that we are in a new source file.
105 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattner9d728512008-10-27 01:19:25 +0000106 SrcMgr::CharacteristicKind FileType =
Chris Lattner0b9e7362008-09-26 21:18:42 +0000107 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000108
109 Callbacks->FileChanged(CurLexer->getFileLoc(),
110 PPCallbacks::EnterFile, FileType);
111 }
112}
113
Ted Kremenek6137dc92008-12-02 19:46:31 +0000114/// EnterSourceFileWithPTH - Add a source file to the top of the include stack
115/// and start getting tokens from it using the PTH cache.
116void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL,
117 const DirectoryLookup *CurDir) {
118
119 if (CurPPLexer || CurTokenLexer)
120 PushIncludeMacroStack();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000121
Ted Kremenek6137dc92008-12-02 19:46:31 +0000122 CurDirLookup = CurDir;
123 CurPTHLexer.reset(PL);
124 CurPPLexer = CurPTHLexer.get();
125
126 // Notify the client, if desired, that we are in a new source file.
127 if (Callbacks) {
128 unsigned FileID = CurPPLexer->getFileID();
129 SrcMgr::CharacteristicKind FileType =
130 SourceMgr.getFileCharacteristic(CurPPLexer->getFileID());
131 Callbacks->FileChanged(SourceLocation::getFileLoc(FileID, 0),
132 PPCallbacks::EnterFile, FileType);
133 }
134}
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000135
136/// EnterMacro - Add a Macro to the top of the include stack and start lexing
137/// tokens from it instead of the current buffer.
138void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
Ted Kremeneked04c4c2008-11-13 16:51:03 +0000139 PushIncludeMacroStack();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000140 CurDirLookup = 0;
141
142 if (NumCachedTokenLexers == 0) {
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000143 CurTokenLexer.reset(new TokenLexer(Tok, Args, *this));
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000144 } else {
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000145 CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000146 CurTokenLexer->Init(Tok, Args);
147 }
148}
149
150/// EnterTokenStream - Add a "macro" context to the top of the include stack,
Chris Lattner6b884502008-03-10 06:06:04 +0000151/// which will cause the lexer to start returning the specified tokens.
152///
153/// If DisableMacroExpansion is true, tokens lexed from the token stream will
154/// not be subject to further macro expansion. Otherwise, these tokens will
155/// be re-macro-expanded when/if expansion is enabled.
156///
157/// If OwnsTokens is false, this method assumes that the specified stream of
158/// tokens has a permanent owner somewhere, so they do not need to be copied.
159/// If it is true, it assumes the array of tokens is allocated with new[] and
160/// must be freed.
161///
162void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
163 bool DisableMacroExpansion,
164 bool OwnsTokens) {
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000165 // Save our current state.
Ted Kremeneked04c4c2008-11-13 16:51:03 +0000166 PushIncludeMacroStack();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000167 CurDirLookup = 0;
168
169 // Create a macro expander to expand from the specified token stream.
170 if (NumCachedTokenLexers == 0) {
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000171 CurTokenLexer.reset(new TokenLexer(Toks, NumToks, DisableMacroExpansion,
172 OwnsTokens, *this));
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000173 } else {
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000174 CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
Chris Lattner6b884502008-03-10 06:06:04 +0000175 CurTokenLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000176 }
177}
178
179/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
180/// the current file. This either returns the EOF token or pops a level off
181/// the include stack and keeps going.
182bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
183 assert(!CurTokenLexer &&
184 "Ending a file when currently in a macro!");
185
186 // See if this file had a controlling macro.
Ted Kremenek1a531572008-11-19 22:43:49 +0000187 if (CurPPLexer) { // Not ending a macro, ignore it.
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000188 if (const IdentifierInfo *ControllingMacro =
Ted Kremenek1a531572008-11-19 22:43:49 +0000189 CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000190 // Okay, this has a controlling macro, remember in PerFileInfo.
191 if (const FileEntry *FE =
Ted Kremenek1a531572008-11-19 22:43:49 +0000192 SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000193 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
194 }
195 }
196
197 // If this is a #include'd file, pop it off the include stack and continue
198 // lexing the #includer file.
199 if (!IncludeMacroStack.empty()) {
200 // We're done with the #included file.
201 RemoveTopOfLexerStack();
202
203 // Notify the client, if desired, that we are in a new source file.
Ted Kremenek1a531572008-11-19 22:43:49 +0000204 if (Callbacks && !isEndOfMacro && CurPPLexer) {
Chris Lattner9d728512008-10-27 01:19:25 +0000205 SrcMgr::CharacteristicKind FileType =
Ted Kremenek1a531572008-11-19 22:43:49 +0000206 SourceMgr.getFileCharacteristic(CurPPLexer->getFileID());
Ted Kremenekbc0f6bc2008-12-10 23:20:59 +0000207 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
208 PPCallbacks::ExitFile, FileType);
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000209 }
210
211 // Client should lex another token.
212 return false;
213 }
214
215 // If the file ends with a newline, form the EOF token on the newline itself,
216 // rather than "on the line following it", which doesn't exist. This makes
217 // diagnostics relating to the end of file include the last file that the user
218 // actually typed, which is goodness.
Ted Kremenek1a531572008-11-19 22:43:49 +0000219 if (CurLexer) {
220 const char *EndPos = CurLexer->BufferEnd;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000221 if (EndPos != CurLexer->BufferStart &&
Ted Kremenek1a531572008-11-19 22:43:49 +0000222 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000223 --EndPos;
Ted Kremenek1a531572008-11-19 22:43:49 +0000224
225 // Handle \n\r and \r\n:
226 if (EndPos != CurLexer->BufferStart &&
227 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
228 EndPos[-1] != EndPos[0])
229 --EndPos;
230 }
231
232 Result.startToken();
233 CurLexer->BufferPtr = EndPos;
234 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
235
236 // We're done with the #included file.
237 CurLexer.reset();
238 }
239 else {
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000240 CurPTHLexer->getEOF(Result);
Ted Kremenek1a531572008-11-19 22:43:49 +0000241 CurPTHLexer.reset();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000242 }
243
Ted Kremenek41938c82008-11-19 21:57:25 +0000244 CurPPLexer = 0;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000245
246 // This is the end of the top-level file. If the diag::pp_macro_not_used
247 // diagnostic is enabled, look for macros that have not been used.
248 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
249 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
250 Macros.begin(), E = Macros.end(); I != E; ++I) {
251 if (!I->second->isUsed())
252 Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
253 }
254 }
255 return true;
256}
257
258/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
259/// hits the end of its token stream.
260bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
Ted Kremenek1a531572008-11-19 22:43:49 +0000261 assert(CurTokenLexer && !CurPPLexer &&
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000262 "Ending a macro when currently in a #include file!");
263
264 // Delete or cache the now-dead macro expander.
265 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000266 CurTokenLexer.reset();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000267 else
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000268 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000269
270 // Handle this like a #include file being popped off the stack.
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000271 return HandleEndOfFile(Result, true);
272}
273
274/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
275/// lexer stack. This should only be used in situations where the current
276/// state of the top-of-stack lexer is unknown.
277void Preprocessor::RemoveTopOfLexerStack() {
278 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
279
280 if (CurTokenLexer) {
281 // Delete or cache the now-dead macro expander.
282 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000283 CurTokenLexer.reset();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000284 else
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000285 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
Ted Kremenek15ba2af2008-11-20 07:56:33 +0000286 }
Ted Kremeneked04c4c2008-11-13 16:51:03 +0000287
288 PopIncludeMacroStack();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000289}
290
291/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
292/// comment (/##/) in microsoft mode, this method handles updating the current
293/// state, returning the token on the next source line.
294void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
Ted Kremenek1a531572008-11-19 22:43:49 +0000295 assert(CurTokenLexer && !CurPPLexer &&
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000296 "Pasted comment can only be formed from macro");
297
298 // We handle this by scanning for the closest real lexer, switching it to
299 // raw mode and preprocessor mode. This will cause it to return \n as an
300 // explicit EOM token.
Ted Kremenek1a531572008-11-19 22:43:49 +0000301 PreprocessorLexer *FoundLexer = 0;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000302 bool LexerWasInPPMode = false;
303 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
304 IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
Ted Kremenek1a531572008-11-19 22:43:49 +0000305 if (ISI.ThePPLexer == 0) continue; // Scan for a real lexer.
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000306
307 // Once we find a real lexer, mark it as raw mode (disabling macro
308 // expansions) and preprocessor mode (return EOM). We know that the lexer
309 // was *not* in raw mode before, because the macro that the comment came
310 // from was expanded. However, it could have already been in preprocessor
311 // mode (#if COMMENT) in which case we have to return it to that mode and
312 // return EOM.
Ted Kremenek1a531572008-11-19 22:43:49 +0000313 FoundLexer = ISI.ThePPLexer;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000314 FoundLexer->LexingRawMode = true;
315 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
316 FoundLexer->ParsingPreprocessorDirective = true;
317 break;
318 }
319
320 // Okay, we either found and switched over the lexer, or we didn't find a
321 // lexer. In either case, finish off the macro the comment came from, getting
322 // the next token.
323 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
324
325 // Discarding comments as long as we don't have EOF or EOM. This 'comments
326 // out' the rest of the line, including any tokens that came from other macros
327 // that were active, as in:
328 // #define submacro a COMMENT b
329 // submacro c
330 // which should lex to 'a' only: 'b' and 'c' should be removed.
331 while (Tok.isNot(tok::eom) && Tok.isNot(tok::eof))
332 Lex(Tok);
333
334 // If we got an eom token, then we successfully found the end of the line.
335 if (Tok.is(tok::eom)) {
336 assert(FoundLexer && "Can't get end of line without an active lexer");
337 // Restore the lexer back to normal mode instead of raw mode.
338 FoundLexer->LexingRawMode = false;
339
340 // If the lexer was already in preprocessor mode, just return the EOM token
341 // to finish the preprocessor line.
342 if (LexerWasInPPMode) return;
343
344 // Otherwise, switch out of PP mode and return the next lexed token.
345 FoundLexer->ParsingPreprocessorDirective = false;
346 return Lex(Tok);
347 }
348
349 // If we got an EOF token, then we reached the end of the token stream but
350 // didn't find an explicit \n. This can only happen if there was no lexer
351 // active (an active lexer would return EOM at EOF if there was no \n in
352 // preprocessor directive mode), so just return EOF as our token.
353 assert(!FoundLexer && "Lexer should return EOM before EOF in PP mode");
354}