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