]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/predicates.go
go/types, types2: ensure that named types never expand infinitely
[gostls13.git] / src / cmd / compile / internal / types2 / predicates.go
1 // Copyright 2012 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 commonly used type predicates.
6
7 package types2
8
9 // The isX predicates below report whether t is an X.
10 // If t is a type parameter the result is false; i.e.,
11 // these predicates don't look inside a type parameter.
12
13 func isBoolean(t Type) bool        { return isBasic(t, IsBoolean) }
14 func isInteger(t Type) bool        { return isBasic(t, IsInteger) }
15 func isUnsigned(t Type) bool       { return isBasic(t, IsUnsigned) }
16 func isFloat(t Type) bool          { return isBasic(t, IsFloat) }
17 func isComplex(t Type) bool        { return isBasic(t, IsComplex) }
18 func isNumeric(t Type) bool        { return isBasic(t, IsNumeric) }
19 func isString(t Type) bool         { return isBasic(t, IsString) }
20 func isIntegerOrFloat(t Type) bool { return isBasic(t, IsInteger|IsFloat) }
21 func isConstType(t Type) bool      { return isBasic(t, IsConstType) }
22
23 // isBasic reports whether under(t) is a basic type with the specified info.
24 // If t is a type parameter the result is false; i.e.,
25 // isBasic does not look inside a type parameter.
26 func isBasic(t Type, info BasicInfo) bool {
27         u, _ := under(t).(*Basic)
28         return u != nil && u.info&info != 0
29 }
30
31 // The allX predicates below report whether t is an X.
32 // If t is a type parameter the result is true if isX is true
33 // for all specified types of the type parameter's type set.
34 // allX is an optimized version of isX(coreType(t)) (which
35 // is the same as underIs(t, isX)).
36
37 func allBoolean(t Type) bool         { return allBasic(t, IsBoolean) }
38 func allInteger(t Type) bool         { return allBasic(t, IsInteger) }
39 func allUnsigned(t Type) bool        { return allBasic(t, IsUnsigned) }
40 func allNumeric(t Type) bool         { return allBasic(t, IsNumeric) }
41 func allString(t Type) bool          { return allBasic(t, IsString) }
42 func allOrdered(t Type) bool         { return allBasic(t, IsOrdered) }
43 func allNumericOrString(t Type) bool { return allBasic(t, IsNumeric|IsString) }
44
45 // allBasic reports whether under(t) is a basic type with the specified info.
46 // If t is a type parameter, the result is true if isBasic(t, info) is true
47 // for all specific types of the type parameter's type set.
48 // allBasic(t, info) is an optimized version of isBasic(coreType(t), info).
49 func allBasic(t Type, info BasicInfo) bool {
50         if tpar, _ := t.(*TypeParam); tpar != nil {
51                 return tpar.is(func(t *term) bool { return t != nil && isBasic(t.typ, info) })
52         }
53         return isBasic(t, info)
54 }
55
56 // hasName reports whether t has a name. This includes
57 // predeclared types, defined types, and type parameters.
58 // hasName may be called with types that are not fully set up.
59 func hasName(t Type) bool {
60         switch t.(type) {
61         case *Basic, *Named, *TypeParam:
62                 return true
63         }
64         return false
65 }
66
67 // isTyped reports whether t is typed; i.e., not an untyped
68 // constant or boolean. isTyped may be called with types that
69 // are not fully set up.
70 func isTyped(t Type) bool {
71         // isTyped is called with types that are not fully
72         // set up. Must not call under()!
73         b, _ := t.(*Basic)
74         return b == nil || b.info&IsUntyped == 0
75 }
76
77 // isUntyped(t) is the same as !isTyped(t).
78 func isUntyped(t Type) bool {
79         return !isTyped(t)
80 }
81
82 // IsInterface reports whether t is an interface type.
83 func IsInterface(t Type) bool {
84         _, ok := under(t).(*Interface)
85         return ok
86 }
87
88 // isNonTypeParamInterface reports whether t is an interface type but not a type parameter.
89 func isNonTypeParamInterface(t Type) bool {
90         return !isTypeParam(t) && IsInterface(t)
91 }
92
93 // isTypeParam reports whether t is a type parameter.
94 func isTypeParam(t Type) bool {
95         _, ok := t.(*TypeParam)
96         return ok
97 }
98
99 // isGeneric reports whether a type is a generic, uninstantiated type
100 // (generic signatures are not included).
101 // TODO(gri) should we include signatures or assert that they are not present?
102 func isGeneric(t Type) bool {
103         // A parameterized type is only generic if it doesn't have an instantiation already.
104         named, _ := t.(*Named)
105         return named != nil && named.obj != nil && named.inst == nil && named.TypeParams().Len() > 0
106 }
107
108 // Comparable reports whether values of type T are comparable.
109 func Comparable(T Type) bool {
110         return comparable(T, true, nil, nil)
111 }
112
113 // If dynamic is set, non-type parameter interfaces are always comparable.
114 // If reportf != nil, it may be used to report why T is not comparable.
115 func comparable(T Type, dynamic bool, seen map[Type]bool, reportf func(string, ...interface{})) bool {
116         if seen[T] {
117                 return true
118         }
119         if seen == nil {
120                 seen = make(map[Type]bool)
121         }
122         seen[T] = true
123
124         switch t := under(T).(type) {
125         case *Basic:
126                 // assume invalid types to be comparable
127                 // to avoid follow-up errors
128                 return t.kind != UntypedNil
129         case *Pointer, *Chan:
130                 return true
131         case *Struct:
132                 for _, f := range t.fields {
133                         if !comparable(f.typ, dynamic, seen, nil) {
134                                 if reportf != nil {
135                                         reportf("struct containing %s cannot be compared", f.typ)
136                                 }
137                                 return false
138                         }
139                 }
140                 return true
141         case *Array:
142                 if !comparable(t.elem, dynamic, seen, nil) {
143                         if reportf != nil {
144                                 reportf("%s cannot be compared", t)
145                         }
146                         return false
147                 }
148                 return true
149         case *Interface:
150                 return dynamic && !isTypeParam(T) || t.typeSet().IsComparable(seen)
151         }
152         return false
153 }
154
155 // hasNil reports whether type t includes the nil value.
156 func hasNil(t Type) bool {
157         switch u := under(t).(type) {
158         case *Basic:
159                 return u.kind == UnsafePointer
160         case *Slice, *Pointer, *Signature, *Map, *Chan:
161                 return true
162         case *Interface:
163                 return !isTypeParam(t) || u.typeSet().underIs(func(u Type) bool {
164                         return u != nil && hasNil(u)
165                 })
166         }
167         return false
168 }
169
170 // An ifacePair is a node in a stack of interface type pairs compared for identity.
171 type ifacePair struct {
172         x, y *Interface
173         prev *ifacePair
174 }
175
176 func (p *ifacePair) identical(q *ifacePair) bool {
177         return p.x == q.x && p.y == q.y || p.x == q.y && p.y == q.x
178 }
179
180 // For changes to this code the corresponding changes should be made to unifier.nify.
181 func identical(x, y Type, cmpTags bool, p *ifacePair) bool {
182         if x == y {
183                 return true
184         }
185
186         switch x := x.(type) {
187         case *Basic:
188                 // Basic types are singletons except for the rune and byte
189                 // aliases, thus we cannot solely rely on the x == y check
190                 // above. See also comment in TypeName.IsAlias.
191                 if y, ok := y.(*Basic); ok {
192                         return x.kind == y.kind
193                 }
194
195         case *Array:
196                 // Two array types are identical if they have identical element types
197                 // and the same array length.
198                 if y, ok := y.(*Array); ok {
199                         // If one or both array lengths are unknown (< 0) due to some error,
200                         // assume they are the same to avoid spurious follow-on errors.
201                         return (x.len < 0 || y.len < 0 || x.len == y.len) && identical(x.elem, y.elem, cmpTags, p)
202                 }
203
204         case *Slice:
205                 // Two slice types are identical if they have identical element types.
206                 if y, ok := y.(*Slice); ok {
207                         return identical(x.elem, y.elem, cmpTags, p)
208                 }
209
210         case *Struct:
211                 // Two struct types are identical if they have the same sequence of fields,
212                 // and if corresponding fields have the same names, and identical types,
213                 // and identical tags. Two embedded fields are considered to have the same
214                 // name. Lower-case field names from different packages are always different.
215                 if y, ok := y.(*Struct); ok {
216                         if x.NumFields() == y.NumFields() {
217                                 for i, f := range x.fields {
218                                         g := y.fields[i]
219                                         if f.embedded != g.embedded ||
220                                                 cmpTags && x.Tag(i) != y.Tag(i) ||
221                                                 !f.sameId(g.pkg, g.name) ||
222                                                 !identical(f.typ, g.typ, cmpTags, p) {
223                                                 return false
224                                         }
225                                 }
226                                 return true
227                         }
228                 }
229
230         case *Pointer:
231                 // Two pointer types are identical if they have identical base types.
232                 if y, ok := y.(*Pointer); ok {
233                         return identical(x.base, y.base, cmpTags, p)
234                 }
235
236         case *Tuple:
237                 // Two tuples types are identical if they have the same number of elements
238                 // and corresponding elements have identical types.
239                 if y, ok := y.(*Tuple); ok {
240                         if x.Len() == y.Len() {
241                                 if x != nil {
242                                         for i, v := range x.vars {
243                                                 w := y.vars[i]
244                                                 if !identical(v.typ, w.typ, cmpTags, p) {
245                                                         return false
246                                                 }
247                                         }
248                                 }
249                                 return true
250                         }
251                 }
252
253         case *Signature:
254                 y, _ := y.(*Signature)
255                 if y == nil {
256                         return false
257                 }
258
259                 // Two function types are identical if they have the same number of
260                 // parameters and result values, corresponding parameter and result types
261                 // are identical, and either both functions are variadic or neither is.
262                 // Parameter and result names are not required to match, and type
263                 // parameters are considered identical modulo renaming.
264
265                 if x.TypeParams().Len() != y.TypeParams().Len() {
266                         return false
267                 }
268
269                 // In the case of generic signatures, we will substitute in yparams and
270                 // yresults.
271                 yparams := y.params
272                 yresults := y.results
273
274                 if x.TypeParams().Len() > 0 {
275                         // We must ignore type parameter names when comparing x and y. The
276                         // easiest way to do this is to substitute x's type parameters for y's.
277                         xtparams := x.TypeParams().list()
278                         ytparams := y.TypeParams().list()
279
280                         var targs []Type
281                         for i := range xtparams {
282                                 targs = append(targs, x.TypeParams().At(i))
283                         }
284                         smap := makeSubstMap(ytparams, targs)
285
286                         var check *Checker   // ok to call subst on a nil *Checker
287                         ctxt := NewContext() // need a non-nil Context for the substitution below
288
289                         // Constraints must be pair-wise identical, after substitution.
290                         for i, xtparam := range xtparams {
291                                 ybound := check.subst(nopos, ytparams[i].bound, smap, nil, ctxt)
292                                 if !identical(xtparam.bound, ybound, cmpTags, p) {
293                                         return false
294                                 }
295                         }
296
297                         yparams = check.subst(nopos, y.params, smap, nil, ctxt).(*Tuple)
298                         yresults = check.subst(nopos, y.results, smap, nil, ctxt).(*Tuple)
299                 }
300
301                 return x.variadic == y.variadic &&
302                         identical(x.params, yparams, cmpTags, p) &&
303                         identical(x.results, yresults, cmpTags, p)
304
305         case *Union:
306                 if y, _ := y.(*Union); y != nil {
307                         // TODO(rfindley): can this be reached during type checking? If so,
308                         // consider passing a type set map.
309                         unionSets := make(map[*Union]*_TypeSet)
310                         xset := computeUnionTypeSet(nil, unionSets, nopos, x)
311                         yset := computeUnionTypeSet(nil, unionSets, nopos, y)
312                         return xset.terms.equal(yset.terms)
313                 }
314
315         case *Interface:
316                 // Two interface types are identical if they describe the same type sets.
317                 // With the existing implementation restriction, this simplifies to:
318                 //
319                 // Two interface types are identical if they have the same set of methods with
320                 // the same names and identical function types, and if any type restrictions
321                 // are the same. Lower-case method names from different packages are always
322                 // different. The order of the methods is irrelevant.
323                 if y, ok := y.(*Interface); ok {
324                         xset := x.typeSet()
325                         yset := y.typeSet()
326                         if xset.comparable != yset.comparable {
327                                 return false
328                         }
329                         if !xset.terms.equal(yset.terms) {
330                                 return false
331                         }
332                         a := xset.methods
333                         b := yset.methods
334                         if len(a) == len(b) {
335                                 // Interface types are the only types where cycles can occur
336                                 // that are not "terminated" via named types; and such cycles
337                                 // can only be created via method parameter types that are
338                                 // anonymous interfaces (directly or indirectly) embedding
339                                 // the current interface. Example:
340                                 //
341                                 //    type T interface {
342                                 //        m() interface{T}
343                                 //    }
344                                 //
345                                 // If two such (differently named) interfaces are compared,
346                                 // endless recursion occurs if the cycle is not detected.
347                                 //
348                                 // If x and y were compared before, they must be equal
349                                 // (if they were not, the recursion would have stopped);
350                                 // search the ifacePair stack for the same pair.
351                                 //
352                                 // This is a quadratic algorithm, but in practice these stacks
353                                 // are extremely short (bounded by the nesting depth of interface
354                                 // type declarations that recur via parameter types, an extremely
355                                 // rare occurrence). An alternative implementation might use a
356                                 // "visited" map, but that is probably less efficient overall.
357                                 q := &ifacePair{x, y, p}
358                                 for p != nil {
359                                         if p.identical(q) {
360                                                 return true // same pair was compared before
361                                         }
362                                         p = p.prev
363                                 }
364                                 if debug {
365                                         assertSortedMethods(a)
366                                         assertSortedMethods(b)
367                                 }
368                                 for i, f := range a {
369                                         g := b[i]
370                                         if f.Id() != g.Id() || !identical(f.typ, g.typ, cmpTags, q) {
371                                                 return false
372                                         }
373                                 }
374                                 return true
375                         }
376                 }
377
378         case *Map:
379                 // Two map types are identical if they have identical key and value types.
380                 if y, ok := y.(*Map); ok {
381                         return identical(x.key, y.key, cmpTags, p) && identical(x.elem, y.elem, cmpTags, p)
382                 }
383
384         case *Chan:
385                 // Two channel types are identical if they have identical value types
386                 // and the same direction.
387                 if y, ok := y.(*Chan); ok {
388                         return x.dir == y.dir && identical(x.elem, y.elem, cmpTags, p)
389                 }
390
391         case *Named:
392                 // Two named types are identical if their type names originate
393                 // in the same type declaration.
394                 if y, ok := y.(*Named); ok {
395                         xargs := x.TypeArgs().list()
396                         yargs := y.TypeArgs().list()
397
398                         if len(xargs) != len(yargs) {
399                                 return false
400                         }
401
402                         if len(xargs) > 0 {
403                                 // Instances are identical if their original type and type arguments
404                                 // are identical.
405                                 if !Identical(x.Origin(), y.Origin()) {
406                                         return false
407                                 }
408                                 for i, xa := range xargs {
409                                         if !Identical(xa, yargs[i]) {
410                                                 return false
411                                         }
412                                 }
413                                 return true
414                         }
415
416                         // TODO(gri) Why is x == y not sufficient? And if it is,
417                         //           we can just return false here because x == y
418                         //           is caught in the very beginning of this function.
419                         return x.obj == y.obj
420                 }
421
422         case *TypeParam:
423                 // nothing to do (x and y being equal is caught in the very beginning of this function)
424
425         case nil:
426                 // avoid a crash in case of nil type
427
428         default:
429                 unreachable()
430         }
431
432         return false
433 }
434
435 // identicalInstance reports if two type instantiations are identical.
436 // Instantiations are identical if their origin and type arguments are
437 // identical.
438 func identicalInstance(xorig Type, xargs []Type, yorig Type, yargs []Type) bool {
439         if len(xargs) != len(yargs) {
440                 return false
441         }
442
443         for i, xa := range xargs {
444                 if !Identical(xa, yargs[i]) {
445                         return false
446                 }
447         }
448
449         return Identical(xorig, yorig)
450 }
451
452 // Default returns the default "typed" type for an "untyped" type;
453 // it returns the incoming type for all other types. The default type
454 // for untyped nil is untyped nil.
455 func Default(t Type) Type {
456         if t, ok := t.(*Basic); ok {
457                 switch t.kind {
458                 case UntypedBool:
459                         return Typ[Bool]
460                 case UntypedInt:
461                         return Typ[Int]
462                 case UntypedRune:
463                         return universeRune // use 'rune' name
464                 case UntypedFloat:
465                         return Typ[Float64]
466                 case UntypedComplex:
467                         return Typ[Complex128]
468                 case UntypedString:
469                         return Typ[String]
470                 }
471         }
472         return t
473 }