]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/signature.go
[dev.typeparams] cmd/compile/internal/types2: delay interface check for type bounds
[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 // Disabled by default, but enabled when running tests (via types_test.go).
13 var acceptMethodTypeParams bool
14
15 // funcType type-checks a function or method type.
16 func (check *Checker) funcType(sig *Signature, recvPar *syntax.Field, tparams []*syntax.Field, ftyp *syntax.FuncType) {
17         check.openScope(ftyp, "function")
18         check.scope.isFunc = true
19         check.recordScope(ftyp, check.scope)
20         sig.scope = check.scope
21         defer check.closeScope()
22
23         var recvTyp syntax.Expr // rewritten receiver type; valid if != nil
24         if recvPar != nil {
25                 // collect generic receiver type parameters, if any
26                 // - a receiver type parameter is like any other type parameter, except that it is declared implicitly
27                 // - the receiver specification acts as local declaration for its type parameters, which may be blank
28                 _, rname, rparams := check.unpackRecv(recvPar.Type, true)
29                 if len(rparams) > 0 {
30                         // Blank identifiers don't get declared and regular type-checking of the instantiated
31                         // parameterized receiver type expression fails in Checker.collectParams of receiver.
32                         // Identify blank type parameters and substitute each with a unique new identifier named
33                         // "n_" (where n is the parameter index) and which cannot conflict with any user-defined
34                         // name.
35                         var smap map[*syntax.Name]*syntax.Name // substitution map from "_" to "!n" identifiers
36                         for i, p := range rparams {
37                                 if p.Value == "_" {
38                                         new := *p
39                                         new.Value = fmt.Sprintf("%d_", i)
40                                         rparams[i] = &new // use n_ identifier instead of _ so it can be looked up
41                                         if smap == nil {
42                                                 smap = make(map[*syntax.Name]*syntax.Name)
43                                         }
44                                         smap[p] = &new
45                                 }
46                         }
47                         if smap != nil {
48                                 // blank identifiers were found => use rewritten receiver type
49                                 recvTyp = isubst(recvPar.Type, smap)
50                         }
51                         sig.rparams = make([]*TypeName, len(rparams))
52                         for i, rparam := range rparams {
53                                 sig.rparams[i] = check.declareTypeParam(i, rparam)
54                         }
55                         // determine receiver type to get its type parameters
56                         // and the respective type parameter bounds
57                         var recvTParams []*TypeName
58                         if rname != nil {
59                                 // recv should be a Named type (otherwise an error is reported elsewhere)
60                                 // Also: Don't report an error via genericType since it will be reported
61                                 //       again when we type-check the signature.
62                                 // TODO(gri) maybe the receiver should be marked as invalid instead?
63                                 if recv := asNamed(check.genericType(rname, false)); recv != nil {
64                                         recvTParams = recv.TParams()
65                                 }
66                         }
67                         // provide type parameter bounds
68                         // - only do this if we have the right number (otherwise an error is reported elsewhere)
69                         if len(sig.rparams) == len(recvTParams) {
70                                 // We have a list of *TypeNames but we need a list of Types.
71                                 list := make([]Type, len(sig.rparams))
72                                 for i, t := range sig.rparams {
73                                         list[i] = t.typ
74                                 }
75                                 smap := makeSubstMap(recvTParams, list)
76                                 for i, tname := range sig.rparams {
77                                         bound := recvTParams[i].typ.(*TypeParam).bound
78                                         // bound is (possibly) parameterized in the context of the
79                                         // receiver type declaration. Substitute parameters for the
80                                         // current context.
81                                         // TODO(gri) should we assume now that bounds always exist?
82                                         //           (no bound == empty interface)
83                                         if bound != nil {
84                                                 bound = check.subst(tname.pos, bound, smap)
85                                                 tname.typ.(*TypeParam).bound = bound
86                                         }
87                                 }
88                         }
89                 }
90         }
91
92         if tparams != nil {
93                 sig.tparams = check.collectTypeParams(tparams)
94                 // Always type-check method type parameters but complain if they are not enabled.
95                 // (A separate check is needed when type-checking interface method signatures because
96                 // they don't have a receiver specification.)
97                 if recvPar != nil && !acceptMethodTypeParams {
98                         check.error(ftyp, "methods cannot have type parameters")
99                 }
100         }
101
102         // Value (non-type) parameters' scope starts in the function body. Use a temporary scope for their
103         // declarations and then squash that scope into the parent scope (and report any redeclarations at
104         // that time).
105         scope := NewScope(check.scope, nopos, nopos, "function body (temp. scope)")
106         var recvList []*Var // TODO(gri) remove the need for making a list here
107         if recvPar != nil {
108                 recvList, _ = check.collectParams(scope, []*syntax.Field{recvPar}, recvTyp, false) // use rewritten receiver type, if any
109         }
110         params, variadic := check.collectParams(scope, ftyp.ParamList, nil, true)
111         results, _ := check.collectParams(scope, ftyp.ResultList, nil, false)
112         scope.Squash(func(obj, alt Object) {
113                 var err error_
114                 err.errorf(obj, "%s redeclared in this block", obj.Name())
115                 err.recordAltDecl(alt)
116                 check.report(&err)
117         })
118
119         if recvPar != nil {
120                 // recv parameter list present (may be empty)
121                 // spec: "The receiver is specified via an extra parameter section preceding the
122                 // method name. That parameter section must declare a single parameter, the receiver."
123                 var recv *Var
124                 switch len(recvList) {
125                 case 0:
126                         // error reported by resolver
127                         recv = NewParam(nopos, nil, "", Typ[Invalid]) // ignore recv below
128                 default:
129                         // more than one receiver
130                         check.error(recvList[len(recvList)-1].Pos(), "method must have exactly one receiver")
131                         fallthrough // continue with first receiver
132                 case 1:
133                         recv = recvList[0]
134                 }
135
136                 // TODO(gri) We should delay rtyp expansion to when we actually need the
137                 //           receiver; thus all checks here should be delayed to later.
138                 rtyp, _ := deref(recv.typ)
139                 rtyp = expand(rtyp)
140
141                 // spec: "The receiver type must be of the form T or *T where T is a type name."
142                 // (ignore invalid types - error was reported before)
143                 if t := rtyp; t != Typ[Invalid] {
144                         var err string
145                         if T := asNamed(t); T != nil {
146                                 // spec: "The type denoted by T is called the receiver base type; it must not
147                                 // be a pointer or interface type and it must be declared in the same package
148                                 // as the method."
149                                 if T.obj.pkg != check.pkg {
150                                         err = "type not defined in this package"
151                                         if check.conf.CompilerErrorMessages {
152                                                 check.errorf(recv.pos, "cannot define new methods on non-local type %s", recv.typ)
153                                                 err = ""
154                                         }
155                                 } else {
156                                         switch u := optype(T).(type) {
157                                         case *Basic:
158                                                 // unsafe.Pointer is treated like a regular pointer
159                                                 if u.kind == UnsafePointer {
160                                                         err = "unsafe.Pointer"
161                                                 }
162                                         case *Pointer, *Interface:
163                                                 err = "pointer or interface type"
164                                         }
165                                 }
166                         } else if T := asBasic(t); T != nil {
167                                 err = "basic or unnamed type"
168                                 if check.conf.CompilerErrorMessages {
169                                         check.errorf(recv.pos, "cannot define new methods on non-local type %s", recv.typ)
170                                         err = ""
171                                 }
172                         } else {
173                                 check.errorf(recv.pos, "invalid receiver type %s", recv.typ)
174                         }
175                         if err != "" {
176                                 check.errorf(recv.pos, "invalid receiver type %s (%s)", recv.typ, err)
177                                 // ok to continue
178                         }
179                 }
180                 sig.recv = recv
181         }
182
183         sig.params = NewTuple(params...)
184         sig.results = NewTuple(results...)
185         sig.variadic = variadic
186 }
187
188 // collectParams declares the parameters of list in scope and returns the corresponding
189 // variable list. If type0 != nil, it is used instead of the first type in list.
190 func (check *Checker) collectParams(scope *Scope, list []*syntax.Field, type0 syntax.Expr, variadicOk bool) (params []*Var, variadic bool) {
191         if list == nil {
192                 return
193         }
194
195         var named, anonymous bool
196
197         var typ Type
198         var prev syntax.Expr
199         for i, field := range list {
200                 ftype := field.Type
201                 // type-check type of grouped fields only once
202                 if ftype != prev {
203                         prev = ftype
204                         if i == 0 && type0 != nil {
205                                 ftype = type0
206                         }
207                         if t, _ := ftype.(*syntax.DotsType); t != nil {
208                                 ftype = t.Elem
209                                 if variadicOk && i == len(list)-1 {
210                                         variadic = true
211                                 } else {
212                                         check.softErrorf(t, "can only use ... with final parameter in list")
213                                         // ignore ... and continue
214                                 }
215                         }
216                         typ = check.varType(ftype)
217                 }
218                 // The parser ensures that f.Tag is nil and we don't
219                 // care if a constructed AST contains a non-nil tag.
220                 if field.Name != nil {
221                         // named parameter
222                         name := field.Name.Value
223                         if name == "" {
224                                 check.error(field.Name, invalidAST+"anonymous parameter")
225                                 // ok to continue
226                         }
227                         par := NewParam(field.Name.Pos(), check.pkg, name, typ)
228                         check.declare(scope, field.Name, par, scope.pos)
229                         params = append(params, par)
230                         named = true
231                 } else {
232                         // anonymous parameter
233                         par := NewParam(field.Pos(), check.pkg, "", typ)
234                         check.recordImplicit(field, par)
235                         params = append(params, par)
236                         anonymous = true
237                 }
238         }
239
240         if named && anonymous {
241                 check.error(list[0], invalidAST+"list contains both named and anonymous parameters")
242                 // ok to continue
243         }
244
245         // For a variadic function, change the last parameter's type from T to []T.
246         // Since we type-checked T rather than ...T, we also need to retro-actively
247         // record the type for ...T.
248         if variadic {
249                 last := params[len(params)-1]
250                 last.typ = &Slice{elem: last.typ}
251                 check.recordTypeAndValue(list[len(list)-1].Type, typexpr, last.typ, nil)
252         }
253
254         return
255 }
256
257 // isubst returns an x with identifiers substituted per the substitution map smap.
258 // isubst only handles the case of (valid) method receiver type expressions correctly.
259 func isubst(x syntax.Expr, smap map[*syntax.Name]*syntax.Name) syntax.Expr {
260         switch n := x.(type) {
261         case *syntax.Name:
262                 if alt := smap[n]; alt != nil {
263                         return alt
264                 }
265         // case *syntax.StarExpr:
266         //      X := isubst(n.X, smap)
267         //      if X != n.X {
268         //              new := *n
269         //              new.X = X
270         //              return &new
271         //      }
272         case *syntax.Operation:
273                 if n.Op == syntax.Mul && n.Y == nil {
274                         X := isubst(n.X, smap)
275                         if X != n.X {
276                                 new := *n
277                                 new.X = X
278                                 return &new
279                         }
280                 }
281         case *syntax.IndexExpr:
282                 Index := isubst(n.Index, smap)
283                 if Index != n.Index {
284                         new := *n
285                         new.Index = Index
286                         return &new
287                 }
288         case *syntax.ListExpr:
289                 var elems []syntax.Expr
290                 for i, elem := range n.ElemList {
291                         new := isubst(elem, smap)
292                         if new != elem {
293                                 if elems == nil {
294                                         elems = make([]syntax.Expr, len(n.ElemList))
295                                         copy(elems, n.ElemList)
296                                 }
297                                 elems[i] = new
298                         }
299                 }
300                 if elems != nil {
301                         new := *n
302                         new.ElemList = elems
303                         return &new
304                 }
305         case *syntax.ParenExpr:
306                 return isubst(n.X, smap) // no need to keep parentheses
307         default:
308                 // Other receiver type expressions are invalid.
309                 // It's fine to ignore those here as they will
310                 // be checked elsewhere.
311         }
312         return x
313 }