rename test
[clang.git] / lib / Lex / PPLexerChange.cpp
blobeef42b69d87ff1f385943197f3f53368be45fb27
1 //===--- 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.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Lex/Preprocessor.h"
16 #include "clang/Lex/HeaderSearch.h"
17 #include "clang/Lex/MacroInfo.h"
18 #include "clang/Lex/LexDiagnostic.h"
19 #include "clang/Basic/SourceManager.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 using namespace clang;
23 PPCallbacks::~PPCallbacks() {}
25 //===----------------------------------------------------------------------===//
26 // Miscellaneous Methods.
27 //===----------------------------------------------------------------------===//
29 /// isInPrimaryFile - Return true if we're in the top-level file, not in a
30 /// #include. This looks through macro expansions and active _Pragma lexers.
31 bool Preprocessor::isInPrimaryFile() const {
32 if (IsFileLexer())
33 return IncludeMacroStack.empty();
35 // If there are any stacked lexers, we're in a #include.
36 assert(IsFileLexer(IncludeMacroStack[0]) &&
37 "Top level include stack isn't our primary lexer?");
38 for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
39 if (IsFileLexer(IncludeMacroStack[i]))
40 return false;
41 return true;
44 /// getCurrentLexer - Return the current file lexer being lexed from. Note
45 /// that this ignores any potentially active macro expansions and _Pragma
46 /// expansions going on at the time.
47 PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
48 if (IsFileLexer())
49 return CurPPLexer;
51 // Look for a stacked lexer.
52 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
53 const IncludeStackInfo& ISI = IncludeMacroStack[i-1];
54 if (IsFileLexer(ISI))
55 return ISI.ThePPLexer;
57 return 0;
61 //===----------------------------------------------------------------------===//
62 // Methods for Entering and Callbacks for leaving various contexts
63 //===----------------------------------------------------------------------===//
65 /// EnterSourceFile - Add a source file to the top of the include stack and
66 /// start lexing tokens from it instead of the current buffer.
67 void Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir,
68 SourceLocation Loc) {
69 assert(CurTokenLexer == 0 && "Cannot #include a file inside a macro!");
70 ++NumEnteredSourceFiles;
72 if (MaxIncludeStackDepth < IncludeMacroStack.size())
73 MaxIncludeStackDepth = IncludeMacroStack.size();
75 if (PTH) {
76 if (PTHLexer *PL = PTH->CreateLexer(FID)) {
77 EnterSourceFileWithPTH(PL, CurDir);
78 return;
82 // Get the MemoryBuffer for this FID, if it fails, we fail.
83 bool Invalid = false;
84 const llvm::MemoryBuffer *InputFile =
85 getSourceManager().getBuffer(FID, Loc, &Invalid);
86 if (Invalid) {
87 SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
88 Diag(Loc, diag::err_pp_error_opening_file)
89 << std::string(SourceMgr.getBufferName(FileStart)) << "";
90 return;
93 EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir);
94 return;
97 /// EnterSourceFileWithLexer - Add a source file to the top of the include stack
98 /// and start lexing tokens from it instead of the current buffer.
99 void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
100 const DirectoryLookup *CurDir) {
102 // Add the current lexer to the include stack.
103 if (CurPPLexer || CurTokenLexer)
104 PushIncludeMacroStack();
106 CurLexer.reset(TheLexer);
107 CurPPLexer = TheLexer;
108 CurDirLookup = CurDir;
110 // Notify the client, if desired, that we are in a new source file.
111 if (Callbacks && !CurLexer->Is_PragmaLexer) {
112 SrcMgr::CharacteristicKind FileType =
113 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
115 Callbacks->FileChanged(CurLexer->getFileLoc(),
116 PPCallbacks::EnterFile, FileType);
120 /// EnterSourceFileWithPTH - Add a source file to the top of the include stack
121 /// and start getting tokens from it using the PTH cache.
122 void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL,
123 const DirectoryLookup *CurDir) {
125 if (CurPPLexer || CurTokenLexer)
126 PushIncludeMacroStack();
128 CurDirLookup = CurDir;
129 CurPTHLexer.reset(PL);
130 CurPPLexer = CurPTHLexer.get();
132 // Notify the client, if desired, that we are in a new source file.
133 if (Callbacks) {
134 FileID FID = CurPPLexer->getFileID();
135 SourceLocation EnterLoc = SourceMgr.getLocForStartOfFile(FID);
136 SrcMgr::CharacteristicKind FileType =
137 SourceMgr.getFileCharacteristic(EnterLoc);
138 Callbacks->FileChanged(EnterLoc, PPCallbacks::EnterFile, FileType);
142 /// EnterMacro - Add a Macro to the top of the include stack and start lexing
143 /// tokens from it instead of the current buffer.
144 void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
145 MacroArgs *Args) {
146 PushIncludeMacroStack();
147 CurDirLookup = 0;
149 if (NumCachedTokenLexers == 0) {
150 CurTokenLexer.reset(new TokenLexer(Tok, ILEnd, Args, *this));
151 } else {
152 CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
153 CurTokenLexer->Init(Tok, ILEnd, Args);
157 /// EnterTokenStream - Add a "macro" context to the top of the include stack,
158 /// which will cause the lexer to start returning the specified tokens.
160 /// If DisableMacroExpansion is true, tokens lexed from the token stream will
161 /// not be subject to further macro expansion. Otherwise, these tokens will
162 /// be re-macro-expanded when/if expansion is enabled.
164 /// If OwnsTokens is false, this method assumes that the specified stream of
165 /// tokens has a permanent owner somewhere, so they do not need to be copied.
166 /// If it is true, it assumes the array of tokens is allocated with new[] and
167 /// must be freed.
169 void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
170 bool DisableMacroExpansion,
171 bool OwnsTokens) {
172 // Save our current state.
173 PushIncludeMacroStack();
174 CurDirLookup = 0;
176 // Create a macro expander to expand from the specified token stream.
177 if (NumCachedTokenLexers == 0) {
178 CurTokenLexer.reset(new TokenLexer(Toks, NumToks, DisableMacroExpansion,
179 OwnsTokens, *this));
180 } else {
181 CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
182 CurTokenLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
186 /// HandleEndOfFile - This callback is invoked when the lexer hits the end of
187 /// the current file. This either returns the EOF token or pops a level off
188 /// the include stack and keeps going.
189 bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
190 assert(!CurTokenLexer &&
191 "Ending a file when currently in a macro!");
193 // See if this file had a controlling macro.
194 if (CurPPLexer) { // Not ending a macro, ignore it.
195 if (const IdentifierInfo *ControllingMacro =
196 CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
197 // Okay, this has a controlling macro, remember in HeaderFileInfo.
198 if (const FileEntry *FE =
199 SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))
200 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
204 // If this is a #include'd file, pop it off the include stack and continue
205 // lexing the #includer file.
206 if (!IncludeMacroStack.empty()) {
207 // We're done with the #included file.
208 RemoveTopOfLexerStack();
210 // Notify the client, if desired, that we are in a new source file.
211 if (Callbacks && !isEndOfMacro && CurPPLexer) {
212 SrcMgr::CharacteristicKind FileType =
213 SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
214 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
215 PPCallbacks::ExitFile, FileType);
218 // Client should lex another token.
219 return false;
222 // If the file ends with a newline, form the EOF token on the newline itself,
223 // rather than "on the line following it", which doesn't exist. This makes
224 // diagnostics relating to the end of file include the last file that the user
225 // actually typed, which is goodness.
226 if (CurLexer) {
227 const char *EndPos = CurLexer->BufferEnd;
228 if (EndPos != CurLexer->BufferStart &&
229 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
230 --EndPos;
232 // Handle \n\r and \r\n:
233 if (EndPos != CurLexer->BufferStart &&
234 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
235 EndPos[-1] != EndPos[0])
236 --EndPos;
239 Result.startToken();
240 CurLexer->BufferPtr = EndPos;
241 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
243 // We're done with the #included file.
244 CurLexer.reset();
245 } else {
246 assert(CurPTHLexer && "Got EOF but no current lexer set!");
247 CurPTHLexer->getEOF(Result);
248 CurPTHLexer.reset();
251 CurPPLexer = 0;
253 // This is the end of the top-level file. 'WarnUnusedMacroLocs' has collected
254 // all macro locations that we need to warn because they are not used.
255 for (WarnUnusedMacroLocsTy::iterator
256 I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end(); I!=E; ++I)
257 Diag(*I, diag::pp_macro_not_used);
259 return true;
262 /// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
263 /// hits the end of its token stream.
264 bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
265 assert(CurTokenLexer && !CurPPLexer &&
266 "Ending a macro when currently in a #include file!");
268 // Delete or cache the now-dead macro expander.
269 if (NumCachedTokenLexers == TokenLexerCacheSize)
270 CurTokenLexer.reset();
271 else
272 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
274 // Handle this like a #include file being popped off the stack.
275 return HandleEndOfFile(Result, true);
278 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
279 /// lexer stack. This should only be used in situations where the current
280 /// state of the top-of-stack lexer is unknown.
281 void Preprocessor::RemoveTopOfLexerStack() {
282 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
284 if (CurTokenLexer) {
285 // Delete or cache the now-dead macro expander.
286 if (NumCachedTokenLexers == TokenLexerCacheSize)
287 CurTokenLexer.reset();
288 else
289 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
292 PopIncludeMacroStack();
295 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a
296 /// comment (/##/) in microsoft mode, this method handles updating the current
297 /// state, returning the token on the next source line.
298 void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
299 assert(CurTokenLexer && !CurPPLexer &&
300 "Pasted comment can only be formed from macro");
302 // We handle this by scanning for the closest real lexer, switching it to
303 // raw mode and preprocessor mode. This will cause it to return \n as an
304 // explicit EOM token.
305 PreprocessorLexer *FoundLexer = 0;
306 bool LexerWasInPPMode = false;
307 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
308 IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
309 if (ISI.ThePPLexer == 0) continue; // Scan for a real lexer.
311 // Once we find a real lexer, mark it as raw mode (disabling macro
312 // expansions) and preprocessor mode (return EOM). We know that the lexer
313 // was *not* in raw mode before, because the macro that the comment came
314 // from was expanded. However, it could have already been in preprocessor
315 // mode (#if COMMENT) in which case we have to return it to that mode and
316 // return EOM.
317 FoundLexer = ISI.ThePPLexer;
318 FoundLexer->LexingRawMode = true;
319 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
320 FoundLexer->ParsingPreprocessorDirective = true;
321 break;
324 // Okay, we either found and switched over the lexer, or we didn't find a
325 // lexer. In either case, finish off the macro the comment came from, getting
326 // the next token.
327 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
329 // Discarding comments as long as we don't have EOF or EOM. This 'comments
330 // out' the rest of the line, including any tokens that came from other macros
331 // that were active, as in:
332 // #define submacro a COMMENT b
333 // submacro c
334 // which should lex to 'a' only: 'b' and 'c' should be removed.
335 while (Tok.isNot(tok::eom) && Tok.isNot(tok::eof))
336 Lex(Tok);
338 // If we got an eom token, then we successfully found the end of the line.
339 if (Tok.is(tok::eom)) {
340 assert(FoundLexer && "Can't get end of line without an active lexer");
341 // Restore the lexer back to normal mode instead of raw mode.
342 FoundLexer->LexingRawMode = false;
344 // If the lexer was already in preprocessor mode, just return the EOM token
345 // to finish the preprocessor line.
346 if (LexerWasInPPMode) return;
348 // Otherwise, switch out of PP mode and return the next lexed token.
349 FoundLexer->ParsingPreprocessorDirective = false;
350 return Lex(Tok);
353 // If we got an EOF token, then we reached the end of the token stream but
354 // didn't find an explicit \n. This can only happen if there was no lexer
355 // active (an active lexer would return EOM at EOF if there was no \n in
356 // preprocessor directive mode), so just return EOF as our token.
357 assert(!FoundLexer && "Lexer should return EOM before EOF in PP mode");