Source file
src/go/types/signature.go
1
2
3
4
5 package types
6
7 import (
8 "fmt"
9 "go/ast"
10 "go/token"
11 . "internal/types/errors"
12 "path/filepath"
13 "strings"
14 )
15
16
17
18
19
20
21 type Signature struct {
22
23
24
25
26 rparams *TypeParamList
27 tparams *TypeParamList
28 scope *Scope
29 recv *Var
30 params *Tuple
31 results *Tuple
32 variadic bool
33
34
35
36
37
38
39 }
40
41
42
43
44
45
46
47
48
49 func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature {
50 return NewSignatureType(recv, nil, nil, params, results, variadic)
51 }
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68 func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature {
69 if variadic {
70 n := params.Len()
71 if n == 0 {
72 panic("variadic function must have at least one parameter")
73 }
74 last := params.At(n - 1).typ
75 var S *Slice
76 for t := range typeset(last) {
77 if t == nil {
78 break
79 }
80 var s *Slice
81 if isString(t) {
82 s = NewSlice(universeByte)
83 } else {
84
85
86
87
88
89
90
91
92
93
94
95
96 s, _ = t.Underlying().(*Slice)
97 }
98 if S == nil {
99 S = s
100 } else if s == nil || !Identical(S, s) {
101 S = nil
102 break
103 }
104 }
105 if S == nil {
106 panic(fmt.Sprintf("got %s, want variadic parameter of slice or string type", last))
107 }
108 }
109 sig := &Signature{recv: recv, params: params, results: results, variadic: variadic}
110 if len(recvTypeParams) != 0 {
111 if recv == nil {
112 panic("function with receiver type parameters must have a receiver")
113 }
114 sig.rparams = bindTParams(recvTypeParams)
115 }
116 if len(typeParams) != 0 {
117 if recv != nil {
118 panic("function with type parameters cannot have a receiver")
119 }
120 sig.tparams = bindTParams(typeParams)
121 }
122 return sig
123 }
124
125
126
127
128
129
130
131 func (s *Signature) Recv() *Var { return s.recv }
132
133
134 func (s *Signature) TypeParams() *TypeParamList { return s.tparams }
135
136
137 func (s *Signature) RecvTypeParams() *TypeParamList { return s.rparams }
138
139
140
141 func (s *Signature) Params() *Tuple { return s.params }
142
143
144 func (s *Signature) Results() *Tuple { return s.results }
145
146
147 func (s *Signature) Variadic() bool { return s.variadic }
148
149 func (s *Signature) Underlying() Type { return s }
150 func (s *Signature) String() string { return TypeString(s, nil) }
151
152
153
154
155
156 func (check *Checker) funcType(sig *Signature, recvPar *ast.FieldList, ftyp *ast.FuncType) {
157 check.openScope(ftyp, "function")
158 check.scope.isFunc = true
159 check.recordScope(ftyp, check.scope)
160 sig.scope = check.scope
161 defer check.closeScope()
162
163
164 var recv *Var
165 var rparams *TypeParamList
166 if recvPar != nil && recvPar.NumFields() > 0 {
167
168 if n := len(recvPar.List); n > 1 {
169 check.error(recvPar.List[n-1], InvalidRecv, "method has multiple receivers")
170
171 }
172
173 scopePos := ftyp.Pos()
174 recv, rparams = check.collectRecv(recvPar.List[0], scopePos)
175 }
176
177
178 if ftyp.TypeParams != nil {
179 check.collectTypeParams(&sig.tparams, ftyp.TypeParams)
180 }
181
182
183 pnames, params, variadic := check.collectParams(ParamVar, ftyp.Params)
184 rnames, results, _ := check.collectParams(ResultVar, ftyp.Results)
185
186
187 scopePos := ftyp.End()
188 if recv != nil && recv.name != "" {
189 check.declare(check.scope, recvPar.List[0].Names[0], recv, scopePos)
190 }
191 check.declareParams(pnames, params, scopePos)
192 check.declareParams(rnames, results, scopePos)
193
194 sig.recv = recv
195 sig.rparams = rparams
196 sig.params = NewTuple(params...)
197 sig.results = NewTuple(results...)
198 sig.variadic = variadic
199 }
200
201
202
203
204 func (check *Checker) collectRecv(rparam *ast.Field, scopePos token.Pos) (*Var, *TypeParamList) {
205
206
207
208
209
210
211 rptr, rbase, rtparams := check.unpackRecv(rparam.Type, true)
212
213
214 var recvType Type = Typ[Invalid]
215 var recvTParamsList *TypeParamList
216 if rtparams == nil {
217
218
219
220
221
222 recvType = check.varType(rparam.Type)
223
224
225
226
227 a, _ := unpointer(recvType).(*Alias)
228 for a != nil {
229 baseType := unpointer(a.fromRHS)
230 if g, _ := baseType.(genericType); g != nil && g.TypeParams() != nil {
231 check.errorf(rbase, InvalidRecv, "cannot define new methods on instantiated type %s", g)
232 recvType = Typ[Invalid]
233 break
234 }
235 a, _ = baseType.(*Alias)
236 }
237 } else {
238
239
240
241 var baseType *Named
242 var cause string
243 if t := check.genericType(rbase, &cause); isValid(t) {
244 switch t := t.(type) {
245 case *Named:
246 baseType = t
247 case *Alias:
248
249
250 if isValid(t) {
251 check.errorf(rbase, InvalidRecv, "cannot define new methods on generic alias type %s", t)
252 }
253
254
255 default:
256 panic("unreachable")
257 }
258 } else {
259 if cause != "" {
260 check.errorf(rbase, InvalidRecv, "%s", cause)
261 }
262
263 }
264
265
266
267
268
269 recvTParams := make([]*TypeParam, len(rtparams))
270 for i, rparam := range rtparams {
271 tpar := check.declareTypeParam(rparam, scopePos)
272 recvTParams[i] = tpar
273
274
275
276 check.recordUse(rparam, tpar.obj)
277 check.recordTypeAndValue(rparam, typexpr, tpar, nil)
278 }
279 recvTParamsList = bindTParams(recvTParams)
280
281
282
283 if baseType != nil {
284 baseTParams := baseType.TypeParams().list()
285 if len(recvTParams) == len(baseTParams) {
286 smap := makeRenameMap(baseTParams, recvTParams)
287 for i, recvTPar := range recvTParams {
288 baseTPar := baseTParams[i]
289 check.mono.recordCanon(recvTPar, baseTPar)
290
291
292
293 recvTPar.bound = check.subst(recvTPar.obj.pos, baseTPar.bound, smap, nil, check.context())
294 }
295 } else {
296 got := measure(len(recvTParams), "type parameter")
297 check.errorf(rbase, BadRecv, "receiver declares %s, but receiver base type declares %d", got, len(baseTParams))
298 }
299
300
301
302 check.verifyVersionf(rbase, go1_18, "type instantiation")
303 targs := make([]Type, len(recvTParams))
304 for i, targ := range recvTParams {
305 targs[i] = targ
306 }
307 recvType = check.instance(rparam.Type.Pos(), baseType, targs, nil, check.context())
308 check.recordInstance(rbase, targs, recvType)
309
310
311 if rptr && isValid(recvType) {
312 recvType = NewPointer(recvType)
313 }
314
315 check.recordParenthesizedRecvTypes(rparam.Type, recvType)
316 }
317 }
318
319
320 var rname *ast.Ident
321 if n := len(rparam.Names); n >= 1 {
322 if n > 1 {
323 check.error(rparam.Names[n-1], InvalidRecv, "method has multiple receivers")
324 }
325 rname = rparam.Names[0]
326 }
327
328
329
330 var recv *Var
331 if rname != nil && rname.Name != "" {
332
333 recv = newVar(RecvVar, rname.Pos(), check.pkg, rname.Name, recvType)
334
335
336
337 } else {
338
339 recv = newVar(RecvVar, rparam.Pos(), check.pkg, "", recvType)
340 check.recordImplicit(rparam, recv)
341 }
342
343
344
345 check.later(func() {
346 check.validRecv(rbase, recv)
347 }).describef(recv, "validRecv(%s)", recv)
348
349 return recv, recvTParamsList
350 }
351
352 func unpointer(t Type) Type {
353 for {
354 p, _ := t.(*Pointer)
355 if p == nil {
356 return t
357 }
358 t = p.base
359 }
360 }
361
362
363
364
365
366
367
368
369
370
371
372 func (check *Checker) recordParenthesizedRecvTypes(expr ast.Expr, typ Type) {
373 for {
374 check.recordTypeAndValue(expr, typexpr, typ, nil)
375 switch e := expr.(type) {
376 case *ast.ParenExpr:
377 expr = e.X
378 case *ast.StarExpr:
379 expr = e.X
380
381
382 ptr, _ := typ.(*Pointer)
383 if ptr == nil {
384 return
385 }
386 typ = ptr.base
387 default:
388 return
389 }
390 }
391 }
392
393
394
395
396
397 func (check *Checker) collectParams(kind VarKind, list *ast.FieldList) (names []*ast.Ident, params []*Var, variadic bool) {
398 if list == nil {
399 return
400 }
401
402 var named, anonymous bool
403 for i, field := range list.List {
404 ftype := field.Type
405 if t, _ := ftype.(*ast.Ellipsis); t != nil {
406 ftype = t.Elt
407 if kind == ParamVar && i == len(list.List)-1 && len(field.Names) <= 1 {
408 variadic = true
409 } else {
410 check.softErrorf(t, InvalidSyntaxTree, "invalid use of ...")
411
412 }
413 }
414 typ := check.varType(ftype)
415
416
417 if len(field.Names) > 0 {
418
419 for _, name := range field.Names {
420 if name.Name == "" {
421 check.error(name, InvalidSyntaxTree, "anonymous parameter")
422
423 }
424 par := newVar(kind, name.Pos(), check.pkg, name.Name, typ)
425
426 names = append(names, name)
427 params = append(params, par)
428 }
429 named = true
430 } else {
431
432 par := newVar(kind, ftype.Pos(), check.pkg, "", typ)
433 check.recordImplicit(field, par)
434 names = append(names, nil)
435 params = append(params, par)
436 anonymous = true
437 }
438 }
439
440 if named && anonymous {
441 check.error(list, InvalidSyntaxTree, "list contains both named and anonymous parameters")
442
443 }
444
445
446
447
448 if variadic {
449 last := params[len(params)-1]
450 last.typ = &Slice{elem: last.typ}
451 check.recordTypeAndValue(list.List[len(list.List)-1].Type, typexpr, last.typ, nil)
452 }
453
454 return
455 }
456
457
458 func (check *Checker) declareParams(names []*ast.Ident, params []*Var, scopePos token.Pos) {
459 for i, name := range names {
460 if name != nil && name.Name != "" {
461 check.declare(check.scope, name, params[i], scopePos)
462 }
463 }
464 }
465
466
467
468 func (check *Checker) validRecv(pos positioner, recv *Var) {
469
470 rtyp, _ := deref(recv.typ)
471 atyp := Unalias(rtyp)
472 if !isValid(atyp) {
473 return
474 }
475
476
477
478 switch T := atyp.(type) {
479 case *Named:
480 if T.obj.pkg != check.pkg || isCGoTypeObj(check.fset, T.obj) {
481 check.errorf(pos, InvalidRecv, "cannot define new methods on non-local type %s", rtyp)
482 break
483 }
484 var cause string
485 switch u := T.Underlying().(type) {
486 case *Basic:
487
488 if u.kind == UnsafePointer {
489 cause = "unsafe.Pointer"
490 }
491 case *Pointer, *Interface:
492 cause = "pointer or interface type"
493 case *TypeParam:
494
495
496 panic("unreachable")
497 }
498 if cause != "" {
499 check.errorf(pos, InvalidRecv, "invalid receiver type %s (%s)", rtyp, cause)
500 }
501 case *Basic:
502 check.errorf(pos, InvalidRecv, "cannot define new methods on non-local type %s", rtyp)
503 default:
504 check.errorf(pos, InvalidRecv, "invalid receiver type %s", recv.typ)
505 }
506 }
507
508
509 func isCGoTypeObj(fset *token.FileSet, obj *TypeName) bool {
510 return strings.HasPrefix(obj.name, "_Ctype_") ||
511 strings.HasPrefix(filepath.Base(fset.File(obj.pos).Name()), "_cgo_")
512 }
513
View as plain text