blob: 2a32565eb7abc7eded1d1050bba64a18bb5b8c49 [file] [log] [blame]
Haojian Wu4c1394d2017-12-12 15:42:10 +00001//===--- SymbolCollector.cpp -------------------------------------*- 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 "SymbolCollector.h"
Eric Liu76f6b442018-01-09 17:32:00 +000011#include "../CodeCompletionStrings.h"
Eric Liu7f247652018-02-06 16:10:35 +000012#include "../Logger.h"
13#include "../URI.h"
Eric Liuc5105f92018-02-16 14:15:55 +000014#include "CanonicalIncludes.h"
Haojian Wu4c1394d2017-12-12 15:42:10 +000015#include "clang/AST/DeclCXX.h"
Eric Liu9af958f2018-01-10 14:57:58 +000016#include "clang/ASTMatchers/ASTMatchFinder.h"
Haojian Wu4c1394d2017-12-12 15:42:10 +000017#include "clang/Basic/SourceManager.h"
18#include "clang/Index/IndexSymbol.h"
19#include "clang/Index/USRGeneration.h"
Eric Liu278e2d12018-01-29 15:13:29 +000020#include "llvm/Support/FileSystem.h"
Haojian Wu4c1394d2017-12-12 15:42:10 +000021#include "llvm/Support/MemoryBuffer.h"
22#include "llvm/Support/Path.h"
23
24namespace clang {
25namespace clangd {
26
27namespace {
Eric Liu7f247652018-02-06 16:10:35 +000028// Returns a URI of \p Path. Firstly, this makes the \p Path absolute using the
29// current working directory of the given SourceManager if the Path is not an
30// absolute path. If failed, this resolves relative paths against \p FallbackDir
31// to get an absolute path. Then, this tries creating an URI for the absolute
32// path with schemes specified in \p Opts. This returns an URI with the first
33// working scheme, if there is any; otherwise, this returns None.
Haojian Wu4c1394d2017-12-12 15:42:10 +000034//
35// The Path can be a path relative to the build directory, or retrieved from
36// the SourceManager.
Eric Liu7f247652018-02-06 16:10:35 +000037llvm::Optional<std::string> toURI(const SourceManager &SM, StringRef Path,
38 const SymbolCollector::Options &Opts) {
Haojian Wu4c1394d2017-12-12 15:42:10 +000039 llvm::SmallString<128> AbsolutePath(Path);
40 if (std::error_code EC =
41 SM.getFileManager().getVirtualFileSystem()->makeAbsolute(
42 AbsolutePath))
43 llvm::errs() << "Warning: could not make absolute file: '" << EC.message()
44 << '\n';
Eric Liu278e2d12018-01-29 15:13:29 +000045 if (llvm::sys::path::is_absolute(AbsolutePath)) {
46 // Handle the symbolic link path case where the current working directory
47 // (getCurrentWorkingDirectory) is a symlink./ We always want to the real
48 // file path (instead of the symlink path) for the C++ symbols.
49 //
50 // Consider the following example:
51 //
52 // src dir: /project/src/foo.h
53 // current working directory (symlink): /tmp/build -> /project/src/
54 //
55 // The file path of Symbol is "/project/src/foo.h" instead of
56 // "/tmp/build/foo.h"
57 if (const DirectoryEntry *Dir = SM.getFileManager().getDirectory(
58 llvm::sys::path::parent_path(AbsolutePath.str()))) {
59 StringRef DirName = SM.getFileManager().getCanonicalName(Dir);
60 SmallString<128> AbsoluteFilename;
61 llvm::sys::path::append(AbsoluteFilename, DirName,
62 llvm::sys::path::filename(AbsolutePath.str()));
63 AbsolutePath = AbsoluteFilename;
64 }
Eric Liu7f247652018-02-06 16:10:35 +000065 } else if (!Opts.FallbackDir.empty()) {
66 llvm::sys::fs::make_absolute(Opts.FallbackDir, AbsolutePath);
Eric Liu278e2d12018-01-29 15:13:29 +000067 llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/true);
Haojian Wu4c1394d2017-12-12 15:42:10 +000068 }
Eric Liu7f247652018-02-06 16:10:35 +000069
70 std::string ErrMsg;
71 for (const auto &Scheme : Opts.URISchemes) {
72 auto U = URI::create(AbsolutePath, Scheme);
73 if (U)
74 return U->toString();
75 ErrMsg += llvm::toString(U.takeError()) + "\n";
76 }
77 log(llvm::Twine("Failed to create an URI for file ") + AbsolutePath + ": " +
78 ErrMsg);
79 return llvm::None;
Haojian Wu4c1394d2017-12-12 15:42:10 +000080}
Eric Liu4feda802017-12-19 11:37:40 +000081
Sam McCall8b2faee2018-01-19 22:18:21 +000082// "a::b::c", return {"a::b::", "c"}. Scope is empty if there's no qualifier.
Eric Liu4feda802017-12-19 11:37:40 +000083std::pair<llvm::StringRef, llvm::StringRef>
84splitQualifiedName(llvm::StringRef QName) {
85 assert(!QName.startswith("::") && "Qualified names should not start with ::");
86 size_t Pos = QName.rfind("::");
87 if (Pos == llvm::StringRef::npos)
88 return {StringRef(), QName};
Sam McCall8b2faee2018-01-19 22:18:21 +000089 return {QName.substr(0, Pos + 2), QName.substr(Pos + 2)};
Eric Liu4feda802017-12-19 11:37:40 +000090}
91
Eric Liu9af958f2018-01-10 14:57:58 +000092bool shouldFilterDecl(const NamedDecl *ND, ASTContext *ASTCtx,
93 const SymbolCollector::Options &Opts) {
94 using namespace clang::ast_matchers;
95 if (ND->isImplicit())
96 return true;
Haojian Wu9873fdd2018-01-19 09:35:55 +000097 // Skip anonymous declarations, e.g (anonymous enum/class/struct).
98 if (ND->getDeclName().isEmpty())
99 return true;
100
Eric Liu9af958f2018-01-10 14:57:58 +0000101 // FIXME: figure out a way to handle internal linkage symbols (e.g. static
102 // variables, function) defined in the .cc files. Also we skip the symbols
103 // in anonymous namespace as the qualifier names of these symbols are like
104 // `foo::<anonymous>::bar`, which need a special handling.
105 // In real world projects, we have a relatively large set of header files
106 // that define static variables (like "static const int A = 1;"), we still
107 // want to collect these symbols, although they cause potential ODR
108 // violations.
109 if (ND->isInAnonymousNamespace())
110 return true;
111
Haojian Wu9873fdd2018-01-19 09:35:55 +0000112 // We only want:
113 // * symbols in namespaces or translation unit scopes (e.g. no class
114 // members)
115 // * enum constants in unscoped enum decl (e.g. "red" in "enum {red};")
Eric Liucf177382018-02-02 10:31:42 +0000116 auto InTopLevelScope = hasDeclContext(
117 anyOf(namespaceDecl(), translationUnitDecl(), linkageSpecDecl()));
Haojian Wu9873fdd2018-01-19 09:35:55 +0000118 if (match(decl(allOf(Opts.IndexMainFiles
119 ? decl()
120 : decl(unless(isExpansionInMainFile())),
121 anyOf(InTopLevelScope,
122 hasDeclContext(enumDecl(InTopLevelScope,
123 unless(isScoped())))))),
Eric Liu9af958f2018-01-10 14:57:58 +0000124 *ND, *ASTCtx)
125 .empty())
126 return true;
127
128 return false;
129}
130
Eric Liuc5105f92018-02-16 14:15:55 +0000131// We only collect #include paths for symbols that are suitable for global code
132// completion, except for namespaces since #include path for a namespace is hard
133// to define.
134bool shouldCollectIncludePath(index::SymbolKind Kind) {
135 using SK = index::SymbolKind;
136 switch (Kind) {
137 case SK::Macro:
138 case SK::Enum:
139 case SK::Struct:
140 case SK::Class:
141 case SK::Union:
142 case SK::TypeAlias:
143 case SK::Using:
144 case SK::Function:
145 case SK::Variable:
146 case SK::EnumConstant:
147 return true;
148 default:
149 return false;
150 }
151}
152
153/// Gets a canonical include (<header> or "header") for header of \p Loc.
154/// Returns None if the header has no canonical include.
155/// FIXME: we should handle .inc files whose symbols are expected be exported by
156/// their containing headers.
157llvm::Optional<std::string>
158getIncludeHeader(const SourceManager &SM, SourceLocation Loc,
159 const SymbolCollector::Options &Opts) {
160 llvm::StringRef FilePath = SM.getFilename(Loc);
161 if (FilePath.empty())
162 return llvm::None;
163 if (Opts.Includes) {
164 llvm::StringRef Mapped = Opts.Includes->mapHeader(FilePath);
165 if (Mapped != FilePath)
166 return (Mapped.startswith("<") || Mapped.startswith("\""))
167 ? Mapped.str()
168 : ("\"" + Mapped + "\"").str();
169 }
170 // If the header path is the same as the file path of the declaration, we skip
171 // storing the #include path; users can use the URI in declaration location to
172 // calculate the #include path.
173 return llvm::None;
174}
175
Haojian Wub0189062018-01-31 12:56:51 +0000176// Return the symbol location of the given declaration `D`.
177//
178// For symbols defined inside macros:
179// * use expansion location, if the symbol is formed via macro concatenation.
180// * use spelling location, otherwise.
Eric Liu7f247652018-02-06 16:10:35 +0000181llvm::Optional<SymbolLocation>
Sam McCall60039512018-02-09 14:42:01 +0000182getSymbolLocation(const NamedDecl &D, SourceManager &SM,
Eric Liu7f247652018-02-06 16:10:35 +0000183 const SymbolCollector::Options &Opts,
Haojian Wudc02a3d2018-02-13 09:53:50 +0000184 const clang::LangOptions& LangOpts,
Eric Liu7f247652018-02-06 16:10:35 +0000185 std::string &FileURIStorage) {
Haojian Wudc02a3d2018-02-13 09:53:50 +0000186 SourceLocation SpellingLoc = SM.getSpellingLoc(D.getLocation());
187 if (D.getLocation().isMacroID()) {
188 std::string PrintLoc = SpellingLoc.printToString(SM);
Haojian Wu3b8e00c2018-02-06 09:50:35 +0000189 if (llvm::StringRef(PrintLoc).startswith("<scratch") ||
190 llvm::StringRef(PrintLoc).startswith("<command line>")) {
Eric Liu7f247652018-02-06 16:10:35 +0000191 // We use the expansion location for the following symbols, as spelling
192 // locations of these symbols are not interesting to us:
193 // * symbols formed via macro concatenation, the spelling location will
194 // be "<scratch space>"
195 // * symbols controlled and defined by a compile command-line option
196 // `-DName=foo`, the spelling location will be "<command line>".
Haojian Wudc02a3d2018-02-13 09:53:50 +0000197 SpellingLoc = SM.getExpansionRange(D.getLocation()).first;
Haojian Wub0189062018-01-31 12:56:51 +0000198 }
199 }
200
Haojian Wudc02a3d2018-02-13 09:53:50 +0000201 auto U = toURI(SM, SM.getFilename(SpellingLoc), Opts);
Eric Liu7f247652018-02-06 16:10:35 +0000202 if (!U)
203 return llvm::None;
204 FileURIStorage = std::move(*U);
Sam McCall60039512018-02-09 14:42:01 +0000205 SymbolLocation Result;
206 Result.FileURI = FileURIStorage;
Haojian Wudc02a3d2018-02-13 09:53:50 +0000207 Result.StartOffset = SM.getFileOffset(SpellingLoc);
208 Result.EndOffset = Result.StartOffset + clang::Lexer::MeasureTokenLength(
209 SpellingLoc, SM, LangOpts);
Sam McCall60039512018-02-09 14:42:01 +0000210 return std::move(Result);
Haojian Wub0189062018-01-31 12:56:51 +0000211}
212
Haojian Wu4c1394d2017-12-12 15:42:10 +0000213} // namespace
214
Eric Liu9af958f2018-01-10 14:57:58 +0000215SymbolCollector::SymbolCollector(Options Opts) : Opts(std::move(Opts)) {}
216
Eric Liu76f6b442018-01-09 17:32:00 +0000217void SymbolCollector::initialize(ASTContext &Ctx) {
218 ASTCtx = &Ctx;
219 CompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
220 CompletionTUInfo =
221 llvm::make_unique<CodeCompletionTUInfo>(CompletionAllocator);
222}
223
Haojian Wu4c1394d2017-12-12 15:42:10 +0000224// Always return true to continue indexing.
225bool SymbolCollector::handleDeclOccurence(
226 const Decl *D, index::SymbolRoleSet Roles,
227 ArrayRef<index::SymbolRelation> Relations, FileID FID, unsigned Offset,
228 index::IndexDataConsumer::ASTNodeInfo ASTNode) {
Eric Liu9af958f2018-01-10 14:57:58 +0000229 assert(ASTCtx && PP.get() && "ASTContext and Preprocessor must be set.");
230
Haojian Wu4c1394d2017-12-12 15:42:10 +0000231 // FIXME: collect all symbol references.
232 if (!(Roles & static_cast<unsigned>(index::SymbolRole::Declaration) ||
233 Roles & static_cast<unsigned>(index::SymbolRole::Definition)))
234 return true;
235
Eric Liu76f6b442018-01-09 17:32:00 +0000236 assert(CompletionAllocator && CompletionTUInfo);
237
Haojian Wu4c1394d2017-12-12 15:42:10 +0000238 if (const NamedDecl *ND = llvm::dyn_cast<NamedDecl>(D)) {
Eric Liu9af958f2018-01-10 14:57:58 +0000239 if (shouldFilterDecl(ND, ASTCtx, Opts))
Haojian Wu4c1394d2017-12-12 15:42:10 +0000240 return true;
Benjamin Kramer50a967d2017-12-28 14:47:01 +0000241 llvm::SmallString<128> USR;
242 if (index::generateUSRForDecl(ND, USR))
Haojian Wu4c1394d2017-12-12 15:42:10 +0000243 return true;
244
Haojian Wu4c1394d2017-12-12 15:42:10 +0000245 auto ID = SymbolID(USR);
Sam McCall60039512018-02-09 14:42:01 +0000246 const Symbol* BasicSymbol = Symbols.find(ID);
247 if (!BasicSymbol) // Regardless of role, ND is the canonical declaration.
248 BasicSymbol = addDeclaration(*ND, std::move(ID));
249 if (Roles & static_cast<unsigned>(index::SymbolRole::Definition))
250 addDefinition(*cast<NamedDecl>(ASTNode.OrigD), *BasicSymbol);
Haojian Wu4c1394d2017-12-12 15:42:10 +0000251 }
Haojian Wu4c1394d2017-12-12 15:42:10 +0000252 return true;
253}
254
Sam McCall60039512018-02-09 14:42:01 +0000255const Symbol *SymbolCollector::addDeclaration(const NamedDecl &ND,
256 SymbolID ID) {
257 auto &SM = ND.getASTContext().getSourceManager();
258
259 std::string QName;
260 llvm::raw_string_ostream OS(QName);
261 PrintingPolicy Policy(ASTCtx->getLangOpts());
262 // Note that inline namespaces are treated as transparent scopes. This
263 // reflects the way they're most commonly used for lookup. Ideally we'd
264 // include them, but at query time it's hard to find all the inline
265 // namespaces to query: the preamble doesn't have a dedicated list.
266 Policy.SuppressUnwrittenScope = true;
267 ND.printQualifiedName(OS, Policy);
268 OS.flush();
269
270 Symbol S;
271 S.ID = std::move(ID);
272 std::tie(S.Scope, S.Name) = splitQualifiedName(QName);
273 S.SymInfo = index::getSymbolInfo(&ND);
274 std::string FileURI;
275 // FIXME: we may want a different "canonical" heuristic than clang chooses.
276 // Clang seems to choose the first, which may not have the most information.
Haojian Wudc02a3d2018-02-13 09:53:50 +0000277 if (auto DeclLoc =
278 getSymbolLocation(ND, SM, Opts, ASTCtx->getLangOpts(), FileURI))
Sam McCall60039512018-02-09 14:42:01 +0000279 S.CanonicalDeclaration = *DeclLoc;
280
281 // Add completion info.
282 // FIXME: we may want to choose a different redecl, or combine from several.
283 assert(ASTCtx && PP.get() && "ASTContext and Preprocessor must be set.");
284 CodeCompletionResult SymbolCompletion(&ND, 0);
285 const auto *CCS = SymbolCompletion.CreateCodeCompletionString(
286 *ASTCtx, *PP, CodeCompletionContext::CCC_Name, *CompletionAllocator,
287 *CompletionTUInfo,
288 /*IncludeBriefComments*/ true);
289 std::string Label;
290 std::string SnippetInsertText;
291 std::string IgnoredLabel;
292 std::string PlainInsertText;
293 getLabelAndInsertText(*CCS, &Label, &SnippetInsertText,
294 /*EnableSnippets=*/true);
295 getLabelAndInsertText(*CCS, &IgnoredLabel, &PlainInsertText,
296 /*EnableSnippets=*/false);
297 std::string FilterText = getFilterText(*CCS);
298 std::string Documentation = getDocumentation(*CCS);
299 std::string CompletionDetail = getDetail(*CCS);
300
Eric Liuc5105f92018-02-16 14:15:55 +0000301 std::string Include;
302 if (Opts.CollectIncludePath && shouldCollectIncludePath(S.SymInfo.Kind)) {
303 // Use the expansion location to get the #include header since this is
304 // where the symbol is exposed.
305 if (auto Header =
306 getIncludeHeader(SM, SM.getExpansionLoc(ND.getLocation()), Opts))
307 Include = std::move(*Header);
308 }
Sam McCall60039512018-02-09 14:42:01 +0000309 S.CompletionFilterText = FilterText;
310 S.CompletionLabel = Label;
311 S.CompletionPlainInsertText = PlainInsertText;
312 S.CompletionSnippetInsertText = SnippetInsertText;
313 Symbol::Details Detail;
314 Detail.Documentation = Documentation;
315 Detail.CompletionDetail = CompletionDetail;
Eric Liuc5105f92018-02-16 14:15:55 +0000316 Detail.IncludeHeader = Include;
Sam McCall60039512018-02-09 14:42:01 +0000317 S.Detail = &Detail;
318
319 Symbols.insert(S);
320 return Symbols.find(S.ID);
321}
322
323void SymbolCollector::addDefinition(const NamedDecl &ND,
324 const Symbol &DeclSym) {
325 if (DeclSym.Definition)
326 return;
327 // If we saw some forward declaration, we end up copying the symbol.
328 // This is not ideal, but avoids duplicating the "is this a definition" check
329 // in clang::index. We should only see one definition.
330 Symbol S = DeclSym;
331 std::string FileURI;
332 if (auto DefLoc = getSymbolLocation(ND, ND.getASTContext().getSourceManager(),
Haojian Wudc02a3d2018-02-13 09:53:50 +0000333 Opts, ASTCtx->getLangOpts(), FileURI))
Sam McCall60039512018-02-09 14:42:01 +0000334 S.Definition = *DefLoc;
335 Symbols.insert(S);
336}
337
Haojian Wu4c1394d2017-12-12 15:42:10 +0000338} // namespace clangd
339} // namespace clang