]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/predicates.go
go/types: spell out 'Type' in type parameter APIs
[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.TypeParams() != 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         if x == y {
144                 return true
145         }
146
147         switch x := x.(type) {
148         case *Basic:
149                 // Basic types are singletons except for the rune and byte
150                 // aliases, thus we cannot solely rely on the x == y check
151                 // above. See also comment in TypeName.IsAlias.
152                 if y, ok := y.(*Basic); ok {
153                         return x.kind == y.kind
154                 }
155
156         case *Array:
157                 // Two array types are identical if they have identical element types
158                 // and the same array length.
159                 if y, ok := y.(*Array); ok {
160                         // If one or both array lengths are unknown (< 0) due to some error,
161                         // assume they are the same to avoid spurious follow-on errors.
162                         return (x.len < 0 || y.len < 0 || x.len == y.len) && identical(x.elem, y.elem, cmpTags, p)
163                 }
164
165         case *Slice:
166                 // Two slice types are identical if they have identical element types.
167                 if y, ok := y.(*Slice); ok {
168                         return identical(x.elem, y.elem, cmpTags, p)
169                 }
170
171         case *Struct:
172                 // Two struct types are identical if they have the same sequence of fields,
173                 // and if corresponding fields have the same names, and identical types,
174                 // and identical tags. Two embedded fields are considered to have the same
175                 // name. Lower-case field names from different packages are always different.
176                 if y, ok := y.(*Struct); ok {
177                         if x.NumFields() == y.NumFields() {
178                                 for i, f := range x.fields {
179                                         g := y.fields[i]
180                                         if f.embedded != g.embedded ||
181                                                 cmpTags && x.Tag(i) != y.Tag(i) ||
182                                                 !f.sameId(g.pkg, g.name) ||
183                                                 !identical(f.typ, g.typ, cmpTags, p) {
184                                                 return false
185                                         }
186                                 }
187                                 return true
188                         }
189                 }
190
191         case *Pointer:
192                 // Two pointer types are identical if they have identical base types.
193                 if y, ok := y.(*Pointer); ok {
194                         return identical(x.base, y.base, cmpTags, p)
195                 }
196
197         case *Tuple:
198                 // Two tuples types are identical if they have the same number of elements
199                 // and corresponding elements have identical types.
200                 if y, ok := y.(*Tuple); ok {
201                         if x.Len() == y.Len() {
202                                 if x != nil {
203                                         for i, v := range x.vars {
204                                                 w := y.vars[i]
205                                                 if !identical(v.typ, w.typ, cmpTags, p) {
206                                                         return false
207                                                 }
208                                         }
209                                 }
210                                 return true
211                         }
212                 }
213
214         case *Signature:
215                 // Two function types are identical if they have the same number of parameters
216                 // and result values, corresponding parameter and result types are identical,
217                 // and either both functions are variadic or neither is. Parameter and result
218                 // names are not required to match.
219                 // Generic functions must also have matching type parameter lists, but for the
220                 // parameter names.
221                 if y, ok := y.(*Signature); ok {
222                         return x.variadic == y.variadic &&
223                                 identicalTParams(x.TypeParams().list(), y.TypeParams().list(), cmpTags, p) &&
224                                 identical(x.params, y.params, cmpTags, p) &&
225                                 identical(x.results, y.results, cmpTags, p)
226                 }
227
228         case *Interface:
229                 // Two interface types are identical if they describe the same type sets.
230                 // With the existing implementation restriction, this simplifies to:
231                 //
232                 // Two interface types are identical if they have the same set of methods with
233                 // the same names and identical function types, and if any type restrictions
234                 // are the same. Lower-case method names from different packages are always
235                 // different. The order of the methods is irrelevant.
236                 if y, ok := y.(*Interface); ok {
237                         xset := x.typeSet()
238                         yset := y.typeSet()
239                         if !xset.terms.equal(yset.terms) {
240                                 return false
241                         }
242                         a := xset.methods
243                         b := yset.methods
244                         if len(a) == len(b) {
245                                 // Interface types are the only types where cycles can occur
246                                 // that are not "terminated" via named types; and such cycles
247                                 // can only be created via method parameter types that are
248                                 // anonymous interfaces (directly or indirectly) embedding
249                                 // the current interface. Example:
250                                 //
251                                 //    type T interface {
252                                 //        m() interface{T}
253                                 //    }
254                                 //
255                                 // If two such (differently named) interfaces are compared,
256                                 // endless recursion occurs if the cycle is not detected.
257                                 //
258                                 // If x and y were compared before, they must be equal
259                                 // (if they were not, the recursion would have stopped);
260                                 // search the ifacePair stack for the same pair.
261                                 //
262                                 // This is a quadratic algorithm, but in practice these stacks
263                                 // are extremely short (bounded by the nesting depth of interface
264                                 // type declarations that recur via parameter types, an extremely
265                                 // rare occurrence). An alternative implementation might use a
266                                 // "visited" map, but that is probably less efficient overall.
267                                 q := &ifacePair{x, y, p}
268                                 for p != nil {
269                                         if p.identical(q) {
270                                                 return true // same pair was compared before
271                                         }
272                                         p = p.prev
273                                 }
274                                 if debug {
275                                         assertSortedMethods(a)
276                                         assertSortedMethods(b)
277                                 }
278                                 for i, f := range a {
279                                         g := b[i]
280                                         if f.Id() != g.Id() || !identical(f.typ, g.typ, cmpTags, q) {
281                                                 return false
282                                         }
283                                 }
284                                 return true
285                         }
286                 }
287
288         case *Map:
289                 // Two map types are identical if they have identical key and value types.
290                 if y, ok := y.(*Map); ok {
291                         return identical(x.key, y.key, cmpTags, p) && identical(x.elem, y.elem, cmpTags, p)
292                 }
293
294         case *Chan:
295                 // Two channel types are identical if they have identical value types
296                 // and the same direction.
297                 if y, ok := y.(*Chan); ok {
298                         return x.dir == y.dir && identical(x.elem, y.elem, cmpTags, p)
299                 }
300
301         case *Named:
302                 // Two named types are identical if their type names originate
303                 // in the same type declaration.
304                 if y, ok := y.(*Named); ok {
305                         x.expand(nil)
306                         y.expand(nil)
307
308                         xargs := x.TypeArgs().list()
309                         yargs := y.TypeArgs().list()
310
311                         if len(xargs) != len(yargs) {
312                                 return false
313                         }
314
315                         if len(xargs) > 0 {
316                                 // Instances are identical if their original type and type arguments
317                                 // are identical.
318                                 if !Identical(x.orig, y.orig) {
319                                         return false
320                                 }
321                                 for i, xa := range xargs {
322                                         if !Identical(xa, yargs[i]) {
323                                                 return false
324                                         }
325                                 }
326                                 return true
327                         }
328
329                         // TODO(gri) Why is x == y not sufficient? And if it is,
330                         //           we can just return false here because x == y
331                         //           is caught in the very beginning of this function.
332                         return x.obj == y.obj
333                 }
334
335         case *TypeParam:
336                 // nothing to do (x and y being equal is caught in the very beginning of this function)
337
338         case *top:
339                 // Either both types are theTop in which case the initial x == y check
340                 // will have caught them. Otherwise they are not identical.
341
342         case nil:
343                 // avoid a crash in case of nil type
344
345         default:
346                 unreachable()
347         }
348
349         return false
350 }
351
352 func identicalTParams(x, y []*TypeParam, cmpTags bool, p *ifacePair) bool {
353         if len(x) != len(y) {
354                 return false
355         }
356         for i, x := range x {
357                 y := y[i]
358                 if !identical(x.bound, y.bound, cmpTags, p) {
359                         return false
360                 }
361         }
362         return true
363 }
364
365 // Default returns the default "typed" type for an "untyped" type;
366 // it returns the incoming type for all other types. The default type
367 // for untyped nil is untyped nil.
368 //
369 func Default(typ Type) Type {
370         if t, ok := typ.(*Basic); ok {
371                 switch t.kind {
372                 case UntypedBool:
373                         return Typ[Bool]
374                 case UntypedInt:
375                         return Typ[Int]
376                 case UntypedRune:
377                         return universeRune // use 'rune' name
378                 case UntypedFloat:
379                         return Typ[Float64]
380                 case UntypedComplex:
381                         return Typ[Complex128]
382                 case UntypedString:
383                         return Typ[String]
384                 }
385         }
386         return typ
387 }