]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/unify.go
go/types, types2: remove misleading example from comment
[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         "strings"
13 )
14
15 // The unifier maintains two separate sets of type parameters x and y
16 // which are used to resolve type parameters in the x and y arguments
17 // provided to the unify call. For unidirectional unification, only
18 // one of these sets (say x) is provided, and then type parameters are
19 // only resolved for the x argument passed to unify, not the y argument
20 // (even if that also contains possibly the same type parameters).
21 //
22 // For bidirectional unification, both sets are provided. This enables
23 // unification to go from argument to parameter type and vice versa.
24 // For constraint type inference, we use bidirectional unification
25 // where both the x and y type parameters are identical. This is done
26 // by setting up one of them (using init) and then assigning its value
27 // to the other.
28
29 const (
30         // Upper limit for recursion depth. Used to catch infinite recursions
31         // due to implementation issues (e.g., see issues #48619, #48656).
32         unificationDepthLimit = 50
33
34         // Whether to panic when unificationDepthLimit is reached.
35         // If disabled, a recursion depth overflow results in a (quiet)
36         // unification failure.
37         panicAtUnificationDepthLimit = true
38
39         // If enableCoreTypeUnification is set, unification will consider
40         // the core types, if any, of non-local (unbound) type parameters.
41         enableCoreTypeUnification = true
42
43         // If traceInference is set, unification will print a trace of its operation.
44         // Interpretation of trace:
45         //   x ≡ y    attempt to unify types x and y
46         //   p ➞ y    type parameter p is set to type y (p is inferred to be y)
47         //   p ⇄ q    type parameters p and q match (p is inferred to be q and vice versa)
48         //   x ≢ y    types x and y cannot be unified
49         //   [p, q, ...] ➞ [x, y, ...]    mapping from type parameters to types
50         traceInference = false
51 )
52
53 // A unifier maintains the current type parameters for x and y
54 // and the respective types inferred for each type parameter.
55 // A unifier is created by calling newUnifier.
56 type unifier struct {
57         exact bool
58         x, y  tparamsList // x and y must initialized via tparamsList.init
59         types []Type      // inferred types, shared by x and y
60         depth int         // recursion depth during unification
61 }
62
63 // newUnifier returns a new unifier.
64 // If exact is set, unification requires unified types to match
65 // exactly. If exact is not set, a named type's underlying type
66 // is considered if unification would fail otherwise, and the
67 // direction of channels is ignored.
68 // TODO(gri) exact is not set anymore by a caller. Consider removing it.
69 func newUnifier(exact bool) *unifier {
70         u := &unifier{exact: exact}
71         u.x.unifier = u
72         u.y.unifier = u
73         return u
74 }
75
76 // unify attempts to unify x and y and reports whether it succeeded.
77 func (u *unifier) unify(x, y Type) bool {
78         return u.nify(x, y, nil)
79 }
80
81 func (u *unifier) tracef(format string, args ...interface{}) {
82         fmt.Println(strings.Repeat(".  ", u.depth) + sprintf(nil, true, format, args...))
83 }
84
85 // A tparamsList describes a list of type parameters and the types inferred for them.
86 type tparamsList struct {
87         unifier *unifier
88         tparams []*TypeParam
89         // For each tparams element, there is a corresponding type slot index in indices.
90         // index  < 0: unifier.types[-index-1] == nil
91         // index == 0: no type slot allocated yet
92         // index  > 0: unifier.types[index-1] == typ
93         // Joined tparams elements share the same type slot and thus have the same index.
94         // By using a negative index for nil types we don't need to check unifier.types
95         // to see if we have a type or not.
96         indices []int // len(d.indices) == len(d.tparams)
97 }
98
99 // String returns a string representation for a tparamsList. For debugging.
100 func (d *tparamsList) String() string {
101         var buf bytes.Buffer
102         w := newTypeWriter(&buf, nil)
103         w.byte('[')
104         for i, tpar := range d.tparams {
105                 if i > 0 {
106                         w.string(", ")
107                 }
108                 w.typ(tpar)
109                 w.string(": ")
110                 w.typ(d.at(i))
111         }
112         w.byte(']')
113         return buf.String()
114 }
115
116 // init initializes d with the given type parameters.
117 // The type parameters must be in the order in which they appear in their declaration
118 // (this ensures that the tparams indices match the respective type parameter index).
119 func (d *tparamsList) init(tparams []*TypeParam) {
120         if len(tparams) == 0 {
121                 return
122         }
123         if debug {
124                 for i, tpar := range tparams {
125                         assert(i == tpar.index)
126                 }
127         }
128         d.tparams = tparams
129         d.indices = make([]int, len(tparams))
130 }
131
132 // join unifies the i'th type parameter of x with the j'th type parameter of y.
133 // If both type parameters already have a type associated with them and they are
134 // not joined, join fails and returns false.
135 func (u *unifier) join(i, j int) bool {
136         if traceInference {
137                 u.tracef("%s ⇄ %s", u.x.tparams[i], u.y.tparams[j])
138         }
139         ti := u.x.indices[i]
140         tj := u.y.indices[j]
141         switch {
142         case ti == 0 && tj == 0:
143                 // Neither type parameter has a type slot associated with them.
144                 // Allocate a new joined nil type slot (negative index).
145                 u.types = append(u.types, nil)
146                 u.x.indices[i] = -len(u.types)
147                 u.y.indices[j] = -len(u.types)
148         case ti == 0:
149                 // The type parameter for x has no type slot yet. Use slot of y.
150                 u.x.indices[i] = tj
151         case tj == 0:
152                 // The type parameter for y has no type slot yet. Use slot of x.
153                 u.y.indices[j] = ti
154
155         // Both type parameters have a slot: ti != 0 && tj != 0.
156         case ti == tj:
157                 // Both type parameters already share the same slot. Nothing to do.
158                 break
159         case ti > 0 && tj > 0:
160                 // Both type parameters have (possibly different) inferred types. Cannot join.
161                 // TODO(gri) Should we check if types are identical? Investigate.
162                 return false
163         case ti > 0:
164                 // Only the type parameter for x has an inferred type. Use x slot for y.
165                 u.y.setIndex(j, ti)
166         // This case is handled like the default case.
167         // case tj > 0:
168         //      // Only the type parameter for y has an inferred type. Use y slot for x.
169         //      u.x.setIndex(i, tj)
170         default:
171                 // Neither type parameter has an inferred type. Use y slot for x
172                 // (or x slot for y, it doesn't matter).
173                 u.x.setIndex(i, tj)
174         }
175         return true
176 }
177
178 // If typ is a type parameter of d, index returns the type parameter index.
179 // Otherwise, the result is < 0.
180 func (d *tparamsList) index(typ Type) int {
181         if tpar, ok := typ.(*TypeParam); ok {
182                 return tparamIndex(d.tparams, tpar)
183         }
184         return -1
185 }
186
187 // If tpar is a type parameter in list, tparamIndex returns the type parameter index.
188 // Otherwise, the result is < 0. tpar must not be nil.
189 func tparamIndex(list []*TypeParam, tpar *TypeParam) int {
190         // Once a type parameter is bound its index is >= 0. However, there are some
191         // code paths (namely tracing and type hashing) by which it is possible to
192         // arrive here with a type parameter that has not been bound, hence the check
193         // for 0 <= i below.
194         // TODO(rfindley): investigate a better approach for guarding against using
195         // unbound type parameters.
196         if i := tpar.index; 0 <= i && i < len(list) && list[i] == tpar {
197                 return i
198         }
199         return -1
200 }
201
202 // setIndex sets the type slot index for the i'th type parameter
203 // (and all its joined parameters) to tj. The type parameter
204 // must have a (possibly nil) type slot associated with it.
205 func (d *tparamsList) setIndex(i, tj int) {
206         ti := d.indices[i]
207         assert(ti != 0 && tj != 0)
208         for k, tk := range d.indices {
209                 if tk == ti {
210                         d.indices[k] = tj
211                 }
212         }
213 }
214
215 // at returns the type set for the i'th type parameter; or nil.
216 func (d *tparamsList) at(i int) Type {
217         if ti := d.indices[i]; ti > 0 {
218                 return d.unifier.types[ti-1]
219         }
220         return nil
221 }
222
223 // set sets the type typ for the i'th type parameter;
224 // typ must not be nil and it must not have been set before.
225 func (d *tparamsList) set(i int, typ Type) {
226         assert(typ != nil)
227         u := d.unifier
228         if traceInference {
229                 u.tracef("%s ➞ %s", d.tparams[i], typ)
230         }
231         switch ti := d.indices[i]; {
232         case ti < 0:
233                 u.types[-ti-1] = typ
234                 d.setIndex(i, -ti)
235         case ti == 0:
236                 u.types = append(u.types, typ)
237                 d.indices[i] = len(u.types)
238         default:
239                 panic("type already set")
240         }
241 }
242
243 // unknowns returns the number of type parameters for which no type has been set yet.
244 func (d *tparamsList) unknowns() int {
245         n := 0
246         for _, ti := range d.indices {
247                 if ti <= 0 {
248                         n++
249                 }
250         }
251         return n
252 }
253
254 // types returns the list of inferred types (via unification) for the type parameters
255 // described by d, and an index. If all types were inferred, the returned index is < 0.
256 // Otherwise, it is the index of the first type parameter which couldn't be inferred;
257 // i.e., for which list[index] is nil.
258 func (d *tparamsList) types() (list []Type, index int) {
259         list = make([]Type, len(d.tparams))
260         index = -1
261         for i := range d.tparams {
262                 t := d.at(i)
263                 list[i] = t
264                 if index < 0 && t == nil {
265                         index = i
266                 }
267         }
268         return
269 }
270
271 func (u *unifier) nifyEq(x, y Type, p *ifacePair) bool {
272         return x == y || u.nify(x, y, p)
273 }
274
275 // nify implements the core unification algorithm which is an
276 // adapted version of Checker.identical. For changes to that
277 // code the corresponding changes should be made here.
278 // Must not be called directly from outside the unifier.
279 func (u *unifier) nify(x, y Type, p *ifacePair) (result bool) {
280         if traceInference {
281                 u.tracef("%s ≡ %s", x, y)
282         }
283
284         // Stop gap for cases where unification fails.
285         if u.depth >= unificationDepthLimit {
286                 if traceInference {
287                         u.tracef("depth %d >= %d", u.depth, unificationDepthLimit)
288                 }
289                 if panicAtUnificationDepthLimit {
290                         panic("unification reached recursion depth limit")
291                 }
292                 return false
293         }
294         u.depth++
295         defer func() {
296                 u.depth--
297                 if traceInference && !result {
298                         u.tracef("%s ≢ %s", x, y)
299                 }
300         }()
301
302         if !u.exact {
303                 // If exact unification is known to fail because we attempt to
304                 // match a type name against an unnamed type literal, consider
305                 // the underlying type of the named type.
306                 // (We use !hasName to exclude any type with a name, including
307                 // basic types and type parameters; the rest are unamed types.)
308                 if nx, _ := x.(*Named); nx != nil && !hasName(y) {
309                         if traceInference {
310                                 u.tracef("under %s ≡ %s", nx, y)
311                         }
312                         return u.nify(nx.under(), y, p)
313                 } else if ny, _ := y.(*Named); ny != nil && !hasName(x) {
314                         if traceInference {
315                                 u.tracef("%s ≡ under %s", x, ny)
316                         }
317                         return u.nify(x, ny.under(), p)
318                 }
319         }
320
321         // Cases where at least one of x or y is a type parameter.
322         switch i, j := u.x.index(x), u.y.index(y); {
323         case i >= 0 && j >= 0:
324                 // both x and y are type parameters
325                 if u.join(i, j) {
326                         return true
327                 }
328                 // both x and y have an inferred type - they must match
329                 return u.nifyEq(u.x.at(i), u.y.at(j), p)
330
331         case i >= 0:
332                 // x is a type parameter, y is not
333                 if tx := u.x.at(i); tx != nil {
334                         return u.nifyEq(tx, y, p)
335                 }
336                 // otherwise, infer type from y
337                 u.x.set(i, y)
338                 return true
339
340         case j >= 0:
341                 // y is a type parameter, x is not
342                 if ty := u.y.at(j); ty != nil {
343                         return u.nifyEq(x, ty, p)
344                 }
345                 // otherwise, infer type from x
346                 u.y.set(j, x)
347                 return true
348         }
349
350         // If we get here and x or y is a type parameter, they are type parameters
351         // from outside our declaration list. Try to unify their core types, if any
352         // (see go.dev/issue/50755 for a test case).
353         if enableCoreTypeUnification && !u.exact {
354                 if isTypeParam(x) && !hasName(y) {
355                         // When considering the type parameter for unification
356                         // we look at the adjusted core term (adjusted core type
357                         // with tilde information).
358                         // If the adjusted core type is a named type N; the
359                         // corresponding core type is under(N). Since !u.exact
360                         // and y doesn't have a name, unification will end up
361                         // comparing under(N) to y, so we can just use the core
362                         // type instead. And we can ignore the tilde because we
363                         // already look at the underlying types on both sides
364                         // and we have known types on both sides.
365                         // Optimization.
366                         if cx := coreType(x); cx != nil {
367                                 if traceInference {
368                                         u.tracef("core %s ≡ %s", x, y)
369                                 }
370                                 return u.nify(cx, y, p)
371                         }
372                 } else if isTypeParam(y) && !hasName(x) {
373                         // see comment above
374                         if cy := coreType(y); cy != nil {
375                                 if traceInference {
376                                         u.tracef("%s ≡ core %s", x, y)
377                                 }
378                                 return u.nify(x, cy, p)
379                         }
380                 }
381         }
382
383         // For type unification, do not shortcut (x == y) for identical
384         // types. Instead keep comparing them element-wise to unify the
385         // matching (and equal type parameter types). A simple test case
386         // where this matters is: func f[P any](a P) { f(a) } .
387
388         switch x := x.(type) {
389         case *Basic:
390                 // Basic types are singletons except for the rune and byte
391                 // aliases, thus we cannot solely rely on the x == y check
392                 // above. See also comment in TypeName.IsAlias.
393                 if y, ok := y.(*Basic); ok {
394                         return x.kind == y.kind
395                 }
396
397         case *Array:
398                 // Two array types are identical if they have identical element types
399                 // and the same array length.
400                 if y, ok := y.(*Array); ok {
401                         // If one or both array lengths are unknown (< 0) due to some error,
402                         // assume they are the same to avoid spurious follow-on errors.
403                         return (x.len < 0 || y.len < 0 || x.len == y.len) && u.nify(x.elem, y.elem, p)
404                 }
405
406         case *Slice:
407                 // Two slice types are identical if they have identical element types.
408                 if y, ok := y.(*Slice); ok {
409                         return u.nify(x.elem, y.elem, p)
410                 }
411
412         case *Struct:
413                 // Two struct types are identical if they have the same sequence of fields,
414                 // and if corresponding fields have the same names, and identical types,
415                 // and identical tags. Two embedded fields are considered to have the same
416                 // name. Lower-case field names from different packages are always different.
417                 if y, ok := y.(*Struct); ok {
418                         if x.NumFields() == y.NumFields() {
419                                 for i, f := range x.fields {
420                                         g := y.fields[i]
421                                         if f.embedded != g.embedded ||
422                                                 x.Tag(i) != y.Tag(i) ||
423                                                 !f.sameId(g.pkg, g.name) ||
424                                                 !u.nify(f.typ, g.typ, p) {
425                                                 return false
426                                         }
427                                 }
428                                 return true
429                         }
430                 }
431
432         case *Pointer:
433                 // Two pointer types are identical if they have identical base types.
434                 if y, ok := y.(*Pointer); ok {
435                         return u.nify(x.base, y.base, p)
436                 }
437
438         case *Tuple:
439                 // Two tuples types are identical if they have the same number of elements
440                 // and corresponding elements have identical types.
441                 if y, ok := y.(*Tuple); ok {
442                         if x.Len() == y.Len() {
443                                 if x != nil {
444                                         for i, v := range x.vars {
445                                                 w := y.vars[i]
446                                                 if !u.nify(v.typ, w.typ, p) {
447                                                         return false
448                                                 }
449                                         }
450                                 }
451                                 return true
452                         }
453                 }
454
455         case *Signature:
456                 // Two function types are identical if they have the same number of parameters
457                 // and result values, corresponding parameter and result types are identical,
458                 // and either both functions are variadic or neither is. Parameter and result
459                 // names are not required to match.
460                 // TODO(gri) handle type parameters or document why we can ignore them.
461                 if y, ok := y.(*Signature); ok {
462                         return x.variadic == y.variadic &&
463                                 u.nify(x.params, y.params, p) &&
464                                 u.nify(x.results, y.results, p)
465                 }
466
467         case *Interface:
468                 // Two interface types are identical if they have the same set of methods with
469                 // the same names and identical function types. Lower-case method names from
470                 // different packages are always different. The order of the methods is irrelevant.
471                 if y, ok := y.(*Interface); ok {
472                         xset := x.typeSet()
473                         yset := y.typeSet()
474                         if xset.comparable != yset.comparable {
475                                 return false
476                         }
477                         if !xset.terms.equal(yset.terms) {
478                                 return false
479                         }
480                         a := xset.methods
481                         b := yset.methods
482                         if len(a) == len(b) {
483                                 // Interface types are the only types where cycles can occur
484                                 // that are not "terminated" via named types; and such cycles
485                                 // can only be created via method parameter types that are
486                                 // anonymous interfaces (directly or indirectly) embedding
487                                 // the current interface. Example:
488                                 //
489                                 //    type T interface {
490                                 //        m() interface{T}
491                                 //    }
492                                 //
493                                 // If two such (differently named) interfaces are compared,
494                                 // endless recursion occurs if the cycle is not detected.
495                                 //
496                                 // If x and y were compared before, they must be equal
497                                 // (if they were not, the recursion would have stopped);
498                                 // search the ifacePair stack for the same pair.
499                                 //
500                                 // This is a quadratic algorithm, but in practice these stacks
501                                 // are extremely short (bounded by the nesting depth of interface
502                                 // type declarations that recur via parameter types, an extremely
503                                 // rare occurrence). An alternative implementation might use a
504                                 // "visited" map, but that is probably less efficient overall.
505                                 q := &ifacePair{x, y, p}
506                                 for p != nil {
507                                         if p.identical(q) {
508                                                 return true // same pair was compared before
509                                         }
510                                         p = p.prev
511                                 }
512                                 if debug {
513                                         assertSortedMethods(a)
514                                         assertSortedMethods(b)
515                                 }
516                                 for i, f := range a {
517                                         g := b[i]
518                                         if f.Id() != g.Id() || !u.nify(f.typ, g.typ, q) {
519                                                 return false
520                                         }
521                                 }
522                                 return true
523                         }
524                 }
525
526         case *Map:
527                 // Two map types are identical if they have identical key and value types.
528                 if y, ok := y.(*Map); ok {
529                         return u.nify(x.key, y.key, p) && u.nify(x.elem, y.elem, p)
530                 }
531
532         case *Chan:
533                 // Two channel types are identical if they have identical value types.
534                 if y, ok := y.(*Chan); ok {
535                         return (!u.exact || x.dir == y.dir) && u.nify(x.elem, y.elem, p)
536                 }
537
538         case *Named:
539                 // TODO(gri) This code differs now from the parallel code in Checker.identical. Investigate.
540                 if y, ok := y.(*Named); ok {
541                         xargs := x.TypeArgs().list()
542                         yargs := y.TypeArgs().list()
543
544                         if len(xargs) != len(yargs) {
545                                 return false
546                         }
547
548                         // TODO(gri) This is not always correct: two types may have the same names
549                         //           in the same package if one of them is nested in a function.
550                         //           Extremely unlikely but we need an always correct solution.
551                         if x.obj.pkg == y.obj.pkg && x.obj.name == y.obj.name {
552                                 for i, x := range xargs {
553                                         if !u.nify(x, yargs[i], p) {
554                                                 return false
555                                         }
556                                 }
557                                 return true
558                         }
559                 }
560
561         case *TypeParam:
562                 // Two type parameters (which are not part of the type parameters of the
563                 // enclosing type as those are handled in the beginning of this function)
564                 // are identical if they originate in the same declaration.
565                 return x == y
566
567         case nil:
568                 // avoid a crash in case of nil type
569
570         default:
571                 panic(sprintf(nil, true, "u.nify(%s, %s), u.x.tparams = %s", x, y, u.x.tparams))
572         }
573
574         return false
575 }