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