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