blob: cdc6aa5c01f44a8a4816d6ce2f832dd677ebecbd [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 Liuf7688682018-09-07 09:40:36 +000011#include "AST.h"
Eric Liuc5105f92018-02-16 14:15:55 +000012#include "CanonicalIncludes.h"
Eric Liuf7688682018-09-07 09:40:36 +000013#include "CodeComplete.h"
14#include "CodeCompletionStrings.h"
15#include "Logger.h"
16#include "SourceCode.h"
17#include "URI.h"
Eric Liua57afd02018-09-17 07:43:49 +000018#include "clang/AST/Decl.h"
19#include "clang/AST/DeclBase.h"
Haojian Wu4c1394d2017-12-12 15:42:10 +000020#include "clang/AST/DeclCXX.h"
Ilya Biryukovcf124bd2018-04-13 11:03:07 +000021#include "clang/AST/DeclTemplate.h"
Haojian Wu7dd49502018-10-17 08:38:36 +000022#include "clang/Basic/SourceLocation.h"
Haojian Wu4c1394d2017-12-12 15:42:10 +000023#include "clang/Basic/SourceManager.h"
Eric Liua57afd02018-09-17 07:43:49 +000024#include "clang/Basic/Specifiers.h"
Haojian Wu4c1394d2017-12-12 15:42:10 +000025#include "clang/Index/IndexSymbol.h"
26#include "clang/Index/USRGeneration.h"
Eric Liua57afd02018-09-17 07:43:49 +000027#include "llvm/Support/Casting.h"
Eric Liu278e2d12018-01-29 15:13:29 +000028#include "llvm/Support/FileSystem.h"
Haojian Wu4c1394d2017-12-12 15:42:10 +000029#include "llvm/Support/MemoryBuffer.h"
30#include "llvm/Support/Path.h"
31
32namespace clang {
33namespace clangd {
Haojian Wu4c1394d2017-12-12 15:42:10 +000034namespace {
Sam McCallc008af62018-10-20 15:30:37 +000035
Ilya Biryukovf118d512018-04-14 16:27:35 +000036/// If \p ND is a template specialization, returns the described template.
Ilya Biryukovcf124bd2018-04-13 11:03:07 +000037/// Otherwise, returns \p ND.
38const NamedDecl &getTemplateOrThis(const NamedDecl &ND) {
Ilya Biryukovf118d512018-04-14 16:27:35 +000039 if (auto T = ND.getDescribedTemplate())
40 return *T;
Ilya Biryukovcf124bd2018-04-13 11:03:07 +000041 return ND;
42}
43
Eric Liu7f247652018-02-06 16:10:35 +000044// Returns a URI of \p Path. Firstly, this makes the \p Path absolute using the
45// current working directory of the given SourceManager if the Path is not an
46// absolute path. If failed, this resolves relative paths against \p FallbackDir
47// to get an absolute path. Then, this tries creating an URI for the absolute
48// path with schemes specified in \p Opts. This returns an URI with the first
49// working scheme, if there is any; otherwise, this returns None.
Haojian Wu4c1394d2017-12-12 15:42:10 +000050//
51// The Path can be a path relative to the build directory, or retrieved from
52// the SourceManager.
Kadir Cetinkayadd677932018-12-19 10:46:21 +000053std::string toURI(const SourceManager &SM, llvm::StringRef Path,
54 const SymbolCollector::Options &Opts) {
55 llvm::SmallString<128> AbsolutePath(Path);
56 if (auto CanonPath =
57 getCanonicalPath(SM.getFileManager().getFile(Path), SM)) {
58 AbsolutePath = *CanonPath;
Haojian Wu4c1394d2017-12-12 15:42:10 +000059 }
Kadir Cetinkayadd677932018-12-19 10:46:21 +000060 // We don't perform is_absolute check in an else branch because makeAbsolute
61 // might return a relative path on some InMemoryFileSystems.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000062 if (!llvm::sys::path::is_absolute(AbsolutePath) && !Opts.FallbackDir.empty())
63 llvm::sys::fs::make_absolute(Opts.FallbackDir, AbsolutePath);
64 llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/true);
Eric Liuc0ac4bb2018-11-22 15:02:05 +000065 return URI::create(AbsolutePath).toString();
Haojian Wu4c1394d2017-12-12 15:42:10 +000066}
Eric Liu4feda802017-12-19 11:37:40 +000067
Eric Liud67ec242018-05-16 12:12:30 +000068// All proto generated headers should start with this line.
69static const char *PROTO_HEADER_COMMENT =
70 "// Generated by the protocol buffer compiler. DO NOT EDIT!";
71
72// Checks whether the decl is a private symbol in a header generated by
73// protobuf compiler.
74// To identify whether a proto header is actually generated by proto compiler,
75// we check whether it starts with PROTO_HEADER_COMMENT.
76// FIXME: make filtering extensible when there are more use cases for symbol
77// filters.
78bool isPrivateProtoDecl(const NamedDecl &ND) {
79 const auto &SM = ND.getASTContext().getSourceManager();
80 auto Loc = findNameLoc(&ND);
81 auto FileName = SM.getFilename(Loc);
82 if (!FileName.endswith(".proto.h") && !FileName.endswith(".pb.h"))
83 return false;
84 auto FID = SM.getFileID(Loc);
85 // Double check that this is an actual protobuf header.
86 if (!SM.getBufferData(FID).startswith(PROTO_HEADER_COMMENT))
87 return false;
88
89 // ND without identifier can be operators.
90 if (ND.getIdentifier() == nullptr)
91 return false;
92 auto Name = ND.getIdentifier()->getName();
93 if (!Name.contains('_'))
94 return false;
95 // Nested proto entities (e.g. Message::Nested) have top-level decls
96 // that shouldn't be used (Message_Nested). Ignore them completely.
97 // The nested entities are dangling type aliases, we may want to reconsider
98 // including them in the future.
99 // For enum constants, SOME_ENUM_CONSTANT is not private and should be
100 // indexed. Outer_INNER is private. This heuristic relies on naming style, it
101 // will include OUTER_INNER and exclude some_enum_constant.
102 // FIXME: the heuristic relies on naming style (i.e. no underscore in
103 // user-defined names) and can be improved.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000104 return (ND.getKind() != Decl::EnumConstant) || llvm::any_of(Name, islower);
Eric Liud67ec242018-05-16 12:12:30 +0000105}
106
Eric Liuc5105f92018-02-16 14:15:55 +0000107// We only collect #include paths for symbols that are suitable for global code
108// completion, except for namespaces since #include path for a namespace is hard
109// to define.
110bool shouldCollectIncludePath(index::SymbolKind Kind) {
111 using SK = index::SymbolKind;
112 switch (Kind) {
113 case SK::Macro:
114 case SK::Enum:
115 case SK::Struct:
116 case SK::Class:
117 case SK::Union:
118 case SK::TypeAlias:
119 case SK::Using:
120 case SK::Function:
121 case SK::Variable:
122 case SK::EnumConstant:
123 return true;
124 default:
125 return false;
126 }
127}
128
Eric Liu02ce01f2018-02-22 10:14:05 +0000129/// Gets a canonical include (URI of the header or <header> or "header") for
130/// header of \p Loc.
131/// Returns None if fails to get include header for \p Loc.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000132llvm::Optional<std::string>
133getIncludeHeader(llvm::StringRef QName, const SourceManager &SM,
134 SourceLocation Loc, const SymbolCollector::Options &Opts) {
Eric Liu3cee95e2018-05-24 14:40:24 +0000135 std::vector<std::string> Headers;
136 // Collect the #include stack.
137 while (true) {
138 if (!Loc.isValid())
139 break;
140 auto FilePath = SM.getFilename(Loc);
141 if (FilePath.empty())
142 break;
143 Headers.push_back(FilePath);
144 if (SM.isInMainFile(Loc))
145 break;
146 Loc = SM.getIncludeLoc(SM.getFileID(Loc));
Eric Liuc5105f92018-02-16 14:15:55 +0000147 }
Eric Liu3cee95e2018-05-24 14:40:24 +0000148 if (Headers.empty())
Sam McCallc008af62018-10-20 15:30:37 +0000149 return None;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000150 llvm::StringRef Header = Headers[0];
Eric Liu3cee95e2018-05-24 14:40:24 +0000151 if (Opts.Includes) {
152 Header = Opts.Includes->mapHeader(Headers, QName);
153 if (Header.startswith("<") || Header.startswith("\""))
154 return Header.str();
155 }
156 return toURI(SM, Header, Opts);
Eric Liuc5105f92018-02-16 14:15:55 +0000157}
158
Haojian Wud81e3142018-08-31 12:54:13 +0000159// Return the symbol range of the token at \p TokLoc.
160std::pair<SymbolLocation::Position, SymbolLocation::Position>
161getTokenRange(SourceLocation TokLoc, const SourceManager &SM,
162 const LangOptions &LangOpts) {
163 auto CreatePosition = [&SM](SourceLocation Loc) {
164 auto LSPLoc = sourceLocToPosition(SM, Loc);
165 SymbolLocation::Position Pos;
Haojian Wub515fab2018-10-18 10:43:50 +0000166 Pos.setLine(LSPLoc.line);
167 Pos.setColumn(LSPLoc.character);
Haojian Wud81e3142018-08-31 12:54:13 +0000168 return Pos;
169 };
170
171 auto TokenLength = clang::Lexer::MeasureTokenLength(TokLoc, SM, LangOpts);
172 return {CreatePosition(TokLoc),
173 CreatePosition(TokLoc.getLocWithOffset(TokenLength))};
174}
175
Eric Liuad588af2018-11-06 10:55:21 +0000176bool shouldIndexFile(const SourceManager &SM, FileID FID,
177 const SymbolCollector::Options &Opts,
178 llvm::DenseMap<FileID, bool> *FilesToIndexCache) {
179 if (!Opts.FileFilter)
180 return true;
181 auto I = FilesToIndexCache->try_emplace(FID);
182 if (I.second)
183 I.first->second = Opts.FileFilter(SM, FID);
184 return I.first->second;
185}
186
Haojian Wud81e3142018-08-31 12:54:13 +0000187// Return the symbol location of the token at \p TokLoc.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000188llvm::Optional<SymbolLocation>
189getTokenLocation(SourceLocation TokLoc, const SourceManager &SM,
190 const SymbolCollector::Options &Opts,
191 const clang::LangOptions &LangOpts,
192 std::string &FileURIStorage) {
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000193 auto Path = SM.getFilename(TokLoc);
194 if (Path.empty())
Sam McCallc008af62018-10-20 15:30:37 +0000195 return None;
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000196 FileURIStorage = toURI(SM, Path, Opts);
Sam McCall60039512018-02-09 14:42:01 +0000197 SymbolLocation Result;
Haojian Wuee54a2b2018-11-14 11:55:45 +0000198 Result.FileURI = FileURIStorage.c_str();
Haojian Wud81e3142018-08-31 12:54:13 +0000199 auto Range = getTokenRange(TokLoc, SM, LangOpts);
200 Result.Start = Range.first;
201 Result.End = Range.second;
Haojian Wu545c02a2018-04-13 08:30:39 +0000202
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000203 return Result;
Haojian Wub0189062018-01-31 12:56:51 +0000204}
205
Eric Liucf8601b2018-02-28 09:33:15 +0000206// Checks whether \p ND is a definition of a TagDecl (class/struct/enum/union)
207// in a header file, in which case clangd would prefer to use ND as a canonical
208// declaration.
209// FIXME: handle symbol types that are not TagDecl (e.g. functions), if using
Fangrui Song943e12e2018-03-29 20:03:16 +0000210// the first seen declaration as canonical declaration is not a good enough
Eric Liucf8601b2018-02-28 09:33:15 +0000211// heuristic.
212bool isPreferredDeclaration(const NamedDecl &ND, index::SymbolRoleSet Roles) {
Sam McCall5fb97462018-10-05 14:03:04 +0000213 const auto& SM = ND.getASTContext().getSourceManager();
Eric Liucf8601b2018-02-28 09:33:15 +0000214 return (Roles & static_cast<unsigned>(index::SymbolRole::Definition)) &&
Sam McCallc008af62018-10-20 15:30:37 +0000215 isa<TagDecl>(&ND) &&
Sam McCall5fb97462018-10-05 14:03:04 +0000216 !SM.isWrittenInMainFile(SM.getExpansionLoc(ND.getLocation()));
Eric Liucf8601b2018-02-28 09:33:15 +0000217}
218
Sam McCallb0138312018-09-04 14:39:56 +0000219RefKind toRefKind(index::SymbolRoleSet Roles) {
220 return static_cast<RefKind>(static_cast<unsigned>(RefKind::All) & Roles);
Haojian Wud81e3142018-08-31 12:54:13 +0000221}
222
Eric Liua57afd02018-09-17 07:43:49 +0000223template <class T> bool explicitTemplateSpecialization(const NamedDecl &ND) {
Sam McCallc008af62018-10-20 15:30:37 +0000224 if (const auto *TD = dyn_cast<T>(&ND))
Eric Liua57afd02018-09-17 07:43:49 +0000225 if (TD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
226 return true;
227 return false;
228}
229
Haojian Wu4c1394d2017-12-12 15:42:10 +0000230} // namespace
231
Eric Liu9af958f2018-01-10 14:57:58 +0000232SymbolCollector::SymbolCollector(Options Opts) : Opts(std::move(Opts)) {}
233
Eric Liu76f6b442018-01-09 17:32:00 +0000234void SymbolCollector::initialize(ASTContext &Ctx) {
235 ASTCtx = &Ctx;
236 CompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
237 CompletionTUInfo =
238 llvm::make_unique<CodeCompletionTUInfo>(CompletionAllocator);
239}
240
Eric Liu8763e482018-06-21 12:12:26 +0000241bool SymbolCollector::shouldCollectSymbol(const NamedDecl &ND,
Haojian Wu7800dbe2018-12-03 13:16:04 +0000242 const ASTContext &ASTCtx,
Eric Liu8763e482018-06-21 12:12:26 +0000243 const Options &Opts) {
Eric Liu8763e482018-06-21 12:12:26 +0000244 if (ND.isImplicit())
245 return false;
246 // Skip anonymous declarations, e.g (anonymous enum/class/struct).
247 if (ND.getDeclName().isEmpty())
248 return false;
249
250 // FIXME: figure out a way to handle internal linkage symbols (e.g. static
251 // variables, function) defined in the .cc files. Also we skip the symbols
252 // in anonymous namespace as the qualifier names of these symbols are like
253 // `foo::<anonymous>::bar`, which need a special handling.
254 // In real world projects, we have a relatively large set of header files
255 // that define static variables (like "static const int A = 1;"), we still
256 // want to collect these symbols, although they cause potential ODR
257 // violations.
258 if (ND.isInAnonymousNamespace())
259 return false;
260
261 // We want most things but not "local" symbols such as symbols inside
262 // FunctionDecl, BlockDecl, ObjCMethodDecl and OMPDeclareReductionDecl.
263 // FIXME: Need a matcher for ExportDecl in order to include symbols declared
264 // within an export.
Eric Liua57afd02018-09-17 07:43:49 +0000265 const auto *DeclCtx = ND.getDeclContext();
266 switch (DeclCtx->getDeclKind()) {
267 case Decl::TranslationUnit:
268 case Decl::Namespace:
269 case Decl::LinkageSpec:
270 case Decl::Enum:
271 case Decl::ObjCProtocol:
272 case Decl::ObjCInterface:
273 case Decl::ObjCCategory:
274 case Decl::ObjCCategoryImpl:
275 case Decl::ObjCImplementation:
276 break;
277 default:
278 // Record has a few derivations (e.g. CXXRecord, Class specialization), it's
279 // easier to cast.
Sam McCallc008af62018-10-20 15:30:37 +0000280 if (!isa<RecordDecl>(DeclCtx))
Eric Liua57afd02018-09-17 07:43:49 +0000281 return false;
282 }
283 if (explicitTemplateSpecialization<FunctionDecl>(ND) ||
284 explicitTemplateSpecialization<CXXRecordDecl>(ND) ||
285 explicitTemplateSpecialization<VarDecl>(ND))
Eric Liu8763e482018-06-21 12:12:26 +0000286 return false;
287
Eric Liua57afd02018-09-17 07:43:49 +0000288 const auto &SM = ASTCtx.getSourceManager();
289 // Skip decls in the main file.
290 if (SM.isInMainFile(SM.getExpansionLoc(ND.getBeginLoc())))
291 return false;
Eric Liu8763e482018-06-21 12:12:26 +0000292 // Avoid indexing internal symbols in protobuf generated headers.
293 if (isPrivateProtoDecl(ND))
294 return false;
295 return true;
296}
297
Haojian Wu4c1394d2017-12-12 15:42:10 +0000298// Always return true to continue indexing.
299bool SymbolCollector::handleDeclOccurence(
300 const Decl *D, index::SymbolRoleSet Roles,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000301 llvm::ArrayRef<index::SymbolRelation> Relations, SourceLocation Loc,
Haojian Wu4c1394d2017-12-12 15:42:10 +0000302 index::IndexDataConsumer::ASTNodeInfo ASTNode) {
Eric Liu9af958f2018-01-10 14:57:58 +0000303 assert(ASTCtx && PP.get() && "ASTContext and Preprocessor must be set.");
Sam McCall93f99bf2018-03-12 14:49:09 +0000304 assert(CompletionAllocator && CompletionTUInfo);
Eric Liu77d18112018-06-04 11:31:55 +0000305 assert(ASTNode.OrigD);
306 // If OrigD is an declaration associated with a friend declaration and it's
307 // not a definition, skip it. Note that OrigD is the occurrence that the
308 // collector is currently visiting.
309 if ((ASTNode.OrigD->getFriendObjectKind() !=
310 Decl::FriendObjectKind::FOK_None) &&
311 !(Roles & static_cast<unsigned>(index::SymbolRole::Definition)))
312 return true;
313 // A declaration created for a friend declaration should not be used as the
314 // canonical declaration in the index. Use OrigD instead, unless we've already
315 // picked a replacement for D
316 if (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None)
317 D = CanonicalDecls.try_emplace(D, ASTNode.OrigD).first->second;
Sam McCallc008af62018-10-20 15:30:37 +0000318 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Sam McCall93f99bf2018-03-12 14:49:09 +0000319 if (!ND)
320 return true;
Eric Liu9af958f2018-01-10 14:57:58 +0000321
Sam McCall93f99bf2018-03-12 14:49:09 +0000322 // Mark D as referenced if this is a reference coming from the main file.
323 // D may not be an interesting symbol, but it's cheaper to check at the end.
Sam McCallb9d57112018-04-09 14:28:52 +0000324 auto &SM = ASTCtx->getSourceManager();
Haojian Wud81e3142018-08-31 12:54:13 +0000325 auto SpellingLoc = SM.getSpellingLoc(Loc);
Sam McCall93f99bf2018-03-12 14:49:09 +0000326 if (Opts.CountReferences &&
327 (Roles & static_cast<unsigned>(index::SymbolRole::Reference)) &&
Haojian Wud81e3142018-08-31 12:54:13 +0000328 SM.getFileID(SpellingLoc) == SM.getMainFileID())
Sam McCall93f99bf2018-03-12 14:49:09 +0000329 ReferencedDecls.insert(ND);
330
Haojian Wue83cacc2018-10-15 11:46:26 +0000331 bool CollectRef = static_cast<unsigned>(Opts.RefFilter) & Roles;
332 bool IsOnlyRef =
333 !(Roles & (static_cast<unsigned>(index::SymbolRole::Declaration) |
334 static_cast<unsigned>(index::SymbolRole::Definition)));
Haojian Wud81e3142018-08-31 12:54:13 +0000335
Haojian Wue83cacc2018-10-15 11:46:26 +0000336 if (IsOnlyRef && !CollectRef)
Haojian Wu4c1394d2017-12-12 15:42:10 +0000337 return true;
Eric Liu8763e482018-06-21 12:12:26 +0000338 if (!shouldCollectSymbol(*ND, *ASTCtx, Opts))
Sam McCall93f99bf2018-03-12 14:49:09 +0000339 return true;
Haojian Wuf761a2c2018-11-07 14:59:24 +0000340 if (CollectRef && !isa<NamespaceDecl>(ND) &&
Haojian Wu7dd49502018-10-17 08:38:36 +0000341 (Opts.RefsInHeaders || SM.getFileID(SpellingLoc) == SM.getMainFileID()))
Haojian Wue83cacc2018-10-15 11:46:26 +0000342 DeclRefs[ND].emplace_back(SpellingLoc, Roles);
343 // Don't continue indexing if this is a mere reference.
344 if (IsOnlyRef)
345 return true;
Haojian Wu4c1394d2017-12-12 15:42:10 +0000346
Haojian Wuc6ddb462018-08-07 08:57:52 +0000347 auto ID = getSymbolID(ND);
348 if (!ID)
Sam McCall93f99bf2018-03-12 14:49:09 +0000349 return true;
Eric Liu76f6b442018-01-09 17:32:00 +0000350
Sam McCall93f99bf2018-03-12 14:49:09 +0000351 const NamedDecl &OriginalDecl = *cast<NamedDecl>(ASTNode.OrigD);
Haojian Wuc6ddb462018-08-07 08:57:52 +0000352 const Symbol *BasicSymbol = Symbols.find(*ID);
Sam McCall93f99bf2018-03-12 14:49:09 +0000353 if (!BasicSymbol) // Regardless of role, ND is the canonical declaration.
Haojian Wuc6ddb462018-08-07 08:57:52 +0000354 BasicSymbol = addDeclaration(*ND, std::move(*ID));
Sam McCall93f99bf2018-03-12 14:49:09 +0000355 else if (isPreferredDeclaration(OriginalDecl, Roles))
356 // If OriginalDecl is preferred, replace the existing canonical
357 // declaration (e.g. a class forward declaration). There should be at most
358 // one duplicate as we expect to see only one preferred declaration per
359 // TU, because in practice they are definitions.
Haojian Wuc6ddb462018-08-07 08:57:52 +0000360 BasicSymbol = addDeclaration(OriginalDecl, std::move(*ID));
Haojian Wu4c1394d2017-12-12 15:42:10 +0000361
Sam McCall93f99bf2018-03-12 14:49:09 +0000362 if (Roles & static_cast<unsigned>(index::SymbolRole::Definition))
363 addDefinition(OriginalDecl, *BasicSymbol);
Haojian Wu4c1394d2017-12-12 15:42:10 +0000364 return true;
365}
366
Eric Liu48db19e2018-07-09 15:31:07 +0000367bool SymbolCollector::handleMacroOccurence(const IdentifierInfo *Name,
368 const MacroInfo *MI,
369 index::SymbolRoleSet Roles,
370 SourceLocation Loc) {
371 if (!Opts.CollectMacro)
372 return true;
373 assert(PP.get());
374
375 const auto &SM = PP->getSourceManager();
Eric Liuad588af2018-11-06 10:55:21 +0000376 auto DefLoc = MI->getDefinitionLoc();
377 if (SM.isInMainFile(SM.getExpansionLoc(DefLoc)))
Eric Liu48db19e2018-07-09 15:31:07 +0000378 return true;
379 // Header guards are not interesting in index. Builtin macros don't have
380 // useful locations and are not needed for code completions.
381 if (MI->isUsedForHeaderGuard() || MI->isBuiltinMacro())
382 return true;
383
384 // Mark the macro as referenced if this is a reference coming from the main
385 // file. The macro may not be an interesting symbol, but it's cheaper to check
386 // at the end.
387 if (Opts.CountReferences &&
388 (Roles & static_cast<unsigned>(index::SymbolRole::Reference)) &&
389 SM.getFileID(SM.getSpellingLoc(Loc)) == SM.getMainFileID())
390 ReferencedMacros.insert(Name);
391 // Don't continue indexing if this is a mere reference.
392 // FIXME: remove macro with ID if it is undefined.
393 if (!(Roles & static_cast<unsigned>(index::SymbolRole::Declaration) ||
394 Roles & static_cast<unsigned>(index::SymbolRole::Definition)))
395 return true;
396
Eric Liud25f1212018-09-06 09:59:37 +0000397 auto ID = getSymbolID(*Name, MI, SM);
398 if (!ID)
Eric Liu48db19e2018-07-09 15:31:07 +0000399 return true;
Eric Liu48db19e2018-07-09 15:31:07 +0000400
401 // Only collect one instance in case there are multiple.
Eric Liud25f1212018-09-06 09:59:37 +0000402 if (Symbols.find(*ID) != nullptr)
Eric Liu48db19e2018-07-09 15:31:07 +0000403 return true;
404
405 Symbol S;
Eric Liud25f1212018-09-06 09:59:37 +0000406 S.ID = std::move(*ID);
Eric Liu48db19e2018-07-09 15:31:07 +0000407 S.Name = Name->getName();
Eric Liu6df66002018-09-06 18:52:26 +0000408 S.Flags |= Symbol::IndexedForCodeCompletion;
Eric Liu48db19e2018-07-09 15:31:07 +0000409 S.SymInfo = index::getSymbolInfoForMacro(*MI);
410 std::string FileURI;
Eric Liuad588af2018-11-06 10:55:21 +0000411 // FIXME: use the result to filter out symbols.
412 shouldIndexFile(SM, SM.getFileID(Loc), Opts, &FilesToIndexCache);
413 if (auto DeclLoc =
414 getTokenLocation(DefLoc, SM, Opts, PP->getLangOpts(), FileURI))
Eric Liu48db19e2018-07-09 15:31:07 +0000415 S.CanonicalDeclaration = *DeclLoc;
416
417 CodeCompletionResult SymbolCompletion(Name);
418 const auto *CCS = SymbolCompletion.CreateCodeCompletionStringForMacro(
419 *PP, *CompletionAllocator, *CompletionTUInfo);
420 std::string Signature;
421 std::string SnippetSuffix;
422 getSignature(*CCS, &Signature, &SnippetSuffix);
423
424 std::string Include;
425 if (Opts.CollectIncludePath && shouldCollectIncludePath(S.SymInfo.Kind)) {
Eric Liuad588af2018-11-06 10:55:21 +0000426 if (auto Header = getIncludeHeader(Name->getName(), SM,
427 SM.getExpansionLoc(DefLoc), Opts))
Eric Liu48db19e2018-07-09 15:31:07 +0000428 Include = std::move(*Header);
429 }
430 S.Signature = Signature;
431 S.CompletionSnippetSuffix = SnippetSuffix;
Eric Liu83f63e42018-09-03 10:18:21 +0000432 if (!Include.empty())
433 S.IncludeHeaders.emplace_back(Include, 1);
434
Eric Liu48db19e2018-07-09 15:31:07 +0000435 Symbols.insert(S);
436 return true;
437}
438
Sam McCall93f99bf2018-03-12 14:49:09 +0000439void SymbolCollector::finish() {
Eric Liu48db19e2018-07-09 15:31:07 +0000440 // At the end of the TU, add 1 to the refcount of all referenced symbols.
441 auto IncRef = [this](const SymbolID &ID) {
442 if (const auto *S = Symbols.find(ID)) {
443 Symbol Inc = *S;
444 ++Inc.References;
445 Symbols.insert(Inc);
446 }
447 };
448 for (const NamedDecl *ND : ReferencedDecls) {
Haojian Wuc6ddb462018-08-07 08:57:52 +0000449 if (auto ID = getSymbolID(ND)) {
450 IncRef(*ID);
451 }
Eric Liu48db19e2018-07-09 15:31:07 +0000452 }
453 if (Opts.CollectMacro) {
454 assert(PP);
455 for (const IdentifierInfo *II : ReferencedMacros) {
Eric Liua62c9d62018-07-09 18:54:51 +0000456 if (const auto *MI = PP->getMacroDefinition(II).getMacroInfo())
Eric Liud25f1212018-09-06 09:59:37 +0000457 if (auto ID = getSymbolID(*II, MI, PP->getSourceManager()))
458 IncRef(*ID);
Eric Liu48db19e2018-07-09 15:31:07 +0000459 }
Sam McCall93f99bf2018-03-12 14:49:09 +0000460 }
Haojian Wud81e3142018-08-31 12:54:13 +0000461
462 const auto &SM = ASTCtx->getSourceManager();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000463 llvm::DenseMap<FileID, std::string> URICache;
464 auto GetURI = [&](FileID FID) -> llvm::Optional<std::string> {
Haojian Wu7dd49502018-10-17 08:38:36 +0000465 auto Found = URICache.find(FID);
466 if (Found == URICache.end()) {
Haojian Wu7dd49502018-10-17 08:38:36 +0000467 if (auto *FileEntry = SM.getFileEntryForID(FID)) {
468 auto FileURI = toURI(SM, FileEntry->getName(), Opts);
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000469 Found = URICache.insert({FID, FileURI}).first;
Haojian Wuc014d862018-10-17 08:54:48 +0000470 } else {
471 // Ignore cases where we can not find a corresponding file entry
472 // for the loc, thoses are not interesting, e.g. symbols formed
473 // via macro concatenation.
Sam McCallc008af62018-10-20 15:30:37 +0000474 return None;
Haojian Wu7dd49502018-10-17 08:38:36 +0000475 }
476 }
477 return Found->second;
478 };
Haojian Wud81e3142018-08-31 12:54:13 +0000479
Haojian Wu7dd49502018-10-17 08:38:36 +0000480 if (auto MainFileURI = GetURI(SM.getMainFileID())) {
Sam McCallb0138312018-09-04 14:39:56 +0000481 for (const auto &It : DeclRefs) {
Haojian Wud81e3142018-08-31 12:54:13 +0000482 if (auto ID = getSymbolID(It.first)) {
Haojian Wue83cacc2018-10-15 11:46:26 +0000483 for (const auto &LocAndRole : It.second) {
Haojian Wu7dd49502018-10-17 08:38:36 +0000484 auto FileID = SM.getFileID(LocAndRole.first);
Eric Liuad588af2018-11-06 10:55:21 +0000485 // FIXME: use the result to filter out references.
486 shouldIndexFile(SM, FileID, Opts, &FilesToIndexCache);
Haojian Wu7dd49502018-10-17 08:38:36 +0000487 if (auto FileURI = GetURI(FileID)) {
488 auto Range =
489 getTokenRange(LocAndRole.first, SM, ASTCtx->getLangOpts());
490 Ref R;
491 R.Location.Start = Range.first;
492 R.Location.End = Range.second;
Haojian Wuee54a2b2018-11-14 11:55:45 +0000493 R.Location.FileURI = FileURI->c_str();
Haojian Wu7dd49502018-10-17 08:38:36 +0000494 R.Kind = toRefKind(LocAndRole.second);
495 Refs.insert(*ID, R);
496 }
Haojian Wud81e3142018-08-31 12:54:13 +0000497 }
498 }
499 }
Haojian Wud81e3142018-08-31 12:54:13 +0000500 }
501
Sam McCall93f99bf2018-03-12 14:49:09 +0000502 ReferencedDecls.clear();
Eric Liu48db19e2018-07-09 15:31:07 +0000503 ReferencedMacros.clear();
Sam McCallb0138312018-09-04 14:39:56 +0000504 DeclRefs.clear();
Eric Liuad588af2018-11-06 10:55:21 +0000505 FilesToIndexCache.clear();
Sam McCall93f99bf2018-03-12 14:49:09 +0000506}
507
Sam McCall60039512018-02-09 14:42:01 +0000508const Symbol *SymbolCollector::addDeclaration(const NamedDecl &ND,
509 SymbolID ID) {
Ilya Biryukov43714502018-05-16 12:32:44 +0000510 auto &Ctx = ND.getASTContext();
511 auto &SM = Ctx.getSourceManager();
Sam McCall60039512018-02-09 14:42:01 +0000512
Sam McCall60039512018-02-09 14:42:01 +0000513 Symbol S;
514 S.ID = std::move(ID);
Eric Liu7ad16962018-06-22 10:46:59 +0000515 std::string QName = printQualifiedName(ND);
Sam McCall60039512018-02-09 14:42:01 +0000516 std::tie(S.Scope, S.Name) = splitQualifiedName(QName);
Sam McCall032db942018-06-22 06:41:43 +0000517 // FIXME: this returns foo:bar: for objective-C methods, we prefer only foo:
518 // for consistency with CodeCompletionString and a clean name/signature split.
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +0000519
Eric Liu6df66002018-09-06 18:52:26 +0000520 if (isIndexedForCodeCompletion(ND, Ctx))
521 S.Flags |= Symbol::IndexedForCodeCompletion;
Eric Liu48597382018-10-18 12:23:05 +0000522 if (isImplementationDetail(&ND))
523 S.Flags |= Symbol::ImplementationDetail;
Sam McCall60039512018-02-09 14:42:01 +0000524 S.SymInfo = index::getSymbolInfo(&ND);
525 std::string FileURI;
Eric Liuad588af2018-11-06 10:55:21 +0000526 auto Loc = findNameLoc(&ND);
527 // FIXME: use the result to filter out symbols.
528 shouldIndexFile(SM, SM.getFileID(Loc), Opts, &FilesToIndexCache);
529 if (auto DeclLoc =
530 getTokenLocation(Loc, SM, Opts, ASTCtx->getLangOpts(), FileURI))
Sam McCall60039512018-02-09 14:42:01 +0000531 S.CanonicalDeclaration = *DeclLoc;
532
533 // Add completion info.
534 // FIXME: we may want to choose a different redecl, or combine from several.
535 assert(ASTCtx && PP.get() && "ASTContext and Preprocessor must be set.");
Ilya Biryukovcf124bd2018-04-13 11:03:07 +0000536 // We use the primary template, as clang does during code completion.
537 CodeCompletionResult SymbolCompletion(&getTemplateOrThis(ND), 0);
Sam McCall60039512018-02-09 14:42:01 +0000538 const auto *CCS = SymbolCompletion.CreateCodeCompletionString(
Kadir Cetinkayab9157902018-10-24 15:24:29 +0000539 *ASTCtx, *PP, CodeCompletionContext::CCC_Symbol, *CompletionAllocator,
Sam McCall60039512018-02-09 14:42:01 +0000540 *CompletionTUInfo,
Ilya Biryukov43714502018-05-16 12:32:44 +0000541 /*IncludeBriefComments*/ false);
Sam McCalla68951e2018-06-22 16:11:35 +0000542 std::string Signature;
543 std::string SnippetSuffix;
544 getSignature(*CCS, &Signature, &SnippetSuffix);
Ilya Biryukov43714502018-05-16 12:32:44 +0000545 std::string Documentation =
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +0000546 formatDocumentation(*CCS, getDocComment(Ctx, SymbolCompletion,
547 /*CommentsFromHeaders=*/true));
Sam McCalla68951e2018-06-22 16:11:35 +0000548 std::string ReturnType = getReturnType(*CCS);
Sam McCall60039512018-02-09 14:42:01 +0000549
Eric Liuc5105f92018-02-16 14:15:55 +0000550 std::string Include;
551 if (Opts.CollectIncludePath && shouldCollectIncludePath(S.SymInfo.Kind)) {
552 // Use the expansion location to get the #include header since this is
553 // where the symbol is exposed.
Eric Liub96363d2018-03-01 18:06:40 +0000554 if (auto Header = getIncludeHeader(
555 QName, SM, SM.getExpansionLoc(ND.getLocation()), Opts))
Eric Liuc5105f92018-02-16 14:15:55 +0000556 Include = std::move(*Header);
557 }
Sam McCalla68951e2018-06-22 16:11:35 +0000558 S.Signature = Signature;
559 S.CompletionSnippetSuffix = SnippetSuffix;
Sam McCall2e5700f2018-08-31 13:55:01 +0000560 S.Documentation = Documentation;
561 S.ReturnType = ReturnType;
Eric Liu83f63e42018-09-03 10:18:21 +0000562 if (!Include.empty())
563 S.IncludeHeaders.emplace_back(Include, 1);
Sam McCall60039512018-02-09 14:42:01 +0000564
Ilya Biryukov4d3d82e2018-11-26 15:52:16 +0000565 llvm::Optional<OpaqueType> TypeStorage;
Ilya Biryukova21392b2018-11-26 15:29:14 +0000566 if (S.Flags & Symbol::IndexedForCodeCompletion) {
Ilya Biryukov4d3d82e2018-11-26 15:52:16 +0000567 TypeStorage = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion);
568 if (TypeStorage)
569 S.Type = TypeStorage->raw();
Ilya Biryukova21392b2018-11-26 15:29:14 +0000570 }
571
Sam McCall2161ec72018-07-05 06:20:41 +0000572 S.Origin = Opts.Origin;
Eric Liu6df66002018-09-06 18:52:26 +0000573 if (ND.getAvailability() == AR_Deprecated)
574 S.Flags |= Symbol::Deprecated;
Sam McCall60039512018-02-09 14:42:01 +0000575 Symbols.insert(S);
576 return Symbols.find(S.ID);
577}
578
579void SymbolCollector::addDefinition(const NamedDecl &ND,
580 const Symbol &DeclSym) {
581 if (DeclSym.Definition)
582 return;
583 // If we saw some forward declaration, we end up copying the symbol.
584 // This is not ideal, but avoids duplicating the "is this a definition" check
585 // in clang::index. We should only see one definition.
586 Symbol S = DeclSym;
587 std::string FileURI;
Eric Liuad588af2018-11-06 10:55:21 +0000588 auto Loc = findNameLoc(&ND);
589 const auto &SM = ND.getASTContext().getSourceManager();
590 // FIXME: use the result to filter out symbols.
591 shouldIndexFile(SM, SM.getFileID(Loc), Opts, &FilesToIndexCache);
592 if (auto DefLoc =
593 getTokenLocation(Loc, SM, Opts, ASTCtx->getLangOpts(), FileURI))
Sam McCall60039512018-02-09 14:42:01 +0000594 S.Definition = *DefLoc;
595 Symbols.insert(S);
596}
597
Haojian Wu4c1394d2017-12-12 15:42:10 +0000598} // namespace clangd
599} // namespace clang