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"
21 using namespace clang;
22 
23 PPCallbacks::~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.
31 bool 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.
47 PreprocessorLexer *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.  Return true
67 /// on failure.
68 void Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir) {
69   assert(CurTokenLexer == 0 && "Cannot #include a file inside a macro!");
70   ++NumEnteredSourceFiles;
71 
72   if (MaxIncludeStackDepth < IncludeMacroStack.size())
73     MaxIncludeStackDepth = IncludeMacroStack.size();
74 
75   if (PTH) {
76     if (PTHLexer *PL = PTH->CreateLexer(FID))
77       return EnterSourceFileWithPTH(PL, CurDir);
78   }
79   EnterSourceFileWithLexer(new Lexer(FID, *this), CurDir);
80 }
81 
82 /// EnterSourceFileWithLexer - Add a source file to the top of the include stack
83 ///  and start lexing tokens from it instead of the current buffer.
84 void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
85                                             const DirectoryLookup *CurDir) {
86 
87   // Add the current lexer to the include stack.
88   if (CurPPLexer || CurTokenLexer)
89     PushIncludeMacroStack();
90 
91   CurLexer.reset(TheLexer);
92   CurPPLexer = TheLexer;
93   CurDirLookup = CurDir;
94 
95   // Notify the client, if desired, that we are in a new source file.
96   if (Callbacks && !CurLexer->Is_PragmaLexer) {
97     SrcMgr::CharacteristicKind FileType =
98        SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
99 
100     Callbacks->FileChanged(CurLexer->getFileLoc(),
101                            PPCallbacks::EnterFile, FileType);
102   }
103 }
104 
105 /// EnterSourceFileWithPTH - Add a source file to the top of the include stack
106 /// and start getting tokens from it using the PTH cache.
107 void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL,
108                                           const DirectoryLookup *CurDir) {
109 
110   if (CurPPLexer || CurTokenLexer)
111     PushIncludeMacroStack();
112 
113   CurDirLookup = CurDir;
114   CurPTHLexer.reset(PL);
115   CurPPLexer = CurPTHLexer.get();
116 
117   // Notify the client, if desired, that we are in a new source file.
118   if (Callbacks) {
119     FileID FID = CurPPLexer->getFileID();
120     SourceLocation EnterLoc = SourceMgr.getLocForStartOfFile(FID);
121     SrcMgr::CharacteristicKind FileType =
122       SourceMgr.getFileCharacteristic(EnterLoc);
123     Callbacks->FileChanged(EnterLoc, PPCallbacks::EnterFile, FileType);
124   }
125 }
126 
127 /// EnterMacro - Add a Macro to the top of the include stack and start lexing
128 /// tokens from it instead of the current buffer.
129 void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
130                               MacroArgs *Args) {
131   PushIncludeMacroStack();
132   CurDirLookup = 0;
133 
134   if (NumCachedTokenLexers == 0) {
135     CurTokenLexer.reset(new TokenLexer(Tok, ILEnd, Args, *this));
136   } else {
137     CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
138     CurTokenLexer->Init(Tok, ILEnd, Args);
139   }
140 }
141 
142 /// EnterTokenStream - Add a "macro" context to the top of the include stack,
143 /// which will cause the lexer to start returning the specified tokens.
144 ///
145 /// If DisableMacroExpansion is true, tokens lexed from the token stream will
146 /// not be subject to further macro expansion.  Otherwise, these tokens will
147 /// be re-macro-expanded when/if expansion is enabled.
148 ///
149 /// If OwnsTokens is false, this method assumes that the specified stream of
150 /// tokens has a permanent owner somewhere, so they do not need to be copied.
151 /// If it is true, it assumes the array of tokens is allocated with new[] and
152 /// must be freed.
153 ///
154 void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
155                                     bool DisableMacroExpansion,
156                                     bool OwnsTokens) {
157   // Save our current state.
158   PushIncludeMacroStack();
159   CurDirLookup = 0;
160 
161   // Create a macro expander to expand from the specified token stream.
162   if (NumCachedTokenLexers == 0) {
163     CurTokenLexer.reset(new TokenLexer(Toks, NumToks, DisableMacroExpansion,
164                                        OwnsTokens, *this));
165   } else {
166     CurTokenLexer.reset(TokenLexerCache[--NumCachedTokenLexers]);
167     CurTokenLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
168   }
169 }
170 
171 /// HandleEndOfFile - This callback is invoked when the lexer hits the end of
172 /// the current file.  This either returns the EOF token or pops a level off
173 /// the include stack and keeps going.
174 bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
175   assert(!CurTokenLexer &&
176          "Ending a file when currently in a macro!");
177 
178   // See if this file had a controlling macro.
179   if (CurPPLexer) {  // Not ending a macro, ignore it.
180     if (const IdentifierInfo *ControllingMacro =
181           CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
182       // Okay, this has a controlling macro, remember in HeaderFileInfo.
183       if (const FileEntry *FE =
184             SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))
185         HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
186     }
187   }
188 
189   // If this is a #include'd file, pop it off the include stack and continue
190   // lexing the #includer file.
191   if (!IncludeMacroStack.empty()) {
192     // We're done with the #included file.
193     RemoveTopOfLexerStack();
194 
195     // Notify the client, if desired, that we are in a new source file.
196     if (Callbacks && !isEndOfMacro && CurPPLexer) {
197       SrcMgr::CharacteristicKind FileType =
198         SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
199       Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
200                              PPCallbacks::ExitFile, FileType);
201     }
202 
203     // Client should lex another token.
204     return false;
205   }
206 
207   // If the file ends with a newline, form the EOF token on the newline itself,
208   // rather than "on the line following it", which doesn't exist.  This makes
209   // diagnostics relating to the end of file include the last file that the user
210   // actually typed, which is goodness.
211   if (CurLexer) {
212     const char *EndPos = CurLexer->BufferEnd;
213     if (EndPos != CurLexer->BufferStart &&
214         (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
215       --EndPos;
216 
217       // Handle \n\r and \r\n:
218       if (EndPos != CurLexer->BufferStart &&
219           (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
220           EndPos[-1] != EndPos[0])
221         --EndPos;
222     }
223 
224     Result.startToken();
225     CurLexer->BufferPtr = EndPos;
226     CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
227 
228     // We're done with the #included file.
229     CurLexer.reset();
230   } else {
231     assert(CurPTHLexer && "Got EOF but no current lexer set!");
232     CurPTHLexer->getEOF(Result);
233     CurPTHLexer.reset();
234   }
235 
236   CurPPLexer = 0;
237 
238   // This is the end of the top-level file.  If the diag::pp_macro_not_used
239   // diagnostic is enabled, look for macros that have not been used.
240   if (getDiagnostics().getDiagnosticLevel(diag::pp_macro_not_used) !=
241         Diagnostic::Ignored) {
242     for (macro_iterator I = macro_begin(), E = macro_end(); I != E; ++I)
243       if (!I->second->isUsed())
244         Diag(I->second->getDefinitionLoc(), diag::pp_macro_not_used);
245   }
246   return true;
247 }
248 
249 /// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
250 /// hits the end of its token stream.
251 bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
252   assert(CurTokenLexer && !CurPPLexer &&
253          "Ending a macro when currently in a #include file!");
254 
255   // Delete or cache the now-dead macro expander.
256   if (NumCachedTokenLexers == TokenLexerCacheSize)
257     CurTokenLexer.reset();
258   else
259     TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
260 
261   // Handle this like a #include file being popped off the stack.
262   return HandleEndOfFile(Result, true);
263 }
264 
265 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
266 /// lexer stack.  This should only be used in situations where the current
267 /// state of the top-of-stack lexer is unknown.
268 void Preprocessor::RemoveTopOfLexerStack() {
269   assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
270 
271   if (CurTokenLexer) {
272     // Delete or cache the now-dead macro expander.
273     if (NumCachedTokenLexers == TokenLexerCacheSize)
274       CurTokenLexer.reset();
275     else
276       TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
277   }
278 
279   PopIncludeMacroStack();
280 }
281 
282 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a
283 /// comment (/##/) in microsoft mode, this method handles updating the current
284 /// state, returning the token on the next source line.
285 void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
286   assert(CurTokenLexer && !CurPPLexer &&
287          "Pasted comment can only be formed from macro");
288 
289   // We handle this by scanning for the closest real lexer, switching it to
290   // raw mode and preprocessor mode.  This will cause it to return \n as an
291   // explicit EOM token.
292   PreprocessorLexer *FoundLexer = 0;
293   bool LexerWasInPPMode = false;
294   for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
295     IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
296     if (ISI.ThePPLexer == 0) continue;  // Scan for a real lexer.
297 
298     // Once we find a real lexer, mark it as raw mode (disabling macro
299     // expansions) and preprocessor mode (return EOM).  We know that the lexer
300     // was *not* in raw mode before, because the macro that the comment came
301     // from was expanded.  However, it could have already been in preprocessor
302     // mode (#if COMMENT) in which case we have to return it to that mode and
303     // return EOM.
304     FoundLexer = ISI.ThePPLexer;
305     FoundLexer->LexingRawMode = true;
306     LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
307     FoundLexer->ParsingPreprocessorDirective = true;
308     break;
309   }
310 
311   // Okay, we either found and switched over the lexer, or we didn't find a
312   // lexer.  In either case, finish off the macro the comment came from, getting
313   // the next token.
314   if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
315 
316   // Discarding comments as long as we don't have EOF or EOM.  This 'comments
317   // out' the rest of the line, including any tokens that came from other macros
318   // that were active, as in:
319   //  #define submacro a COMMENT b
320   //    submacro c
321   // which should lex to 'a' only: 'b' and 'c' should be removed.
322   while (Tok.isNot(tok::eom) && Tok.isNot(tok::eof))
323     Lex(Tok);
324 
325   // If we got an eom token, then we successfully found the end of the line.
326   if (Tok.is(tok::eom)) {
327     assert(FoundLexer && "Can't get end of line without an active lexer");
328     // Restore the lexer back to normal mode instead of raw mode.
329     FoundLexer->LexingRawMode = false;
330 
331     // If the lexer was already in preprocessor mode, just return the EOM token
332     // to finish the preprocessor line.
333     if (LexerWasInPPMode) return;
334 
335     // Otherwise, switch out of PP mode and return the next lexed token.
336     FoundLexer->ParsingPreprocessorDirective = false;
337     return Lex(Tok);
338   }
339 
340   // If we got an EOF token, then we reached the end of the token stream but
341   // didn't find an explicit \n.  This can only happen if there was no lexer
342   // active (an active lexer would return EOM at EOF if there was no \n in
343   // preprocessor directive mode), so just return EOF as our token.
344   assert(!FoundLexer && "Lexer should return EOM before EOF in PP mode");
345 }
346