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