blob: c4af420ca4201d02c3ef41ee97a676b4da1e7a25 [file] [log] [blame]
Eric Liuc5105f92018-02-16 14:15:55 +00001//===--- Headers.cpp - Include headers ---------------------------*- C++-*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Eric Liuc5105f92018-02-16 14:15:55 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "Headers.h"
10#include "Compiler.h"
11#include "Logger.h"
Eric Liu155f5a42018-05-14 12:19:16 +000012#include "SourceCode.h"
Eric Liuc5105f92018-02-16 14:15:55 +000013#include "clang/Frontend/CompilerInstance.h"
14#include "clang/Frontend/CompilerInvocation.h"
15#include "clang/Frontend/FrontendActions.h"
16#include "clang/Lex/HeaderSearch.h"
Eric Liu709bde82018-02-19 18:48:44 +000017#include "llvm/Support/Path.h"
Eric Liuc5105f92018-02-16 14:15:55 +000018
19namespace clang {
20namespace clangd {
21namespace {
22
23class RecordHeaders : public PPCallbacks {
24public:
Sam McCall3f0243f2018-07-03 08:09:29 +000025 RecordHeaders(const SourceManager &SM, IncludeStructure *Out)
26 : SM(SM), Out(Out) {}
Eric Liuc5105f92018-02-16 14:15:55 +000027
Eric Liu155f5a42018-05-14 12:19:16 +000028 // Record existing #includes - both written and resolved paths. Only #includes
29 // in the main file are collected.
30 void InclusionDirective(SourceLocation HashLoc, const Token & /*IncludeTok*/,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000031 llvm::StringRef FileName, bool IsAngled,
Eric Liu155f5a42018-05-14 12:19:16 +000032 CharSourceRange FilenameRange, const FileEntry *File,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000033 llvm::StringRef /*SearchPath*/,
34 llvm::StringRef /*RelativePath*/,
Julie Hockett546943f2018-05-10 19:13:14 +000035 const Module * /*Imported*/,
Sam McCall991e3162018-11-20 10:58:48 +000036 SrcMgr::CharacteristicKind FileKind) override {
37 if (SM.isWrittenInMainFile(HashLoc)) {
38 Out->MainFileIncludes.emplace_back();
39 auto &Inc = Out->MainFileIncludes.back();
40 Inc.R = halfOpenToRange(SM, FilenameRange);
41 Inc.Written =
42 (IsAngled ? "<" + FileName + ">" : "\"" + FileName + "\"").str();
43 Inc.Resolved = File ? File->tryGetRealPathName() : "";
44 Inc.HashOffset = SM.getFileOffset(HashLoc);
45 Inc.FileKind = FileKind;
46 }
Sam McCall3f0243f2018-07-03 08:09:29 +000047 if (File) {
48 auto *IncludingFileEntry = SM.getFileEntryForID(SM.getFileID(HashLoc));
49 if (!IncludingFileEntry) {
50 assert(SM.getBufferName(HashLoc).startswith("<") &&
51 "Expected #include location to be a file or <built-in>");
52 // Treat as if included from the main file.
53 IncludingFileEntry = SM.getFileEntryForID(SM.getMainFileID());
54 }
55 Out->recordInclude(IncludingFileEntry->getName(), File->getName(),
56 File->tryGetRealPathName());
57 }
Eric Liuc5105f92018-02-16 14:15:55 +000058 }
59
60private:
Eric Liu155f5a42018-05-14 12:19:16 +000061 const SourceManager &SM;
Sam McCall3f0243f2018-07-03 08:09:29 +000062 IncludeStructure *Out;
Eric Liuc5105f92018-02-16 14:15:55 +000063};
64
65} // namespace
66
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000067bool isLiteralInclude(llvm::StringRef Include) {
Eric Liu6c8e8582018-02-26 08:32:13 +000068 return Include.startswith("<") || Include.startswith("\"");
69}
70
71bool HeaderFile::valid() const {
72 return (Verbatim && isLiteralInclude(File)) ||
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000073 (!Verbatim && llvm::sys::path::is_absolute(File));
Eric Liu6c8e8582018-02-26 08:32:13 +000074}
75
Eric Liu155f5a42018-05-14 12:19:16 +000076std::unique_ptr<PPCallbacks>
Sam McCall3f0243f2018-07-03 08:09:29 +000077collectIncludeStructureCallback(const SourceManager &SM,
78 IncludeStructure *Out) {
79 return llvm::make_unique<RecordHeaders>(SM, Out);
80}
81
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000082void IncludeStructure::recordInclude(llvm::StringRef IncludingName,
83 llvm::StringRef IncludedName,
84 llvm::StringRef IncludedRealName) {
Sam McCall3f0243f2018-07-03 08:09:29 +000085 auto Child = fileIndex(IncludedName);
86 if (!IncludedRealName.empty() && RealPathNames[Child].empty())
87 RealPathNames[Child] = IncludedRealName;
88 auto Parent = fileIndex(IncludingName);
89 IncludeChildren[Parent].push_back(Child);
90}
91
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000092unsigned IncludeStructure::fileIndex(llvm::StringRef Name) {
Sam McCall3f0243f2018-07-03 08:09:29 +000093 auto R = NameToIndex.try_emplace(Name, RealPathNames.size());
94 if (R.second)
95 RealPathNames.emplace_back();
96 return R.first->getValue();
97}
98
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000099llvm::StringMap<unsigned>
100IncludeStructure::includeDepth(llvm::StringRef Root) const {
Sam McCall3f0243f2018-07-03 08:09:29 +0000101 // Include depth 0 is the main file only.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000102 llvm::StringMap<unsigned> Result;
Sam McCall3f0243f2018-07-03 08:09:29 +0000103 Result[Root] = 0;
104 std::vector<unsigned> CurrentLevel;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000105 llvm::DenseSet<unsigned> Seen;
Sam McCall3f0243f2018-07-03 08:09:29 +0000106 auto It = NameToIndex.find(Root);
107 if (It != NameToIndex.end()) {
108 CurrentLevel.push_back(It->second);
109 Seen.insert(It->second);
110 }
111
112 // Each round of BFS traversal finds the next depth level.
113 std::vector<unsigned> PreviousLevel;
114 for (unsigned Level = 1; !CurrentLevel.empty(); ++Level) {
115 PreviousLevel.clear();
116 PreviousLevel.swap(CurrentLevel);
117 for (const auto &Parent : PreviousLevel) {
118 for (const auto &Child : IncludeChildren.lookup(Parent)) {
119 if (Seen.insert(Child).second) {
120 CurrentLevel.push_back(Child);
121 const auto &Name = RealPathNames[Child];
122 // Can't include files if we don't have their real path.
123 if (!Name.empty())
124 Result[Name] = Level;
125 }
126 }
127 }
128 }
129 return Result;
Eric Liu155f5a42018-05-14 12:19:16 +0000130}
131
Eric Liufd9f4262018-09-27 14:27:02 +0000132void IncludeInserter::addExisting(const Inclusion &Inc) {
133 IncludedHeaders.insert(Inc.Written);
134 if (!Inc.Resolved.empty())
135 IncludedHeaders.insert(Inc.Resolved);
136}
137
Eric Liuc5105f92018-02-16 14:15:55 +0000138/// FIXME(ioeric): we might not want to insert an absolute include path if the
139/// path is not shortened.
Eric Liu8f3678d2018-06-15 13:34:18 +0000140bool IncludeInserter::shouldInsertInclude(
141 const HeaderFile &DeclaringHeader, const HeaderFile &InsertedHeader) const {
Eric Liu6c8e8582018-02-26 08:32:13 +0000142 assert(DeclaringHeader.valid() && InsertedHeader.valid());
Eric Liu8f3678d2018-06-15 13:34:18 +0000143 if (FileName == DeclaringHeader.File || FileName == InsertedHeader.File)
144 return false;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000145 auto Included = [&](llvm::StringRef Header) {
Eric Liu155f5a42018-05-14 12:19:16 +0000146 return IncludedHeaders.find(Header) != IncludedHeaders.end();
Eric Liu6c8e8582018-02-26 08:32:13 +0000147 };
Eric Liu8f3678d2018-06-15 13:34:18 +0000148 return !Included(DeclaringHeader.File) && !Included(InsertedHeader.File);
149}
Eric Liuc5105f92018-02-16 14:15:55 +0000150
Eric Liu8f3678d2018-06-15 13:34:18 +0000151std::string
152IncludeInserter::calculateIncludePath(const HeaderFile &DeclaringHeader,
153 const HeaderFile &InsertedHeader) const {
154 assert(DeclaringHeader.valid() && InsertedHeader.valid());
Eric Liu6c8e8582018-02-26 08:32:13 +0000155 if (InsertedHeader.Verbatim)
156 return InsertedHeader.File;
Eric Liu8f3678d2018-06-15 13:34:18 +0000157 bool IsSystem = false;
Eric Liuc5105f92018-02-16 14:15:55 +0000158 std::string Suggested = HeaderSearchInfo.suggestPathToFileForDiagnostics(
Eric Liu63f419a2018-05-15 15:29:32 +0000159 InsertedHeader.File, BuildDir, &IsSystem);
Eric Liuc5105f92018-02-16 14:15:55 +0000160 if (IsSystem)
161 Suggested = "<" + Suggested + ">";
162 else
163 Suggested = "\"" + Suggested + "\"";
Eric Liuc5105f92018-02-16 14:15:55 +0000164 return Suggested;
165}
166
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000167llvm::Optional<TextEdit>
168IncludeInserter::insert(llvm::StringRef VerbatimHeader) const {
169 llvm::Optional<TextEdit> Edit = None;
Eric Liu8f3678d2018-06-15 13:34:18 +0000170 if (auto Insertion = Inserter.insert(VerbatimHeader.trim("\"<>"),
171 VerbatimHeader.startswith("<")))
172 Edit = replacementToEdit(Code, *Insertion);
173 return Edit;
Eric Liu63f419a2018-05-15 15:29:32 +0000174}
175
Sam McCall991e3162018-11-20 10:58:48 +0000176llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Inclusion &Inc) {
177 return OS << Inc.Written << " = "
178 << (Inc.Resolved.empty() ? Inc.Resolved : "[unresolved]") << " at "
179 << Inc.R;
180}
181
Eric Liuc5105f92018-02-16 14:15:55 +0000182} // namespace clangd
183} // namespace clang