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