blob: 5129d58bd7fc9fc3da31587151b1ce01a1effa74 [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 Kremenekb93efa32008-11-21 20:51:59 +000077#if 1
Chris Lattner8c32b1a2008-03-09 04:10:46 +000078 Lexer *TheLexer = new Lexer(SourceLocation::getFileLoc(FileID, 0), *this);
79 EnterSourceFileWithLexer(TheLexer, CurDir);
Ted Kremenek15ba2af2008-11-20 07:56:33 +000080#else
Ted Kremenek82a500b2008-11-27 00:38:24 +000081 if (CurPPLexer || CurTokenLexer)
82 PushIncludeMacroStack();
83
84 CurDirLookup = CurDir;
85 SourceLocation Loc = SourceLocation::getFileLoc(FileID, 0);
86 CurPTHLexer.reset(new PTHLexer(*this, Loc));
87 CurPPLexer = CurPTHLexer.get();
88
89 // Generate the tokens.
90
Ted Kremenek15ba2af2008-11-20 07:56:33 +000091 const llvm::MemoryBuffer* B = getSourceManager().getBuffer(FileID);
92
93 // Create a raw lexer.
94 Lexer L(SourceLocation::getFileLoc(FileID, 0), getLangOptions(),
95 B->getBufferStart(), B->getBufferEnd(), B);
96
97 // Ignore whitespace.
98 L.SetKeepWhitespaceMode(false);
99 L.SetCommentRetentionState(false);
100
101 // Lex the file, populating our data structures.
Ted Kremenek82a500b2008-11-27 00:38:24 +0000102 std::vector<Token>& Tokens = CurPTHLexer->getTokens();
Ted Kremenekc840f0c2008-11-21 19:41:29 +0000103 Token Tok;
Ted Kremenek15ba2af2008-11-20 07:56:33 +0000104
105 do {
106 L.LexFromRawLexer(Tok);
107
Ted Kremenekc840f0c2008-11-21 19:41:29 +0000108 if (Tok.is(tok::identifier)) {
Ted Kremenek15ba2af2008-11-20 07:56:33 +0000109 Tok.setIdentifierInfo(LookUpIdentifierInfo(Tok));
Ted Kremenekc840f0c2008-11-21 19:41:29 +0000110 }
111 else if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
112 // Special processing for #include. Store the '#' token and lex
113 // the next token.
Ted Kremenek82a500b2008-11-27 00:38:24 +0000114 Tokens.push_back(Tok);
Ted Kremenekc840f0c2008-11-21 19:41:29 +0000115 L.LexFromRawLexer(Tok);
116
117 // Did we see 'include'/'import'/'include_next'?
118 if (!Tok.is(tok::identifier))
119 continue;
120
121 IdentifierInfo* II = LookUpIdentifierInfo(Tok);
122 Tok.setIdentifierInfo(II);
123 tok::PPKeywordKind K = II->getPPKeywordID();
124
125 if (K == tok::pp_include || K == tok::pp_import ||
126 K == tok::pp_include_next) {
127
128 // Save the 'include' token.
Ted Kremenek82a500b2008-11-27 00:38:24 +0000129 Tokens.push_back(Tok);
Ted Kremenekc840f0c2008-11-21 19:41:29 +0000130
131 // Lex the next token as an include string.
132 L.ParsingPreprocessorDirective = true;
133 L.LexIncludeFilename(Tok);
134 L.ParsingPreprocessorDirective = false;
Ted Kremenekd5a8f0b2008-11-21 20:51:15 +0000135
136 if (Tok.is(tok::identifier))
137 Tok.setIdentifierInfo(LookUpIdentifierInfo(Tok));
Ted Kremenekc840f0c2008-11-21 19:41:29 +0000138 }
139 }
Ted Kremenek15ba2af2008-11-20 07:56:33 +0000140 }
Ted Kremenek82a500b2008-11-27 00:38:24 +0000141 while (Tokens.push_back(Tok), Tok.isNot(tok::eof));
Ted Kremenek15ba2af2008-11-20 07:56:33 +0000142
143 // Notify the client, if desired, that we are in a new source file.
144 if (Callbacks) {
145 SrcMgr::CharacteristicKind FileType =
146 SourceMgr.getFileCharacteristic(CurPPLexer->getFileID());
147 Callbacks->FileChanged(Loc, PPCallbacks::EnterFile, FileType);
148 }
149#endif
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000150}
Chris Lattner72181832008-09-26 20:12:23 +0000151
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000152/// EnterSourceFile - Add a source file to the top of the include stack and
153/// start lexing tokens from it instead of the current buffer.
154void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
155 const DirectoryLookup *CurDir) {
156
157 // Add the current lexer to the include stack.
Ted Kremenek41938c82008-11-19 21:57:25 +0000158 if (CurPPLexer || CurTokenLexer)
Ted Kremeneked04c4c2008-11-13 16:51:03 +0000159 PushIncludeMacroStack();
160
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000161 CurLexer.reset(TheLexer);
Ted Kremenek9c1b7502008-11-18 00:12:49 +0000162 CurPPLexer = TheLexer;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000163 CurDirLookup = CurDir;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000164
165 // Notify the client, if desired, that we are in a new source file.
166 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattner9d728512008-10-27 01:19:25 +0000167 SrcMgr::CharacteristicKind FileType =
Chris Lattner0b9e7362008-09-26 21:18:42 +0000168 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000169
170 Callbacks->FileChanged(CurLexer->getFileLoc(),
171 PPCallbacks::EnterFile, FileType);
172 }
173}
174
175
176
177/// EnterMacro - Add a Macro to the top of the include stack and start lexing
178/// tokens from it instead of the current buffer.
179void Preprocessor::EnterMacro(Token &Tok, MacroArgs *Args) {
Ted Kremeneked04c4c2008-11-13 16:51:03 +0000180 PushIncludeMacroStack();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000181 CurDirLookup = 0;
182
183 if (NumCachedTokenLexers == 0) {
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000184 CurTokenLexer.reset(new TokenLexer(Tok, Args, *this));
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000185 } else {
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000186 CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000187 CurTokenLexer->Init(Tok, Args);
188 }
189}
190
191/// EnterTokenStream - Add a "macro" context to the top of the include stack,
Chris Lattner6b884502008-03-10 06:06:04 +0000192/// which will cause the lexer to start returning the specified tokens.
193///
194/// If DisableMacroExpansion is true, tokens lexed from the token stream will
195/// not be subject to further macro expansion. Otherwise, these tokens will
196/// be re-macro-expanded when/if expansion is enabled.
197///
198/// If OwnsTokens is false, this method assumes that the specified stream of
199/// tokens has a permanent owner somewhere, so they do not need to be copied.
200/// If it is true, it assumes the array of tokens is allocated with new[] and
201/// must be freed.
202///
203void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
204 bool DisableMacroExpansion,
205 bool OwnsTokens) {
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000206 // Save our current state.
Ted Kremeneked04c4c2008-11-13 16:51:03 +0000207 PushIncludeMacroStack();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000208 CurDirLookup = 0;
209
210 // Create a macro expander to expand from the specified token stream.
211 if (NumCachedTokenLexers == 0) {
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000212 CurTokenLexer.reset(new TokenLexer(Toks, NumToks, DisableMacroExpansion,
213 OwnsTokens, *this));
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000214 } else {
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000215 CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
Chris Lattner6b884502008-03-10 06:06:04 +0000216 CurTokenLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000217 }
218}
219
220/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
221/// the current file. This either returns the EOF token or pops a level off
222/// the include stack and keeps going.
223bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
224 assert(!CurTokenLexer &&
225 "Ending a file when currently in a macro!");
226
227 // See if this file had a controlling macro.
Ted Kremenek1a531572008-11-19 22:43:49 +0000228 if (CurPPLexer) { // Not ending a macro, ignore it.
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000229 if (const IdentifierInfo *ControllingMacro =
Ted Kremenek1a531572008-11-19 22:43:49 +0000230 CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000231 // Okay, this has a controlling macro, remember in PerFileInfo.
232 if (const FileEntry *FE =
Ted Kremenek1a531572008-11-19 22:43:49 +0000233 SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000234 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
235 }
236 }
237
238 // If this is a #include'd file, pop it off the include stack and continue
239 // lexing the #includer file.
240 if (!IncludeMacroStack.empty()) {
241 // We're done with the #included file.
242 RemoveTopOfLexerStack();
243
244 // Notify the client, if desired, that we are in a new source file.
Ted Kremenek1a531572008-11-19 22:43:49 +0000245 if (Callbacks && !isEndOfMacro && CurPPLexer) {
Chris Lattner9d728512008-10-27 01:19:25 +0000246 SrcMgr::CharacteristicKind FileType =
Ted Kremenek1a531572008-11-19 22:43:49 +0000247 SourceMgr.getFileCharacteristic(CurPPLexer->getFileID());
Ted Kremenek15ba2af2008-11-20 07:56:33 +0000248
Ted Kremeneka7512172008-11-20 01:52:55 +0000249 if (CurLexer) {
Ted Kremenek1a531572008-11-19 22:43:49 +0000250 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
251 PPCallbacks::ExitFile, FileType);
Ted Kremeneka7512172008-11-20 01:52:55 +0000252 }
253 else {
Ted Kremenek15ba2af2008-11-20 07:56:33 +0000254 // FIXME: Is this okay to use the location of 'Result'?
255 Callbacks->FileChanged(Result.getLocation(), PPCallbacks::ExitFile,
256 FileType);
Ted Kremeneka7512172008-11-20 01:52:55 +0000257 }
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000258 }
259
260 // Client should lex another token.
261 return false;
262 }
263
264 // If the file ends with a newline, form the EOF token on the newline itself,
265 // rather than "on the line following it", which doesn't exist. This makes
266 // diagnostics relating to the end of file include the last file that the user
267 // actually typed, which is goodness.
Ted Kremenek1a531572008-11-19 22:43:49 +0000268 if (CurLexer) {
269 const char *EndPos = CurLexer->BufferEnd;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000270 if (EndPos != CurLexer->BufferStart &&
Ted Kremenek1a531572008-11-19 22:43:49 +0000271 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000272 --EndPos;
Ted Kremenek1a531572008-11-19 22:43:49 +0000273
274 // Handle \n\r and \r\n:
275 if (EndPos != CurLexer->BufferStart &&
276 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
277 EndPos[-1] != EndPos[0])
278 --EndPos;
279 }
280
281 Result.startToken();
282 CurLexer->BufferPtr = EndPos;
283 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
284
285 // We're done with the #included file.
286 CurLexer.reset();
287 }
288 else {
289 CurPTHLexer->setEOF(Result);
290 CurPTHLexer.reset();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000291 }
292
Ted Kremenek41938c82008-11-19 21:57:25 +0000293 CurPPLexer = 0;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000294
295 // This is the end of the top-level file. If the diag::pp_macro_not_used
296 // diagnostic is enabled, look for macros that have not been used.
297 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
298 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
299 Macros.begin(), E = Macros.end(); I != E; ++I) {
300 if (!I->second->isUsed())
301 Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
302 }
303 }
304 return true;
305}
306
307/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
308/// hits the end of its token stream.
309bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
Ted Kremenek1a531572008-11-19 22:43:49 +0000310 assert(CurTokenLexer && !CurPPLexer &&
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000311 "Ending a macro when currently in a #include file!");
312
313 // Delete or cache the now-dead macro expander.
314 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000315 CurTokenLexer.reset();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000316 else
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000317 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000318
319 // Handle this like a #include file being popped off the stack.
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000320 return HandleEndOfFile(Result, true);
321}
322
323/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
324/// lexer stack. This should only be used in situations where the current
325/// state of the top-of-stack lexer is unknown.
326void Preprocessor::RemoveTopOfLexerStack() {
327 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
328
329 if (CurTokenLexer) {
330 // Delete or cache the now-dead macro expander.
331 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000332 CurTokenLexer.reset();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000333 else
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000334 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
Ted Kremenek15ba2af2008-11-20 07:56:33 +0000335 }
Ted Kremeneked04c4c2008-11-13 16:51:03 +0000336
337 PopIncludeMacroStack();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000338}
339
340/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
341/// comment (/##/) in microsoft mode, this method handles updating the current
342/// state, returning the token on the next source line.
343void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
Ted Kremenek1a531572008-11-19 22:43:49 +0000344 assert(CurTokenLexer && !CurPPLexer &&
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000345 "Pasted comment can only be formed from macro");
346
347 // We handle this by scanning for the closest real lexer, switching it to
348 // raw mode and preprocessor mode. This will cause it to return \n as an
349 // explicit EOM token.
Ted Kremenek1a531572008-11-19 22:43:49 +0000350 PreprocessorLexer *FoundLexer = 0;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000351 bool LexerWasInPPMode = false;
352 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
353 IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
Ted Kremenek1a531572008-11-19 22:43:49 +0000354 if (ISI.ThePPLexer == 0) continue; // Scan for a real lexer.
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000355
356 // Once we find a real lexer, mark it as raw mode (disabling macro
357 // expansions) and preprocessor mode (return EOM). We know that the lexer
358 // was *not* in raw mode before, because the macro that the comment came
359 // from was expanded. However, it could have already been in preprocessor
360 // mode (#if COMMENT) in which case we have to return it to that mode and
361 // return EOM.
Ted Kremenek1a531572008-11-19 22:43:49 +0000362 FoundLexer = ISI.ThePPLexer;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000363 FoundLexer->LexingRawMode = true;
364 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
365 FoundLexer->ParsingPreprocessorDirective = true;
366 break;
367 }
368
369 // Okay, we either found and switched over the lexer, or we didn't find a
370 // lexer. In either case, finish off the macro the comment came from, getting
371 // the next token.
372 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
373
374 // Discarding comments as long as we don't have EOF or EOM. This 'comments
375 // out' the rest of the line, including any tokens that came from other macros
376 // that were active, as in:
377 // #define submacro a COMMENT b
378 // submacro c
379 // which should lex to 'a' only: 'b' and 'c' should be removed.
380 while (Tok.isNot(tok::eom) && Tok.isNot(tok::eof))
381 Lex(Tok);
382
383 // If we got an eom token, then we successfully found the end of the line.
384 if (Tok.is(tok::eom)) {
385 assert(FoundLexer && "Can't get end of line without an active lexer");
386 // Restore the lexer back to normal mode instead of raw mode.
387 FoundLexer->LexingRawMode = false;
388
389 // If the lexer was already in preprocessor mode, just return the EOM token
390 // to finish the preprocessor line.
391 if (LexerWasInPPMode) return;
392
393 // Otherwise, switch out of PP mode and return the next lexed token.
394 FoundLexer->ParsingPreprocessorDirective = false;
395 return Lex(Tok);
396 }
397
398 // If we got an EOF token, then we reached the end of the token stream but
399 // didn't find an explicit \n. This can only happen if there was no lexer
400 // active (an active lexer would return EOM at EOF if there was no \n in
401 // preprocessor directive mode), so just return EOF as our token.
402 assert(!FoundLexer && "Lexer should return EOM before EOF in PP mode");
403}