blob: 0d5147c5b265110b0ed1678623f0558229c7d128 [file] [log] [blame]
Chris Lattner87414e82008-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 Lattner87414e82008-03-09 04:10:46 +000018#include "clang/Basic/Diagnostic.h"
19#include "clang/Basic/SourceManager.h"
20using namespace clang;
21
Ted Kremenek6f531ab2008-11-18 01:33:13 +000022PPCallbacks::~PPCallbacks() {}
Chris Lattner87414e82008-03-09 04:10:46 +000023
24//===----------------------------------------------------------------------===//
Chris Lattner80712392008-03-10 06:06:04 +000025// Miscellaneous Methods.
Chris Lattner87414e82008-03-09 04:10:46 +000026//===----------------------------------------------------------------------===//
27
Chris Lattner87414e82008-03-09 04:10:46 +000028/// isInPrimaryFile - Return true if we're in the top-level file, not in a
Chris Lattnerb99dc1d2008-03-09 04:49:35 +000029/// #include. This looks through macro expansions and active _Pragma lexers.
Chris Lattner87414e82008-03-09 04:10:46 +000030bool Preprocessor::isInPrimaryFile() const {
Ted Kremenek56758d22008-11-19 21:57:25 +000031 if (IsNonPragmaNonMacroLexer())
Chris Lattner87414e82008-03-09 04:10:46 +000032 return IncludeMacroStack.empty();
33
34 // If there are any stacked lexers, we're in a #include.
Ted Kremenek56758d22008-11-19 21:57:25 +000035 assert(IsNonPragmaNonMacroLexer(IncludeMacroStack[0]) &&
Chris Lattner87414e82008-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 Kremenek56758d22008-11-19 21:57:25 +000038 if (IsNonPragmaNonMacroLexer(IncludeMacroStack[i]))
Chris Lattner87414e82008-03-09 04:10:46 +000039 return false;
40 return true;
41}
42
43/// getCurrentLexer - Return the current file lexer being lexed from. Note
44/// that this ignores any potentially active macro expansions and _Pragma
45/// expansions going on at the time.
46Lexer *Preprocessor::getCurrentFileLexer() const {
Ted Kremenekb0eef362008-11-13 17:11:24 +000047 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer.get();
Chris Lattner87414e82008-03-09 04:10:46 +000048
49 // Look for a stacked lexer.
50 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
51 Lexer *L = IncludeMacroStack[i-1].TheLexer;
52 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
53 return L;
54 }
55 return 0;
56}
57
Chris Lattner80712392008-03-10 06:06:04 +000058
59//===----------------------------------------------------------------------===//
60// Methods for Entering and Callbacks for leaving various contexts
61//===----------------------------------------------------------------------===//
Chris Lattner87414e82008-03-09 04:10:46 +000062
63/// EnterSourceFile - Add a source file to the top of the include stack and
64/// start lexing tokens from it instead of the current buffer. Return true
65/// on failure.
66void Preprocessor::EnterSourceFile(unsigned FileID,
67 const DirectoryLookup *CurDir) {
68 assert(CurTokenLexer == 0 && "Cannot #include a file inside a macro!");
69 ++NumEnteredSourceFiles;
70
71 if (MaxIncludeStackDepth < IncludeMacroStack.size())
72 MaxIncludeStackDepth = IncludeMacroStack.size();
73
74 Lexer *TheLexer = new Lexer(SourceLocation::getFileLoc(FileID, 0), *this);
75 EnterSourceFileWithLexer(TheLexer, CurDir);
76}
Chris Lattner7257ce22008-09-26 20:12:23 +000077
Chris Lattner87414e82008-03-09 04:10:46 +000078/// EnterSourceFile - Add a source file to the top of the include stack and
79/// start lexing tokens from it instead of the current buffer.
80void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
81 const DirectoryLookup *CurDir) {
82
83 // Add the current lexer to the include stack.
Ted Kremenek56758d22008-11-19 21:57:25 +000084 if (CurPPLexer || CurTokenLexer)
Ted Kremenek383ad382008-11-13 16:51:03 +000085 PushIncludeMacroStack();
86
Ted Kremenekb0eef362008-11-13 17:11:24 +000087 CurLexer.reset(TheLexer);
Ted Kremenek306be5f2008-11-18 00:12:49 +000088 CurPPLexer = TheLexer;
Chris Lattner87414e82008-03-09 04:10:46 +000089 CurDirLookup = CurDir;
Chris Lattner87414e82008-03-09 04:10:46 +000090
91 // Notify the client, if desired, that we are in a new source file.
92 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattner7a4864e2008-10-27 01:19:25 +000093 SrcMgr::CharacteristicKind FileType =
Chris Lattner6f044062008-09-26 21:18:42 +000094 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
Chris Lattner87414e82008-03-09 04:10:46 +000095
96 Callbacks->FileChanged(CurLexer->getFileLoc(),
97 PPCallbacks::EnterFile, FileType);
98 }
99}
100
101
102
103/// EnterMacro - Add a Macro to the top of the include stack and start lexing
104/// tokens from it instead of the current buffer.
105void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
Ted Kremenek383ad382008-11-13 16:51:03 +0000106 PushIncludeMacroStack();
Chris Lattner87414e82008-03-09 04:10:46 +0000107 CurDirLookup = 0;
108
109 if (NumCachedTokenLexers == 0) {
Ted Kremenekb0eef362008-11-13 17:11:24 +0000110 CurTokenLexer.reset(new TokenLexer(Tok, Args, *this));
Chris Lattner87414e82008-03-09 04:10:46 +0000111 } else {
Ted Kremenekb0eef362008-11-13 17:11:24 +0000112 CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
Chris Lattner87414e82008-03-09 04:10:46 +0000113 CurTokenLexer->Init(Tok, Args);
114 }
115}
116
117/// EnterTokenStream - Add a "macro" context to the top of the include stack,
Chris Lattner80712392008-03-10 06:06:04 +0000118/// which will cause the lexer to start returning the specified tokens.
119///
120/// If DisableMacroExpansion is true, tokens lexed from the token stream will
121/// not be subject to further macro expansion. Otherwise, these tokens will
122/// be re-macro-expanded when/if expansion is enabled.
123///
124/// If OwnsTokens is false, this method assumes that the specified stream of
125/// tokens has a permanent owner somewhere, so they do not need to be copied.
126/// If it is true, it assumes the array of tokens is allocated with new[] and
127/// must be freed.
128///
129void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
130 bool DisableMacroExpansion,
131 bool OwnsTokens) {
Chris Lattner87414e82008-03-09 04:10:46 +0000132 // Save our current state.
Ted Kremenek383ad382008-11-13 16:51:03 +0000133 PushIncludeMacroStack();
Chris Lattner87414e82008-03-09 04:10:46 +0000134 CurDirLookup = 0;
135
136 // Create a macro expander to expand from the specified token stream.
137 if (NumCachedTokenLexers == 0) {
Ted Kremenekb0eef362008-11-13 17:11:24 +0000138 CurTokenLexer.reset(new TokenLexer(Toks, NumToks, DisableMacroExpansion,
139 OwnsTokens, *this));
Chris Lattner87414e82008-03-09 04:10:46 +0000140 } else {
Ted Kremenekb0eef362008-11-13 17:11:24 +0000141 CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
Chris Lattner80712392008-03-10 06:06:04 +0000142 CurTokenLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
Chris Lattner87414e82008-03-09 04:10:46 +0000143 }
144}
145
146/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
147/// the current file. This either returns the EOF token or pops a level off
148/// the include stack and keeps going.
149bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
150 assert(!CurTokenLexer &&
151 "Ending a file when currently in a macro!");
152
153 // See if this file had a controlling macro.
Ted Kremenek3acf6702008-11-19 22:43:49 +0000154 if (CurPPLexer) { // Not ending a macro, ignore it.
Chris Lattner87414e82008-03-09 04:10:46 +0000155 if (const IdentifierInfo *ControllingMacro =
Ted Kremenek3acf6702008-11-19 22:43:49 +0000156 CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner87414e82008-03-09 04:10:46 +0000157 // Okay, this has a controlling macro, remember in PerFileInfo.
158 if (const FileEntry *FE =
Ted Kremenek3acf6702008-11-19 22:43:49 +0000159 SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))
Chris Lattner87414e82008-03-09 04:10:46 +0000160 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
161 }
162 }
163
164 // If this is a #include'd file, pop it off the include stack and continue
165 // lexing the #includer file.
166 if (!IncludeMacroStack.empty()) {
167 // We're done with the #included file.
168 RemoveTopOfLexerStack();
169
170 // Notify the client, if desired, that we are in a new source file.
Ted Kremenek3acf6702008-11-19 22:43:49 +0000171 if (Callbacks && !isEndOfMacro && CurPPLexer) {
Chris Lattner7a4864e2008-10-27 01:19:25 +0000172 SrcMgr::CharacteristicKind FileType =
Ted Kremenek3acf6702008-11-19 22:43:49 +0000173 SourceMgr.getFileCharacteristic(CurPPLexer->getFileID());
Chris Lattner87414e82008-03-09 04:10:46 +0000174
Ted Kremenek3acf6702008-11-19 22:43:49 +0000175 if (CurLexer)
176 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
177 PPCallbacks::ExitFile, FileType);
178 // FIXME: Add callback support for PTHLexer.
Chris Lattner87414e82008-03-09 04:10:46 +0000179 }
180
181 // Client should lex another token.
182 return false;
183 }
184
185 // If the file ends with a newline, form the EOF token on the newline itself,
186 // rather than "on the line following it", which doesn't exist. This makes
187 // diagnostics relating to the end of file include the last file that the user
188 // actually typed, which is goodness.
Ted Kremenek3acf6702008-11-19 22:43:49 +0000189 if (CurLexer) {
190 const char *EndPos = CurLexer->BufferEnd;
Chris Lattner87414e82008-03-09 04:10:46 +0000191 if (EndPos != CurLexer->BufferStart &&
Ted Kremenek3acf6702008-11-19 22:43:49 +0000192 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
Chris Lattner87414e82008-03-09 04:10:46 +0000193 --EndPos;
Ted Kremenek3acf6702008-11-19 22:43:49 +0000194
195 // Handle \n\r and \r\n:
196 if (EndPos != CurLexer->BufferStart &&
197 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
198 EndPos[-1] != EndPos[0])
199 --EndPos;
200 }
201
202 Result.startToken();
203 CurLexer->BufferPtr = EndPos;
204 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
205
206 // We're done with the #included file.
207 CurLexer.reset();
208 }
209 else {
210 CurPTHLexer->setEOF(Result);
211 CurPTHLexer.reset();
Chris Lattner87414e82008-03-09 04:10:46 +0000212 }
213
Ted Kremenek56758d22008-11-19 21:57:25 +0000214 CurPPLexer = 0;
Chris Lattner87414e82008-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) {
Ted Kremenek3acf6702008-11-19 22:43:49 +0000231 assert(CurTokenLexer && !CurPPLexer &&
Chris Lattner87414e82008-03-09 04:10:46 +0000232 "Ending a macro when currently in a #include file!");
233
234 // Delete or cache the now-dead macro expander.
235 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremenekb0eef362008-11-13 17:11:24 +0000236 CurTokenLexer.reset();
Chris Lattner87414e82008-03-09 04:10:46 +0000237 else
Ted Kremenekb0eef362008-11-13 17:11:24 +0000238 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
Chris Lattner87414e82008-03-09 04:10:46 +0000239
240 // Handle this like a #include file being popped off the stack.
Chris Lattner87414e82008-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 Kremenekb0eef362008-11-13 17:11:24 +0000253 CurTokenLexer.reset();
Chris Lattner87414e82008-03-09 04:10:46 +0000254 else
Ted Kremenekb0eef362008-11-13 17:11:24 +0000255 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
Chris Lattner87414e82008-03-09 04:10:46 +0000256 } else {
Ted Kremenekb0eef362008-11-13 17:11:24 +0000257 CurLexer.reset();
Chris Lattner87414e82008-03-09 04:10:46 +0000258 }
Ted Kremenek383ad382008-11-13 16:51:03 +0000259
260 PopIncludeMacroStack();
Chris Lattner87414e82008-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) {
Ted Kremenek3acf6702008-11-19 22:43:49 +0000267 assert(CurTokenLexer && !CurPPLexer &&
Chris Lattner87414e82008-03-09 04:10:46 +0000268 "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.
Ted Kremenek3acf6702008-11-19 22:43:49 +0000273 PreprocessorLexer *FoundLexer = 0;
Chris Lattner87414e82008-03-09 04:10:46 +0000274 bool LexerWasInPPMode = false;
275 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
276 IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
Ted Kremenek3acf6702008-11-19 22:43:49 +0000277 if (ISI.ThePPLexer == 0) continue; // Scan for a real lexer.
Chris Lattner87414e82008-03-09 04:10:46 +0000278
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.
Ted Kremenek3acf6702008-11-19 22:43:49 +0000285 FoundLexer = ISI.ThePPLexer;
Chris Lattner87414e82008-03-09 04:10:46 +0000286 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}