clang-tools  8.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 FileKind) override {
38  if (SM.isWrittenInMainFile(HashLoc)) {
39  Out->MainFileIncludes.emplace_back();
40  auto &Inc = Out->MainFileIncludes.back();
41  Inc.R = halfOpenToRange(SM, FilenameRange);
42  Inc.Written =
43  (IsAngled ? "<" + FileName + ">" : "\"" + FileName + "\"").str();
44  Inc.Resolved = File ? File->tryGetRealPathName() : "";
45  Inc.HashOffset = SM.getFileOffset(HashLoc);
46  Inc.FileKind = FileKind;
47  }
48  if (File) {
49  auto *IncludingFileEntry = SM.getFileEntryForID(SM.getFileID(HashLoc));
50  if (!IncludingFileEntry) {
51  assert(SM.getBufferName(HashLoc).startswith("<") &&
52  "Expected #include location to be a file or <built-in>");
53  // Treat as if included from the main file.
54  IncludingFileEntry = SM.getFileEntryForID(SM.getMainFileID());
55  }
56  Out->recordInclude(IncludingFileEntry->getName(), File->getName(),
57  File->tryGetRealPathName());
58  }
59  }
60 
61 private:
62  const SourceManager &SM;
63  IncludeStructure *Out;
64 };
65 
66 } // namespace
67 
68 bool isLiteralInclude(llvm::StringRef Include) {
69  return Include.startswith("<") || Include.startswith("\"");
70 }
71 
72 bool HeaderFile::valid() const {
73  return (Verbatim && isLiteralInclude(File)) ||
74  (!Verbatim && llvm::sys::path::is_absolute(File));
75 }
76 
77 std::unique_ptr<PPCallbacks>
78 collectIncludeStructureCallback(const SourceManager &SM,
79  IncludeStructure *Out) {
80  return llvm::make_unique<RecordHeaders>(SM, Out);
81 }
82 
83 void IncludeStructure::recordInclude(llvm::StringRef IncludingName,
84  llvm::StringRef IncludedName,
85  llvm::StringRef IncludedRealName) {
86  auto Child = fileIndex(IncludedName);
87  if (!IncludedRealName.empty() && RealPathNames[Child].empty())
88  RealPathNames[Child] = IncludedRealName;
89  auto Parent = fileIndex(IncludingName);
90  IncludeChildren[Parent].push_back(Child);
91 }
92 
93 unsigned IncludeStructure::fileIndex(llvm::StringRef Name) {
94  auto R = NameToIndex.try_emplace(Name, RealPathNames.size());
95  if (R.second)
96  RealPathNames.emplace_back();
97  return R.first->getValue();
98 }
99 
100 llvm::StringMap<unsigned>
101 IncludeStructure::includeDepth(llvm::StringRef Root) const {
102  // Include depth 0 is the main file only.
103  llvm::StringMap<unsigned> Result;
104  Result[Root] = 0;
105  std::vector<unsigned> CurrentLevel;
106  llvm::DenseSet<unsigned> Seen;
107  auto It = NameToIndex.find(Root);
108  if (It != NameToIndex.end()) {
109  CurrentLevel.push_back(It->second);
110  Seen.insert(It->second);
111  }
112 
113  // Each round of BFS traversal finds the next depth level.
114  std::vector<unsigned> PreviousLevel;
115  for (unsigned Level = 1; !CurrentLevel.empty(); ++Level) {
116  PreviousLevel.clear();
117  PreviousLevel.swap(CurrentLevel);
118  for (const auto &Parent : PreviousLevel) {
119  for (const auto &Child : IncludeChildren.lookup(Parent)) {
120  if (Seen.insert(Child).second) {
121  CurrentLevel.push_back(Child);
122  const auto &Name = RealPathNames[Child];
123  // Can't include files if we don't have their real path.
124  if (!Name.empty())
125  Result[Name] = Level;
126  }
127  }
128  }
129  }
130  return Result;
131 }
132 
134  IncludedHeaders.insert(Inc.Written);
135  if (!Inc.Resolved.empty())
136  IncludedHeaders.insert(Inc.Resolved);
137 }
138 
139 /// FIXME(ioeric): we might not want to insert an absolute include path if the
140 /// path is not shortened.
142  const HeaderFile &DeclaringHeader, const HeaderFile &InsertedHeader) const {
143  assert(DeclaringHeader.valid() && InsertedHeader.valid());
144  if (FileName == DeclaringHeader.File || FileName == InsertedHeader.File)
145  return false;
146  auto Included = [&](llvm::StringRef Header) {
147  return IncludedHeaders.find(Header) != IncludedHeaders.end();
148  };
149  return !Included(DeclaringHeader.File) && !Included(InsertedHeader.File);
150 }
151 
152 std::string
154  const HeaderFile &InsertedHeader) const {
155  assert(DeclaringHeader.valid() && InsertedHeader.valid());
156  if (InsertedHeader.Verbatim)
157  return InsertedHeader.File;
158  bool IsSystem = false;
159  std::string Suggested = HeaderSearchInfo.suggestPathToFileForDiagnostics(
160  InsertedHeader.File, BuildDir, &IsSystem);
161  if (IsSystem)
162  Suggested = "<" + Suggested + ">";
163  else
164  Suggested = "\"" + Suggested + "\"";
165  return Suggested;
166 }
167 
168 llvm::Optional<TextEdit>
169 IncludeInserter::insert(llvm::StringRef VerbatimHeader) const {
170  llvm::Optional<TextEdit> Edit = None;
171  if (auto Insertion = Inserter.insert(VerbatimHeader.trim("\"<>"),
172  VerbatimHeader.startswith("<")))
173  Edit = replacementToEdit(Code, *Insertion);
174  return Edit;
175 }
176 
177 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Inclusion &Inc) {
178  return OS << Inc.Written << " = "
179  << (Inc.Resolved.empty() ? Inc.Resolved : "[unresolved]") << " at "
180  << Inc.R;
181 }
182 
183 } // namespace clangd
184 } // namespace clang
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.
llvm::Optional< TextEdit > insert(llvm::StringRef VerbatimHeader) const
Calculates an edit that inserts VerbatimHeader into code.
Definition: Headers.cpp:169
std::string Written
Definition: Headers.h:44
void addExisting(const Inclusion &Inc)
Definition: Headers.cpp:133
bool IsAngled
true if this was an include with angle brackets
static constexpr llvm::StringLiteral Name
llvm::Optional< llvm::Expected< tooling::AtomicChanges > > Result
bool shouldInsertInclude(const HeaderFile &DeclaringHeader, const HeaderFile &InsertedHeader) const
Checks whether to add an #include of the header into File.
Definition: Headers.cpp:141
PathRef FileName
void recordInclude(llvm::StringRef IncludingName, llvm::StringRef IncludedName, llvm::StringRef IncludedRealName)
Definition: Headers.cpp:83
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:153
std::unique_ptr< PPCallbacks > collectIncludeStructureCallback(const SourceManager &SM, IncludeStructure *Out)
Returns a PPCallback that visits all inclusions in the main file.
Definition: Headers.cpp:78
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
TextEdit replacementToEdit(llvm::StringRef Code, const tooling::Replacement &R)
Definition: SourceCode.cpp:171
llvm::StringMap< unsigned > includeDepth(llvm::StringRef Root) const
Definition: Headers.cpp:101
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, const CodeCompletion &C)
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:68
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R)
Definition: SourceCode.cpp:145