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