]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/predicates.go
go/types, types2: use a comparer struct to control the identical predicate
[gostls13.git] / src / go / types / predicates.go
1 // Code generated by "go test -run=Generate -write=all"; DO NOT EDIT.
2
3 // Copyright 2012 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
6
7 // This file implements commonly used type predicates.
8
9 package types
10
11 // The isX predicates below report whether t is an X.
12 // If t is a type parameter the result is false; i.e.,
13 // these predicates don't look inside a type parameter.
14
15 func isBoolean(t Type) bool        { return isBasic(t, IsBoolean) }
16 func isInteger(t Type) bool        { return isBasic(t, IsInteger) }
17 func isUnsigned(t Type) bool       { return isBasic(t, IsUnsigned) }
18 func isFloat(t Type) bool          { return isBasic(t, IsFloat) }
19 func isComplex(t Type) bool        { return isBasic(t, IsComplex) }
20 func isNumeric(t Type) bool        { return isBasic(t, IsNumeric) }
21 func isString(t Type) bool         { return isBasic(t, IsString) }
22 func isIntegerOrFloat(t Type) bool { return isBasic(t, IsInteger|IsFloat) }
23 func isConstType(t Type) bool      { return isBasic(t, IsConstType) }
24
25 // isBasic reports whether under(t) is a basic type with the specified info.
26 // If t is a type parameter the result is false; i.e.,
27 // isBasic does not look inside a type parameter.
28 func isBasic(t Type, info BasicInfo) bool {
29         u, _ := under(t).(*Basic)
30         return u != nil && u.info&info != 0
31 }
32
33 // The allX predicates below report whether t is an X.
34 // If t is a type parameter the result is true if isX is true
35 // for all specified types of the type parameter's type set.
36 // allX is an optimized version of isX(coreType(t)) (which
37 // is the same as underIs(t, isX)).
38
39 func allBoolean(t Type) bool         { return allBasic(t, IsBoolean) }
40 func allInteger(t Type) bool         { return allBasic(t, IsInteger) }
41 func allUnsigned(t Type) bool        { return allBasic(t, IsUnsigned) }
42 func allNumeric(t Type) bool         { return allBasic(t, IsNumeric) }
43 func allString(t Type) bool          { return allBasic(t, IsString) }
44 func allOrdered(t Type) bool         { return allBasic(t, IsOrdered) }
45 func allNumericOrString(t Type) bool { return allBasic(t, IsNumeric|IsString) }
46
47 // allBasic reports whether under(t) is a basic type with the specified info.
48 // If t is a type parameter, the result is true if isBasic(t, info) is true
49 // for all specific types of the type parameter's type set.
50 // allBasic(t, info) is an optimized version of isBasic(coreType(t), info).
51 func allBasic(t Type, info BasicInfo) bool {
52         if tpar, _ := t.(*TypeParam); tpar != nil {
53                 return tpar.is(func(t *term) bool { return t != nil && isBasic(t.typ, info) })
54         }
55         return isBasic(t, info)
56 }
57
58 // hasName reports whether t has a name. This includes
59 // predeclared types, defined types, and type parameters.
60 // hasName may be called with types that are not fully set up.
61 func hasName(t Type) bool {
62         switch t.(type) {
63         case *Basic, *Named, *TypeParam:
64                 return true
65         }
66         return false
67 }
68
69 // isTyped reports whether t is typed; i.e., not an untyped
70 // constant or boolean. isTyped may be called with types that
71 // are not fully set up.
72 func isTyped(t Type) bool {
73         // isTyped is called with types that are not fully
74         // set up. Must not call under()!
75         b, _ := t.(*Basic)
76         return b == nil || b.info&IsUntyped == 0
77 }
78
79 // isUntyped(t) is the same as !isTyped(t).
80 func isUntyped(t Type) bool {
81         return !isTyped(t)
82 }
83
84 // IsInterface reports whether t is an interface type.
85 func IsInterface(t Type) bool {
86         _, ok := under(t).(*Interface)
87         return ok
88 }
89
90 // isNonTypeParamInterface reports whether t is an interface type but not a type parameter.
91 func isNonTypeParamInterface(t Type) bool {
92         return !isTypeParam(t) && IsInterface(t)
93 }
94
95 // isTypeParam reports whether t is a type parameter.
96 func isTypeParam(t Type) bool {
97         _, ok := t.(*TypeParam)
98         return ok
99 }
100
101 // hasEmptyTypeset reports whether t is a type parameter with an empty type set.
102 // The function does not force the computation of the type set and so is safe to
103 // use anywhere, but it may report a false negative if the type set has not been
104 // computed yet.
105 func hasEmptyTypeset(t Type) bool {
106         if tpar, _ := t.(*TypeParam); tpar != nil && tpar.bound != nil {
107                 iface, _ := safeUnderlying(tpar.bound).(*Interface)
108                 return iface != nil && iface.tset != nil && iface.tset.IsEmpty()
109         }
110         return false
111 }
112
113 // isGeneric reports whether a type is a generic, uninstantiated type
114 // (generic signatures are not included).
115 // TODO(gri) should we include signatures or assert that they are not present?
116 func isGeneric(t Type) bool {
117         // A parameterized type is only generic if it doesn't have an instantiation already.
118         named, _ := t.(*Named)
119         return named != nil && named.obj != nil && named.inst == nil && named.TypeParams().Len() > 0
120 }
121
122 // Comparable reports whether values of type T are comparable.
123 func Comparable(T Type) bool {
124         return comparable(T, true, nil, nil)
125 }
126
127 // If dynamic is set, non-type parameter interfaces are always comparable.
128 // If reportf != nil, it may be used to report why T is not comparable.
129 func comparable(T Type, dynamic bool, seen map[Type]bool, reportf func(string, ...interface{})) bool {
130         if seen[T] {
131                 return true
132         }
133         if seen == nil {
134                 seen = make(map[Type]bool)
135         }
136         seen[T] = true
137
138         switch t := under(T).(type) {
139         case *Basic:
140                 // assume invalid types to be comparable
141                 // to avoid follow-up errors
142                 return t.kind != UntypedNil
143         case *Pointer, *Chan:
144                 return true
145         case *Struct:
146                 for _, f := range t.fields {
147                         if !comparable(f.typ, dynamic, seen, nil) {
148                                 if reportf != nil {
149                                         reportf("struct containing %s cannot be compared", f.typ)
150                                 }
151                                 return false
152                         }
153                 }
154                 return true
155         case *Array:
156                 if !comparable(t.elem, dynamic, seen, nil) {
157                         if reportf != nil {
158                                 reportf("%s cannot be compared", t)
159                         }
160                         return false
161                 }
162                 return true
163         case *Interface:
164                 if dynamic && !isTypeParam(T) || t.typeSet().IsComparable(seen) {
165                         return true
166                 }
167                 if reportf != nil {
168                         if t.typeSet().IsEmpty() {
169                                 reportf("empty type set")
170                         } else {
171                                 reportf("incomparable types in type set")
172                         }
173                 }
174                 // fallthrough
175         }
176         return false
177 }
178
179 // hasNil reports whether type t includes the nil value.
180 func hasNil(t Type) bool {
181         switch u := under(t).(type) {
182         case *Basic:
183                 return u.kind == UnsafePointer
184         case *Slice, *Pointer, *Signature, *Map, *Chan:
185                 return true
186         case *Interface:
187                 return !isTypeParam(t) || u.typeSet().underIs(func(u Type) bool {
188                         return u != nil && hasNil(u)
189                 })
190         }
191         return false
192 }
193
194 // An ifacePair is a node in a stack of interface type pairs compared for identity.
195 type ifacePair struct {
196         x, y *Interface
197         prev *ifacePair
198 }
199
200 func (p *ifacePair) identical(q *ifacePair) bool {
201         return p.x == q.x && p.y == q.y || p.x == q.y && p.y == q.x
202 }
203
204 // A comparer is used to compare types.
205 type comparer struct {
206         ignoreTags bool // if set, identical ignores struct tags
207 }
208
209 // For changes to this code the corresponding changes should be made to unifier.nify.
210 func (c *comparer) identical(x, y Type, p *ifacePair) bool {
211         if x == y {
212                 return true
213         }
214
215         switch x := x.(type) {
216         case *Basic:
217                 // Basic types are singletons except for the rune and byte
218                 // aliases, thus we cannot solely rely on the x == y check
219                 // above. See also comment in TypeName.IsAlias.
220                 if y, ok := y.(*Basic); ok {
221                         return x.kind == y.kind
222                 }
223
224         case *Array:
225                 // Two array types are identical if they have identical element types
226                 // and the same array length.
227                 if y, ok := y.(*Array); ok {
228                         // If one or both array lengths are unknown (< 0) due to some error,
229                         // assume they are the same to avoid spurious follow-on errors.
230                         return (x.len < 0 || y.len < 0 || x.len == y.len) && c.identical(x.elem, y.elem, p)
231                 }
232
233         case *Slice:
234                 // Two slice types are identical if they have identical element types.
235                 if y, ok := y.(*Slice); ok {
236                         return c.identical(x.elem, y.elem, p)
237                 }
238
239         case *Struct:
240                 // Two struct types are identical if they have the same sequence of fields,
241                 // and if corresponding fields have the same names, and identical types,
242                 // and identical tags. Two embedded fields are considered to have the same
243                 // name. Lower-case field names from different packages are always different.
244                 if y, ok := y.(*Struct); ok {
245                         if x.NumFields() == y.NumFields() {
246                                 for i, f := range x.fields {
247                                         g := y.fields[i]
248                                         if f.embedded != g.embedded ||
249                                                 !c.ignoreTags && x.Tag(i) != y.Tag(i) ||
250                                                 !f.sameId(g.pkg, g.name) ||
251                                                 !c.identical(f.typ, g.typ, p) {
252                                                 return false
253                                         }
254                                 }
255                                 return true
256                         }
257                 }
258
259         case *Pointer:
260                 // Two pointer types are identical if they have identical base types.
261                 if y, ok := y.(*Pointer); ok {
262                         return c.identical(x.base, y.base, p)
263                 }
264
265         case *Tuple:
266                 // Two tuples types are identical if they have the same number of elements
267                 // and corresponding elements have identical types.
268                 if y, ok := y.(*Tuple); ok {
269                         if x.Len() == y.Len() {
270                                 if x != nil {
271                                         for i, v := range x.vars {
272                                                 w := y.vars[i]
273                                                 if !c.identical(v.typ, w.typ, p) {
274                                                         return false
275                                                 }
276                                         }
277                                 }
278                                 return true
279                         }
280                 }
281
282         case *Signature:
283                 y, _ := y.(*Signature)
284                 if y == nil {
285                         return false
286                 }
287
288                 // Two function types are identical if they have the same number of
289                 // parameters and result values, corresponding parameter and result types
290                 // are identical, and either both functions are variadic or neither is.
291                 // Parameter and result names are not required to match, and type
292                 // parameters are considered identical modulo renaming.
293
294                 if x.TypeParams().Len() != y.TypeParams().Len() {
295                         return false
296                 }
297
298                 // In the case of generic signatures, we will substitute in yparams and
299                 // yresults.
300                 yparams := y.params
301                 yresults := y.results
302
303                 if x.TypeParams().Len() > 0 {
304                         // We must ignore type parameter names when comparing x and y. The
305                         // easiest way to do this is to substitute x's type parameters for y's.
306                         xtparams := x.TypeParams().list()
307                         ytparams := y.TypeParams().list()
308
309                         var targs []Type
310                         for i := range xtparams {
311                                 targs = append(targs, x.TypeParams().At(i))
312                         }
313                         smap := makeSubstMap(ytparams, targs)
314
315                         var check *Checker   // ok to call subst on a nil *Checker
316                         ctxt := NewContext() // need a non-nil Context for the substitution below
317
318                         // Constraints must be pair-wise identical, after substitution.
319                         for i, xtparam := range xtparams {
320                                 ybound := check.subst(nopos, ytparams[i].bound, smap, nil, ctxt)
321                                 if !c.identical(xtparam.bound, ybound, p) {
322                                         return false
323                                 }
324                         }
325
326                         yparams = check.subst(nopos, y.params, smap, nil, ctxt).(*Tuple)
327                         yresults = check.subst(nopos, y.results, smap, nil, ctxt).(*Tuple)
328                 }
329
330                 return x.variadic == y.variadic &&
331                         c.identical(x.params, yparams, p) &&
332                         c.identical(x.results, yresults, p)
333
334         case *Union:
335                 if y, _ := y.(*Union); y != nil {
336                         // TODO(rfindley): can this be reached during type checking? If so,
337                         // consider passing a type set map.
338                         unionSets := make(map[*Union]*_TypeSet)
339                         xset := computeUnionTypeSet(nil, unionSets, nopos, x)
340                         yset := computeUnionTypeSet(nil, unionSets, nopos, y)
341                         return xset.terms.equal(yset.terms)
342                 }
343
344         case *Interface:
345                 // Two interface types are identical if they describe the same type sets.
346                 // With the existing implementation restriction, this simplifies to:
347                 //
348                 // Two interface types are identical if they have the same set of methods with
349                 // the same names and identical function types, and if any type restrictions
350                 // are the same. Lower-case method names from different packages are always
351                 // different. The order of the methods is irrelevant.
352                 if y, ok := y.(*Interface); ok {
353                         xset := x.typeSet()
354                         yset := y.typeSet()
355                         if xset.comparable != yset.comparable {
356                                 return false
357                         }
358                         if !xset.terms.equal(yset.terms) {
359                                 return false
360                         }
361                         a := xset.methods
362                         b := yset.methods
363                         if len(a) == len(b) {
364                                 // Interface types are the only types where cycles can occur
365                                 // that are not "terminated" via named types; and such cycles
366                                 // can only be created via method parameter types that are
367                                 // anonymous interfaces (directly or indirectly) embedding
368                                 // the current interface. Example:
369                                 //
370                                 //    type T interface {
371                                 //        m() interface{T}
372                                 //    }
373                                 //
374                                 // If two such (differently named) interfaces are compared,
375                                 // endless recursion occurs if the cycle is not detected.
376                                 //
377                                 // If x and y were compared before, they must be equal
378                                 // (if they were not, the recursion would have stopped);
379                                 // search the ifacePair stack for the same pair.
380                                 //
381                                 // This is a quadratic algorithm, but in practice these stacks
382                                 // are extremely short (bounded by the nesting depth of interface
383                                 // type declarations that recur via parameter types, an extremely
384                                 // rare occurrence). An alternative implementation might use a
385                                 // "visited" map, but that is probably less efficient overall.
386                                 q := &ifacePair{x, y, p}
387                                 for p != nil {
388                                         if p.identical(q) {
389                                                 return true // same pair was compared before
390                                         }
391                                         p = p.prev
392                                 }
393                                 if debug {
394                                         assertSortedMethods(a)
395                                         assertSortedMethods(b)
396                                 }
397                                 for i, f := range a {
398                                         g := b[i]
399                                         if f.Id() != g.Id() || !c.identical(f.typ, g.typ, q) {
400                                                 return false
401                                         }
402                                 }
403                                 return true
404                         }
405                 }
406
407         case *Map:
408                 // Two map types are identical if they have identical key and value types.
409                 if y, ok := y.(*Map); ok {
410                         return c.identical(x.key, y.key, p) && c.identical(x.elem, y.elem, p)
411                 }
412
413         case *Chan:
414                 // Two channel types are identical if they have identical value types
415                 // and the same direction.
416                 if y, ok := y.(*Chan); ok {
417                         return x.dir == y.dir && c.identical(x.elem, y.elem, p)
418                 }
419
420         case *Named:
421                 // Two named types are identical if their type names originate
422                 // in the same type declaration.
423                 if y, ok := y.(*Named); ok {
424                         xargs := x.TypeArgs().list()
425                         yargs := y.TypeArgs().list()
426
427                         if len(xargs) != len(yargs) {
428                                 return false
429                         }
430
431                         if len(xargs) > 0 {
432                                 // Instances are identical if their original type and type arguments
433                                 // are identical.
434                                 if !Identical(x.Origin(), y.Origin()) {
435                                         return false
436                                 }
437                                 for i, xa := range xargs {
438                                         if !Identical(xa, yargs[i]) {
439                                                 return false
440                                         }
441                                 }
442                                 return true
443                         }
444
445                         // TODO(gri) Why is x == y not sufficient? And if it is,
446                         //           we can just return false here because x == y
447                         //           is caught in the very beginning of this function.
448                         return x.obj == y.obj
449                 }
450
451         case *TypeParam:
452                 // nothing to do (x and y being equal is caught in the very beginning of this function)
453
454         case nil:
455                 // avoid a crash in case of nil type
456
457         default:
458                 unreachable()
459         }
460
461         return false
462 }
463
464 // identicalInstance reports if two type instantiations are identical.
465 // Instantiations are identical if their origin and type arguments are
466 // identical.
467 func identicalInstance(xorig Type, xargs []Type, yorig Type, yargs []Type) bool {
468         if len(xargs) != len(yargs) {
469                 return false
470         }
471
472         for i, xa := range xargs {
473                 if !Identical(xa, yargs[i]) {
474                         return false
475                 }
476         }
477
478         return Identical(xorig, yorig)
479 }
480
481 // Default returns the default "typed" type for an "untyped" type;
482 // it returns the incoming type for all other types. The default type
483 // for untyped nil is untyped nil.
484 func Default(t Type) Type {
485         if t, ok := t.(*Basic); ok {
486                 switch t.kind {
487                 case UntypedBool:
488                         return Typ[Bool]
489                 case UntypedInt:
490                         return Typ[Int]
491                 case UntypedRune:
492                         return universeRune // use 'rune' name
493                 case UntypedFloat:
494                         return Typ[Float64]
495                 case UntypedComplex:
496                         return Typ[Complex128]
497                 case UntypedString:
498                         return Typ[String]
499                 }
500         }
501         return t
502 }