]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/signature.go
go/types, types2: allow (string...) signature with NewSignatureType
[gostls13.git] / src / cmd / compile / internal / types2 / signature.go
1 // Copyright 2021 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 types2
6
7 import (
8         "cmd/compile/internal/syntax"
9         "fmt"
10 )
11
12 // ----------------------------------------------------------------------------
13 // API
14
15 // A Signature represents a (non-builtin) function or method type.
16 // The receiver is ignored when comparing signatures for identity.
17 type Signature struct {
18         // We need to keep the scope in Signature (rather than passing it around
19         // and store it in the Func Object) because when type-checking a function
20         // literal we call the general type checker which returns a general Type.
21         // We then unpack the *Signature and use the scope for the literal body.
22         rparams  *TypeParamList // receiver type parameters from left to right, or nil
23         tparams  *TypeParamList // type parameters from left to right, or nil
24         scope    *Scope         // function scope for package-local and non-instantiated signatures; nil otherwise
25         recv     *Var           // nil if not a method
26         params   *Tuple         // (incoming) parameters from left to right; or nil
27         results  *Tuple         // (outgoing) results from left to right; or nil
28         variadic bool           // true if the last parameter's type is of the form ...T (or string, for append built-in only)
29 }
30
31 // NewSignatureType creates a new function type for the given receiver,
32 // receiver type parameters, type parameters, parameters, and results. If
33 // variadic is set, params must hold at least one parameter and the last
34 // parameter's core type must be of unnamed slice or bytestring type.
35 // If recv is non-nil, typeParams must be empty. If recvTypeParams is
36 // non-empty, recv must be non-nil.
37 func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature {
38         if variadic {
39                 n := params.Len()
40                 if n == 0 {
41                         panic("variadic function must have at least one parameter")
42                 }
43                 core := coreString(params.At(n - 1).typ)
44                 if _, ok := core.(*Slice); !ok && !isString(core) {
45                         panic(fmt.Sprintf("got %s, want variadic parameter with unnamed slice type or string as core type", core.String()))
46                 }
47         }
48         sig := &Signature{recv: recv, params: params, results: results, variadic: variadic}
49         if len(recvTypeParams) != 0 {
50                 if recv == nil {
51                         panic("function with receiver type parameters must have a receiver")
52                 }
53                 sig.rparams = bindTParams(recvTypeParams)
54         }
55         if len(typeParams) != 0 {
56                 if recv != nil {
57                         panic("function with type parameters cannot have a receiver")
58                 }
59                 sig.tparams = bindTParams(typeParams)
60         }
61         return sig
62 }
63
64 // Recv returns the receiver of signature s (if a method), or nil if a
65 // function. It is ignored when comparing signatures for identity.
66 //
67 // For an abstract method, Recv returns the enclosing interface either
68 // as a *Named or an *Interface. Due to embedding, an interface may
69 // contain methods whose receiver type is a different interface.
70 func (s *Signature) Recv() *Var { return s.recv }
71
72 // TypeParams returns the type parameters of signature s, or nil.
73 func (s *Signature) TypeParams() *TypeParamList { return s.tparams }
74
75 // SetTypeParams sets the type parameters of signature s.
76 func (s *Signature) SetTypeParams(tparams []*TypeParam) { s.tparams = bindTParams(tparams) }
77
78 // RecvTypeParams returns the receiver type parameters of signature s, or nil.
79 func (s *Signature) RecvTypeParams() *TypeParamList { return s.rparams }
80
81 // Params returns the parameters of signature s, or nil.
82 func (s *Signature) Params() *Tuple { return s.params }
83
84 // Results returns the results of signature s, or nil.
85 func (s *Signature) Results() *Tuple { return s.results }
86
87 // Variadic reports whether the signature s is variadic.
88 func (s *Signature) Variadic() bool { return s.variadic }
89
90 func (s *Signature) Underlying() Type { return s }
91 func (s *Signature) String() string   { return TypeString(s, nil) }
92
93 // ----------------------------------------------------------------------------
94 // Implementation
95
96 // funcType type-checks a function or method type.
97 func (check *Checker) funcType(sig *Signature, recvPar *syntax.Field, tparams []*syntax.Field, ftyp *syntax.FuncType) {
98         check.openScope(ftyp, "function")
99         check.scope.isFunc = true
100         check.recordScope(ftyp, check.scope)
101         sig.scope = check.scope
102         defer check.closeScope()
103
104         if recvPar != nil {
105                 // collect generic receiver type parameters, if any
106                 // - a receiver type parameter is like any other type parameter, except that it is declared implicitly
107                 // - the receiver specification acts as local declaration for its type parameters, which may be blank
108                 _, rname, rparams := check.unpackRecv(recvPar.Type, true)
109                 if len(rparams) > 0 {
110                         tparams := make([]*TypeParam, len(rparams))
111                         for i, rparam := range rparams {
112                                 tparams[i] = check.declareTypeParam(rparam)
113                         }
114                         sig.rparams = bindTParams(tparams)
115                         // Blank identifiers don't get declared, so naive type-checking of the
116                         // receiver type expression would fail in Checker.collectParams below,
117                         // when Checker.ident cannot resolve the _ to a type.
118                         //
119                         // Checker.recvTParamMap maps these blank identifiers to their type parameter
120                         // types, so that they may be resolved in Checker.ident when they fail
121                         // lookup in the scope.
122                         for i, p := range rparams {
123                                 if p.Value == "_" {
124                                         if check.recvTParamMap == nil {
125                                                 check.recvTParamMap = make(map[*syntax.Name]*TypeParam)
126                                         }
127                                         check.recvTParamMap[p] = tparams[i]
128                                 }
129                         }
130                         // determine receiver type to get its type parameters
131                         // and the respective type parameter bounds
132                         var recvTParams []*TypeParam
133                         if rname != nil {
134                                 // recv should be a Named type (otherwise an error is reported elsewhere)
135                                 // Also: Don't report an error via genericType since it will be reported
136                                 //       again when we type-check the signature.
137                                 // TODO(gri) maybe the receiver should be marked as invalid instead?
138                                 if recv, _ := check.genericType(rname, nil).(*Named); recv != nil {
139                                         recvTParams = recv.TypeParams().list()
140                                 }
141                         }
142                         // provide type parameter bounds
143                         if len(tparams) == len(recvTParams) {
144                                 smap := makeRenameMap(recvTParams, tparams)
145                                 for i, tpar := range tparams {
146                                         recvTPar := recvTParams[i]
147                                         check.mono.recordCanon(tpar, recvTPar)
148                                         // recvTPar.bound is (possibly) parameterized in the context of the
149                                         // receiver type declaration. Substitute parameters for the current
150                                         // context.
151                                         tpar.bound = check.subst(tpar.obj.pos, recvTPar.bound, smap, nil, check.context())
152                                 }
153                         } else if len(tparams) < len(recvTParams) {
154                                 // Reporting an error here is a stop-gap measure to avoid crashes in the
155                                 // compiler when a type parameter/argument cannot be inferred later. It
156                                 // may lead to follow-on errors (see issues #51339, #51343).
157                                 // TODO(gri) find a better solution
158                                 got := measure(len(tparams), "type parameter")
159                                 check.errorf(recvPar, _BadRecv, "got %s, but receiver base type declares %d", got, len(recvTParams))
160                         }
161                 }
162         }
163
164         if tparams != nil {
165                 // The parser will complain about invalid type parameters for methods.
166                 check.collectTypeParams(&sig.tparams, tparams)
167         }
168
169         // Value (non-type) parameters' scope starts in the function body. Use a temporary scope for their
170         // declarations and then squash that scope into the parent scope (and report any redeclarations at
171         // that time).
172         scope := NewScope(check.scope, nopos, nopos, "function body (temp. scope)")
173         var recvList []*Var // TODO(gri) remove the need for making a list here
174         if recvPar != nil {
175                 recvList, _ = check.collectParams(scope, []*syntax.Field{recvPar}, false) // use rewritten receiver type, if any
176         }
177         params, variadic := check.collectParams(scope, ftyp.ParamList, true)
178         results, _ := check.collectParams(scope, ftyp.ResultList, false)
179         scope.Squash(func(obj, alt Object) {
180                 var err error_
181                 err.errorf(obj, "%s redeclared in this block", obj.Name())
182                 err.recordAltDecl(alt)
183                 check.report(&err)
184         })
185
186         if recvPar != nil {
187                 // recv parameter list present (may be empty)
188                 // spec: "The receiver is specified via an extra parameter section preceding the
189                 // method name. That parameter section must declare a single parameter, the receiver."
190                 var recv *Var
191                 switch len(recvList) {
192                 case 0:
193                         // error reported by resolver
194                         recv = NewParam(nopos, nil, "", Typ[Invalid]) // ignore recv below
195                 default:
196                         // more than one receiver
197                         check.error(recvList[len(recvList)-1].Pos(), _InvalidRecv, "method must have exactly one receiver")
198                         fallthrough // continue with first receiver
199                 case 1:
200                         recv = recvList[0]
201                 }
202                 sig.recv = recv
203
204                 // Delay validation of receiver type as it may cause premature expansion
205                 // of types the receiver type is dependent on (see issues #51232, #51233).
206                 check.later(func() {
207                         // spec: "The receiver type must be of the form T or *T where T is a type name."
208                         rtyp, _ := deref(recv.typ)
209                         if rtyp == Typ[Invalid] {
210                                 return // error was reported before
211                         }
212                         // spec: "The type denoted by T is called the receiver base type; it must not
213                         // be a pointer or interface type and it must be declared in the same package
214                         // as the method."
215                         switch T := rtyp.(type) {
216                         case *Named:
217                                 // The receiver type may be an instantiated type referred to
218                                 // by an alias (which cannot have receiver parameters for now).
219                                 if T.TypeArgs() != nil && sig.RecvTypeParams() == nil {
220                                         check.errorf(recv, _InvalidRecv, "cannot define new methods on instantiated type %s", rtyp)
221                                         break
222                                 }
223                                 if T.obj.pkg != check.pkg {
224                                         check.errorf(recv, _InvalidRecv, "cannot define new methods on non-local type %s", rtyp)
225                                         break
226                                 }
227                                 var cause string
228                                 switch u := T.under().(type) {
229                                 case *Basic:
230                                         // unsafe.Pointer is treated like a regular pointer
231                                         if u.kind == UnsafePointer {
232                                                 cause = "unsafe.Pointer"
233                                         }
234                                 case *Pointer, *Interface:
235                                         cause = "pointer or interface type"
236                                 case *TypeParam:
237                                         // The underlying type of a receiver base type cannot be a
238                                         // type parameter: "type T[P any] P" is not a valid declaration.
239                                         unreachable()
240                                 }
241                                 if cause != "" {
242                                         check.errorf(recv, _InvalidRecv, "invalid receiver type %s (%s)", rtyp, cause)
243                                 }
244                         case *Basic:
245                                 check.errorf(recv, _InvalidRecv, "cannot define new methods on non-local type %s", rtyp)
246                         default:
247                                 check.errorf(recv, _InvalidRecv, "invalid receiver type %s", recv.typ)
248                         }
249                 }).describef(recv, "validate receiver %s", recv)
250         }
251
252         sig.params = NewTuple(params...)
253         sig.results = NewTuple(results...)
254         sig.variadic = variadic
255 }
256
257 // collectParams declares the parameters of list in scope and returns the corresponding
258 // variable list.
259 func (check *Checker) collectParams(scope *Scope, list []*syntax.Field, variadicOk bool) (params []*Var, variadic bool) {
260         if list == nil {
261                 return
262         }
263
264         var named, anonymous bool
265
266         var typ Type
267         var prev syntax.Expr
268         for i, field := range list {
269                 ftype := field.Type
270                 // type-check type of grouped fields only once
271                 if ftype != prev {
272                         prev = ftype
273                         if t, _ := ftype.(*syntax.DotsType); t != nil {
274                                 ftype = t.Elem
275                                 if variadicOk && i == len(list)-1 {
276                                         variadic = true
277                                 } else {
278                                         check.softErrorf(t, _MisplacedDotDotDot, "can only use ... with final parameter in list")
279                                         // ignore ... and continue
280                                 }
281                         }
282                         typ = check.varType(ftype)
283                 }
284                 // The parser ensures that f.Tag is nil and we don't
285                 // care if a constructed AST contains a non-nil tag.
286                 if field.Name != nil {
287                         // named parameter
288                         name := field.Name.Value
289                         if name == "" {
290                                 check.error(field.Name, 0, invalidAST+"anonymous parameter")
291                                 // ok to continue
292                         }
293                         par := NewParam(field.Name.Pos(), check.pkg, name, typ)
294                         check.declare(scope, field.Name, par, scope.pos)
295                         params = append(params, par)
296                         named = true
297                 } else {
298                         // anonymous parameter
299                         par := NewParam(field.Pos(), check.pkg, "", typ)
300                         check.recordImplicit(field, par)
301                         params = append(params, par)
302                         anonymous = true
303                 }
304         }
305
306         if named && anonymous {
307                 check.error(list[0], 0, invalidAST+"list contains both named and anonymous parameters")
308                 // ok to continue
309         }
310
311         // For a variadic function, change the last parameter's type from T to []T.
312         // Since we type-checked T rather than ...T, we also need to retro-actively
313         // record the type for ...T.
314         if variadic {
315                 last := params[len(params)-1]
316                 last.typ = &Slice{elem: last.typ}
317                 check.recordTypeAndValue(list[len(list)-1].Type, typexpr, last.typ, nil)
318         }
319
320         return
321 }