PPLexerChange.cpp revision 6e2901407bff59aeb4cc301cc58b034723d0eb49
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.
12//
13//===----------------------------------------------------------------------===//
14
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"
21using namespace clang;
22
23PPCallbacks::~PPCallbacks() {}
24
25//===----------------------------------------------------------------------===//
26// Miscellaneous Methods.
27//===----------------------------------------------------------------------===//
28
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.
31bool Preprocessor::isInPrimaryFile() const {
32  if (IsFileLexer())
33    return IncludeMacroStack.empty();
34
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;
42}
43
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.
47PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
48  if (IsFileLexer())
49    return CurPPLexer;
50
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;
56  }
57  return 0;
58}
59
60
61//===----------------------------------------------------------------------===//
62// Methods for Entering and Callbacks for leaving various contexts
63//===----------------------------------------------------------------------===//
64
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.
67bool Preprocessor::EnterSourceFile(FileID FID, 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  if (PTH) {
75    if (PTHLexer *PL = PTH->CreateLexer(FID)) {
76      EnterSourceFileWithPTH(PL, CurDir);
77      return false;
78    }
79  }
80
81  // Get the MemoryBuffer for this FID, if it fails, we fail.
82  const llvm::MemoryBuffer *InputFile = getSourceManager().getBuffer(FID);
83  if (InputFile == 0)
84    return true;
85
86  EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir);
87  return false;
88}
89
90/// EnterSourceFileWithLexer - Add a source file to the top of the include stack
91///  and start lexing tokens from it instead of the current buffer.
92void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
93                                            const DirectoryLookup *CurDir) {
94
95  // Add the current lexer to the include stack.
96  if (CurPPLexer || CurTokenLexer)
97    PushIncludeMacroStack();
98
99  CurLexer.reset(TheLexer);
100  CurPPLexer = TheLexer;
101  CurDirLookup = CurDir;
102
103  // Notify the client, if desired, that we are in a new source file.
104  if (Callbacks && !CurLexer->Is_PragmaLexer) {
105    SrcMgr::CharacteristicKind FileType =
106       SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
107
108    Callbacks->FileChanged(CurLexer->getFileLoc(),
109                           PPCallbacks::EnterFile, FileType);
110  }
111}
112
113/// EnterSourceFileWithPTH - Add a source file to the top of the include stack
114/// and start getting tokens from it using the PTH cache.
115void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL,
116                                          const DirectoryLookup *CurDir) {
117
118  if (CurPPLexer || CurTokenLexer)
119    PushIncludeMacroStack();
120
121  CurDirLookup = CurDir;
122  CurPTHLexer.reset(PL);
123  CurPPLexer = CurPTHLexer.get();
124
125  // Notify the client, if desired, that we are in a new source file.
126  if (Callbacks) {
127    FileID FID = CurPPLexer->getFileID();
128    SourceLocation EnterLoc = SourceMgr.getLocForStartOfFile(FID);
129    SrcMgr::CharacteristicKind FileType =
130      SourceMgr.getFileCharacteristic(EnterLoc);
131    Callbacks->FileChanged(EnterLoc, PPCallbacks::EnterFile, FileType);
132  }
133}
134
135/// EnterMacro - Add a Macro to the top of the include stack and start lexing
136/// tokens from it instead of the current buffer.
137void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
138                              MacroArgs *Args) {
139  PushIncludeMacroStack();
140  CurDirLookup = 0;
141
142  if (NumCachedTokenLexers == 0) {
143    CurTokenLexer.reset(new TokenLexer(Tok, ILEnd, Args, *this));
144  } else {
145    CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
146    CurTokenLexer->Init(Tok, ILEnd, Args);
147  }
148}
149
150/// EnterTokenStream - Add a "macro" context to the top of the include stack,
151/// 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) {
165  // Save our current state.
166  PushIncludeMacroStack();
167  CurDirLookup = 0;
168
169  // Create a macro expander to expand from the specified token stream.
170  if (NumCachedTokenLexers == 0) {
171    CurTokenLexer.reset(new TokenLexer(Toks, NumToks, DisableMacroExpansion,
172                                       OwnsTokens, *this));
173  } else {
174    CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
175    CurTokenLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
176  }
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.
187  if (CurPPLexer) {  // Not ending a macro, ignore it.
188    if (const IdentifierInfo *ControllingMacro =
189          CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
190      // Okay, this has a controlling macro, remember in HeaderFileInfo.
191      if (const FileEntry *FE =
192            SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))
193        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.
204    if (Callbacks && !isEndOfMacro && CurPPLexer) {
205      SrcMgr::CharacteristicKind FileType =
206        SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
207      Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
208                             PPCallbacks::ExitFile, FileType);
209    }
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.
219  if (CurLexer) {
220    const char *EndPos = CurLexer->BufferEnd;
221    if (EndPos != CurLexer->BufferStart &&
222        (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
223      --EndPos;
224
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  } else {
239    assert(CurPTHLexer && "Got EOF but no current lexer set!");
240    CurPTHLexer->getEOF(Result);
241    CurPTHLexer.reset();
242  }
243
244  CurPPLexer = 0;
245
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 (getDiagnostics().getDiagnosticLevel(diag::pp_macro_not_used) !=
249        Diagnostic::Ignored) {
250    for (macro_iterator I = macro_begin(), E = macro_end(); I != E; ++I)
251      if (!I->second->isUsed())
252        Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
253  }
254  return true;
255}
256
257/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
258/// hits the end of its token stream.
259bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
260  assert(CurTokenLexer && !CurPPLexer &&
261         "Ending a macro when currently in a #include file!");
262
263  // Delete or cache the now-dead macro expander.
264  if (NumCachedTokenLexers == TokenLexerCacheSize)
265    CurTokenLexer.reset();
266  else
267    TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
268
269  // Handle this like a #include file being popped off the stack.
270  return HandleEndOfFile(Result, true);
271}
272
273/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
274/// lexer stack.  This should only be used in situations where the current
275/// state of the top-of-stack lexer is unknown.
276void Preprocessor::RemoveTopOfLexerStack() {
277  assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
278
279  if (CurTokenLexer) {
280    // Delete or cache the now-dead macro expander.
281    if (NumCachedTokenLexers == TokenLexerCacheSize)
282      CurTokenLexer.reset();
283    else
284      TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
285  }
286
287  PopIncludeMacroStack();
288}
289
290/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
291/// comment (/##/) in microsoft mode, this method handles updating the current
292/// state, returning the token on the next source line.
293void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
294  assert(CurTokenLexer && !CurPPLexer &&
295         "Pasted comment can only be formed from macro");
296
297  // We handle this by scanning for the closest real lexer, switching it to
298  // raw mode and preprocessor mode.  This will cause it to return \n as an
299  // explicit EOM token.
300  PreprocessorLexer *FoundLexer = 0;
301  bool LexerWasInPPMode = false;
302  for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
303    IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
304    if (ISI.ThePPLexer == 0) continue;  // Scan for a real lexer.
305
306    // Once we find a real lexer, mark it as raw mode (disabling macro
307    // expansions) and preprocessor mode (return EOM).  We know that the lexer
308    // was *not* in raw mode before, because the macro that the comment came
309    // from was expanded.  However, it could have already been in preprocessor
310    // mode (#if COMMENT) in which case we have to return it to that mode and
311    // return EOM.
312    FoundLexer = ISI.ThePPLexer;
313    FoundLexer->LexingRawMode = true;
314    LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
315    FoundLexer->ParsingPreprocessorDirective = true;
316    break;
317  }
318
319  // Okay, we either found and switched over the lexer, or we didn't find a
320  // lexer.  In either case, finish off the macro the comment came from, getting
321  // the next token.
322  if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
323
324  // Discarding comments as long as we don't have EOF or EOM.  This 'comments
325  // out' the rest of the line, including any tokens that came from other macros
326  // that were active, as in:
327  //  #define submacro a COMMENT b
328  //    submacro c
329  // which should lex to 'a' only: 'b' and 'c' should be removed.
330  while (Tok.isNot(tok::eom) && Tok.isNot(tok::eof))
331    Lex(Tok);
332
333  // If we got an eom token, then we successfully found the end of the line.
334  if (Tok.is(tok::eom)) {
335    assert(FoundLexer && "Can't get end of line without an active lexer");
336    // Restore the lexer back to normal mode instead of raw mode.
337    FoundLexer->LexingRawMode = false;
338
339    // If the lexer was already in preprocessor mode, just return the EOM token
340    // to finish the preprocessor line.
341    if (LexerWasInPPMode) return;
342
343    // Otherwise, switch out of PP mode and return the next lexed token.
344    FoundLexer->ParsingPreprocessorDirective = false;
345    return Lex(Tok);
346  }
347
348  // If we got an EOF token, then we reached the end of the token stream but
349  // didn't find an explicit \n.  This can only happen if there was no lexer
350  // active (an active lexer would return EOM at EOF if there was no \n in
351  // preprocessor directive mode), so just return EOF as our token.
352  assert(!FoundLexer && "Lexer should return EOM before EOF in PP mode");
353}
354