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"
28#define DEBUG_TYPE "FindSymbols"
34using ScoredSymbolInfo = std::pair<float, SymbolInformation>;
35struct ScoredSymbolGreater {
36 bool operator()(
const ScoredSymbolInfo &L,
const ScoredSymbolInfo &R) {
37 if (L.first != R.first)
38 return L.first > R.first;
39 return L.second.name < R.second.name;
44bool approximateScopeMatch(llvm::StringRef Scope, llvm::StringRef Query) {
45 assert(Scope.empty() || Scope.ends_with(
"::"));
46 assert(Query.empty() || Query.ends_with(
"::"));
47 while (!Scope.empty() && !Query.empty()) {
48 auto Colons = Scope.find(
"::");
49 assert(Colons != llvm::StringRef::npos);
51 llvm::StringRef LeadingSpecifier = Scope.slice(0, Colons + 2);
52 Scope = Scope.slice(Colons + 2, llvm::StringRef::npos);
53 Query.consume_front(LeadingSpecifier);
61 llvm::StringRef TUPath) {
64 return error(
"Could not resolve path for file '{0}': {1}", Loc.
FileURI,
73 L.
range = {Start, End};
78 llvm::StringRef TUPath) {
84llvm::Expected<std::vector<SymbolInformation>>
86 const SymbolIndex *
const Index, llvm::StringRef HintPath) {
87 std::vector<SymbolInformation> Result;
98 Req.
Query = std::string(Names.second);
101 auto HasLeadingColons = Names.first.consume_front(
"::");
105 if (HasLeadingColons || !Names.first.empty())
106 Req.
Scopes = {std::string(Names.first)};
115 Req.
Limit.value_or(std::numeric_limits<size_t>::max()));
119 ReqScope = Names.first](
const Symbol &Sym) {
120 llvm::StringRef Scope = Sym.Scope;
123 if (AnyScope && !approximateScopeMatch(Scope, ReqScope))
126 auto Loc = symbolToLocation(Sym, HintPath);
128 log(
"Workspace symbols: {0}", Loc.takeError());
138 Relevance.InBaseClass = AnyScope && Scope != ReqScope;
139 if (
auto NameMatch = Filter.
match(Sym.
Name))
140 Relevance.NameMatch = *NameMatch;
142 log(
"Workspace symbol: {0} didn't match query {1}", Sym.Name,
146 Relevance.merge(Sym);
147 auto QualScore = Quality.evaluateHeuristics();
148 auto RelScore = Relevance.evaluateHeuristics();
150 dlog(
"FindSymbols: {0}{1} = {2}\n{3}{4}\n", Sym.
Scope, Sym.
Name, Score,
156 Info.location = *Loc;
157 Scope.consume_back(
"::");
158 Info.containerName = Scope.str();
161 Info.score = Relevance.NameMatch > std::numeric_limits<float>::epsilon()
162 ? Score / Relevance.NameMatch
166 for (
auto &R : std::move(Top).items())
167 Result.push_back(std::move(R.second));
172std::string getSymbolName(ASTContext &Ctx,
const NamedDecl &ND) {
175 if (
const auto *Container = dyn_cast<ObjCContainerDecl>(&ND))
176 return printObjCContainer(*Container);
179 if (
const auto *Method = dyn_cast<ObjCMethodDecl>(&ND)) {
181 llvm::raw_string_ostream OS(Name);
183 OS << (Method->isInstanceMethod() ?
'-' :
'+');
184 Method->getSelector().print(OS);
191std::string getSymbolDetail(ASTContext &Ctx,
const NamedDecl &ND) {
192 PrintingPolicy
P(Ctx.getPrintingPolicy());
193 P.SuppressScope =
true;
194 P.SuppressUnwrittenScope =
true;
195 P.AnonymousTagLocations =
false;
196 P.PolishForDeclaration =
true;
198 llvm::raw_string_ostream OS(Detail);
199 if (ND.getDescribedTemplateParams()) {
202 if (
const auto *VD = dyn_cast<ValueDecl>(&ND)) {
204 if (isa<CXXConstructorDecl>(VD)) {
205 std::string ConstructorType = VD->getType().getAsString(P);
207 llvm::StringRef WithoutVoid = ConstructorType;
208 WithoutVoid.consume_front(
"void ");
210 }
else if (!isa<CXXDestructorDecl>(VD)) {
211 VD->getType().print(OS, P);
213 }
else if (
const auto *TD = dyn_cast<TagDecl>(&ND)) {
214 OS << TD->getKindName();
215 }
else if (isa<TypedefNameDecl>(&ND)) {
217 }
else if (isa<ConceptDecl>(&ND)) {
220 return std::move(OS.str());
223std::optional<DocumentSymbol> declToSym(ASTContext &Ctx,
const NamedDecl &ND) {
224 auto &SM = Ctx.getSourceManager();
226 SourceLocation BeginLoc = ND.getBeginLoc();
227 SourceLocation EndLoc = ND.getEndLoc();
228 const auto SymbolRange =
233 index::SymbolInfo SymInfo = index::getSymbolInfo(&ND);
239 SI.name = getSymbolName(Ctx, ND);
241 SI.deprecated = ND.isDeprecated();
244 SI.detail = getSymbolDetail(Ctx, ND);
246 SourceLocation NameLoc = ND.getLocation();
247 SourceLocation FallbackNameLoc;
248 if (NameLoc.isMacroID()) {
251 FallbackNameLoc = SM.getExpansionLoc(NameLoc);
252 NameLoc = SM.getSpellingLoc(NameLoc);
254 NameLoc = SM.getExpansionLoc(NameLoc);
257 auto ComputeSelectionRange = [&](SourceLocation L) -> Range {
260 SM, Lexer::getLocForEndOfToken(L, 0, SM, Ctx.getLangOpts()));
261 return Range{NameBegin, NameEnd};
264 SI.selectionRange = ComputeSelectionRange(NameLoc);
265 if (!SI.range.contains(SI.selectionRange) && FallbackNameLoc.isValid()) {
269 SI.selectionRange = ComputeSelectionRange(FallbackNameLoc);
271 if (!SI.range.contains(SI.selectionRange)) {
274 SI.range = SI.selectionRange;
287class DocumentOutline {
293 DocumentSymbol Symbol;
296 llvm::SmallVector<SourceLocation> EnclosingMacroLoc;
299 DocumentSymbol build() && {
300 for (SymBuilder &C : Children) {
301 Symbol.children.push_back(std::move(C).build());
307 std::min(Symbol.range.start, Symbol.children.back().range.start);
309 std::max(Symbol.range.end, Symbol.children.back().range.end);
311 return std::move(Symbol);
315 SymBuilder &
addChild(DocumentSymbol S) {
317 Children.back().EnclosingMacroLoc = EnclosingMacroLoc;
318 Children.back().Symbol = std::move(S);
328 SymBuilder &inMacro(
const syntax::Token &Tok,
const SourceManager &SM,
329 std::optional<syntax::TokenBuffer::Expansion> Exp) {
330 if (llvm::is_contained(EnclosingMacroLoc, Tok.location()))
334 Children.back().EnclosingMacroLoc.back() == Tok.location())
338 Sym.name = Tok.text(SM).str();
339 Sym.kind = SymbolKind::Null;
340 Sym.range = Sym.selectionRange =
347 Exp->Spelled.front().location(),
348 Exp->Spelled.back().endLocation()));
350 llvm::raw_string_ostream OS(Sym.detail);
351 const syntax::Token *Prev =
nullptr;
352 for (
const auto &Tok : Exp->Spelled.drop_front()) {
354 if (OS.tell() > 80) {
358 if (Prev && Prev->endLocation() != Tok.location())
364 SymBuilder &Child =
addChild(std::move(Sym));
365 Child.EnclosingMacroLoc.push_back(Tok.location());
371 DocumentOutline(ParsedAST &AST) :
AST(
AST) {}
374 std::vector<DocumentSymbol> build() {
376 for (
auto &TopLevel :
AST.getLocalTopLevelDecls())
377 traverseDecl(TopLevel, Root);
378 return std::move(std::move(Root).build().children);
382 enum class VisitKind {
No, OnlyDecl, OnlyChildren, DeclAndChildren };
384 void traverseDecl(Decl *D, SymBuilder &Parent) {
389 if (
auto *Templ = llvm::dyn_cast<TemplateDecl>(D)) {
391 if (
auto *TD = Templ->getTemplatedDecl())
398 if (
auto *Friend = llvm::dyn_cast<FriendDecl>(D)) {
400 llvm::dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl())) {
401 if (Func->isThisDeclarationADefinition())
406 VisitKind Visit = shouldVisit(D);
407 if (Visit == VisitKind::No)
410 if (Visit == VisitKind::OnlyChildren)
411 return traverseChildren(D, Parent);
413 auto *ND = llvm::cast<NamedDecl>(D);
414 auto Sym = declToSym(
AST.getASTContext(), *ND);
417 SymBuilder &MacroParent = possibleMacroContainer(
D->getLocation(), Parent);
418 SymBuilder &Child = MacroParent.addChild(std::move(*Sym));
420 if (Visit == VisitKind::OnlyDecl)
423 assert(Visit == VisitKind::DeclAndChildren &&
"Unexpected VisitKind");
424 traverseChildren(ND, Child);
442 SymBuilder &possibleMacroContainer(SourceLocation TargetLoc,
443 SymBuilder &Parent) {
444 const auto &SM =
AST.getSourceManager();
447 SymBuilder *CurParent = &Parent;
448 for (SourceLocation Loc = TargetLoc; Loc.isMacroID();
449 Loc = SM.getImmediateMacroCallerLoc(Loc)) {
452 if (SM.isMacroArgExpansion(Loc)) {
454 MacroBody = SM.getFileID(SM.getImmediateExpansionRange(Loc).getBegin());
457 MacroBody = SM.getFileID(Loc);
461 SourceLocation MacroName =
462 SM.getSLocEntry(MacroBody).getExpansion().getExpansionLocStart();
465 if (!MacroName.isValid() || !MacroName.isFileID())
468 if (
auto *Tok =
AST.getTokens().spelledTokenContaining(MacroName))
469 CurParent = &CurParent->inMacro(
470 *Tok, SM,
AST.getTokens().expansionStartingAt(Tok));
475 void traverseChildren(Decl *D, SymBuilder &Builder) {
476 auto *Scope = llvm::dyn_cast<DeclContext>(D);
479 for (
auto *C : Scope->decls())
480 traverseDecl(C, Builder);
483 VisitKind shouldVisit(Decl *D) {
485 return VisitKind::No;
487 if (llvm::isa<LinkageSpecDecl>(D) || llvm::isa<ExportDecl>(D))
488 return VisitKind::OnlyChildren;
490 if (!llvm::isa<NamedDecl>(D))
491 return VisitKind::No;
493 if (
auto *Func = llvm::dyn_cast<FunctionDecl>(D)) {
496 if (
auto *Info = Func->getTemplateSpecializationInfo()) {
497 if (!
Info->isExplicitInstantiationOrSpecialization())
498 return VisitKind::No;
502 return VisitKind::OnlyDecl;
512 if (
auto *TemplSpec = llvm::dyn_cast<ClassTemplateSpecializationDecl>(D)) {
513 if (TemplSpec->isExplicitInstantiationOrSpecialization())
514 return TemplSpec->isExplicitSpecialization()
515 ? VisitKind::DeclAndChildren
516 : VisitKind::OnlyDecl;
517 return VisitKind::No;
519 if (
auto *TemplSpec = llvm::dyn_cast<VarTemplateSpecializationDecl>(D)) {
520 if (TemplSpec->isExplicitInstantiationOrSpecialization())
521 return TemplSpec->isExplicitSpecialization()
522 ? VisitKind::DeclAndChildren
523 : VisitKind::OnlyDecl;
524 return VisitKind::No;
527 return VisitKind::DeclAndChildren;
533struct PragmaMarkSymbol {
534 DocumentSymbol DocSym;
540void mergePragmas(DocumentSymbol &Root, ArrayRef<PragmaMarkSymbol> Pragmas) {
541 while (!Pragmas.empty()) {
543 PragmaMarkSymbol
P = std::move(Pragmas.front());
544 Pragmas = Pragmas.drop_front();
545 DocumentSymbol *Cur = &Root;
546 while (Cur->range.contains(
P.DocSym.range)) {
547 bool Swapped =
false;
548 for (
auto &C : Cur->children) {
551 if (
C.range.contains(
P.DocSym.range)) {
563 Cur->children.emplace_back(std::move(
P.DocSym));
574 bool TerminatedByNextPragma =
false;
575 for (
auto &NextPragma : Pragmas) {
577 if (!Cur->range.contains(NextPragma.DocSym.range))
582 if (llvm::any_of(Cur->children, [&NextPragma](
const auto &Child) {
583 return Child.range.contains(NextPragma.DocSym.range);
588 auto It = llvm::partition(Cur->children,
589 [&P, &NextPragma](
const auto &S) ->
bool {
590 return !(P.DocSym.range < S.range &&
591 S.range < NextPragma.DocSym.range);
593 P.DocSym.children.assign(make_move_iterator(It),
594 make_move_iterator(Cur->children.end()));
595 Cur->children.erase(It, Cur->children.end());
596 TerminatedByNextPragma =
true;
599 if (!TerminatedByNextPragma) {
602 auto It = llvm::partition(Cur->children, [&P](
const auto &S) ->
bool {
603 return !(P.DocSym.range < S.range);
605 P.DocSym.children.assign(make_move_iterator(It),
606 make_move_iterator(Cur->children.end()));
607 Cur->children.erase(It, Cur->children.end());
610 for (DocumentSymbol &Sym :
P.DocSym.children)
612 Cur->children.emplace_back(std::move(
P.DocSym));
616PragmaMarkSymbol markToSymbol(
const PragmaMark &P) {
617 StringRef Name = StringRef(
P.Trivia).trim();
618 bool IsGroup =
false;
625 StringRef MaybeGroupName = Name;
626 if (MaybeGroupName.consume_front(
"-") &&
627 (MaybeGroupName.ltrim() != MaybeGroupName || MaybeGroupName.empty())) {
628 Name = MaybeGroupName.empty() ?
"(unnamed group)" : MaybeGroupName.ltrim();
630 }
else if (Name.empty()) {
631 Name =
"(unnamed mark)";
634 Sym.name = Name.str();
635 Sym.kind = SymbolKind::File;
637 Sym.selectionRange =
P.Rng;
638 return {Sym, IsGroup};
641std::vector<DocumentSymbol> collectDocSymbols(ParsedAST &AST) {
642 std::vector<DocumentSymbol> Syms = DocumentOutline(AST).build();
644 const auto &PragmaMarks =
AST.getMarks();
645 if (PragmaMarks.empty())
648 std::vector<PragmaMarkSymbol> Pragmas;
649 Pragmas.reserve(PragmaMarks.size());
650 for (
const auto &P : PragmaMarks)
651 Pragmas.push_back(markToSymbol(P));
654 {std::numeric_limits<int>::max(), std::numeric_limits<int>::max()}};
656 Root.children = std::move(Syms);
657 Root.range = EntireFile;
658 mergePragmas(Root, llvm::ArrayRef(Pragmas));
659 return Root.children;
665 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)
Helper function for deriving an LSP Location from an index SymbolLocation.
@ 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.
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.
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.
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.
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.
void addChild(NamespaceInfo *I, FunctionInfo &&R)
cppcoreguidelines::ProBoundsAvoidUncheckedContainerAccess 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.