Debian Codegraph @

gopls/internal/golang/stubmethods/stubmethods.go

raw symbols SCIP
1 // Copyright 2022 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 stubmethods provides the analysis logic for the quick fix
6 // to "Declare missing methods of TYPE" errors. (The fix logic lives
7 // in golang.stubMethodsFixer.)
8 package stubmethods
9
10 import (
11 "bytes"
12 "fmt"
13 "go/ast"
14 "go/token"
15 "go/types"
16 "strings"
17
18 "golang.org/x/tools/go/ast/edge"
19 "golang.org/x/tools/go/ast/inspector"
20 "golang.org/x/tools/internal/typeparams"
21 "golang.org/x/tools/internal/typesinternal"
22
23 "golang.org/x/tools/gopls/internal/cache/parsego"
24 "golang.org/x/tools/gopls/internal/util/typesutil"
25 )
26
27 // IfaceStubInfo represents a concrete type
28 // that wants to stub out an interface type
29 type IfaceStubInfo struct {
30 Fset *token.FileSet
31 Interface types.Type // interface type to implement (may be unnamed, named, or even instantiated)
32 Concrete typesinternal.NamedOrAlias // concrete type on which to declare methods
33 Pointer bool
34 }
35
36 // GetIfaceStubInfo determines whether the "missing method error"
37 // can be used to deduced what the concrete and interface types are.
38 //
39 // TODO(adonovan): this function (and its following 5 helpers) tries
40 // to deduce a pair of (concrete, interface) types that are related by
41 // an assignment, either explicitly or through a return statement or
42 // function call. This is essentially what the refactor/satisfy does,
43 // more generally. Refactor to share logic, after auditing 'satisfy'
44 // for safety on ill-typed code.
45 func GetIfaceStubInfo(fset *token.FileSet, info *types.Info, pgf *parsego.File, pos, end token.Pos) *IfaceStubInfo {
46 cur, _ := pgf.Cursor().FindByPos(pos, end)
47 for cur := range cur.Enclosing() {
48 // TODO: do cur = unparenEnclosing(cur) first, once CL 701035 lands.
49 switch cur.ParentEdgeKind() {
50 case edge.ValueSpec_Values:
51 return fromValueSpec(fset, info, cur)
52 case edge.ReturnStmt_Results:
53 // An error here may not indicate a real error the user should know about, but it may.
54 // Therefore, it would be best to log it out for debugging/reporting purposes instead of ignoring
55 // it. However, event.Log takes a context which is not passed via the analysis package.
56 // TODO(marwan-at-work): properly log this error.
57 si, _ := fromReturnStmt(fset, info, cur)
58 return si
59 case edge.AssignStmt_Rhs:
60 return fromAssignStmt(fset, info, cur)
61 case edge.CallExpr_Args:
62 // Note that some call expressions don't carry the interface type
63 // because they don't point to a function or method declaration elsewhere.
64 // For eaxmple, "var Interface = (*Concrete)(nil)". In that case, continue
65 // this loop to encounter other possibilities such as *ast.ValueSpec or others.
66 si := fromCallExpr(fset, info, cur)
67 if si != nil {
68 return si
69 }
70 }
71 }
72 return nil
73 }
74
75 // Emit writes to out the missing methods of si.Concrete required for it to implement si.Interface
76 func (si *IfaceStubInfo) Emit(out *bytes.Buffer, qual types.Qualifier) error {
77 conc := si.Concrete.Obj()
78 // Record all direct methods of the current object
79 concreteFuncs := make(map[string]struct{})
80 if named, ok := types.Unalias(si.Concrete).(*types.Named); ok {
81 for method := range named.Methods() {
82 concreteFuncs[method.Name()] = struct{}{}
83 }
84 }
85
86 // Find subset of interface methods that the concrete type lacks.
87 var missing []*types.Func
88 for imethod := range si.Interface.Underlying().(*types.Interface).Methods() {
89 cmethod, index, _ := types.LookupFieldOrMethod(si.Concrete, si.Pointer, imethod.Pkg(), imethod.Name())
90 if cmethod == nil {
91 missing = append(missing, imethod)
92 continue
93 }
94
95 if _, ok := cmethod.(*types.Var); ok {
96 // len(LookupFieldOrMethod.index) = 1 => conflict, >1 => shadow.
97 return fmt.Errorf("adding method %s.%s would conflict with (or shadow) existing field",
98 conc.Name(), imethod.Name())
99 }
100
101 if _, exist := concreteFuncs[imethod.Name()]; exist {
102 if !types.Identical(cmethod.Type(), imethod.Type()) {
103 return fmt.Errorf("method %s.%s already exists but has the wrong type: got %s, want %s",
104 conc.Name(), imethod.Name(), cmethod.Type(), imethod.Type())
105 }
106 continue
107 }
108
109 if len(index) > 0 {
110 // len(index) > 0 implies that the current method is already
111 // implemented on some embedded object.
112 // Do not generate a method if it would result in shadowing, but
113 // continue generating other parts of the stub.
114 // For example, if some struct A partially implements an interface I
115 // and another struct B embeds A, we should not implement methods on
116 // B that are already implemented on A, as these would be shadowed
117 // methods.
118 continue
119 }
120
121 missing = append(missing, imethod)
122 }
123 if len(missing) == 0 {
124 return fmt.Errorf("no missing methods found")
125 }
126
127 // Format doc link to interface type for "implements" doc comment.
128 ifaceLink := "an anonymous interface"
129 // (I don't know why we unalias here, other than issue65024.txt wants it.)
130 if named, ok := types.Unalias(si.Interface).(*types.Named); ok {
131 ifaceLink = named.Obj().Name()
132 if ipkg := named.Obj().Pkg(); ipkg != nil && ipkg != conc.Pkg() {
133 ifaceLink = ipkg.Name() + "." + ifaceLink
134 }
135 ifaceLink = "[" + ifaceLink + "]"
136 }
137
138 // Pointer receiver?
139 var star string
140 if si.Pointer {
141 star = "*"
142 }
143
144 // If there are any that have named receiver, choose the first one.
145 // Otherwise, use lowercase for the first letter of the object.
146 rn := strings.ToLower(si.Concrete.Obj().Name()[0:1])
147 if named, ok := types.Unalias(si.Concrete).(*types.Named); ok {
148 for method := range named.Methods() {
149 if recv := method.Signature().Recv(); recv.Name() != "" {
150 rn = recv.Name()
151 break
152 }
153 }
154 }
155
156 // Check for receiver name conflicts
157 checkRecvName := func(tuple *types.Tuple) bool {
158 for v := range tuple.Variables() {
159 if rn == v.Name() {
160 return true
161 }
162 }
163 return false
164 }
165
166 for index := range missing {
167 mrn := rn + " "
168 sig := missing[index].Signature()
169 if checkRecvName(sig.Params()) || checkRecvName(sig.Results()) {
170 mrn = ""
171 }
172
173 fmt.Fprintf(out, `// %s implements %s.
174 func (%s%s%s%s) %s%s {
175 panic("unimplemented")
176 }
177 `,
178 missing[index].Name(),
179 ifaceLink,
180 mrn,
181 star,
182 si.Concrete.Obj().Name(),
183 typesutil.FormatTypeParams(si.Concrete.TypeParams()),
184 missing[index].Name(),
185 strings.TrimPrefix(types.TypeString(missing[index].Type(), qual), "func"))
186 }
187 return nil
188 }
189
190 // fromCallExpr tries to find an *ast.CallExpr's function declaration and
191 // analyzes a function call's signature against the passed in call argument to deduce
192 // the concrete and interface types.
193 func fromCallExpr(fset *token.FileSet, info *types.Info, curCallArg inspector.Cursor) *IfaceStubInfo {
194
195 call := curCallArg.Parent().Node().(*ast.CallExpr)
196 arg := curCallArg.Node().(ast.Expr)
197
198 concType, pointer := concreteType(arg, info)
199 if concType == nil || concType.Obj().Pkg() == nil {
200 return nil
201 }
202 sig, ok := types.Unalias(info.TypeOf(call.Fun)).(*types.Signature)
203 if !ok {
204 return nil
205 }
206
207 argIdx := curCallArg.ParentEdgeIndex()
208 var paramType types.Type
209 if sig.Variadic() && argIdx >= sig.Params().Len()-1 {
210 v := sig.Params().At(sig.Params().Len() - 1)
211 if s, _ := v.Type().(*types.Slice); s != nil {
212 paramType = s.Elem()
213 }
214 } else if argIdx < sig.Params().Len() {
215 paramType = sig.Params().At(argIdx).Type()
216 }
217 if !validInterface(paramType) {
218 return nil
219 }
220 return &IfaceStubInfo{
221 Fset: fset,
222 Concrete: concType,
223 Pointer: pointer,
224 Interface: paramType,
225 }
226 }
227
228 // fromReturnStmt analyzes a "return" statement to extract
229 // a concrete type that is trying to be returned as an interface type.
230 //
231 // For example, func() io.Writer { return myType{} }
232 // would return StubIfaceInfo with the interface being io.Writer and the concrete type being myType{}.
233 func fromReturnStmt(fset *token.FileSet, info *types.Info, curResult inspector.Cursor) (*IfaceStubInfo, error) {
234 concType, pointer := concreteType(curResult.Node().(ast.Expr), info)
235 if concType == nil || concType.Obj().Pkg() == nil {
236 return nil, nil // result is not a named or *named or alias thereof
237 }
238 // Inv: the return is not a spread return,
239 // such as "return f()" where f() has tuple type.
240 conc := concType.Obj()
241 if conc.Parent() != conc.Pkg().Scope() {
242 return nil, fmt.Errorf("local type %q cannot be stubbed", conc.Name())
243 }
244
245 sig := typesutil.EnclosingSignature(curResult, info)
246 if sig == nil {
247 // Since curResult must be within a function, this
248 // indicates that the function's type information is
249 // missing, for example because there are two
250 // functions with the same name.
251 return nil, fmt.Errorf("function enclosing return statement has incomplete type information")
252 }
253 rets := sig.Results()
254 // The return operands and function results must match.
255 // (Spread returns were rejected earlier.)
256 ret := curResult.Parent().Node().(*ast.ReturnStmt)
257 if rets.Len() != len(ret.Results) {
258 return nil, fmt.Errorf("%d-operand return statement in %d-result function",
259 len(ret.Results),
260 rets.Len())
261 }
262 iface := rets.At(curResult.ParentEdgeIndex()).Type()
263 if !validInterface(iface) {
264 return nil, nil
265 }
266 return &IfaceStubInfo{
267 Fset: fset,
268 Concrete: concType,
269 Pointer: pointer,
270 Interface: iface,
271 }, nil
272 }
273
274 // fromValueSpec returns *StubIfaceInfo from a variable declaration such as
275 // var x io.Writer = &T{}
276 func fromValueSpec(fset *token.FileSet, info *types.Info, curValue inspector.Cursor) *IfaceStubInfo {
277
278 rhs := curValue.Node().(ast.Expr)
279 spec := curValue.Parent().Node().(*ast.ValueSpec)
280
281 // Possible implicit/explicit conversion to interface type?
282 ifaceNode := spec.Type // var _ myInterface = ...
283 if call, ok := rhs.(*ast.CallExpr); ok && ifaceNode == nil && len(call.Args) == 1 {
284 // var _ = myInterface(v)
285 ifaceNode = call.Fun
286 rhs = call.Args[0]
287 }
288 concType, pointer := concreteType(rhs, info)
289 if concType == nil || concType.Obj().Pkg() == nil {
290 return nil
291 }
292 conc := concType.Obj()
293 if conc.Parent() != conc.Pkg().Scope() {
294 return nil
295 }
296
297 iface := info.TypeOf(ifaceNode)
298 if !validInterface(iface) {
299 return nil
300 }
301 return &IfaceStubInfo{
302 Fset: fset,
303 Concrete: concType,
304 Interface: iface,
305 Pointer: pointer,
306 }
307 }
308
309 // fromAssignStmt returns *StubIfaceInfo from a variable assignment such as
310 // var x io.Writer
311 // x = &T{}
312 func fromAssignStmt(fset *token.FileSet, info *types.Info, curRhs inspector.Cursor) *IfaceStubInfo {
313 // The interface conversion error in an assignment is against the RHS:
314 //
315 // var x io.Writer
316 // x = &T{} // error: missing method
317 // ^^^^
318
319 assign := curRhs.Parent().Node().(*ast.AssignStmt)
320 idx := curRhs.ParentEdgeIndex()
321 // ill-type code may have fewer LHS than RHS so guard it.
322 if idx >= len(assign.Lhs) {
323 return nil
324 }
325 lhs, rhs := assign.Lhs[idx], curRhs.Node().(ast.Expr)
326
327 iface := info.TypeOf(lhs)
328 if !validInterface(iface) {
329 return nil
330 }
331 concType, pointer := concreteType(rhs, info)
332 if concType == nil || concType.Obj().Pkg() == nil {
333 return nil
334 }
335 conc := concType.Obj()
336 if conc.Parent() != conc.Pkg().Scope() {
337 return nil
338 }
339 return &IfaceStubInfo{
340 Fset: fset,
341 Concrete: concType,
342 Interface: iface,
343 Pointer: pointer,
344 }
345 }
346
347 // concreteType tries to extract the *types.Named that defines
348 // the concrete type given the ast.Expr where the "missing method"
349 // or "conversion" errors happened. If the concrete type is something
350 // that cannot have methods defined on it (such as basic types), this
351 // method will return a nil *types.Named. The second return parameter
352 // is a boolean that indicates whether the concreteType was defined as a
353 // pointer or value.
354 func concreteType(e ast.Expr, info *types.Info) (*types.Named, bool) {
355 t := info.TypeOf(e)
356 ptr, isPtr := types.Unalias(t).(*types.Pointer)
357 if isPtr {
358 t = ptr.Elem()
359 }
360 named, ok := types.Unalias(t).(*types.Named)
361 if !ok {
362 return nil, false
363 }
364 return named, isPtr
365 }
366
367 // validInterface reports whether iface is a non-nil interface
368 // type with no free type parameters.
369 func validInterface(iface types.Type) bool {
370 return iface != nil &&
371 types.IsInterface(iface) &&
372 !new(typeparams.Free).Has(iface)
373 }