blob: 35f3edb4202964794ca2e7a197373fe9183375a0 [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"
Eric Liu9af958f2018-01-10 14:57:58 +000022#include "clang/ASTMatchers/ASTMatchFinder.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 {
34
35namespace {
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.
Eric Liu7f247652018-02-06 16:10:35 +000053llvm::Optional<std::string> toURI(const SourceManager &SM, StringRef Path,
54 const SymbolCollector::Options &Opts) {
Haojian Wu4c1394d2017-12-12 15:42:10 +000055 llvm::SmallString<128> AbsolutePath(Path);
56 if (std::error_code EC =
57 SM.getFileManager().getVirtualFileSystem()->makeAbsolute(
58 AbsolutePath))
Sam McCallbed58852018-07-11 10:35:11 +000059 log("Warning: could not make absolute file: {0}", EC.message());
Eric Liu278e2d12018-01-29 15:13:29 +000060 if (llvm::sys::path::is_absolute(AbsolutePath)) {
61 // Handle the symbolic link path case where the current working directory
62 // (getCurrentWorkingDirectory) is a symlink./ We always want to the real
63 // file path (instead of the symlink path) for the C++ symbols.
64 //
65 // Consider the following example:
66 //
67 // src dir: /project/src/foo.h
68 // current working directory (symlink): /tmp/build -> /project/src/
69 //
70 // The file path of Symbol is "/project/src/foo.h" instead of
71 // "/tmp/build/foo.h"
72 if (const DirectoryEntry *Dir = SM.getFileManager().getDirectory(
73 llvm::sys::path::parent_path(AbsolutePath.str()))) {
74 StringRef DirName = SM.getFileManager().getCanonicalName(Dir);
75 SmallString<128> AbsoluteFilename;
76 llvm::sys::path::append(AbsoluteFilename, DirName,
77 llvm::sys::path::filename(AbsolutePath.str()));
78 AbsolutePath = AbsoluteFilename;
79 }
Eric Liu7f247652018-02-06 16:10:35 +000080 } else if (!Opts.FallbackDir.empty()) {
81 llvm::sys::fs::make_absolute(Opts.FallbackDir, AbsolutePath);
Haojian Wu4c1394d2017-12-12 15:42:10 +000082 }
Eric Liu7f247652018-02-06 16:10:35 +000083
Eric Liua0957702018-06-25 11:50:11 +000084 llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/true);
85
Eric Liu7f247652018-02-06 16:10:35 +000086 std::string ErrMsg;
87 for (const auto &Scheme : Opts.URISchemes) {
88 auto U = URI::create(AbsolutePath, Scheme);
89 if (U)
90 return U->toString();
91 ErrMsg += llvm::toString(U.takeError()) + "\n";
92 }
Sam McCallbed58852018-07-11 10:35:11 +000093 log("Failed to create an URI for file {0}: {1}", AbsolutePath, ErrMsg);
Eric Liu7f247652018-02-06 16:10:35 +000094 return llvm::None;
Haojian Wu4c1394d2017-12-12 15:42:10 +000095}
Eric Liu4feda802017-12-19 11:37:40 +000096
Eric Liud67ec242018-05-16 12:12:30 +000097// All proto generated headers should start with this line.
98static const char *PROTO_HEADER_COMMENT =
99 "// Generated by the protocol buffer compiler. DO NOT EDIT!";
100
101// Checks whether the decl is a private symbol in a header generated by
102// protobuf compiler.
103// To identify whether a proto header is actually generated by proto compiler,
104// we check whether it starts with PROTO_HEADER_COMMENT.
105// FIXME: make filtering extensible when there are more use cases for symbol
106// filters.
107bool isPrivateProtoDecl(const NamedDecl &ND) {
108 const auto &SM = ND.getASTContext().getSourceManager();
109 auto Loc = findNameLoc(&ND);
110 auto FileName = SM.getFilename(Loc);
111 if (!FileName.endswith(".proto.h") && !FileName.endswith(".pb.h"))
112 return false;
113 auto FID = SM.getFileID(Loc);
114 // Double check that this is an actual protobuf header.
115 if (!SM.getBufferData(FID).startswith(PROTO_HEADER_COMMENT))
116 return false;
117
118 // ND without identifier can be operators.
119 if (ND.getIdentifier() == nullptr)
120 return false;
121 auto Name = ND.getIdentifier()->getName();
122 if (!Name.contains('_'))
123 return false;
124 // Nested proto entities (e.g. Message::Nested) have top-level decls
125 // that shouldn't be used (Message_Nested). Ignore them completely.
126 // The nested entities are dangling type aliases, we may want to reconsider
127 // including them in the future.
128 // For enum constants, SOME_ENUM_CONSTANT is not private and should be
129 // indexed. Outer_INNER is private. This heuristic relies on naming style, it
130 // will include OUTER_INNER and exclude some_enum_constant.
131 // FIXME: the heuristic relies on naming style (i.e. no underscore in
132 // user-defined names) and can be improved.
133 return (ND.getKind() != Decl::EnumConstant) ||
134 std::any_of(Name.begin(), Name.end(), islower);
135}
136
Eric Liuc5105f92018-02-16 14:15:55 +0000137// We only collect #include paths for symbols that are suitable for global code
138// completion, except for namespaces since #include path for a namespace is hard
139// to define.
140bool shouldCollectIncludePath(index::SymbolKind Kind) {
141 using SK = index::SymbolKind;
142 switch (Kind) {
143 case SK::Macro:
144 case SK::Enum:
145 case SK::Struct:
146 case SK::Class:
147 case SK::Union:
148 case SK::TypeAlias:
149 case SK::Using:
150 case SK::Function:
151 case SK::Variable:
152 case SK::EnumConstant:
153 return true;
154 default:
155 return false;
156 }
157}
158
Eric Liu02ce01f2018-02-22 10:14:05 +0000159/// Gets a canonical include (URI of the header or <header> or "header") for
160/// header of \p Loc.
161/// Returns None if fails to get include header for \p Loc.
Eric Liuc5105f92018-02-16 14:15:55 +0000162llvm::Optional<std::string>
Eric Liub96363d2018-03-01 18:06:40 +0000163getIncludeHeader(llvm::StringRef QName, const SourceManager &SM,
164 SourceLocation Loc, const SymbolCollector::Options &Opts) {
Eric Liu3cee95e2018-05-24 14:40:24 +0000165 std::vector<std::string> Headers;
166 // Collect the #include stack.
167 while (true) {
168 if (!Loc.isValid())
169 break;
170 auto FilePath = SM.getFilename(Loc);
171 if (FilePath.empty())
172 break;
173 Headers.push_back(FilePath);
174 if (SM.isInMainFile(Loc))
175 break;
176 Loc = SM.getIncludeLoc(SM.getFileID(Loc));
Eric Liuc5105f92018-02-16 14:15:55 +0000177 }
Eric Liu3cee95e2018-05-24 14:40:24 +0000178 if (Headers.empty())
179 return llvm::None;
180 llvm::StringRef Header = Headers[0];
181 if (Opts.Includes) {
182 Header = Opts.Includes->mapHeader(Headers, QName);
183 if (Header.startswith("<") || Header.startswith("\""))
184 return Header.str();
185 }
186 return toURI(SM, Header, Opts);
Eric Liuc5105f92018-02-16 14:15:55 +0000187}
188
Haojian Wud81e3142018-08-31 12:54:13 +0000189// Return the symbol range of the token at \p TokLoc.
190std::pair<SymbolLocation::Position, SymbolLocation::Position>
191getTokenRange(SourceLocation TokLoc, const SourceManager &SM,
192 const LangOptions &LangOpts) {
193 auto CreatePosition = [&SM](SourceLocation Loc) {
194 auto LSPLoc = sourceLocToPosition(SM, Loc);
195 SymbolLocation::Position Pos;
196 Pos.Line = LSPLoc.line;
197 Pos.Column = LSPLoc.character;
198 return Pos;
199 };
200
201 auto TokenLength = clang::Lexer::MeasureTokenLength(TokLoc, SM, LangOpts);
202 return {CreatePosition(TokLoc),
203 CreatePosition(TokLoc.getLocWithOffset(TokenLength))};
204}
205
206// Return the symbol location of the token at \p TokLoc.
Eric Liu48db19e2018-07-09 15:31:07 +0000207llvm::Optional<SymbolLocation>
208getTokenLocation(SourceLocation TokLoc, const SourceManager &SM,
209 const SymbolCollector::Options &Opts,
210 const clang::LangOptions &LangOpts,
211 std::string &FileURIStorage) {
212 auto U = toURI(SM, SM.getFilename(TokLoc), Opts);
Eric Liu7f247652018-02-06 16:10:35 +0000213 if (!U)
214 return llvm::None;
215 FileURIStorage = std::move(*U);
Sam McCall60039512018-02-09 14:42:01 +0000216 SymbolLocation Result;
217 Result.FileURI = FileURIStorage;
Haojian Wud81e3142018-08-31 12:54:13 +0000218 auto Range = getTokenRange(TokLoc, SM, LangOpts);
219 Result.Start = Range.first;
220 Result.End = Range.second;
Haojian Wu545c02a2018-04-13 08:30:39 +0000221
Sam McCall60039512018-02-09 14:42:01 +0000222 return std::move(Result);
Haojian Wub0189062018-01-31 12:56:51 +0000223}
224
Eric Liucf8601b2018-02-28 09:33:15 +0000225// Checks whether \p ND is a definition of a TagDecl (class/struct/enum/union)
226// in a header file, in which case clangd would prefer to use ND as a canonical
227// declaration.
228// FIXME: handle symbol types that are not TagDecl (e.g. functions), if using
Fangrui Song943e12e2018-03-29 20:03:16 +0000229// the first seen declaration as canonical declaration is not a good enough
Eric Liucf8601b2018-02-28 09:33:15 +0000230// heuristic.
231bool isPreferredDeclaration(const NamedDecl &ND, index::SymbolRoleSet Roles) {
232 using namespace clang::ast_matchers;
233 return (Roles & static_cast<unsigned>(index::SymbolRole::Definition)) &&
234 llvm::isa<TagDecl>(&ND) &&
235 match(decl(isExpansionInMainFile()), ND, ND.getASTContext()).empty();
236}
237
Sam McCallb0138312018-09-04 14:39:56 +0000238RefKind toRefKind(index::SymbolRoleSet Roles) {
239 return static_cast<RefKind>(static_cast<unsigned>(RefKind::All) & Roles);
Haojian Wud81e3142018-08-31 12:54:13 +0000240}
241
Eric Liua57afd02018-09-17 07:43:49 +0000242template <class T> bool explicitTemplateSpecialization(const NamedDecl &ND) {
243 if (const auto *TD = llvm::dyn_cast<T>(&ND))
244 if (TD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
245 return true;
246 return false;
247}
248
Haojian Wu4c1394d2017-12-12 15:42:10 +0000249} // namespace
250
Eric Liu9af958f2018-01-10 14:57:58 +0000251SymbolCollector::SymbolCollector(Options Opts) : Opts(std::move(Opts)) {}
252
Eric Liu76f6b442018-01-09 17:32:00 +0000253void SymbolCollector::initialize(ASTContext &Ctx) {
254 ASTCtx = &Ctx;
255 CompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
256 CompletionTUInfo =
257 llvm::make_unique<CodeCompletionTUInfo>(CompletionAllocator);
258}
259
Eric Liu8763e482018-06-21 12:12:26 +0000260bool SymbolCollector::shouldCollectSymbol(const NamedDecl &ND,
261 ASTContext &ASTCtx,
262 const Options &Opts) {
263 using namespace clang::ast_matchers;
264 if (ND.isImplicit())
265 return false;
266 // Skip anonymous declarations, e.g (anonymous enum/class/struct).
267 if (ND.getDeclName().isEmpty())
268 return false;
269
270 // FIXME: figure out a way to handle internal linkage symbols (e.g. static
271 // variables, function) defined in the .cc files. Also we skip the symbols
272 // in anonymous namespace as the qualifier names of these symbols are like
273 // `foo::<anonymous>::bar`, which need a special handling.
274 // In real world projects, we have a relatively large set of header files
275 // that define static variables (like "static const int A = 1;"), we still
276 // want to collect these symbols, although they cause potential ODR
277 // violations.
278 if (ND.isInAnonymousNamespace())
279 return false;
280
281 // We want most things but not "local" symbols such as symbols inside
282 // FunctionDecl, BlockDecl, ObjCMethodDecl and OMPDeclareReductionDecl.
283 // FIXME: Need a matcher for ExportDecl in order to include symbols declared
284 // within an export.
Eric Liua57afd02018-09-17 07:43:49 +0000285 const auto *DeclCtx = ND.getDeclContext();
286 switch (DeclCtx->getDeclKind()) {
287 case Decl::TranslationUnit:
288 case Decl::Namespace:
289 case Decl::LinkageSpec:
290 case Decl::Enum:
291 case Decl::ObjCProtocol:
292 case Decl::ObjCInterface:
293 case Decl::ObjCCategory:
294 case Decl::ObjCCategoryImpl:
295 case Decl::ObjCImplementation:
296 break;
297 default:
298 // Record has a few derivations (e.g. CXXRecord, Class specialization), it's
299 // easier to cast.
300 if (!llvm::isa<RecordDecl>(DeclCtx))
301 return false;
302 }
303 if (explicitTemplateSpecialization<FunctionDecl>(ND) ||
304 explicitTemplateSpecialization<CXXRecordDecl>(ND) ||
305 explicitTemplateSpecialization<VarDecl>(ND))
Eric Liu8763e482018-06-21 12:12:26 +0000306 return false;
307
Eric Liua57afd02018-09-17 07:43:49 +0000308 const auto &SM = ASTCtx.getSourceManager();
309 // Skip decls in the main file.
310 if (SM.isInMainFile(SM.getExpansionLoc(ND.getBeginLoc())))
311 return false;
Eric Liu8763e482018-06-21 12:12:26 +0000312 // Avoid indexing internal symbols in protobuf generated headers.
313 if (isPrivateProtoDecl(ND))
314 return false;
315 return true;
316}
317
Haojian Wu4c1394d2017-12-12 15:42:10 +0000318// Always return true to continue indexing.
319bool SymbolCollector::handleDeclOccurence(
320 const Decl *D, index::SymbolRoleSet Roles,
Sam McCallb9d57112018-04-09 14:28:52 +0000321 ArrayRef<index::SymbolRelation> Relations, SourceLocation Loc,
Haojian Wu4c1394d2017-12-12 15:42:10 +0000322 index::IndexDataConsumer::ASTNodeInfo ASTNode) {
Eric Liu9af958f2018-01-10 14:57:58 +0000323 assert(ASTCtx && PP.get() && "ASTContext and Preprocessor must be set.");
Sam McCall93f99bf2018-03-12 14:49:09 +0000324 assert(CompletionAllocator && CompletionTUInfo);
Eric Liu77d18112018-06-04 11:31:55 +0000325 assert(ASTNode.OrigD);
326 // If OrigD is an declaration associated with a friend declaration and it's
327 // not a definition, skip it. Note that OrigD is the occurrence that the
328 // collector is currently visiting.
329 if ((ASTNode.OrigD->getFriendObjectKind() !=
330 Decl::FriendObjectKind::FOK_None) &&
331 !(Roles & static_cast<unsigned>(index::SymbolRole::Definition)))
332 return true;
333 // A declaration created for a friend declaration should not be used as the
334 // canonical declaration in the index. Use OrigD instead, unless we've already
335 // picked a replacement for D
336 if (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None)
337 D = CanonicalDecls.try_emplace(D, ASTNode.OrigD).first->second;
Sam McCall93f99bf2018-03-12 14:49:09 +0000338 const NamedDecl *ND = llvm::dyn_cast<NamedDecl>(D);
339 if (!ND)
340 return true;
Eric Liu9af958f2018-01-10 14:57:58 +0000341
Sam McCall93f99bf2018-03-12 14:49:09 +0000342 // Mark D as referenced if this is a reference coming from the main file.
343 // D may not be an interesting symbol, but it's cheaper to check at the end.
Sam McCallb9d57112018-04-09 14:28:52 +0000344 auto &SM = ASTCtx->getSourceManager();
Haojian Wud81e3142018-08-31 12:54:13 +0000345 auto SpellingLoc = SM.getSpellingLoc(Loc);
Sam McCall93f99bf2018-03-12 14:49:09 +0000346 if (Opts.CountReferences &&
347 (Roles & static_cast<unsigned>(index::SymbolRole::Reference)) &&
Haojian Wud81e3142018-08-31 12:54:13 +0000348 SM.getFileID(SpellingLoc) == SM.getMainFileID())
Sam McCall93f99bf2018-03-12 14:49:09 +0000349 ReferencedDecls.insert(ND);
350
Sam McCallb0138312018-09-04 14:39:56 +0000351 if ((static_cast<unsigned>(Opts.RefFilter) & Roles) &&
Haojian Wud81e3142018-08-31 12:54:13 +0000352 SM.getFileID(SpellingLoc) == SM.getMainFileID())
Sam McCallb0138312018-09-04 14:39:56 +0000353 DeclRefs[ND].emplace_back(SpellingLoc, Roles);
Haojian Wud81e3142018-08-31 12:54:13 +0000354
Sam McCall93f99bf2018-03-12 14:49:09 +0000355 // Don't continue indexing if this is a mere reference.
Haojian Wu4c1394d2017-12-12 15:42:10 +0000356 if (!(Roles & static_cast<unsigned>(index::SymbolRole::Declaration) ||
357 Roles & static_cast<unsigned>(index::SymbolRole::Definition)))
358 return true;
Eric Liu8763e482018-06-21 12:12:26 +0000359 if (!shouldCollectSymbol(*ND, *ASTCtx, Opts))
Sam McCall93f99bf2018-03-12 14:49:09 +0000360 return true;
Haojian Wu4c1394d2017-12-12 15:42:10 +0000361
Haojian Wuc6ddb462018-08-07 08:57:52 +0000362 auto ID = getSymbolID(ND);
363 if (!ID)
Sam McCall93f99bf2018-03-12 14:49:09 +0000364 return true;
Eric Liu76f6b442018-01-09 17:32:00 +0000365
Sam McCall93f99bf2018-03-12 14:49:09 +0000366 const NamedDecl &OriginalDecl = *cast<NamedDecl>(ASTNode.OrigD);
Haojian Wuc6ddb462018-08-07 08:57:52 +0000367 const Symbol *BasicSymbol = Symbols.find(*ID);
Sam McCall93f99bf2018-03-12 14:49:09 +0000368 if (!BasicSymbol) // Regardless of role, ND is the canonical declaration.
Haojian Wuc6ddb462018-08-07 08:57:52 +0000369 BasicSymbol = addDeclaration(*ND, std::move(*ID));
Sam McCall93f99bf2018-03-12 14:49:09 +0000370 else if (isPreferredDeclaration(OriginalDecl, Roles))
371 // If OriginalDecl is preferred, replace the existing canonical
372 // declaration (e.g. a class forward declaration). There should be at most
373 // one duplicate as we expect to see only one preferred declaration per
374 // TU, because in practice they are definitions.
Haojian Wuc6ddb462018-08-07 08:57:52 +0000375 BasicSymbol = addDeclaration(OriginalDecl, std::move(*ID));
Haojian Wu4c1394d2017-12-12 15:42:10 +0000376
Sam McCall93f99bf2018-03-12 14:49:09 +0000377 if (Roles & static_cast<unsigned>(index::SymbolRole::Definition))
378 addDefinition(OriginalDecl, *BasicSymbol);
Haojian Wu4c1394d2017-12-12 15:42:10 +0000379 return true;
380}
381
Eric Liu48db19e2018-07-09 15:31:07 +0000382bool SymbolCollector::handleMacroOccurence(const IdentifierInfo *Name,
383 const MacroInfo *MI,
384 index::SymbolRoleSet Roles,
385 SourceLocation Loc) {
386 if (!Opts.CollectMacro)
387 return true;
388 assert(PP.get());
389
390 const auto &SM = PP->getSourceManager();
391 if (SM.isInMainFile(SM.getExpansionLoc(MI->getDefinitionLoc())))
392 return true;
393 // Header guards are not interesting in index. Builtin macros don't have
394 // useful locations and are not needed for code completions.
395 if (MI->isUsedForHeaderGuard() || MI->isBuiltinMacro())
396 return true;
397
398 // Mark the macro as referenced if this is a reference coming from the main
399 // file. The macro may not be an interesting symbol, but it's cheaper to check
400 // at the end.
401 if (Opts.CountReferences &&
402 (Roles & static_cast<unsigned>(index::SymbolRole::Reference)) &&
403 SM.getFileID(SM.getSpellingLoc(Loc)) == SM.getMainFileID())
404 ReferencedMacros.insert(Name);
405 // Don't continue indexing if this is a mere reference.
406 // FIXME: remove macro with ID if it is undefined.
407 if (!(Roles & static_cast<unsigned>(index::SymbolRole::Declaration) ||
408 Roles & static_cast<unsigned>(index::SymbolRole::Definition)))
409 return true;
410
Eric Liud25f1212018-09-06 09:59:37 +0000411 auto ID = getSymbolID(*Name, MI, SM);
412 if (!ID)
Eric Liu48db19e2018-07-09 15:31:07 +0000413 return true;
Eric Liu48db19e2018-07-09 15:31:07 +0000414
415 // Only collect one instance in case there are multiple.
Eric Liud25f1212018-09-06 09:59:37 +0000416 if (Symbols.find(*ID) != nullptr)
Eric Liu48db19e2018-07-09 15:31:07 +0000417 return true;
418
419 Symbol S;
Eric Liud25f1212018-09-06 09:59:37 +0000420 S.ID = std::move(*ID);
Eric Liu48db19e2018-07-09 15:31:07 +0000421 S.Name = Name->getName();
Eric Liu6df66002018-09-06 18:52:26 +0000422 S.Flags |= Symbol::IndexedForCodeCompletion;
Eric Liu48db19e2018-07-09 15:31:07 +0000423 S.SymInfo = index::getSymbolInfoForMacro(*MI);
424 std::string FileURI;
425 if (auto DeclLoc = getTokenLocation(MI->getDefinitionLoc(), SM, Opts,
426 PP->getLangOpts(), FileURI))
427 S.CanonicalDeclaration = *DeclLoc;
428
429 CodeCompletionResult SymbolCompletion(Name);
430 const auto *CCS = SymbolCompletion.CreateCodeCompletionStringForMacro(
431 *PP, *CompletionAllocator, *CompletionTUInfo);
432 std::string Signature;
433 std::string SnippetSuffix;
434 getSignature(*CCS, &Signature, &SnippetSuffix);
435
436 std::string Include;
437 if (Opts.CollectIncludePath && shouldCollectIncludePath(S.SymInfo.Kind)) {
438 if (auto Header =
439 getIncludeHeader(Name->getName(), SM,
440 SM.getExpansionLoc(MI->getDefinitionLoc()), Opts))
441 Include = std::move(*Header);
442 }
443 S.Signature = Signature;
444 S.CompletionSnippetSuffix = SnippetSuffix;
Eric Liu83f63e42018-09-03 10:18:21 +0000445 if (!Include.empty())
446 S.IncludeHeaders.emplace_back(Include, 1);
447
Eric Liu48db19e2018-07-09 15:31:07 +0000448 Symbols.insert(S);
449 return true;
450}
451
Sam McCall93f99bf2018-03-12 14:49:09 +0000452void SymbolCollector::finish() {
Eric Liu48db19e2018-07-09 15:31:07 +0000453 // At the end of the TU, add 1 to the refcount of all referenced symbols.
454 auto IncRef = [this](const SymbolID &ID) {
455 if (const auto *S = Symbols.find(ID)) {
456 Symbol Inc = *S;
457 ++Inc.References;
458 Symbols.insert(Inc);
459 }
460 };
461 for (const NamedDecl *ND : ReferencedDecls) {
Haojian Wuc6ddb462018-08-07 08:57:52 +0000462 if (auto ID = getSymbolID(ND)) {
463 IncRef(*ID);
464 }
Eric Liu48db19e2018-07-09 15:31:07 +0000465 }
466 if (Opts.CollectMacro) {
467 assert(PP);
468 for (const IdentifierInfo *II : ReferencedMacros) {
Eric Liua62c9d62018-07-09 18:54:51 +0000469 if (const auto *MI = PP->getMacroDefinition(II).getMacroInfo())
Eric Liud25f1212018-09-06 09:59:37 +0000470 if (auto ID = getSymbolID(*II, MI, PP->getSourceManager()))
471 IncRef(*ID);
Eric Liu48db19e2018-07-09 15:31:07 +0000472 }
Sam McCall93f99bf2018-03-12 14:49:09 +0000473 }
Haojian Wud81e3142018-08-31 12:54:13 +0000474
475 const auto &SM = ASTCtx->getSourceManager();
476 auto* MainFileEntry = SM.getFileEntryForID(SM.getMainFileID());
477
478 if (auto MainFileURI = toURI(SM, MainFileEntry->getName(), Opts)) {
479 std::string MainURI = *MainFileURI;
Sam McCallb0138312018-09-04 14:39:56 +0000480 for (const auto &It : DeclRefs) {
Haojian Wud81e3142018-08-31 12:54:13 +0000481 if (auto ID = getSymbolID(It.first)) {
482 if (Symbols.find(*ID)) {
483 for (const auto &LocAndRole : It.second) {
Sam McCallb0138312018-09-04 14:39:56 +0000484 Ref R;
Haojian Wud81e3142018-08-31 12:54:13 +0000485 auto Range =
486 getTokenRange(LocAndRole.first, SM, ASTCtx->getLangOpts());
Sam McCallb0138312018-09-04 14:39:56 +0000487 R.Location.Start = Range.first;
488 R.Location.End = Range.second;
489 R.Location.FileURI = MainURI;
490 R.Kind = toRefKind(LocAndRole.second);
491 Refs.insert(*ID, R);
Haojian Wud81e3142018-08-31 12:54:13 +0000492 }
493 }
494 }
495 }
496 } else {
497 log("Failed to create URI for main file: {0}", MainFileEntry->getName());
498 }
499
Sam McCall93f99bf2018-03-12 14:49:09 +0000500 ReferencedDecls.clear();
Eric Liu48db19e2018-07-09 15:31:07 +0000501 ReferencedMacros.clear();
Sam McCallb0138312018-09-04 14:39:56 +0000502 DeclRefs.clear();
Sam McCall93f99bf2018-03-12 14:49:09 +0000503}
504
Sam McCall60039512018-02-09 14:42:01 +0000505const Symbol *SymbolCollector::addDeclaration(const NamedDecl &ND,
506 SymbolID ID) {
Ilya Biryukov43714502018-05-16 12:32:44 +0000507 auto &Ctx = ND.getASTContext();
508 auto &SM = Ctx.getSourceManager();
Sam McCall60039512018-02-09 14:42:01 +0000509
Sam McCall60039512018-02-09 14:42:01 +0000510 Symbol S;
511 S.ID = std::move(ID);
Eric Liu7ad16962018-06-22 10:46:59 +0000512 std::string QName = printQualifiedName(ND);
Sam McCall60039512018-02-09 14:42:01 +0000513 std::tie(S.Scope, S.Name) = splitQualifiedName(QName);
Sam McCall032db942018-06-22 06:41:43 +0000514 // FIXME: this returns foo:bar: for objective-C methods, we prefer only foo:
515 // for consistency with CodeCompletionString and a clean name/signature split.
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +0000516
Eric Liu6df66002018-09-06 18:52:26 +0000517 if (isIndexedForCodeCompletion(ND, Ctx))
518 S.Flags |= Symbol::IndexedForCodeCompletion;
Sam McCall60039512018-02-09 14:42:01 +0000519 S.SymInfo = index::getSymbolInfo(&ND);
520 std::string FileURI;
Eric Liu48db19e2018-07-09 15:31:07 +0000521 if (auto DeclLoc = getTokenLocation(findNameLoc(&ND), SM, Opts,
522 ASTCtx->getLangOpts(), FileURI))
Sam McCall60039512018-02-09 14:42:01 +0000523 S.CanonicalDeclaration = *DeclLoc;
524
525 // Add completion info.
526 // FIXME: we may want to choose a different redecl, or combine from several.
527 assert(ASTCtx && PP.get() && "ASTContext and Preprocessor must be set.");
Ilya Biryukovcf124bd2018-04-13 11:03:07 +0000528 // We use the primary template, as clang does during code completion.
529 CodeCompletionResult SymbolCompletion(&getTemplateOrThis(ND), 0);
Sam McCall60039512018-02-09 14:42:01 +0000530 const auto *CCS = SymbolCompletion.CreateCodeCompletionString(
531 *ASTCtx, *PP, CodeCompletionContext::CCC_Name, *CompletionAllocator,
532 *CompletionTUInfo,
Ilya Biryukov43714502018-05-16 12:32:44 +0000533 /*IncludeBriefComments*/ false);
Sam McCalla68951e2018-06-22 16:11:35 +0000534 std::string Signature;
535 std::string SnippetSuffix;
536 getSignature(*CCS, &Signature, &SnippetSuffix);
Ilya Biryukov43714502018-05-16 12:32:44 +0000537 std::string Documentation =
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +0000538 formatDocumentation(*CCS, getDocComment(Ctx, SymbolCompletion,
539 /*CommentsFromHeaders=*/true));
Sam McCalla68951e2018-06-22 16:11:35 +0000540 std::string ReturnType = getReturnType(*CCS);
Sam McCall60039512018-02-09 14:42:01 +0000541
Eric Liuc5105f92018-02-16 14:15:55 +0000542 std::string Include;
543 if (Opts.CollectIncludePath && shouldCollectIncludePath(S.SymInfo.Kind)) {
544 // Use the expansion location to get the #include header since this is
545 // where the symbol is exposed.
Eric Liub96363d2018-03-01 18:06:40 +0000546 if (auto Header = getIncludeHeader(
547 QName, SM, SM.getExpansionLoc(ND.getLocation()), Opts))
Eric Liuc5105f92018-02-16 14:15:55 +0000548 Include = std::move(*Header);
549 }
Sam McCalla68951e2018-06-22 16:11:35 +0000550 S.Signature = Signature;
551 S.CompletionSnippetSuffix = SnippetSuffix;
Sam McCall2e5700f2018-08-31 13:55:01 +0000552 S.Documentation = Documentation;
553 S.ReturnType = ReturnType;
Eric Liu83f63e42018-09-03 10:18:21 +0000554 if (!Include.empty())
555 S.IncludeHeaders.emplace_back(Include, 1);
Sam McCall60039512018-02-09 14:42:01 +0000556
Sam McCall2161ec72018-07-05 06:20:41 +0000557 S.Origin = Opts.Origin;
Eric Liu6df66002018-09-06 18:52:26 +0000558 if (ND.getAvailability() == AR_Deprecated)
559 S.Flags |= Symbol::Deprecated;
Sam McCall60039512018-02-09 14:42:01 +0000560 Symbols.insert(S);
561 return Symbols.find(S.ID);
562}
563
564void SymbolCollector::addDefinition(const NamedDecl &ND,
565 const Symbol &DeclSym) {
566 if (DeclSym.Definition)
567 return;
568 // If we saw some forward declaration, we end up copying the symbol.
569 // This is not ideal, but avoids duplicating the "is this a definition" check
570 // in clang::index. We should only see one definition.
571 Symbol S = DeclSym;
572 std::string FileURI;
Eric Liu48db19e2018-07-09 15:31:07 +0000573 if (auto DefLoc = getTokenLocation(findNameLoc(&ND),
574 ND.getASTContext().getSourceManager(),
575 Opts, ASTCtx->getLangOpts(), FileURI))
Sam McCall60039512018-02-09 14:42:01 +0000576 S.Definition = *DefLoc;
577 Symbols.insert(S);
578}
579
Haojian Wu4c1394d2017-12-12 15:42:10 +0000580} // namespace clangd
581} // namespace clang