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