Debian Codegraph @

gopls/internal/golang/references.go

raw symbols SCIP
1 // Copyright 2019 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 // This file defines the 'references' query based on a serializable
8 // index constructed during type checking, thus avoiding the need to
9 // type-check packages at search time.
10 //
11 // See the ./xrefs/ subpackage for the index construction and lookup.
12 //
13 // This implementation does not intermingle objects from distinct
14 // calls to TypeCheck.
15
16 import (
17 "context"
18 "fmt"
19 "go/ast"
20 "go/types"
21 "sort"
22 "strings"
23 "sync"
24
25 "golang.org/x/sync/errgroup"
26 "golang.org/x/tools/go/ast/edge"
27 "golang.org/x/tools/go/ast/inspector"
28 "golang.org/x/tools/go/types/objectpath"
29 "golang.org/x/tools/go/types/typeutil"
30 "golang.org/x/tools/gopls/internal/cache"
31 "golang.org/x/tools/gopls/internal/cache/metadata"
32 "golang.org/x/tools/gopls/internal/cache/methodsets"
33 "golang.org/x/tools/gopls/internal/cache/parsego"
34 "golang.org/x/tools/gopls/internal/file"
35 "golang.org/x/tools/gopls/internal/protocol"
36 "golang.org/x/tools/gopls/internal/util/cursorutil"
37 "golang.org/x/tools/gopls/internal/util/safetoken"
38
39 "golang.org/x/tools/internal/event"
40 )
41
42 // References returns a list of all references (sorted with
43 // definitions before uses) to the object denoted by the identifier at
44 // the given file/position, searching the entire workspace.
45 func References(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, rng protocol.Range, includeDeclaration bool) ([]protocol.Location, error) {
46 references, err := references(ctx, snapshot, fh, rng, includeDeclaration)
47 if err != nil {
48 return nil, err
49 }
50 locations := make([]protocol.Location, len(references))
51 for i, ref := range references {
52 locations[i] = ref.location
53 }
54 return locations, nil
55 }
56
57 // A reference describes an identifier that refers to the same
58 // object as the subject of a References query.
59 type reference struct {
60 isDeclaration bool
61 location protocol.Location
62 pkgPath PackagePath // of declaring package (same for all elements of the slice)
63 }
64
65 // references returns a list of all references (sorted with
66 // definitions before uses) to the object denoted by the identifier at
67 // the given file/position, searching the entire workspace.
68 func references(ctx context.Context, snapshot *cache.Snapshot, f file.Handle, rng protocol.Range, includeDeclaration bool) ([]reference, error) {
69 ctx, done := event.Start(ctx, "golang.references")
70 defer done()
71
72 // Is the cursor within the package name declaration?
73 _, inPackageName, err := parsePackageNameDecl(ctx, snapshot, f, rng)
74 if err != nil {
75 return nil, err
76 }
77
78 var refs []reference
79 if inPackageName {
80 refs, err = packageReferences(ctx, snapshot, f.URI())
81 } else {
82 refs, err = ordinaryReferences(ctx, snapshot, f.URI(), rng)
83 }
84 if err != nil {
85 return nil, err
86 }
87
88 sort.Slice(refs, func(i, j int) bool {
89 x, y := refs[i], refs[j]
90 if x.isDeclaration != y.isDeclaration {
91 return x.isDeclaration // decls < refs
92 }
93 return protocol.CompareLocation(x.location, y.location) < 0
94 })
95
96 // De-duplicate by location, and optionally remove declarations.
97 out := refs[:0]
98 for _, ref := range refs {
99 if !includeDeclaration && ref.isDeclaration {
100 continue
101 }
102 if len(out) == 0 || out[len(out)-1].location != ref.location {
103 out = append(out, ref)
104 }
105 }
106 refs = out
107
108 return refs, nil
109 }
110
111 // packageReferences returns a list of references to the package
112 // declaration of the specified name and uri by searching among the
113 // import declarations of all packages that directly import the target
114 // package.
115 func packageReferences(ctx context.Context, snapshot *cache.Snapshot, uri protocol.DocumentURI) ([]reference, error) {
116 metas, err := snapshot.MetadataForFile(ctx, uri, false)
117 if err != nil {
118 return nil, err
119 }
120 if len(metas) == 0 {
121 return nil, fmt.Errorf("found no package containing %s", uri)
122 }
123
124 var refs []reference
125
126 // Find external references to the package declaration
127 // from each direct import of the package.
128 //
129 // The narrowest package is the most broadly imported,
130 // so we choose it for the external references.
131 //
132 // But if the file ends with _test.go then we need to
133 // find the package it is testing; there's no direct way
134 // to do that, so pick a file from the same package that
135 // doesn't end in _test.go and start over.
136 narrowest := metas[0]
137 if narrowest.ForTest != "" && strings.HasSuffix(string(uri), "_test.go") {
138 for _, f := range narrowest.CompiledGoFiles {
139 if !strings.HasSuffix(string(f), "_test.go") {
140 return packageReferences(ctx, snapshot, f)
141 }
142 }
143 // This package has no non-test files.
144 // Skip the search for external references.
145 // (Conceivably one could blank-import an empty package, but why?)
146 } else {
147 rdeps, err := snapshot.ReverseDependencies(ctx, narrowest.ID, false) // direct
148 if err != nil {
149 return nil, err
150 }
151
152 // Restrict search to workspace packages.
153 workspace, err := snapshot.WorkspaceMetadata(ctx)
154 if err != nil {
155 return nil, err
156 }
157 workspaceMap := make(map[PackageID]*metadata.Package, len(workspace))
158 for _, mp := range workspace {
159 workspaceMap[mp.ID] = mp
160 }
161
162 for _, rdep := range rdeps {
163 if _, ok := workspaceMap[rdep.ID]; !ok {
164 continue
165 }
166 for _, uri := range rdep.CompiledGoFiles {
167 fh, err := snapshot.ReadFile(ctx, uri)
168 if err != nil {
169 return nil, err
170 }
171 f, err := snapshot.ParseGo(ctx, fh, parsego.Header)
172 if err != nil {
173 return nil, err
174 }
175 for _, imp := range f.File.Imports {
176 if rdep.DepsByImpPath[metadata.UnquoteImportPath(imp)] == narrowest.ID {
177 refs = append(refs, reference{
178 isDeclaration: false,
179 location: mustLocation(f, imp),
180 pkgPath: narrowest.PkgPath,
181 })
182 }
183 }
184 }
185 }
186 }
187
188 // Find internal "references" to the package from
189 // of each package declaration in the target package itself.
190 //
191 // The widest package (possibly a test variant) has the
192 // greatest number of files and thus we choose it for the
193 // "internal" references.
194 widest := metas[len(metas)-1] // may include _test.go files
195 for _, uri := range widest.CompiledGoFiles {
196 fh, err := snapshot.ReadFile(ctx, uri)
197 if err != nil {
198 return nil, err
199 }
200 f, err := snapshot.ParseGo(ctx, fh, parsego.Header)
201 if err != nil {
202 return nil, err
203 }
204 // golang/go#66250: don't crash if the package file lacks a name.
205 if f.File.Name.Pos().IsValid() {
206 refs = append(refs, reference{
207 isDeclaration: true, // (one of many)
208 location: mustLocation(f, f.File.Name),
209 pkgPath: widest.PkgPath,
210 })
211 }
212 }
213
214 return refs, nil
215 }
216
217 // ordinaryReferences computes references for all ordinary objects (not package declarations).
218 func ordinaryReferences(ctx context.Context, snapshot *cache.Snapshot, uri protocol.DocumentURI, rng protocol.Range) ([]reference, error) {
219 // Strategy: use the reference information computed by the
220 // type checker to find the declaration. First type-check this
221 // package to find the declaration, then type check the
222 // declaring package (which may be different), plus variants,
223 // to find local (in-package) references.
224 // Global references are satisfied by the index.
225
226 // Strictly speaking, a wider package could provide a different
227 // declaration (e.g. because the _test.go files can change the
228 // meaning of a field or method selection), but the narrower
229 // package reports the more broadly referenced object.
230 pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, uri)
231 if err != nil {
232 return nil, err
233 }
234
235 // Find the selected object (declaration or reference).
236 // For struct{T}, we choose the field (Def) over the type (Use).
237 start, end, err := pgf.RangePos(rng)
238 if err != nil {
239 return nil, err
240 }
241 cur, _ := pgf.Cursor().FindByPos(start, end) // can't fail
242
243 candidates, err := objectsAt(pkg.TypesInfo(), cur)
244 if err != nil {
245 return nil, err
246 }
247 // Pick first object arbitrarily.
248 // The case variables of a type switch have different
249 // types but that difference is immaterial here.
250 obj := candidates[0].obj
251
252 // nil, error, error.Error, iota, or other built-in?
253 if isBuiltin(obj) {
254 return nil, fmt.Errorf("references to builtin %q are not supported", obj.Name())
255 }
256
257 // Find metadata of all packages containing the object's defining file.
258 // This may include the query pkg, and possibly other variants.
259 declPosn := safetoken.StartPosition(pkg.FileSet(), obj.Pos())
260 declURI := protocol.URIFromPath(declPosn.Filename)
261 variants, err := snapshot.MetadataForFile(ctx, declURI, false)
262 if err != nil {
263 return nil, err
264 }
265 if len(variants) == 0 {
266 return nil, fmt.Errorf("no packages for file %q", declURI) // can't happen
267 }
268 // (variants must include ITVs for reverse dependency computation below.)
269
270 // Is object exported?
271 // If so, compute scope and targets of the global search.
272 var (
273 globalScope = make(map[PackageID]*metadata.Package) // (excludes ITVs)
274 globalTargets map[PackagePath]map[objectpath.Path]unit
275 expansions = make(map[PackageID]unit) // packages that caused search expansion
276 )
277 // TODO(adonovan): what about generic functions? Need to consider both
278 // uninstantiated and instantiated. The latter have no objectpath. Use Origin?
279 if path, err := objectpath.For(obj); err == nil && obj.Exported() {
280 pkgPath := variants[0].PkgPath // (all variants have same package path)
281 globalTargets = map[PackagePath]map[objectpath.Path]unit{
282 pkgPath: {path: {}}, // primary target
283 }
284
285 // Compute set of (non-ITV) workspace packages.
286 // We restrict references to this subset.
287 workspace, err := snapshot.WorkspaceMetadata(ctx)
288 if err != nil {
289 return nil, err
290 }
291 workspaceMap := make(map[PackageID]*metadata.Package, len(workspace))
292 workspaceIDs := make([]PackageID, 0, len(workspace))
293 for _, mp := range workspace {
294 workspaceMap[mp.ID] = mp
295 workspaceIDs = append(workspaceIDs, mp.ID)
296 }
297
298 // addRdeps expands the global scope to include the
299 // reverse dependencies of the specified package.
300 addRdeps := func(id PackageID, transitive bool) error {
301 rdeps, err := snapshot.ReverseDependencies(ctx, id, transitive)
302 if err != nil {
303 return err
304 }
305 for rdepID, rdep := range rdeps {
306 // Skip non-workspace packages.
307 //
308 // This means we also skip any expansion of the
309 // search that might be caused by a non-workspace
310 // package, possibly causing us to miss references
311 // to the expanded target set from workspace packages.
312 //
313 // TODO(adonovan): don't skip those expansions.
314 // The challenge is how to so without type-checking
315 // a lot of non-workspace packages not covered by
316 // the initial workspace load.
317 if _, ok := workspaceMap[rdepID]; !ok {
318 continue
319 }
320
321 globalScope[rdepID] = rdep
322 }
323 return nil
324 }
325
326 // How far need we search?
327 // For package-level objects, we need only search the direct importers.
328 // For fields and methods, we must search transitively.
329 transitive := obj.Pkg().Scope().Lookup(obj.Name()) != obj
330
331 // The scope is the union of rdeps of each variant.
332 // (Each set is disjoint so there's no benefit to
333 // combining the metadata graph traversals.)
334 for _, mp := range variants {
335 if err := addRdeps(mp.ID, transitive); err != nil {
336 return nil, err
337 }
338 }
339
340 // Is object a method?
341 //
342 // If so, expand the search so that the targets include
343 // all methods that correspond to it through interface
344 // satisfaction, and the scope includes the rdeps of
345 // the package that declares each corresponding type.
346 //
347 // 'expansions' records the packages that declared
348 // such types.
349 if recv := effectiveReceiver(obj); recv != nil {
350 if err := expandMethodSearch(ctx, snapshot, workspaceIDs, obj.(*types.Func), recv, addRdeps, globalTargets, expansions); err != nil {
351 return nil, err
352 }
353 }
354 }
355
356 // The search functions will call report(loc) for each hit.
357 var (
358 refsMu sync.Mutex
359 refs []reference
360 )
361 report := func(loc protocol.Location, isDecl bool) {
362 ref := reference{
363 isDeclaration: isDecl,
364 location: loc,
365 pkgPath: pkg.Metadata().PkgPath,
366 }
367 refsMu.Lock()
368 refs = append(refs, ref)
369 refsMu.Unlock()
370 }
371
372 // Loop over the variants of the declaring package,
373 // and perform both the local (in-package) and global
374 // (cross-package) searches, in parallel.
375 //
376 // TODO(adonovan): opt: support LSP reference streaming. See:
377 // - https://github.com/microsoft/vscode-languageserver-node/pull/164
378 // - https://github.com/microsoft/language-server-protocol/pull/182
379 //
380 // Careful: this goroutine must not return before group.Wait.
381 var group errgroup.Group
382
383 // Compute local references for each variant.
384 // The target objects are identified by (URI, offset).
385 for _, mp := range variants {
386 // We want the ordinary importable package,
387 // plus any test-augmented variants, since
388 // declarations in _test.go files may change
389 // the reference of a selection, or even a
390 // field into a method or vice versa.
391 //
392 // But we don't need intermediate test variants,
393 // as their local references will be covered
394 // already by other variants.
395 if mp.IsIntermediateTestVariant() {
396 continue
397 }
398 mp := mp
399 group.Go(func() error {
400 // TODO(adonovan): opt: batch these TypeChecks.
401 pkgs, err := snapshot.TypeCheck(ctx, mp.ID)
402 if err != nil {
403 return err
404 }
405 pkg := pkgs[0]
406
407 // Find the declaration of the corresponding
408 // object in this package based on (URI, offset).
409 pgf, err := pkg.File(declURI)
410 if err != nil {
411 return err
412 }
413 pos, err := safetoken.Pos(pgf.Tok, declPosn.Offset)
414 if err != nil {
415 return err
416 }
417 cur, _ := pgf.Cursor().FindByPos(pos, pos) // can't fail
418
419 objects, err := objectsAt(pkg.TypesInfo(), cur)
420 if err != nil {
421 return err // unreachable? (probably caught earlier)
422 }
423
424 // Report the locations of the declaration(s).
425 // TODO(adonovan): what about for corresponding methods? Add tests.
426 for _, o := range objects {
427 report(mustLocation(pgf, o.cur.Node()), true)
428 }
429
430 // Convert objects list to targets set.
431 targets := make(map[types.Object]bool)
432 for _, o := range objects {
433 targets[o.obj] = true
434 }
435
436 return localReferences(pkg, targets, true, report)
437 })
438 }
439
440 // Also compute local references within packages that declare
441 // corresponding methods (see above), which expand the global search.
442 // The target objects are identified by (PkgPath, objectpath).
443 for id := range expansions {
444 group.Go(func() error {
445 // TODO(adonovan): opt: batch these TypeChecks.
446 pkgs, err := snapshot.TypeCheck(ctx, id)
447 if err != nil {
448 return err
449 }
450 pkg := pkgs[0]
451
452 targets := make(map[types.Object]bool)
453 for objpath := range globalTargets[pkg.Metadata().PkgPath] {
454 obj, err := objectpath.Object(pkg.Types(), objpath)
455 if err != nil {
456 // No such object, because it was
457 // declared only in the test variant.
458 continue
459 }
460 targets[obj] = true
461 }
462
463 // Don't include corresponding types or methods
464 // since expansions did that already, and we don't
465 // want (e.g.) concrete -> interface -> concrete.
466 const correspond = false
467 return localReferences(pkg, targets, correspond, report)
468 })
469 }
470
471 // Compute global references for selected reverse dependencies.
472 group.Go(func() error {
473 var globalIDs []PackageID
474 for id := range globalScope {
475 globalIDs = append(globalIDs, id)
476 }
477 indexes, err := snapshot.References(ctx, globalIDs...)
478 if err != nil {
479 return err
480 }
481 for _, index := range indexes {
482 for _, loc := range index.Lookup(globalTargets) {
483 report(loc, false)
484 }
485 }
486 return nil
487 })
488
489 if err := group.Wait(); err != nil {
490 return nil, err
491 }
492 return refs, nil
493 }
494
495 // expandMethodSearch expands the scope and targets of a global search
496 // for an exported method to include all methods in the workspace
497 // that correspond to it through interface satisfaction.
498 //
499 // Each package that declares a corresponding type is added to
500 // expansions so that we can also find local references to the type
501 // within the package, which of course requires type checking.
502 //
503 // The scope is expanded by a sequence of calls (not concurrent) to addRdeps.
504 //
505 // recv is the method's effective receiver type, for method-set computations.
506 func expandMethodSearch(ctx context.Context, snapshot *cache.Snapshot, workspaceIDs []PackageID, method *types.Func, recv types.Type, addRdeps func(id PackageID, transitive bool) error, targets map[PackagePath]map[objectpath.Path]unit, expansions map[PackageID]unit) error {
507 // Compute the method-set fingerprint used as a key to the global search.
508 key, hasMethods := methodsets.KeyOf(recv)
509 if !hasMethods {
510 // The query object was method T.m, but methodset(T)={}:
511 // this indicates that ill-typed T has conflicting fields and methods.
512 // Rather than bug-report (#67978), treat the empty method set at face value.
513 return nil
514 }
515 // Search the methodset index of each package in the workspace.
516 indexes, err := snapshot.MethodSets(ctx, workspaceIDs...)
517 if err != nil {
518 return err
519 }
520 var mu sync.Mutex // guards addRdeps, targets, expansions
521 var group errgroup.Group
522 for i, index := range indexes {
523 group.Go(func() error {
524 // Consult index for matching (super/sub) methods.
525 const want = methodsets.Supertype | methodsets.Subtype
526 results := index.Search(key, want, method)
527 if len(results) == 0 {
528 return nil
529 }
530
531 // We have discovered one or more corresponding types.
532 id := workspaceIDs[i]
533
534 mu.Lock()
535 defer mu.Unlock()
536
537 // Expand global search scope to include rdeps of this pkg.
538 if err := addRdeps(id, true); err != nil {
539 return err
540 }
541
542 // Mark this package so that we search within it for
543 // local references to the additional types/methods.
544 expansions[id] = unit{}
545
546 // Add each corresponding method the to set of global search targets.
547 for _, res := range results {
548 methodPkg := PackagePath(res.PkgPath)
549 opaths, ok := targets[methodPkg]
550 if !ok {
551 opaths = make(map[objectpath.Path]unit)
552 targets[methodPkg] = opaths
553 }
554 opaths[res.ObjectPath] = unit{}
555 }
556 return nil
557 })
558 }
559 return group.Wait()
560 }
561
562 // localReferences traverses syntax and reports each reference to one
563 // of the target objects, or (if correspond is set) an object that
564 // corresponds to one of them via interface satisfaction.
565 func localReferences(pkg *cache.Package, targets map[types.Object]bool, correspond bool, report func(loc protocol.Location, isDecl bool)) error {
566 // If we're searching for references to a method optionally
567 // broaden the search to include references to corresponding
568 // methods of mutually assignable receiver types.
569 // (We use a slice, but objectsAt never returns >1 methods.)
570 var methodRecvs []types.Type
571 var methodName string // name of an arbitrary target, iff a method
572 if correspond {
573 for obj := range targets {
574 if t := effectiveReceiver(obj); t != nil {
575 methodRecvs = append(methodRecvs, t)
576 methodName = obj.Name()
577 }
578 }
579 }
580
581 var msets typeutil.MethodSetCache
582
583 // matches reports whether obj either is or corresponds to a target.
584 // (Correspondence is defined as usual for interface methods: super/subtype.)
585 matches := func(obj types.Object) bool {
586 if containsOrigin(targets, obj) {
587 return true
588 }
589 if methodRecvs != nil && obj.Name() == methodName {
590 if orecv := effectiveReceiver(obj); orecv != nil {
591 for _, mrecv := range methodRecvs {
592 if implements(&msets, orecv, mrecv) ||
593 implements(&msets, mrecv, orecv) {
594 return true
595 }
596 }
597 }
598 }
599 return false
600 }
601
602 // Collect target names for fast pre-filtering:
603 // skip identifiers whose name can't match any target.
604 targetNames := make(map[string]struct{}, len(targets))
605 for obj := range targets {
606 targetNames[obj.Name()] = struct{}{}
607 }
608
609 // Scan through syntax looking for uses of one of the target objects.
610 for _, pgf := range pkg.CompiledGoFiles() {
611 for curId := range pgf.Cursor().Preorder((*ast.Ident)(nil)) {
612 id := curId.Node().(*ast.Ident)
613 if _, ok := targetNames[id.Name]; !ok {
614 continue
615 }
616 if obj, ok := pkg.TypesInfo().Uses[id]; ok && matches(obj) {
617 report(mustLocation(pgf, id), false)
618 }
619 }
620 }
621 return nil
622 }
623
624 // effectiveReceiver returns the effective receiver type for method-set
625 // comparisons for obj, if it is a method, or nil otherwise.
626 func effectiveReceiver(obj types.Object) types.Type {
627 if fn, ok := obj.(*types.Func); ok {
628 if recv := fn.Signature().Recv(); recv != nil {
629 return methodsets.EnsurePointer(recv.Type())
630 }
631 }
632 return nil
633 }
634
635 type objectAt struct {
636 obj types.Object // symbol
637 cur inspector.Cursor // associated syntax (Ident | ImportSpec)
638 }
639
640 // objectsAt returns the non-empty list of objects referenced (defined
641 // or used) at or near the position specified by cur. It returns an
642 // error if none were found.
643 //
644 // The implementation may look "nearby", for example at x when given
645 // a cursor to an expression "*x", i.e. the cursor was at the star.
646 //
647 // The result may contain more than one element because all case
648 // variables of a type switch appear to be declared at the same
649 // identifier.
650 //
651 // Each object is paired with a cursor for the syntax node that was
652 // treated as an identifier, which is not always an ast.Ident.
653 func objectsAt(info *types.Info, cur inspector.Cursor) ([]objectAt, error) {
654
655 // Within an ImportSpec, return the PkgName
656 // and its .Name (if explicit) or the spec if not.
657 if cur.ParentEdgeKind() == edge.ImportSpec_Path {
658 cur = cur.Parent() // ImportSpec
659 spec := cur.Node().(*ast.ImportSpec)
660 pkgname := info.PkgNameOf(spec)
661 if pkgname == nil {
662 return nil, fmt.Errorf("%w for import %s", errNoObjectFound, metadata.UnquoteImportPath(spec))
663 }
664 if spec.Name != nil { // explicit?
665 cur = cur.ChildAt(edge.ImportSpec_Name, -1) // Ident
666 }
667 return []objectAt{{pkgname, cur}}, nil
668 }
669
670 // If the selection is the * of *T or *ptr,
671 // nudge it to the T or ptr operand in the hope
672 // that it is an Ident. This makes (e.g.) Hover and
673 // Definition more flexible w.r.t selections:
674 if is[*ast.StarExpr](cur.Node()) {
675 cur, _ = cur.FirstChild() // can't fail
676 }
677
678 id, ok := cur.Node().(*ast.Ident)
679 if !ok {
680 return nil, ErrNoIdentFound
681 }
682
683 // If id is a reference to a special var v in
684 // switch v := expr.(type) { case T: use(v); ... }
685 // then return all the implicit case vars.
686 objects, _ := typeSwitchVars(info, cur)
687 if len(objects) > 0 {
688 return objects, nil
689 }
690
691 // All other identifiers.
692 // For struct{T}, we prefer the defined field Var over the used TypeName.
693 obj := info.ObjectOf(id)
694 if obj == nil {
695 return nil, fmt.Errorf("%w for %q", errNoObjectFound, id.Name)
696 }
697 return []objectAt{{obj, cur}}, nil
698 }
699
700 // typeSwitchVars returns information about type switch local variables.
701 //
702 // Given the cursor for an identifier that refers to a variable v
703 // declared by a type switch of this form:
704 //
705 // switch v := expr.(type) {
706 // case T: use(v)
707 // ...
708 // }
709 //
710 // it returns:
711 //
712 // - the (possibly empty) list of variables implicitly declared for
713 // each case type; and
714 //
715 // - the identifier's effective type, which is either the case type
716 // (for an occurrence in a case), or the type of 'expr' for the
717 // occurrence in "switch v".
718 //
719 // The identifier may be v in "switch v", or a use of it in one of the
720 // cases. typeSwitchVars returns zero for all other identifiers.
721 func typeSwitchVars(info *types.Info, curIdent inspector.Cursor) ([]objectAt, types.Type) {
722 sw, curSwitch := cursorutil.FirstEnclosing[*ast.TypeSwitchStmt](curIdent)
723 if sw == nil {
724 return nil, nil
725 }
726 assign, ok := sw.Assign.(*ast.AssignStmt)
727 if !(ok &&
728 len(assign.Lhs) == 1 &&
729 is[*ast.Ident](assign.Lhs[0]) &&
730 len(assign.Rhs) == 1 &&
731 is[*ast.TypeAssertExpr](assign.Rhs[0])) {
732 return nil, nil
733 }
734 // Have: switch v := expr.(type)
735
736 id := curIdent.Node().(*ast.Ident)
737
738 match := false
739
740 // Is selected ident "switch v" var?
741 // Since it has no object, use the type of 'expr'.
742 var t types.Type
743 if id == assign.Lhs[0] {
744 match = true
745 t = info.TypeOf(assign.Rhs[0].(*ast.TypeAssertExpr).X) // may be nil
746 }
747
748 // Gather the switch's implicit variables.
749 var objects []objectAt
750 for curCase := range curSwitch.ChildAt(edge.TypeSwitchStmt_Body, -1).Children() {
751 clause := curCase.Node().(*ast.CaseClause)
752 v, ok := info.Implicits[clause]
753 if ok {
754 if v == info.Uses[id] {
755 // Selected ident is one of the case vars.
756 t = v.Type()
757 match = true
758 }
759 objects = append(objects, objectAt{v, curIdent})
760 }
761 }
762
763 if !match {
764 // Type switch is unrelated to ident.
765 return nil, nil
766 }
767
768 // Note: match does not imply t != nil,
769 // as type information may be incomplete.
770
771 return objects, t
772 }
773
774 // mustLocation reports the location interval a syntax node,
775 // which must belong to m.File.
776 //
777 // Safe for use only by references and implementations.
778 func mustLocation(pgf *parsego.File, n ast.Node) protocol.Location {
779 loc, err := pgf.NodeLocation(n)
780 if err != nil {
781 panic(err) // can't happen in references or implementations
782 }
783 return loc
784 }