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