]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/signature.go
cmd/compile/internal/types2: merge Instantiate and InstantiateLazy
[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  *TypeParams // receiver type parameters from left to right, or nil
23         tparams  *TypeParams // 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 // TParams returns the type parameters of signature s, or nil.
57 func (s *Signature) TParams() *TypeParams { return s.tparams }
58
59 // SetTParams sets the type parameters of signature s.
60 func (s *Signature) SetTParams(tparams []*TypeName) { s.tparams = bindTParams(tparams) }
61
62 // RParams returns the receiver type parameters of signature s, or nil.
63 func (s *Signature) RParams() *TypeParams { return s.rparams }
64
65 // SetRParams sets the receiver type params of signature s.
66 func (s *Signature) SetRParams(rparams []*TypeName) { 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([]*TypeName, 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 []*TypeName
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 := asNamed(check.genericType(rname, false)); recv != nil {
136                                         recvTParams = recv.TParams().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.typ
146                                 }
147                                 smap := makeSubstMap(recvTParams, list)
148                                 for i, tname := range sig.RParams().list() {
149                                         bound := recvTParams[i].typ.(*TypeParam).bound
150                                         // bound is (possibly) parameterized in the context of the
151                                         // receiver type declaration. Substitute parameters for the
152                                         // current context.
153                                         // TODO(gri) should we assume now that bounds always exist?
154                                         //           (no bound == empty interface)
155                                         if bound != nil {
156                                                 bound = check.subst(tname.pos, bound, smap, nil)
157                                                 tname.typ.(*TypeParam).bound = bound
158                                         }
159                                 }
160                         }
161                 }
162         }
163
164         if tparams != nil {
165                 sig.tparams = check.collectTypeParams(tparams)
166                 // Always type-check method type parameters but complain if they are not enabled.
167                 // (A separate check is needed when type-checking interface method signatures because
168                 // they don't have a receiver specification.)
169                 if recvPar != nil && !acceptMethodTypeParams {
170                         check.error(ftyp, "methods cannot have type parameters")
171                 }
172         }
173
174         // Value (non-type) parameters' scope starts in the function body. Use a temporary scope for their
175         // declarations and then squash that scope into the parent scope (and report any redeclarations at
176         // that time).
177         scope := NewScope(check.scope, nopos, nopos, "function body (temp. scope)")
178         var recvList []*Var // TODO(gri) remove the need for making a list here
179         if recvPar != nil {
180                 recvList, _ = check.collectParams(scope, []*syntax.Field{recvPar}, recvTyp, false) // use rewritten receiver type, if any
181         }
182         params, variadic := check.collectParams(scope, ftyp.ParamList, nil, true)
183         results, _ := check.collectParams(scope, ftyp.ResultList, nil, false)
184         scope.Squash(func(obj, alt Object) {
185                 var err error_
186                 err.errorf(obj, "%s redeclared in this block", obj.Name())
187                 err.recordAltDecl(alt)
188                 check.report(&err)
189         })
190
191         if recvPar != nil {
192                 // recv parameter list present (may be empty)
193                 // spec: "The receiver is specified via an extra parameter section preceding the
194                 // method name. That parameter section must declare a single parameter, the receiver."
195                 var recv *Var
196                 switch len(recvList) {
197                 case 0:
198                         // error reported by resolver
199                         recv = NewParam(nopos, nil, "", Typ[Invalid]) // ignore recv below
200                 default:
201                         // more than one receiver
202                         check.error(recvList[len(recvList)-1].Pos(), "method must have exactly one receiver")
203                         fallthrough // continue with first receiver
204                 case 1:
205                         recv = recvList[0]
206                 }
207
208                 // TODO(gri) We should delay rtyp expansion to when we actually need the
209                 //           receiver; thus all checks here should be delayed to later.
210                 rtyp, _ := deref(recv.typ)
211
212                 // spec: "The receiver type must be of the form T or *T where T is a type name."
213                 // (ignore invalid types - error was reported before)
214                 if rtyp != Typ[Invalid] {
215                         var err string
216                         switch T := rtyp.(type) {
217                         case *Named:
218                                 T.expand(nil)
219                                 // spec: "The type denoted by T is called the receiver base type; it must not
220                                 // be a pointer or interface type and it must be declared in the same package
221                                 // as the method."
222                                 if T.obj.pkg != check.pkg {
223                                         err = "type not defined in this package"
224                                         if check.conf.CompilerErrorMessages {
225                                                 check.errorf(recv.pos, "cannot define new methods on non-local type %s", recv.typ)
226                                                 err = ""
227                                         }
228                                 } else {
229                                         // The underlying type of a receiver base type can be a type parameter;
230                                         // e.g. for methods with a generic receiver T[P] with type T[P any] P.
231                                         underIs(T, func(u Type) bool {
232                                                 switch u := u.(type) {
233                                                 case *Basic:
234                                                         // unsafe.Pointer is treated like a regular pointer
235                                                         if u.kind == UnsafePointer {
236                                                                 err = "unsafe.Pointer"
237                                                                 return false
238                                                         }
239                                                 case *Pointer, *Interface:
240                                                         err = "pointer or interface type"
241                                                         return false
242                                                 }
243                                                 return true
244                                         })
245                                 }
246                         case *Basic:
247                                 err = "basic or unnamed type"
248                                 if check.conf.CompilerErrorMessages {
249                                         check.errorf(recv.pos, "cannot define new methods on non-local type %s", recv.typ)
250                                         err = ""
251                                 }
252                         default:
253                                 check.errorf(recv.pos, "invalid receiver type %s", recv.typ)
254                         }
255                         if err != "" {
256                                 check.errorf(recv.pos, "invalid receiver type %s (%s)", recv.typ, err)
257                                 // ok to continue
258                         }
259                 }
260                 sig.recv = recv
261         }
262
263         sig.params = NewTuple(params...)
264         sig.results = NewTuple(results...)
265         sig.variadic = variadic
266 }
267
268 // collectParams declares the parameters of list in scope and returns the corresponding
269 // variable list. If type0 != nil, it is used instead of the first type in list.
270 func (check *Checker) collectParams(scope *Scope, list []*syntax.Field, type0 syntax.Expr, variadicOk bool) (params []*Var, variadic bool) {
271         if list == nil {
272                 return
273         }
274
275         var named, anonymous bool
276
277         var typ Type
278         var prev syntax.Expr
279         for i, field := range list {
280                 ftype := field.Type
281                 // type-check type of grouped fields only once
282                 if ftype != prev {
283                         prev = ftype
284                         if i == 0 && type0 != nil {
285                                 ftype = type0
286                         }
287                         if t, _ := ftype.(*syntax.DotsType); t != nil {
288                                 ftype = t.Elem
289                                 if variadicOk && i == len(list)-1 {
290                                         variadic = true
291                                 } else {
292                                         check.softErrorf(t, "can only use ... with final parameter in list")
293                                         // ignore ... and continue
294                                 }
295                         }
296                         typ = check.varType(ftype)
297                 }
298                 // The parser ensures that f.Tag is nil and we don't
299                 // care if a constructed AST contains a non-nil tag.
300                 if field.Name != nil {
301                         // named parameter
302                         name := field.Name.Value
303                         if name == "" {
304                                 check.error(field.Name, invalidAST+"anonymous parameter")
305                                 // ok to continue
306                         }
307                         par := NewParam(field.Name.Pos(), check.pkg, name, typ)
308                         check.declare(scope, field.Name, par, scope.pos)
309                         params = append(params, par)
310                         named = true
311                 } else {
312                         // anonymous parameter
313                         par := NewParam(field.Pos(), check.pkg, "", typ)
314                         check.recordImplicit(field, par)
315                         params = append(params, par)
316                         anonymous = true
317                 }
318         }
319
320         if named && anonymous {
321                 check.error(list[0], invalidAST+"list contains both named and anonymous parameters")
322                 // ok to continue
323         }
324
325         // For a variadic function, change the last parameter's type from T to []T.
326         // Since we type-checked T rather than ...T, we also need to retro-actively
327         // record the type for ...T.
328         if variadic {
329                 last := params[len(params)-1]
330                 last.typ = &Slice{elem: last.typ}
331                 check.recordTypeAndValue(list[len(list)-1].Type, typexpr, last.typ, nil)
332         }
333
334         return
335 }
336
337 // isubst returns an x with identifiers substituted per the substitution map smap.
338 // isubst only handles the case of (valid) method receiver type expressions correctly.
339 func isubst(x syntax.Expr, smap map[*syntax.Name]*syntax.Name) syntax.Expr {
340         switch n := x.(type) {
341         case *syntax.Name:
342                 if alt := smap[n]; alt != nil {
343                         return alt
344                 }
345         // case *syntax.StarExpr:
346         //      X := isubst(n.X, smap)
347         //      if X != n.X {
348         //              new := *n
349         //              new.X = X
350         //              return &new
351         //      }
352         case *syntax.Operation:
353                 if n.Op == syntax.Mul && n.Y == nil {
354                         X := isubst(n.X, smap)
355                         if X != n.X {
356                                 new := *n
357                                 new.X = X
358                                 return &new
359                         }
360                 }
361         case *syntax.IndexExpr:
362                 Index := isubst(n.Index, smap)
363                 if Index != n.Index {
364                         new := *n
365                         new.Index = Index
366                         return &new
367                 }
368         case *syntax.ListExpr:
369                 var elems []syntax.Expr
370                 for i, elem := range n.ElemList {
371                         new := isubst(elem, smap)
372                         if new != elem {
373                                 if elems == nil {
374                                         elems = make([]syntax.Expr, len(n.ElemList))
375                                         copy(elems, n.ElemList)
376                                 }
377                                 elems[i] = new
378                         }
379                 }
380                 if elems != nil {
381                         new := *n
382                         new.ElemList = elems
383                         return &new
384                 }
385         case *syntax.ParenExpr:
386                 return isubst(n.X, smap) // no need to keep parentheses
387         default:
388                 // Other receiver type expressions are invalid.
389                 // It's fine to ignore those here as they will
390                 // be checked elsewhere.
391         }
392         return x
393 }