Debian Codegraph @

gopls/internal/golang/stubmethods/stubcalledfunc.go

raw symbols SCIP
1 // Copyright 2024 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
6
7 import (
8 "bytes"
9 "fmt"
10 "go/ast"
11 "go/token"
12 "go/types"
13 "strings"
14 "unicode"
15
16 "golang.org/x/tools/go/ast/inspector"
17 "golang.org/x/tools/gopls/internal/cache/parsego"
18 "golang.org/x/tools/gopls/internal/util/cursorutil"
19 "golang.org/x/tools/gopls/internal/util/typesutil"
20 "golang.org/x/tools/internal/typesinternal"
21 )
22
23 var anyType = types.Universe.Lookup("any").Type()
24
25 // CallStubInfo represents a missing method
26 // that a receiver type is about to generate
27 // which has "type X has no field or method Y" error
28 type CallStubInfo struct {
29 Fset *token.FileSet // the FileSet used to type-check the types below
30 Receiver typesinternal.NamedOrAlias // the method's receiver type
31 MethodName string
32 After types.Object // decl after which to insert the new decl
33 pointer bool
34 info *types.Info
35 curCall inspector.Cursor // cursor to the CallExpr
36 }
37
38 // GetCallStubInfo extracts necessary information to generate a method definition from
39 // a CallExpr.
40 func GetCallStubInfo(fset *token.FileSet, info *types.Info, pgf *parsego.File, start, end token.Pos) *CallStubInfo {
41 callCur, _ := pgf.Cursor().FindByPos(start, end)
42 call, callCur := cursorutil.FirstEnclosing[*ast.CallExpr](callCur)
43 if call == nil {
44 return nil
45 }
46 s, ok := call.Fun.(*ast.SelectorExpr)
47 // TODO: support generating stub functions in the same way.
48 if !ok {
49 return nil
50 }
51
52 // If recvExpr is a package name, compiler error would be
53 // e.g., "undefined: http.bar", thus will not hit this code path.
54 recvExpr := s.X
55 recvType, pointer := concreteType(recvExpr, info)
56
57 if recvType == nil || recvType.Obj().Pkg() == nil {
58 return nil
59 }
60
61 // A method of a function-local type cannot be stubbed
62 // since there's nowhere to put the methods.
63 recv := recvType.Obj()
64 if recv.Parent() != recv.Pkg().Scope() {
65 return nil
66 }
67
68 after := types.Object(recv)
69 // If the enclosing function declaration is a method declaration,
70 // and matches the receiver type of the diagnostic,
71 // insert after the enclosing method.
72 decl, _ := cursorutil.FirstEnclosing[*ast.FuncDecl](callCur)
73 if decl != nil && decl.Recv != nil {
74 if len(decl.Recv.List) != 1 {
75 return nil
76 }
77 mrt := info.TypeOf(decl.Recv.List[0].Type)
78 if mrt != nil && types.Identical(types.Unalias(typesinternal.Unpointer(mrt)), recv.Type()) {
79 after = info.ObjectOf(decl.Name)
80 }
81 }
82 return &CallStubInfo{
83 Fset: fset,
84 Receiver: recvType,
85 MethodName: s.Sel.Name,
86 After: after,
87 pointer: pointer,
88 curCall: callCur,
89 info: info,
90 }
91 }
92
93 // Emit writes to out the missing method based on type info of si.Receiver and CallExpr.
94 func (si *CallStubInfo) Emit(out *bytes.Buffer, qual types.Qualifier) error {
95 params := si.collectParams()
96 rets := typesutil.TypesFromContext(si.info, si.curCall)
97 recv := si.Receiver.Obj()
98 // Pointer receiver?
99 var star string
100 if si.pointer {
101 star = "*"
102 }
103
104 // Choose receiver name.
105 // If any method has a named receiver, choose the first one.
106 // Otherwise, use lowercase for the first letter of the object.
107 recvName := strings.ToLower(fmt.Sprintf("%.1s", recv.Name()))
108 if named, ok := types.Unalias(si.Receiver).(*types.Named); ok {
109 for method := range named.Methods() {
110 if recv := method.Signature().Recv(); recv.Name() != "" {
111 recvName = recv.Name()
112 break
113 }
114 }
115 }
116
117 // Emit method declaration.
118 fmt.Fprintf(out, "\nfunc (%s %s%s%s) %s",
119 recvName,
120 star,
121 recv.Name(),
122 typesutil.FormatTypeParams(si.Receiver.TypeParams()),
123 si.MethodName)
124
125 // Emit parameters, avoiding name conflicts.
126 seen := map[string]bool{recvName: true}
127 out.WriteString("(")
128 for i, param := range params {
129 name := param.name
130 if seen[name] {
131 name = fmt.Sprintf("param%d", i+1)
132 }
133 seen[name] = true
134
135 if i > 0 {
136 out.WriteString(", ")
137 }
138 fmt.Fprintf(out, "%s %s", name, types.TypeString(param.typ, qual))
139 }
140 out.WriteString(") ")
141
142 // Emit result types.
143 if len(rets) > 1 {
144 out.WriteString("(")
145 }
146 for i, r := range rets {
147 if i > 0 {
148 out.WriteString(", ")
149 }
150 out.WriteString(types.TypeString(r, qual))
151 }
152 if len(rets) > 1 {
153 out.WriteString(")")
154 }
155
156 // Emit body.
157 out.WriteString(` {
158 panic("unimplemented")
159 }`)
160 return nil
161 }
162
163 type param struct {
164 name string
165 typ types.Type // the type of param, inferred from CallExpr
166 }
167
168 // collectParams gathers the parameter information needed to generate a method stub.
169 // The param's type default to any if there is a type error in the argument.
170 func (si *CallStubInfo) collectParams() []param {
171 var params []param
172 appendParam := func(e ast.Expr, t types.Type) {
173 p := param{"param", anyType}
174 if t != nil && !containsInvalid(t) {
175 t = types.Default(t)
176 p = param{paramName(e, t), t}
177 }
178 params = append(params, p)
179 }
180
181 args := si.curCall.Node().(*ast.CallExpr).Args
182 for _, arg := range args {
183 t := si.info.TypeOf(arg)
184 switch t := t.(type) {
185 // This is the case where another function call returning multiple
186 // results is used as an argument.
187 case *types.Tuple:
188 for v := range t.Variables() {
189 appendParam(arg, v.Type())
190 }
191 default:
192 appendParam(arg, t)
193 }
194 }
195 return params
196 }
197
198 // containsInvalid checks if the type name contains "invalid type",
199 // which is not a valid syntax to generate.
200 func containsInvalid(t types.Type) bool {
201 typeString := types.TypeString(t, nil)
202 return strings.Contains(typeString, types.Typ[types.Invalid].String())
203 }
204
205 // paramName heuristically chooses a parameter name from
206 // its argument expression and type. Caller should ensure
207 // typ is non-nil.
208 func paramName(e ast.Expr, typ types.Type) string {
209 if typ == types.Universe.Lookup("error").Type() {
210 return "err"
211 }
212 switch t := e.(type) {
213 // Use the identifier's name as the argument name.
214 case *ast.Ident:
215 return t.Name
216 // Use the Sel.Name's last section as the argument name.
217 case *ast.SelectorExpr:
218 return lastSection(t.Sel.Name)
219 }
220
221 typ = typesinternal.Unpointer(typ)
222 switch t := typ.(type) {
223 // Use the first character of the type name as the argument name for builtin types
224 case *types.Basic:
225 return t.Name()[:1]
226 case *types.Slice:
227 return paramName(e, t.Elem())
228 case *types.Array:
229 return paramName(e, t.Elem())
230 case *types.Signature:
231 return "f"
232 case *types.Map:
233 return "m"
234 case *types.Chan:
235 return "ch"
236 case *types.Named:
237 return lastSection(t.Obj().Name())
238 default:
239 return lastSection(t.String())
240 }
241 }
242
243 // lastSection find the position of the last uppercase letter,
244 // extract the substring from that point onward,
245 // and convert it to lowercase.
246 //
247 // Example: lastSection("registryManagerFactory") = "factory"
248 func lastSection(identName string) string {
249 lastUpperIndex := -1
250 for i, r := range identName {
251 if unicode.IsUpper(r) {
252 lastUpperIndex = i
253 }
254 }
255 if lastUpperIndex != -1 {
256 last := identName[lastUpperIndex:]
257 return strings.ToLower(last)
258 } else {
259 return identName
260 }
261 }