Debian Codegraph @

gopls/internal/golang/workspace_symbol.go

raw symbols SCIP
1 // Copyright 2020 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package golang
6
7 import (
8 "cmp"
9 "context"
10 "fmt"
11 "path/filepath"
12 "runtime"
13 "slices"
14 "sort"
15 "strings"
16 "unicode"
17
18 "golang.org/x/tools/gopls/internal/cache"
19 "golang.org/x/tools/gopls/internal/cache/metadata"
20 "golang.org/x/tools/gopls/internal/cache/symbols"
21 "golang.org/x/tools/gopls/internal/fuzzy"
22 "golang.org/x/tools/gopls/internal/protocol"
23 "golang.org/x/tools/gopls/internal/settings"
24 "golang.org/x/tools/internal/event"
25 )
26
27 // maxSymbols defines the maximum number of symbol results that should ever be
28 // sent in response to a client.
29 const maxSymbols = 100
30
31 // WorkspaceSymbolsOptions defines optional parameters of the [WorkspaceSymbols]
32 // function.
33 type WorkspaceSymbolsOptions struct {
34 // Filter is an optional predicate used to exclude symbols from the result.
35 //
36 // Note: The standard LSP 'workspace/symbol' request does not currently
37 // support server-side filtering. Clients are expected to receive all
38 // matches and filter locally. This field is intended for internal or
39 // experimental use (see microsoft/language-server-protocol#941).
40 Filter SymbolFilter
41
42 // Matcher determines how well a symbol string matches a query.
43 //
44 // It must return a non-negative score indicating the quality of the match,
45 // where a score of 0 indicates no match.
46 Matcher settings.SymbolMatcher
47
48 // Style controls how the symbol's name is formatted and extracted.
49 //
50 // This determines the string representation (e.g., fully qualified vs.
51 // package-qualified) used for both matching against the query and for
52 // the final presentation.
53 Style settings.SymbolStyle
54 }
55
56 // SymbolFilter returns whether the symbol we want to keep.
57 type SymbolFilter func(sym symbols.Symbol) bool
58
59 // WorkspaceSymbols matches symbols across all views using the given query,
60 // according to the match semantics parameterized by matcherType and style.
61 //
62 // The workspace symbol method is defined in the spec as follows:
63 //
64 // The workspace symbol request is sent from the client to the server to
65 // list project-wide symbols matching the query string.
66 //
67 // It is unclear what "project-wide" means here, but given the parameters of
68 // workspace/symbol do not include any workspace identifier, then it has to be
69 // assumed that "project-wide" means "across all workspaces". Hence why
70 // WorkspaceSymbols receives the views []View.
71 //
72 // However, it then becomes unclear what it would mean to call WorkspaceSymbols
73 // with a different configured SymbolMatcher per View. Therefore we assume that
74 // Session level configuration will define the SymbolMatcher to be used for the
75 // WorkspaceSymbols method.
76 func WorkspaceSymbols(ctx context.Context, snapshots []*cache.Snapshot, query string, opts WorkspaceSymbolsOptions) ([]protocol.SymbolInformation, error) {
77 ctx, done := event.Start(ctx, "golang.WorkspaceSymbols")
78 defer done()
79 if query == "" {
80 return nil, nil
81 }
82
83 return collectSymbols(ctx, snapshots, query, opts)
84 }
85
86 // A matcherFunc returns the index and score of a symbol match.
87 //
88 // See the comment for symbolCollector for more information.
89 type matcherFunc func(chunks []string) (int, float64)
90
91 // A symbolizer returns the best symbol match for a name with pkg, according to
92 // some heuristic. The symbol name is passed as the slice nameParts of logical
93 // name pieces. For example, for myType.field the caller can pass either
94 // []string{"myType.field"} or []string{"myType.", "field"}.
95 //
96 // See the comment for symbolCollector for more information.
97 //
98 // The space argument is an empty slice with spare capacity that may be used
99 // to allocate the result.
100 type symbolizer func(space []string, name string, pkg *metadata.Package, m matcherFunc) ([]string, float64)
101
102 func fullyQualifiedSymbolMatch(space []string, name string, pkg *metadata.Package, matcher matcherFunc) ([]string, float64) {
103 if _, score := dynamicSymbolMatch(space, name, pkg, matcher); score > 0 {
104 return append(space, string(pkg.PkgPath), ".", name), score
105 }
106 return nil, 0
107 }
108
109 func dynamicSymbolMatch(space []string, name string, pkg *metadata.Package, matcher matcherFunc) ([]string, float64) {
110 if metadata.IsCommandLineArguments(pkg.ID) {
111 // command-line-arguments packages have a non-sensical package path, so
112 // just use their package name.
113 return packageSymbolMatch(space, name, pkg, matcher)
114 }
115
116 var score float64
117
118 endsInPkgName := strings.HasSuffix(string(pkg.PkgPath), string(pkg.Name))
119
120 // If the package path does not end in the package name, we need to check the
121 // package-qualified symbol as an extra pass first.
122 if !endsInPkgName {
123 pkgQualified := append(space, string(pkg.Name), ".", name)
124 idx, score := matcher(pkgQualified)
125 nameStart := len(pkg.Name) + 1
126 if score > 0 {
127 // If our match is contained entirely within the unqualified portion,
128 // just return that.
129 if idx >= nameStart {
130 return append(space, name), score
131 }
132 // Lower the score for matches that include the package name.
133 return pkgQualified, score * 0.8
134 }
135 }
136
137 // Now try matching the fully qualified symbol.
138 fullyQualified := append(space, string(pkg.PkgPath), ".", name)
139 idx, score := matcher(fullyQualified)
140
141 // As above, check if we matched just the unqualified symbol name.
142 nameStart := len(pkg.PkgPath) + 1
143 if idx >= nameStart {
144 return append(space, name), score
145 }
146
147 // If our package path ends in the package name, we'll have skipped the
148 // initial pass above, so check if we matched just the package-qualified
149 // name.
150 if endsInPkgName && idx >= 0 {
151 pkgStart := len(pkg.PkgPath) - len(pkg.Name)
152 if idx >= pkgStart {
153 return append(space, string(pkg.Name), ".", name), score
154 }
155 }
156
157 // Our match was not contained within the unqualified or package qualified
158 // symbol. Return the fully qualified symbol but discount the score.
159 return fullyQualified, score * 0.6
160 }
161
162 func packageSymbolMatch(space []string, name string, pkg *metadata.Package, matcher matcherFunc) ([]string, float64) {
163 qualified := append(space, string(pkg.Name), ".", name)
164 if _, s := matcher(qualified); s > 0 {
165 return qualified, s
166 }
167 return nil, 0
168 }
169
170 func buildMatcher(matcher settings.SymbolMatcher, query string) matcherFunc {
171 switch matcher {
172 case settings.SymbolFuzzy:
173 return parseQuery(query, newFuzzyMatcher)
174 case settings.SymbolFastFuzzy:
175 return parseQuery(query, func(query string) matcherFunc {
176 return fuzzy.NewSymbolMatcher(query).Match
177 })
178 case settings.SymbolCaseSensitive:
179 return matchExact(query)
180 case settings.SymbolCaseInsensitive:
181 q := strings.ToLower(query)
182 exact := matchExact(q)
183 wrapper := []string{""}
184 return func(chunks []string) (int, float64) {
185 s := strings.Join(chunks, "")
186 wrapper[0] = strings.ToLower(s)
187 return exact(wrapper)
188 }
189 }
190 panic(fmt.Errorf("unknown symbol matcher: %v", matcher))
191 }
192
193 func newFuzzyMatcher(query string) matcherFunc {
194 fm := fuzzy.NewMatcher(query)
195 return func(chunks []string) (int, float64) {
196 score := float64(fm.ScoreChunks(chunks))
197 ranges := fm.MatchedRanges()
198 if len(ranges) > 0 {
199 return ranges[0], score
200 }
201 return -1, score
202 }
203 }
204
205 // parseQuery parses a field-separated symbol query, extracting the special
206 // characters listed below, and returns a matcherFunc corresponding to the AND
207 // of all field queries.
208 //
209 // Special characters:
210 //
211 // ^ match exact prefix
212 // $ match exact suffix
213 // ' match exact
214 //
215 // In all three of these special queries, matches are 'smart-cased', meaning
216 // they are case sensitive if the symbol query contains any upper-case
217 // characters, and case insensitive otherwise.
218 func parseQuery(q string, newMatcher func(string) matcherFunc) matcherFunc {
219 fields := strings.Fields(q)
220 if len(fields) == 0 {
221 return func([]string) (int, float64) { return -1, 0 }
222 }
223 var funcs []matcherFunc
224 for _, field := range fields {
225 var f matcherFunc
226 switch {
227 case strings.HasPrefix(field, "^"):
228 prefix := field[1:]
229 f = smartCase(prefix, func(chunks []string) (int, float64) {
230 s := strings.Join(chunks, "")
231 if strings.HasPrefix(s, prefix) {
232 return 0, 1
233 }
234 return -1, 0
235 })
236 case strings.HasPrefix(field, "'"):
237 exact := field[1:]
238 f = smartCase(exact, matchExact(exact))
239 case strings.HasSuffix(field, "$"):
240 suffix := field[0 : len(field)-1]
241 f = smartCase(suffix, func(chunks []string) (int, float64) {
242 s := strings.Join(chunks, "")
243 if strings.HasSuffix(s, suffix) {
244 return len(s) - len(suffix), 1
245 }
246 return -1, 0
247 })
248 default:
249 f = newMatcher(field)
250 }
251 funcs = append(funcs, f)
252 }
253 if len(funcs) == 1 {
254 return funcs[0]
255 }
256 return comboMatcher(funcs).match
257 }
258
259 func matchExact(exact string) matcherFunc {
260 return func(chunks []string) (int, float64) {
261 s := strings.Join(chunks, "")
262 if idx := strings.LastIndex(s, exact); idx >= 0 {
263 return idx, 1
264 }
265 return -1, 0
266 }
267 }
268
269 // smartCase returns a matcherFunc that is case-sensitive if q contains any
270 // upper-case characters, and case-insensitive otherwise.
271 func smartCase(q string, m matcherFunc) matcherFunc {
272 insensitive := strings.ToLower(q) == q
273 wrapper := []string{""}
274 return func(chunks []string) (int, float64) {
275 s := strings.Join(chunks, "")
276 if insensitive {
277 s = strings.ToLower(s)
278 }
279 wrapper[0] = s
280 return m(wrapper)
281 }
282 }
283
284 type comboMatcher []matcherFunc
285
286 func (c comboMatcher) match(chunks []string) (int, float64) {
287 score := 1.0
288 first := 0
289 for _, f := range c {
290 idx, s := f(chunks)
291 if idx < first {
292 first = idx
293 }
294 score *= s
295 }
296 return first, score
297 }
298
299 // collectSymbols searches all files in the provided snapshots for symbols
300 // matching the query.
301 //
302 // It walks the syntax trees of the views' current snapshots and returns a
303 // list of symbols, sorted by match quality.
304 //
305 // The search behavior (scoring, filtering, and formatting) is governed by
306 // the provided options. See [WorkspaceSymbolsOptions] for details on how
307 // matches are calculated and styled.
308 func collectSymbols(ctx context.Context, snapshots []*cache.Snapshot, query string, opts WorkspaceSymbolsOptions) ([]protocol.SymbolInformation, error) {
309 // Extract symbols from all files.
310 var work []symbolFile
311 seen := make(map[protocol.DocumentURI]*metadata.Package) // only scan each file once
312
313 for _, snapshot := range snapshots {
314 // Use the root view URIs for determining (lexically)
315 // whether a URI is in any open workspace.
316 folderURI := snapshot.Folder()
317
318 pathIncluded := cache.PathIncludeFunc(snapshot.Options().DirectoryFilters)
319 folder := filepath.ToSlash(folderURI.Path())
320
321 var (
322 mps []*metadata.Package
323 err error
324 )
325 if snapshot.Options().SymbolScope == settings.AllSymbolScope {
326 mps, err = snapshot.AllMetadata(ctx)
327 } else {
328 mps, err = snapshot.WorkspaceMetadata(ctx)
329 }
330 if err != nil {
331 return nil, err
332 }
333 metadata.RemoveIntermediateTestVariants(&mps)
334
335 // We'll process packages in order to consider candidate symbols.
336 //
337 // The order here doesn't matter for correctness, but can affect
338 // performance:
339 // - As workspace packages score higher than non-workspace packages,
340 // sort them first to increase the likelihood that non-workspace
341 // symbols are skipped.
342 // - As files can be contained in multiple packages, sort by wider
343 // packages first, to cover all files with fewer packages.
344 workspacePackages := snapshot.WorkspacePackages()
345 slices.SortFunc(mps, func(a, b *metadata.Package) int {
346 _, aworkspace := workspacePackages.Value(a.ID)
347 _, bworkspace := workspacePackages.Value(b.ID)
348 if cmp := boolCompare(aworkspace, bworkspace); cmp != 0 {
349 return -cmp // workspace packages first
350 }
351 return -cmp.Compare(len(a.CompiledGoFiles), len(b.CompiledGoFiles)) // widest first
352 })
353
354 // Filter out unneeded mps in place, and collect file<->package
355 // associations.
356 var ids []metadata.PackageID
357 for _, mp := range mps {
358 used := false
359 for _, list := range [][]protocol.DocumentURI{mp.GoFiles, mp.CompiledGoFiles} {
360 for _, uri := range list {
361 if _, ok := seen[uri]; !ok {
362 seen[uri] = mp
363 used = true
364 }
365 }
366 }
367 if used {
368 mps[len(ids)] = mp
369 ids = append(ids, mp.ID)
370 }
371 }
372 mps = mps[:len(ids)]
373
374 symbolPkgs, err := snapshot.Symbols(ctx, ids...)
375 if err != nil {
376 return nil, err
377 }
378
379 for i, sp := range symbolPkgs {
380 if sp == nil {
381 continue
382 }
383 mp := mps[i]
384 for i, syms := range sp.Symbols {
385 uri := sp.Files[i]
386 norm := filepath.ToSlash(uri.Path())
387 nm := strings.TrimPrefix(norm, folder)
388 if !pathIncluded(nm) {
389 continue
390 }
391 // Only scan each file once.
392 if seen[uri] != mp {
393 continue
394 }
395 // seen[uri] = true
396 _, workspace := workspacePackages.Value(mp.ID)
397 work = append(work, symbolFile{mp, uri, syms, workspace})
398 }
399 }
400 }
401
402 var symbolizer symbolizer
403 switch opts.Style {
404 case settings.DynamicSymbols:
405 symbolizer = dynamicSymbolMatch
406 case settings.FullyQualifiedSymbols:
407 symbolizer = fullyQualifiedSymbolMatch
408 case settings.PackageQualifiedSymbols:
409 symbolizer = packageSymbolMatch
410 default:
411 panic(fmt.Sprintf("unknown symbol style: %v", opts.Style))
412 }
413
414 // Match symbols in parallel.
415 // Each worker has its own symbolStore,
416 // which we merge at the end.
417 nmatchers := runtime.GOMAXPROCS(-1) // matching is CPU bound
418 results := make(chan *symbolStore)
419 for i := range nmatchers {
420 go func(i int) {
421 matcher := buildMatcher(opts.Matcher, query)
422 store := new(symbolStore)
423 // Assign files to workers in round-robin fashion.
424 for j := i; j < len(work); j += nmatchers {
425 matchFile(store, symbolizer, matcher, opts.Filter, work[j])
426 }
427 results <- store
428 }(i)
429 }
430
431 // Gather and merge results as they arrive.
432 var unified symbolStore
433 for range nmatchers {
434 store := <-results
435 for _, syms := range store.res {
436 if syms != nil {
437 unified.store(syms)
438 }
439 }
440 }
441 return unified.results(), nil
442 }
443
444 // symbolFile holds symbol information for a single file.
445 type symbolFile struct {
446 mp *metadata.Package
447 uri protocol.DocumentURI
448 syms []symbols.Symbol
449 workspace bool
450 }
451
452 // matchFile scans a symbol file and adds matching symbols to the store.
453 func matchFile(store *symbolStore, symbolizer symbolizer, matcher matcherFunc, filter SymbolFilter, f symbolFile) {
454 space := make([]string, 0, 3)
455 for _, sym := range f.syms {
456 // Check if the symbol should be filtered out.
457 if filter != nil && !filter(sym) {
458 continue
459 }
460
461 symbolParts, score := symbolizer(space, sym.Name, f.mp, matcher)
462
463 // Check if the score is too low before applying any downranking.
464 if store.tooLow(score) {
465 continue
466 }
467
468 // Factors to apply to the match score for the purpose of downranking
469 // results.
470 //
471 // These numbers were crudely calibrated based on trial-and-error using a
472 // small number of sample queries. Adjust as necessary.
473 //
474 // All factors are multiplicative, meaning if more than one applies they are
475 // multiplied together.
476 const (
477 // nonWorkspaceFactor is applied to symbols outside the workspace.
478 // Developers are less likely to want to jump to code that they
479 // are not actively working on.
480 nonWorkspaceFactor = 0.5
481 // nonWorkspaceUnexportedFactor is applied to unexported symbols outside
482 // the workspace. Since one wouldn't usually jump to unexported
483 // symbols to understand a package API, they are particularly irrelevant.
484 nonWorkspaceUnexportedFactor = 0.5
485 // every field or method nesting level to access the field decreases
486 // the score by a factor of 1.0 - depth*depthFactor, up to a depth of
487 // 3.
488 //
489 // Use a small constant here, as this exists mostly to break ties
490 // (e.g. given a type Foo and a field x.Foo, prefer Foo).
491 depthFactor = 0.01
492 )
493
494 // TODO(rfindley): compute this downranking *before* calling the symbolizer
495 // (which is expensive), so that we can pre-filter candidates whose score
496 // will always be too low, even with a perfect match.
497
498 startWord := true
499 exported := true
500 depth := 0.0
501 for _, r := range sym.Name {
502 if startWord && !unicode.IsUpper(r) {
503 exported = false
504 }
505 if r == '.' {
506 startWord = true
507 depth++
508 } else {
509 startWord = false
510 }
511 }
512
513 // Apply downranking based on workspace position.
514 if !f.workspace {
515 score *= nonWorkspaceFactor
516 if !exported {
517 score *= nonWorkspaceUnexportedFactor
518 }
519 }
520
521 // Apply downranking based on symbol depth.
522 if depth > 3 {
523 depth = 3
524 }
525 score *= 1.0 - depth*depthFactor
526
527 if store.tooLow(score) {
528 continue
529 }
530
531 si := &scoredSymbol{
532 score: score,
533 info: protocol.SymbolInformation{
534 Name: strings.Join(symbolParts, ""),
535 Kind: sym.Kind,
536 Location: f.uri.Location(sym.Range),
537 ContainerName: string(f.mp.PkgPath),
538 },
539 }
540 store.store(si)
541 }
542 }
543
544 type symbolStore struct {
545 res [maxSymbols]*scoredSymbol
546 }
547
548 // store inserts si into the sorted results, if si has a high enough score.
549 func (sc *symbolStore) store(ss *scoredSymbol) {
550 if sc.tooLow(ss.score) {
551 return
552 }
553 insertAt := sort.Search(len(sc.res), func(i int) bool {
554 if sc.res[i] == nil {
555 return true
556 }
557 // Sort by score, then symbol length, and finally lexically.
558 if ss.score != sc.res[i].score {
559 return ss.score > sc.res[i].score
560 }
561 if cmp := cmp.Compare(len(ss.info.Name), len(sc.res[i].info.Name)); cmp != 0 {
562 return cmp < 0 // shortest first
563 }
564 return ss.info.Name < sc.res[i].info.Name
565 })
566 if insertAt < len(sc.res)-1 {
567 copy(sc.res[insertAt+1:], sc.res[insertAt:len(sc.res)-1])
568 }
569 sc.res[insertAt] = ss
570 }
571
572 func (sc *symbolStore) tooLow(score float64) bool {
573 last := sc.res[len(sc.res)-1]
574 if last == nil {
575 return false
576 }
577 return score <= last.score
578 }
579
580 func (sc *symbolStore) results() []protocol.SymbolInformation {
581 var res []protocol.SymbolInformation
582 for _, si := range sc.res {
583 if si == nil || si.score <= 0 {
584 return res
585 }
586 res = append(res, si.info)
587 }
588 return res
589 }
590
591 type scoredSymbol struct {
592 score float64
593 info protocol.SymbolInformation
594 }