blob: 0cbc1c86eaaad3bbc05725de6bc67d5663c81483 [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 {
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.
Kirill Bobyrev4a5ff882018-10-07 14:49:41 +0000133 return (ND.getKind() != Decl::EnumConstant) || llvm::any_of(Name, islower);
Eric Liud67ec242018-05-16 12:12:30 +0000134}
135
Eric Liuc5105f92018-02-16 14:15:55 +0000136// We only collect #include paths for symbols that are suitable for global code
137// completion, except for namespaces since #include path for a namespace is hard
138// to define.
139bool shouldCollectIncludePath(index::SymbolKind Kind) {
140 using SK = index::SymbolKind;
141 switch (Kind) {
142 case SK::Macro:
143 case SK::Enum:
144 case SK::Struct:
145 case SK::Class:
146 case SK::Union:
147 case SK::TypeAlias:
148 case SK::Using:
149 case SK::Function:
150 case SK::Variable:
151 case SK::EnumConstant:
152 return true;
153 default:
154 return false;
155 }
156}
157
Eric Liu02ce01f2018-02-22 10:14:05 +0000158/// Gets a canonical include (URI of the header or <header> or "header") for
159/// header of \p Loc.
160/// Returns None if fails to get include header for \p Loc.
Eric Liuc5105f92018-02-16 14:15:55 +0000161llvm::Optional<std::string>
Eric Liub96363d2018-03-01 18:06:40 +0000162getIncludeHeader(llvm::StringRef QName, const SourceManager &SM,
163 SourceLocation Loc, const SymbolCollector::Options &Opts) {
Eric Liu3cee95e2018-05-24 14:40:24 +0000164 std::vector<std::string> Headers;
165 // Collect the #include stack.
166 while (true) {
167 if (!Loc.isValid())
168 break;
169 auto FilePath = SM.getFilename(Loc);
170 if (FilePath.empty())
171 break;
172 Headers.push_back(FilePath);
173 if (SM.isInMainFile(Loc))
174 break;
175 Loc = SM.getIncludeLoc(SM.getFileID(Loc));
Eric Liuc5105f92018-02-16 14:15:55 +0000176 }
Eric Liu3cee95e2018-05-24 14:40:24 +0000177 if (Headers.empty())
178 return llvm::None;
179 llvm::StringRef Header = Headers[0];
180 if (Opts.Includes) {
181 Header = Opts.Includes->mapHeader(Headers, QName);
182 if (Header.startswith("<") || Header.startswith("\""))
183 return Header.str();
184 }
185 return toURI(SM, Header, Opts);
Eric Liuc5105f92018-02-16 14:15:55 +0000186}
187
Haojian Wud81e3142018-08-31 12:54:13 +0000188// Return the symbol range of the token at \p TokLoc.
189std::pair<SymbolLocation::Position, SymbolLocation::Position>
190getTokenRange(SourceLocation TokLoc, const SourceManager &SM,
191 const LangOptions &LangOpts) {
192 auto CreatePosition = [&SM](SourceLocation Loc) {
193 auto LSPLoc = sourceLocToPosition(SM, Loc);
194 SymbolLocation::Position Pos;
Haojian Wub515fab2018-10-18 10:43:50 +0000195 Pos.setLine(LSPLoc.line);
196 Pos.setColumn(LSPLoc.character);
Haojian Wud81e3142018-08-31 12:54:13 +0000197 return Pos;
198 };
199
200 auto TokenLength = clang::Lexer::MeasureTokenLength(TokLoc, SM, LangOpts);
201 return {CreatePosition(TokLoc),
202 CreatePosition(TokLoc.getLocWithOffset(TokenLength))};
203}
204
205// Return the symbol location of the token at \p TokLoc.
Eric Liu48db19e2018-07-09 15:31:07 +0000206llvm::Optional<SymbolLocation>
207getTokenLocation(SourceLocation TokLoc, const SourceManager &SM,
208 const SymbolCollector::Options &Opts,
209 const clang::LangOptions &LangOpts,
210 std::string &FileURIStorage) {
211 auto U = toURI(SM, SM.getFilename(TokLoc), Opts);
Eric Liu7f247652018-02-06 16:10:35 +0000212 if (!U)
213 return llvm::None;
214 FileURIStorage = std::move(*U);
Sam McCall60039512018-02-09 14:42:01 +0000215 SymbolLocation Result;
216 Result.FileURI = FileURIStorage;
Haojian Wud81e3142018-08-31 12:54:13 +0000217 auto Range = getTokenRange(TokLoc, SM, LangOpts);
218 Result.Start = Range.first;
219 Result.End = Range.second;
Haojian Wu545c02a2018-04-13 08:30:39 +0000220
Sam McCall60039512018-02-09 14:42:01 +0000221 return std::move(Result);
Haojian Wub0189062018-01-31 12:56:51 +0000222}
223
Eric Liucf8601b2018-02-28 09:33:15 +0000224// Checks whether \p ND is a definition of a TagDecl (class/struct/enum/union)
225// in a header file, in which case clangd would prefer to use ND as a canonical
226// declaration.
227// FIXME: handle symbol types that are not TagDecl (e.g. functions), if using
Fangrui Song943e12e2018-03-29 20:03:16 +0000228// the first seen declaration as canonical declaration is not a good enough
Eric Liucf8601b2018-02-28 09:33:15 +0000229// heuristic.
230bool isPreferredDeclaration(const NamedDecl &ND, index::SymbolRoleSet Roles) {
Sam McCall5fb97462018-10-05 14:03:04 +0000231 const auto& SM = ND.getASTContext().getSourceManager();
Eric Liucf8601b2018-02-28 09:33:15 +0000232 return (Roles & static_cast<unsigned>(index::SymbolRole::Definition)) &&
233 llvm::isa<TagDecl>(&ND) &&
Sam McCall5fb97462018-10-05 14:03:04 +0000234 !SM.isWrittenInMainFile(SM.getExpansionLoc(ND.getLocation()));
Eric Liucf8601b2018-02-28 09:33:15 +0000235}
236
Sam McCallb0138312018-09-04 14:39:56 +0000237RefKind toRefKind(index::SymbolRoleSet Roles) {
238 return static_cast<RefKind>(static_cast<unsigned>(RefKind::All) & Roles);
Haojian Wud81e3142018-08-31 12:54:13 +0000239}
240
Eric Liua57afd02018-09-17 07:43:49 +0000241template <class T> bool explicitTemplateSpecialization(const NamedDecl &ND) {
242 if (const auto *TD = llvm::dyn_cast<T>(&ND))
243 if (TD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
244 return true;
245 return false;
246}
247
Haojian Wu4c1394d2017-12-12 15:42:10 +0000248} // namespace
249
Eric Liu9af958f2018-01-10 14:57:58 +0000250SymbolCollector::SymbolCollector(Options Opts) : Opts(std::move(Opts)) {}
251
Eric Liu76f6b442018-01-09 17:32:00 +0000252void SymbolCollector::initialize(ASTContext &Ctx) {
253 ASTCtx = &Ctx;
254 CompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
255 CompletionTUInfo =
256 llvm::make_unique<CodeCompletionTUInfo>(CompletionAllocator);
257}
258
Eric Liu8763e482018-06-21 12:12:26 +0000259bool SymbolCollector::shouldCollectSymbol(const NamedDecl &ND,
260 ASTContext &ASTCtx,
261 const Options &Opts) {
Eric Liu8763e482018-06-21 12:12:26 +0000262 if (ND.isImplicit())
263 return false;
264 // Skip anonymous declarations, e.g (anonymous enum/class/struct).
265 if (ND.getDeclName().isEmpty())
266 return false;
267
268 // FIXME: figure out a way to handle internal linkage symbols (e.g. static
269 // variables, function) defined in the .cc files. Also we skip the symbols
270 // in anonymous namespace as the qualifier names of these symbols are like
271 // `foo::<anonymous>::bar`, which need a special handling.
272 // In real world projects, we have a relatively large set of header files
273 // that define static variables (like "static const int A = 1;"), we still
274 // want to collect these symbols, although they cause potential ODR
275 // violations.
276 if (ND.isInAnonymousNamespace())
277 return false;
278
279 // We want most things but not "local" symbols such as symbols inside
280 // FunctionDecl, BlockDecl, ObjCMethodDecl and OMPDeclareReductionDecl.
281 // FIXME: Need a matcher for ExportDecl in order to include symbols declared
282 // within an export.
Eric Liua57afd02018-09-17 07:43:49 +0000283 const auto *DeclCtx = ND.getDeclContext();
284 switch (DeclCtx->getDeclKind()) {
285 case Decl::TranslationUnit:
286 case Decl::Namespace:
287 case Decl::LinkageSpec:
288 case Decl::Enum:
289 case Decl::ObjCProtocol:
290 case Decl::ObjCInterface:
291 case Decl::ObjCCategory:
292 case Decl::ObjCCategoryImpl:
293 case Decl::ObjCImplementation:
294 break;
295 default:
296 // Record has a few derivations (e.g. CXXRecord, Class specialization), it's
297 // easier to cast.
298 if (!llvm::isa<RecordDecl>(DeclCtx))
299 return false;
300 }
301 if (explicitTemplateSpecialization<FunctionDecl>(ND) ||
302 explicitTemplateSpecialization<CXXRecordDecl>(ND) ||
303 explicitTemplateSpecialization<VarDecl>(ND))
Eric Liu8763e482018-06-21 12:12:26 +0000304 return false;
305
Eric Liua57afd02018-09-17 07:43:49 +0000306 const auto &SM = ASTCtx.getSourceManager();
307 // Skip decls in the main file.
308 if (SM.isInMainFile(SM.getExpansionLoc(ND.getBeginLoc())))
309 return false;
Eric Liu8763e482018-06-21 12:12:26 +0000310 // Avoid indexing internal symbols in protobuf generated headers.
311 if (isPrivateProtoDecl(ND))
312 return false;
313 return true;
314}
315
Haojian Wu4c1394d2017-12-12 15:42:10 +0000316// Always return true to continue indexing.
317bool SymbolCollector::handleDeclOccurence(
318 const Decl *D, index::SymbolRoleSet Roles,
Sam McCallb9d57112018-04-09 14:28:52 +0000319 ArrayRef<index::SymbolRelation> Relations, SourceLocation Loc,
Haojian Wu4c1394d2017-12-12 15:42:10 +0000320 index::IndexDataConsumer::ASTNodeInfo ASTNode) {
Eric Liu9af958f2018-01-10 14:57:58 +0000321 assert(ASTCtx && PP.get() && "ASTContext and Preprocessor must be set.");
Sam McCall93f99bf2018-03-12 14:49:09 +0000322 assert(CompletionAllocator && CompletionTUInfo);
Eric Liu77d18112018-06-04 11:31:55 +0000323 assert(ASTNode.OrigD);
324 // If OrigD is an declaration associated with a friend declaration and it's
325 // not a definition, skip it. Note that OrigD is the occurrence that the
326 // collector is currently visiting.
327 if ((ASTNode.OrigD->getFriendObjectKind() !=
328 Decl::FriendObjectKind::FOK_None) &&
329 !(Roles & static_cast<unsigned>(index::SymbolRole::Definition)))
330 return true;
331 // A declaration created for a friend declaration should not be used as the
332 // canonical declaration in the index. Use OrigD instead, unless we've already
333 // picked a replacement for D
334 if (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None)
335 D = CanonicalDecls.try_emplace(D, ASTNode.OrigD).first->second;
Sam McCall93f99bf2018-03-12 14:49:09 +0000336 const NamedDecl *ND = llvm::dyn_cast<NamedDecl>(D);
337 if (!ND)
338 return true;
Eric Liu9af958f2018-01-10 14:57:58 +0000339
Sam McCall93f99bf2018-03-12 14:49:09 +0000340 // Mark D as referenced if this is a reference coming from the main file.
341 // D may not be an interesting symbol, but it's cheaper to check at the end.
Sam McCallb9d57112018-04-09 14:28:52 +0000342 auto &SM = ASTCtx->getSourceManager();
Haojian Wud81e3142018-08-31 12:54:13 +0000343 auto SpellingLoc = SM.getSpellingLoc(Loc);
Sam McCall93f99bf2018-03-12 14:49:09 +0000344 if (Opts.CountReferences &&
345 (Roles & static_cast<unsigned>(index::SymbolRole::Reference)) &&
Haojian Wud81e3142018-08-31 12:54:13 +0000346 SM.getFileID(SpellingLoc) == SM.getMainFileID())
Sam McCall93f99bf2018-03-12 14:49:09 +0000347 ReferencedDecls.insert(ND);
348
Haojian Wue83cacc2018-10-15 11:46:26 +0000349 bool CollectRef = static_cast<unsigned>(Opts.RefFilter) & Roles;
350 bool IsOnlyRef =
351 !(Roles & (static_cast<unsigned>(index::SymbolRole::Declaration) |
352 static_cast<unsigned>(index::SymbolRole::Definition)));
Haojian Wud81e3142018-08-31 12:54:13 +0000353
Haojian Wue83cacc2018-10-15 11:46:26 +0000354 if (IsOnlyRef && !CollectRef)
Haojian Wu4c1394d2017-12-12 15:42:10 +0000355 return true;
Eric Liu8763e482018-06-21 12:12:26 +0000356 if (!shouldCollectSymbol(*ND, *ASTCtx, Opts))
Sam McCall93f99bf2018-03-12 14:49:09 +0000357 return true;
Haojian Wu7dd49502018-10-17 08:38:36 +0000358 if (CollectRef &&
359 (Opts.RefsInHeaders || SM.getFileID(SpellingLoc) == SM.getMainFileID()))
Haojian Wue83cacc2018-10-15 11:46:26 +0000360 DeclRefs[ND].emplace_back(SpellingLoc, Roles);
361 // Don't continue indexing if this is a mere reference.
362 if (IsOnlyRef)
363 return true;
Haojian Wu4c1394d2017-12-12 15:42:10 +0000364
Haojian Wuc6ddb462018-08-07 08:57:52 +0000365 auto ID = getSymbolID(ND);
366 if (!ID)
Sam McCall93f99bf2018-03-12 14:49:09 +0000367 return true;
Eric Liu76f6b442018-01-09 17:32:00 +0000368
Sam McCall93f99bf2018-03-12 14:49:09 +0000369 const NamedDecl &OriginalDecl = *cast<NamedDecl>(ASTNode.OrigD);
Haojian Wuc6ddb462018-08-07 08:57:52 +0000370 const Symbol *BasicSymbol = Symbols.find(*ID);
Sam McCall93f99bf2018-03-12 14:49:09 +0000371 if (!BasicSymbol) // Regardless of role, ND is the canonical declaration.
Haojian Wuc6ddb462018-08-07 08:57:52 +0000372 BasicSymbol = addDeclaration(*ND, std::move(*ID));
Sam McCall93f99bf2018-03-12 14:49:09 +0000373 else if (isPreferredDeclaration(OriginalDecl, Roles))
374 // If OriginalDecl is preferred, replace the existing canonical
375 // declaration (e.g. a class forward declaration). There should be at most
376 // one duplicate as we expect to see only one preferred declaration per
377 // TU, because in practice they are definitions.
Haojian Wuc6ddb462018-08-07 08:57:52 +0000378 BasicSymbol = addDeclaration(OriginalDecl, std::move(*ID));
Haojian Wu4c1394d2017-12-12 15:42:10 +0000379
Sam McCall93f99bf2018-03-12 14:49:09 +0000380 if (Roles & static_cast<unsigned>(index::SymbolRole::Definition))
381 addDefinition(OriginalDecl, *BasicSymbol);
Haojian Wu4c1394d2017-12-12 15:42:10 +0000382 return true;
383}
384
Eric Liu48db19e2018-07-09 15:31:07 +0000385bool SymbolCollector::handleMacroOccurence(const IdentifierInfo *Name,
386 const MacroInfo *MI,
387 index::SymbolRoleSet Roles,
388 SourceLocation Loc) {
389 if (!Opts.CollectMacro)
390 return true;
391 assert(PP.get());
392
393 const auto &SM = PP->getSourceManager();
394 if (SM.isInMainFile(SM.getExpansionLoc(MI->getDefinitionLoc())))
395 return true;
396 // Header guards are not interesting in index. Builtin macros don't have
397 // useful locations and are not needed for code completions.
398 if (MI->isUsedForHeaderGuard() || MI->isBuiltinMacro())
399 return true;
400
401 // Mark the macro as referenced if this is a reference coming from the main
402 // file. The macro may not be an interesting symbol, but it's cheaper to check
403 // at the end.
404 if (Opts.CountReferences &&
405 (Roles & static_cast<unsigned>(index::SymbolRole::Reference)) &&
406 SM.getFileID(SM.getSpellingLoc(Loc)) == SM.getMainFileID())
407 ReferencedMacros.insert(Name);
408 // Don't continue indexing if this is a mere reference.
409 // FIXME: remove macro with ID if it is undefined.
410 if (!(Roles & static_cast<unsigned>(index::SymbolRole::Declaration) ||
411 Roles & static_cast<unsigned>(index::SymbolRole::Definition)))
412 return true;
413
Eric Liud25f1212018-09-06 09:59:37 +0000414 auto ID = getSymbolID(*Name, MI, SM);
415 if (!ID)
Eric Liu48db19e2018-07-09 15:31:07 +0000416 return true;
Eric Liu48db19e2018-07-09 15:31:07 +0000417
418 // Only collect one instance in case there are multiple.
Eric Liud25f1212018-09-06 09:59:37 +0000419 if (Symbols.find(*ID) != nullptr)
Eric Liu48db19e2018-07-09 15:31:07 +0000420 return true;
421
422 Symbol S;
Eric Liud25f1212018-09-06 09:59:37 +0000423 S.ID = std::move(*ID);
Eric Liu48db19e2018-07-09 15:31:07 +0000424 S.Name = Name->getName();
Eric Liu6df66002018-09-06 18:52:26 +0000425 S.Flags |= Symbol::IndexedForCodeCompletion;
Eric Liu48db19e2018-07-09 15:31:07 +0000426 S.SymInfo = index::getSymbolInfoForMacro(*MI);
427 std::string FileURI;
428 if (auto DeclLoc = getTokenLocation(MI->getDefinitionLoc(), SM, Opts,
429 PP->getLangOpts(), FileURI))
430 S.CanonicalDeclaration = *DeclLoc;
431
432 CodeCompletionResult SymbolCompletion(Name);
433 const auto *CCS = SymbolCompletion.CreateCodeCompletionStringForMacro(
434 *PP, *CompletionAllocator, *CompletionTUInfo);
435 std::string Signature;
436 std::string SnippetSuffix;
437 getSignature(*CCS, &Signature, &SnippetSuffix);
438
439 std::string Include;
440 if (Opts.CollectIncludePath && shouldCollectIncludePath(S.SymInfo.Kind)) {
441 if (auto Header =
442 getIncludeHeader(Name->getName(), SM,
443 SM.getExpansionLoc(MI->getDefinitionLoc()), Opts))
444 Include = std::move(*Header);
445 }
446 S.Signature = Signature;
447 S.CompletionSnippetSuffix = SnippetSuffix;
Eric Liu83f63e42018-09-03 10:18:21 +0000448 if (!Include.empty())
449 S.IncludeHeaders.emplace_back(Include, 1);
450
Eric Liu48db19e2018-07-09 15:31:07 +0000451 Symbols.insert(S);
452 return true;
453}
454
Sam McCall93f99bf2018-03-12 14:49:09 +0000455void SymbolCollector::finish() {
Eric Liu48db19e2018-07-09 15:31:07 +0000456 // At the end of the TU, add 1 to the refcount of all referenced symbols.
457 auto IncRef = [this](const SymbolID &ID) {
458 if (const auto *S = Symbols.find(ID)) {
459 Symbol Inc = *S;
460 ++Inc.References;
461 Symbols.insert(Inc);
462 }
463 };
464 for (const NamedDecl *ND : ReferencedDecls) {
Haojian Wuc6ddb462018-08-07 08:57:52 +0000465 if (auto ID = getSymbolID(ND)) {
466 IncRef(*ID);
467 }
Eric Liu48db19e2018-07-09 15:31:07 +0000468 }
469 if (Opts.CollectMacro) {
470 assert(PP);
471 for (const IdentifierInfo *II : ReferencedMacros) {
Eric Liua62c9d62018-07-09 18:54:51 +0000472 if (const auto *MI = PP->getMacroDefinition(II).getMacroInfo())
Eric Liud25f1212018-09-06 09:59:37 +0000473 if (auto ID = getSymbolID(*II, MI, PP->getSourceManager()))
474 IncRef(*ID);
Eric Liu48db19e2018-07-09 15:31:07 +0000475 }
Sam McCall93f99bf2018-03-12 14:49:09 +0000476 }
Haojian Wud81e3142018-08-31 12:54:13 +0000477
478 const auto &SM = ASTCtx->getSourceManager();
Haojian Wu7dd49502018-10-17 08:38:36 +0000479 llvm::DenseMap<FileID, std::string> URICache;
480 auto GetURI = [&](FileID FID) -> llvm::Optional<std::string> {
481 auto Found = URICache.find(FID);
482 if (Found == URICache.end()) {
Haojian Wu7dd49502018-10-17 08:38:36 +0000483 if (auto *FileEntry = SM.getFileEntryForID(FID)) {
484 auto FileURI = toURI(SM, FileEntry->getName(), Opts);
485 if (!FileURI) {
486 log("Failed to create URI for file: {0}\n", FileEntry);
487 FileURI = ""; // reset to empty as we also want to cache this case.
488 }
489 Found = URICache.insert({FID, *FileURI}).first;
Haojian Wuc014d862018-10-17 08:54:48 +0000490 } else {
491 // Ignore cases where we can not find a corresponding file entry
492 // for the loc, thoses are not interesting, e.g. symbols formed
493 // via macro concatenation.
494 return llvm::None;
Haojian Wu7dd49502018-10-17 08:38:36 +0000495 }
496 }
497 return Found->second;
498 };
Haojian Wud81e3142018-08-31 12:54:13 +0000499
Haojian Wu7dd49502018-10-17 08:38:36 +0000500 if (auto MainFileURI = GetURI(SM.getMainFileID())) {
Sam McCallb0138312018-09-04 14:39:56 +0000501 for (const auto &It : DeclRefs) {
Haojian Wud81e3142018-08-31 12:54:13 +0000502 if (auto ID = getSymbolID(It.first)) {
Haojian Wue83cacc2018-10-15 11:46:26 +0000503 for (const auto &LocAndRole : It.second) {
Haojian Wu7dd49502018-10-17 08:38:36 +0000504 auto FileID = SM.getFileID(LocAndRole.first);
505 if (auto FileURI = GetURI(FileID)) {
506 auto Range =
507 getTokenRange(LocAndRole.first, SM, ASTCtx->getLangOpts());
508 Ref R;
509 R.Location.Start = Range.first;
510 R.Location.End = Range.second;
511 R.Location.FileURI = *FileURI;
512 R.Kind = toRefKind(LocAndRole.second);
513 Refs.insert(*ID, R);
514 }
Haojian Wud81e3142018-08-31 12:54:13 +0000515 }
516 }
517 }
Haojian Wud81e3142018-08-31 12:54:13 +0000518 }
519
Sam McCall93f99bf2018-03-12 14:49:09 +0000520 ReferencedDecls.clear();
Eric Liu48db19e2018-07-09 15:31:07 +0000521 ReferencedMacros.clear();
Sam McCallb0138312018-09-04 14:39:56 +0000522 DeclRefs.clear();
Sam McCall93f99bf2018-03-12 14:49:09 +0000523}
524
Sam McCall60039512018-02-09 14:42:01 +0000525const Symbol *SymbolCollector::addDeclaration(const NamedDecl &ND,
526 SymbolID ID) {
Ilya Biryukov43714502018-05-16 12:32:44 +0000527 auto &Ctx = ND.getASTContext();
528 auto &SM = Ctx.getSourceManager();
Sam McCall60039512018-02-09 14:42:01 +0000529
Sam McCall60039512018-02-09 14:42:01 +0000530 Symbol S;
531 S.ID = std::move(ID);
Eric Liu7ad16962018-06-22 10:46:59 +0000532 std::string QName = printQualifiedName(ND);
Sam McCall60039512018-02-09 14:42:01 +0000533 std::tie(S.Scope, S.Name) = splitQualifiedName(QName);
Sam McCall032db942018-06-22 06:41:43 +0000534 // FIXME: this returns foo:bar: for objective-C methods, we prefer only foo:
535 // for consistency with CodeCompletionString and a clean name/signature split.
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +0000536
Eric Liu6df66002018-09-06 18:52:26 +0000537 if (isIndexedForCodeCompletion(ND, Ctx))
538 S.Flags |= Symbol::IndexedForCodeCompletion;
Sam McCall60039512018-02-09 14:42:01 +0000539 S.SymInfo = index::getSymbolInfo(&ND);
540 std::string FileURI;
Eric Liu48db19e2018-07-09 15:31:07 +0000541 if (auto DeclLoc = getTokenLocation(findNameLoc(&ND), SM, Opts,
542 ASTCtx->getLangOpts(), FileURI))
Sam McCall60039512018-02-09 14:42:01 +0000543 S.CanonicalDeclaration = *DeclLoc;
544
545 // Add completion info.
546 // FIXME: we may want to choose a different redecl, or combine from several.
547 assert(ASTCtx && PP.get() && "ASTContext and Preprocessor must be set.");
Ilya Biryukovcf124bd2018-04-13 11:03:07 +0000548 // We use the primary template, as clang does during code completion.
549 CodeCompletionResult SymbolCompletion(&getTemplateOrThis(ND), 0);
Sam McCall60039512018-02-09 14:42:01 +0000550 const auto *CCS = SymbolCompletion.CreateCodeCompletionString(
551 *ASTCtx, *PP, CodeCompletionContext::CCC_Name, *CompletionAllocator,
552 *CompletionTUInfo,
Ilya Biryukov43714502018-05-16 12:32:44 +0000553 /*IncludeBriefComments*/ false);
Sam McCalla68951e2018-06-22 16:11:35 +0000554 std::string Signature;
555 std::string SnippetSuffix;
556 getSignature(*CCS, &Signature, &SnippetSuffix);
Ilya Biryukov43714502018-05-16 12:32:44 +0000557 std::string Documentation =
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +0000558 formatDocumentation(*CCS, getDocComment(Ctx, SymbolCompletion,
559 /*CommentsFromHeaders=*/true));
Sam McCalla68951e2018-06-22 16:11:35 +0000560 std::string ReturnType = getReturnType(*CCS);
Sam McCall60039512018-02-09 14:42:01 +0000561
Eric Liuc5105f92018-02-16 14:15:55 +0000562 std::string Include;
563 if (Opts.CollectIncludePath && shouldCollectIncludePath(S.SymInfo.Kind)) {
564 // Use the expansion location to get the #include header since this is
565 // where the symbol is exposed.
Eric Liub96363d2018-03-01 18:06:40 +0000566 if (auto Header = getIncludeHeader(
567 QName, SM, SM.getExpansionLoc(ND.getLocation()), Opts))
Eric Liuc5105f92018-02-16 14:15:55 +0000568 Include = std::move(*Header);
569 }
Sam McCalla68951e2018-06-22 16:11:35 +0000570 S.Signature = Signature;
571 S.CompletionSnippetSuffix = SnippetSuffix;
Sam McCall2e5700f2018-08-31 13:55:01 +0000572 S.Documentation = Documentation;
573 S.ReturnType = ReturnType;
Eric Liu83f63e42018-09-03 10:18:21 +0000574 if (!Include.empty())
575 S.IncludeHeaders.emplace_back(Include, 1);
Sam McCall60039512018-02-09 14:42:01 +0000576
Sam McCall2161ec72018-07-05 06:20:41 +0000577 S.Origin = Opts.Origin;
Eric Liu6df66002018-09-06 18:52:26 +0000578 if (ND.getAvailability() == AR_Deprecated)
579 S.Flags |= Symbol::Deprecated;
Sam McCall60039512018-02-09 14:42:01 +0000580 Symbols.insert(S);
581 return Symbols.find(S.ID);
582}
583
584void SymbolCollector::addDefinition(const NamedDecl &ND,
585 const Symbol &DeclSym) {
586 if (DeclSym.Definition)
587 return;
588 // If we saw some forward declaration, we end up copying the symbol.
589 // This is not ideal, but avoids duplicating the "is this a definition" check
590 // in clang::index. We should only see one definition.
591 Symbol S = DeclSym;
592 std::string FileURI;
Eric Liu48db19e2018-07-09 15:31:07 +0000593 if (auto DefLoc = getTokenLocation(findNameLoc(&ND),
594 ND.getASTContext().getSourceManager(),
595 Opts, ASTCtx->getLangOpts(), FileURI))
Sam McCall60039512018-02-09 14:42:01 +0000596 S.Definition = *DefLoc;
597 Symbols.insert(S);
598}
599
Haojian Wu4c1394d2017-12-12 15:42:10 +0000600} // namespace clangd
601} // namespace clang