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