clang-tools 24.0.0git
FindSymbols.cpp
Go to the documentation of this file.
1//===--- FindSymbols.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#include "FindSymbols.h"
9
10#include "AST.h"
11#include "FuzzyMatch.h"
12#include "ParsedAST.h"
13#include "Quality.h"
14#include "SourceCode.h"
15#include "index/Index.h"
16#include "index/Symbol.h"
18#include "support/Logger.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclFriend.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/Index/IndexSymbol.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringRef.h"
27#include <limits>
28#include <optional>
29
30#define DEBUG_TYPE "FindSymbols"
31
32namespace clang {
33namespace clangd {
34
35namespace {
36
37// "Static" means many things in C++, only some get the "static" modifier.
38//
39// Meanings that do:
40// - Members associated with the class rather than the instance.
41// This is what 'static' most often means across languages.
42// - static local variables
43// These are similarly "detached from their context" by the static keyword.
44// In practice, these are rarely used inside classes, reducing confusion.
45//
46// Meanings that don't:
47// - Namespace-scoped variables, which have static storage class.
48// This is implicit, so the keyword "static" isn't so strongly associated.
49// If we want a modifier for these, "global scope" is probably the concept.
50// - Namespace-scoped variables/functions explicitly marked "static".
51// There the keyword changes *linkage* , which is a totally different concept.
52// If we want to model this, "file scope" would be a nice modifier.
53//
54// This is confusing, and maybe we should use another name, but because "static"
55// is a standard LSP modifier, having one with that name has advantages.
56bool isStatic(const Decl *D) {
57 if (const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(D))
58 return CMD->isStatic();
59 if (const VarDecl *VD = llvm::dyn_cast<VarDecl>(D))
60 return VD->isStaticDataMember() || VD->isStaticLocal();
61 if (const auto *OPD = llvm::dyn_cast<ObjCPropertyDecl>(D))
62 return OPD->isClassProperty();
63 if (const auto *OMD = llvm::dyn_cast<ObjCMethodDecl>(D))
64 return OMD->isClassMethod();
65 if (const auto *FD = llvm::dyn_cast<FunctionDecl>(D))
66 return FD->isStatic();
67 return false;
68}
69
70// Whether T is const in a loose sense - is a variable with this type readonly?
71bool isConst(QualType T) {
72 if (T.isNull())
73 return false;
74 T = T.getNonReferenceType();
75 if (T.isConstQualified())
76 return true;
77 if (const auto *AT = T->getAsArrayTypeUnsafe())
78 return isConst(AT->getElementType());
79 if (isConst(T->getPointeeType()))
80 return true;
81 return false;
82}
83
84// Whether D is const in a loose sense (should it be highlighted as such?)
85// FIXME: This is separate from whether *a particular usage* can mutate D.
86// We may want V in V.size() to be readonly even if V is mutable.
87bool isConst(const Decl *D) {
88 if (llvm::isa<EnumConstantDecl>(D) || llvm::isa<NonTypeTemplateParmDecl>(D))
89 return true;
90 if (llvm::isa<FieldDecl>(D) || llvm::isa<VarDecl>(D) ||
91 llvm::isa<MSPropertyDecl>(D) || llvm::isa<BindingDecl>(D)) {
92 if (isConst(llvm::cast<ValueDecl>(D)->getType()))
93 return true;
94 }
95 if (const auto *OCPD = llvm::dyn_cast<ObjCPropertyDecl>(D)) {
96 if (OCPD->isReadOnly())
97 return true;
98 }
99 if (const auto *MPD = llvm::dyn_cast<MSPropertyDecl>(D)) {
100 if (!MPD->hasSetter())
101 return true;
102 }
103 if (const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(D)) {
104 if (CMD->isConst())
105 return true;
106 }
107 if (const auto *FD = llvm::dyn_cast<FunctionDecl>(D))
108 return isConst(FD->getReturnType());
109 return false;
110}
111
112// Indicates whether declaration D is abstract in cases where D is a struct or a
113// class.
114bool isAbstract(const Decl *D) {
115 if (const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(D))
116 return CMD->isPureVirtual();
117 if (const auto *CRD = llvm::dyn_cast<CXXRecordDecl>(D))
118 return CRD->hasDefinition() && CRD->isAbstract();
119 return false;
120}
121
122// Indicates whether declaration D is virtual in cases where D is a method.
123bool isVirtual(const Decl *D) {
124 if (const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(D))
125 return CMD->isVirtual();
126 return false;
127}
128
129// Indicates whether declaration D is final in cases where D is a struct, class
130// or method.
131bool isFinal(const Decl *D) {
132 if (const auto *CRD = dyn_cast<CXXMethodDecl>(D))
133 return CRD->hasAttr<FinalAttr>();
134
135 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D))
136 return CRD->hasAttr<FinalAttr>();
137
138 return false;
139}
140
141// A method "overrides" if:
142// 1. It overrides at least one method
143// 2. At least one of the overridden methods is virtual (but NOT pure
144// virtual)
145bool isOverrides(const NamedDecl *ND) {
146 if (const auto *MD = llvm::dyn_cast<CXXMethodDecl>(ND)) {
147 if (!MD->isVirtual())
148 return false;
149
150 for (const auto *Overridden : MD->overridden_methods()) {
151 // Pure virtual method indicates that we have a bug in clang.
152 assert(Overridden->isVirtual());
153 // Check if the overridden method is virtual.
154 if (!Overridden->isPureVirtual())
155 return true;
156 }
157 }
158 return false;
159}
160
161// A method "implements" pure virtual methods from base classes if:
162// 1. It overrides at least one method
163// 2. It is NOT itself pure virtual (i.e., it has a concrete implementation)
164// 3. ALL overridden methods are pure virtual
165bool isImplements(const NamedDecl *ND) {
166 if (const auto *MD = llvm::dyn_cast<CXXMethodDecl>(ND)) {
167 if (MD->size_overridden_methods() == 0 || MD->isPureVirtual())
168 return false;
169
170 for (const auto *Overridden : MD->overridden_methods()) {
171 if (!Overridden->isPureVirtual())
172 return false;
173 }
174 return true;
175 }
176 return false;
177}
178
179// Indicates whether declaration D is a unique definition (as opposed to a
180// declaration).
181bool isUniqueDefinition(const NamedDecl *Decl) {
182 if (auto *Func = dyn_cast<FunctionDecl>(Decl))
183 return Func->isThisDeclarationADefinition();
184 if (auto *Klass = dyn_cast<CXXRecordDecl>(Decl))
185 return Klass->isThisDeclarationADefinition();
186 if (auto *Iface = dyn_cast<ObjCInterfaceDecl>(Decl))
187 return Iface->isThisDeclarationADefinition();
188 if (auto *Proto = dyn_cast<ObjCProtocolDecl>(Decl))
189 return Proto->isThisDeclarationADefinition();
190 if (auto *Var = dyn_cast<VarDecl>(Decl))
191 return Var->isThisDeclarationADefinition();
192 return isa<TemplateTypeParmDecl>(Decl) ||
193 isa<NonTypeTemplateParmDecl>(Decl) ||
194 isa<TemplateTemplateParmDecl>(Decl) || isa<ObjCCategoryDecl>(Decl) ||
195 isa<ObjCImplDecl>(Decl);
196}
197
198// Filter symbol tags based on the presence of other tags and the kind of
199// symbol. This is needed to avoid redundant tags, e.g. Overrides implies
200// Virtual and Implements implies Overrides/Virtual.
201SymbolTags filterSymbolTags(SymbolTags ST) {
207
208 const SymbolTags VirtualAndOverridesMask = VirtualMask | OverridesMask;
209
210 // Implements implies both Overrides and Virtual.
211 if (ST & ImplementsMask)
212 ST &= ~VirtualAndOverridesMask;
213
214 // Final also suppresses both Virtual and Overrides in this model.
215 if (ST & FinalMask)
216 ST &= ~VirtualAndOverridesMask;
217
218 // Overrides or Abstract each imply Virtual.
219 if (ST & (OverridesMask | AbstractMask))
220 ST &= ~VirtualMask;
221
222 return ST;
223}
224
225bool isCXXClassMethod(const clang::clangd::Symbol &S) {
226 using clang::index::SymbolKind;
227 using clang::index::SymbolLanguage;
228
229 if (S.SymInfo.Lang != SymbolLanguage::CXX)
230 return false;
231
232 return llvm::is_contained({SymbolKind::InstanceMethod,
233 SymbolKind::StaticMethod, SymbolKind::Constructor,
234 SymbolKind::Destructor,
235 SymbolKind::ConversionFunction},
236 S.SymInfo.Kind);
237}
238
239template <typename E> constexpr E enumIncrement(E Value) {
240 return static_cast<E>(static_cast<std::underlying_type_t<E>>(Value) + 1);
241}
242} // namespace
243
245 return (1 << static_cast<unsigned>(ST));
246}
247
248SymbolTags computeSymbolTags(const NamedDecl &ND) {
249 SymbolTags Result = 0;
250 const auto IsDef = isUniqueDefinition(&ND);
251
252 if (ND.isDeprecated())
254
255 if (isConst(&ND))
257
258 if (isStatic(&ND))
260
261 if (isVirtual(&ND))
263
264 if (isAbstract(&ND))
266
267 if (isOverrides(&ND))
269
270 if (isFinal(&ND))
272
273 if (isImplements(&ND))
275
276 if (not isa<UnresolvedUsingValueDecl>(ND)) {
277 // Do not treat an UnresolvedUsingValueDecl as a declaration.
278 // It's more common to think of it as a reference to the
279 // underlying declaration.
281
282 if (IsDef)
284 }
285
286 switch (ND.getAccess()) {
287 case AS_public:
289 break;
290 case AS_protected:
292 break;
293 case AS_private:
295 break;
296 default:
297 break;
298 }
299
300 return Result;
301}
302
303std::vector<SymbolTag> expandTagBitmask(const SymbolTags STGS) {
304 std::vector<SymbolTag> Tags;
305
306 if (STGS == 0)
307 return Tags;
308
309 // No filtering required since this function is only used for Symbols from the
310 // index, which have already been filtered in getSymbolTags(const NamedDecl
311 // &ND).
312
313 // Iterate through SymbolTag enum values and collect any that are present in
314 // the bitmask. SymbolTag values are in the numeric range
315 // [FirstTag .. LastTag].
316 constexpr unsigned MinTag = static_cast<unsigned>(SymbolTag::FirstTag);
317 constexpr unsigned MaxTag = static_cast<unsigned>(SymbolTag::LastTag);
318 for (unsigned I = MinTag; I <= MaxTag; ++I) {
319 auto ST = static_cast<SymbolTag>(I);
320 if (STGS & toSymbolTagBitmask(ST))
321 Tags.push_back(ST);
322 }
323 return Tags;
324}
325
326std::vector<SymbolTag> getSymbolTags(const Symbol &S) {
327 const SymbolTags Tags =
328 isCXXClassMethod(S) ? filterSymbolTags(S.Tags) : S.Tags;
329 return expandTagBitmask(Tags);
330}
331
332std::vector<SymbolTag> getSymbolTags(const NamedDecl &ND) {
333 const auto STGS = computeSymbolTags(ND);
334 SymbolTags FilteredTags = STGS;
335 std::vector<SymbolTag> Tags;
336
337 if (STGS == 0)
338 return Tags;
339
340 // Apply specific filter to the symbol tags only on CXX class methods.
341 if (isa<CXXMethodDecl>(ND))
342 FilteredTags = filterSymbolTags(STGS);
343
344 // Iterate through SymbolTag enum values and collect any that are present in
345 // the bitmask. SymbolTag values are in the numeric range
346 // [FirstTag .. LastTag].
348 Tag = enumIncrement(Tag)) {
349 if (FilteredTags & toSymbolTagBitmask(Tag))
350 Tags.push_back(Tag);
351 }
352 return Tags;
353}
354
355namespace {
356using ScoredSymbolInfo = std::pair<float, SymbolInformation>;
357struct ScoredSymbolGreater {
358 bool operator()(const ScoredSymbolInfo &L, const ScoredSymbolInfo &R) {
359 if (L.first != R.first)
360 return L.first > R.first;
361 return L.second.name < R.second.name; // Earlier name is better.
362 }
363};
364
365// Returns true if \p Query can be found as a sub-sequence inside \p Scope.
366bool approximateScopeMatch(llvm::StringRef Scope, llvm::StringRef Query) {
367 assert(Scope.empty() || Scope.ends_with("::"));
368 assert(Query.empty() || Query.ends_with("::"));
369 while (!Scope.empty() && !Query.empty()) {
370 auto Colons = Scope.find("::");
371 assert(Colons != llvm::StringRef::npos);
372
373 llvm::StringRef LeadingSpecifier = Scope.slice(0, Colons + 2);
374 Scope = Scope.slice(Colons + 2, llvm::StringRef::npos);
375 Query.consume_front(LeadingSpecifier);
376 }
377 return Query.empty();
378}
379
380} // namespace
381
382llvm::Expected<Location> indexToLSPLocation(const SymbolLocation &Loc,
383 llvm::StringRef TUPath) {
384 auto Path = URI::resolve(Loc.FileURI, TUPath);
385 if (!Path)
386 return error("Could not resolve path for file '{0}': {1}", Loc.FileURI,
387 Path.takeError());
388 Location L;
389 L.uri = URIForFile::canonicalize(*Path, TUPath);
390 Position Start, End;
391 Start.line = Loc.Start.line();
392 Start.character = Loc.Start.column();
393 End.line = Loc.End.line();
394 End.character = Loc.End.column();
395 L.range = {Start, End};
396 return L;
397}
398
399llvm::Expected<Location> symbolToLocation(const Symbol &Sym,
400 llvm::StringRef TUPath) {
401 // Prefer the definition over e.g. a function declaration in a header
402 return indexToLSPLocation(
403 Sym.Definition ? Sym.Definition : Sym.CanonicalDeclaration, TUPath);
404}
405
406llvm::Expected<std::vector<SymbolInformation>>
407getWorkspaceSymbols(llvm::StringRef Query, int Limit,
408 const SymbolIndex *const Index, llvm::StringRef HintPath) {
409 std::vector<SymbolInformation> Result;
410 if (!Index)
411 return Result;
412
413 // Lookup for qualified names are performed as:
414 // - Exact namespaces are boosted by the index.
415 // - Approximate matches are (sub-scope match) included via AnyScope logic.
416 // - Non-matching namespaces (no sub-scope match) are post-filtered.
417 auto Names = splitQualifiedName(Query);
418
420 Req.Query = std::string(Names.second);
421
422 // FuzzyFind doesn't want leading :: qualifier.
423 auto HasLeadingColons = Names.first.consume_front("::");
424 // Limit the query to specific namespace if it is fully-qualified.
425 Req.AnyScope = !HasLeadingColons;
426 // Boost symbols from desired namespace.
427 if (HasLeadingColons || !Names.first.empty())
428 Req.Scopes = {std::string(Names.first)};
429 if (Limit) {
430 Req.Limit = Limit;
431 // If we are boosting a specific scope allow more results to be retrieved,
432 // since some symbols from preferred namespaces might not make the cut.
433 if (Req.AnyScope && !Req.Scopes.empty())
434 *Req.Limit *= 5;
435 }
437 Req.Limit.value_or(std::numeric_limits<size_t>::max()));
438 FuzzyMatcher Filter(Req.Query);
439
440 Index->fuzzyFind(Req, [HintPath, &Top, &Filter, AnyScope = Req.AnyScope,
441 ReqScope = Names.first](const Symbol &Sym) {
442 llvm::StringRef Scope = Sym.Scope;
443 // Fuzzyfind might return symbols from irrelevant namespaces if query was
444 // not fully-qualified, drop those.
445 if (AnyScope && !approximateScopeMatch(Scope, ReqScope))
446 return;
447
448 auto Loc = symbolToLocation(Sym, HintPath);
449 if (!Loc) {
450 log("Workspace symbols: {0}", Loc.takeError());
451 return;
452 }
453
454 SymbolQualitySignals Quality;
455 Quality.merge(Sym);
456 SymbolRelevanceSignals Relevance;
457 Relevance.Name = Sym.Name;
458 Relevance.Query = SymbolRelevanceSignals::Generic;
459 // If symbol and request scopes do not match exactly, apply a penalty.
460 Relevance.InBaseClass = AnyScope && Scope != ReqScope;
461 if (auto NameMatch = Filter.match(Sym.Name))
462 Relevance.NameMatch = *NameMatch;
463 else {
464 log("Workspace symbol: {0} didn't match query {1}", Sym.Name,
465 Filter.pattern());
466 return;
467 }
468 Relevance.merge(Sym);
469 auto QualScore = Quality.evaluateHeuristics();
470 auto RelScore = Relevance.evaluateHeuristics();
471 auto Score = evaluateSymbolAndRelevance(QualScore, RelScore);
472 dlog("FindSymbols: {0}{1} = {2}\n{3}{4}\n", Sym.Scope, Sym.Name, Score,
473 Quality, Relevance);
474
476 Info.name = (Sym.Name + Sym.TemplateSpecializationArgs).str();
478 Info.location = *Loc;
479 Scope.consume_back("::");
480 Info.containerName = Scope.str();
481
482 // Exposed score excludes fuzzy-match component, for client-side re-ranking.
483 Info.score = Relevance.NameMatch > std::numeric_limits<float>::epsilon()
484 ? Score / Relevance.NameMatch
485 : QualScore;
486 Info.tags = getSymbolTags(Sym);
487 Top.push({Score, std::move(Info)});
488 });
489 for (auto &R : std::move(Top).items())
490 Result.push_back(std::move(R.second));
491 return Result;
492}
493
494namespace {
495std::string getSymbolName(ASTContext &Ctx, const NamedDecl &ND) {
496 // Print `MyClass(Category)` instead of `Category` and `MyClass()` instead
497 // of `anonymous`.
498 if (const auto *Container = dyn_cast<ObjCContainerDecl>(&ND))
499 return printObjCContainer(*Container);
500 // Differentiate between class and instance methods: print `-foo` instead of
501 // `foo` and `+sharedInstance` instead of `sharedInstance`.
502 if (const auto *Method = dyn_cast<ObjCMethodDecl>(&ND)) {
503 std::string Name;
504 llvm::raw_string_ostream OS(Name);
505
506 OS << (Method->isInstanceMethod() ? '-' : '+');
507 Method->getSelector().print(OS);
508
509 return Name;
510 }
511 return printName(Ctx, ND);
512}
513
514std::string getSymbolDetail(ASTContext &Ctx, const NamedDecl &ND) {
515 PrintingPolicy P(Ctx.getPrintingPolicy());
516 P.SuppressScope = true;
517 P.SuppressUnwrittenScope = true;
518 P.AnonymousTagNameStyle =
519 llvm::to_underlying(PrintingPolicy::AnonymousTagMode::Plain);
520 P.PolishForDeclaration = true;
521 std::string Detail;
522 llvm::raw_string_ostream OS(Detail);
523 if (ND.getDescribedTemplateParams()) {
524 OS << "template ";
525 }
526 if (const auto *VD = dyn_cast<ValueDecl>(&ND)) {
527 // FIXME: better printing for dependent type
528 if (isa<CXXConstructorDecl>(VD)) {
529 std::string ConstructorType = VD->getType().getAsString(P);
530 // Print constructor type as "(int)" instead of "void (int)".
531 llvm::StringRef WithoutVoid = ConstructorType;
532 WithoutVoid.consume_front("void ");
533 OS << WithoutVoid;
534 } else if (!isa<CXXDestructorDecl>(VD)) {
535 VD->getType().print(OS, P);
536 }
537 } else if (const auto *TD = dyn_cast<TagDecl>(&ND)) {
538 OS << TD->getKindName();
539 } else if (isa<TypedefNameDecl>(&ND)) {
540 OS << "type alias";
541 } else if (isa<ConceptDecl>(&ND)) {
542 OS << "concept";
543 }
544 return std::move(OS.str());
545}
546
547std::optional<DocumentSymbol> declToSym(ASTContext &Ctx, const NamedDecl &ND) {
548 auto &SM = Ctx.getSourceManager();
549
550 SourceLocation BeginLoc = ND.getBeginLoc();
551 SourceLocation EndLoc = ND.getEndLoc();
552 const auto SymbolRange =
553 toHalfOpenFileRange(SM, Ctx.getLangOpts(), {BeginLoc, EndLoc});
554 if (!SymbolRange)
555 return std::nullopt;
556
557 index::SymbolInfo SymInfo = index::getSymbolInfo(&ND);
558 // FIXME: This is not classifying constructors, destructors and operators
559 // correctly.
561
562 DocumentSymbol SI;
563 SI.name = getSymbolName(Ctx, ND);
564 SI.kind = SK;
565 SI.deprecated = ND.isDeprecated();
566 SI.range = Range{sourceLocToPosition(SM, SymbolRange->getBegin()),
567 sourceLocToPosition(SM, SymbolRange->getEnd())};
568 SI.detail = getSymbolDetail(Ctx, ND);
569 SI.tags = getSymbolTags(ND);
570
571 SourceLocation NameLoc = ND.getLocation();
572 SourceLocation FallbackNameLoc;
573 if (NameLoc.isMacroID()) {
574 if (isSpelledInSource(NameLoc, SM)) {
575 // Prefer the spelling loc, but save the expansion loc as a fallback.
576 FallbackNameLoc = SM.getExpansionLoc(NameLoc);
577 NameLoc = SM.getSpellingLoc(NameLoc);
578 } else {
579 NameLoc = SM.getExpansionLoc(NameLoc);
580 }
581 }
582 auto ComputeSelectionRange = [&](SourceLocation L) -> Range {
583 Position NameBegin = sourceLocToPosition(SM, L);
584 Position NameEnd = sourceLocToPosition(
585 SM, Lexer::getLocForEndOfToken(L, 0, SM, Ctx.getLangOpts()));
586 return Range{NameBegin, NameEnd};
587 };
588
589 SI.selectionRange = ComputeSelectionRange(NameLoc);
590 if (!SI.range.contains(SI.selectionRange) && FallbackNameLoc.isValid()) {
591 // 'selectionRange' must be contained in 'range'. In cases where clang
592 // reports unrelated ranges, we first try falling back to the expansion
593 // loc for the selection range.
594 SI.selectionRange = ComputeSelectionRange(FallbackNameLoc);
595 }
596 if (!SI.range.contains(SI.selectionRange)) {
597 // If the containment relationship still doesn't hold, throw away
598 // 'range' and use 'selectionRange' for both.
599 SI.range = SI.selectionRange;
600 }
601 return SI;
602}
603
604/// A helper class to build an outline for the parse AST. It traverses the AST
605/// directly instead of using RecursiveASTVisitor (RAV) for three main reasons:
606/// - there is no way to keep RAV from traversing subtrees we are not
607/// interested in. E.g. not traversing function locals or implicit template
608/// instantiations.
609/// - it's easier to combine results of recursive passes,
610/// - visiting decls is actually simple, so we don't hit the complicated
611/// cases that RAV mostly helps with (types, expressions, etc.)
612class DocumentOutline {
613 // A DocumentSymbol we're constructing.
614 // We use this instead of DocumentSymbol directly so that we can keep track
615 // of the nodes we insert for macros.
616 class SymBuilder {
617 std::vector<SymBuilder> Children;
618 DocumentSymbol Symbol; // Symbol.children is empty, use Children instead.
619 // Macro expansions that this node or its parents are associated with.
620 // (Thus we will never create further children for these expansions).
621 llvm::SmallVector<SourceLocation> EnclosingMacroLoc;
622
623 public:
624 DocumentSymbol build() && {
625 for (SymBuilder &C : Children) {
626 Symbol.children.push_back(std::move(C).build());
627 // Expand range to ensure children nest properly, which editors expect.
628 // This can fix some edge-cases in the AST, but is vital for macros.
629 // A macro expansion "contains" AST node if it covers the node's primary
630 // location, but it may not span the node's whole range.
631 Symbol.range.start =
632 std::min(Symbol.range.start, Symbol.children.back().range.start);
633 Symbol.range.end =
634 std::max(Symbol.range.end, Symbol.children.back().range.end);
635 }
636 return std::move(Symbol);
637 }
638
639 // Add a symbol as a child of the current one.
640 SymBuilder &addChild(DocumentSymbol S) {
641 Children.emplace_back();
642 Children.back().EnclosingMacroLoc = EnclosingMacroLoc;
643 Children.back().Symbol = std::move(S);
644 return Children.back();
645 }
646
647 // Get an appropriate container for children of this symbol that were
648 // expanded from a macro (whose spelled name is Tok).
649 //
650 // This may return:
651 // - a macro symbol child of this (either new or previously created)
652 // - this scope itself, if it *is* the macro symbol or is nested within it
653 SymBuilder &inMacro(const syntax::Token &Tok, const SourceManager &SM,
654 std::optional<syntax::TokenBuffer::Expansion> Exp) {
655 if (llvm::is_contained(EnclosingMacroLoc, Tok.location()))
656 return *this;
657 // If there's an existing child for this macro, we expect it to be last.
658 if (!Children.empty() && !Children.back().EnclosingMacroLoc.empty() &&
659 Children.back().EnclosingMacroLoc.back() == Tok.location())
660 return Children.back();
661
662 DocumentSymbol Sym;
663 Sym.name = Tok.text(SM).str();
664 Sym.kind = SymbolKind::Null; // There's no suitable kind!
665 Sym.range = Sym.selectionRange =
666 halfOpenToRange(SM, Tok.range(SM).toCharRange(SM));
667
668 // FIXME: Exp is currently unavailable for nested expansions.
669 if (Exp) {
670 // Full range covers the macro args.
671 Sym.range = halfOpenToRange(SM, CharSourceRange::getCharRange(
672 Exp->Spelled.front().location(),
673 Exp->Spelled.back().endLocation()));
674 // Show macro args as detail.
675 llvm::raw_string_ostream OS(Sym.detail);
676 const syntax::Token *Prev = nullptr;
677 for (const auto &Tok : Exp->Spelled.drop_front()) {
678 // Don't dump arbitrarily long macro args.
679 if (OS.tell() > 80) {
680 OS << " ...)";
681 break;
682 }
683 if (Prev && Prev->endLocation() != Tok.location())
684 OS << ' ';
685 OS << Tok.text(SM);
686 Prev = &Tok;
687 }
688 }
689 SymBuilder &Child = addChild(std::move(Sym));
690 Child.EnclosingMacroLoc.push_back(Tok.location());
691 return Child;
692 }
693 };
694
695public:
696 DocumentOutline(ParsedAST &AST) : AST(AST) {}
697
698 /// Builds the document outline for the generated AST.
699 std::vector<DocumentSymbol> build() {
700 SymBuilder Root;
701 for (auto &TopLevel : AST.getLocalTopLevelDecls())
702 traverseDecl(TopLevel, Root);
703 return std::move(std::move(Root).build().children);
704 }
705
706private:
707 enum class VisitKind { No, OnlyDecl, OnlyChildren, DeclAndChildren };
708
709 void traverseDecl(Decl *D, SymBuilder &Parent) {
710 // Skip symbols which do not originate from the main file.
711 if (!isInsideMainFile(D->getLocation(), AST.getSourceManager()))
712 return;
713
714 if (auto *Templ = llvm::dyn_cast<TemplateDecl>(D)) {
715 // TemplatedDecl might be null, e.g. concepts.
716 if (auto *TD = Templ->getTemplatedDecl())
717 D = TD;
718 }
719
720 // FriendDecls don't act as DeclContexts, but they might wrap a function
721 // definition that won't be visible through other means in the AST. Hence
722 // unwrap it here instead.
723 if (auto *Friend = llvm::dyn_cast<FriendDecl>(D)) {
724 if (auto *Func =
725 llvm::dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl())) {
726 if (Func->isThisDeclarationADefinition())
727 D = Func;
728 }
729 }
730
731 VisitKind Visit = shouldVisit(D);
732 if (Visit == VisitKind::No)
733 return;
734
735 if (Visit == VisitKind::OnlyChildren)
736 return traverseChildren(D, Parent);
737
738 auto *ND = llvm::cast<NamedDecl>(D);
739 auto Sym = declToSym(AST.getASTContext(), *ND);
740 if (!Sym)
741 return;
742 SymBuilder &MacroParent = possibleMacroContainer(D->getLocation(), Parent);
743 SymBuilder &Child = MacroParent.addChild(std::move(*Sym));
744
745 if (Visit == VisitKind::OnlyDecl)
746 return;
747
748 assert(Visit == VisitKind::DeclAndChildren && "Unexpected VisitKind");
749 traverseChildren(ND, Child);
750 }
751
752 // Determines where a decl should appear in the DocumentSymbol hierarchy.
753 //
754 // This is usually a direct child of the relevant AST parent.
755 // But we may also insert nodes for macros. Given:
756 // #define DECLARE_INT(V) int v;
757 // namespace a { DECLARE_INT(x) }
758 // We produce:
759 // Namespace a
760 // Macro DECLARE_INT(x)
761 // Variable x
762 //
763 // In the absence of macros, this method simply returns Parent.
764 // Otherwise it may return a macro expansion node instead.
765 // Each macro only has at most one node in the hierarchy, even if it expands
766 // to multiple decls.
767 SymBuilder &possibleMacroContainer(SourceLocation TargetLoc,
768 SymBuilder &Parent) {
769 const auto &SM = AST.getSourceManager();
770 // Look at the path of macro-callers from the token to the main file.
771 // Note that along these paths we see the "outer" macro calls first.
772 SymBuilder *CurParent = &Parent;
773 for (SourceLocation Loc = TargetLoc; Loc.isMacroID();
774 Loc = SM.getImmediateMacroCallerLoc(Loc)) {
775 // Find the virtual macro body that our token is being substituted into.
776 FileID MacroBody;
777 if (SM.isMacroArgExpansion(Loc)) {
778 // Loc is part of a macro arg being substituted into a macro body.
779 MacroBody = SM.getFileID(SM.getImmediateExpansionRange(Loc).getBegin());
780 } else {
781 // Loc is already in the macro body.
782 MacroBody = SM.getFileID(Loc);
783 }
784 // The macro body is being substituted for a macro expansion, whose
785 // first token is the name of the macro.
786 SourceLocation MacroName =
787 SM.getSLocEntry(MacroBody).getExpansion().getExpansionLocStart();
788 // Only include the macro expansion in the outline if it was written
789 // directly in the main file, rather than expanded from another macro.
790 if (!MacroName.isValid() || !MacroName.isFileID())
791 continue;
792 // All conditions satisfied, add the macro.
793 if (auto *Tok = AST.getTokens().spelledTokenContaining(MacroName))
794 CurParent = &CurParent->inMacro(
795 *Tok, SM, AST.getTokens().expansionStartingAt(Tok));
796 }
797 return *CurParent;
798 }
799
800 void traverseChildren(Decl *D, SymBuilder &Builder) {
801 auto *Scope = llvm::dyn_cast<DeclContext>(D);
802 if (!Scope)
803 return;
804 for (auto *C : Scope->decls())
805 traverseDecl(C, Builder);
806 }
807
808 VisitKind shouldVisit(Decl *D) {
809 if (D->isImplicit())
810 return VisitKind::No;
811
812 if (llvm::isa<LinkageSpecDecl>(D) || llvm::isa<ExportDecl>(D))
813 return VisitKind::OnlyChildren;
814
815 if (!llvm::isa<NamedDecl>(D))
816 return VisitKind::No;
817
818 if (auto *Func = llvm::dyn_cast<FunctionDecl>(D)) {
819 // Some functions are implicit template instantiations, those should be
820 // ignored.
821 if (auto *Info = Func->getTemplateSpecializationInfo()) {
822 if (!Info->isExplicitInstantiationOrSpecialization())
823 return VisitKind::No;
824 }
825 // Only visit the function itself, do not visit the children (i.e.
826 // function parameters, etc.)
827 return VisitKind::OnlyDecl;
828 }
829 // Handle template instantiations. We have three cases to consider:
830 // - explicit instantiations, e.g. 'template class std::vector<int>;'
831 // Visit the decl itself (it's present in the code), but not the
832 // children.
833 // - implicit instantiations, i.e. not written by the user.
834 // Do not visit at all, they are not present in the code.
835 // - explicit specialization, e.g. 'template <> class vector<bool> {};'
836 // Visit both the decl and its children, both are written in the code.
837 if (auto *TemplSpec = llvm::dyn_cast<ClassTemplateSpecializationDecl>(D)) {
838 if (TemplSpec->isExplicitInstantiationOrSpecialization())
839 return TemplSpec->isExplicitSpecialization()
840 ? VisitKind::DeclAndChildren
841 : VisitKind::OnlyDecl;
842 return VisitKind::No;
843 }
844 if (auto *TemplSpec = llvm::dyn_cast<VarTemplateSpecializationDecl>(D)) {
845 if (TemplSpec->isExplicitInstantiationOrSpecialization())
846 return TemplSpec->isExplicitSpecialization()
847 ? VisitKind::DeclAndChildren
848 : VisitKind::OnlyDecl;
849 return VisitKind::No;
850 }
851 // For all other cases, visit both the children and the decl.
852 return VisitKind::DeclAndChildren;
853 }
854
855 ParsedAST &AST;
856};
857
858struct PragmaMarkSymbol {
859 DocumentSymbol DocSym;
860 bool IsGroup;
861};
862
863/// Merge in `PragmaMarkSymbols`, sorted ascending by range, into the given
864/// `DocumentSymbol` tree.
865void mergePragmas(DocumentSymbol &Root, ArrayRef<PragmaMarkSymbol> Pragmas) {
866 while (!Pragmas.empty()) {
867 // We'll figure out where the Pragmas.front() should go.
868 PragmaMarkSymbol P = std::move(Pragmas.front());
869 Pragmas = Pragmas.drop_front();
870 DocumentSymbol *Cur = &Root;
871 while (Cur->range.contains(P.DocSym.range)) {
872 bool Swapped = false;
873 for (auto &C : Cur->children) {
874 // We assume at most 1 child can contain the pragma (as pragmas are on
875 // a single line, and children have disjoint ranges).
876 if (C.range.contains(P.DocSym.range)) {
877 Cur = &C;
878 Swapped = true;
879 break;
880 }
881 }
882 // Cur is the parent of P since none of the children contain P.
883 if (!Swapped)
884 break;
885 }
886 // Pragma isn't a group so we can just insert it and we are done.
887 if (!P.IsGroup) {
888 Cur->children.emplace_back(std::move(P.DocSym));
889 continue;
890 }
891 // Pragma is a group, so we need to figure out where it terminates:
892 // - If the next Pragma is not contained in Cur, P owns all of its
893 // parent's children which occur after P.
894 // - If the next pragma is contained in Cur but actually belongs to one
895 // of the parent's children, we temporarily skip over it and look at
896 // the next pragma to decide where we end.
897 // - Otherwise nest all of its parent's children which occur after P but
898 // before the next pragma.
899 bool TerminatedByNextPragma = false;
900 for (auto &NextPragma : Pragmas) {
901 // If we hit a pragma outside of Cur, the rest will be outside as well.
902 if (!Cur->range.contains(NextPragma.DocSym.range))
903 break;
904
905 // NextPragma cannot terminate P if it is nested inside a child, look for
906 // the next one.
907 if (llvm::any_of(Cur->children, [&NextPragma](const auto &Child) {
908 return Child.range.contains(NextPragma.DocSym.range);
909 }))
910 continue;
911
912 // Pragma owns all the children between P and NextPragma
913 auto It = llvm::partition(Cur->children,
914 [&P, &NextPragma](const auto &S) -> bool {
915 return !(P.DocSym.range < S.range &&
916 S.range < NextPragma.DocSym.range);
917 });
918 P.DocSym.children.assign(make_move_iterator(It),
919 make_move_iterator(Cur->children.end()));
920 Cur->children.erase(It, Cur->children.end());
921 TerminatedByNextPragma = true;
922 break;
923 }
924 if (!TerminatedByNextPragma) {
925 // P is terminated by the end of current symbol, hence it owns all the
926 // children after P.
927 auto It = llvm::partition(Cur->children, [&P](const auto &S) -> bool {
928 return !(P.DocSym.range < S.range);
929 });
930 P.DocSym.children.assign(make_move_iterator(It),
931 make_move_iterator(Cur->children.end()));
932 Cur->children.erase(It, Cur->children.end());
933 }
934 // Update the range for P to cover children and append to Cur.
935 for (DocumentSymbol &Sym : P.DocSym.children)
936 unionRanges(P.DocSym.range, Sym.range);
937 Cur->children.emplace_back(std::move(P.DocSym));
938 }
939}
940
941PragmaMarkSymbol markToSymbol(const PragmaMark &P) {
942 StringRef Name = StringRef(P.Trivia).trim();
943 bool IsGroup = false;
944 // "-\s+<group name>" or "<name>" after an initial trim. The former is
945 // considered a group, the latter just a mark. Like Xcode, we don't consider
946 // `-Foo` to be a group (space(s) after the `-` is required).
947 //
948 // We need to include a name here, otherwise editors won't properly render the
949 // symbol.
950 StringRef MaybeGroupName = Name;
951 if (MaybeGroupName.consume_front("-") &&
952 (MaybeGroupName.ltrim() != MaybeGroupName || MaybeGroupName.empty())) {
953 Name = MaybeGroupName.empty() ? "(unnamed group)" : MaybeGroupName.ltrim();
954 IsGroup = true;
955 } else if (Name.empty()) {
956 Name = "(unnamed mark)";
957 }
958 DocumentSymbol Sym;
959 Sym.name = Name.str();
960 Sym.kind = SymbolKind::File;
961 Sym.range = P.Rng;
962 Sym.selectionRange = P.Rng;
963 return {Sym, IsGroup};
964}
965
966std::vector<DocumentSymbol> collectDocSymbols(ParsedAST &AST) {
967 std::vector<DocumentSymbol> Syms = DocumentOutline(AST).build();
968
969 const auto &PragmaMarks = AST.getMarks();
970 if (PragmaMarks.empty())
971 return Syms;
972
973 std::vector<PragmaMarkSymbol> Pragmas;
974 Pragmas.reserve(PragmaMarks.size());
975 for (const auto &P : PragmaMarks)
976 Pragmas.push_back(markToSymbol(P));
977 Range EntireFile = {
978 {0, 0},
979 {std::numeric_limits<int>::max(), std::numeric_limits<int>::max()}};
980 DocumentSymbol Root;
981 Root.children = std::move(Syms);
982 Root.range = EntireFile;
983 mergePragmas(Root, llvm::ArrayRef(Pragmas));
984 return Root.children;
985}
986
987} // namespace
988
989llvm::Expected<std::vector<DocumentSymbol>> getDocumentSymbols(ParsedAST &AST) {
990 return collectDocSymbols(AST);
991}
992
993} // namespace clangd
994} // namespace clang
#define dlog(...)
Definition Logger.h:101
static GeneratorRegistry::Add< MDGenerator > MD(MDGenerator::Format, "Generator for Markdown output.")
clang::find_all_symbols::SymbolInfo::SymbolKind SymbolKind
std::optional< float > match(llvm::StringRef Word)
Stores and provides access to parsed AST.
Definition ParsedAST.h:46
Interface for symbol indexes that can be used for searching or matching symbols among a set of symbol...
Definition Index.h:134
virtual bool fuzzyFind(const FuzzyFindRequest &Req, llvm::function_ref< void(const Symbol &)> Callback) const =0
Matches symbols in the index fuzzily and applies Callback on each matched symbol before returning.
TopN<T> is a lossy container that preserves only the "best" N elements.
Definition Quality.h:189
bool push(value_type &&V)
Definition Quality.h:197
static llvm::Expected< std::string > resolve(const URI &U, llvm::StringRef HintPath="")
Resolves the absolute path of U.
Definition URI.cpp:244
std::pair< StringRef, StringRef > splitQualifiedName(StringRef QName)
llvm::Expected< Location > indexToLSPLocation(const SymbolLocation &Loc, llvm::StringRef TUPath)
Helper function for deriving an LSP Location from an index SymbolLocation.
@ Info
An information message.
Definition Protocol.h:755
std::optional< SourceRange > toHalfOpenFileRange(const SourceManager &SM, const LangOptions &LangOpts, SourceRange R)
Turns a token range into a half-open range and checks its correctness.
uint32_t SymbolTags
A bitmask type representing symbol tags supported by LSP.
Definition Symbol.h:29
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R)
std::string printName(const ASTContext &Ctx, const NamedDecl &ND)
Prints unqualified name of the decl for the purpose of displaying it to the user.
Definition AST.cpp:248
SymbolTag
Symbol tags are extra annotations that can be attached to a symbol.
Definition Protocol.h:1126
std::vector< SymbolTag > getSymbolTags(const Symbol &S)
Returns the SymbolTag values for the given indexed S.
bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM)
Returns true iff Loc is inside the main file.
llvm::Expected< Location > symbolToLocation(const Symbol &Sym, llvm::StringRef TUPath)
Helper function for deriving an LSP Location for a Symbol.
void unionRanges(Range &A, Range B)
llvm::Error error(std::error_code EC, const char *Fmt, Ts &&... Vals)
Definition Logger.h:79
Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc)
Turn a SourceLocation into a [line, column] pair.
SymbolTags toSymbolTagBitmask(const SymbolTag ST)
Converts a single SymbolTag to a bitmask.
llvm::Expected< std::vector< DocumentSymbol > > getDocumentSymbols(ParsedAST &AST)
Retrieves the symbols contained in the "main file" section of an AST in the same order that they appe...
@ No
Diagnostics must be generated for this snapshot.
Definition TUScheduler.h:55
std::string Path
A typedef to represent a file path.
Definition Path.h:26
llvm::Expected< std::vector< SymbolInformation > > getWorkspaceSymbols(llvm::StringRef Query, int Limit, const SymbolIndex *const Index, llvm::StringRef HintPath)
Searches for the symbols matching Query.
SymbolKind indexSymbolKindToSymbolKind(const index::SymbolInfo &Info)
Definition Protocol.cpp:306
bool isSpelledInSource(SourceLocation Loc, const SourceManager &SM)
Returns true if the token at Loc is spelled in the source code.
float evaluateSymbolAndRelevance(float SymbolQuality, float SymbolRelevance)
Combine symbol quality and relevance into a single score.
Definition Quality.cpp:534
std::vector< SymbolTag > expandTagBitmask(const SymbolTags STGS)
SymbolTags computeSymbolTags(const NamedDecl &ND)
Computes symbol tags for a given NamedDecl.
cppcoreguidelines::ProBoundsAvoidUncheckedContainerAccessCheck P
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
std::vector< std::string > Scopes
If this is non-empty, symbols must be in at least one of the scopes (e.g.
Definition Index.h:36
std::string Query
A query string for the fuzzy find.
Definition Index.h:29
bool AnyScope
If set to true, allow symbols from any scope.
Definition Index.h:39
std::optional< uint32_t > Limit
The number of top candidates to return.
Definition Index.h:42
URIForFile uri
The text document's URI.
Definition Protocol.h:214
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
Represents information about programming constructs like variables, classes, interfaces etc.
Definition Protocol.h:1202
Position Start
The symbol range, using half-open range [Start, End).
Attributes of a symbol that affect how much we like it.
Definition Quality.h:56
void merge(const CodeCompletionResult &SemaCCResult)
Definition Quality.cpp:178
Attributes of a symbol-query pair that affect how much we like it.
Definition Quality.h:86
llvm::StringRef Name
The name of the symbol (for ContextWords). Must be explicitly assigned.
Definition Quality.h:88
Ensure we have enough bits to represent all SymbolTag values.
Definition Symbol.h:49
SymbolLocation Definition
The location of the symbol's definition, if one was found.
Definition Symbol.h:62
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::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 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
static URIForFile canonicalize(llvm::StringRef AbsPath, llvm::StringRef TUPath)
Canonicalizes AbsPath via URI.
Definition Protocol.cpp:46