clang-tools  7.0.0
Headers.cpp
Go to the documentation of this file.
1 //===--- Headers.cpp - Include headers ---------------------------*- C++-*-===//
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 #include "Headers.h"
11 #include "Compiler.h"
12 #include "Logger.h"
13 #include "SourceCode.h"
14 #include "clang/Frontend/CompilerInstance.h"
15 #include "clang/Frontend/CompilerInvocation.h"
16 #include "clang/Frontend/FrontendActions.h"
17 #include "clang/Lex/HeaderSearch.h"
18 #include "llvm/Support/Path.h"
19 
20 namespace clang {
21 namespace clangd {
22 namespace {
23 
24 class RecordHeaders : public PPCallbacks {
25 public:
26  RecordHeaders(const SourceManager &SM, IncludeStructure *Out)
27  : SM(SM), Out(Out) {}
28 
29  // Record existing #includes - both written and resolved paths. Only #includes
30  // in the main file are collected.
31  void InclusionDirective(SourceLocation HashLoc, const Token & /*IncludeTok*/,
32  llvm::StringRef FileName, bool IsAngled,
33  CharSourceRange FilenameRange, const FileEntry *File,
34  llvm::StringRef /*SearchPath*/,
35  llvm::StringRef /*RelativePath*/,
36  const Module * /*Imported*/,
37  SrcMgr::CharacteristicKind /*FileType*/) override {
38  if (SM.isInMainFile(HashLoc))
39  Out->MainFileIncludes.push_back({
40  halfOpenToRange(SM, FilenameRange),
41  (IsAngled ? "<" + FileName + ">" : "\"" + FileName + "\"").str(),
42  File ? File->tryGetRealPathName() : "",
43  });
44  if (File) {
45  auto *IncludingFileEntry = SM.getFileEntryForID(SM.getFileID(HashLoc));
46  if (!IncludingFileEntry) {
47  assert(SM.getBufferName(HashLoc).startswith("<") &&
48  "Expected #include location to be a file or <built-in>");
49  // Treat as if included from the main file.
50  IncludingFileEntry = SM.getFileEntryForID(SM.getMainFileID());
51  }
52  Out->recordInclude(IncludingFileEntry->getName(), File->getName(),
53  File->tryGetRealPathName());
54  }
55  }
56 
57 private:
58  const SourceManager &SM;
59  IncludeStructure *Out;
60 };
61 
62 } // namespace
63 
64 bool isLiteralInclude(llvm::StringRef Include) {
65  return Include.startswith("<") || Include.startswith("\"");
66 }
67 
68 bool HeaderFile::valid() const {
69  return (Verbatim && isLiteralInclude(File)) ||
70  (!Verbatim && llvm::sys::path::is_absolute(File));
71 }
72 
73 std::unique_ptr<PPCallbacks>
74 collectIncludeStructureCallback(const SourceManager &SM,
75  IncludeStructure *Out) {
76  return llvm::make_unique<RecordHeaders>(SM, Out);
77 }
78 
79 void IncludeStructure::recordInclude(llvm::StringRef IncludingName,
80  llvm::StringRef IncludedName,
81  llvm::StringRef IncludedRealName) {
82  auto Child = fileIndex(IncludedName);
83  if (!IncludedRealName.empty() && RealPathNames[Child].empty())
84  RealPathNames[Child] = IncludedRealName;
85  auto Parent = fileIndex(IncludingName);
86  IncludeChildren[Parent].push_back(Child);
87 }
88 
89 unsigned IncludeStructure::fileIndex(llvm::StringRef Name) {
90  auto R = NameToIndex.try_emplace(Name, RealPathNames.size());
91  if (R.second)
92  RealPathNames.emplace_back();
93  return R.first->getValue();
94 }
95 
96 llvm::StringMap<unsigned>
97 IncludeStructure::includeDepth(llvm::StringRef Root) const {
98  // Include depth 0 is the main file only.
99  llvm::StringMap<unsigned> Result;
100  Result[Root] = 0;
101  std::vector<unsigned> CurrentLevel;
102  llvm::DenseSet<unsigned> Seen;
103  auto It = NameToIndex.find(Root);
104  if (It != NameToIndex.end()) {
105  CurrentLevel.push_back(It->second);
106  Seen.insert(It->second);
107  }
108 
109  // Each round of BFS traversal finds the next depth level.
110  std::vector<unsigned> PreviousLevel;
111  for (unsigned Level = 1; !CurrentLevel.empty(); ++Level) {
112  PreviousLevel.clear();
113  PreviousLevel.swap(CurrentLevel);
114  for (const auto &Parent : PreviousLevel) {
115  for (const auto &Child : IncludeChildren.lookup(Parent)) {
116  if (Seen.insert(Child).second) {
117  CurrentLevel.push_back(Child);
118  const auto &Name = RealPathNames[Child];
119  // Can't include files if we don't have their real path.
120  if (!Name.empty())
121  Result[Name] = Level;
122  }
123  }
124  }
125  }
126  return Result;
127 }
128 
129 /// FIXME(ioeric): we might not want to insert an absolute include path if the
130 /// path is not shortened.
132  const HeaderFile &DeclaringHeader, const HeaderFile &InsertedHeader) const {
133  assert(DeclaringHeader.valid() && InsertedHeader.valid());
134  if (FileName == DeclaringHeader.File || FileName == InsertedHeader.File)
135  return false;
136  llvm::StringSet<> IncludedHeaders;
137  for (const auto &Inc : Inclusions) {
138  IncludedHeaders.insert(Inc.Written);
139  if (!Inc.Resolved.empty())
140  IncludedHeaders.insert(Inc.Resolved);
141  }
142  auto Included = [&](llvm::StringRef Header) {
143  return IncludedHeaders.find(Header) != IncludedHeaders.end();
144  };
145  return !Included(DeclaringHeader.File) && !Included(InsertedHeader.File);
146 }
147 
148 std::string
150  const HeaderFile &InsertedHeader) const {
151  assert(DeclaringHeader.valid() && InsertedHeader.valid());
152  if (InsertedHeader.Verbatim)
153  return InsertedHeader.File;
154  bool IsSystem = false;
155  std::string Suggested = HeaderSearchInfo.suggestPathToFileForDiagnostics(
156  InsertedHeader.File, BuildDir, &IsSystem);
157  if (IsSystem)
158  Suggested = "<" + Suggested + ">";
159  else
160  Suggested = "\"" + Suggested + "\"";
161  return Suggested;
162 }
163 
164 Optional<TextEdit> IncludeInserter::insert(StringRef VerbatimHeader) const {
165  Optional<TextEdit> Edit = None;
166  if (auto Insertion = Inserter.insert(VerbatimHeader.trim("\"<>"),
167  VerbatimHeader.startswith("<")))
168  Edit = replacementToEdit(Code, *Insertion);
169  return Edit;
170 }
171 
172 } // namespace clangd
173 } // namespace clang
llvm::StringRef Name
bool Verbatim
If this is true, File is a literal string quoted with <> or "" that can be #included directly; otherw...
Definition: Headers.h:36
Documents should not be synced at all.
TextEdit replacementToEdit(StringRef Code, const tooling::Replacement &R)
Definition: SourceCode.cpp:173
bool IsAngled
true if this was an include with angle brackets
bool shouldInsertInclude(const HeaderFile &DeclaringHeader, const HeaderFile &InsertedHeader) const
Checks whether to add an #include of the header into File.
Definition: Headers.cpp:131
PathRef FileName
void recordInclude(llvm::StringRef IncludingName, llvm::StringRef IncludedName, llvm::StringRef IncludedRealName)
Definition: Headers.cpp:79
std::string calculateIncludePath(const HeaderFile &DeclaringHeader, const HeaderFile &InsertedHeader) const
Determines the preferred way to #include a file, taking into account the search path.
Definition: Headers.cpp:149
std::unique_ptr< PPCallbacks > collectIncludeStructureCallback(const SourceManager &SM, IncludeStructure *Out)
Returns a PPCallback that visits all inclusions in the main file.
Definition: Headers.cpp:74
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
llvm::StringMap< unsigned > includeDepth(llvm::StringRef Root) const
Definition: Headers.cpp:97
llvm::Optional< TextEdit > insert(llvm::StringRef VerbatimHeader) const
Calculates an edit that inserts VerbatimHeader into code.
Definition: Headers.cpp:164
Represents a header file to be #include&#39;d.
Definition: Headers.h:32
bool isLiteralInclude(llvm::StringRef Include)
Returns true if Include is literal include like "path" or <path>.
Definition: Headers.cpp:64