17#include "clang/AST/DeclFriend.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/Index/IndexSymbol.h"
20#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/StringRef.h"
27#define DEBUG_TYPE "FindSymbols"
53bool isStatic(
const Decl *D) {
54 if (
const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(D))
55 return CMD->isStatic();
56 if (
const VarDecl *VD = llvm::dyn_cast<VarDecl>(D))
57 return VD->isStaticDataMember() || VD->isStaticLocal();
58 if (
const auto *OPD = llvm::dyn_cast<ObjCPropertyDecl>(D))
59 return OPD->isClassProperty();
60 if (
const auto *OMD = llvm::dyn_cast<ObjCMethodDecl>(D))
61 return OMD->isClassMethod();
62 if (
const auto *FD = llvm::dyn_cast<FunctionDecl>(D))
63 return FD->isStatic();
68bool isConst(QualType T) {
71 T = T.getNonReferenceType();
72 if (T.isConstQualified())
74 if (
const auto *AT = T->getAsArrayTypeUnsafe())
75 return isConst(AT->getElementType());
76 if (isConst(T->getPointeeType()))
84bool isConst(
const Decl *D) {
85 if (llvm::isa<EnumConstantDecl>(D) || llvm::isa<NonTypeTemplateParmDecl>(D))
87 if (llvm::isa<FieldDecl>(D) || llvm::isa<VarDecl>(D) ||
88 llvm::isa<MSPropertyDecl>(D) || llvm::isa<BindingDecl>(D)) {
89 if (isConst(llvm::cast<ValueDecl>(D)->getType()))
92 if (
const auto *OCPD = llvm::dyn_cast<ObjCPropertyDecl>(D)) {
93 if (OCPD->isReadOnly())
96 if (
const auto *MPD = llvm::dyn_cast<MSPropertyDecl>(D)) {
97 if (!MPD->hasSetter())
100 if (
const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(D)) {
104 if (
const auto *FD = llvm::dyn_cast<FunctionDecl>(D))
105 return isConst(FD->getReturnType());
111bool isAbstract(
const Decl *D) {
112 if (
const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(D))
113 return CMD->isPureVirtual();
114 if (
const auto *CRD = llvm::dyn_cast<CXXRecordDecl>(D))
115 return CRD->hasDefinition() && CRD->isAbstract();
120bool isVirtual(
const Decl *D) {
121 if (
const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(D))
122 return CMD->isVirtual();
128bool isFinal(
const Decl *D) {
129 if (
const auto *CRD = dyn_cast<CXXMethodDecl>(D))
130 return CRD->hasAttr<FinalAttr>();
132 if (
const auto *CRD = dyn_cast<CXXRecordDecl>(D))
133 return CRD->hasAttr<FinalAttr>();
140bool isUniqueDefinition(
const NamedDecl *Decl) {
141 if (
auto *Func = dyn_cast<FunctionDecl>(Decl))
142 return Func->isThisDeclarationADefinition();
143 if (
auto *Klass = dyn_cast<CXXRecordDecl>(Decl))
144 return Klass->isThisDeclarationADefinition();
145 if (
auto *Iface = dyn_cast<ObjCInterfaceDecl>(Decl))
146 return Iface->isThisDeclarationADefinition();
147 if (
auto *Proto = dyn_cast<ObjCProtocolDecl>(Decl))
148 return Proto->isThisDeclarationADefinition();
149 if (
auto *Var = dyn_cast<VarDecl>(Decl))
150 return Var->isThisDeclarationADefinition();
151 return isa<TemplateTypeParmDecl>(Decl) ||
152 isa<NonTypeTemplateParmDecl>(Decl) ||
153 isa<TemplateTemplateParmDecl>(Decl) || isa<ObjCCategoryDecl>(Decl) ||
154 isa<ObjCImplDecl>(Decl);
159 return (1 <<
static_cast<unsigned>(ST));
164 const auto IsDef = isUniqueDefinition(&ND);
166 if (ND.isDeprecated())
184 if (not isa<UnresolvedUsingValueDecl>(ND)) {
194 switch (ND.getAccess()) {
213 std::vector<SymbolTag> Tags;
223 for (
unsigned I = MinTag; I <= MaxTag; ++I) {
232using ScoredSymbolInfo = std::pair<float, SymbolInformation>;
233struct ScoredSymbolGreater {
234 bool operator()(
const ScoredSymbolInfo &L,
const ScoredSymbolInfo &R) {
235 if (L.first != R.first)
236 return L.first > R.first;
237 return L.second.name < R.second.name;
242bool approximateScopeMatch(llvm::StringRef Scope, llvm::StringRef Query) {
243 assert(Scope.empty() || Scope.ends_with(
"::"));
244 assert(Query.empty() || Query.ends_with(
"::"));
245 while (!Scope.empty() && !Query.empty()) {
246 auto Colons = Scope.find(
"::");
247 assert(Colons != llvm::StringRef::npos);
249 llvm::StringRef LeadingSpecifier = Scope.slice(0, Colons + 2);
250 Scope = Scope.slice(Colons + 2, llvm::StringRef::npos);
251 Query.consume_front(LeadingSpecifier);
253 return Query.empty();
259 llvm::StringRef TUPath) {
262 return error(
"Could not resolve path for file '{0}': {1}", Loc.
FileURI,
271 L.
range = {Start, End};
276 llvm::StringRef TUPath) {
282llvm::Expected<std::vector<SymbolInformation>>
284 const SymbolIndex *
const Index, llvm::StringRef HintPath) {
285 std::vector<SymbolInformation> Result;
296 Req.
Query = std::string(Names.second);
299 auto HasLeadingColons = Names.first.consume_front(
"::");
303 if (HasLeadingColons || !Names.first.empty())
304 Req.
Scopes = {std::string(Names.first)};
313 Req.
Limit.value_or(std::numeric_limits<size_t>::max()));
317 ReqScope = Names.first](
const Symbol &Sym) {
318 llvm::StringRef Scope = Sym.Scope;
321 if (AnyScope && !approximateScopeMatch(Scope, ReqScope))
324 auto Loc = symbolToLocation(Sym, HintPath);
326 log(
"Workspace symbols: {0}", Loc.takeError());
336 Relevance.InBaseClass = AnyScope && Scope != ReqScope;
337 if (
auto NameMatch = Filter.
match(Sym.
Name))
338 Relevance.NameMatch = *NameMatch;
340 log(
"Workspace symbol: {0} didn't match query {1}", Sym.Name,
344 Relevance.merge(Sym);
345 auto QualScore = Quality.evaluateHeuristics();
346 auto RelScore = Relevance.evaluateHeuristics();
348 dlog(
"FindSymbols: {0}{1} = {2}\n{3}{4}\n", Sym.
Scope, Sym.
Name, Score,
354 Info.location = *Loc;
355 Scope.consume_back(
"::");
356 Info.containerName = Scope.str();
359 Info.score = Relevance.NameMatch > std::numeric_limits<float>::epsilon()
360 ? Score / Relevance.NameMatch
364 for (
auto &R : std::move(Top).items())
365 Result.push_back(std::move(R.second));
370std::string getSymbolName(ASTContext &Ctx,
const NamedDecl &ND) {
373 if (
const auto *Container = dyn_cast<ObjCContainerDecl>(&ND))
374 return printObjCContainer(*Container);
377 if (
const auto *Method = dyn_cast<ObjCMethodDecl>(&ND)) {
379 llvm::raw_string_ostream OS(Name);
381 OS << (Method->isInstanceMethod() ?
'-' :
'+');
382 Method->getSelector().print(OS);
389std::string getSymbolDetail(ASTContext &Ctx,
const NamedDecl &ND) {
390 PrintingPolicy
P(Ctx.getPrintingPolicy());
391 P.SuppressScope =
true;
392 P.SuppressUnwrittenScope =
true;
393 P.AnonymousTagNameStyle =
394 llvm::to_underlying(PrintingPolicy::AnonymousTagMode::Plain);
395 P.PolishForDeclaration =
true;
397 llvm::raw_string_ostream OS(Detail);
398 if (ND.getDescribedTemplateParams()) {
401 if (
const auto *VD = dyn_cast<ValueDecl>(&ND)) {
403 if (isa<CXXConstructorDecl>(VD)) {
404 std::string ConstructorType = VD->getType().getAsString(P);
406 llvm::StringRef WithoutVoid = ConstructorType;
407 WithoutVoid.consume_front(
"void ");
409 }
else if (!isa<CXXDestructorDecl>(VD)) {
410 VD->getType().print(OS, P);
412 }
else if (
const auto *TD = dyn_cast<TagDecl>(&ND)) {
413 OS << TD->getKindName();
414 }
else if (isa<TypedefNameDecl>(&ND)) {
416 }
else if (isa<ConceptDecl>(&ND)) {
419 return std::move(OS.str());
422std::optional<DocumentSymbol> declToSym(ASTContext &Ctx,
const NamedDecl &ND) {
423 auto &SM = Ctx.getSourceManager();
425 SourceLocation BeginLoc = ND.getBeginLoc();
426 SourceLocation EndLoc = ND.getEndLoc();
427 const auto SymbolRange =
432 index::SymbolInfo SymInfo = index::getSymbolInfo(&ND);
438 SI.name = getSymbolName(Ctx, ND);
440 SI.deprecated = ND.isDeprecated();
443 SI.detail = getSymbolDetail(Ctx, ND);
446 SourceLocation NameLoc = ND.getLocation();
447 SourceLocation FallbackNameLoc;
448 if (NameLoc.isMacroID()) {
451 FallbackNameLoc = SM.getExpansionLoc(NameLoc);
452 NameLoc = SM.getSpellingLoc(NameLoc);
454 NameLoc = SM.getExpansionLoc(NameLoc);
457 auto ComputeSelectionRange = [&](SourceLocation L) -> Range {
460 SM, Lexer::getLocForEndOfToken(L, 0, SM, Ctx.getLangOpts()));
461 return Range{NameBegin, NameEnd};
464 SI.selectionRange = ComputeSelectionRange(NameLoc);
465 if (!SI.range.contains(SI.selectionRange) && FallbackNameLoc.isValid()) {
469 SI.selectionRange = ComputeSelectionRange(FallbackNameLoc);
471 if (!SI.range.contains(SI.selectionRange)) {
474 SI.range = SI.selectionRange;
487class DocumentOutline {
493 DocumentSymbol Symbol;
496 llvm::SmallVector<SourceLocation> EnclosingMacroLoc;
499 DocumentSymbol build() && {
500 for (SymBuilder &C : Children) {
501 Symbol.children.push_back(std::move(C).build());
507 std::min(Symbol.range.start, Symbol.children.back().range.start);
509 std::max(Symbol.range.end, Symbol.children.back().range.end);
511 return std::move(Symbol);
515 SymBuilder &
addChild(DocumentSymbol S) {
517 Children.back().EnclosingMacroLoc = EnclosingMacroLoc;
518 Children.back().Symbol = std::move(S);
528 SymBuilder &inMacro(
const syntax::Token &Tok,
const SourceManager &SM,
529 std::optional<syntax::TokenBuffer::Expansion> Exp) {
530 if (llvm::is_contained(EnclosingMacroLoc, Tok.location()))
534 Children.back().EnclosingMacroLoc.back() == Tok.location())
538 Sym.name = Tok.text(SM).str();
539 Sym.kind = SymbolKind::Null;
540 Sym.range = Sym.selectionRange =
547 Exp->Spelled.front().location(),
548 Exp->Spelled.back().endLocation()));
550 llvm::raw_string_ostream OS(Sym.detail);
551 const syntax::Token *Prev =
nullptr;
552 for (
const auto &Tok : Exp->Spelled.drop_front()) {
554 if (OS.tell() > 80) {
558 if (Prev && Prev->endLocation() != Tok.location())
564 SymBuilder &Child =
addChild(std::move(Sym));
565 Child.EnclosingMacroLoc.push_back(Tok.location());
571 DocumentOutline(ParsedAST &AST) :
AST(
AST) {}
574 std::vector<DocumentSymbol> build() {
576 for (
auto &TopLevel :
AST.getLocalTopLevelDecls())
577 traverseDecl(TopLevel, Root);
578 return std::move(std::move(Root).build().children);
582 enum class VisitKind {
No, OnlyDecl, OnlyChildren, DeclAndChildren };
584 void traverseDecl(Decl *D, SymBuilder &Parent) {
589 if (
auto *Templ = llvm::dyn_cast<TemplateDecl>(D)) {
591 if (
auto *TD = Templ->getTemplatedDecl())
598 if (
auto *Friend = llvm::dyn_cast<FriendDecl>(D)) {
600 llvm::dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl())) {
601 if (Func->isThisDeclarationADefinition())
606 VisitKind Visit = shouldVisit(D);
607 if (Visit == VisitKind::No)
610 if (Visit == VisitKind::OnlyChildren)
611 return traverseChildren(D, Parent);
613 auto *ND = llvm::cast<NamedDecl>(D);
614 auto Sym = declToSym(
AST.getASTContext(), *ND);
617 SymBuilder &MacroParent = possibleMacroContainer(
D->getLocation(), Parent);
618 SymBuilder &Child = MacroParent.addChild(std::move(*Sym));
620 if (Visit == VisitKind::OnlyDecl)
623 assert(Visit == VisitKind::DeclAndChildren &&
"Unexpected VisitKind");
624 traverseChildren(ND, Child);
642 SymBuilder &possibleMacroContainer(SourceLocation TargetLoc,
643 SymBuilder &Parent) {
644 const auto &SM =
AST.getSourceManager();
647 SymBuilder *CurParent = &Parent;
648 for (SourceLocation Loc = TargetLoc; Loc.isMacroID();
649 Loc = SM.getImmediateMacroCallerLoc(Loc)) {
652 if (SM.isMacroArgExpansion(Loc)) {
654 MacroBody = SM.getFileID(SM.getImmediateExpansionRange(Loc).getBegin());
657 MacroBody = SM.getFileID(Loc);
661 SourceLocation MacroName =
662 SM.getSLocEntry(MacroBody).getExpansion().getExpansionLocStart();
665 if (!MacroName.isValid() || !MacroName.isFileID())
668 if (
auto *Tok =
AST.getTokens().spelledTokenContaining(MacroName))
669 CurParent = &CurParent->inMacro(
670 *Tok, SM,
AST.getTokens().expansionStartingAt(Tok));
675 void traverseChildren(Decl *D, SymBuilder &Builder) {
676 auto *Scope = llvm::dyn_cast<DeclContext>(D);
679 for (
auto *C : Scope->decls())
680 traverseDecl(C, Builder);
683 VisitKind shouldVisit(Decl *D) {
685 return VisitKind::No;
687 if (llvm::isa<LinkageSpecDecl>(D) || llvm::isa<ExportDecl>(D))
688 return VisitKind::OnlyChildren;
690 if (!llvm::isa<NamedDecl>(D))
691 return VisitKind::No;
693 if (
auto *Func = llvm::dyn_cast<FunctionDecl>(D)) {
696 if (
auto *Info = Func->getTemplateSpecializationInfo()) {
697 if (!
Info->isExplicitInstantiationOrSpecialization())
698 return VisitKind::No;
702 return VisitKind::OnlyDecl;
712 if (
auto *TemplSpec = llvm::dyn_cast<ClassTemplateSpecializationDecl>(D)) {
713 if (TemplSpec->isExplicitInstantiationOrSpecialization())
714 return TemplSpec->isExplicitSpecialization()
715 ? VisitKind::DeclAndChildren
716 : VisitKind::OnlyDecl;
717 return VisitKind::No;
719 if (
auto *TemplSpec = llvm::dyn_cast<VarTemplateSpecializationDecl>(D)) {
720 if (TemplSpec->isExplicitInstantiationOrSpecialization())
721 return TemplSpec->isExplicitSpecialization()
722 ? VisitKind::DeclAndChildren
723 : VisitKind::OnlyDecl;
724 return VisitKind::No;
727 return VisitKind::DeclAndChildren;
733struct PragmaMarkSymbol {
734 DocumentSymbol DocSym;
740void mergePragmas(DocumentSymbol &Root, ArrayRef<PragmaMarkSymbol> Pragmas) {
741 while (!Pragmas.empty()) {
743 PragmaMarkSymbol
P = std::move(Pragmas.front());
744 Pragmas = Pragmas.drop_front();
745 DocumentSymbol *Cur = &Root;
746 while (Cur->range.contains(
P.DocSym.range)) {
747 bool Swapped =
false;
748 for (
auto &C : Cur->children) {
751 if (
C.range.contains(
P.DocSym.range)) {
763 Cur->children.emplace_back(std::move(
P.DocSym));
774 bool TerminatedByNextPragma =
false;
775 for (
auto &NextPragma : Pragmas) {
777 if (!Cur->range.contains(NextPragma.DocSym.range))
782 if (llvm::any_of(Cur->children, [&NextPragma](
const auto &Child) {
783 return Child.range.contains(NextPragma.DocSym.range);
788 auto It = llvm::partition(Cur->children,
789 [&P, &NextPragma](
const auto &S) ->
bool {
790 return !(P.DocSym.range < S.range &&
791 S.range < NextPragma.DocSym.range);
793 P.DocSym.children.assign(make_move_iterator(It),
794 make_move_iterator(Cur->children.end()));
795 Cur->children.erase(It, Cur->children.end());
796 TerminatedByNextPragma =
true;
799 if (!TerminatedByNextPragma) {
802 auto It = llvm::partition(Cur->children, [&P](
const auto &S) ->
bool {
803 return !(P.DocSym.range < S.range);
805 P.DocSym.children.assign(make_move_iterator(It),
806 make_move_iterator(Cur->children.end()));
807 Cur->children.erase(It, Cur->children.end());
810 for (DocumentSymbol &Sym :
P.DocSym.children)
812 Cur->children.emplace_back(std::move(
P.DocSym));
816PragmaMarkSymbol markToSymbol(
const PragmaMark &P) {
817 StringRef Name = StringRef(
P.Trivia).trim();
818 bool IsGroup =
false;
825 StringRef MaybeGroupName = Name;
826 if (MaybeGroupName.consume_front(
"-") &&
827 (MaybeGroupName.ltrim() != MaybeGroupName || MaybeGroupName.empty())) {
828 Name = MaybeGroupName.empty() ?
"(unnamed group)" : MaybeGroupName.ltrim();
830 }
else if (Name.empty()) {
831 Name =
"(unnamed mark)";
834 Sym.name = Name.str();
835 Sym.kind = SymbolKind::File;
837 Sym.selectionRange =
P.Rng;
838 return {Sym, IsGroup};
841std::vector<DocumentSymbol> collectDocSymbols(ParsedAST &AST) {
842 std::vector<DocumentSymbol> Syms = DocumentOutline(AST).build();
844 const auto &PragmaMarks =
AST.getMarks();
845 if (PragmaMarks.empty())
848 std::vector<PragmaMarkSymbol> Pragmas;
849 Pragmas.reserve(PragmaMarks.size());
850 for (
const auto &P : PragmaMarks)
851 Pragmas.push_back(markToSymbol(P));
854 {std::numeric_limits<int>::max(), std::numeric_limits<int>::max()}};
856 Root.children = std::move(Syms);
857 Root.range = EntireFile;
858 mergePragmas(Root, llvm::ArrayRef(Pragmas));
859 return Root.children;
865 return collectDocSymbols(
AST);
clang::find_all_symbols::SymbolInfo::SymbolKind SymbolKind
std::optional< float > match(llvm::StringRef Word)
Stores and provides access to parsed AST.
Interface for symbol indexes that can be used for searching or matching symbols among a set of symbol...
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.
bool push(value_type &&V)
static llvm::Expected< std::string > resolve(const URI &U, llvm::StringRef HintPath="")
Resolves the absolute path of U.
std::pair< StringRef, StringRef > splitQualifiedName(StringRef QName)
llvm::Expected< Location > indexToLSPLocation(const SymbolLocation &Loc, llvm::StringRef TUPath)
Ensure we have enough bits to represent all SymbolTag values.
@ Info
An information message.
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.
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.
SymbolTag
Symbol tags are extra annotations that can be attached to a symbol.
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)
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.
std::string Path
A typedef to represent a file path.
std::vector< SymbolTag > getSymbolTags(const NamedDecl &ND)
Returns the symbol tags for the given declaration.
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)
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.
SymbolTags computeSymbolTags(const NamedDecl &ND)
Computes symbol tags for a given NamedDecl.
void addChild(NamespaceInfo *I, FunctionInfo &&R)
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.
std::string Query
A query string for the fuzzy find.
bool AnyScope
If set to true, allow symbols from any scope.
std::optional< uint32_t > Limit
The number of top candidates to return.
URIForFile uri
The text document's URI.
int line
Line position in a document (zero-based).
int character
Character offset on a line in a document (zero-based).
Position Start
The symbol range, using half-open range [Start, End).
Attributes of a symbol that affect how much we like it.
void merge(const CodeCompletionResult &SemaCCResult)
Attributes of a symbol-query pair that affect how much we like it.
llvm::StringRef Name
The name of the symbol (for ContextWords). Must be explicitly assigned.
The class presents a C++ symbol, e.g.
SymbolLocation Definition
The location of the symbol's definition, if one was found.
index::SymbolInfo SymInfo
The symbol information, like symbol kind.
llvm::StringRef Name
The unqualified name of the symbol, e.g. "bar" (for ns::bar).
llvm::StringRef Scope
The containing namespace. e.g. "" (global), "ns::" (top-level namespace).
llvm::StringRef TemplateSpecializationArgs
Argument list in human-readable format, will be displayed to help disambiguate between different spec...
SymbolLocation CanonicalDeclaration
The location of the preferred declaration of the symbol.
static URIForFile canonicalize(llvm::StringRef AbsPath, llvm::StringRef TUPath)
Canonicalizes AbsPath via URI.