blob: 06f822b34fba5ca443d51324da5b5756fe719dd0 [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*/,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000032 llvm::StringRef FileName, bool IsAngled,
Eric Liu155f5a42018-05-14 12:19:16 +000033 CharSourceRange FilenameRange, const FileEntry *File,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000034 llvm::StringRef /*SearchPath*/,
35 llvm::StringRef /*RelativePath*/,
Julie Hockett546943f2018-05-10 19:13:14 +000036 const Module * /*Imported*/,
Sam McCall991e3162018-11-20 10:58:48 +000037 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 }
Sam McCall3f0243f2018-07-03 08:09:29 +000048 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 }
Eric Liuc5105f92018-02-16 14:15:55 +000059 }
60
61private:
Eric Liu155f5a42018-05-14 12:19:16 +000062 const SourceManager &SM;
Sam McCall3f0243f2018-07-03 08:09:29 +000063 IncludeStructure *Out;
Eric Liuc5105f92018-02-16 14:15:55 +000064};
65
66} // namespace
67
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000068bool isLiteralInclude(llvm::StringRef Include) {
Eric Liu6c8e8582018-02-26 08:32:13 +000069 return Include.startswith("<") || Include.startswith("\"");
70}
71
72bool HeaderFile::valid() const {
73 return (Verbatim && isLiteralInclude(File)) ||
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000074 (!Verbatim && llvm::sys::path::is_absolute(File));
Eric Liu6c8e8582018-02-26 08:32:13 +000075}
76
Eric Liu155f5a42018-05-14 12:19:16 +000077std::unique_ptr<PPCallbacks>
Sam McCall3f0243f2018-07-03 08:09:29 +000078collectIncludeStructureCallback(const SourceManager &SM,
79 IncludeStructure *Out) {
80 return llvm::make_unique<RecordHeaders>(SM, Out);
81}
82
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000083void IncludeStructure::recordInclude(llvm::StringRef IncludingName,
84 llvm::StringRef IncludedName,
85 llvm::StringRef IncludedRealName) {
Sam McCall3f0243f2018-07-03 08:09:29 +000086 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
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000093unsigned IncludeStructure::fileIndex(llvm::StringRef Name) {
Sam McCall3f0243f2018-07-03 08:09:29 +000094 auto R = NameToIndex.try_emplace(Name, RealPathNames.size());
95 if (R.second)
96 RealPathNames.emplace_back();
97 return R.first->getValue();
98}
99
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000100llvm::StringMap<unsigned>
101IncludeStructure::includeDepth(llvm::StringRef Root) const {
Sam McCall3f0243f2018-07-03 08:09:29 +0000102 // Include depth 0 is the main file only.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000103 llvm::StringMap<unsigned> Result;
Sam McCall3f0243f2018-07-03 08:09:29 +0000104 Result[Root] = 0;
105 std::vector<unsigned> CurrentLevel;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000106 llvm::DenseSet<unsigned> Seen;
Sam McCall3f0243f2018-07-03 08:09:29 +0000107 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;
Eric Liu155f5a42018-05-14 12:19:16 +0000131}
132
Eric Liufd9f4262018-09-27 14:27:02 +0000133void IncludeInserter::addExisting(const Inclusion &Inc) {
134 IncludedHeaders.insert(Inc.Written);
135 if (!Inc.Resolved.empty())
136 IncludedHeaders.insert(Inc.Resolved);
137}
138
Eric Liuc5105f92018-02-16 14:15:55 +0000139/// FIXME(ioeric): we might not want to insert an absolute include path if the
140/// path is not shortened.
Eric Liu8f3678d2018-06-15 13:34:18 +0000141bool IncludeInserter::shouldInsertInclude(
142 const HeaderFile &DeclaringHeader, const HeaderFile &InsertedHeader) const {
Eric Liu6c8e8582018-02-26 08:32:13 +0000143 assert(DeclaringHeader.valid() && InsertedHeader.valid());
Eric Liu8f3678d2018-06-15 13:34:18 +0000144 if (FileName == DeclaringHeader.File || FileName == InsertedHeader.File)
145 return false;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000146 auto Included = [&](llvm::StringRef Header) {
Eric Liu155f5a42018-05-14 12:19:16 +0000147 return IncludedHeaders.find(Header) != IncludedHeaders.end();
Eric Liu6c8e8582018-02-26 08:32:13 +0000148 };
Eric Liu8f3678d2018-06-15 13:34:18 +0000149 return !Included(DeclaringHeader.File) && !Included(InsertedHeader.File);
150}
Eric Liuc5105f92018-02-16 14:15:55 +0000151
Eric Liu8f3678d2018-06-15 13:34:18 +0000152std::string
153IncludeInserter::calculateIncludePath(const HeaderFile &DeclaringHeader,
154 const HeaderFile &InsertedHeader) const {
155 assert(DeclaringHeader.valid() && InsertedHeader.valid());
Eric Liu6c8e8582018-02-26 08:32:13 +0000156 if (InsertedHeader.Verbatim)
157 return InsertedHeader.File;
Eric Liu8f3678d2018-06-15 13:34:18 +0000158 bool IsSystem = false;
Eric Liuc5105f92018-02-16 14:15:55 +0000159 std::string Suggested = HeaderSearchInfo.suggestPathToFileForDiagnostics(
Eric Liu63f419a2018-05-15 15:29:32 +0000160 InsertedHeader.File, BuildDir, &IsSystem);
Eric Liuc5105f92018-02-16 14:15:55 +0000161 if (IsSystem)
162 Suggested = "<" + Suggested + ">";
163 else
164 Suggested = "\"" + Suggested + "\"";
Eric Liuc5105f92018-02-16 14:15:55 +0000165 return Suggested;
166}
167
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000168llvm::Optional<TextEdit>
169IncludeInserter::insert(llvm::StringRef VerbatimHeader) const {
170 llvm::Optional<TextEdit> Edit = None;
Eric Liu8f3678d2018-06-15 13:34:18 +0000171 if (auto Insertion = Inserter.insert(VerbatimHeader.trim("\"<>"),
172 VerbatimHeader.startswith("<")))
173 Edit = replacementToEdit(Code, *Insertion);
174 return Edit;
Eric Liu63f419a2018-05-15 15:29:32 +0000175}
176
Sam McCall991e3162018-11-20 10:58:48 +0000177llvm::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
Eric Liuc5105f92018-02-16 14:15:55 +0000183} // namespace clangd
184} // namespace clang