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