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