blob: 80b5c5b011820aabe1c851b6875ef9c7cc1bf29b [file] [log] [blame]
Haojian Wu4c1394d2017-12-12 15:42:10 +00001//===--- SymbolCollector.cpp -------------------------------------*- C++-*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Haojian Wu4c1394d2017-12-12 15:42:10 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "SymbolCollector.h"
Eric Liuf7688682018-09-07 09:40:36 +000010#include "AST.h"
Eric Liuc5105f92018-02-16 14:15:55 +000011#include "CanonicalIncludes.h"
Eric Liuf7688682018-09-07 09:40:36 +000012#include "CodeComplete.h"
13#include "CodeCompletionStrings.h"
14#include "Logger.h"
15#include "SourceCode.h"
Dmitri Gribenko5306a712019-02-28 11:02:01 +000016#include "SymbolLocation.h"
Eric Liuf7688682018-09-07 09:40:36 +000017#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,
Sam McCall0e93b072019-01-14 10:01:17 +0000243 const Options &Opts,
244 bool IsMainFileOnly) {
Eric Liu8763e482018-06-21 12:12:26 +0000245 if (ND.isImplicit())
246 return false;
247 // Skip anonymous declarations, e.g (anonymous enum/class/struct).
248 if (ND.getDeclName().isEmpty())
249 return false;
250
Sam McCall0e93b072019-01-14 10:01:17 +0000251 // Skip main-file symbols if we are not collecting them.
252 if (IsMainFileOnly && !Opts.CollectMainFileSymbols)
253 return false;
254
255 // Skip symbols in anonymous namespaces in header files.
256 if (!IsMainFileOnly && ND.isInAnonymousNamespace())
Eric Liu8763e482018-06-21 12:12:26 +0000257 return false;
258
259 // We want most things but not "local" symbols such as symbols inside
260 // FunctionDecl, BlockDecl, ObjCMethodDecl and OMPDeclareReductionDecl.
261 // FIXME: Need a matcher for ExportDecl in order to include symbols declared
262 // within an export.
Eric Liua57afd02018-09-17 07:43:49 +0000263 const auto *DeclCtx = ND.getDeclContext();
264 switch (DeclCtx->getDeclKind()) {
265 case Decl::TranslationUnit:
266 case Decl::Namespace:
267 case Decl::LinkageSpec:
268 case Decl::Enum:
269 case Decl::ObjCProtocol:
270 case Decl::ObjCInterface:
271 case Decl::ObjCCategory:
272 case Decl::ObjCCategoryImpl:
273 case Decl::ObjCImplementation:
274 break;
275 default:
276 // Record has a few derivations (e.g. CXXRecord, Class specialization), it's
277 // easier to cast.
Sam McCallc008af62018-10-20 15:30:37 +0000278 if (!isa<RecordDecl>(DeclCtx))
Eric Liua57afd02018-09-17 07:43:49 +0000279 return false;
280 }
281 if (explicitTemplateSpecialization<FunctionDecl>(ND) ||
282 explicitTemplateSpecialization<CXXRecordDecl>(ND) ||
283 explicitTemplateSpecialization<VarDecl>(ND))
Eric Liu8763e482018-06-21 12:12:26 +0000284 return false;
285
286 // Avoid indexing internal symbols in protobuf generated headers.
287 if (isPrivateProtoDecl(ND))
288 return false;
289 return true;
290}
291
Haojian Wu4c1394d2017-12-12 15:42:10 +0000292// Always return true to continue indexing.
293bool SymbolCollector::handleDeclOccurence(
294 const Decl *D, index::SymbolRoleSet Roles,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000295 llvm::ArrayRef<index::SymbolRelation> Relations, SourceLocation Loc,
Haojian Wu4c1394d2017-12-12 15:42:10 +0000296 index::IndexDataConsumer::ASTNodeInfo ASTNode) {
Eric Liu9af958f2018-01-10 14:57:58 +0000297 assert(ASTCtx && PP.get() && "ASTContext and Preprocessor must be set.");
Sam McCall93f99bf2018-03-12 14:49:09 +0000298 assert(CompletionAllocator && CompletionTUInfo);
Eric Liu77d18112018-06-04 11:31:55 +0000299 assert(ASTNode.OrigD);
300 // If OrigD is an declaration associated with a friend declaration and it's
301 // not a definition, skip it. Note that OrigD is the occurrence that the
302 // collector is currently visiting.
303 if ((ASTNode.OrigD->getFriendObjectKind() !=
304 Decl::FriendObjectKind::FOK_None) &&
305 !(Roles & static_cast<unsigned>(index::SymbolRole::Definition)))
306 return true;
307 // A declaration created for a friend declaration should not be used as the
308 // canonical declaration in the index. Use OrigD instead, unless we've already
309 // picked a replacement for D
310 if (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None)
311 D = CanonicalDecls.try_emplace(D, ASTNode.OrigD).first->second;
Sam McCallc008af62018-10-20 15:30:37 +0000312 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
Sam McCall93f99bf2018-03-12 14:49:09 +0000313 if (!ND)
314 return true;
Eric Liu9af958f2018-01-10 14:57:58 +0000315
Sam McCall93f99bf2018-03-12 14:49:09 +0000316 // Mark D as referenced if this is a reference coming from the main file.
317 // D may not be an interesting symbol, but it's cheaper to check at the end.
Sam McCallb9d57112018-04-09 14:28:52 +0000318 auto &SM = ASTCtx->getSourceManager();
Haojian Wud81e3142018-08-31 12:54:13 +0000319 auto SpellingLoc = SM.getSpellingLoc(Loc);
Sam McCall93f99bf2018-03-12 14:49:09 +0000320 if (Opts.CountReferences &&
321 (Roles & static_cast<unsigned>(index::SymbolRole::Reference)) &&
Haojian Wud81e3142018-08-31 12:54:13 +0000322 SM.getFileID(SpellingLoc) == SM.getMainFileID())
Sam McCall93f99bf2018-03-12 14:49:09 +0000323 ReferencedDecls.insert(ND);
324
Haojian Wue83cacc2018-10-15 11:46:26 +0000325 bool CollectRef = static_cast<unsigned>(Opts.RefFilter) & Roles;
326 bool IsOnlyRef =
327 !(Roles & (static_cast<unsigned>(index::SymbolRole::Declaration) |
328 static_cast<unsigned>(index::SymbolRole::Definition)));
Haojian Wud81e3142018-08-31 12:54:13 +0000329
Haojian Wue83cacc2018-10-15 11:46:26 +0000330 if (IsOnlyRef && !CollectRef)
Haojian Wu4c1394d2017-12-12 15:42:10 +0000331 return true;
Sam McCall0e93b072019-01-14 10:01:17 +0000332
333 // ND is the canonical (i.e. first) declaration. If it's in the main file,
334 // then no public declaration was visible, so assume it's main-file only.
335 bool IsMainFileOnly = SM.isWrittenInMainFile(SM.getExpansionLoc(
336 ND->getBeginLoc()));
337 if (!shouldCollectSymbol(*ND, *ASTCtx, Opts, IsMainFileOnly))
Sam McCall93f99bf2018-03-12 14:49:09 +0000338 return true;
Sam McCall0e93b072019-01-14 10:01:17 +0000339 // Do not store references to main-file symbols.
340 if (CollectRef && !IsMainFileOnly && !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
Ilya Biryukov4e0c4002019-01-23 10:35:12 +0000351 // FIXME: ObjCPropertyDecl are not properly indexed here:
352 // - ObjCPropertyDecl may have an OrigD of ObjCPropertyImplDecl, which is
353 // not a NamedDecl.
354 auto *OriginalDecl = dyn_cast<NamedDecl>(ASTNode.OrigD);
355 if (!OriginalDecl)
356 return true;
357
Haojian Wuc6ddb462018-08-07 08:57:52 +0000358 const Symbol *BasicSymbol = Symbols.find(*ID);
Sam McCall93f99bf2018-03-12 14:49:09 +0000359 if (!BasicSymbol) // Regardless of role, ND is the canonical declaration.
Sam McCall0e93b072019-01-14 10:01:17 +0000360 BasicSymbol = addDeclaration(*ND, std::move(*ID), IsMainFileOnly);
Ilya Biryukov4e0c4002019-01-23 10:35:12 +0000361 else if (isPreferredDeclaration(*OriginalDecl, Roles))
Sam McCall93f99bf2018-03-12 14:49:09 +0000362 // If OriginalDecl is preferred, replace the existing canonical
363 // declaration (e.g. a class forward declaration). There should be at most
364 // one duplicate as we expect to see only one preferred declaration per
365 // TU, because in practice they are definitions.
Ilya Biryukov4e0c4002019-01-23 10:35:12 +0000366 BasicSymbol = addDeclaration(*OriginalDecl, std::move(*ID), IsMainFileOnly);
Haojian Wu4c1394d2017-12-12 15:42:10 +0000367
Sam McCall93f99bf2018-03-12 14:49:09 +0000368 if (Roles & static_cast<unsigned>(index::SymbolRole::Definition))
Ilya Biryukov4e0c4002019-01-23 10:35:12 +0000369 addDefinition(*OriginalDecl, *BasicSymbol);
Haojian Wu4c1394d2017-12-12 15:42:10 +0000370 return true;
371}
372
Eric Liu48db19e2018-07-09 15:31:07 +0000373bool SymbolCollector::handleMacroOccurence(const IdentifierInfo *Name,
374 const MacroInfo *MI,
375 index::SymbolRoleSet Roles,
376 SourceLocation Loc) {
377 if (!Opts.CollectMacro)
378 return true;
379 assert(PP.get());
380
381 const auto &SM = PP->getSourceManager();
Eric Liuad588af2018-11-06 10:55:21 +0000382 auto DefLoc = MI->getDefinitionLoc();
Haojian Wu7b6f8742019-01-28 14:11:49 +0000383
Eric Liu48db19e2018-07-09 15:31:07 +0000384 // Header guards are not interesting in index. Builtin macros don't have
385 // useful locations and are not needed for code completions.
386 if (MI->isUsedForHeaderGuard() || MI->isBuiltinMacro())
387 return true;
388
Haojian Wu7b6f8742019-01-28 14:11:49 +0000389 // Skip main-file symbols if we are not collecting them.
390 bool IsMainFileSymbol = SM.isInMainFile(SM.getExpansionLoc(DefLoc));
391 if (IsMainFileSymbol && !Opts.CollectMainFileSymbols)
392 return false;
393
394 // Also avoid storing predefined macros like __DBL_MIN__.
395 if (SM.isWrittenInBuiltinFile(DefLoc))
396 return true;
397
Eric Liu48db19e2018-07-09 15:31:07 +0000398 // 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();
Haojian Wu7b6f8742019-01-28 14:11:49 +0000422 if (!IsMainFileSymbol) {
423 S.Flags |= Symbol::IndexedForCodeCompletion;
424 S.Flags |= Symbol::VisibleOutsideFile;
425 }
Eric Liu48db19e2018-07-09 15:31:07 +0000426 S.SymInfo = index::getSymbolInfoForMacro(*MI);
427 std::string FileURI;
Eric Liuad588af2018-11-06 10:55:21 +0000428 // FIXME: use the result to filter out symbols.
429 shouldIndexFile(SM, SM.getFileID(Loc), Opts, &FilesToIndexCache);
430 if (auto DeclLoc =
431 getTokenLocation(DefLoc, SM, Opts, PP->getLangOpts(), FileURI))
Eric Liu48db19e2018-07-09 15:31:07 +0000432 S.CanonicalDeclaration = *DeclLoc;
433
434 CodeCompletionResult SymbolCompletion(Name);
435 const auto *CCS = SymbolCompletion.CreateCodeCompletionStringForMacro(
436 *PP, *CompletionAllocator, *CompletionTUInfo);
437 std::string Signature;
438 std::string SnippetSuffix;
439 getSignature(*CCS, &Signature, &SnippetSuffix);
440
441 std::string Include;
442 if (Opts.CollectIncludePath && shouldCollectIncludePath(S.SymInfo.Kind)) {
Eric Liuad588af2018-11-06 10:55:21 +0000443 if (auto Header = getIncludeHeader(Name->getName(), SM,
444 SM.getExpansionLoc(DefLoc), Opts))
Eric Liu48db19e2018-07-09 15:31:07 +0000445 Include = std::move(*Header);
446 }
447 S.Signature = Signature;
448 S.CompletionSnippetSuffix = SnippetSuffix;
Eric Liu83f63e42018-09-03 10:18:21 +0000449 if (!Include.empty())
450 S.IncludeHeaders.emplace_back(Include, 1);
451
Eric Liu48db19e2018-07-09 15:31:07 +0000452 Symbols.insert(S);
453 return true;
454}
455
Sam McCall93f99bf2018-03-12 14:49:09 +0000456void SymbolCollector::finish() {
Eric Liu48db19e2018-07-09 15:31:07 +0000457 // At the end of the TU, add 1 to the refcount of all referenced symbols.
458 auto IncRef = [this](const SymbolID &ID) {
459 if (const auto *S = Symbols.find(ID)) {
460 Symbol Inc = *S;
461 ++Inc.References;
462 Symbols.insert(Inc);
463 }
464 };
465 for (const NamedDecl *ND : ReferencedDecls) {
Haojian Wuc6ddb462018-08-07 08:57:52 +0000466 if (auto ID = getSymbolID(ND)) {
467 IncRef(*ID);
468 }
Eric Liu48db19e2018-07-09 15:31:07 +0000469 }
470 if (Opts.CollectMacro) {
471 assert(PP);
472 for (const IdentifierInfo *II : ReferencedMacros) {
Eric Liua62c9d62018-07-09 18:54:51 +0000473 if (const auto *MI = PP->getMacroDefinition(II).getMacroInfo())
Eric Liud25f1212018-09-06 09:59:37 +0000474 if (auto ID = getSymbolID(*II, MI, PP->getSourceManager()))
475 IncRef(*ID);
Eric Liu48db19e2018-07-09 15:31:07 +0000476 }
Sam McCall93f99bf2018-03-12 14:49:09 +0000477 }
Haojian Wud81e3142018-08-31 12:54:13 +0000478
479 const auto &SM = ASTCtx->getSourceManager();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000480 llvm::DenseMap<FileID, std::string> URICache;
481 auto GetURI = [&](FileID FID) -> llvm::Optional<std::string> {
Haojian Wu7dd49502018-10-17 08:38:36 +0000482 auto Found = URICache.find(FID);
483 if (Found == URICache.end()) {
Haojian Wu7dd49502018-10-17 08:38:36 +0000484 if (auto *FileEntry = SM.getFileEntryForID(FID)) {
485 auto FileURI = toURI(SM, FileEntry->getName(), Opts);
Kadir Cetinkayadd677932018-12-19 10:46:21 +0000486 Found = URICache.insert({FID, FileURI}).first;
Haojian Wuc014d862018-10-17 08:54:48 +0000487 } else {
488 // Ignore cases where we can not find a corresponding file entry
489 // for the loc, thoses are not interesting, e.g. symbols formed
490 // via macro concatenation.
Sam McCallc008af62018-10-20 15:30:37 +0000491 return None;
Haojian Wu7dd49502018-10-17 08:38:36 +0000492 }
493 }
494 return Found->second;
495 };
Haojian Wud81e3142018-08-31 12:54:13 +0000496
Haojian Wu7dd49502018-10-17 08:38:36 +0000497 if (auto MainFileURI = GetURI(SM.getMainFileID())) {
Sam McCallb0138312018-09-04 14:39:56 +0000498 for (const auto &It : DeclRefs) {
Haojian Wud81e3142018-08-31 12:54:13 +0000499 if (auto ID = getSymbolID(It.first)) {
Haojian Wue83cacc2018-10-15 11:46:26 +0000500 for (const auto &LocAndRole : It.second) {
Haojian Wu7dd49502018-10-17 08:38:36 +0000501 auto FileID = SM.getFileID(LocAndRole.first);
Eric Liuad588af2018-11-06 10:55:21 +0000502 // FIXME: use the result to filter out references.
503 shouldIndexFile(SM, FileID, Opts, &FilesToIndexCache);
Haojian Wu7dd49502018-10-17 08:38:36 +0000504 if (auto FileURI = GetURI(FileID)) {
505 auto Range =
506 getTokenRange(LocAndRole.first, SM, ASTCtx->getLangOpts());
507 Ref R;
508 R.Location.Start = Range.first;
509 R.Location.End = Range.second;
Haojian Wuee54a2b2018-11-14 11:55:45 +0000510 R.Location.FileURI = FileURI->c_str();
Haojian Wu7dd49502018-10-17 08:38:36 +0000511 R.Kind = toRefKind(LocAndRole.second);
512 Refs.insert(*ID, R);
513 }
Haojian Wud81e3142018-08-31 12:54:13 +0000514 }
515 }
516 }
Haojian Wud81e3142018-08-31 12:54:13 +0000517 }
518
Sam McCall93f99bf2018-03-12 14:49:09 +0000519 ReferencedDecls.clear();
Eric Liu48db19e2018-07-09 15:31:07 +0000520 ReferencedMacros.clear();
Sam McCallb0138312018-09-04 14:39:56 +0000521 DeclRefs.clear();
Eric Liuad588af2018-11-06 10:55:21 +0000522 FilesToIndexCache.clear();
Sam McCall93f99bf2018-03-12 14:49:09 +0000523}
524
Sam McCall60039512018-02-09 14:42:01 +0000525const Symbol *SymbolCollector::addDeclaration(const NamedDecl &ND,
Sam McCall0e93b072019-01-14 10:01:17 +0000526 SymbolID ID,
527 bool IsMainFileOnly) {
Ilya Biryukov43714502018-05-16 12:32:44 +0000528 auto &Ctx = ND.getASTContext();
529 auto &SM = Ctx.getSourceManager();
Sam McCall60039512018-02-09 14:42:01 +0000530
Sam McCall60039512018-02-09 14:42:01 +0000531 Symbol S;
532 S.ID = std::move(ID);
Eric Liu7ad16962018-06-22 10:46:59 +0000533 std::string QName = printQualifiedName(ND);
Sam McCall60039512018-02-09 14:42:01 +0000534 std::tie(S.Scope, S.Name) = splitQualifiedName(QName);
Sam McCall032db942018-06-22 06:41:43 +0000535 // FIXME: this returns foo:bar: for objective-C methods, we prefer only foo:
536 // for consistency with CodeCompletionString and a clean name/signature split.
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +0000537
Sam McCall0e93b072019-01-14 10:01:17 +0000538 // We collect main-file symbols, but do not use them for code completion.
539 if (!IsMainFileOnly && isIndexedForCodeCompletion(ND, Ctx))
Eric Liu6df66002018-09-06 18:52:26 +0000540 S.Flags |= Symbol::IndexedForCodeCompletion;
Eric Liu48597382018-10-18 12:23:05 +0000541 if (isImplementationDetail(&ND))
542 S.Flags |= Symbol::ImplementationDetail;
Sam McCall0e93b072019-01-14 10:01:17 +0000543 if (!IsMainFileOnly)
544 S.Flags |= Symbol::VisibleOutsideFile;
Sam McCall60039512018-02-09 14:42:01 +0000545 S.SymInfo = index::getSymbolInfo(&ND);
546 std::string FileURI;
Eric Liuad588af2018-11-06 10:55:21 +0000547 auto Loc = findNameLoc(&ND);
548 // FIXME: use the result to filter out symbols.
549 shouldIndexFile(SM, SM.getFileID(Loc), Opts, &FilesToIndexCache);
550 if (auto DeclLoc =
551 getTokenLocation(Loc, SM, Opts, ASTCtx->getLangOpts(), FileURI))
Sam McCall60039512018-02-09 14:42:01 +0000552 S.CanonicalDeclaration = *DeclLoc;
553
Haojian Wu8f85b9f2019-01-10 09:22:40 +0000554 S.Origin = Opts.Origin;
555 if (ND.getAvailability() == AR_Deprecated)
556 S.Flags |= Symbol::Deprecated;
557
Sam McCall60039512018-02-09 14:42:01 +0000558 // Add completion info.
559 // FIXME: we may want to choose a different redecl, or combine from several.
560 assert(ASTCtx && PP.get() && "ASTContext and Preprocessor must be set.");
Ilya Biryukovcf124bd2018-04-13 11:03:07 +0000561 // We use the primary template, as clang does during code completion.
562 CodeCompletionResult SymbolCompletion(&getTemplateOrThis(ND), 0);
Sam McCall60039512018-02-09 14:42:01 +0000563 const auto *CCS = SymbolCompletion.CreateCodeCompletionString(
Kadir Cetinkayab9157902018-10-24 15:24:29 +0000564 *ASTCtx, *PP, CodeCompletionContext::CCC_Symbol, *CompletionAllocator,
Sam McCall60039512018-02-09 14:42:01 +0000565 *CompletionTUInfo,
Ilya Biryukov43714502018-05-16 12:32:44 +0000566 /*IncludeBriefComments*/ false);
Ilya Biryukov43714502018-05-16 12:32:44 +0000567 std::string Documentation =
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +0000568 formatDocumentation(*CCS, getDocComment(Ctx, SymbolCompletion,
569 /*CommentsFromHeaders=*/true));
Haojian Wu8f85b9f2019-01-10 09:22:40 +0000570 if (!(S.Flags & Symbol::IndexedForCodeCompletion)) {
Haojian Wuda79dcc2019-02-25 16:00:00 +0000571 if (Opts.StoreAllDocumentation)
572 S.Documentation = Documentation;
Haojian Wu8f85b9f2019-01-10 09:22:40 +0000573 Symbols.insert(S);
574 return Symbols.find(S.ID);
575 }
Haojian Wuda79dcc2019-02-25 16:00:00 +0000576 S.Documentation = Documentation;
Haojian Wu8f85b9f2019-01-10 09:22:40 +0000577 std::string Signature;
578 std::string SnippetSuffix;
579 getSignature(*CCS, &Signature, &SnippetSuffix);
580 S.Signature = Signature;
581 S.CompletionSnippetSuffix = SnippetSuffix;
Sam McCalla68951e2018-06-22 16:11:35 +0000582 std::string ReturnType = getReturnType(*CCS);
Haojian Wu8f85b9f2019-01-10 09:22:40 +0000583 S.ReturnType = ReturnType;
Sam McCall60039512018-02-09 14:42:01 +0000584
Eric Liuc5105f92018-02-16 14:15:55 +0000585 std::string Include;
586 if (Opts.CollectIncludePath && shouldCollectIncludePath(S.SymInfo.Kind)) {
587 // Use the expansion location to get the #include header since this is
588 // where the symbol is exposed.
Eric Liub96363d2018-03-01 18:06:40 +0000589 if (auto Header = getIncludeHeader(
590 QName, SM, SM.getExpansionLoc(ND.getLocation()), Opts))
Eric Liuc5105f92018-02-16 14:15:55 +0000591 Include = std::move(*Header);
592 }
Eric Liu83f63e42018-09-03 10:18:21 +0000593 if (!Include.empty())
594 S.IncludeHeaders.emplace_back(Include, 1);
Sam McCall60039512018-02-09 14:42:01 +0000595
Ilya Biryukov4d3d82e2018-11-26 15:52:16 +0000596 llvm::Optional<OpaqueType> TypeStorage;
Ilya Biryukova21392b2018-11-26 15:29:14 +0000597 if (S.Flags & Symbol::IndexedForCodeCompletion) {
Ilya Biryukov4d3d82e2018-11-26 15:52:16 +0000598 TypeStorage = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion);
599 if (TypeStorage)
600 S.Type = TypeStorage->raw();
Ilya Biryukova21392b2018-11-26 15:29:14 +0000601 }
602
Sam McCall60039512018-02-09 14:42:01 +0000603 Symbols.insert(S);
604 return Symbols.find(S.ID);
605}
606
607void SymbolCollector::addDefinition(const NamedDecl &ND,
608 const Symbol &DeclSym) {
609 if (DeclSym.Definition)
610 return;
611 // If we saw some forward declaration, we end up copying the symbol.
612 // This is not ideal, but avoids duplicating the "is this a definition" check
613 // in clang::index. We should only see one definition.
614 Symbol S = DeclSym;
615 std::string FileURI;
Eric Liuad588af2018-11-06 10:55:21 +0000616 auto Loc = findNameLoc(&ND);
617 const auto &SM = ND.getASTContext().getSourceManager();
618 // FIXME: use the result to filter out symbols.
619 shouldIndexFile(SM, SM.getFileID(Loc), Opts, &FilesToIndexCache);
620 if (auto DefLoc =
621 getTokenLocation(Loc, SM, Opts, ASTCtx->getLangOpts(), FileURI))
Sam McCall60039512018-02-09 14:42:01 +0000622 S.Definition = *DefLoc;
623 Symbols.insert(S);
624}
625
Haojian Wu4c1394d2017-12-12 15:42:10 +0000626} // namespace clangd
627} // namespace clang