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