blob: c43d72c4eb8770d4244950c6a1f391db71bd9593 [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*/,
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
Sam McCallc008af62018-10-20 15:30:37 +000068bool isLiteralInclude(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)) ||
Sam McCallc008af62018-10-20 15:30:37 +000074 (!Verbatim && 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
Sam McCallc008af62018-10-20 15:30:37 +000083void IncludeStructure::recordInclude(StringRef IncludingName,
84 StringRef IncludedName,
85 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
Sam McCallc008af62018-10-20 15:30:37 +000093unsigned IncludeStructure::fileIndex(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
Sam McCallc008af62018-10-20 15:30:37 +0000100StringMap<unsigned> IncludeStructure::includeDepth(StringRef Root) const {
Sam McCall3f0243f2018-07-03 08:09:29 +0000101 // Include depth 0 is the main file only.
Sam McCallc008af62018-10-20 15:30:37 +0000102 StringMap<unsigned> Result;
Sam McCall3f0243f2018-07-03 08:09:29 +0000103 Result[Root] = 0;
104 std::vector<unsigned> CurrentLevel;
Sam McCallc008af62018-10-20 15:30:37 +0000105 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;
Sam McCallc008af62018-10-20 15:30:37 +0000145 auto Included = [&](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
Eric Liu8f3678d2018-06-15 13:34:18 +0000167Optional<TextEdit> IncludeInserter::insert(StringRef VerbatimHeader) const {
168 Optional<TextEdit> Edit = None;
169 if (auto Insertion = Inserter.insert(VerbatimHeader.trim("\"<>"),
170 VerbatimHeader.startswith("<")))
171 Edit = replacementToEdit(Code, *Insertion);
172 return Edit;
Eric Liu63f419a2018-05-15 15:29:32 +0000173}
174
Sam McCall991e3162018-11-20 10:58:48 +0000175llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Inclusion &Inc) {
176 return OS << Inc.Written << " = "
177 << (Inc.Resolved.empty() ? Inc.Resolved : "[unresolved]") << " at "
178 << Inc.R;
179}
180
Eric Liuc5105f92018-02-16 14:15:55 +0000181} // namespace clangd
182} // namespace clang