Debian Codegraph @

gopls/internal/golang/implement_interface.go

raw symbols SCIP
1 // Copyright 2026 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 "fmt"
10 "go/ast"
11 "go/types"
12 "strings"
13
14 "golang.org/x/tools/gopls/internal/cache"
15 "golang.org/x/tools/gopls/internal/cache/metadata"
16 "golang.org/x/tools/gopls/internal/golang/stubmethods"
17 "golang.org/x/tools/gopls/internal/protocol"
18 "golang.org/x/tools/gopls/internal/util/cursorutil"
19 internalastutil "golang.org/x/tools/internal/astutil"
20 "golang.org/x/tools/internal/packagepath"
21 "golang.org/x/tools/internal/typesinternal"
22 )
23
24 // ImplementInterface generates workspace edits to add method stubs, making the
25 // package-level type at the given location implement the target interface.
26 //
27 // The ifaceStr must be "error" or a fully qualified name (e.g.,
28 // "example.com/pkg.Type").
29 func ImplementInterface(ctx context.Context, snapshot *cache.Snapshot, loc protocol.Location, ifaceStr string) (changes []protocol.DocumentChange, _ error) {
30 pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, loc.URI)
31 if err != nil {
32 return nil, err
33 }
34
35 metadataPkgForPath := func(pkgPath string) (*metadata.Package, error) {
36 mps, ok := snapshot.MetadataGraph().ForPackagePath[metadata.PackagePath(pkgPath)]
37 if !ok {
38 return nil, fmt.Errorf("package %q is not in the workspace", pkgPath)
39 }
40
41 if len(mps) == 0 {
42 return nil, fmt.Errorf("no package metadata for package %q", pkgPath)
43 }
44
45 return mps[0], nil
46 }
47
48 var (
49 iface *types.TypeName
50 ifacePkg *cache.Package
51 )
52 {
53 if ifaceStr == "error" {
54 iface = types.Universe.Lookup("error").(*types.TypeName)
55 } else {
56 lastDot := strings.LastIndex(ifaceStr, ".")
57 if lastDot == -1 {
58 return nil, fmt.Errorf(
59 `invalid interface type name (want string of form "example.com/pkg.Type"`)
60 } else {
61 // Do not assume the target package is already imported or type-checked
62 // in the current context. Look it up globally via the metadata graph.
63 pkgPath := ifaceStr[:lastDot]
64 symName := ifaceStr[lastDot+1:]
65
66 mp, err := metadataPkgForPath(pkgPath)
67 if err != nil {
68 return nil, err
69 }
70
71 pkgs, err := snapshot.TypeCheck(ctx, mp.ID)
72 if err != nil {
73 return nil, err
74 }
75
76 ifacePkg = pkgs[0]
77
78 obj := ifacePkg.Types().Scope().Lookup(symName)
79 if obj == nil {
80 return nil, fmt.Errorf("symbol %q not found in package %q", symName, pkgPath)
81 }
82
83 var ok bool
84 iface, ok = obj.(*types.TypeName)
85 if !ok {
86 return nil, fmt.Errorf("%s.%s is a %s, not a type", pkgPath, symName, typesinternal.ObjectKind(obj))
87 }
88
89 if !types.IsInterface(iface.Type()) {
90 return nil, fmt.Errorf("%s.%s is not an interface", pkgPath, symName)
91 }
92 }
93 }
94 }
95
96 var (
97 named *types.Named
98 namedPkg *metadata.Package
99 )
100 {
101 start, end, err := pgf.RangePos(loc.Range)
102 if err != nil {
103 return nil, err
104 }
105 cur, _, _, _ := internalastutil.Select(pgf.Cursor(), start, end) // can't fail: pgf contains pos
106
107 spec, curSpec := cursorutil.FirstEnclosing[*ast.TypeSpec](cur)
108 if spec == nil {
109 return nil, fmt.Errorf("no enclosing type declaration")
110 }
111
112 // Only package level.
113 if curSpec.Parent().Parent().Node() != pgf.File {
114 return nil, fmt.Errorf("enclosing type %s is not at package level", spec.Name.Name)
115 }
116
117 t, ok := types.Unalias(pkg.TypesInfo().TypeOf(spec.Name)).(*types.Named)
118 if !ok {
119 return nil, fmt.Errorf("enclosing type is not a named type")
120 }
121
122 if is[*types.Pointer](t.Underlying()) {
123 return nil, fmt.Errorf("cannot declare concrete methods on a pointer type %s", t.Obj().Name())
124 }
125
126 if types.IsInterface(t) {
127 return nil, fmt.Errorf("cannot declare concrete methods on a interface type %s", t.Obj().Name())
128 }
129
130 named = t
131 namedPkgPath := t.Obj().Pkg().Path()
132
133 namedPkg, err = metadataPkgForPath(namedPkgPath)
134 if err != nil {
135 return nil, err
136 }
137 }
138
139 // Reject cases that would add cycle-forming or disallowed internal imports
140 // for types mentioned in the added methods.
141 if ifaceStr != "error" && namedPkg != ifacePkg.Metadata() {
142 // extraPackages maps each referenced package to the method that introduced it.
143 extraPackages := make(map[*types.Package]*types.Func)
144 dependingOnX := snapshot.MetadataGraph().ReverseReflexiveTransitiveClosure(namedPkg.ID)
145 for m := range iface.Type().Underlying().(*types.Interface).Methods() {
146 if !m.Exported() {
147 return nil, fmt.Errorf("cannot add unexported method %s from package %s to type %s", m.Name(), namedPkg.Name, named.Obj().Name())
148 }
149 // Extract all packages referenced in the method signature.
150 _ = types.TypeString(m.Type(), func(p *types.Package) string {
151 extraPackages[p] = m
152 return ""
153 })
154 }
155 for p, method := range extraPackages {
156 mp, err := metadataPkgForPath(p.Path())
157 if err != nil {
158 return nil, err
159 }
160
161 if _, ok := dependingOnX[mp.ID]; ok {
162 return nil, fmt.Errorf("adding method %s to type %s would create an import cycle", method.Name(), named.Obj().Name())
163 }
164
165 if !packagepath.CanImport(namedPkg.String(), p.Path()) {
166 return nil, fmt.Errorf("adding method %s to type %s would require import of inaccessible package %s", method.Name(), named.Obj().Name(), p.Name())
167 }
168 }
169 }
170
171 // TODO(hxjiang): if the package contains the interface is visible and
172 // importable from the package contains the named type, consider add:
173 // var _ Interface = (*Type)(nil)
174 si := stubmethods.IfaceStubInfo{
175 Fset: pkg.FileSet(),
176 Interface: iface.Type(),
177 Concrete: named,
178 // TODO(hxjiang): consider make it question and let the user decide
179 // whether to use pointer receiver or not.
180 Pointer: true, // by default, use pointer receiver
181 }
182
183 // TODO(hxjiang): fix the comment position after insert the methods, see test
184 // result in testdata/codeaction/implement_interface.txt basic/good/good.go
185 fixFset, suggestion, err := insertDeclsAfter(ctx, snapshot, pkg.Metadata(), si.Fset, si.Concrete.Obj(), si.Emit)
186 if err != nil {
187 return nil, err
188 }
189
190 return suggestedFixToDocumentChange(ctx, snapshot, fixFset, suggestion)
191 }