blob: 7c1a08999826507c9d2e4dc0978abc6488245532 [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 Lattner500d3292009-01-29 05:15:15 +000018#include "clang/Lex/LexDiagnostic.h"
Chris Lattner8c32b1a2008-03-09 04:10:46 +000019#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.
Chris Lattner2b2453a2009-01-17 06:22:33 +000069void Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir) {
Chris Lattner8c32b1a2008-03-09 04:10:46 +000070 assert(CurTokenLexer == 0 && "Cannot #include a file inside a macro!");
71 ++NumEnteredSourceFiles;
72
73 if (MaxIncludeStackDepth < IncludeMacroStack.size())
74 MaxIncludeStackDepth = IncludeMacroStack.size();
75
Ted Kremenek6137dc92008-12-02 19:46:31 +000076 if (PTH) {
Chris Lattnerf056d922009-01-17 08:06:50 +000077 if (PTHLexer *PL = PTH->CreateLexer(FID))
Chris Lattner88d3ac12009-01-17 08:03:42 +000078 return EnterSourceFileWithPTH(PL, CurDir);
Ted Kremenek6137dc92008-12-02 19:46:31 +000079 }
Chris Lattner88d3ac12009-01-17 08:03:42 +000080 EnterSourceFileWithLexer(new Lexer(FID, *this), CurDir);
Chris Lattner8c32b1a2008-03-09 04:10:46 +000081}
Chris Lattner72181832008-09-26 20:12:23 +000082
Ted Kremenek6137dc92008-12-02 19:46:31 +000083/// EnterSourceFileWithLexer - Add a source file to the top of the include stack
84/// and start lexing tokens from it instead of the current buffer.
Chris Lattner8c32b1a2008-03-09 04:10:46 +000085void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
86 const DirectoryLookup *CurDir) {
87
88 // Add the current lexer to the include stack.
Ted Kremenek41938c82008-11-19 21:57:25 +000089 if (CurPPLexer || CurTokenLexer)
Ted Kremeneked04c4c2008-11-13 16:51:03 +000090 PushIncludeMacroStack();
91
Ted Kremenekcaaa7df2008-11-13 17:11:24 +000092 CurLexer.reset(TheLexer);
Ted Kremenek9c1b7502008-11-18 00:12:49 +000093 CurPPLexer = TheLexer;
Chris Lattner8c32b1a2008-03-09 04:10:46 +000094 CurDirLookup = CurDir;
Chris Lattner8c32b1a2008-03-09 04:10:46 +000095
96 // Notify the client, if desired, that we are in a new source file.
97 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattner9d728512008-10-27 01:19:25 +000098 SrcMgr::CharacteristicKind FileType =
Chris Lattner0b9e7362008-09-26 21:18:42 +000099 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000100
101 Callbacks->FileChanged(CurLexer->getFileLoc(),
102 PPCallbacks::EnterFile, FileType);
103 }
104}
105
Ted Kremenek6137dc92008-12-02 19:46:31 +0000106/// EnterSourceFileWithPTH - Add a source file to the top of the include stack
107/// and start getting tokens from it using the PTH cache.
108void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL,
109 const DirectoryLookup *CurDir) {
110
111 if (CurPPLexer || CurTokenLexer)
112 PushIncludeMacroStack();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000113
Ted Kremenek6137dc92008-12-02 19:46:31 +0000114 CurDirLookup = CurDir;
115 CurPTHLexer.reset(PL);
116 CurPPLexer = CurPTHLexer.get();
117
118 // Notify the client, if desired, that we are in a new source file.
119 if (Callbacks) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000120 FileID FID = CurPPLexer->getFileID();
Chris Lattner8c61b532009-01-19 08:01:53 +0000121 SourceLocation EnterLoc = SourceMgr.getLocForStartOfFile(FID);
122 SrcMgr::CharacteristicKind FileType =
123 SourceMgr.getFileCharacteristic(EnterLoc);
124 Callbacks->FileChanged(EnterLoc, PPCallbacks::EnterFile, FileType);
Ted Kremenek6137dc92008-12-02 19:46:31 +0000125 }
126}
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000127
128/// EnterMacro - Add a Macro to the top of the include stack and start lexing
129/// tokens from it instead of the current buffer.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000130void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
131 MacroArgs *Args) {
Ted Kremeneked04c4c2008-11-13 16:51:03 +0000132 PushIncludeMacroStack();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000133 CurDirLookup = 0;
134
135 if (NumCachedTokenLexers == 0) {
Chris Lattnere7fb4842009-02-15 20:52:18 +0000136 CurTokenLexer.reset(new TokenLexer(Tok, ILEnd, Args, *this));
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000137 } else {
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000138 CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
Chris Lattnere7fb4842009-02-15 20:52:18 +0000139 CurTokenLexer->Init(Tok, ILEnd, Args);
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000140 }
141}
142
143/// EnterTokenStream - Add a "macro" context to the top of the include stack,
Chris Lattner6b884502008-03-10 06:06:04 +0000144/// which will cause the lexer to start returning the specified tokens.
145///
146/// If DisableMacroExpansion is true, tokens lexed from the token stream will
147/// not be subject to further macro expansion. Otherwise, these tokens will
148/// be re-macro-expanded when/if expansion is enabled.
149///
150/// If OwnsTokens is false, this method assumes that the specified stream of
151/// tokens has a permanent owner somewhere, so they do not need to be copied.
152/// If it is true, it assumes the array of tokens is allocated with new[] and
153/// must be freed.
154///
155void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
156 bool DisableMacroExpansion,
157 bool OwnsTokens) {
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000158 // Save our current state.
Ted Kremeneked04c4c2008-11-13 16:51:03 +0000159 PushIncludeMacroStack();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000160 CurDirLookup = 0;
161
162 // Create a macro expander to expand from the specified token stream.
163 if (NumCachedTokenLexers == 0) {
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000164 CurTokenLexer.reset(new TokenLexer(Toks, NumToks, DisableMacroExpansion,
165 OwnsTokens, *this));
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000166 } else {
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000167 CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
Chris Lattner6b884502008-03-10 06:06:04 +0000168 CurTokenLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000169 }
170}
171
172/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
173/// the current file. This either returns the EOF token or pops a level off
174/// the include stack and keeps going.
175bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
176 assert(!CurTokenLexer &&
177 "Ending a file when currently in a macro!");
178
179 // See if this file had a controlling macro.
Ted Kremenek1a531572008-11-19 22:43:49 +0000180 if (CurPPLexer) { // Not ending a macro, ignore it.
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000181 if (const IdentifierInfo *ControllingMacro =
Ted Kremenek1a531572008-11-19 22:43:49 +0000182 CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000183 // Okay, this has a controlling macro, remember in PerFileInfo.
184 if (const FileEntry *FE =
Ted Kremenek1a531572008-11-19 22:43:49 +0000185 SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000186 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
187 }
188 }
189
190 // If this is a #include'd file, pop it off the include stack and continue
191 // lexing the #includer file.
192 if (!IncludeMacroStack.empty()) {
193 // We're done with the #included file.
194 RemoveTopOfLexerStack();
195
196 // Notify the client, if desired, that we are in a new source file.
Ted Kremenek1a531572008-11-19 22:43:49 +0000197 if (Callbacks && !isEndOfMacro && CurPPLexer) {
Chris Lattner9d728512008-10-27 01:19:25 +0000198 SrcMgr::CharacteristicKind FileType =
Chris Lattner8c61b532009-01-19 08:01:53 +0000199 SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
200 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
201 PPCallbacks::ExitFile, FileType);
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000202 }
203
204 // Client should lex another token.
205 return false;
206 }
207
208 // If the file ends with a newline, form the EOF token on the newline itself,
209 // rather than "on the line following it", which doesn't exist. This makes
210 // diagnostics relating to the end of file include the last file that the user
211 // actually typed, which is goodness.
Ted Kremenek1a531572008-11-19 22:43:49 +0000212 if (CurLexer) {
213 const char *EndPos = CurLexer->BufferEnd;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000214 if (EndPos != CurLexer->BufferStart &&
Ted Kremenek1a531572008-11-19 22:43:49 +0000215 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000216 --EndPos;
Ted Kremenek1a531572008-11-19 22:43:49 +0000217
218 // Handle \n\r and \r\n:
219 if (EndPos != CurLexer->BufferStart &&
220 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
221 EndPos[-1] != EndPos[0])
222 --EndPos;
223 }
224
225 Result.startToken();
226 CurLexer->BufferPtr = EndPos;
227 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
228
229 // We're done with the #included file.
230 CurLexer.reset();
Chris Lattner67116082009-02-13 23:06:48 +0000231 } else {
232 assert(CurPTHLexer && "Got EOF but no current lexer set!");
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000233 CurPTHLexer->getEOF(Result);
Ted Kremenek1a531572008-11-19 22:43:49 +0000234 CurPTHLexer.reset();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000235 }
236
Ted Kremenek41938c82008-11-19 21:57:25 +0000237 CurPPLexer = 0;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000238
239 // This is the end of the top-level file. If the diag::pp_macro_not_used
240 // diagnostic is enabled, look for macros that have not been used.
Chris Lattner7f549df2009-03-13 21:17:23 +0000241 if (getDiagnostics().getDiagnosticLevel(diag::pp_macro_not_used) !=
242 Diagnostic::Ignored) {
Chris Lattner09b5c1d2009-02-06 06:26:42 +0000243 for (macro_iterator I = macro_begin(), E = macro_end(); I != E; ++I)
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000244 if (!I->second->isUsed())
245 Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000246 }
247 return true;
248}
249
250/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
251/// hits the end of its token stream.
252bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
Ted Kremenek1a531572008-11-19 22:43:49 +0000253 assert(CurTokenLexer && !CurPPLexer &&
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000254 "Ending a macro when currently in a #include file!");
255
256 // Delete or cache the now-dead macro expander.
257 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000258 CurTokenLexer.reset();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000259 else
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000260 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000261
262 // Handle this like a #include file being popped off the stack.
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000263 return HandleEndOfFile(Result, true);
264}
265
266/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
267/// lexer stack. This should only be used in situations where the current
268/// state of the top-of-stack lexer is unknown.
269void Preprocessor::RemoveTopOfLexerStack() {
270 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
271
272 if (CurTokenLexer) {
273 // Delete or cache the now-dead macro expander.
274 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000275 CurTokenLexer.reset();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000276 else
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000277 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
Ted Kremenek15ba2af2008-11-20 07:56:33 +0000278 }
Ted Kremeneked04c4c2008-11-13 16:51:03 +0000279
280 PopIncludeMacroStack();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000281}
282
283/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
284/// comment (/##/) in microsoft mode, this method handles updating the current
285/// state, returning the token on the next source line.
286void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
Ted Kremenek1a531572008-11-19 22:43:49 +0000287 assert(CurTokenLexer && !CurPPLexer &&
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000288 "Pasted comment can only be formed from macro");
289
290 // We handle this by scanning for the closest real lexer, switching it to
291 // raw mode and preprocessor mode. This will cause it to return \n as an
292 // explicit EOM token.
Ted Kremenek1a531572008-11-19 22:43:49 +0000293 PreprocessorLexer *FoundLexer = 0;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000294 bool LexerWasInPPMode = false;
295 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
296 IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
Ted Kremenek1a531572008-11-19 22:43:49 +0000297 if (ISI.ThePPLexer == 0) continue; // Scan for a real lexer.
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000298
299 // Once we find a real lexer, mark it as raw mode (disabling macro
300 // expansions) and preprocessor mode (return EOM). We know that the lexer
301 // was *not* in raw mode before, because the macro that the comment came
302 // from was expanded. However, it could have already been in preprocessor
303 // mode (#if COMMENT) in which case we have to return it to that mode and
304 // return EOM.
Ted Kremenek1a531572008-11-19 22:43:49 +0000305 FoundLexer = ISI.ThePPLexer;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000306 FoundLexer->LexingRawMode = true;
307 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
308 FoundLexer->ParsingPreprocessorDirective = true;
309 break;
310 }
311
312 // Okay, we either found and switched over the lexer, or we didn't find a
313 // lexer. In either case, finish off the macro the comment came from, getting
314 // the next token.
315 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
316
317 // Discarding comments as long as we don't have EOF or EOM. This 'comments
318 // out' the rest of the line, including any tokens that came from other macros
319 // that were active, as in:
320 // #define submacro a COMMENT b
321 // submacro c
322 // which should lex to 'a' only: 'b' and 'c' should be removed.
323 while (Tok.isNot(tok::eom) && Tok.isNot(tok::eof))
324 Lex(Tok);
325
326 // If we got an eom token, then we successfully found the end of the line.
327 if (Tok.is(tok::eom)) {
328 assert(FoundLexer && "Can't get end of line without an active lexer");
329 // Restore the lexer back to normal mode instead of raw mode.
330 FoundLexer->LexingRawMode = false;
331
332 // If the lexer was already in preprocessor mode, just return the EOM token
333 // to finish the preprocessor line.
334 if (LexerWasInPPMode) return;
335
336 // Otherwise, switch out of PP mode and return the next lexed token.
337 FoundLexer->ParsingPreprocessorDirective = false;
338 return Lex(Tok);
339 }
340
341 // If we got an EOF token, then we reached the end of the token stream but
342 // didn't find an explicit \n. This can only happen if there was no lexer
343 // active (an active lexer would return EOM at EOF if there was no \n in
344 // preprocessor directive mode), so just return EOF as our token.
345 assert(!FoundLexer && "Lexer should return EOM before EOF in PP mode");
346}