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.AnonymousTagLocations =
false;
394 P.PolishForDeclaration =
true;
396 llvm::raw_string_ostream OS(Detail);
397 if (ND.getDescribedTemplateParams()) {
400 if (
const auto *VD = dyn_cast<ValueDecl>(&ND)) {
402 if (isa<CXXConstructorDecl>(VD)) {
403 std::string ConstructorType = VD->getType().getAsString(P);
405 llvm::StringRef WithoutVoid = ConstructorType;
406 WithoutVoid.consume_front(
"void ");
408 }
else if (!isa<CXXDestructorDecl>(VD)) {
409 VD->getType().print(OS, P);
411 }
else if (
const auto *TD = dyn_cast<TagDecl>(&ND)) {
412 OS << TD->getKindName();
413 }
else if (isa<TypedefNameDecl>(&ND)) {
415 }
else if (isa<ConceptDecl>(&ND)) {
418 return std::move(OS.str());
421std::optional<DocumentSymbol> declToSym(ASTContext &Ctx,
const NamedDecl &ND) {
422 auto &SM = Ctx.getSourceManager();
424 SourceLocation BeginLoc = ND.getBeginLoc();
425 SourceLocation EndLoc = ND.getEndLoc();
426 const auto SymbolRange =
431 index::SymbolInfo SymInfo = index::getSymbolInfo(&ND);
437 SI.name = getSymbolName(Ctx, ND);
439 SI.deprecated = ND.isDeprecated();
442 SI.detail = getSymbolDetail(Ctx, ND);
445 SourceLocation NameLoc = ND.getLocation();
446 SourceLocation FallbackNameLoc;
447 if (NameLoc.isMacroID()) {
450 FallbackNameLoc = SM.getExpansionLoc(NameLoc);
451 NameLoc = SM.getSpellingLoc(NameLoc);
453 NameLoc = SM.getExpansionLoc(NameLoc);
456 auto ComputeSelectionRange = [&](SourceLocation L) -> Range {
459 SM, Lexer::getLocForEndOfToken(L, 0, SM, Ctx.getLangOpts()));
460 return Range{NameBegin, NameEnd};
463 SI.selectionRange = ComputeSelectionRange(NameLoc);
464 if (!SI.range.contains(SI.selectionRange) && FallbackNameLoc.isValid()) {
468 SI.selectionRange = ComputeSelectionRange(FallbackNameLoc);
470 if (!SI.range.contains(SI.selectionRange)) {
473 SI.range = SI.selectionRange;
486class DocumentOutline {
492 DocumentSymbol Symbol;
495 llvm::SmallVector<SourceLocation> EnclosingMacroLoc;
498 DocumentSymbol build() && {
499 for (SymBuilder &C : Children) {
500 Symbol.children.push_back(std::move(C).build());
506 std::min(Symbol.range.start, Symbol.children.back().range.start);
508 std::max(Symbol.range.end, Symbol.children.back().range.end);
510 return std::move(Symbol);
514 SymBuilder &
addChild(DocumentSymbol S) {
516 Children.back().EnclosingMacroLoc = EnclosingMacroLoc;
517 Children.back().Symbol = std::move(S);
527 SymBuilder &inMacro(
const syntax::Token &Tok,
const SourceManager &SM,
528 std::optional<syntax::TokenBuffer::Expansion> Exp) {
529 if (llvm::is_contained(EnclosingMacroLoc, Tok.location()))
533 Children.back().EnclosingMacroLoc.back() == Tok.location())
537 Sym.name = Tok.text(SM).str();
538 Sym.kind = SymbolKind::Null;
539 Sym.range = Sym.selectionRange =
546 Exp->Spelled.front().location(),
547 Exp->Spelled.back().endLocation()));
549 llvm::raw_string_ostream OS(Sym.detail);
550 const syntax::Token *Prev =
nullptr;
551 for (
const auto &Tok : Exp->Spelled.drop_front()) {
553 if (OS.tell() > 80) {
557 if (Prev && Prev->endLocation() != Tok.location())
563 SymBuilder &Child =
addChild(std::move(Sym));
564 Child.EnclosingMacroLoc.push_back(Tok.location());
570 DocumentOutline(ParsedAST &AST) :
AST(
AST) {}
573 std::vector<DocumentSymbol> build() {
575 for (
auto &TopLevel :
AST.getLocalTopLevelDecls())
576 traverseDecl(TopLevel, Root);
577 return std::move(std::move(Root).build().children);
581 enum class VisitKind {
No, OnlyDecl, OnlyChildren, DeclAndChildren };
583 void traverseDecl(Decl *D, SymBuilder &Parent) {
588 if (
auto *Templ = llvm::dyn_cast<TemplateDecl>(D)) {
590 if (
auto *TD = Templ->getTemplatedDecl())
597 if (
auto *Friend = llvm::dyn_cast<FriendDecl>(D)) {
599 llvm::dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl())) {
600 if (Func->isThisDeclarationADefinition())
605 VisitKind Visit = shouldVisit(D);
606 if (Visit == VisitKind::No)
609 if (Visit == VisitKind::OnlyChildren)
610 return traverseChildren(D, Parent);
612 auto *ND = llvm::cast<NamedDecl>(D);
613 auto Sym = declToSym(
AST.getASTContext(), *ND);
616 SymBuilder &MacroParent = possibleMacroContainer(
D->getLocation(), Parent);
617 SymBuilder &Child = MacroParent.addChild(std::move(*Sym));
619 if (Visit == VisitKind::OnlyDecl)
622 assert(Visit == VisitKind::DeclAndChildren &&
"Unexpected VisitKind");
623 traverseChildren(ND, Child);
641 SymBuilder &possibleMacroContainer(SourceLocation TargetLoc,
642 SymBuilder &Parent) {
643 const auto &SM =
AST.getSourceManager();
646 SymBuilder *CurParent = &Parent;
647 for (SourceLocation Loc = TargetLoc; Loc.isMacroID();
648 Loc = SM.getImmediateMacroCallerLoc(Loc)) {
651 if (SM.isMacroArgExpansion(Loc)) {
653 MacroBody = SM.getFileID(SM.getImmediateExpansionRange(Loc).getBegin());
656 MacroBody = SM.getFileID(Loc);
660 SourceLocation MacroName =
661 SM.getSLocEntry(MacroBody).getExpansion().getExpansionLocStart();
664 if (!MacroName.isValid() || !MacroName.isFileID())
667 if (
auto *Tok =
AST.getTokens().spelledTokenContaining(MacroName))
668 CurParent = &CurParent->inMacro(
669 *Tok, SM,
AST.getTokens().expansionStartingAt(Tok));
674 void traverseChildren(Decl *D, SymBuilder &Builder) {
675 auto *Scope = llvm::dyn_cast<DeclContext>(D);
678 for (
auto *C : Scope->decls())
679 traverseDecl(C, Builder);
682 VisitKind shouldVisit(Decl *D) {
684 return VisitKind::No;
686 if (llvm::isa<LinkageSpecDecl>(D) || llvm::isa<ExportDecl>(D))
687 return VisitKind::OnlyChildren;
689 if (!llvm::isa<NamedDecl>(D))
690 return VisitKind::No;
692 if (
auto *Func = llvm::dyn_cast<FunctionDecl>(D)) {
695 if (
auto *Info = Func->getTemplateSpecializationInfo()) {
696 if (!
Info->isExplicitInstantiationOrSpecialization())
697 return VisitKind::No;
701 return VisitKind::OnlyDecl;
711 if (
auto *TemplSpec = llvm::dyn_cast<ClassTemplateSpecializationDecl>(D)) {
712 if (TemplSpec->isExplicitInstantiationOrSpecialization())
713 return TemplSpec->isExplicitSpecialization()
714 ? VisitKind::DeclAndChildren
715 : VisitKind::OnlyDecl;
716 return VisitKind::No;
718 if (
auto *TemplSpec = llvm::dyn_cast<VarTemplateSpecializationDecl>(D)) {
719 if (TemplSpec->isExplicitInstantiationOrSpecialization())
720 return TemplSpec->isExplicitSpecialization()
721 ? VisitKind::DeclAndChildren
722 : VisitKind::OnlyDecl;
723 return VisitKind::No;
726 return VisitKind::DeclAndChildren;
732struct PragmaMarkSymbol {
733 DocumentSymbol DocSym;
739void mergePragmas(DocumentSymbol &Root, ArrayRef<PragmaMarkSymbol> Pragmas) {
740 while (!Pragmas.empty()) {
742 PragmaMarkSymbol
P = std::move(Pragmas.front());
743 Pragmas = Pragmas.drop_front();
744 DocumentSymbol *Cur = &Root;
745 while (Cur->range.contains(
P.DocSym.range)) {
746 bool Swapped =
false;
747 for (
auto &C : Cur->children) {
750 if (
C.range.contains(
P.DocSym.range)) {
762 Cur->children.emplace_back(std::move(
P.DocSym));
773 bool TerminatedByNextPragma =
false;
774 for (
auto &NextPragma : Pragmas) {
776 if (!Cur->range.contains(NextPragma.DocSym.range))
781 if (llvm::any_of(Cur->children, [&NextPragma](
const auto &Child) {
782 return Child.range.contains(NextPragma.DocSym.range);
787 auto It = llvm::partition(Cur->children,
788 [&P, &NextPragma](
const auto &S) ->
bool {
789 return !(P.DocSym.range < S.range &&
790 S.range < NextPragma.DocSym.range);
792 P.DocSym.children.assign(make_move_iterator(It),
793 make_move_iterator(Cur->children.end()));
794 Cur->children.erase(It, Cur->children.end());
795 TerminatedByNextPragma =
true;
798 if (!TerminatedByNextPragma) {
801 auto It = llvm::partition(Cur->children, [&P](
const auto &S) ->
bool {
802 return !(P.DocSym.range < S.range);
804 P.DocSym.children.assign(make_move_iterator(It),
805 make_move_iterator(Cur->children.end()));
806 Cur->children.erase(It, Cur->children.end());
809 for (DocumentSymbol &Sym :
P.DocSym.children)
811 Cur->children.emplace_back(std::move(
P.DocSym));
815PragmaMarkSymbol markToSymbol(
const PragmaMark &P) {
816 StringRef Name = StringRef(
P.Trivia).trim();
817 bool IsGroup =
false;
824 StringRef MaybeGroupName = Name;
825 if (MaybeGroupName.consume_front(
"-") &&
826 (MaybeGroupName.ltrim() != MaybeGroupName || MaybeGroupName.empty())) {
827 Name = MaybeGroupName.empty() ?
"(unnamed group)" : MaybeGroupName.ltrim();
829 }
else if (Name.empty()) {
830 Name =
"(unnamed mark)";
833 Sym.name = Name.str();
834 Sym.kind = SymbolKind::File;
836 Sym.selectionRange =
P.Rng;
837 return {Sym, IsGroup};
840std::vector<DocumentSymbol> collectDocSymbols(ParsedAST &AST) {
841 std::vector<DocumentSymbol> Syms = DocumentOutline(AST).build();
843 const auto &PragmaMarks =
AST.getMarks();
844 if (PragmaMarks.empty())
847 std::vector<PragmaMarkSymbol> Pragmas;
848 Pragmas.reserve(PragmaMarks.size());
849 for (
const auto &P : PragmaMarks)
850 Pragmas.push_back(markToSymbol(P));
853 {std::numeric_limits<int>::max(), std::numeric_limits<int>::max()}};
855 Root.children = std::move(Syms);
856 Root.range = EntireFile;
857 mergePragmas(Root, llvm::ArrayRef(Pragmas));
858 return Root.children;
864 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...
SymbolKind indexSymbolKindToSymbolKind(index::SymbolKind Kind)
@ 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.
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.