blob: 1d3dee44fe87d3e8d660cbbad9d17f1e1c97af22 [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
Sam McCallc008af62018-10-20 15:30:37 +000020using namespace llvm;
Eric Liuc5105f92018-02-16 14:15:55 +000021namespace clang {
22namespace clangd {
23namespace {
24
25class RecordHeaders : public PPCallbacks {
26public:
Sam McCall3f0243f2018-07-03 08:09:29 +000027 RecordHeaders(const SourceManager &SM, IncludeStructure *Out)
28 : SM(SM), Out(Out) {}
Eric Liuc5105f92018-02-16 14:15:55 +000029
Eric Liu155f5a42018-05-14 12:19:16 +000030 // Record existing #includes - both written and resolved paths. Only #includes
31 // in the main file are collected.
32 void InclusionDirective(SourceLocation HashLoc, const Token & /*IncludeTok*/,
Sam McCallc008af62018-10-20 15:30:37 +000033 StringRef FileName, bool IsAngled,
Eric Liu155f5a42018-05-14 12:19:16 +000034 CharSourceRange FilenameRange, const FileEntry *File,
Sam McCallc008af62018-10-20 15:30:37 +000035 StringRef /*SearchPath*/, 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
Sam McCallc008af62018-10-20 15:30:37 +000064bool isLiteralInclude(StringRef Include) {
Eric Liu6c8e8582018-02-26 08:32:13 +000065 return Include.startswith("<") || Include.startswith("\"");
66}
67
68bool HeaderFile::valid() const {
69 return (Verbatim && isLiteralInclude(File)) ||
Sam McCallc008af62018-10-20 15:30:37 +000070 (!Verbatim && sys::path::is_absolute(File));
Eric Liu6c8e8582018-02-26 08:32:13 +000071}
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
Sam McCallc008af62018-10-20 15:30:37 +000079void IncludeStructure::recordInclude(StringRef IncludingName,
80 StringRef IncludedName,
81 StringRef IncludedRealName) {
Sam McCall3f0243f2018-07-03 08:09:29 +000082 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
Sam McCallc008af62018-10-20 15:30:37 +000089unsigned IncludeStructure::fileIndex(StringRef Name) {
Sam McCall3f0243f2018-07-03 08:09:29 +000090 auto R = NameToIndex.try_emplace(Name, RealPathNames.size());
91 if (R.second)
92 RealPathNames.emplace_back();
93 return R.first->getValue();
94}
95
Sam McCallc008af62018-10-20 15:30:37 +000096StringMap<unsigned> IncludeStructure::includeDepth(StringRef Root) const {
Sam McCall3f0243f2018-07-03 08:09:29 +000097 // Include depth 0 is the main file only.
Sam McCallc008af62018-10-20 15:30:37 +000098 StringMap<unsigned> Result;
Sam McCall3f0243f2018-07-03 08:09:29 +000099 Result[Root] = 0;
100 std::vector<unsigned> CurrentLevel;
Sam McCallc008af62018-10-20 15:30:37 +0000101 DenseSet<unsigned> Seen;
Sam McCall3f0243f2018-07-03 08:09:29 +0000102 auto It = NameToIndex.find(Root);
103 if (It != NameToIndex.end()) {
104 CurrentLevel.push_back(It->second);
105 Seen.insert(It->second);
106 }
107
108 // Each round of BFS traversal finds the next depth level.
109 std::vector<unsigned> PreviousLevel;
110 for (unsigned Level = 1; !CurrentLevel.empty(); ++Level) {
111 PreviousLevel.clear();
112 PreviousLevel.swap(CurrentLevel);
113 for (const auto &Parent : PreviousLevel) {
114 for (const auto &Child : IncludeChildren.lookup(Parent)) {
115 if (Seen.insert(Child).second) {
116 CurrentLevel.push_back(Child);
117 const auto &Name = RealPathNames[Child];
118 // Can't include files if we don't have their real path.
119 if (!Name.empty())
120 Result[Name] = Level;
121 }
122 }
123 }
124 }
125 return Result;
Eric Liu155f5a42018-05-14 12:19:16 +0000126}
127
Eric Liufd9f4262018-09-27 14:27:02 +0000128void IncludeInserter::addExisting(const Inclusion &Inc) {
129 IncludedHeaders.insert(Inc.Written);
130 if (!Inc.Resolved.empty())
131 IncludedHeaders.insert(Inc.Resolved);
132}
133
Eric Liuc5105f92018-02-16 14:15:55 +0000134/// FIXME(ioeric): we might not want to insert an absolute include path if the
135/// path is not shortened.
Eric Liu8f3678d2018-06-15 13:34:18 +0000136bool IncludeInserter::shouldInsertInclude(
137 const HeaderFile &DeclaringHeader, const HeaderFile &InsertedHeader) const {
Eric Liu6c8e8582018-02-26 08:32:13 +0000138 assert(DeclaringHeader.valid() && InsertedHeader.valid());
Eric Liu8f3678d2018-06-15 13:34:18 +0000139 if (FileName == DeclaringHeader.File || FileName == InsertedHeader.File)
140 return false;
Sam McCallc008af62018-10-20 15:30:37 +0000141 auto Included = [&](StringRef Header) {
Eric Liu155f5a42018-05-14 12:19:16 +0000142 return IncludedHeaders.find(Header) != IncludedHeaders.end();
Eric Liu6c8e8582018-02-26 08:32:13 +0000143 };
Eric Liu8f3678d2018-06-15 13:34:18 +0000144 return !Included(DeclaringHeader.File) && !Included(InsertedHeader.File);
145}
Eric Liuc5105f92018-02-16 14:15:55 +0000146
Eric Liu8f3678d2018-06-15 13:34:18 +0000147std::string
148IncludeInserter::calculateIncludePath(const HeaderFile &DeclaringHeader,
149 const HeaderFile &InsertedHeader) const {
150 assert(DeclaringHeader.valid() && InsertedHeader.valid());
Eric Liu6c8e8582018-02-26 08:32:13 +0000151 if (InsertedHeader.Verbatim)
152 return InsertedHeader.File;
Eric Liu8f3678d2018-06-15 13:34:18 +0000153 bool IsSystem = false;
Eric Liuc5105f92018-02-16 14:15:55 +0000154 std::string Suggested = HeaderSearchInfo.suggestPathToFileForDiagnostics(
Eric Liu63f419a2018-05-15 15:29:32 +0000155 InsertedHeader.File, BuildDir, &IsSystem);
Eric Liuc5105f92018-02-16 14:15:55 +0000156 if (IsSystem)
157 Suggested = "<" + Suggested + ">";
158 else
159 Suggested = "\"" + Suggested + "\"";
Eric Liuc5105f92018-02-16 14:15:55 +0000160 return Suggested;
161}
162
Eric Liu8f3678d2018-06-15 13:34:18 +0000163Optional<TextEdit> IncludeInserter::insert(StringRef VerbatimHeader) const {
164 Optional<TextEdit> Edit = None;
165 if (auto Insertion = Inserter.insert(VerbatimHeader.trim("\"<>"),
166 VerbatimHeader.startswith("<")))
167 Edit = replacementToEdit(Code, *Insertion);
168 return Edit;
Eric Liu63f419a2018-05-15 15:29:32 +0000169}
170
Eric Liuc5105f92018-02-16 14:15:55 +0000171} // namespace clangd
172} // namespace clang