1193326Sed//===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed// This file implements pieces of the Preprocessor interface that manage the
11193326Sed// current lexer stack.
12193326Sed//
13193326Sed//===----------------------------------------------------------------------===//
14193326Sed
15193326Sed#include "clang/Lex/Preprocessor.h"
16249423Sdim#include "clang/Basic/FileManager.h"
17249423Sdim#include "clang/Basic/SourceManager.h"
18193326Sed#include "clang/Lex/HeaderSearch.h"
19249423Sdim#include "clang/Lex/LexDiagnostic.h"
20193326Sed#include "clang/Lex/MacroInfo.h"
21249423Sdim#include "llvm/ADT/StringSwitch.h"
22234353Sdim#include "llvm/Support/FileSystem.h"
23193326Sed#include "llvm/Support/MemoryBuffer.h"
24263508Sdim#include "llvm/Support/Path.h"
25193326Sedusing namespace clang;
26193326Sed
27193326SedPPCallbacks::~PPCallbacks() {}
28193326Sed
29193326Sed//===----------------------------------------------------------------------===//
30193326Sed// Miscellaneous Methods.
31193326Sed//===----------------------------------------------------------------------===//
32193326Sed
33193326Sed/// isInPrimaryFile - Return true if we're in the top-level file, not in a
34239462Sdim/// \#include.  This looks through macro expansions and active _Pragma lexers.
35193326Sedbool Preprocessor::isInPrimaryFile() const {
36193326Sed  if (IsFileLexer())
37193326Sed    return IncludeMacroStack.empty();
38198092Srdivacky
39193326Sed  // If there are any stacked lexers, we're in a #include.
40193326Sed  assert(IsFileLexer(IncludeMacroStack[0]) &&
41193326Sed         "Top level include stack isn't our primary lexer?");
42193326Sed  for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
43193326Sed    if (IsFileLexer(IncludeMacroStack[i]))
44193326Sed      return false;
45193326Sed  return true;
46193326Sed}
47193326Sed
48193326Sed/// getCurrentLexer - Return the current file lexer being lexed from.  Note
49193326Sed/// that this ignores any potentially active macro expansions and _Pragma
50193326Sed/// expansions going on at the time.
51193326SedPreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
52193326Sed  if (IsFileLexer())
53193326Sed    return CurPPLexer;
54198092Srdivacky
55193326Sed  // Look for a stacked lexer.
56193326Sed  for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
57193326Sed    const IncludeStackInfo& ISI = IncludeMacroStack[i-1];
58193326Sed    if (IsFileLexer(ISI))
59193326Sed      return ISI.ThePPLexer;
60193326Sed  }
61193326Sed  return 0;
62193326Sed}
63193326Sed
64193326Sed
65193326Sed//===----------------------------------------------------------------------===//
66193326Sed// Methods for Entering and Callbacks for leaving various contexts
67193326Sed//===----------------------------------------------------------------------===//
68193326Sed
69193326Sed/// EnterSourceFile - Add a source file to the top of the include stack and
70199990Srdivacky/// start lexing tokens from it instead of the current buffer.
71207619Srdivackyvoid Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir,
72207619Srdivacky                                   SourceLocation Loc) {
73263508Sdim  assert(!CurTokenLexer && "Cannot #include a file inside a macro!");
74193326Sed  ++NumEnteredSourceFiles;
75198092Srdivacky
76193326Sed  if (MaxIncludeStackDepth < IncludeMacroStack.size())
77193326Sed    MaxIncludeStackDepth = IncludeMacroStack.size();
78193326Sed
79193326Sed  if (PTH) {
80199990Srdivacky    if (PTHLexer *PL = PTH->CreateLexer(FID)) {
81199990Srdivacky      EnterSourceFileWithPTH(PL, CurDir);
82207619Srdivacky      return;
83199990Srdivacky    }
84193326Sed  }
85199990Srdivacky
86199990Srdivacky  // Get the MemoryBuffer for this FID, if it fails, we fail.
87205408Srdivacky  bool Invalid = false;
88207619Srdivacky  const llvm::MemoryBuffer *InputFile =
89207619Srdivacky    getSourceManager().getBuffer(FID, Loc, &Invalid);
90207619Srdivacky  if (Invalid) {
91207619Srdivacky    SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
92207619Srdivacky    Diag(Loc, diag::err_pp_error_opening_file)
93207619Srdivacky      << std::string(SourceMgr.getBufferName(FileStart)) << "";
94207619Srdivacky    return;
95207619Srdivacky  }
96226633Sdim
97226633Sdim  if (isCodeCompletionEnabled() &&
98226633Sdim      SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) {
99226633Sdim    CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID);
100226633Sdim    CodeCompletionLoc =
101226633Sdim        CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset);
102226633Sdim  }
103226633Sdim
104199990Srdivacky  EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir);
105207619Srdivacky  return;
106198092Srdivacky}
107193326Sed
108193326Sed/// EnterSourceFileWithLexer - Add a source file to the top of the include stack
109193326Sed///  and start lexing tokens from it instead of the current buffer.
110198092Srdivackyvoid Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
111193326Sed                                            const DirectoryLookup *CurDir) {
112198092Srdivacky
113193326Sed  // Add the current lexer to the include stack.
114193326Sed  if (CurPPLexer || CurTokenLexer)
115193326Sed    PushIncludeMacroStack();
116193326Sed
117193326Sed  CurLexer.reset(TheLexer);
118193326Sed  CurPPLexer = TheLexer;
119193326Sed  CurDirLookup = CurDir;
120226633Sdim  if (CurLexerKind != CLK_LexAfterModuleImport)
121226633Sdim    CurLexerKind = CLK_Lexer;
122226633Sdim
123193326Sed  // Notify the client, if desired, that we are in a new source file.
124193326Sed  if (Callbacks && !CurLexer->Is_PragmaLexer) {
125193326Sed    SrcMgr::CharacteristicKind FileType =
126193326Sed       SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
127198092Srdivacky
128193326Sed    Callbacks->FileChanged(CurLexer->getFileLoc(),
129193326Sed                           PPCallbacks::EnterFile, FileType);
130193326Sed  }
131193326Sed}
132193326Sed
133193326Sed/// EnterSourceFileWithPTH - Add a source file to the top of the include stack
134193326Sed/// and start getting tokens from it using the PTH cache.
135198092Srdivackyvoid Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL,
136193326Sed                                          const DirectoryLookup *CurDir) {
137198092Srdivacky
138193326Sed  if (CurPPLexer || CurTokenLexer)
139193326Sed    PushIncludeMacroStack();
140193326Sed
141193326Sed  CurDirLookup = CurDir;
142193326Sed  CurPTHLexer.reset(PL);
143193326Sed  CurPPLexer = CurPTHLexer.get();
144226633Sdim  if (CurLexerKind != CLK_LexAfterModuleImport)
145226633Sdim    CurLexerKind = CLK_PTHLexer;
146226633Sdim
147193326Sed  // Notify the client, if desired, that we are in a new source file.
148193326Sed  if (Callbacks) {
149193326Sed    FileID FID = CurPPLexer->getFileID();
150193326Sed    SourceLocation EnterLoc = SourceMgr.getLocForStartOfFile(FID);
151193326Sed    SrcMgr::CharacteristicKind FileType =
152193326Sed      SourceMgr.getFileCharacteristic(EnterLoc);
153193326Sed    Callbacks->FileChanged(EnterLoc, PPCallbacks::EnterFile, FileType);
154193326Sed  }
155193326Sed}
156193326Sed
157193326Sed/// EnterMacro - Add a Macro to the top of the include stack and start lexing
158193326Sed/// tokens from it instead of the current buffer.
159193326Sedvoid Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
160243830Sdim                              MacroInfo *Macro, MacroArgs *Args) {
161249423Sdim  TokenLexer *TokLexer;
162193326Sed  if (NumCachedTokenLexers == 0) {
163249423Sdim    TokLexer = new TokenLexer(Tok, ILEnd, Macro, Args, *this);
164193326Sed  } else {
165249423Sdim    TokLexer = TokenLexerCache[--NumCachedTokenLexers];
166249423Sdim    TokLexer->Init(Tok, ILEnd, Macro, Args);
167193326Sed  }
168249423Sdim
169249423Sdim  PushIncludeMacroStack();
170249423Sdim  CurDirLookup = 0;
171249423Sdim  CurTokenLexer.reset(TokLexer);
172226633Sdim  if (CurLexerKind != CLK_LexAfterModuleImport)
173226633Sdim    CurLexerKind = CLK_TokenLexer;
174193326Sed}
175193326Sed
176193326Sed/// EnterTokenStream - Add a "macro" context to the top of the include stack,
177193326Sed/// which will cause the lexer to start returning the specified tokens.
178193326Sed///
179193326Sed/// If DisableMacroExpansion is true, tokens lexed from the token stream will
180193326Sed/// not be subject to further macro expansion.  Otherwise, these tokens will
181193326Sed/// be re-macro-expanded when/if expansion is enabled.
182193326Sed///
183193326Sed/// If OwnsTokens is false, this method assumes that the specified stream of
184193326Sed/// tokens has a permanent owner somewhere, so they do not need to be copied.
185193326Sed/// If it is true, it assumes the array of tokens is allocated with new[] and
186193326Sed/// must be freed.
187193326Sed///
188193326Sedvoid Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
189193326Sed                                    bool DisableMacroExpansion,
190193326Sed                                    bool OwnsTokens) {
191193326Sed  // Create a macro expander to expand from the specified token stream.
192249423Sdim  TokenLexer *TokLexer;
193193326Sed  if (NumCachedTokenLexers == 0) {
194249423Sdim    TokLexer = new TokenLexer(Toks, NumToks, DisableMacroExpansion,
195249423Sdim                              OwnsTokens, *this);
196193326Sed  } else {
197249423Sdim    TokLexer = TokenLexerCache[--NumCachedTokenLexers];
198249423Sdim    TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
199193326Sed  }
200249423Sdim
201249423Sdim  // Save our current state.
202249423Sdim  PushIncludeMacroStack();
203249423Sdim  CurDirLookup = 0;
204249423Sdim  CurTokenLexer.reset(TokLexer);
205226633Sdim  if (CurLexerKind != CLK_LexAfterModuleImport)
206226633Sdim    CurLexerKind = CLK_TokenLexer;
207193326Sed}
208193326Sed
209234353Sdim/// \brief Compute the relative path that names the given file relative to
210234353Sdim/// the given directory.
211234353Sdimstatic void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir,
212234353Sdim                                const FileEntry *File,
213234353Sdim                                SmallString<128> &Result) {
214234353Sdim  Result.clear();
215234353Sdim
216234353Sdim  StringRef FilePath = File->getDir()->getName();
217234353Sdim  StringRef Path = FilePath;
218234353Sdim  while (!Path.empty()) {
219234353Sdim    if (const DirectoryEntry *CurDir = FM.getDirectory(Path)) {
220234353Sdim      if (CurDir == Dir) {
221234353Sdim        Result = FilePath.substr(Path.size());
222234353Sdim        llvm::sys::path::append(Result,
223234353Sdim                                llvm::sys::path::filename(File->getName()));
224234353Sdim        return;
225234353Sdim      }
226234353Sdim    }
227234353Sdim
228234353Sdim    Path = llvm::sys::path::parent_path(Path);
229234353Sdim  }
230234353Sdim
231234353Sdim  Result = File->getName();
232234353Sdim}
233234353Sdim
234263508Sdimvoid Preprocessor::PropagateLineStartLeadingSpaceInfo(Token &Result) {
235263508Sdim  if (CurTokenLexer) {
236263508Sdim    CurTokenLexer->PropagateLineStartLeadingSpaceInfo(Result);
237263508Sdim    return;
238263508Sdim  }
239263508Sdim  if (CurLexer) {
240263508Sdim    CurLexer->PropagateLineStartLeadingSpaceInfo(Result);
241263508Sdim    return;
242263508Sdim  }
243263508Sdim  // FIXME: Handle other kinds of lexers?  It generally shouldn't matter,
244263508Sdim  // but it might if they're empty?
245263508Sdim}
246263508Sdim
247193326Sed/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
248193326Sed/// the current file.  This either returns the EOF token or pops a level off
249193326Sed/// the include stack and keeps going.
250193326Sedbool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
251193326Sed  assert(!CurTokenLexer &&
252193326Sed         "Ending a file when currently in a macro!");
253198092Srdivacky
254193326Sed  // See if this file had a controlling macro.
255193326Sed  if (CurPPLexer) {  // Not ending a macro, ignore it.
256198092Srdivacky    if (const IdentifierInfo *ControllingMacro =
257193326Sed          CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
258193326Sed      // Okay, this has a controlling macro, remember in HeaderFileInfo.
259198092Srdivacky      if (const FileEntry *FE =
260263508Sdim            SourceMgr.getFileEntryForID(CurPPLexer->getFileID())) {
261193326Sed        HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
262263508Sdim        if (const IdentifierInfo *DefinedMacro =
263263508Sdim              CurPPLexer->MIOpt.GetDefinedMacro()) {
264263508Sdim          if (!ControllingMacro->hasMacroDefinition() &&
265263508Sdim              DefinedMacro != ControllingMacro &&
266263508Sdim              HeaderInfo.FirstTimeLexingFile(FE)) {
267263508Sdim
268263508Sdim            // If the edit distance between the two macros is more than 50%,
269263508Sdim            // DefinedMacro may not be header guard, or can be header guard of
270263508Sdim            // another header file. Therefore, it maybe defining something
271263508Sdim            // completely different. This can be observed in the wild when
272263508Sdim            // handling feature macros or header guards in different files.
273263508Sdim
274263508Sdim            const StringRef ControllingMacroName = ControllingMacro->getName();
275263508Sdim            const StringRef DefinedMacroName = DefinedMacro->getName();
276263508Sdim            const size_t MaxHalfLength = std::max(ControllingMacroName.size(),
277263508Sdim                                                  DefinedMacroName.size()) / 2;
278263508Sdim            const unsigned ED = ControllingMacroName.edit_distance(
279263508Sdim                DefinedMacroName, true, MaxHalfLength);
280263508Sdim            if (ED <= MaxHalfLength) {
281263508Sdim              // Emit a warning for a bad header guard.
282263508Sdim              Diag(CurPPLexer->MIOpt.GetMacroLocation(),
283263508Sdim                   diag::warn_header_guard)
284263508Sdim                  << CurPPLexer->MIOpt.GetMacroLocation() << ControllingMacro;
285263508Sdim              Diag(CurPPLexer->MIOpt.GetDefinedLocation(),
286263508Sdim                   diag::note_header_guard)
287263508Sdim                  << CurPPLexer->MIOpt.GetDefinedLocation() << DefinedMacro
288263508Sdim                  << ControllingMacro
289263508Sdim                  << FixItHint::CreateReplacement(
290263508Sdim                         CurPPLexer->MIOpt.GetDefinedLocation(),
291263508Sdim                         ControllingMacro->getName());
292263508Sdim            }
293263508Sdim          }
294263508Sdim        }
295263508Sdim      }
296193326Sed    }
297193326Sed  }
298198092Srdivacky
299234353Sdim  // Complain about reaching a true EOF within arc_cf_code_audited.
300234353Sdim  // We don't want to complain about reaching the end of a macro
301234353Sdim  // instantiation or a _Pragma.
302234353Sdim  if (PragmaARCCFCodeAuditedLoc.isValid() &&
303234353Sdim      !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
304226633Sdim    Diag(PragmaARCCFCodeAuditedLoc, diag::err_pp_eof_in_arc_cf_code_audited);
305226633Sdim
306226633Sdim    // Recover by leaving immediately.
307226633Sdim    PragmaARCCFCodeAuditedLoc = SourceLocation();
308226633Sdim  }
309226633Sdim
310193326Sed  // If this is a #include'd file, pop it off the include stack and continue
311193326Sed  // lexing the #includer file.
312193326Sed  if (!IncludeMacroStack.empty()) {
313226633Sdim
314226633Sdim    // If we lexed the code-completion file, act as if we reached EOF.
315226633Sdim    if (isCodeCompletionEnabled() && CurPPLexer &&
316226633Sdim        SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==
317226633Sdim            CodeCompletionFileLoc) {
318226633Sdim      if (CurLexer) {
319226633Sdim        Result.startToken();
320226633Sdim        CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
321226633Sdim        CurLexer.reset();
322226633Sdim      } else {
323226633Sdim        assert(CurPTHLexer && "Got EOF but no current lexer set!");
324226633Sdim        CurPTHLexer->getEOF(Result);
325226633Sdim        CurPTHLexer.reset();
326226633Sdim      }
327226633Sdim
328226633Sdim      CurPPLexer = 0;
329226633Sdim      return true;
330226633Sdim    }
331226633Sdim
332226633Sdim    if (!isEndOfMacro && CurPPLexer &&
333226633Sdim        SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid()) {
334226633Sdim      // Notify SourceManager to record the number of FileIDs that were created
335226633Sdim      // during lexing of the #include'd file.
336226633Sdim      unsigned NumFIDs =
337226633Sdim          SourceMgr.local_sloc_entry_size() -
338226633Sdim          CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/;
339226633Sdim      SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);
340226633Sdim    }
341226633Sdim
342226633Sdim    FileID ExitedFID;
343226633Sdim    if (Callbacks && !isEndOfMacro && CurPPLexer)
344226633Sdim      ExitedFID = CurPPLexer->getFileID();
345226633Sdim
346193326Sed    // We're done with the #included file.
347193326Sed    RemoveTopOfLexerStack();
348193326Sed
349263508Sdim    // Propagate info about start-of-line/leading white-space/etc.
350263508Sdim    PropagateLineStartLeadingSpaceInfo(Result);
351263508Sdim
352193326Sed    // Notify the client, if desired, that we are in a new source file.
353193326Sed    if (Callbacks && !isEndOfMacro && CurPPLexer) {
354193326Sed      SrcMgr::CharacteristicKind FileType =
355193326Sed        SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
356193326Sed      Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
357226633Sdim                             PPCallbacks::ExitFile, FileType, ExitedFID);
358193326Sed    }
359193326Sed
360193326Sed    // Client should lex another token.
361193326Sed    return false;
362193326Sed  }
363193326Sed
364193326Sed  // If the file ends with a newline, form the EOF token on the newline itself,
365193326Sed  // rather than "on the line following it", which doesn't exist.  This makes
366193326Sed  // diagnostics relating to the end of file include the last file that the user
367193326Sed  // actually typed, which is goodness.
368193326Sed  if (CurLexer) {
369193326Sed    const char *EndPos = CurLexer->BufferEnd;
370198092Srdivacky    if (EndPos != CurLexer->BufferStart &&
371193326Sed        (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
372193326Sed      --EndPos;
373198092Srdivacky
374193326Sed      // Handle \n\r and \r\n:
375198092Srdivacky      if (EndPos != CurLexer->BufferStart &&
376193326Sed          (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
377193326Sed          EndPos[-1] != EndPos[0])
378193326Sed        --EndPos;
379193326Sed    }
380198092Srdivacky
381193326Sed    Result.startToken();
382193326Sed    CurLexer->BufferPtr = EndPos;
383193326Sed    CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
384198092Srdivacky
385249423Sdim    if (isCodeCompletionEnabled()) {
386249423Sdim      // Inserting the code-completion point increases the source buffer by 1,
387249423Sdim      // but the main FileID was created before inserting the point.
388249423Sdim      // Compensate by reducing the EOF location by 1, otherwise the location
389249423Sdim      // will point to the next FileID.
390249423Sdim      // FIXME: This is hacky, the code-completion point should probably be
391249423Sdim      // inserted before the main FileID is created.
392249423Sdim      if (CurLexer->getFileLoc() == CodeCompletionFileLoc)
393249423Sdim        Result.setLocation(Result.getLocation().getLocWithOffset(-1));
394249423Sdim    }
395249423Sdim
396234353Sdim    if (!isIncrementalProcessingEnabled())
397234353Sdim      // We're done with lexing.
398234353Sdim      CurLexer.reset();
399193326Sed  } else {
400193326Sed    assert(CurPTHLexer && "Got EOF but no current lexer set!");
401193326Sed    CurPTHLexer->getEOF(Result);
402193326Sed    CurPTHLexer.reset();
403193326Sed  }
404234353Sdim
405234353Sdim  if (!isIncrementalProcessingEnabled())
406234353Sdim    CurPPLexer = 0;
407198092Srdivacky
408218893Sdim  // This is the end of the top-level file. 'WarnUnusedMacroLocs' has collected
409218893Sdim  // all macro locations that we need to warn because they are not used.
410218893Sdim  for (WarnUnusedMacroLocsTy::iterator
411218893Sdim         I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end(); I!=E; ++I)
412218893Sdim    Diag(*I, diag::pp_macro_not_used);
413206084Srdivacky
414234353Sdim  // If we are building a module that has an umbrella header, make sure that
415234353Sdim  // each of the headers within the directory covered by the umbrella header
416234353Sdim  // was actually included by the umbrella header.
417234353Sdim  if (Module *Mod = getCurrentModule()) {
418234353Sdim    if (Mod->getUmbrellaHeader()) {
419234353Sdim      SourceLocation StartLoc
420234353Sdim        = SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
421234353Sdim
422234353Sdim      if (getDiagnostics().getDiagnosticLevel(
423234353Sdim            diag::warn_uncovered_module_header,
424234353Sdim            StartLoc) != DiagnosticsEngine::Ignored) {
425234353Sdim        ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
426234353Sdim        typedef llvm::sys::fs::recursive_directory_iterator
427234353Sdim          recursive_directory_iterator;
428234353Sdim        const DirectoryEntry *Dir = Mod->getUmbrellaDir();
429234353Sdim        llvm::error_code EC;
430234353Sdim        for (recursive_directory_iterator Entry(Dir->getName(), EC), End;
431234353Sdim             Entry != End && !EC; Entry.increment(EC)) {
432234353Sdim          using llvm::StringSwitch;
433234353Sdim
434234353Sdim          // Check whether this entry has an extension typically associated with
435234353Sdim          // headers.
436234353Sdim          if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->path()))
437234353Sdim                 .Cases(".h", ".H", ".hh", ".hpp", true)
438234353Sdim                 .Default(false))
439234353Sdim            continue;
440234353Sdim
441234353Sdim          if (const FileEntry *Header = getFileManager().getFile(Entry->path()))
442234353Sdim            if (!getSourceManager().hasFileInfo(Header)) {
443234353Sdim              if (!ModMap.isHeaderInUnavailableModule(Header)) {
444234353Sdim                // Find the relative path that would access this header.
445234353Sdim                SmallString<128> RelativePath;
446234353Sdim                computeRelativePath(FileMgr, Dir, Header, RelativePath);
447234353Sdim                Diag(StartLoc, diag::warn_uncovered_module_header)
448249423Sdim                  << Mod->getFullModuleName() << RelativePath;
449234353Sdim              }
450234353Sdim            }
451234353Sdim        }
452234353Sdim      }
453234353Sdim    }
454263508Sdim
455263508Sdim    // Check whether there are any headers that were included, but not
456263508Sdim    // mentioned at all in the module map. Such headers
457263508Sdim    SourceLocation StartLoc
458263508Sdim      = SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
459263508Sdim    if (getDiagnostics().getDiagnosticLevel(diag::warn_forgotten_module_header,
460263508Sdim                                            StartLoc)
461263508Sdim          != DiagnosticsEngine::Ignored) {
462263508Sdim      ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
463263508Sdim      for (unsigned I = 0, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
464263508Sdim        // We only care about file entries.
465263508Sdim        const SrcMgr::SLocEntry &Entry = SourceMgr.getLocalSLocEntry(I);
466263508Sdim        if (!Entry.isFile())
467263508Sdim          continue;
468263508Sdim
469263508Sdim        // Dig out the actual file.
470263508Sdim        const FileEntry *File = Entry.getFile().getContentCache()->OrigEntry;
471263508Sdim        if (!File)
472263508Sdim          continue;
473263508Sdim
474263508Sdim        // If it's not part of a module and not unknown, complain.
475263508Sdim        if (!ModMap.findModuleForHeader(File) &&
476263508Sdim            !ModMap.isHeaderInUnavailableModule(File)) {
477263508Sdim          Diag(StartLoc, diag::warn_forgotten_module_header)
478263508Sdim            << File->getName() << Mod->getFullModuleName();
479263508Sdim        }
480263508Sdim      }
481263508Sdim    }
482234353Sdim  }
483263508Sdim
484193326Sed  return true;
485193326Sed}
486193326Sed
487193326Sed/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
488193326Sed/// hits the end of its token stream.
489193326Sedbool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
490193326Sed  assert(CurTokenLexer && !CurPPLexer &&
491193326Sed         "Ending a macro when currently in a #include file!");
492193326Sed
493224145Sdim  if (!MacroExpandingLexersStack.empty() &&
494224145Sdim      MacroExpandingLexersStack.back().first == CurTokenLexer.get())
495224145Sdim    removeCachedMacroExpandedTokensOfLastLexer();
496224145Sdim
497193326Sed  // Delete or cache the now-dead macro expander.
498193326Sed  if (NumCachedTokenLexers == TokenLexerCacheSize)
499193326Sed    CurTokenLexer.reset();
500193326Sed  else
501193326Sed    TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
502193326Sed
503193326Sed  // Handle this like a #include file being popped off the stack.
504193326Sed  return HandleEndOfFile(Result, true);
505193326Sed}
506193326Sed
507193326Sed/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
508193326Sed/// lexer stack.  This should only be used in situations where the current
509193326Sed/// state of the top-of-stack lexer is unknown.
510193326Sedvoid Preprocessor::RemoveTopOfLexerStack() {
511193326Sed  assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
512198092Srdivacky
513193326Sed  if (CurTokenLexer) {
514193326Sed    // Delete or cache the now-dead macro expander.
515193326Sed    if (NumCachedTokenLexers == TokenLexerCacheSize)
516193326Sed      CurTokenLexer.reset();
517193326Sed    else
518193326Sed      TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
519198092Srdivacky  }
520198092Srdivacky
521193326Sed  PopIncludeMacroStack();
522193326Sed}
523193326Sed
524193326Sed/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
525193326Sed/// comment (/##/) in microsoft mode, this method handles updating the current
526193326Sed/// state, returning the token on the next source line.
527193326Sedvoid Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
528193326Sed  assert(CurTokenLexer && !CurPPLexer &&
529193326Sed         "Pasted comment can only be formed from macro");
530198092Srdivacky
531193326Sed  // We handle this by scanning for the closest real lexer, switching it to
532193326Sed  // raw mode and preprocessor mode.  This will cause it to return \n as an
533221345Sdim  // explicit EOD token.
534193326Sed  PreprocessorLexer *FoundLexer = 0;
535193326Sed  bool LexerWasInPPMode = false;
536193326Sed  for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
537193326Sed    IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
538193326Sed    if (ISI.ThePPLexer == 0) continue;  // Scan for a real lexer.
539198092Srdivacky
540193326Sed    // Once we find a real lexer, mark it as raw mode (disabling macro
541221345Sdim    // expansions) and preprocessor mode (return EOD).  We know that the lexer
542193326Sed    // was *not* in raw mode before, because the macro that the comment came
543193326Sed    // from was expanded.  However, it could have already been in preprocessor
544193326Sed    // mode (#if COMMENT) in which case we have to return it to that mode and
545221345Sdim    // return EOD.
546193326Sed    FoundLexer = ISI.ThePPLexer;
547193326Sed    FoundLexer->LexingRawMode = true;
548193326Sed    LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
549193326Sed    FoundLexer->ParsingPreprocessorDirective = true;
550193326Sed    break;
551193326Sed  }
552198092Srdivacky
553193326Sed  // Okay, we either found and switched over the lexer, or we didn't find a
554193326Sed  // lexer.  In either case, finish off the macro the comment came from, getting
555193326Sed  // the next token.
556193326Sed  if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
557198092Srdivacky
558221345Sdim  // Discarding comments as long as we don't have EOF or EOD.  This 'comments
559193326Sed  // out' the rest of the line, including any tokens that came from other macros
560193326Sed  // that were active, as in:
561193326Sed  //  #define submacro a COMMENT b
562193326Sed  //    submacro c
563193326Sed  // which should lex to 'a' only: 'b' and 'c' should be removed.
564221345Sdim  while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof))
565193326Sed    Lex(Tok);
566198092Srdivacky
567221345Sdim  // If we got an eod token, then we successfully found the end of the line.
568221345Sdim  if (Tok.is(tok::eod)) {
569193326Sed    assert(FoundLexer && "Can't get end of line without an active lexer");
570193326Sed    // Restore the lexer back to normal mode instead of raw mode.
571193326Sed    FoundLexer->LexingRawMode = false;
572198092Srdivacky
573221345Sdim    // If the lexer was already in preprocessor mode, just return the EOD token
574193326Sed    // to finish the preprocessor line.
575193326Sed    if (LexerWasInPPMode) return;
576198092Srdivacky
577193326Sed    // Otherwise, switch out of PP mode and return the next lexed token.
578193326Sed    FoundLexer->ParsingPreprocessorDirective = false;
579193326Sed    return Lex(Tok);
580193326Sed  }
581198092Srdivacky
582193326Sed  // If we got an EOF token, then we reached the end of the token stream but
583193326Sed  // didn't find an explicit \n.  This can only happen if there was no lexer
584221345Sdim  // active (an active lexer would return EOD at EOF if there was no \n in
585193326Sed  // preprocessor directive mode), so just return EOF as our token.
586221345Sdim  assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");
587193326Sed}
588