blob: f42f204c16bce4eff75b831dbed03fdf7a89c255 [file] [log] [blame]
Eric Liuc5105f92018-02-16 14:15:55 +00001//===--- 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"
Eric Liu155f5a42018-05-14 12:19:16 +000013#include "SourceCode.h"
Eric Liuc5105f92018-02-16 14:15:55 +000014#include "clang/Frontend/CompilerInstance.h"
15#include "clang/Frontend/CompilerInvocation.h"
16#include "clang/Frontend/FrontendActions.h"
17#include "clang/Lex/HeaderSearch.h"
Eric Liu709bde82018-02-19 18:48:44 +000018#include "llvm/Support/Path.h"
Eric Liuc5105f92018-02-16 14:15:55 +000019
20namespace clang {
21namespace clangd {
22namespace {
23
24class RecordHeaders : public PPCallbacks {
25public:
Sam McCall3f0243f2018-07-03 08:09:29 +000026 RecordHeaders(const SourceManager &SM, IncludeStructure *Out)
27 : SM(SM), Out(Out) {}
Eric Liuc5105f92018-02-16 14:15:55 +000028
Eric Liu155f5a42018-05-14 12:19:16 +000029 // 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*/,
Eric Liu6c8e8582018-02-26 08:32:13 +000032 llvm::StringRef FileName, bool IsAngled,
Eric Liu155f5a42018-05-14 12:19:16 +000033 CharSourceRange FilenameRange, const FileEntry *File,
34 llvm::StringRef /*SearchPath*/,
Eric Liuc5105f92018-02-16 14:15:55 +000035 llvm::StringRef /*RelativePath*/,
Julie Hockett546943f2018-05-10 19:13:14 +000036 const Module * /*Imported*/,
37 SrcMgr::CharacteristicKind /*FileType*/) override {
Sam McCall3f0243f2018-07-03 08:09:29 +000038 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 }
Eric Liuc5105f92018-02-16 14:15:55 +000055 }
56
57private:
Eric Liu155f5a42018-05-14 12:19:16 +000058 const SourceManager &SM;
Sam McCall3f0243f2018-07-03 08:09:29 +000059 IncludeStructure *Out;
Eric Liuc5105f92018-02-16 14:15:55 +000060};
61
62} // namespace
63
Eric Liu6c8e8582018-02-26 08:32:13 +000064bool isLiteralInclude(llvm::StringRef Include) {
65 return Include.startswith("<") || Include.startswith("\"");
66}
67
68bool HeaderFile::valid() const {
69 return (Verbatim && isLiteralInclude(File)) ||
70 (!Verbatim && llvm::sys::path::is_absolute(File));
71}
72
Eric Liu155f5a42018-05-14 12:19:16 +000073std::unique_ptr<PPCallbacks>
Sam McCall3f0243f2018-07-03 08:09:29 +000074collectIncludeStructureCallback(const SourceManager &SM,
75 IncludeStructure *Out) {
76 return llvm::make_unique<RecordHeaders>(SM, Out);
77}
78
79void 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
89unsigned 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
96llvm::StringMap<unsigned>
97IncludeStructure::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;
Eric Liu155f5a42018-05-14 12:19:16 +0000127}
128
Eric Liufd9f4262018-09-27 14:27:02 +0000129void IncludeInserter::addExisting(const Inclusion &Inc) {
130 IncludedHeaders.insert(Inc.Written);
131 if (!Inc.Resolved.empty())
132 IncludedHeaders.insert(Inc.Resolved);
133}
134
Eric Liuc5105f92018-02-16 14:15:55 +0000135/// FIXME(ioeric): we might not want to insert an absolute include path if the
136/// path is not shortened.
Eric Liu8f3678d2018-06-15 13:34:18 +0000137bool IncludeInserter::shouldInsertInclude(
138 const HeaderFile &DeclaringHeader, const HeaderFile &InsertedHeader) const {
Eric Liu6c8e8582018-02-26 08:32:13 +0000139 assert(DeclaringHeader.valid() && InsertedHeader.valid());
Eric Liu8f3678d2018-06-15 13:34:18 +0000140 if (FileName == DeclaringHeader.File || FileName == InsertedHeader.File)
141 return false;
Eric Liu6c8e8582018-02-26 08:32:13 +0000142 auto Included = [&](llvm::StringRef Header) {
Eric Liu155f5a42018-05-14 12:19:16 +0000143 return IncludedHeaders.find(Header) != IncludedHeaders.end();
Eric Liu6c8e8582018-02-26 08:32:13 +0000144 };
Eric Liu8f3678d2018-06-15 13:34:18 +0000145 return !Included(DeclaringHeader.File) && !Included(InsertedHeader.File);
146}
Eric Liuc5105f92018-02-16 14:15:55 +0000147
Eric Liu8f3678d2018-06-15 13:34:18 +0000148std::string
149IncludeInserter::calculateIncludePath(const HeaderFile &DeclaringHeader,
150 const HeaderFile &InsertedHeader) const {
151 assert(DeclaringHeader.valid() && InsertedHeader.valid());
Eric Liu6c8e8582018-02-26 08:32:13 +0000152 if (InsertedHeader.Verbatim)
153 return InsertedHeader.File;
Eric Liu8f3678d2018-06-15 13:34:18 +0000154 bool IsSystem = false;
Eric Liuc5105f92018-02-16 14:15:55 +0000155 std::string Suggested = HeaderSearchInfo.suggestPathToFileForDiagnostics(
Eric Liu63f419a2018-05-15 15:29:32 +0000156 InsertedHeader.File, BuildDir, &IsSystem);
Eric Liuc5105f92018-02-16 14:15:55 +0000157 if (IsSystem)
158 Suggested = "<" + Suggested + ">";
159 else
160 Suggested = "\"" + Suggested + "\"";
Eric Liuc5105f92018-02-16 14:15:55 +0000161 return Suggested;
162}
163
Eric Liu8f3678d2018-06-15 13:34:18 +0000164Optional<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;
Eric Liu63f419a2018-05-15 15:29:32 +0000170}
171
Eric Liuc5105f92018-02-16 14:15:55 +0000172} // namespace clangd
173} // namespace clang