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