]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/unify.go
[dev.typeparams] all: merge master (c8f4e61) into dev.typeparams
[gostls13.git] / src / cmd / compile / internal / types2 / unify.go
1 // Copyright 2020 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 // This file implements type unification.
6
7 package types2
8
9 import (
10         "bytes"
11         "fmt"
12 )
13
14 // The unifier maintains two separate sets of type parameters x and y
15 // which are used to resolve type parameters in the x and y arguments
16 // provided to the unify call. For unidirectional unification, only
17 // one of these sets (say x) is provided, and then type parameters are
18 // only resolved for the x argument passed to unify, not the y argument
19 // (even if that also contains possibly the same type parameters). This
20 // is crucial to infer the type parameters of self-recursive calls:
21 //
22 //      func f[P any](a P) { f(a) }
23 //
24 // For the call f(a) we want to infer that the type argument for P is P.
25 // During unification, the parameter type P must be resolved to the type
26 // parameter P ("x" side), but the argument type P must be left alone so
27 // that unification resolves the type parameter P to P.
28 //
29 // For bidirection unification, both sets are provided. This enables
30 // unification to go from argument to parameter type and vice versa.
31 // For constraint type inference, we use bidirectional unification
32 // where both the x and y type parameters are identical. This is done
33 // by setting up one of them (using init) and then assigning its value
34 // to the other.
35
36 // A unifier maintains the current type parameters for x and y
37 // and the respective types inferred for each type parameter.
38 // A unifier is created by calling newUnifier.
39 type unifier struct {
40         exact bool
41         x, y  tparamsList // x and y must initialized via tparamsList.init
42         types []Type      // inferred types, shared by x and y
43 }
44
45 // newUnifier returns a new unifier.
46 // If exact is set, unification requires unified types to match
47 // exactly. If exact is not set, a named type's underlying type
48 // is considered if unification would fail otherwise, and the
49 // direction of channels is ignored.
50 func newUnifier(exact bool) *unifier {
51         u := &unifier{exact: exact}
52         u.x.unifier = u
53         u.y.unifier = u
54         return u
55 }
56
57 // unify attempts to unify x and y and reports whether it succeeded.
58 func (u *unifier) unify(x, y Type) bool {
59         return u.nify(x, y, nil)
60 }
61
62 // A tparamsList describes a list of type parameters and the types inferred for them.
63 type tparamsList struct {
64         unifier *unifier
65         tparams []*TypeName
66         // For each tparams element, there is a corresponding type slot index in indices.
67         // index  < 0: unifier.types[-index-1] == nil
68         // index == 0: no type slot allocated yet
69         // index  > 0: unifier.types[index-1] == typ
70         // Joined tparams elements share the same type slot and thus have the same index.
71         // By using a negative index for nil types we don't need to check unifier.types
72         // to see if we have a type or not.
73         indices []int // len(d.indices) == len(d.tparams)
74 }
75
76 // String returns a string representation for a tparamsList. For debugging.
77 func (d *tparamsList) String() string {
78         var buf bytes.Buffer
79         buf.WriteByte('[')
80         for i, tname := range d.tparams {
81                 if i > 0 {
82                         buf.WriteString(", ")
83                 }
84                 writeType(&buf, tname.typ, nil, nil)
85                 buf.WriteString(": ")
86                 writeType(&buf, d.at(i), nil, nil)
87         }
88         buf.WriteByte(']')
89         return buf.String()
90 }
91
92 // init initializes d with the given type parameters.
93 // The type parameters must be in the order in which they appear in their declaration
94 // (this ensures that the tparams indices match the respective type parameter index).
95 func (d *tparamsList) init(tparams []*TypeName) {
96         if len(tparams) == 0 {
97                 return
98         }
99         if debug {
100                 for i, tpar := range tparams {
101                         assert(i == tpar.typ.(*TypeParam).index)
102                 }
103         }
104         d.tparams = tparams
105         d.indices = make([]int, len(tparams))
106 }
107
108 // join unifies the i'th type parameter of x with the j'th type parameter of y.
109 // If both type parameters already have a type associated with them and they are
110 // not joined, join fails and return false.
111 func (u *unifier) join(i, j int) bool {
112         ti := u.x.indices[i]
113         tj := u.y.indices[j]
114         switch {
115         case ti == 0 && tj == 0:
116                 // Neither type parameter has a type slot associated with them.
117                 // Allocate a new joined nil type slot (negative index).
118                 u.types = append(u.types, nil)
119                 u.x.indices[i] = -len(u.types)
120                 u.y.indices[j] = -len(u.types)
121         case ti == 0:
122                 // The type parameter for x has no type slot yet. Use slot of y.
123                 u.x.indices[i] = tj
124         case tj == 0:
125                 // The type parameter for y has no type slot yet. Use slot of x.
126                 u.y.indices[j] = ti
127
128         // Both type parameters have a slot: ti != 0 && tj != 0.
129         case ti == tj:
130                 // Both type parameters already share the same slot. Nothing to do.
131                 break
132         case ti > 0 && tj > 0:
133                 // Both type parameters have (possibly different) inferred types. Cannot join.
134                 return false
135         case ti > 0:
136                 // Only the type parameter for x has an inferred type. Use x slot for y.
137                 u.y.setIndex(j, ti)
138         // This case is handled like the default case.
139         // case tj > 0:
140         //      // Only the type parameter for y has an inferred type. Use y slot for x.
141         //      u.x.setIndex(i, tj)
142         default:
143                 // Neither type parameter has an inferred type. Use y slot for x
144                 // (or x slot for y, it doesn't matter).
145                 u.x.setIndex(i, tj)
146         }
147         return true
148 }
149
150 // If typ is a type parameter of d, index returns the type parameter index.
151 // Otherwise, the result is < 0.
152 func (d *tparamsList) index(typ Type) int {
153         if tpar, ok := typ.(*TypeParam); ok {
154                 return tparamIndex(d.tparams, tpar)
155         }
156         return -1
157 }
158
159 // If tpar is a type parameter in list, tparamIndex returns the type parameter index.
160 // Otherwise, the result is < 0. tpar must not be nil.
161 func tparamIndex(list []*TypeName, tpar *TypeParam) int {
162         if i := tpar.index; i < len(list) && list[i].typ == tpar {
163                 return i
164         }
165         return -1
166 }
167
168 // setIndex sets the type slot index for the i'th type parameter
169 // (and all its joined parameters) to tj. The type parameter
170 // must have a (possibly nil) type slot associated with it.
171 func (d *tparamsList) setIndex(i, tj int) {
172         ti := d.indices[i]
173         assert(ti != 0 && tj != 0)
174         for k, tk := range d.indices {
175                 if tk == ti {
176                         d.indices[k] = tj
177                 }
178         }
179 }
180
181 // at returns the type set for the i'th type parameter; or nil.
182 func (d *tparamsList) at(i int) Type {
183         if ti := d.indices[i]; ti > 0 {
184                 return d.unifier.types[ti-1]
185         }
186         return nil
187 }
188
189 // set sets the type typ for the i'th type parameter;
190 // typ must not be nil and it must not have been set before.
191 func (d *tparamsList) set(i int, typ Type) {
192         assert(typ != nil)
193         u := d.unifier
194         switch ti := d.indices[i]; {
195         case ti < 0:
196                 u.types[-ti-1] = typ
197                 d.setIndex(i, -ti)
198         case ti == 0:
199                 u.types = append(u.types, typ)
200                 d.indices[i] = len(u.types)
201         default:
202                 panic("type already set")
203         }
204 }
205
206 // types returns the list of inferred types (via unification) for the type parameters
207 // described by d, and an index. If all types were inferred, the returned index is < 0.
208 // Otherwise, it is the index of the first type parameter which couldn't be inferred;
209 // i.e., for which list[index] is nil.
210 func (d *tparamsList) types() (list []Type, index int) {
211         list = make([]Type, len(d.tparams))
212         index = -1
213         for i := range d.tparams {
214                 t := d.at(i)
215                 list[i] = t
216                 if index < 0 && t == nil {
217                         index = i
218                 }
219         }
220         return
221 }
222
223 func (u *unifier) nifyEq(x, y Type, p *ifacePair) bool {
224         return x == y || u.nify(x, y, p)
225 }
226
227 // nify implements the core unification algorithm which is an
228 // adapted version of Checker.identical0. For changes to that
229 // code the corresponding changes should be made here.
230 // Must not be called directly from outside the unifier.
231 func (u *unifier) nify(x, y Type, p *ifacePair) bool {
232         // types must be expanded for comparison
233         x = expand(x)
234         y = expand(y)
235
236         if !u.exact {
237                 // If exact unification is known to fail because we attempt to
238                 // match a type name against an unnamed type literal, consider
239                 // the underlying type of the named type.
240                 // (Subtle: We use isNamed to include any type with a name (incl.
241                 // basic types and type parameters. We use asNamed because we only
242                 // want *Named types.)
243                 switch {
244                 case !isNamed(x) && y != nil && asNamed(y) != nil:
245                         return u.nify(x, under(y), p)
246                 case x != nil && asNamed(x) != nil && !isNamed(y):
247                         return u.nify(under(x), y, p)
248                 }
249         }
250
251         // Cases where at least one of x or y is a type parameter.
252         switch i, j := u.x.index(x), u.y.index(y); {
253         case i >= 0 && j >= 0:
254                 // both x and y are type parameters
255                 if u.join(i, j) {
256                         return true
257                 }
258                 // both x and y have an inferred type - they must match
259                 return u.nifyEq(u.x.at(i), u.y.at(j), p)
260
261         case i >= 0:
262                 // x is a type parameter, y is not
263                 if tx := u.x.at(i); tx != nil {
264                         return u.nifyEq(tx, y, p)
265                 }
266                 // otherwise, infer type from y
267                 u.x.set(i, y)
268                 return true
269
270         case j >= 0:
271                 // y is a type parameter, x is not
272                 if ty := u.y.at(j); ty != nil {
273                         return u.nifyEq(x, ty, p)
274                 }
275                 // otherwise, infer type from x
276                 u.y.set(j, x)
277                 return true
278         }
279
280         // For type unification, do not shortcut (x == y) for identical
281         // types. Instead keep comparing them element-wise to unify the
282         // matching (and equal type parameter types). A simple test case
283         // where this matters is: func f[P any](a P) { f(a) } .
284
285         switch x := x.(type) {
286         case *Basic:
287                 // Basic types are singletons except for the rune and byte
288                 // aliases, thus we cannot solely rely on the x == y check
289                 // above. See also comment in TypeName.IsAlias.
290                 if y, ok := y.(*Basic); ok {
291                         return x.kind == y.kind
292                 }
293
294         case *Array:
295                 // Two array types are identical if they have identical element types
296                 // and the same array length.
297                 if y, ok := y.(*Array); ok {
298                         // If one or both array lengths are unknown (< 0) due to some error,
299                         // assume they are the same to avoid spurious follow-on errors.
300                         return (x.len < 0 || y.len < 0 || x.len == y.len) && u.nify(x.elem, y.elem, p)
301                 }
302
303         case *Slice:
304                 // Two slice types are identical if they have identical element types.
305                 if y, ok := y.(*Slice); ok {
306                         return u.nify(x.elem, y.elem, p)
307                 }
308
309         case *Struct:
310                 // Two struct types are identical if they have the same sequence of fields,
311                 // and if corresponding fields have the same names, and identical types,
312                 // and identical tags. Two embedded fields are considered to have the same
313                 // name. Lower-case field names from different packages are always different.
314                 if y, ok := y.(*Struct); ok {
315                         if x.NumFields() == y.NumFields() {
316                                 for i, f := range x.fields {
317                                         g := y.fields[i]
318                                         if f.embedded != g.embedded ||
319                                                 x.Tag(i) != y.Tag(i) ||
320                                                 !f.sameId(g.pkg, g.name) ||
321                                                 !u.nify(f.typ, g.typ, p) {
322                                                 return false
323                                         }
324                                 }
325                                 return true
326                         }
327                 }
328
329         case *Pointer:
330                 // Two pointer types are identical if they have identical base types.
331                 if y, ok := y.(*Pointer); ok {
332                         return u.nify(x.base, y.base, p)
333                 }
334
335         case *Tuple:
336                 // Two tuples types are identical if they have the same number of elements
337                 // and corresponding elements have identical types.
338                 if y, ok := y.(*Tuple); ok {
339                         if x.Len() == y.Len() {
340                                 if x != nil {
341                                         for i, v := range x.vars {
342                                                 w := y.vars[i]
343                                                 if !u.nify(v.typ, w.typ, p) {
344                                                         return false
345                                                 }
346                                         }
347                                 }
348                                 return true
349                         }
350                 }
351
352         case *Signature:
353                 // Two function types are identical if they have the same number of parameters
354                 // and result values, corresponding parameter and result types are identical,
355                 // and either both functions are variadic or neither is. Parameter and result
356                 // names are not required to match.
357                 // TODO(gri) handle type parameters or document why we can ignore them.
358                 if y, ok := y.(*Signature); ok {
359                         return x.variadic == y.variadic &&
360                                 u.nify(x.params, y.params, p) &&
361                                 u.nify(x.results, y.results, p)
362                 }
363
364         case *Union:
365                 panic("unimplemented: unification with type sets described by types")
366
367         case *Interface:
368                 // Two interface types are identical if they have the same set of methods with
369                 // the same names and identical function types. Lower-case method names from
370                 // different packages are always different. The order of the methods is irrelevant.
371                 if y, ok := y.(*Interface); ok {
372                         xset := x.typeSet()
373                         yset := y.typeSet()
374                         if !Identical(xset.types, yset.types) {
375                                 return false
376                         }
377                         a := xset.methods
378                         b := yset.methods
379                         if len(a) == len(b) {
380                                 // Interface types are the only types where cycles can occur
381                                 // that are not "terminated" via named types; and such cycles
382                                 // can only be created via method parameter types that are
383                                 // anonymous interfaces (directly or indirectly) embedding
384                                 // the current interface. Example:
385                                 //
386                                 //    type T interface {
387                                 //        m() interface{T}
388                                 //    }
389                                 //
390                                 // If two such (differently named) interfaces are compared,
391                                 // endless recursion occurs if the cycle is not detected.
392                                 //
393                                 // If x and y were compared before, they must be equal
394                                 // (if they were not, the recursion would have stopped);
395                                 // search the ifacePair stack for the same pair.
396                                 //
397                                 // This is a quadratic algorithm, but in practice these stacks
398                                 // are extremely short (bounded by the nesting depth of interface
399                                 // type declarations that recur via parameter types, an extremely
400                                 // rare occurrence). An alternative implementation might use a
401                                 // "visited" map, but that is probably less efficient overall.
402                                 q := &ifacePair{x, y, p}
403                                 for p != nil {
404                                         if p.identical(q) {
405                                                 return true // same pair was compared before
406                                         }
407                                         p = p.prev
408                                 }
409                                 if debug {
410                                         assertSortedMethods(a)
411                                         assertSortedMethods(b)
412                                 }
413                                 for i, f := range a {
414                                         g := b[i]
415                                         if f.Id() != g.Id() || !u.nify(f.typ, g.typ, q) {
416                                                 return false
417                                         }
418                                 }
419                                 return true
420                         }
421                 }
422
423         case *Map:
424                 // Two map types are identical if they have identical key and value types.
425                 if y, ok := y.(*Map); ok {
426                         return u.nify(x.key, y.key, p) && u.nify(x.elem, y.elem, p)
427                 }
428
429         case *Chan:
430                 // Two channel types are identical if they have identical value types.
431                 if y, ok := y.(*Chan); ok {
432                         return (!u.exact || x.dir == y.dir) && u.nify(x.elem, y.elem, p)
433                 }
434
435         case *Named:
436                 // Two named types are identical if their type names originate
437                 // in the same type declaration.
438                 // if y, ok := y.(*Named); ok {
439                 //      return x.obj == y.obj
440                 // }
441                 if y, ok := y.(*Named); ok {
442                         // TODO(gri) This is not always correct: two types may have the same names
443                         //           in the same package if one of them is nested in a function.
444                         //           Extremely unlikely but we need an always correct solution.
445                         if x.obj.pkg == y.obj.pkg && x.obj.name == y.obj.name {
446                                 assert(len(x.targs) == len(y.targs))
447                                 for i, x := range x.targs {
448                                         if !u.nify(x, y.targs[i], p) {
449                                                 return false
450                                         }
451                                 }
452                                 return true
453                         }
454                 }
455
456         case *TypeParam:
457                 // Two type parameters (which are not part of the type parameters of the
458                 // enclosing type as those are handled in the beginning of this function)
459                 // are identical if they originate in the same declaration.
460                 return x == y
461
462         // case *instance:
463         //      unreachable since types are expanded
464
465         case nil:
466                 // avoid a crash in case of nil type
467
468         default:
469                 panic(fmt.Sprintf("### u.nify(%s, %s), u.x.tparams = %s", x, y, u.x.tparams))
470         }
471
472         return false
473 }