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/Basic/FileManager.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "clang/Lex/HeaderSearch.h"
19 #include "clang/Lex/LexDiagnostic.h"
20 #include "clang/Lex/MacroInfo.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/Support/FileSystem.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/Path.h"
25 using namespace clang;
26 
27 PPCallbacks::~PPCallbacks() {}
28 
29 //===----------------------------------------------------------------------===//
30 // Miscellaneous Methods.
31 //===----------------------------------------------------------------------===//
32 
33 /// isInPrimaryFile - Return true if we're in the top-level file, not in a
34 /// \#include.  This looks through macro expansions and active _Pragma lexers.
35 bool Preprocessor::isInPrimaryFile() const {
36   if (IsFileLexer())
37     return IncludeMacroStack.empty();
38 
39   // If there are any stacked lexers, we're in a #include.
40   assert(IsFileLexer(IncludeMacroStack[0]) &&
41          "Top level include stack isn't our primary lexer?");
42   for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
43     if (IsFileLexer(IncludeMacroStack[i]))
44       return false;
45   return true;
46 }
47 
48 /// getCurrentLexer - Return the current file lexer being lexed from.  Note
49 /// that this ignores any potentially active macro expansions and _Pragma
50 /// expansions going on at the time.
51 PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
52   if (IsFileLexer())
53     return CurPPLexer;
54 
55   // Look for a stacked lexer.
56   for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
57     const IncludeStackInfo& ISI = IncludeMacroStack[i-1];
58     if (IsFileLexer(ISI))
59       return ISI.ThePPLexer;
60   }
61   return 0;
62 }
63 
64 
65 //===----------------------------------------------------------------------===//
66 // Methods for Entering and Callbacks for leaving various contexts
67 //===----------------------------------------------------------------------===//
68 
69 /// EnterSourceFile - Add a source file to the top of the include stack and
70 /// start lexing tokens from it instead of the current buffer.
71 void Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir,
72                                    SourceLocation Loc, bool IsSubmodule) {
73   assert(!CurTokenLexer && "Cannot #include a file inside a macro!");
74   ++NumEnteredSourceFiles;
75 
76   if (MaxIncludeStackDepth < IncludeMacroStack.size())
77     MaxIncludeStackDepth = IncludeMacroStack.size();
78 
79   if (PTH) {
80     if (PTHLexer *PL = PTH->CreateLexer(FID)) {
81       EnterSourceFileWithPTH(PL, CurDir, IsSubmodule);
82       return;
83     }
84   }
85 
86   // Get the MemoryBuffer for this FID, if it fails, we fail.
87   bool Invalid = false;
88   const llvm::MemoryBuffer *InputFile =
89     getSourceManager().getBuffer(FID, Loc, &Invalid);
90   if (Invalid) {
91     SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
92     Diag(Loc, diag::err_pp_error_opening_file)
93       << std::string(SourceMgr.getBufferName(FileStart)) << "";
94     return;
95   }
96 
97   if (isCodeCompletionEnabled() &&
98       SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) {
99     CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID);
100     CodeCompletionLoc =
101         CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset);
102   }
103 
104   EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir,
105                            IsSubmodule);
106   return;
107 }
108 
109 /// EnterSourceFileWithLexer - Add a source file to the top of the include stack
110 ///  and start lexing tokens from it instead of the current buffer.
111 void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
112                                             const DirectoryLookup *CurDir,
113                                             bool IsSubmodule) {
114 
115   // Add the current lexer to the include stack.
116   if (CurPPLexer || CurTokenLexer)
117     PushIncludeMacroStack();
118 
119   CurLexer.reset(TheLexer);
120   CurPPLexer = TheLexer;
121   CurDirLookup = CurDir;
122   CurIsSubmodule = IsSubmodule;
123   if (CurLexerKind != CLK_LexAfterModuleImport)
124     CurLexerKind = CLK_Lexer;
125 
126   // Notify the client, if desired, that we are in a new source file.
127   if (Callbacks && !CurLexer->Is_PragmaLexer) {
128     SrcMgr::CharacteristicKind FileType =
129        SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
130 
131     Callbacks->FileChanged(CurLexer->getFileLoc(),
132                            PPCallbacks::EnterFile, FileType);
133   }
134 }
135 
136 /// EnterSourceFileWithPTH - Add a source file to the top of the include stack
137 /// and start getting tokens from it using the PTH cache.
138 void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL,
139                                           const DirectoryLookup *CurDir,
140                                           bool IsSubmodule) {
141 
142   if (CurPPLexer || CurTokenLexer)
143     PushIncludeMacroStack();
144 
145   CurDirLookup = CurDir;
146   CurPTHLexer.reset(PL);
147   CurPPLexer = CurPTHLexer.get();
148   CurIsSubmodule = IsSubmodule;
149   if (CurLexerKind != CLK_LexAfterModuleImport)
150     CurLexerKind = CLK_PTHLexer;
151 
152   // Notify the client, if desired, that we are in a new source file.
153   if (Callbacks) {
154     FileID FID = CurPPLexer->getFileID();
155     SourceLocation EnterLoc = SourceMgr.getLocForStartOfFile(FID);
156     SrcMgr::CharacteristicKind FileType =
157       SourceMgr.getFileCharacteristic(EnterLoc);
158     Callbacks->FileChanged(EnterLoc, PPCallbacks::EnterFile, FileType);
159   }
160 }
161 
162 /// EnterMacro - Add a Macro to the top of the include stack and start lexing
163 /// tokens from it instead of the current buffer.
164 void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
165                               MacroInfo *Macro, MacroArgs *Args) {
166   TokenLexer *TokLexer;
167   if (NumCachedTokenLexers == 0) {
168     TokLexer = new TokenLexer(Tok, ILEnd, Macro, Args, *this);
169   } else {
170     TokLexer = TokenLexerCache[--NumCachedTokenLexers];
171     TokLexer->Init(Tok, ILEnd, Macro, Args);
172   }
173 
174   PushIncludeMacroStack();
175   CurDirLookup = 0;
176   CurTokenLexer.reset(TokLexer);
177   if (CurLexerKind != CLK_LexAfterModuleImport)
178     CurLexerKind = CLK_TokenLexer;
179 }
180 
181 /// EnterTokenStream - Add a "macro" context to the top of the include stack,
182 /// which will cause the lexer to start returning the specified tokens.
183 ///
184 /// If DisableMacroExpansion is true, tokens lexed from the token stream will
185 /// not be subject to further macro expansion.  Otherwise, these tokens will
186 /// be re-macro-expanded when/if expansion is enabled.
187 ///
188 /// If OwnsTokens is false, this method assumes that the specified stream of
189 /// tokens has a permanent owner somewhere, so they do not need to be copied.
190 /// If it is true, it assumes the array of tokens is allocated with new[] and
191 /// must be freed.
192 ///
193 void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
194                                     bool DisableMacroExpansion,
195                                     bool OwnsTokens) {
196   // Create a macro expander to expand from the specified token stream.
197   TokenLexer *TokLexer;
198   if (NumCachedTokenLexers == 0) {
199     TokLexer = new TokenLexer(Toks, NumToks, DisableMacroExpansion,
200                               OwnsTokens, *this);
201   } else {
202     TokLexer = TokenLexerCache[--NumCachedTokenLexers];
203     TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
204   }
205 
206   // Save our current state.
207   PushIncludeMacroStack();
208   CurDirLookup = 0;
209   CurTokenLexer.reset(TokLexer);
210   if (CurLexerKind != CLK_LexAfterModuleImport)
211     CurLexerKind = CLK_TokenLexer;
212 }
213 
214 /// \brief Compute the relative path that names the given file relative to
215 /// the given directory.
216 static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir,
217                                 const FileEntry *File,
218                                 SmallString<128> &Result) {
219   Result.clear();
220 
221   StringRef FilePath = File->getDir()->getName();
222   StringRef Path = FilePath;
223   while (!Path.empty()) {
224     if (const DirectoryEntry *CurDir = FM.getDirectory(Path)) {
225       if (CurDir == Dir) {
226         Result = FilePath.substr(Path.size());
227         llvm::sys::path::append(Result,
228                                 llvm::sys::path::filename(File->getName()));
229         return;
230       }
231     }
232 
233     Path = llvm::sys::path::parent_path(Path);
234   }
235 
236   Result = File->getName();
237 }
238 
239 void Preprocessor::PropagateLineStartLeadingSpaceInfo(Token &Result) {
240   if (CurTokenLexer) {
241     CurTokenLexer->PropagateLineStartLeadingSpaceInfo(Result);
242     return;
243   }
244   if (CurLexer) {
245     CurLexer->PropagateLineStartLeadingSpaceInfo(Result);
246     return;
247   }
248   // FIXME: Handle other kinds of lexers?  It generally shouldn't matter,
249   // but it might if they're empty?
250 }
251 
252 /// \brief Determine the location to use as the end of the buffer for a lexer.
253 ///
254 /// If the file ends with a newline, form the EOF token on the newline itself,
255 /// rather than "on the line following it", which doesn't exist.  This makes
256 /// diagnostics relating to the end of file include the last file that the user
257 /// actually typed, which is goodness.
258 const char *Preprocessor::getCurLexerEndPos() {
259   const char *EndPos = CurLexer->BufferEnd;
260   if (EndPos != CurLexer->BufferStart &&
261       (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
262     --EndPos;
263 
264     // Handle \n\r and \r\n:
265     if (EndPos != CurLexer->BufferStart &&
266         (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
267         EndPos[-1] != EndPos[0])
268       --EndPos;
269   }
270 
271   return EndPos;
272 }
273 
274 
275 /// HandleEndOfFile - This callback is invoked when the lexer hits the end of
276 /// the current file.  This either returns the EOF token or pops a level off
277 /// the include stack and keeps going.
278 bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
279   assert(!CurTokenLexer &&
280          "Ending a file when currently in a macro!");
281 
282   // See if this file had a controlling macro.
283   if (CurPPLexer) {  // Not ending a macro, ignore it.
284     if (const IdentifierInfo *ControllingMacro =
285           CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
286       // Okay, this has a controlling macro, remember in HeaderFileInfo.
287       if (const FileEntry *FE =
288             SourceMgr.getFileEntryForID(CurPPLexer->getFileID())) {
289         HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
290         if (const IdentifierInfo *DefinedMacro =
291               CurPPLexer->MIOpt.GetDefinedMacro()) {
292           if (!ControllingMacro->hasMacroDefinition() &&
293               DefinedMacro != ControllingMacro &&
294               HeaderInfo.FirstTimeLexingFile(FE)) {
295 
296             // If the edit distance between the two macros is more than 50%,
297             // DefinedMacro may not be header guard, or can be header guard of
298             // another header file. Therefore, it maybe defining something
299             // completely different. This can be observed in the wild when
300             // handling feature macros or header guards in different files.
301 
302             const StringRef ControllingMacroName = ControllingMacro->getName();
303             const StringRef DefinedMacroName = DefinedMacro->getName();
304             const size_t MaxHalfLength = std::max(ControllingMacroName.size(),
305                                                   DefinedMacroName.size()) / 2;
306             const unsigned ED = ControllingMacroName.edit_distance(
307                 DefinedMacroName, true, MaxHalfLength);
308             if (ED <= MaxHalfLength) {
309               // Emit a warning for a bad header guard.
310               Diag(CurPPLexer->MIOpt.GetMacroLocation(),
311                    diag::warn_header_guard)
312                   << CurPPLexer->MIOpt.GetMacroLocation() << ControllingMacro;
313               Diag(CurPPLexer->MIOpt.GetDefinedLocation(),
314                    diag::note_header_guard)
315                   << CurPPLexer->MIOpt.GetDefinedLocation() << DefinedMacro
316                   << ControllingMacro
317                   << FixItHint::CreateReplacement(
318                          CurPPLexer->MIOpt.GetDefinedLocation(),
319                          ControllingMacro->getName());
320             }
321           }
322         }
323       }
324     }
325   }
326 
327   // Complain about reaching a true EOF within arc_cf_code_audited.
328   // We don't want to complain about reaching the end of a macro
329   // instantiation or a _Pragma.
330   if (PragmaARCCFCodeAuditedLoc.isValid() &&
331       !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
332     Diag(PragmaARCCFCodeAuditedLoc, diag::err_pp_eof_in_arc_cf_code_audited);
333 
334     // Recover by leaving immediately.
335     PragmaARCCFCodeAuditedLoc = SourceLocation();
336   }
337 
338   // If this is a #include'd file, pop it off the include stack and continue
339   // lexing the #includer file.
340   if (!IncludeMacroStack.empty()) {
341 
342     // If we lexed the code-completion file, act as if we reached EOF.
343     if (isCodeCompletionEnabled() && CurPPLexer &&
344         SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==
345             CodeCompletionFileLoc) {
346       if (CurLexer) {
347         Result.startToken();
348         CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
349         CurLexer.reset();
350       } else {
351         assert(CurPTHLexer && "Got EOF but no current lexer set!");
352         CurPTHLexer->getEOF(Result);
353         CurPTHLexer.reset();
354       }
355 
356       CurPPLexer = 0;
357       return true;
358     }
359 
360     if (!isEndOfMacro && CurPPLexer &&
361         SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid()) {
362       // Notify SourceManager to record the number of FileIDs that were created
363       // during lexing of the #include'd file.
364       unsigned NumFIDs =
365           SourceMgr.local_sloc_entry_size() -
366           CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/;
367       SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);
368     }
369 
370     FileID ExitedFID;
371     if (Callbacks && !isEndOfMacro && CurPPLexer)
372       ExitedFID = CurPPLexer->getFileID();
373 
374     // If this file corresponded to a submodule, notify the parser that we've
375     // left that submodule.
376     bool LeavingSubmodule = CurIsSubmodule && CurLexer;
377     if (LeavingSubmodule) {
378       const char *EndPos = getCurLexerEndPos();
379       Result.startToken();
380       CurLexer->BufferPtr = EndPos;
381       CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
382       Result.setAnnotationEndLoc(Result.getLocation());
383       Result.setAnnotationValue(0);
384     }
385 
386     // We're done with the #included file.
387     RemoveTopOfLexerStack();
388 
389     // Propagate info about start-of-line/leading white-space/etc.
390     PropagateLineStartLeadingSpaceInfo(Result);
391 
392     // Notify the client, if desired, that we are in a new source file.
393     if (Callbacks && !isEndOfMacro && CurPPLexer) {
394       SrcMgr::CharacteristicKind FileType =
395         SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
396       Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
397                              PPCallbacks::ExitFile, FileType, ExitedFID);
398     }
399 
400     // Client should lex another token unless we generated an EOM.
401     return LeavingSubmodule;
402   }
403 
404   // If this is the end of the main file, form an EOF token.
405   if (CurLexer) {
406     const char *EndPos = getCurLexerEndPos();
407     Result.startToken();
408     CurLexer->BufferPtr = EndPos;
409     CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
410 
411     if (isCodeCompletionEnabled()) {
412       // Inserting the code-completion point increases the source buffer by 1,
413       // but the main FileID was created before inserting the point.
414       // Compensate by reducing the EOF location by 1, otherwise the location
415       // will point to the next FileID.
416       // FIXME: This is hacky, the code-completion point should probably be
417       // inserted before the main FileID is created.
418       if (CurLexer->getFileLoc() == CodeCompletionFileLoc)
419         Result.setLocation(Result.getLocation().getLocWithOffset(-1));
420     }
421 
422     if (!isIncrementalProcessingEnabled())
423       // We're done with lexing.
424       CurLexer.reset();
425   } else {
426     assert(CurPTHLexer && "Got EOF but no current lexer set!");
427     CurPTHLexer->getEOF(Result);
428     CurPTHLexer.reset();
429   }
430 
431   if (!isIncrementalProcessingEnabled())
432     CurPPLexer = 0;
433 
434   // This is the end of the top-level file. 'WarnUnusedMacroLocs' has collected
435   // all macro locations that we need to warn because they are not used.
436   for (WarnUnusedMacroLocsTy::iterator
437          I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end(); I!=E; ++I)
438     Diag(*I, diag::pp_macro_not_used);
439 
440   // If we are building a module that has an umbrella header, make sure that
441   // each of the headers within the directory covered by the umbrella header
442   // was actually included by the umbrella header.
443   if (Module *Mod = getCurrentModule()) {
444     if (Mod->getUmbrellaHeader()) {
445       SourceLocation StartLoc
446         = SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
447 
448       if (getDiagnostics().getDiagnosticLevel(
449             diag::warn_uncovered_module_header,
450             StartLoc) != DiagnosticsEngine::Ignored) {
451         ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
452         typedef llvm::sys::fs::recursive_directory_iterator
453           recursive_directory_iterator;
454         const DirectoryEntry *Dir = Mod->getUmbrellaDir();
455         llvm::error_code EC;
456         for (recursive_directory_iterator Entry(Dir->getName(), EC), End;
457              Entry != End && !EC; Entry.increment(EC)) {
458           using llvm::StringSwitch;
459 
460           // Check whether this entry has an extension typically associated with
461           // headers.
462           if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->path()))
463                  .Cases(".h", ".H", ".hh", ".hpp", true)
464                  .Default(false))
465             continue;
466 
467           if (const FileEntry *Header = getFileManager().getFile(Entry->path()))
468             if (!getSourceManager().hasFileInfo(Header)) {
469               if (!ModMap.isHeaderInUnavailableModule(Header)) {
470                 // Find the relative path that would access this header.
471                 SmallString<128> RelativePath;
472                 computeRelativePath(FileMgr, Dir, Header, RelativePath);
473                 Diag(StartLoc, diag::warn_uncovered_module_header)
474                   << Mod->getFullModuleName() << RelativePath;
475               }
476             }
477         }
478       }
479     }
480 
481     // Check whether there are any headers that were included, but not
482     // mentioned at all in the module map. Such headers
483     SourceLocation StartLoc
484       = SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
485     if (getDiagnostics().getDiagnosticLevel(diag::warn_forgotten_module_header,
486                                             StartLoc)
487           != DiagnosticsEngine::Ignored) {
488       ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
489       for (unsigned I = 0, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
490         // We only care about file entries.
491         const SrcMgr::SLocEntry &Entry = SourceMgr.getLocalSLocEntry(I);
492         if (!Entry.isFile())
493           continue;
494 
495         // Dig out the actual file.
496         const FileEntry *File = Entry.getFile().getContentCache()->OrigEntry;
497         if (!File)
498           continue;
499 
500         // If it's not part of a module and not unknown, complain.
501         if (!ModMap.findModuleForHeader(File) &&
502             !ModMap.isHeaderInUnavailableModule(File)) {
503           Diag(StartLoc, diag::warn_forgotten_module_header)
504             << File->getName() << Mod->getFullModuleName();
505         }
506       }
507     }
508   }
509 
510   return true;
511 }
512 
513 /// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
514 /// hits the end of its token stream.
515 bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
516   assert(CurTokenLexer && !CurPPLexer &&
517          "Ending a macro when currently in a #include file!");
518 
519   if (!MacroExpandingLexersStack.empty() &&
520       MacroExpandingLexersStack.back().first == CurTokenLexer.get())
521     removeCachedMacroExpandedTokensOfLastLexer();
522 
523   // Delete or cache the now-dead macro expander.
524   if (NumCachedTokenLexers == TokenLexerCacheSize)
525     CurTokenLexer.reset();
526   else
527     TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
528 
529   // Handle this like a #include file being popped off the stack.
530   return HandleEndOfFile(Result, true);
531 }
532 
533 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
534 /// lexer stack.  This should only be used in situations where the current
535 /// state of the top-of-stack lexer is unknown.
536 void Preprocessor::RemoveTopOfLexerStack() {
537   assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
538 
539   if (CurTokenLexer) {
540     // Delete or cache the now-dead macro expander.
541     if (NumCachedTokenLexers == TokenLexerCacheSize)
542       CurTokenLexer.reset();
543     else
544       TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
545   }
546 
547   PopIncludeMacroStack();
548 }
549 
550 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a
551 /// comment (/##/) in microsoft mode, this method handles updating the current
552 /// state, returning the token on the next source line.
553 void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
554   assert(CurTokenLexer && !CurPPLexer &&
555          "Pasted comment can only be formed from macro");
556 
557   // We handle this by scanning for the closest real lexer, switching it to
558   // raw mode and preprocessor mode.  This will cause it to return \n as an
559   // explicit EOD token.
560   PreprocessorLexer *FoundLexer = 0;
561   bool LexerWasInPPMode = false;
562   for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
563     IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
564     if (ISI.ThePPLexer == 0) continue;  // Scan for a real lexer.
565 
566     // Once we find a real lexer, mark it as raw mode (disabling macro
567     // expansions) and preprocessor mode (return EOD).  We know that the lexer
568     // was *not* in raw mode before, because the macro that the comment came
569     // from was expanded.  However, it could have already been in preprocessor
570     // mode (#if COMMENT) in which case we have to return it to that mode and
571     // return EOD.
572     FoundLexer = ISI.ThePPLexer;
573     FoundLexer->LexingRawMode = true;
574     LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
575     FoundLexer->ParsingPreprocessorDirective = true;
576     break;
577   }
578 
579   // Okay, we either found and switched over the lexer, or we didn't find a
580   // lexer.  In either case, finish off the macro the comment came from, getting
581   // the next token.
582   if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
583 
584   // Discarding comments as long as we don't have EOF or EOD.  This 'comments
585   // out' the rest of the line, including any tokens that came from other macros
586   // that were active, as in:
587   //  #define submacro a COMMENT b
588   //    submacro c
589   // which should lex to 'a' only: 'b' and 'c' should be removed.
590   while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof))
591     Lex(Tok);
592 
593   // If we got an eod token, then we successfully found the end of the line.
594   if (Tok.is(tok::eod)) {
595     assert(FoundLexer && "Can't get end of line without an active lexer");
596     // Restore the lexer back to normal mode instead of raw mode.
597     FoundLexer->LexingRawMode = false;
598 
599     // If the lexer was already in preprocessor mode, just return the EOD token
600     // to finish the preprocessor line.
601     if (LexerWasInPPMode) return;
602 
603     // Otherwise, switch out of PP mode and return the next lexed token.
604     FoundLexer->ParsingPreprocessorDirective = false;
605     return Lex(Tok);
606   }
607 
608   // If we got an EOF token, then we reached the end of the token stream but
609   // didn't find an explicit \n.  This can only happen if there was no lexer
610   // active (an active lexer would return EOD at EOF if there was no \n in
611   // preprocessor directive mode), so just return EOF as our token.
612   assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");
613 }
614