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