Debian Codegraph @

gopls/internal/golang/implementation.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 import (
8 "context"
9 "errors"
10 "fmt"
11 "go/ast"
12 "go/token"
13 "go/types"
14 "iter"
15 "reflect"
16 "slices"
17 "strings"
18 "sync"
19
20 "golang.org/x/sync/errgroup"
21 "golang.org/x/tools/go/ast/edge"
22 "golang.org/x/tools/go/ast/inspector"
23 "golang.org/x/tools/go/types/typeutil"
24 "golang.org/x/tools/gopls/internal/cache"
25 "golang.org/x/tools/gopls/internal/cache/metadata"
26 "golang.org/x/tools/gopls/internal/cache/methodsets"
27 "golang.org/x/tools/gopls/internal/file"
28 "golang.org/x/tools/gopls/internal/protocol"
29 "golang.org/x/tools/gopls/internal/util/bug"
30 "golang.org/x/tools/gopls/internal/util/safetoken"
31 "golang.org/x/tools/internal/event"
32 "golang.org/x/tools/internal/moreiters"
33 "golang.org/x/tools/internal/typesinternal"
34 )
35
36 // This file defines the new implementation of the 'implementation'
37 // operator that does not require type-checker data structures for an
38 // unbounded number of packages.
39 //
40 // TODO(adonovan):
41 // - Audit to ensure robustness in face of type errors.
42 // - Eliminate false positives due to 'tricky' cases of the global algorithm.
43 // - Ensure we have test coverage of:
44 // type aliases
45 // nil, PkgName, Builtin (all errors)
46 // any (empty result)
47 // method of unnamed interface type (e.g. var x interface { f() })
48 // (the global algorithm may find implementations of this type
49 // but will not include it in the index.)
50
51 // Implementation returns a new sorted array of locations of
52 // declarations of types that implement (or are implemented by) the
53 // type referred to at the given position.
54 //
55 // If the position denotes a method, the computation is applied to its
56 // receiver type and then its corresponding methods are returned.
57 func Implementation(ctx context.Context, snapshot *cache.Snapshot, f file.Handle, rng protocol.Range) ([]protocol.Location, error) {
58 ctx, done := event.Start(ctx, "golang.Implementation")
59 defer done()
60
61 locs, err := implementations(ctx, snapshot, f, rng)
62 if err != nil {
63 return nil, err
64 }
65 slices.SortFunc(locs, protocol.CompareLocation)
66 locs = slices.Compact(locs) // de-duplicate
67 return locs, nil
68 }
69
70 func implementations(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, rng protocol.Range) ([]protocol.Location, error) {
71 // Type check the current package.
72 pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, fh.URI())
73 if err != nil {
74 return nil, err
75 }
76 start, end, err := pgf.RangePos(rng)
77 if err != nil {
78 return nil, err
79 }
80 cur, _ := pgf.Cursor().FindByPos(start, end) // can't fail
81
82 // Find implementations based on func signatures.
83 if locs, err := implFuncs(pkg, cur, start, end); err != errNotHandled {
84 return locs, err
85 }
86
87 // Find implementations based on method sets.
88 var (
89 locsMu sync.Mutex
90 locs []protocol.Location
91 )
92 // relation=0 here means infer direction of the relation
93 // (Supertypes/Subtypes) from concreteness of query type/method.
94 // (Ideally the implementations request would provide directionality
95 // so that one could ask for, say, the superinterfaces of io.ReadCloser;
96 // see https://github.com/golang/go/issues/68641#issuecomment-2269293762.)
97 const relation = methodsets.TypeRelation(0)
98 err = implementationsMsets(ctx, snapshot, pkg, cur, relation, func(_ metadata.PackagePath, _ string, _ bool, loc protocol.Location) {
99 locsMu.Lock()
100 locs = append(locs, loc)
101 locsMu.Unlock()
102 })
103 return locs, err
104 }
105
106 // An implYieldFunc is a callback called for each match produced by the implementation machinery.
107 // - name describes the type or method.
108 // - abstract indicates that the result is an interface type or interface method.
109 //
110 // implYieldFunc implementations must be concurrency-safe.
111 type implYieldFunc func(pkgpath metadata.PackagePath, name string, abstract bool, loc protocol.Location)
112
113 // implementationsMsets computes implementations of the type at the
114 // position specified by cur, by method sets.
115 //
116 // rel specifies the desired direction of the relation: Subtype,
117 // Supertype, or both. As a special case, zero means infer the
118 // direction from the concreteness of the query object: Supertype for
119 // a concrete type, Subtype for an interface.
120 //
121 // It is shared by Implementations and TypeHierarchy.
122 func implementationsMsets(ctx context.Context, snapshot *cache.Snapshot, pkg *cache.Package, cur inspector.Cursor, rel methodsets.TypeRelation, yield implYieldFunc) error {
123 // First, find the object referenced at the cursor.
124 // The object may be declared in a different package.
125 obj, err := implementsObj(pkg.TypesInfo(), cur)
126 if err != nil {
127 return err
128 }
129
130 // If the resulting object has a position, we can expand the search to types
131 // in the declaring package(s). In this case, we must re-type check these
132 // packages in the same realm.
133 var (
134 declOffset int
135 declURI protocol.DocumentURI
136 localPkgs []*cache.Package
137 )
138 if obj.Pos().IsValid() { // no local package for error or error.Error
139 declPosn := safetoken.StartPosition(pkg.FileSet(), obj.Pos())
140 declOffset = declPosn.Offset
141 // Type-check the declaring package (incl. variants) for use
142 // by the "local" search, which uses type information to
143 // enumerate all types within the package that satisfy the
144 // query type, even those defined local to a function.
145 declURI = protocol.URIFromPath(declPosn.Filename)
146 declMPs, err := snapshot.MetadataForFile(ctx, declURI, true)
147 if err != nil {
148 return err
149 }
150 if len(declMPs) == 0 {
151 return fmt.Errorf("no packages for file %s", declURI)
152 }
153 ids := make([]PackageID, len(declMPs))
154 for i, mp := range declMPs {
155 ids[i] = mp.ID
156 }
157 localPkgs, err = snapshot.TypeCheck(ctx, ids...)
158 if err != nil {
159 return err
160 }
161 }
162
163 pkg = nil // no longer used
164
165 // Is the selected identifier a type name or method?
166 // (For methods, report the corresponding method names.)
167 queryType, queryMethod := typeOrMethod(obj)
168 if queryType == nil {
169 return bug.Errorf("%s is not a type or method", obj.Name()) // should have been handled by implementsObj
170 }
171
172 // Compute the method-set fingerprint used as a key to the global search.
173 key, hasMethods := methodsets.KeyOf(queryType)
174 if !hasMethods {
175 // A type with no methods yields an empty result.
176 // (No point reporting that every type satisfies 'any'.)
177 return nil
178 }
179
180 // If the client specified no relation, infer it
181 // from the concreteness of the query type.
182 if rel == 0 {
183 rel = cond(types.IsInterface(queryType),
184 methodsets.Subtype,
185 methodsets.Supertype)
186 }
187
188 // The global search needs to look at every package in the
189 // forward transitive closure of the workspace; see package
190 // ./methodsets.
191 //
192 // For now we do all the type checking before beginning the search.
193 // TODO(adonovan): opt: search in parallel topological order
194 // so that we can overlap index lookup with typechecking.
195 // I suspect a number of algorithms on the result of TypeCheck could
196 // be optimized by being applied as soon as each package is available.
197 globalMetas, err := snapshot.AllMetadata(ctx)
198 if err != nil {
199 return err
200 }
201 metadata.RemoveIntermediateTestVariants(&globalMetas)
202 globalIDs := make([]PackageID, 0, len(globalMetas))
203
204 var pkgPath PackagePath
205 if obj.Pkg() != nil { // nil for error
206 pkgPath = PackagePath(obj.Pkg().Path())
207 }
208 for _, mp := range globalMetas {
209 globalIDs = append(globalIDs, mp.ID)
210 }
211 indexes, err := snapshot.MethodSets(ctx, globalIDs...)
212 if err != nil {
213 return fmt.Errorf("querying method sets: %v", err)
214 }
215
216 // For method queries, results may include methods promoted via
217 // embedding from another package, whose positions are not stored
218 // in the index (see methodsets.Result.Location). Build a map of
219 // indexes by package path so we can resolve such positions in the
220 // declaring package's index.
221 //
222 // Type queries always return positions of types in the indexed
223 // package itself, so this map is not needed.
224 //
225 // Only non-test variants are included: a promoted method's
226 // declaring package is the one that was imported, and test
227 // variants are not importable.
228 var byPkgPath map[PackagePath]*methodsets.Index
229 if queryMethod != nil {
230 byPkgPath = make(map[PackagePath]*methodsets.Index, len(indexes))
231 for i, index := range indexes {
232 if globalMetas[i].ForTest == "" {
233 byPkgPath[index.PkgPath] = index
234 }
235 }
236 }
237
238 // Search local and global packages in parallel.
239 var group errgroup.Group
240
241 // local search
242 for _, pkg := range localPkgs {
243 // The localImplementations algorithm assumes needle and haystack
244 // belong to a single package (="realm" of types symbol identities),
245 // so we need to recompute obj for each local package.
246 // (By contrast the global algorithm is name-based.)
247 group.Go(func() error {
248 pkgID := pkg.Metadata().ID
249
250 // Find declaring identifier based on (URI, offset)
251 // so that localImplementations can locate the
252 // corresponding obj/queryType/queryMethod in pkg.
253 declFile, err := pkg.File(declURI)
254 if err != nil {
255 return err // "can't happen"
256 }
257 pos, err := safetoken.Pos(declFile.Tok, declOffset)
258 if err != nil {
259 return err // also "can't happen"
260 }
261 curIdent, ok := declFile.Cursor().FindByPos(pos, pos)
262 if !ok {
263 return bug.Errorf("position not within file") // can't happen
264 }
265 id, ok := curIdent.Node().(*ast.Ident)
266 if !ok {
267 return ErrNoIdentFound // checked earlier
268 }
269 if err := localImplementations(ctx, snapshot, pkg, id, rel, yield); err != nil {
270 return fmt.Errorf("querying local implementations %q: %v", pkgID, err)
271 }
272 return nil
273 })
274 }
275 // global search
276 for _, index := range indexes {
277 if index.PkgPath == pkgPath {
278 continue // declaring package is handled by local implementation
279 }
280 group.Go(func() error {
281 for _, res := range index.Search(key, rel, queryMethod) {
282 loc := res.Location
283 if loc.Filename == "" {
284 // Method promoted from another package via
285 // embedding: resolve its position from the
286 // declaring package's index.
287 if declIdx, ok := byPkgPath[PackagePath(res.PkgPath)]; ok {
288 loc, _ = declIdx.LocationOf(res.ObjectPath)
289 }
290 if loc.Filename == "" {
291 // The declaring package wasn't in
292 // AllMetadata, or the method isn't in
293 // its index (e.g., unexported receiver
294 // type that isn't package-level).
295 // Neither should occur for a method
296 // promoted into a package-level type.
297 bug.Reportf("methodsets: no location for %s.%s", res.PkgPath, res.ObjectPath)
298 continue
299 }
300 }
301 // Map offsets to protocol.Locations in parallel (may involve I/O).
302 group.Go(func() error {
303 ploc, err := offsetToLocation(ctx, snapshot, loc.Filename, loc.Start, loc.End)
304 if err != nil {
305 return err
306 }
307 yield(index.PkgPath, res.TypeName, res.IsInterface, ploc)
308 return nil
309 })
310 }
311 return nil
312 })
313 }
314 return group.Wait()
315 }
316
317 // typeOrMethod returns the type and optional method to use in an
318 // Implementations operation on the specified symbol.
319 // It returns a nil type to indicate that the query should not proceed.
320 //
321 // (It is factored out to allow it to be used both in the query package
322 // then (in [localImplementations]) again in the declaring package.)
323 func typeOrMethod(obj types.Object) (types.Type, *types.Func) {
324 switch obj := obj.(type) {
325 case *types.TypeName:
326 return obj.Type(), nil
327 case *types.Func:
328 // For methods, use the receiver type, which may be anonymous.
329 if recv := obj.Signature().Recv(); recv != nil {
330 return recv.Type(), obj
331 }
332 }
333 return nil, nil
334 }
335
336 // offsetToLocation converts an offset-based position to a protocol.Location,
337 // which requires reading the file.
338 func offsetToLocation(ctx context.Context, snapshot *cache.Snapshot, filename string, start, end int) (protocol.Location, error) {
339 uri := protocol.URIFromPath(filename)
340 fh, err := snapshot.ReadFile(ctx, uri)
341 if err != nil {
342 return protocol.Location{}, err // cancelled, perhaps
343 }
344 content, err := fh.Content()
345 if err != nil {
346 return protocol.Location{}, err // nonexistent or deleted ("can't happen")
347 }
348 m := protocol.NewMapper(uri, content)
349 return m.OffsetLocation(start, end)
350 }
351
352 // implementsObj returns the object to query for implementations,
353 // which is a type name or method.
354 func implementsObj(info *types.Info, cur inspector.Cursor) (types.Object, error) {
355 // This function inherits the limitation of its predecessor in
356 // requiring the selection to be an identifier (of a type or
357 // method). But there's no fundamental reason why one could
358 // not pose this query about any selected piece of syntax that
359 // has a type and thus a method set.
360 // (If LSP was more thorough about passing text selections as
361 // intervals to queries, you could ask about the method set of a
362 // subexpression such as x.f().)
363 // [Note that this process has begun; see #69058.]
364 id, ok := cur.Node().(*ast.Ident)
365 if !ok {
366 return nil, ErrNoIdentFound
367 }
368
369 // Is the object a type or method? Reject other kinds.
370 obj := info.Uses[id]
371 if obj == nil {
372 // Check uses first (unlike ObjectOf) so that T in
373 // struct{T} is treated as a reference to a type,
374 // not a declaration of a field.
375 obj = info.Defs[id]
376 }
377 switch obj := obj.(type) {
378 case *types.TypeName:
379 // ok
380 case *types.Func:
381 if obj.Signature().Recv() == nil {
382 return nil, fmt.Errorf("%s is a function, not a method (query at 'func' token to find matching signatures)", id.Name)
383 }
384 case nil:
385 return nil, fmt.Errorf("%s denotes unknown object", id.Name)
386 default:
387 // e.g. *types.Var -> "var".
388 kind := strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types."))
389 // TODO(adonovan): improve upon "nil is a nil, not a type".
390 return nil, fmt.Errorf("%s is a %s, not a type", id.Name, kind)
391 }
392
393 return obj, nil
394 }
395
396 // localImplementations searches within pkg for declarations of all
397 // supertypes (if rel contains Supertype) or subtypes (if rel contains
398 // Subtype) of the type or method declared by id within the same
399 // package, and returns a new unordered array of their locations.
400 //
401 // If method is non-nil, the function instead returns the location
402 // of each type's method (if any) of that ID.
403 //
404 // ("Local" refers to the search within the same package, but this
405 // function's results may include type declarations that are local to
406 // a function body. The global search index excludes such types
407 // because reliably naming such types is hard.)
408 //
409 // Results are reported via the yield function.
410 func localImplementations(ctx context.Context, snapshot *cache.Snapshot, pkg *cache.Package, id *ast.Ident, rel methodsets.TypeRelation, yield implYieldFunc) error {
411 queryType, queryMethod := typeOrMethod(pkg.TypesInfo().Defs[id])
412 if queryType == nil {
413 return bug.Errorf("can't find corresponding symbol for %q in package %q", id.Name, pkg)
414 }
415 queryType = methodsets.EnsurePointer(queryType)
416
417 var msets typeutil.MethodSetCache
418
419 matches := func(candidateType types.Type) bool {
420 // Test the direction of the relation.
421 // The client may request either direction or both
422 // (e.g. when the client is References),
423 // and the Result reports each test independently;
424 // both tests succeed when comparing identical
425 // interface types.
426 var got methodsets.TypeRelation
427 if rel&methodsets.Supertype != 0 && implements(&msets, queryType, candidateType) {
428 got |= methodsets.Supertype
429 }
430 if rel&methodsets.Subtype != 0 && implements(&msets, candidateType, queryType) {
431 got |= methodsets.Subtype
432 }
433 return got != 0
434 }
435
436 // Scan through all type declarations in the syntax.
437 for _, pgf := range pkg.CompiledGoFiles() {
438 for cur := range pgf.Cursor().Preorder((*ast.TypeSpec)(nil)) {
439 spec := cur.Node().(*ast.TypeSpec)
440 if spec.Name == id {
441 continue // avoid self-comparison of query type
442 }
443 def := pkg.TypesInfo().Defs[spec.Name]
444 if def == nil {
445 continue // "can't happen" for types
446 }
447 if def.(*types.TypeName).IsAlias() {
448 continue // skip type aliases to avoid duplicate reporting
449 }
450 candidateType := methodsets.EnsurePointer(def.Type())
451 if !matches(candidateType) {
452 continue
453 }
454
455 // Ignore types with empty method sets.
456 // (No point reporting that every type satisfies 'any'.)
457 mset := msets.MethodSet(candidateType)
458 if mset.Len() == 0 {
459 continue
460 }
461
462 isInterface := types.IsInterface(def.Type())
463
464 if queryMethod == nil {
465 // Found matching type.
466 loc := mustLocation(pgf, spec.Name)
467 yield(pkg.Metadata().PkgPath, spec.Name.Name, isInterface, loc)
468 continue
469 }
470
471 // Find corresponding method.
472 //
473 // We can't use LookupFieldOrMethod because it requires
474 // the methodID's types.Package, which we don't know.
475 // We could recursively search pkg.Imports for it,
476 // but it's easier to walk the method set.
477 for method := range mset.Methods() {
478 m := method.Obj()
479 if m.Pos() == id.Pos() {
480 continue // avoid self-comparison of query method
481 }
482 if m.Id() == queryMethod.Id() {
483 posn := safetoken.StartPosition(pkg.FileSet(), m.Pos())
484 loc, err := offsetToLocation(ctx, snapshot, posn.Filename, posn.Offset, posn.Offset+len(m.Name()))
485 if err != nil {
486 return err
487 }
488 yield(pkg.Metadata().PkgPath, m.Name(), isInterface, loc)
489 break
490 }
491 }
492 }
493 }
494
495 // Special case: for types that satisfy error,
496 // report error in builtin.go (see #59527).
497 //
498 // (An inconsistency: we always report the type error
499 // even when the query was for the method error.Error.)
500 if matches(errorType) {
501 loc, err := errorLocation(ctx, snapshot)
502 if err != nil {
503 return err
504 }
505 yield("", "error", true, loc)
506 }
507
508 return nil
509 }
510
511 var errorType = types.Universe.Lookup("error").Type()
512
513 // errorLocation returns the location of the 'error' type in builtin.go.
514 func errorLocation(ctx context.Context, snapshot *cache.Snapshot) (protocol.Location, error) {
515 pgf, err := snapshot.BuiltinFile(ctx)
516 if err != nil {
517 return protocol.Location{}, err
518 }
519 for _, decl := range pgf.File.Decls {
520 if decl, ok := decl.(*ast.GenDecl); ok {
521 for _, spec := range decl.Specs {
522 if spec, ok := spec.(*ast.TypeSpec); ok && spec.Name.Name == "error" {
523 return pgf.NodeLocation(spec.Name)
524 }
525 }
526 }
527 }
528 return protocol.Location{}, fmt.Errorf("built-in error type not found")
529 }
530
531 // implements reports whether x implements y.
532 // If one or both types are generic, the result indicates whether the
533 // interface may be implemented under some instantiation.
534 func implements(msets *typeutil.MethodSetCache, x, y types.Type) bool {
535 if !types.IsInterface(y) {
536 return false
537 }
538
539 // For each interface method of y, check that x has it too.
540 // It is not necessary to compute x's complete method set.
541 //
542 // If y is a constraint interface (!y.IsMethodSet()), we
543 // ignore non-interface terms, leading to occasional spurious
544 // matches. We could in future filter based on them, but it
545 // would lead to divergence with the global (fingerprint-based)
546 // algorithm, which operates only on methodsets.
547 ymset := msets.MethodSet(y)
548 for method := range ymset.Methods() {
549 ym := method.Obj().(*types.Func)
550
551 xobj, _, _ := types.LookupFieldOrMethod(x, false, ym.Pkg(), ym.Name())
552 xm, ok := xobj.(*types.Func)
553 if !ok {
554 return false // x lacks a method of y
555 }
556 if !unify(xm.Signature(), ym.Signature(), nil) {
557 return false // signatures do not match
558 }
559 }
560 return true // all methods found
561 }
562
563 // unify reports whether the types of x and y match.
564 //
565 // If unifier is nil, unify reports only whether it succeeded.
566 // If unifier is non-nil, it is populated with the values
567 // of type parameters determined during a successful unification.
568 // If unification succeeds without binding a type parameter, that parameter
569 // will not be present in the map.
570 //
571 // On entry, the unifier's contents are treated as the values of already-bound type
572 // parameters, constraining the unification.
573 //
574 // For example, if unifier is an empty (not nil) map on entry, then the types
575 //
576 // func[T any](T, int)
577 //
578 // and
579 //
580 // func[U any](bool, U)
581 //
582 // will unify, with T=bool and U=int.
583 // That is, the contents of unifier after unify returns will be
584 //
585 // {T: bool, U: int}
586 //
587 // where "T" is the type parameter T and "bool" is the basic type for bool.
588 //
589 // But if unifier is {T: int} is int on entry, then unification will fail, because T
590 // does not unify with bool.
591 //
592 // Unify does not preserve aliases. For example, given the following:
593 //
594 // type String = string
595 // type A[T] = T
596 //
597 // unification succeeds with T bound to string, not String.
598 //
599 // See also: unify in cache/methodsets/fingerprint, which implements
600 // unification for type fingerprints, for the global index.
601 //
602 // BUG: literal interfaces are not handled properly. But this function is currently
603 // used only for signatures, where such types are very rare.
604 func unify(x, y types.Type, unifier map[*types.TypeParam]types.Type) bool {
605 // bindings[tp] is the binding for type parameter tp.
606 // Although type parameters are nominally bound to types, each bindings[tp]
607 // is a pointer to a type, so unbound variables that unify can share a binding.
608 bindings := map[*types.TypeParam]*types.Type{}
609
610 // Bindings is initialized with pointers to the provided types.
611 for tp, t := range unifier {
612 bindings[tp] = &t
613 }
614
615 // bindingFor returns the *types.Type in bindings for tp if tp is not nil,
616 // creating one if needed.
617 bindingFor := func(tp *types.TypeParam) *types.Type {
618 if tp == nil {
619 return nil
620 }
621 b := bindings[tp]
622 if b == nil {
623 b = new(types.Type)
624 bindings[tp] = b
625 }
626 return b
627 }
628
629 // bind sets b to t if b does not occur in t.
630 bind := func(b *types.Type, t types.Type) bool {
631 for tp := range typeParams(t) {
632 if b == bindings[tp] {
633 return false // failed "occurs" check
634 }
635 }
636 *b = t
637 return true
638 }
639
640 // uni performs the actual unification.
641 depth := 0
642 var uni func(x, y types.Type) bool
643 uni = func(x, y types.Type) bool {
644 // Panic if recursion gets too deep, to detect bugs before
645 // overflowing the stack.
646 depth++
647 defer func() { depth-- }()
648 if depth > 100 {
649 panic("unify: max depth exceeded")
650 }
651
652 x = types.Unalias(x)
653 y = types.Unalias(y)
654
655 tpx, _ := x.(*types.TypeParam)
656 tpy, _ := y.(*types.TypeParam)
657 if tpx != nil || tpy != nil {
658 // Identical type params unify.
659 if tpx == tpy {
660 return true
661 }
662 bx := bindingFor(tpx)
663 by := bindingFor(tpy)
664
665 // If both args are type params and neither is bound, have them share a binding.
666 if bx != nil && by != nil && *bx == nil && *by == nil {
667 // Arbitrarily give y's binding to x.
668 bindings[tpx] = by
669 return true
670 }
671 // Treat param bindings like original args in what follows.
672 if bx != nil && *bx != nil {
673 x = *bx
674 }
675 if by != nil && *by != nil {
676 y = *by
677 }
678 // If the x param is unbound, bind it to y.
679 if bx != nil && *bx == nil {
680 return bind(bx, y)
681 }
682 // If the y param is unbound, bind it to x.
683 if by != nil && *by == nil {
684 return bind(by, x)
685 }
686 // Unify the binding of a bound parameter.
687 return uni(x, y)
688 }
689
690 // Neither arg is a type param.
691
692 if reflect.TypeOf(x) != reflect.TypeOf(y) {
693 return false // mismatched types
694 }
695
696 switch x := x.(type) {
697 case *types.Array:
698 y := y.(*types.Array)
699 return x.Len() == y.Len() &&
700 uni(x.Elem(), y.Elem())
701
702 case *types.Basic:
703 y := y.(*types.Basic)
704 return x.Kind() == y.Kind()
705
706 case *types.Chan:
707 y := y.(*types.Chan)
708 return x.Dir() == y.Dir() &&
709 uni(x.Elem(), y.Elem())
710
711 case *types.Interface:
712 y := y.(*types.Interface)
713 // TODO(adonovan,jba): fix: for correctness, we must check
714 // that both interfaces have the same set of methods
715 // modulo type parameters, while avoiding the risk of
716 // unbounded interface recursion.
717 //
718 // Since non-empty interface literals are vanishingly
719 // rare in methods signatures, we ignore this for now.
720 // If more precision is needed we could compare method
721 // names and arities, still without full recursion.
722 return x.NumMethods() == y.NumMethods()
723
724 case *types.Map:
725 y := y.(*types.Map)
726 return uni(x.Key(), y.Key()) &&
727 uni(x.Elem(), y.Elem())
728
729 case *types.Named:
730 y := y.(*types.Named)
731 if x.Origin() != y.Origin() {
732 return false // different named types
733 }
734 xtargs := x.TypeArgs()
735 ytargs := y.TypeArgs()
736 if xtargs.Len() != ytargs.Len() {
737 return false // arity error (ill-typed)
738 }
739 for i := range xtargs.Len() {
740 if !uni(xtargs.At(i), ytargs.At(i)) {
741 return false // mismatched type args
742 }
743 }
744 return true
745
746 case *types.Pointer:
747 y := y.(*types.Pointer)
748 return uni(x.Elem(), y.Elem())
749
750 case *types.Signature:
751 y := y.(*types.Signature)
752 return x.Variadic() == y.Variadic() &&
753 uni(x.Params(), y.Params()) &&
754 uni(x.Results(), y.Results())
755
756 case *types.Slice:
757 y := y.(*types.Slice)
758 return uni(x.Elem(), y.Elem())
759
760 case *types.Struct:
761 y := y.(*types.Struct)
762 if x.NumFields() != y.NumFields() {
763 return false
764 }
765 for i := range x.NumFields() {
766 xf := x.Field(i)
767 yf := y.Field(i)
768 if xf.Embedded() != yf.Embedded() ||
769 xf.Name() != yf.Name() ||
770 x.Tag(i) != y.Tag(i) ||
771 !xf.Exported() && xf.Pkg() != yf.Pkg() ||
772 !uni(xf.Type(), yf.Type()) {
773 return false
774 }
775 }
776 return true
777
778 case *types.Tuple:
779 y := y.(*types.Tuple)
780 if x.Len() != y.Len() {
781 return false
782 }
783 for i := range x.Len() {
784 if !uni(x.At(i).Type(), y.At(i).Type()) {
785 return false
786 }
787 }
788 return true
789
790 default: // incl. *Union, *TypeParam
791 panic(fmt.Sprintf("unexpected Type %#v", x))
792 }
793 }
794
795 if !uni(x, y) {
796 clear(unifier)
797 return false
798 }
799
800 // Populate the input map with the resulting types.
801 if unifier != nil {
802 for tparam, tptr := range bindings {
803 unifier[tparam] = *tptr
804 }
805 }
806 return true
807 }
808
809 // typeParams yields all the free type parameters within t that are relevant for
810 // unification.
811 //
812 // Note: this function is tailored for the specific needs of the unification algorithm.
813 // Don't try to use it for other purposes, see [typeparams.Free] instead.
814 func typeParams(t types.Type) iter.Seq[*types.TypeParam] {
815
816 return func(yield func(*types.TypeParam) bool) {
817 seen := map[*types.TypeParam]bool{} // yield each type param only once
818
819 // tps(t) yields each TypeParam in t and returns false to stop.
820 var tps func(types.Type) bool
821 tps = func(t types.Type) bool {
822 t = types.Unalias(t)
823
824 switch t := t.(type) {
825 case *types.TypeParam:
826 if seen[t] {
827 return true
828 }
829 seen[t] = true
830 return yield(t)
831
832 case *types.Basic:
833 return true
834
835 case *types.Array:
836 return tps(t.Elem())
837
838 case *types.Chan:
839 return tps(t.Elem())
840
841 case *types.Interface:
842 // TODO(jba): implement.
843 return true
844
845 case *types.Map:
846 return tps(t.Key()) && tps(t.Elem())
847
848 case *types.Named:
849 if t.Origin() == t {
850 // generic type: look at type params
851 return moreiters.Every(t.TypeParams().TypeParams(),
852 func(tp *types.TypeParam) bool { return tps(tp) })
853 }
854 // instantiated type: look at type args
855 return moreiters.Every(t.TypeArgs().Types(), tps)
856
857 case *types.Pointer:
858 return tps(t.Elem())
859
860 case *types.Signature:
861 return tps(t.Params()) && tps(t.Results())
862
863 case *types.Slice:
864 return tps(t.Elem())
865
866 case *types.Struct:
867 return moreiters.Every(t.Fields(),
868 func(v *types.Var) bool { return tps(v.Type()) })
869
870 case *types.Tuple:
871 return moreiters.Every(t.Variables(),
872 func(v *types.Var) bool { return tps(v.Type()) })
873
874 default: // incl. *Union
875 panic(fmt.Sprintf("unexpected Type %#v", t))
876 }
877 }
878
879 tps(t)
880 }
881 }
882
883 var (
884 // TODO(adonovan): why do various RPC handlers related to
885 // IncomingCalls return (nil, nil) on the protocol in response
886 // to this error? That seems like a violation of the protocol.
887 // Is it perhaps a workaround for VSCode behavior?
888 errNoObjectFound = errors.New("no object found")
889 )
890
891 // --- Implementations based on signature types --
892
893 // implFuncs finds Implementations based on func types.
894 //
895 // Just as an interface type abstracts a set of concrete methods, a
896 // function type abstracts a set of concrete functions. Gopls provides
897 // analogous operations for navigating from abstract to concrete and
898 // back in the domain of function types.
899 //
900 // A single type (for example http.HandlerFunc) can have both an
901 // underlying type of function (types.Signature) and have methods that
902 // cause it to implement an interface. To avoid a confusing user
903 // interface we want to separate the two operations so that the user
904 // can unambiguously specify the query they want.
905 //
906 // So, whereas Implementations queries on interface types are usually
907 // keyed by an identifier of a named type, Implementations queries on
908 // function types are keyed by the "func" keyword, or by the "(" of a
909 // call expression. The query relates two sets of locations:
910 //
911 // 1. the "func" token of each function declaration (FuncDecl or
912 // FuncLit). These are analogous to declarations of concrete
913 // methods.
914 //
915 // 2. uses of abstract functions:
916 //
917 // (a) the "func" token of each FuncType that is not part of
918 // Func{Decl,Lit}. These are analogous to interface{...} types.
919 //
920 // (b) the "(" paren of each dynamic call on a value of an
921 // abstract function type. These are analogous to references to
922 // interface method names, but no names are involved, which has
923 // historically made them hard to search for.
924 //
925 // An Implementations query on a location in set 1 returns set 2,
926 // and vice versa.
927 //
928 // curSel denotes the selected syntax node whose type drives the
929 // pos indicates the exact cursor position.
930 //
931 // implFuncs returns errNotHandled to indicate that we should try the
932 // regular method-sets algorithm.
933 func implFuncs(pkg *cache.Package, curSel inspector.Cursor, start, end token.Pos) ([]protocol.Location, error) {
934 info := pkg.TypesInfo()
935 if info.Types == nil || info.Defs == nil || info.Uses == nil {
936 panic("one of info.Types, .Defs or .Uses is nil")
937 }
938
939 // Find innermost enclosing FuncType or CallExpr.
940 //
941 // We are looking for specific tokens (FuncType.Func and
942 // CallExpr.Lparen), but FindPos prefers an adjoining
943 // subexpression: given f(x) without additional spaces between
944 // tokens, FindPos always returns either f or x, never the
945 // CallExpr itself. Thus we must ascend the tree.
946 //
947 // Another subtlety: due to an edge case in go/ast, FindPos at
948 // FuncDecl.Type.Func does not return FuncDecl.Type, only the
949 // FuncDecl, because the orders of tree positions and tokens
950 // are inconsistent. Consequently, the ancestors for a "func"
951 // token of Func{Lit,Decl} do not include FuncType, hence the
952 // explicit cases below.
953 for cur := range curSel.Enclosing(
954 (*ast.FuncDecl)(nil),
955 (*ast.FuncLit)(nil),
956 (*ast.FuncType)(nil),
957 (*ast.CallExpr)(nil),
958 ) {
959 switch n := cur.Node().(type) {
960 case *ast.FuncDecl, *ast.FuncLit:
961 if inToken(n.Pos(), "func", start, end) {
962 // Case 1: concrete function declaration.
963 // Report uses of corresponding function types.
964 switch n := n.(type) {
965 case *ast.FuncDecl:
966 return funcUses(pkg, info.Defs[n.Name].Type())
967 case *ast.FuncLit:
968 return funcUses(pkg, info.TypeOf(n.Type))
969 }
970 }
971
972 case *ast.FuncType:
973 if n.Func.IsValid() && inToken(n.Func, "func", start, end) && !beneathFuncDef(cur) {
974 // Case 2a: function type.
975 // Report declarations of corresponding concrete functions.
976 return funcDefs(pkg, info.TypeOf(n))
977 }
978
979 case *ast.CallExpr:
980 if inToken(n.Lparen, "(", start, end) {
981 t := dynamicFuncCallType(info, n)
982 if t == nil {
983 return nil, fmt.Errorf("not a dynamic function call")
984 }
985 // Case 2b: dynamic call of function value.
986 // Report declarations of corresponding concrete functions.
987 return funcDefs(pkg, t)
988 }
989 }
990 }
991
992 // It's probably a query of a named type or method.
993 // Fall back to the method-sets computation.
994 return nil, errNotHandled
995 }
996
997 var errNotHandled = errors.New("not handled")
998
999 // funcUses returns all locations in the workspace that are dynamic
1000 // uses of the specified function type.
1001 func funcUses(pkg *cache.Package, t types.Type) ([]protocol.Location, error) {
1002 var locs []protocol.Location
1003
1004 // local search
1005 for _, pgf := range pkg.CompiledGoFiles() {
1006 for cur := range pgf.Cursor().Preorder((*ast.CallExpr)(nil), (*ast.FuncType)(nil)) {
1007 var pos, end token.Pos
1008 var ftyp types.Type
1009 switch n := cur.Node().(type) {
1010 case *ast.CallExpr:
1011 ftyp = dynamicFuncCallType(pkg.TypesInfo(), n)
1012 pos, end = n.Lparen, n.Lparen+token.Pos(len("("))
1013
1014 case *ast.FuncType:
1015 if !beneathFuncDef(cur) {
1016 // func type (not def)
1017 ftyp = pkg.TypesInfo().TypeOf(n)
1018 pos, end = n.Func, n.Func+token.Pos(len("func"))
1019 }
1020 }
1021 if ftyp == nil {
1022 continue // missing type information
1023 }
1024 if unify(t, ftyp, nil) {
1025 loc, err := pgf.PosLocation(pos, end)
1026 if err != nil {
1027 return nil, err
1028 }
1029 locs = append(locs, loc)
1030 }
1031 }
1032 }
1033
1034 // TODO(adonovan): implement global search
1035
1036 return locs, nil
1037 }
1038
1039 // funcDefs returns all locations in the workspace that define
1040 // functions of the specified type.
1041 func funcDefs(pkg *cache.Package, t types.Type) ([]protocol.Location, error) {
1042 var locs []protocol.Location
1043
1044 // local search
1045 for _, pgf := range pkg.CompiledGoFiles() {
1046 for curFn := range pgf.Cursor().Preorder((*ast.FuncDecl)(nil), (*ast.FuncLit)(nil)) {
1047 fn := curFn.Node()
1048 var ftyp types.Type
1049 switch fn := fn.(type) {
1050 case *ast.FuncDecl:
1051 ftyp = pkg.TypesInfo().Defs[fn.Name].Type()
1052 case *ast.FuncLit:
1053 ftyp = pkg.TypesInfo().TypeOf(fn)
1054 }
1055 if ftyp == nil {
1056 continue // missing type information
1057 }
1058 if unify(t, ftyp, nil) {
1059 pos := fn.Pos()
1060 loc, err := pgf.PosLocation(pos, pos+token.Pos(len("func")))
1061 if err != nil {
1062 return nil, err
1063 }
1064 locs = append(locs, loc)
1065 }
1066 }
1067 }
1068
1069 // TODO(adonovan): implement global search, by analogy with
1070 // methodsets algorithm.
1071 //
1072 // One optimization: if any signature type has free package
1073 // names, look for matches only in packages among the rdeps of
1074 // those packages.
1075
1076 return locs, nil
1077 }
1078
1079 // beneathFuncDef reports whether the specified FuncType cursor is a
1080 // child of Func{Decl,Lit}.
1081 func beneathFuncDef(cur inspector.Cursor) bool {
1082 switch cur.ParentEdgeKind() {
1083 case edge.FuncDecl_Type, edge.FuncLit_Type:
1084 return true
1085 }
1086 return false
1087 }
1088
1089 // dynamicFuncCallType reports whether call is a dynamic (non-method) function call.
1090 // If so, it returns the function type, otherwise nil.
1091 //
1092 // Tested via ../test/marker/testdata/implementation/signature.txt.
1093 func dynamicFuncCallType(info *types.Info, call *ast.CallExpr) types.Type {
1094 if typesinternal.ClassifyCall(info, call) == typesinternal.CallDynamic {
1095 if tv, ok := info.Types[call.Fun]; ok {
1096 return tv.Type.Underlying()
1097 }
1098 }
1099 return nil
1100 }
1101
1102 // inToken reports whether (start, end) is within the token of
1103 // the specified position and string.
1104 func inToken(tokPos token.Pos, tokStr string, start, end token.Pos) bool {
1105 return tokPos <= start && end <= tokPos+token.Pos(len(tokStr))
1106 }