clang-tools 24.0.0git
SymbolCollector.cpp
Go to the documentation of this file.
1//===--- SymbolCollector.cpp -------------------------------------*- C++-*-===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8
9#include "SymbolCollector.h"
10#include "AST.h"
11#include "CodeComplete.h"
13#include "ExpectedTypes.h"
14#include "FindSymbols.h"
15#include "SourceCode.h"
16#include "URI.h"
17#include "clang-include-cleaner/Analysis.h"
18#include "clang-include-cleaner/IncludeSpeller.h"
19#include "clang-include-cleaner/Record.h"
20#include "clang-include-cleaner/Types.h"
22#include "index/Ref.h"
23#include "index/Relation.h"
24#include "index/Symbol.h"
25#include "index/SymbolID.h"
27#include "clang/AST/Decl.h"
28#include "clang/AST/DeclBase.h"
29#include "clang/AST/DeclCXX.h"
30#include "clang/AST/DeclObjC.h"
31#include "clang/AST/DeclTemplate.h"
32#include "clang/AST/DeclarationName.h"
33#include "clang/AST/Expr.h"
34#include "clang/Basic/FileEntry.h"
35#include "clang/Basic/LangOptions.h"
36#include "clang/Basic/SourceLocation.h"
37#include "clang/Basic/SourceManager.h"
38#include "clang/Index/IndexSymbol.h"
39#include "clang/Lex/Preprocessor.h"
40#include "clang/Lex/Token.h"
41#include "clang/Tooling/Inclusions/HeaderAnalysis.h"
42#include "clang/Tooling/Inclusions/StandardLibrary.h"
43#include "llvm/ADT/ArrayRef.h"
44#include "llvm/ADT/DenseMap.h"
45#include "llvm/ADT/SmallVector.h"
46#include "llvm/ADT/StringRef.h"
47#include "llvm/Support/Casting.h"
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/Support/Path.h"
50#include <cassert>
51#include <memory>
52#include <optional>
53#include <string>
54#include <utility>
55
56namespace clang {
57namespace clangd {
58namespace {
59
60/// If \p ND is a template specialization, returns the described template.
61/// Otherwise, returns \p ND.
62const NamedDecl &getTemplateOrThis(const NamedDecl &ND) {
63 if (auto *T = ND.getDescribedTemplate())
64 return *T;
65 return ND;
66}
67
68// Checks whether the decl is a private symbol in a header generated by
69// protobuf compiler.
70// FIXME: make filtering extensible when there are more use cases for symbol
71// filters.
72bool isPrivateProtoDecl(const NamedDecl &ND) {
73 const auto &SM = ND.getASTContext().getSourceManager();
74 if (!isProtoFile(nameLocation(ND, SM), SM))
75 return false;
76
77 // ND without identifier can be operators.
78 if (ND.getIdentifier() == nullptr)
79 return false;
80 auto Name = ND.getIdentifier()->getName();
81 // There are some internal helpers like _internal_set_foo();
82 if (Name.contains("_internal_"))
83 return true;
84
85 // https://protobuf.dev/reference/cpp/cpp-generated/#nested-types
86 // Nested entities (messages/enums) has two names, one at the top-level scope,
87 // with a mangled name created by prepending all the outer types. These names
88 // are almost never preferred by the developers, so exclude them from index.
89 // e.g.
90 // message Foo {
91 // message Bar {}
92 // enum E { A }
93 // }
94 //
95 // yields:
96 // class Foo_Bar {};
97 // enum Foo_E { Foo_E_A };
98 // class Foo {
99 // using Bar = Foo_Bar;
100 // static constexpr Foo_E A = Foo_E_A;
101 // };
102
103 // We get rid of Foo_Bar and Foo_E by discarding any top-level entries with
104 // `_` in the name. This relies on original message/enum not having `_` in the
105 // name. Hence might go wrong in certain cases.
106 if (ND.getDeclContext()->isNamespace()) {
107 // Strip off some known public suffix helpers for enums, rest of the helpers
108 // are generated inside record decls so we don't care.
109 // https://protobuf.dev/reference/cpp/cpp-generated/#enum
110 Name.consume_back("_descriptor");
111 Name.consume_back("_IsValid");
112 Name.consume_back("_Name");
113 Name.consume_back("_Parse");
114 Name.consume_back("_MIN");
115 Name.consume_back("_MAX");
116 Name.consume_back("_ARRAYSIZE");
117 return Name.contains('_');
118 }
119
120 // EnumConstantDecls need some special attention, despite being nested in a
121 // TagDecl, they might still have mangled names. We filter those by checking
122 // if it has parent's name as a prefix.
123 // This might go wrong if a nested entity has a name that starts with parent's
124 // name, e.g: enum Foo { Foo_X }.
125 if (llvm::isa<EnumConstantDecl>(&ND)) {
126 auto *DC = llvm::cast<EnumDecl>(ND.getDeclContext());
127 if (!DC || !DC->getIdentifier())
128 return false;
129 auto CtxName = DC->getIdentifier()->getName();
130 return !CtxName.empty() && Name.consume_front(CtxName) &&
131 Name.consume_front("_");
132 }
133
134 // Now we're only left with fields/methods without an `_internal_` in the
135 // name, they're intended for public use.
136 return false;
137}
138
139// We only collect #include paths for symbols that are suitable for global code
140// completion, except for namespaces since #include path for a namespace is hard
141// to define.
142Symbol::IncludeDirective shouldCollectIncludePath(index::SymbolKind Kind) {
143 using SK = index::SymbolKind;
144 switch (Kind) {
145 case SK::Macro:
146 case SK::Enum:
147 case SK::Struct:
148 case SK::Class:
149 case SK::Union:
150 case SK::TypeAlias:
151 case SK::Using:
152 case SK::Function:
153 case SK::Variable:
154 case SK::EnumConstant:
155 case SK::Concept:
157 case SK::Protocol:
158 return Symbol::Import;
159 default:
160 return Symbol::Invalid;
161 }
162}
163
164// Return the symbol range of the token at \p TokLoc.
165std::pair<SymbolLocation::Position, SymbolLocation::Position>
166getTokenRange(SourceLocation TokLoc, const SourceManager &SM,
167 const LangOptions &LangOpts) {
168 auto CreatePosition = [&SM](SourceLocation Loc) {
169 auto LSPLoc = sourceLocToPosition(SM, Loc);
171 Pos.setLine(LSPLoc.line);
172 Pos.setColumn(LSPLoc.character);
173 return Pos;
174 };
175
176 auto TokenLength = clang::Lexer::MeasureTokenLength(TokLoc, SM, LangOpts);
177 return {CreatePosition(TokLoc),
178 CreatePosition(TokLoc.getLocWithOffset(TokenLength))};
179}
180
181// Checks whether \p ND is a good candidate to be the *canonical* declaration of
182// its symbol (e.g. a go-to-declaration target). This overrides the default of
183// using Clang's canonical declaration, which is the first in the TU.
184//
185// Example: preferring a class declaration over its forward declaration.
186bool isPreferredDeclaration(const NamedDecl &ND, index::SymbolRoleSet Roles) {
187 const auto &SM = ND.getASTContext().getSourceManager();
188 if (isa<TagDecl>(ND))
189 return (Roles & static_cast<unsigned>(index::SymbolRole::Definition)) &&
190 !isInsideMainFile(ND.getLocation(), SM);
191 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(&ND))
192 return ID->isThisDeclarationADefinition();
193 if (const auto *PD = dyn_cast<ObjCProtocolDecl>(&ND))
194 return PD->isThisDeclarationADefinition();
195 return false;
196}
197
198RefKind toRefKind(index::SymbolRoleSet Roles, bool Spelled = false) {
199 RefKind Result = RefKind::Unknown;
200 if (Roles & static_cast<unsigned>(index::SymbolRole::Declaration))
201 Result |= RefKind::Declaration;
202 if (Roles & static_cast<unsigned>(index::SymbolRole::Definition))
203 Result |= RefKind::Definition;
204 if (Roles & static_cast<unsigned>(index::SymbolRole::Reference))
205 Result |= RefKind::Reference;
206 if (Spelled)
207 Result |= RefKind::Spelled;
208 return Result;
209}
210
211std::optional<RelationKind> indexableRelation(const index::SymbolRelation &R) {
212 if (R.Roles & static_cast<unsigned>(index::SymbolRole::RelationBaseOf))
214 if (R.Roles & static_cast<unsigned>(index::SymbolRole::RelationOverrideOf))
216 return std::nullopt;
217}
218
219// Check if there is an exact spelling of \p ND at \p Loc.
220bool isSpelled(SourceLocation Loc, const NamedDecl &ND) {
221 auto Name = ND.getDeclName();
222 const auto NameKind = Name.getNameKind();
223 if (NameKind != DeclarationName::Identifier &&
224 NameKind != DeclarationName::CXXConstructorName &&
225 NameKind != DeclarationName::ObjCZeroArgSelector &&
226 NameKind != DeclarationName::ObjCOneArgSelector &&
227 NameKind != DeclarationName::ObjCMultiArgSelector)
228 return false;
229 const auto &AST = ND.getASTContext();
230 const auto &SM = AST.getSourceManager();
231 const auto &LO = AST.getLangOpts();
232 clang::Token Tok;
233 if (clang::Lexer::getRawToken(Loc, Tok, SM, LO))
234 return false;
235 auto TokSpelling = clang::Lexer::getSpelling(Tok, SM, LO);
236 if (const auto *MD = dyn_cast<ObjCMethodDecl>(&ND))
237 return TokSpelling == MD->getSelector().getNameForSlot(0);
238 return TokSpelling == Name.getAsString();
239}
240} // namespace
241
242// Encapsulates decisions about how to record header paths in the index,
243// including filename normalization, URI conversion etc.
244// Expensive checks are cached internally.
246 struct FrameworkUmbrellaSpelling {
247 // Spelling for the public umbrella header, e.g. <Foundation/Foundation.h>
248 std::optional<std::string> PublicHeader;
249 // Spelling for the private umbrella header, e.g.
250 // <Foundation/Foundation_Private.h>
251 std::optional<std::string> PrivateHeader;
252 };
253 // Weird double-indirect access to PP, which might not be ready yet when
254 // HeaderFiles is created but will be by the time it's used.
255 // (IndexDataConsumer::setPreprocessor can happen before or after initialize)
256 Preprocessor *&PP;
257 const SourceManager &SM;
258 const include_cleaner::PragmaIncludes *PI;
259 llvm::StringRef FallbackDir;
260 llvm::DenseMap<const FileEntry *, const std::string *> CacheFEToURI;
261 llvm::StringMap<std::string> CachePathToURI;
262 llvm::DenseMap<FileID, llvm::StringRef> CacheFIDToInclude;
263 llvm::StringMap<std::string> CachePathToFrameworkSpelling;
264 llvm::StringMap<FrameworkUmbrellaSpelling>
265 CacheFrameworkToUmbrellaHeaderSpelling;
266
267public:
268 HeaderFileURICache(Preprocessor *&PP, const SourceManager &SM,
269 const SymbolCollector::Options &Opts)
270 : PP(PP), SM(SM), PI(Opts.PragmaIncludes), FallbackDir(Opts.FallbackDir) {
271 }
272
273 // Returns a canonical URI for the file \p FE.
274 // We attempt to make the path absolute first.
275 const std::string &toURI(const FileEntryRef FE) {
276 auto R = CacheFEToURI.try_emplace(FE);
277 if (R.second) {
278 auto CanonPath = getCanonicalPath(FE, SM.getFileManager());
279 R.first->second = &toURIInternal(CanonPath ? *CanonPath : FE.getName());
280 }
281 return *R.first->second;
282 }
283
284 // Returns a canonical URI for \p Path.
285 // If the file is in the FileManager, use that to canonicalize the path.
286 // We attempt to make the path absolute in any case.
287 const std::string &toURI(llvm::StringRef Path) {
288 if (auto File = SM.getFileManager().getFileRef(Path))
289 return toURI(*File);
290 return toURIInternal(Path);
291 }
292
293 // Gets a canonical include (URI of the header or <header> or "header") for
294 // header of \p FID (which should usually be the *expansion* file).
295 // This does not account for any per-symbol overrides!
296 // Returns "" if includes should not be inserted for this file.
297 llvm::StringRef getIncludeHeader(FileID FID) {
298 auto R = CacheFIDToInclude.try_emplace(FID);
299 if (R.second)
300 R.first->second = getIncludeHeaderUncached(FID);
301 return R.first->second;
302 }
303
304 // If a file is mapped by canonical headers, use that mapping, regardless
305 // of whether it's an otherwise-good header (header guards etc).
306 llvm::StringRef mapCanonical(llvm::StringRef HeaderPath) {
307 if (!PP)
308 return "";
309 // Populate the system header mapping as late as possible to
310 // ensure the preprocessor has been set already.
311 CanonicalIncludes SysHeaderMapping;
312 SysHeaderMapping.addSystemHeadersMapping(PP->getLangOpts());
313 auto Canonical = SysHeaderMapping.mapHeader(HeaderPath);
314 if (Canonical.empty())
315 return "";
316 // If we had a mapping, always use it.
317 assert(Canonical.starts_with("<") || Canonical.starts_with("\""));
318 return Canonical;
319 }
320
321private:
322 // This takes care of making paths absolute and path->URI caching, but no
323 // FileManager-based canonicalization.
324 const std::string &toURIInternal(llvm::StringRef Path) {
325 auto R = CachePathToURI.try_emplace(Path);
326 if (R.second) {
327 llvm::SmallString<256> AbsPath = Path;
328 if (!llvm::sys::path::is_absolute(AbsPath) && !FallbackDir.empty())
329 llvm::sys::path::make_absolute(FallbackDir, AbsPath);
330 assert(llvm::sys::path::is_absolute(AbsPath) &&
331 "If the VFS can't make paths absolute, a FallbackDir must be "
332 "provided");
333 llvm::sys::path::remove_dots(AbsPath, /*remove_dot_dot=*/true);
334 R.first->second = URI::create(AbsPath).toString();
335 }
336 return R.first->second;
337 }
338
339 struct FrameworkHeaderPath {
340 // Path to the frameworks directory containing the .framework directory.
341 llvm::StringRef FrameworkParentDir;
342 // Name of the framework.
343 llvm::StringRef FrameworkName;
344 // Subpath relative to the Headers or PrivateHeaders dir, e.g. NSObject.h
345 // Note: This is NOT relative to the `HeadersParentDir`.
346 llvm::StringRef HeaderSubpath;
347 // Whether this header is under the PrivateHeaders dir
348 bool IsPrivateHeader;
349 };
350
351 std::optional<FrameworkHeaderPath>
352 splitFrameworkHeaderPath(llvm::StringRef Path) {
353 using namespace llvm::sys;
354 path::reverse_iterator I = path::rbegin(Path);
355 path::reverse_iterator Prev = I;
356 path::reverse_iterator E = path::rend(Path);
357 FrameworkHeaderPath HeaderPath;
358 while (I != E) {
359 if (*I == "Headers" || *I == "PrivateHeaders") {
360 HeaderPath.HeaderSubpath = Path.substr(Prev - E);
361 HeaderPath.IsPrivateHeader = *I == "PrivateHeaders";
362 if (++I == E)
363 break;
364 HeaderPath.FrameworkName = *I;
365 if (!HeaderPath.FrameworkName.consume_back(".framework"))
366 break;
367 HeaderPath.FrameworkParentDir = Path.substr(0, I - E);
368 return HeaderPath;
369 }
370 Prev = I;
371 ++I;
372 }
373 // Unexpected, must not be a framework header.
374 return std::nullopt;
375 }
376
377 // Frameworks typically have an umbrella header of the same name, e.g.
378 // <Foundation/Foundation.h> instead of <Foundation/NSObject.h> or
379 // <Foundation/Foundation_Private.h> instead of
380 // <Foundation/NSObject_Private.h> which should be used instead of directly
381 // importing the header.
382 std::optional<std::string>
383 getFrameworkUmbrellaSpelling(const HeaderSearch &HS,
384 FrameworkHeaderPath &HeaderPath) {
385 StringRef Framework = HeaderPath.FrameworkName;
386 auto Res = CacheFrameworkToUmbrellaHeaderSpelling.try_emplace(Framework);
387 auto *CachedSpelling = &Res.first->second;
388 if (!Res.second) {
389 return HeaderPath.IsPrivateHeader ? CachedSpelling->PrivateHeader
390 : CachedSpelling->PublicHeader;
391 }
392 SmallString<256> UmbrellaPath(HeaderPath.FrameworkParentDir);
393 llvm::sys::path::append(UmbrellaPath, Framework + ".framework", "Headers",
394 Framework + ".h");
395
396 if (HS.getFileMgr().getOptionalFileRef(UmbrellaPath))
397 CachedSpelling->PublicHeader = llvm::formatv("<{0}/{0}.h>", Framework);
398
399 UmbrellaPath = HeaderPath.FrameworkParentDir;
400 llvm::sys::path::append(UmbrellaPath, Framework + ".framework",
401 "PrivateHeaders", Framework + "_Private.h");
402
403 if (HS.getFileMgr().getOptionalFileRef(UmbrellaPath))
404 CachedSpelling->PrivateHeader =
405 llvm::formatv("<{0}/{0}_Private.h>", Framework);
406
407 return HeaderPath.IsPrivateHeader ? CachedSpelling->PrivateHeader
408 : CachedSpelling->PublicHeader;
409 }
410
411 // Compute the framework include spelling for `FE` which is in a framework
412 // named `Framework`, e.g. `NSObject.h` in framework `Foundation` would
413 // give <Foundation/Foundation.h> if the umbrella header exists, otherwise
414 // <Foundation/NSObject.h>.
415 std::optional<llvm::StringRef>
416 getFrameworkHeaderIncludeSpelling(FileEntryRef FE, HeaderSearch &HS) {
417 auto Res = CachePathToFrameworkSpelling.try_emplace(FE.getName());
418 auto *CachedHeaderSpelling = &Res.first->second;
419 if (!Res.second)
420 return llvm::StringRef(*CachedHeaderSpelling);
421
422 auto HeaderPath = splitFrameworkHeaderPath(FE.getName());
423 if (!HeaderPath) {
424 // Unexpected: must not be a proper framework header, don't cache the
425 // failure.
426 CachePathToFrameworkSpelling.erase(Res.first);
427 return std::nullopt;
428 }
429 if (auto UmbrellaSpelling =
430 getFrameworkUmbrellaSpelling(HS, *HeaderPath)) {
431 *CachedHeaderSpelling = *UmbrellaSpelling;
432 return llvm::StringRef(*CachedHeaderSpelling);
433 }
434
435 *CachedHeaderSpelling =
436 llvm::formatv("<{0}/{1}>", HeaderPath->FrameworkName,
437 HeaderPath->HeaderSubpath)
438 .str();
439 return llvm::StringRef(*CachedHeaderSpelling);
440 }
441
442 llvm::StringRef getIncludeHeaderUncached(FileID FID) {
443 const auto FE = SM.getFileEntryRefForID(FID);
444 if (!FE || FE->getName().empty())
445 return "";
446
447 if (auto Verbatim = PI->getPublic(*FE); !Verbatim.empty())
448 return Verbatim;
449
450 llvm::StringRef Filename = FE->getName();
451 if (auto Canonical = mapCanonical(Filename); !Canonical.empty())
452 return Canonical;
453
454 // Framework headers are spelled as <FrameworkName/Foo.h>, not
455 // "path/FrameworkName.framework/Headers/Foo.h".
456 auto &HS = PP->getHeaderSearchInfo();
457 if (auto Spelling = getFrameworkHeaderIncludeSpelling(*FE, HS))
458 return *Spelling;
459
460 if (!tooling::isSelfContainedHeader(*FE, PP->getSourceManager(),
461 PP->getHeaderSearchInfo())) {
462 // A .inc or .def file is often included into a real header to define
463 // symbols (e.g. LLVM tablegen files).
464 if (Filename.ends_with(".inc") || Filename.ends_with(".def"))
465 // Don't use cache reentrantly due to iterator invalidation.
466 return getIncludeHeaderUncached(SM.getFileID(SM.getIncludeLoc(FID)));
467 // Conservatively refuse to insert #includes to files without guards.
468 return "";
469 }
470 // Standard case: just insert the file itself.
471 return toURI(*FE);
472 }
473};
474
475// Return the symbol location of the token at \p TokLoc.
476std::optional<SymbolLocation>
477SymbolCollector::getTokenLocation(SourceLocation TokLoc) {
478 const auto &SM = ASTCtx->getSourceManager();
479 const auto FE = SM.getFileEntryRefForID(SM.getFileID(TokLoc));
480 if (!FE)
481 return std::nullopt;
482
483 SymbolLocation Result;
484 Result.FileURI = HeaderFileURIs->toURI(*FE).c_str();
485 auto Range = getTokenRange(TokLoc, SM, ASTCtx->getLangOpts());
486 Result.Start = Range.first;
487 Result.End = Range.second;
488
489 return Result;
490}
491
494
495void SymbolCollector::initialize(ASTContext &Ctx) {
496 ASTCtx = &Ctx;
497 HeaderFileURIs = std::make_unique<HeaderFileURICache>(
498 this->PP, ASTCtx->getSourceManager(), Opts);
499 CompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
500 CompletionTUInfo =
501 std::make_unique<CodeCompletionTUInfo>(CompletionAllocator);
502}
503
505 const ASTContext &ASTCtx,
506 const Options &Opts,
507 bool IsMainFileOnly) {
508 // Skip anonymous declarations, e.g (anonymous enum/class/struct).
509 if (ND.getDeclName().isEmpty())
510 return false;
511
512 // Skip main-file symbols if we are not collecting them.
513 if (IsMainFileOnly && !Opts.CollectMainFileSymbols)
514 return false;
515
516 // Skip symbols in anonymous namespaces in header files.
517 if (!IsMainFileOnly && ND.isInAnonymousNamespace())
518 return false;
519
520 // For function local symbols, index only classes and its member functions.
521 if (index::isFunctionLocalSymbol(&ND))
522 return isa<RecordDecl>(ND) ||
523 (ND.isCXXInstanceMember() && ND.isFunctionOrFunctionTemplate());
524
525 // We want most things but not "local" symbols such as symbols inside
526 // FunctionDecl, BlockDecl, ObjCMethodDecl and OMPDeclareReductionDecl.
527 // FIXME: Need a matcher for ExportDecl in order to include symbols declared
528 // within an export.
529 const auto *DeclCtx = ND.getDeclContext();
530 switch (DeclCtx->getDeclKind()) {
531 case Decl::TranslationUnit:
532 case Decl::Namespace:
533 case Decl::LinkageSpec:
534 case Decl::Enum:
535 case Decl::ObjCProtocol:
536 case Decl::ObjCInterface:
537 case Decl::ObjCCategory:
538 case Decl::ObjCCategoryImpl:
539 case Decl::ObjCImplementation:
540 break;
541 default:
542 // Record has a few derivations (e.g. CXXRecord, Class specialization), it's
543 // easier to cast.
544 if (!isa<RecordDecl>(DeclCtx))
545 return false;
546 }
547
548 // Avoid indexing internal symbols in protobuf generated headers.
549 if (isPrivateProtoDecl(ND))
550 return false;
551
552 // System headers that end with `intrin.h` likely contain useful symbols.
553 if (!Opts.CollectReserved &&
554 (hasReservedName(ND) || hasReservedScope(*ND.getDeclContext())) &&
555 ASTCtx.getSourceManager().isInSystemHeader(ND.getLocation()) &&
556 !ASTCtx.getSourceManager()
557 .getFilename(ND.getLocation())
558 .ends_with("intrin.h"))
559 return false;
560
561 return true;
562}
563
564const Decl *
566 const SymbolCollector::Options &Opts) {
567 while (Enclosing) {
568 const auto *ND = dyn_cast<NamedDecl>(Enclosing);
569 if (ND && shouldCollectSymbol(*ND, ND->getASTContext(), Opts, true)) {
570 break;
571 }
572 Enclosing = dyn_cast_or_null<Decl>(Enclosing->getDeclContext());
573 }
574 return Enclosing;
575}
576
577ArrayRef<const CXXConstructorDecl *>
578SymbolCollector::findIndirectConstructors(const Decl *D) {
579 const auto *FD = llvm::dyn_cast<clang::FunctionDecl>(D);
580 if (!FD)
581 return {};
583}
584
585// Always return true to continue indexing.
587 const Decl *D, index::SymbolRoleSet Roles,
588 llvm::ArrayRef<index::SymbolRelation> Relations, SourceLocation Loc,
589 index::IndexDataConsumer::ASTNodeInfo ASTNode) {
590 assert(ASTCtx && PP && HeaderFileURIs);
591 assert(CompletionAllocator && CompletionTUInfo);
592 assert(ASTNode.OrigD);
593 // Indexing API puts canonical decl into D, which might not have a valid
594 // source location for implicit/built-in decls. Fallback to original decl in
595 // such cases.
596 if (D->getLocation().isInvalid())
597 D = ASTNode.OrigD;
598 // If OrigD is an declaration associated with a friend declaration and it's
599 // not a definition, skip it. Note that OrigD is the occurrence that the
600 // collector is currently visiting.
601 if ((ASTNode.OrigD->getFriendObjectKind() !=
602 Decl::FriendObjectKind::FOK_None) &&
603 !(Roles & static_cast<unsigned>(index::SymbolRole::Definition)))
604 return true;
605 // A declaration created for a friend declaration should not be used as the
606 // canonical declaration in the index. Use OrigD instead, unless we've already
607 // picked a replacement for D
608 if (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None)
609 D = CanonicalDecls.try_emplace(D, ASTNode.OrigD).first->second;
610 // Flag to mark that D should be considered canonical meaning its declaration
611 // will override any previous declaration for the Symbol.
612 bool DeclIsCanonical = false;
613 // Avoid treating ObjCImplementationDecl as a canonical declaration if it has
614 // a corresponding non-implicit and non-forward declared ObjcInterfaceDecl.
615 if (const auto *IID = dyn_cast<ObjCImplementationDecl>(D)) {
616 DeclIsCanonical = true;
617 if (const auto *CID = IID->getClassInterface())
618 if (const auto *DD = CID->getDefinition())
619 if (!DD->isImplicitInterfaceDecl())
620 D = DD;
621 }
622 // Avoid treating ObjCCategoryImplDecl as a canonical declaration in favor of
623 // its ObjCCategoryDecl if it has one.
624 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(D)) {
625 DeclIsCanonical = true;
626 if (const auto *CD = CID->getCategoryDecl())
627 D = CD;
628 }
629 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
630 if (!ND)
631 return true;
632
633 auto ID = getSymbolIDCached(ND);
634 if (!ID)
635 return true;
636
637 // Mark D as referenced if this is a reference coming from the main file.
638 // D may not be an interesting symbol, but it's cheaper to check at the end.
639 auto &SM = ASTCtx->getSourceManager();
640 if (Opts.CountReferences &&
641 (Roles & static_cast<unsigned>(index::SymbolRole::Reference)) &&
642 SM.getFileID(SM.getSpellingLoc(Loc)) == SM.getMainFileID())
643 ReferencedSymbols.insert(ID);
644
645 // ND is the canonical (i.e. first) declaration. If it's in the main file
646 // (which is not a header), then no public declaration was visible, so assume
647 // it's main-file only.
648 auto CheckIsMainFileOnly = [&](const NamedDecl *Decl) {
649 return SM.isWrittenInMainFile(SM.getExpansionLoc(Decl->getBeginLoc())) &&
650 !isHeaderFile(SM.getFileEntryRefForID(SM.getMainFileID())->getName(),
651 ASTCtx->getLangOpts());
652 };
653 bool IsMainFileOnly = CheckIsMainFileOnly(ND);
654 // In C, printf is a redecl of an implicit builtin! So check OrigD instead.
655 if (ASTNode.OrigD->isImplicit() ||
656 !shouldCollectSymbol(*ND, *ASTCtx, Opts, IsMainFileOnly))
657 return true;
658
659 // Note: we need to process relations for all decl occurrences, including
660 // refs, because the indexing code only populates relations for specific
661 // occurrences. For example, RelationBaseOf is only populated for the
662 // occurrence inside the base-specifier.
663 processRelations(*ND, ID, Relations);
664
665 bool CollectRef = static_cast<bool>(Opts.RefFilter & toRefKind(Roles));
666 // Unlike other fields, e.g. Symbols (which use spelling locations), we use
667 // file locations for references (as it aligns the behavior of clangd's
668 // AST-based xref).
669 // FIXME: we should try to use the file locations for other fields.
670 if (CollectRef &&
671 (!IsMainFileOnly || Opts.CollectMainFileRefs ||
672 ND->isExternallyVisible()) &&
673 !isa<NamespaceDecl>(ND)) {
674 auto FileLoc = SM.getFileLoc(Loc);
675 auto FID = SM.getFileID(FileLoc);
676 if (Opts.RefsInHeaders || FID == SM.getMainFileID()) {
677 auto *Container = getRefContainer(ASTNode.Parent, Opts);
678 addRef(ID, SymbolRef{FileLoc, FID, Roles, index::getSymbolInfo(ND).Kind,
679 Container, isSpelled(FileLoc, *ND)});
680 // Also collect indirect constructor calls like `make_unique`
681 for (auto *Constructor : findIndirectConstructors(ASTNode.OrigD)) {
682 if (!shouldCollectSymbol(*Constructor, *ASTCtx, Opts,
683 CheckIsMainFileOnly(Constructor)))
684 continue;
685 if (auto ConstructorID = getSymbolIDCached(Constructor))
686 addRef(ConstructorID,
687 SymbolRef{FileLoc, FID, Roles,
688 index::getSymbolInfo(Constructor).Kind, Container,
689 false});
690 }
691 }
692 }
693 // Don't continue indexing if this is a mere reference.
694 if (!(Roles & (static_cast<unsigned>(index::SymbolRole::Declaration) |
695 static_cast<unsigned>(index::SymbolRole::Definition))))
696 return true;
697
698 // FIXME: ObjCPropertyDecl are not properly indexed here:
699 // - ObjCPropertyDecl may have an OrigD of ObjCPropertyImplDecl, which is
700 // not a NamedDecl.
701 auto *OriginalDecl = dyn_cast<NamedDecl>(ASTNode.OrigD);
702 if (!OriginalDecl)
703 return true;
704
705 const Symbol *BasicSymbol = Symbols.find(ID);
706 bool SkipDocCheckInDef = false;
707 if (isPreferredDeclaration(*OriginalDecl, Roles)) {
708 // If OriginalDecl is preferred, replace/create the existing canonical
709 // declaration (e.g. a class forward declaration). There should be at most
710 // one duplicate as we expect to see only one preferred declaration per
711 // TU, because in practice they are definitions.
712 BasicSymbol = addDeclaration(*OriginalDecl, std::move(ID), IsMainFileOnly);
713 SkipDocCheckInDef = true;
714 } else if (!BasicSymbol || DeclIsCanonical) {
715 BasicSymbol = addDeclaration(*ND, std::move(ID), IsMainFileOnly);
716 SkipDocCheckInDef = true;
717 }
718
719 if (Roles & static_cast<unsigned>(index::SymbolRole::Definition))
720 addDefinition(*OriginalDecl, *BasicSymbol, SkipDocCheckInDef);
721
722 return true;
723}
724
725void SymbolCollector::handleMacros(const MainFileMacros &MacroRefsToIndex) {
726 assert(HeaderFileURIs && PP);
727 const auto &SM = PP->getSourceManager();
728 const auto MainFileEntryRef = SM.getFileEntryRefForID(SM.getMainFileID());
729 assert(MainFileEntryRef);
730
731 const std::string &MainFileURI = HeaderFileURIs->toURI(*MainFileEntryRef);
732 // Add macro references.
733 for (const auto &IDToRefs : MacroRefsToIndex.MacroRefs) {
734 for (const auto &MacroRef : IDToRefs.second) {
735 const auto &SR = MacroRef.toSourceRange(SM);
736 auto Range = halfOpenToRange(SM, SR);
737 bool IsDefinition = MacroRef.IsDefinition;
738 Ref R;
743 R.Location.FileURI = MainFileURI.c_str();
744 R.Kind = IsDefinition ? RefKind::Definition : RefKind::Reference;
745 Refs.insert(IDToRefs.first, R);
746 if (IsDefinition) {
747 Symbol S;
748 S.ID = IDToRefs.first;
749 S.Name = toSourceCode(SM, SR.getAsRange());
750 S.SymInfo.Kind = index::SymbolKind::Macro;
751 S.SymInfo.SubKind = index::SymbolSubKind::None;
752 S.SymInfo.Properties = index::SymbolPropertySet();
753 S.SymInfo.Lang = index::SymbolLanguage::C;
754 S.Origin = Opts.Origin;
756 // Make the macro visible for code completion if main file is an
757 // include-able header.
758 if (!HeaderFileURIs->getIncludeHeader(SM.getMainFileID()).empty()) {
761 }
762 Symbols.insert(S);
763 }
764 }
765 }
766}
767
768bool SymbolCollector::handleMacroOccurrence(const IdentifierInfo *Name,
769 const MacroInfo *MI,
770 index::SymbolRoleSet Roles,
771 SourceLocation Loc) {
772 assert(PP);
773 // Builtin macros don't have useful locations and aren't needed in completion.
774 if (MI->isBuiltinMacro())
775 return true;
776
777 const auto &SM = PP->getSourceManager();
778 auto DefLoc = MI->getDefinitionLoc();
779 // Also avoid storing macros that aren't defined in any file, i.e. predefined
780 // macros like __DBL_MIN__ and those defined on the command line.
781 if (SM.isWrittenInBuiltinFile(DefLoc) ||
782 SM.isWrittenInCommandLineFile(DefLoc) ||
783 Name->getName() == "__GCC_HAVE_DWARF2_CFI_ASM")
784 return true;
785
786 auto ID = getSymbolIDCached(Name->getName(), MI, SM);
787 if (!ID)
788 return true;
789
790 auto SpellingLoc = SM.getSpellingLoc(Loc);
791 bool IsMainFileOnly =
792 SM.isInMainFile(SM.getExpansionLoc(DefLoc)) &&
793 !isHeaderFile(SM.getFileEntryRefForID(SM.getMainFileID())->getName(),
794 ASTCtx->getLangOpts());
795 // Do not store references to main-file macros.
796 if ((static_cast<unsigned>(Opts.RefFilter) & Roles) && !IsMainFileOnly &&
797 (Opts.RefsInHeaders || SM.getFileID(SpellingLoc) == SM.getMainFileID())) {
798 // FIXME: Populate container information for macro references.
799 // FIXME: All MacroRefs are marked as Spelled now, but this should be
800 // checked.
801 addRef(ID,
802 SymbolRef{Loc, SM.getFileID(Loc), Roles, index::SymbolKind::Macro,
803 /*Container=*/nullptr,
804 /*Spelled=*/true});
805 }
806
807 // Collect symbols.
808 if (!Opts.CollectMacro)
809 return true;
810
811 // Skip main-file macros if we are not collecting them.
812 if (IsMainFileOnly && !Opts.CollectMainFileSymbols)
813 return false;
814
815 // Mark the macro as referenced if this is a reference coming from the main
816 // file. The macro may not be an interesting symbol, but it's cheaper to check
817 // at the end.
818 if (Opts.CountReferences &&
819 (Roles & static_cast<unsigned>(index::SymbolRole::Reference)) &&
820 SM.getFileID(SpellingLoc) == SM.getMainFileID())
821 ReferencedSymbols.insert(ID);
822
823 // Don't continue indexing if this is a mere reference.
824 // FIXME: remove macro with ID if it is undefined.
825 if (!(Roles & static_cast<unsigned>(index::SymbolRole::Declaration) ||
826 Roles & static_cast<unsigned>(index::SymbolRole::Definition)))
827 return true;
828
829 // Only collect one instance in case there are multiple.
830 if (Symbols.find(ID) != nullptr)
831 return true;
832
833 Symbol S;
834 S.ID = std::move(ID);
835 S.Name = Name->getName();
836 if (!IsMainFileOnly) {
839 }
840 S.SymInfo = index::getSymbolInfoForMacro(*MI);
841 S.Origin = Opts.Origin;
842 // FIXME: use the result to filter out symbols.
843 shouldIndexFile(SM.getFileID(Loc));
844 if (auto DeclLoc = getTokenLocation(DefLoc))
845 S.CanonicalDeclaration = *DeclLoc;
846
847 CodeCompletionResult SymbolCompletion(Name);
848 const auto *CCS = SymbolCompletion.CreateCodeCompletionStringForMacro(
849 *PP, *CompletionAllocator, *CompletionTUInfo);
850 std::string Signature;
851 std::string SnippetSuffix;
852 getSignature(*CCS, &Signature, &SnippetSuffix, SymbolCompletion.Kind,
853 SymbolCompletion.CursorKind);
854 S.Signature = Signature;
855 S.CompletionSnippetSuffix = SnippetSuffix;
856
857 IndexedMacros.insert(Name);
858
859 setIncludeLocation(S, DefLoc, include_cleaner::Macro{Name, DefLoc});
860 Symbols.insert(S);
861 return true;
862}
863
864void SymbolCollector::processRelations(
865 const NamedDecl &ND, const SymbolID &ID,
866 ArrayRef<index::SymbolRelation> Relations) {
867 for (const auto &R : Relations) {
868 auto RKind = indexableRelation(R);
869 if (!RKind)
870 continue;
871 const Decl *Object = R.RelatedSymbol;
872
873 auto ObjectID = getSymbolIDCached(Object);
874 if (!ObjectID)
875 continue;
876
877 // Record the relation.
878 // TODO: There may be cases where the object decl is not indexed for some
879 // reason. Those cases should probably be removed in due course, but for
880 // now there are two possible ways to handle it:
881 // (A) Avoid storing the relation in such cases.
882 // (B) Store it anyways. Clients will likely lookup() the SymbolID
883 // in the index and find nothing, but that's a situation they
884 // probably need to handle for other reasons anyways.
885 // We currently do (B) because it's simpler.
886 if (*RKind == RelationKind::BaseOf)
887 this->Relations.insert({ID, *RKind, ObjectID});
888 else if (*RKind == RelationKind::OverriddenBy)
889 this->Relations.insert({ObjectID, *RKind, ID});
890 }
891}
892
893void SymbolCollector::setIncludeLocation(const Symbol &S, SourceLocation DefLoc,
894 const include_cleaner::Symbol &Sym) {
895 const auto &SM = PP->getSourceManager();
896 if (!Opts.CollectIncludePath ||
897 shouldCollectIncludePath(S.SymInfo.Kind) == Symbol::Invalid)
898 return;
899
900 // Use the expansion location to get the #include header since this is
901 // where the symbol is exposed.
902 if (FileID FID = SM.getDecomposedExpansionLoc(DefLoc).first; FID.isValid())
903 IncludeFiles[S.ID] = FID;
904
905 // We update providers for a symbol with each occurence, as SymbolCollector
906 // might run while parsing, rather than at the end of a translation unit.
907 // Hence we see more and more redecls over time.
908 SymbolProviders[S.ID] =
909 include_cleaner::headersForSymbol(Sym, *PP, Opts.PragmaIncludes);
910}
911
912llvm::StringRef getStdHeader(const Symbol *S, const LangOptions &LangOpts) {
913 tooling::stdlib::Lang Lang = tooling::stdlib::Lang::CXX;
914 if (LangOpts.C11)
915 Lang = tooling::stdlib::Lang::C;
916 else if(!LangOpts.CPlusPlus)
917 return "";
918
919 if (S->Scope == "std::" && S->Name == "move") {
920 if (!S->Signature.contains(','))
921 return "<utility>";
922 return "<algorithm>";
923 }
924
925 if (auto StdSym = tooling::stdlib::Symbol::named(S->Scope, S->Name, Lang))
926 if (auto Header = StdSym->header())
927 return Header->name();
928 return "";
929}
930
932 // At the end of the TU, add 1 to the refcount of all referenced symbols.
933 for (const auto &ID : ReferencedSymbols) {
934 if (const auto *S = Symbols.find(ID)) {
935 // SymbolSlab::Builder returns const symbols because strings are interned
936 // and modifying returned symbols without inserting again wouldn't go
937 // well. const_cast is safe here as we're modifying a data owned by the
938 // Symbol. This reduces time spent in SymbolCollector by ~1%.
939 ++const_cast<Symbol *>(S)->References;
940 }
941 }
942 if (Opts.CollectMacro) {
943 assert(PP);
944 // First, drop header guards. We can't identify these until EOF.
945 for (const IdentifierInfo *II : IndexedMacros) {
946 if (const auto *MI = PP->getMacroDefinition(II).getMacroInfo())
947 if (auto ID =
948 getSymbolIDCached(II->getName(), MI, PP->getSourceManager()))
949 if (MI->isUsedForHeaderGuard())
950 Symbols.erase(ID);
951 }
952 }
953 llvm::DenseMap<FileID, bool> FileToContainsImportsOrObjC;
954 llvm::DenseMap<include_cleaner::Header, std::string> HeaderSpelling;
955 // Fill in IncludeHeaders.
956 // We delay this until end of TU so header guards are all resolved.
957 for (const auto &[SID, Providers] : SymbolProviders) {
958 const Symbol *S = Symbols.find(SID);
959 if (!S)
960 continue;
961
962 FileID FID = IncludeFiles.lookup(SID);
963 // Determine if the FID is #include'd or #import'ed.
965 auto CollectDirectives = shouldCollectIncludePath(S->SymInfo.Kind);
966 if ((CollectDirectives & Symbol::Include) != 0)
967 Directives |= Symbol::Include;
968 // Only allow #import for symbols from ObjC-like files.
969 if ((CollectDirectives & Symbol::Import) != 0 && FID.isValid()) {
970 auto [It, Inserted] = FileToContainsImportsOrObjC.try_emplace(FID);
971 if (Inserted)
972 It->second = FilesWithObjCConstructs.contains(FID) ||
973 tooling::codeContainsImports(
974 ASTCtx->getSourceManager().getBufferData(FID));
975 if (It->second)
976 Directives |= Symbol::Import;
977 }
978
979 if (Directives == Symbol::Invalid)
980 continue;
981
982 // Use the include location-based logic for Objective-C symbols.
983 if (Directives & Symbol::Import) {
984 llvm::StringRef IncludeHeader = getStdHeader(S, ASTCtx->getLangOpts());
985 if (IncludeHeader.empty())
986 IncludeHeader = HeaderFileURIs->getIncludeHeader(FID);
987
988 if (!IncludeHeader.empty()) {
989 auto NewSym = *S;
990 NewSym.IncludeHeaders.push_back({IncludeHeader, 1, Directives});
991 Symbols.insert(NewSym);
992 }
993 // FIXME: use providers from include-cleaner library once it's polished
994 // for Objective-C.
995 continue;
996 }
997
998 // For #include's, use the providers computed by the include-cleaner
999 // library.
1000 assert(Directives == Symbol::Include);
1001 // Ignore providers that are not self-contained, this is especially
1002 // important for symbols defined in the main-file. We want to prefer the
1003 // header, if possible.
1004 // TODO: Limit this to specifically ignore main file, when we're indexing a
1005 // non-header file?
1006 auto SelfContainedProvider =
1007 [this](llvm::ArrayRef<include_cleaner::Header> Providers)
1008 -> std::optional<include_cleaner::Header> {
1009 for (const auto &H : Providers) {
1010 if (H.kind() != include_cleaner::Header::Physical)
1011 return H;
1012 if (tooling::isSelfContainedHeader(H.physical(), PP->getSourceManager(),
1013 PP->getHeaderSearchInfo()))
1014 return H;
1015 }
1016 return std::nullopt;
1017 };
1018 const auto OptionalProvider = SelfContainedProvider(Providers);
1019 if (!OptionalProvider)
1020 continue;
1021 const auto &H = *OptionalProvider;
1022 const auto [SpellingIt, Inserted] = HeaderSpelling.try_emplace(H);
1023 if (Inserted) {
1024 auto &SM = ASTCtx->getSourceManager();
1025 if (H.kind() == include_cleaner::Header::Kind::Physical) {
1026 // FIXME: Get rid of this once include-cleaner has support for system
1027 // headers.
1028 if (auto Canonical =
1029 HeaderFileURIs->mapCanonical(H.physical().getName());
1030 !Canonical.empty())
1031 SpellingIt->second = Canonical;
1032 // For physical files, prefer URIs as spellings might change
1033 // depending on the translation unit.
1034 else if (tooling::isSelfContainedHeader(H.physical(), SM,
1035 PP->getHeaderSearchInfo()))
1036 SpellingIt->second =
1037 HeaderFileURIs->toURI(H.physical());
1038 } else {
1039 SpellingIt->second = include_cleaner::spellHeader(
1040 {H, PP->getHeaderSearchInfo(),
1041 SM.getFileEntryForID(SM.getMainFileID())});
1042 }
1043 }
1044
1045 if (!SpellingIt->second.empty()) {
1046 auto NewSym = *S;
1047 NewSym.IncludeHeaders.push_back({SpellingIt->second, 1, Directives});
1048 Symbols.insert(NewSym);
1049 }
1050 }
1051
1052 ReferencedSymbols.clear();
1053 IncludeFiles.clear();
1054 SymbolProviders.clear();
1055 FilesWithObjCConstructs.clear();
1056}
1057
1058const Symbol *SymbolCollector::addDeclaration(const NamedDecl &ND, SymbolID ID,
1059 bool IsMainFileOnly) {
1060 auto &Ctx = ND.getASTContext();
1061 auto &SM = Ctx.getSourceManager();
1062
1063 Symbol S;
1064 S.ID = std::move(ID);
1065 std::string QName = printQualifiedName(ND);
1066 // FIXME: this returns foo:bar: for objective-C methods, we prefer only foo:
1067 // for consistency with CodeCompletionString and a clean name/signature split.
1068 std::tie(S.Scope, S.Name) = splitQualifiedName(QName);
1069 std::string TemplateSpecializationArgs = printTemplateSpecializationArgs(ND);
1070 S.TemplateSpecializationArgs = TemplateSpecializationArgs;
1071
1072 // We collect main-file symbols, but do not use them for code completion.
1073 if (!IsMainFileOnly && isIndexedForCodeCompletion(ND, Ctx))
1075 if (isImplementationDetail(&ND))
1077 if (!IsMainFileOnly)
1079 S.SymInfo = index::getSymbolInfo(&ND);
1080 auto Loc = nameLocation(ND, SM);
1081 assert(Loc.isValid() && "Invalid source location for NamedDecl");
1082 // FIXME: use the result to filter out symbols.
1083 auto FID = SM.getFileID(Loc);
1084 shouldIndexFile(FID);
1085 if (auto DeclLoc = getTokenLocation(Loc))
1086 S.CanonicalDeclaration = *DeclLoc;
1087
1088 S.Origin = Opts.Origin;
1089 if (ND.getAvailability() == AR_Deprecated)
1091
1092 S.Tags = computeSymbolTags(ND);
1093
1094 // Add completion info.
1095 // FIXME: we may want to choose a different redecl, or combine from several.
1096 assert(ASTCtx && PP && "ASTContext and Preprocessor must be set.");
1097 // We use the primary template, as clang does during code completion.
1098 CodeCompletionResult SymbolCompletion(&getTemplateOrThis(ND), 0);
1099 const auto *CCS = SymbolCompletion.CreateCodeCompletionString(
1100 *ASTCtx, *PP, CodeCompletionContext::CCC_Symbol, *CompletionAllocator,
1101 *CompletionTUInfo,
1102 /*IncludeBriefComments*/ false);
1103 std::string DocComment;
1104 std::string Documentation;
1105 bool AlreadyHasDoc = S.Flags & Symbol::HasDocComment;
1106 if (!AlreadyHasDoc) {
1107 DocComment = getDocComment(Ctx, SymbolCompletion,
1108 /*CommentsFromHeaders=*/true);
1109 Documentation = formatDocumentation(*CCS, DocComment);
1110 }
1111 const auto UpdateDoc = [&] {
1112 if (!AlreadyHasDoc) {
1113 if (!DocComment.empty())
1115 S.Documentation = Documentation;
1116 }
1117 };
1119 if (Opts.StoreAllDocumentation)
1120 UpdateDoc();
1121 Symbols.insert(S);
1122 return Symbols.find(S.ID);
1123 }
1124 UpdateDoc();
1125 std::string Signature;
1126 std::string SnippetSuffix;
1127 getSignature(*CCS, &Signature, &SnippetSuffix, SymbolCompletion.Kind,
1128 SymbolCompletion.CursorKind);
1129 S.Signature = Signature;
1130 S.CompletionSnippetSuffix = SnippetSuffix;
1131 std::string ReturnType = getReturnType(*CCS);
1132 S.ReturnType = ReturnType;
1133
1134 std::optional<OpaqueType> TypeStorage;
1136 TypeStorage = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion);
1137 if (TypeStorage)
1138 S.Type = TypeStorage->raw();
1139 }
1140
1141 Symbols.insert(S);
1142 setIncludeLocation(S, ND.getLocation(), include_cleaner::Symbol{ND});
1143 if (S.SymInfo.Lang == index::SymbolLanguage::ObjC)
1144 FilesWithObjCConstructs.insert(FID);
1145 return Symbols.find(S.ID);
1146}
1147
1148void SymbolCollector::addDefinition(const NamedDecl &ND, const Symbol &DeclSym,
1149 bool SkipDocCheck) {
1150 if (DeclSym.Definition)
1151 return;
1152 const auto &SM = ND.getASTContext().getSourceManager();
1153 auto Loc = nameLocation(ND, SM);
1154 shouldIndexFile(SM.getFileID(Loc));
1155 auto DefLoc = getTokenLocation(Loc);
1156 // If we saw some forward declaration, we end up copying the symbol.
1157 // This is not ideal, but avoids duplicating the "is this a definition" check
1158 // in clang::index. We should only see one definition.
1159 if (!DefLoc)
1160 return;
1161 Symbol S = DeclSym;
1162 // FIXME: use the result to filter out symbols.
1163 S.Definition = *DefLoc;
1164
1165 std::string DocComment;
1166 std::string Documentation;
1167 if (!SkipDocCheck && !(S.Flags & Symbol::HasDocComment) &&
1168 (llvm::isa<FunctionDecl>(ND) || llvm::isa<CXXMethodDecl>(ND))) {
1169 CodeCompletionResult SymbolCompletion(&getTemplateOrThis(ND), 0);
1170 const auto *CCS = SymbolCompletion.CreateCodeCompletionString(
1171 *ASTCtx, *PP, CodeCompletionContext::CCC_Symbol, *CompletionAllocator,
1172 *CompletionTUInfo,
1173 /*IncludeBriefComments*/ false);
1174 DocComment = getDocComment(ND.getASTContext(), SymbolCompletion,
1175 /*CommentsFromHeaders=*/true);
1176 if (!S.Documentation.empty())
1177 Documentation = S.Documentation.str() + '\n' + DocComment;
1178 else
1179 Documentation = formatDocumentation(*CCS, DocComment);
1180 if (!DocComment.empty())
1181 S.Flags |= Symbol::HasDocComment;
1182 S.Documentation = Documentation;
1183 }
1184 S.Tags |= computeSymbolTags(ND);
1185 Symbols.insert(S);
1186}
1187
1189 if (!Opts.FileFilter)
1190 return true;
1191 auto I = FilesToIndexCache.try_emplace(FID);
1192 if (I.second)
1193 I.first->second = Opts.FileFilter(ASTCtx->getSourceManager(), FID);
1194 return I.first->second;
1195}
1196
1197static bool refIsCall(index::SymbolKind Kind) {
1198 using SK = index::SymbolKind;
1199 return Kind == SK::Function || Kind == SK::InstanceMethod ||
1200 Kind == SK::ClassMethod || Kind == SK::StaticMethod ||
1201 Kind == SK::Constructor || Kind == SK::Destructor ||
1202 Kind == SK::ConversionFunction;
1203}
1204
1205void SymbolCollector::addRef(SymbolID ID, const SymbolRef &SR) {
1206 const auto &SM = ASTCtx->getSourceManager();
1207 // FIXME: use the result to filter out references.
1208 shouldIndexFile(SR.FID);
1209 if (const auto FE = SM.getFileEntryRefForID(SR.FID)) {
1210 auto Range = getTokenRange(SR.Loc, SM, ASTCtx->getLangOpts());
1211 Ref R;
1212 R.Location.Start = Range.first;
1213 R.Location.End = Range.second;
1214 R.Location.FileURI = HeaderFileURIs->toURI(*FE).c_str();
1215 R.Kind = toRefKind(SR.Roles, SR.Spelled);
1216 if (refIsCall(SR.Kind)) {
1217 R.Kind |= RefKind::Call;
1218 }
1219 R.Container = getSymbolIDCached(SR.Container);
1220 Refs.insert(ID, R);
1221 }
1222}
1223
1224SymbolID SymbolCollector::getSymbolIDCached(const Decl *D) {
1225 auto It = DeclToIDCache.try_emplace(D);
1226 if (It.second)
1227 It.first->second = getSymbolID(D);
1228 return It.first->second;
1229}
1230
1231SymbolID SymbolCollector::getSymbolIDCached(const llvm::StringRef MacroName,
1232 const MacroInfo *MI,
1233 const SourceManager &SM) {
1234 auto It = MacroToIDCache.try_emplace(MI);
1235 if (It.second)
1236 It.first->second = getSymbolID(MacroName, MI, SM);
1237 return It.first->second;
1238}
1239} // namespace clangd
1240} // namespace clang
static GeneratorRegistry::Add< MDGenerator > MD(MDGenerator::Format, "Generator for Markdown output.")
Maps a definition location onto an include file, based on a set of filename rules.
void addSystemHeadersMapping(const LangOptions &Language)
Adds mapping for system headers and some special symbols (e.g.
llvm::StringRef mapHeader(llvm::StringRef HeaderPath) const
Returns the overridden verbatim spelling for files in Header that can be directly included (i....
static std::optional< OpaqueType > fromCompletionResult(ASTContext &Ctx, const CodeCompletionResult &R)
Create a type from a code completion result.
void insert(const SymbolID &ID, const Ref &S)
Adds a ref to the slab. Deep copy: Strings will be owned by the slab.
Definition Ref.cpp:36
llvm::StringRef mapCanonical(llvm::StringRef HeaderPath)
HeaderFileURICache(Preprocessor *&PP, const SourceManager &SM, const SymbolCollector::Options &Opts)
const std::string & toURI(const FileEntryRef FE)
const std::string & toURI(llvm::StringRef Path)
bool shouldIndexFile(FileID FID)
Returns true if we are interested in references and declarations from FID.
static bool shouldCollectSymbol(const NamedDecl &ND, const ASTContext &ASTCtx, const Options &Opts, bool IsMainFileSymbol)
Returns true is ND should be collected.
static const Decl * getRefContainer(const Decl *Enclosing, const SymbolCollector::Options &Opts)
bool handleDeclOccurrence(const Decl *D, index::SymbolRoleSet Roles, ArrayRef< index::SymbolRelation > Relations, SourceLocation Loc, index::IndexDataConsumer::ASTNodeInfo ASTNode) override
void handleMacros(const MainFileMacros &MacroRefsToIndex)
void initialize(ASTContext &Ctx) override
bool handleMacroOccurrence(const IdentifierInfo *Name, const MacroInfo *MI, index::SymbolRoleSet Roles, SourceLocation Loc) override
static llvm::Expected< URI > create(llvm::StringRef AbsolutePath, llvm::StringRef Scheme)
Creates a URI for a file in the given scheme.
Definition URI.cpp:208
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
Definition AST.cpp:44
std::string printTemplateSpecializationArgs(const NamedDecl &ND)
Prints template arguments of a decl as written in the source code, including enclosing '<' and '>',...
Definition AST.cpp:287
std::pair< StringRef, StringRef > splitQualifiedName(StringRef QName)
SymbolID getSymbolID(const Decl *D)
Gets the symbol ID for a declaration. Returned SymbolID might be null.
Definition AST.cpp:354
std::string formatDocumentation(const CodeCompletionString &CCS, llvm::StringRef DocComment)
Assembles formatted documentation for a completion result.
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R)
static bool refIsCall(index::SymbolKind Kind)
bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM)
Returns true iff Loc is inside the main file.
SourceLocation nameLocation(const clang::Decl &D, const SourceManager &SM)
Find the source location of the identifier for D.
Definition AST.cpp:196
std::string getReturnType(const CodeCompletionString &CCS)
Gets detail to be used as the detail field in an LSP completion item.
Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc)
Turn a SourceLocation into a [line, column] pair.
std::optional< std::string > getCanonicalPath(const FileEntryRef F, FileManager &FileMgr)
Get the canonical path of F.
bool hasReservedName(const Decl &D)
Returns true if this is a NamedDecl with a reserved name.
Definition AST.cpp:444
llvm::StringRef toSourceCode(const SourceManager &SM, SourceRange R)
Returns the source code covered by the source range.
RefKind
Describes the kind of a cross-reference.
Definition Ref.h:28
void getSignature(const CodeCompletionString &CCS, std::string *Signature, std::string *Snippet, CodeCompletionResult::ResultKind ResultKind, CXCursorKind CursorKind, bool IncludeFunctionArguments, std::string *RequiredQualifiers)
Formats the signature for an item, as a display string and snippet.
ArrayRef< const CXXConstructorDecl * > getForwardedConstructors(const FunctionDecl *FD, ForwardingToConstructorCache &Cache)
Returns the constructors that FD forwards to, if FD is a template instantiation of a likely forwardin...
Definition AST.cpp:1119
bool isImplementationDetail(const Decl *D)
Returns true if the declaration is considered implementation detail based on heuristics.
Definition AST.cpp:191
std::string Path
A typedef to represent a file path.
Definition Path.h:26
llvm::DenseMap< const FunctionDecl *, SmallVector< const CXXConstructorDecl *, 1 > > ForwardingToConstructorCache
Cache mapping forwarding function instantiations (e.g.
Definition AST.h:269
bool hasReservedScope(const DeclContext &DC)
Returns true if this scope would be written with a reserved name.
Definition AST.cpp:451
std::string printQualifiedName(const NamedDecl &ND)
Returns the qualified name of ND.
Definition AST.cpp:206
bool isProtoFile(SourceLocation Loc, const SourceManager &SM)
Returns true if the given location is in a generated protobuf file.
std::string getDocComment(const ASTContext &Ctx, const CodeCompletionResult &Result, bool CommentsFromHeaders)
Gets a minimally formatted documentation comment of Result, with comment markers stripped.
llvm::StringRef getStdHeader(const Symbol *S, const LangOptions &LangOpts)
bool isHeaderFile(llvm::StringRef FileName, std::optional< LangOptions > LangOpts)
Infers whether this is a header from the FileName and LangOpts (if presents).
SymbolTags computeSymbolTags(const NamedDecl &ND)
Computes symbol tags for a given NamedDecl.
bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx)
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Simplified description of a clang AST node.
Definition Protocol.h:2093
llvm::DenseMap< SymbolID, std::vector< MacroOccurrence > > MacroRefs
int line
Line position in a document (zero-based).
Definition Protocol.h:159
int character
Character offset on a line in a document (zero-based).
Definition Protocol.h:164
Position start
The range's start position.
Definition Protocol.h:188
Position end
The range's end position.
Definition Protocol.h:191
Represents a symbol occurrence in the source file.
Definition Ref.h:88
RefKind Kind
Definition Ref.h:91
SymbolLocation Location
The source location where the symbol is named.
Definition Ref.h:90
Position Start
The symbol range, using half-open range [Start, End).
Ensure we have enough bits to represent all SymbolTag values.
Definition Symbol.h:49
SymbolFlag Flags
Definition Symbol.h:165
@ IndexedForCodeCompletion
Whether or not this symbol is meant to be used for the code completion.
Definition Symbol.h:155
@ Deprecated
Indicates if the symbol is deprecated.
Definition Symbol.h:157
@ ImplementationDetail
Symbol is an implementation detail.
Definition Symbol.h:159
@ HasDocComment
Symbol has an attached documentation comment.
Definition Symbol.h:163
@ VisibleOutsideFile
Symbol is visible to other files (not e.g. a static helper function).
Definition Symbol.h:161
@ Include
#include "header.h"
Definition Symbol.h:107
@ Import
#import "header.h"
Definition Symbol.h:109
llvm::StringRef Type
Raw representation of the OpaqueType of the symbol, used for scoring purposes.
Definition Symbol.h:102
llvm::StringRef Documentation
Documentation including comment for the symbol declaration.
Definition Symbol.h:93
SymbolTags Tags
Symbol tags for LSP protocol (Deprecated, Static, Virtual, Abstract, Final, ReadOnly,...
Definition Symbol.h:78
index::SymbolInfo SymInfo
The symbol information, like symbol kind.
Definition Symbol.h:53
llvm::SmallVector< IncludeHeaderWithReferences, 1 > IncludeHeaders
One Symbol can potentially be included via different headers.
Definition Symbol.h:147
llvm::StringRef Name
The unqualified name of the symbol, e.g. "bar" (for ns::bar).
Definition Symbol.h:57
llvm::StringRef Scope
The containing namespace. e.g. "" (global), "ns::" (top-level namespace).
Definition Symbol.h:59
llvm::StringRef Signature
A brief description of the symbol that can be appended in the completion candidate list.
Definition Symbol.h:82
llvm::StringRef ReturnType
Type when this symbol is used in an expression.
Definition Symbol.h:97
llvm::StringRef TemplateSpecializationArgs
Argument list in human-readable format, will be displayed to help disambiguate between different spec...
Definition Symbol.h:86
SymbolLocation CanonicalDeclaration
The location of the preferred declaration of the symbol.
Definition Symbol.h:71
llvm::StringRef CompletionSnippetSuffix
What to insert when completing this symbol, after the symbol name.
Definition Symbol.h:91
SymbolID ID
The ID of the symbol.
Definition Symbol.h:51
SymbolOrigin Origin
Where this symbol came from. Usually an index provides a constant value.
Definition Symbol.h:55