]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/signature.go
go/types, types2: rename Environment to Context
[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, present for package-local signatures
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 // NewSignature returns a new function type for the given receiver, parameters,
32 // and results, either of which may be nil. If variadic is set, the function
33 // is variadic, it must have at least one parameter, and the last parameter
34 // must be of unnamed slice type.
35 //
36 // Deprecated: Use NewSignatureType instead which allows for type parameters.
37 func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature {
38         return NewSignatureType(recv, nil, nil, params, results, variadic)
39 }
40
41 // NewSignatureType creates a new function type for the given receiver,
42 // receiver type parameters, type parameters, parameters, and results. If
43 // variadic is set, params must hold at least one parameter and the last
44 // parameter must be of unnamed slice type. If recv is non-nil, typeParams must
45 // be empty. If recvTypeParams is non-empty, recv must be non-nil.
46 func NewSignatureType(recv *Var, recvTypeParams, typeParams []*TypeParam, params, results *Tuple, variadic bool) *Signature {
47         if variadic {
48                 n := params.Len()
49                 if n == 0 {
50                         panic("variadic function must have at least one parameter")
51                 }
52                 if _, ok := params.At(n - 1).typ.(*Slice); !ok {
53                         panic("variadic parameter must be of unnamed slice type")
54                 }
55         }
56         sig := &Signature{recv: recv, params: params, results: results, variadic: variadic}
57         if len(recvTypeParams) != 0 {
58                 if recv == nil {
59                         panic("function with receiver type parameters must have a receiver")
60                 }
61                 sig.rparams = bindTParams(recvTypeParams)
62         }
63         if len(typeParams) != 0 {
64                 if recv != nil {
65                         panic("function with type parameters cannot have a receiver")
66                 }
67                 sig.tparams = bindTParams(typeParams)
68         }
69         return sig
70 }
71
72 // Recv returns the receiver of signature s (if a method), or nil if a
73 // function. It is ignored when comparing signatures for identity.
74 //
75 // For an abstract method, Recv returns the enclosing interface either
76 // as a *Named or an *Interface. Due to embedding, an interface may
77 // contain methods whose receiver type is a different interface.
78 func (s *Signature) Recv() *Var { return s.recv }
79
80 // TypeParams returns the type parameters of signature s, or nil.
81 func (s *Signature) TypeParams() *TypeParamList { return s.tparams }
82
83 // SetTypeParams sets the type parameters of signature s.
84 func (s *Signature) SetTypeParams(tparams []*TypeParam) { s.tparams = bindTParams(tparams) }
85
86 // RecvTypeParams returns the receiver type parameters of signature s, or nil.
87 func (s *Signature) RecvTypeParams() *TypeParamList { return s.rparams }
88
89 // SetRecvTypeParams sets the receiver type params of signature s.
90 func (s *Signature) SetRecvTypeParams(rparams []*TypeParam) { s.rparams = bindTParams(rparams) }
91
92 // Params returns the parameters of signature s, or nil.
93 func (s *Signature) Params() *Tuple { return s.params }
94
95 // Results returns the results of signature s, or nil.
96 func (s *Signature) Results() *Tuple { return s.results }
97
98 // Variadic reports whether the signature s is variadic.
99 func (s *Signature) Variadic() bool { return s.variadic }
100
101 func (s *Signature) Underlying() Type { return s }
102 func (s *Signature) String() string   { return TypeString(s, nil) }
103
104 // ----------------------------------------------------------------------------
105 // Implementation
106
107 // Disabled by default, but enabled when running tests (via types_test.go).
108 var acceptMethodTypeParams bool
109
110 // funcType type-checks a function or method type.
111 func (check *Checker) funcType(sig *Signature, recvPar *syntax.Field, tparams []*syntax.Field, ftyp *syntax.FuncType) {
112         check.openScope(ftyp, "function")
113         check.scope.isFunc = true
114         check.recordScope(ftyp, check.scope)
115         sig.scope = check.scope
116         defer check.closeScope()
117
118         var recvTyp syntax.Expr // rewritten receiver type; valid if != nil
119         if recvPar != nil {
120                 // collect generic receiver type parameters, if any
121                 // - a receiver type parameter is like any other type parameter, except that it is declared implicitly
122                 // - the receiver specification acts as local declaration for its type parameters, which may be blank
123                 _, rname, rparams := check.unpackRecv(recvPar.Type, true)
124                 if len(rparams) > 0 {
125                         // Blank identifiers don't get declared and regular type-checking of the instantiated
126                         // parameterized receiver type expression fails in Checker.collectParams of receiver.
127                         // Identify blank type parameters and substitute each with a unique new identifier named
128                         // "n_" (where n is the parameter index) and which cannot conflict with any user-defined
129                         // name.
130                         var smap map[*syntax.Name]*syntax.Name // substitution map from "_" to "!n" identifiers
131                         for i, p := range rparams {
132                                 if p.Value == "_" {
133                                         new := *p
134                                         new.Value = fmt.Sprintf("%d_", i)
135                                         rparams[i] = &new // use n_ identifier instead of _ so it can be looked up
136                                         if smap == nil {
137                                                 smap = make(map[*syntax.Name]*syntax.Name)
138                                         }
139                                         smap[p] = &new
140                                 }
141                         }
142                         if smap != nil {
143                                 // blank identifiers were found => use rewritten receiver type
144                                 recvTyp = isubst(recvPar.Type, smap)
145                         }
146                         rlist := make([]*TypeParam, len(rparams))
147                         for i, rparam := range rparams {
148                                 rlist[i] = check.declareTypeParam(rparam)
149                         }
150                         sig.rparams = bindTParams(rlist)
151                         // determine receiver type to get its type parameters
152                         // and the respective type parameter bounds
153                         var recvTParams []*TypeParam
154                         if rname != nil {
155                                 // recv should be a Named type (otherwise an error is reported elsewhere)
156                                 // Also: Don't report an error via genericType since it will be reported
157                                 //       again when we type-check the signature.
158                                 // TODO(gri) maybe the receiver should be marked as invalid instead?
159                                 if recv, _ := check.genericType(rname, false).(*Named); recv != nil {
160                                         recvTParams = recv.TypeParams().list()
161                                 }
162                         }
163                         // provide type parameter bounds
164                         // - only do this if we have the right number (otherwise an error is reported elsewhere)
165                         if sig.RecvTypeParams().Len() == len(recvTParams) {
166                                 // We have a list of *TypeNames but we need a list of Types.
167                                 list := make([]Type, sig.RecvTypeParams().Len())
168                                 for i, t := range sig.RecvTypeParams().list() {
169                                         list[i] = t
170                                 }
171                                 smap := makeSubstMap(recvTParams, list)
172                                 for i, tpar := range sig.RecvTypeParams().list() {
173                                         bound := recvTParams[i].bound
174                                         // bound is (possibly) parameterized in the context of the
175                                         // receiver type declaration. Substitute parameters for the
176                                         // current context.
177                                         tpar.bound = check.subst(tpar.obj.pos, bound, smap, nil)
178                                 }
179                         }
180                 }
181         }
182
183         if tparams != nil {
184                 check.collectTypeParams(&sig.tparams, tparams)
185                 // Always type-check method type parameters but complain if they are not enabled.
186                 // (A separate check is needed when type-checking interface method signatures because
187                 // they don't have a receiver specification.)
188                 if recvPar != nil && !acceptMethodTypeParams {
189                         check.error(ftyp, "methods cannot have type parameters")
190                 }
191         }
192
193         // Value (non-type) parameters' scope starts in the function body. Use a temporary scope for their
194         // declarations and then squash that scope into the parent scope (and report any redeclarations at
195         // that time).
196         scope := NewScope(check.scope, nopos, nopos, "function body (temp. scope)")
197         var recvList []*Var // TODO(gri) remove the need for making a list here
198         if recvPar != nil {
199                 recvList, _ = check.collectParams(scope, []*syntax.Field{recvPar}, recvTyp, false) // use rewritten receiver type, if any
200         }
201         params, variadic := check.collectParams(scope, ftyp.ParamList, nil, true)
202         results, _ := check.collectParams(scope, ftyp.ResultList, nil, false)
203         scope.Squash(func(obj, alt Object) {
204                 var err error_
205                 err.errorf(obj, "%s redeclared in this block", obj.Name())
206                 err.recordAltDecl(alt)
207                 check.report(&err)
208         })
209
210         if recvPar != nil {
211                 // recv parameter list present (may be empty)
212                 // spec: "The receiver is specified via an extra parameter section preceding the
213                 // method name. That parameter section must declare a single parameter, the receiver."
214                 var recv *Var
215                 switch len(recvList) {
216                 case 0:
217                         // error reported by resolver
218                         recv = NewParam(nopos, nil, "", Typ[Invalid]) // ignore recv below
219                 default:
220                         // more than one receiver
221                         check.error(recvList[len(recvList)-1].Pos(), "method must have exactly one receiver")
222                         fallthrough // continue with first receiver
223                 case 1:
224                         recv = recvList[0]
225                 }
226
227                 // TODO(gri) We should delay rtyp expansion to when we actually need the
228                 //           receiver; thus all checks here should be delayed to later.
229                 rtyp, _ := deref(recv.typ)
230
231                 // spec: "The receiver type must be of the form T or *T where T is a type name."
232                 // (ignore invalid types - error was reported before)
233                 if rtyp != Typ[Invalid] {
234                         var err string
235                         switch T := rtyp.(type) {
236                         case *Named:
237                                 T.resolve(check.conf.Context)
238                                 // The receiver type may be an instantiated type referred to
239                                 // by an alias (which cannot have receiver parameters for now).
240                                 if T.TypeArgs() != nil && sig.RecvTypeParams() == nil {
241                                         check.errorf(recv.pos, "cannot define methods on instantiated type %s", recv.typ)
242                                         break
243                                 }
244                                 // spec: "The type denoted by T is called the receiver base type; it must not
245                                 // be a pointer or interface type and it must be declared in the same package
246                                 // as the method."
247                                 if T.obj.pkg != check.pkg {
248                                         err = "type not defined in this package"
249                                         if check.conf.CompilerErrorMessages {
250                                                 check.errorf(recv.pos, "cannot define new methods on non-local type %s", recv.typ)
251                                                 err = ""
252                                         }
253                                 } else {
254                                         // The underlying type of a receiver base type can be a type parameter;
255                                         // e.g. for methods with a generic receiver T[P] with type T[P any] P.
256                                         underIs(T, func(u Type) bool {
257                                                 switch u := u.(type) {
258                                                 case *Basic:
259                                                         // unsafe.Pointer is treated like a regular pointer
260                                                         if u.kind == UnsafePointer {
261                                                                 err = "unsafe.Pointer"
262                                                                 return false
263                                                         }
264                                                 case *Pointer, *Interface:
265                                                         err = "pointer or interface type"
266                                                         return false
267                                                 }
268                                                 return true
269                                         })
270                                 }
271                         case *Basic:
272                                 err = "basic or unnamed type"
273                                 if check.conf.CompilerErrorMessages {
274                                         check.errorf(recv.pos, "cannot define new methods on non-local type %s", recv.typ)
275                                         err = ""
276                                 }
277                         default:
278                                 check.errorf(recv.pos, "invalid receiver type %s", recv.typ)
279                         }
280                         if err != "" {
281                                 check.errorf(recv.pos, "invalid receiver type %s (%s)", recv.typ, err)
282                                 // ok to continue
283                         }
284                 }
285                 sig.recv = recv
286         }
287
288         sig.params = NewTuple(params...)
289         sig.results = NewTuple(results...)
290         sig.variadic = variadic
291 }
292
293 // collectParams declares the parameters of list in scope and returns the corresponding
294 // variable list. If type0 != nil, it is used instead of the first type in list.
295 func (check *Checker) collectParams(scope *Scope, list []*syntax.Field, type0 syntax.Expr, variadicOk bool) (params []*Var, variadic bool) {
296         if list == nil {
297                 return
298         }
299
300         var named, anonymous bool
301
302         var typ Type
303         var prev syntax.Expr
304         for i, field := range list {
305                 ftype := field.Type
306                 // type-check type of grouped fields only once
307                 if ftype != prev {
308                         prev = ftype
309                         if i == 0 && type0 != nil {
310                                 ftype = type0
311                         }
312                         if t, _ := ftype.(*syntax.DotsType); t != nil {
313                                 ftype = t.Elem
314                                 if variadicOk && i == len(list)-1 {
315                                         variadic = true
316                                 } else {
317                                         check.softErrorf(t, "can only use ... with final parameter in list")
318                                         // ignore ... and continue
319                                 }
320                         }
321                         typ = check.varType(ftype)
322                 }
323                 // The parser ensures that f.Tag is nil and we don't
324                 // care if a constructed AST contains a non-nil tag.
325                 if field.Name != nil {
326                         // named parameter
327                         name := field.Name.Value
328                         if name == "" {
329                                 check.error(field.Name, invalidAST+"anonymous parameter")
330                                 // ok to continue
331                         }
332                         par := NewParam(field.Name.Pos(), check.pkg, name, typ)
333                         check.declare(scope, field.Name, par, scope.pos)
334                         params = append(params, par)
335                         named = true
336                 } else {
337                         // anonymous parameter
338                         par := NewParam(field.Pos(), check.pkg, "", typ)
339                         check.recordImplicit(field, par)
340                         params = append(params, par)
341                         anonymous = true
342                 }
343         }
344
345         if named && anonymous {
346                 check.error(list[0], invalidAST+"list contains both named and anonymous parameters")
347                 // ok to continue
348         }
349
350         // For a variadic function, change the last parameter's type from T to []T.
351         // Since we type-checked T rather than ...T, we also need to retro-actively
352         // record the type for ...T.
353         if variadic {
354                 last := params[len(params)-1]
355                 last.typ = &Slice{elem: last.typ}
356                 check.recordTypeAndValue(list[len(list)-1].Type, typexpr, last.typ, nil)
357         }
358
359         return
360 }
361
362 // isubst returns an x with identifiers substituted per the substitution map smap.
363 // isubst only handles the case of (valid) method receiver type expressions correctly.
364 func isubst(x syntax.Expr, smap map[*syntax.Name]*syntax.Name) syntax.Expr {
365         switch n := x.(type) {
366         case *syntax.Name:
367                 if alt := smap[n]; alt != nil {
368                         return alt
369                 }
370         // case *syntax.StarExpr:
371         //      X := isubst(n.X, smap)
372         //      if X != n.X {
373         //              new := *n
374         //              new.X = X
375         //              return &new
376         //      }
377         case *syntax.Operation:
378                 if n.Op == syntax.Mul && n.Y == nil {
379                         X := isubst(n.X, smap)
380                         if X != n.X {
381                                 new := *n
382                                 new.X = X
383                                 return &new
384                         }
385                 }
386         case *syntax.IndexExpr:
387                 Index := isubst(n.Index, smap)
388                 if Index != n.Index {
389                         new := *n
390                         new.Index = Index
391                         return &new
392                 }
393         case *syntax.ListExpr:
394                 var elems []syntax.Expr
395                 for i, elem := range n.ElemList {
396                         new := isubst(elem, smap)
397                         if new != elem {
398                                 if elems == nil {
399                                         elems = make([]syntax.Expr, len(n.ElemList))
400                                         copy(elems, n.ElemList)
401                                 }
402                                 elems[i] = new
403                         }
404                 }
405                 if elems != nil {
406                         new := *n
407                         new.ElemList = elems
408                         return &new
409                 }
410         case *syntax.ParenExpr:
411                 return isubst(n.X, smap) // no need to keep parentheses
412         default:
413                 // Other receiver type expressions are invalid.
414                 // It's fine to ignore those here as they will
415                 // be checked elsewhere.
416         }
417         return x
418 }