]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/predicates.go
go/types, types2: enable new type inference
[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         ignoreInvalids bool // if set, identical treats an invalid type as identical to any type
208 }
209
210 // For changes to this code the corresponding changes should be made to unifier.nify.
211 func (c *comparer) identical(x, y Type, p *ifacePair) bool {
212         if x == y {
213                 return true
214         }
215
216         if c.ignoreInvalids && (x == Typ[Invalid] || y == Typ[Invalid]) {
217                 return true
218         }
219
220         switch x := x.(type) {
221         case *Basic:
222                 // Basic types are singletons except for the rune and byte
223                 // aliases, thus we cannot solely rely on the x == y check
224                 // above. See also comment in TypeName.IsAlias.
225                 if y, ok := y.(*Basic); ok {
226                         return x.kind == y.kind
227                 }
228
229         case *Array:
230                 // Two array types are identical if they have identical element types
231                 // and the same array length.
232                 if y, ok := y.(*Array); ok {
233                         // If one or both array lengths are unknown (< 0) due to some error,
234                         // assume they are the same to avoid spurious follow-on errors.
235                         return (x.len < 0 || y.len < 0 || x.len == y.len) && c.identical(x.elem, y.elem, p)
236                 }
237
238         case *Slice:
239                 // Two slice types are identical if they have identical element types.
240                 if y, ok := y.(*Slice); ok {
241                         return c.identical(x.elem, y.elem, p)
242                 }
243
244         case *Struct:
245                 // Two struct types are identical if they have the same sequence of fields,
246                 // and if corresponding fields have the same names, and identical types,
247                 // and identical tags. Two embedded fields are considered to have the same
248                 // name. Lower-case field names from different packages are always different.
249                 if y, ok := y.(*Struct); ok {
250                         if x.NumFields() == y.NumFields() {
251                                 for i, f := range x.fields {
252                                         g := y.fields[i]
253                                         if f.embedded != g.embedded ||
254                                                 !c.ignoreTags && x.Tag(i) != y.Tag(i) ||
255                                                 !f.sameId(g.pkg, g.name) ||
256                                                 !c.identical(f.typ, g.typ, p) {
257                                                 return false
258                                         }
259                                 }
260                                 return true
261                         }
262                 }
263
264         case *Pointer:
265                 // Two pointer types are identical if they have identical base types.
266                 if y, ok := y.(*Pointer); ok {
267                         return c.identical(x.base, y.base, p)
268                 }
269
270         case *Tuple:
271                 // Two tuples types are identical if they have the same number of elements
272                 // and corresponding elements have identical types.
273                 if y, ok := y.(*Tuple); ok {
274                         if x.Len() == y.Len() {
275                                 if x != nil {
276                                         for i, v := range x.vars {
277                                                 w := y.vars[i]
278                                                 if !c.identical(v.typ, w.typ, p) {
279                                                         return false
280                                                 }
281                                         }
282                                 }
283                                 return true
284                         }
285                 }
286
287         case *Signature:
288                 y, _ := y.(*Signature)
289                 if y == nil {
290                         return false
291                 }
292
293                 // Two function types are identical if they have the same number of
294                 // parameters and result values, corresponding parameter and result types
295                 // are identical, and either both functions are variadic or neither is.
296                 // Parameter and result names are not required to match, and type
297                 // parameters are considered identical modulo renaming.
298
299                 if x.TypeParams().Len() != y.TypeParams().Len() {
300                         return false
301                 }
302
303                 // In the case of generic signatures, we will substitute in yparams and
304                 // yresults.
305                 yparams := y.params
306                 yresults := y.results
307
308                 if x.TypeParams().Len() > 0 {
309                         // We must ignore type parameter names when comparing x and y. The
310                         // easiest way to do this is to substitute x's type parameters for y's.
311                         xtparams := x.TypeParams().list()
312                         ytparams := y.TypeParams().list()
313
314                         var targs []Type
315                         for i := range xtparams {
316                                 targs = append(targs, x.TypeParams().At(i))
317                         }
318                         smap := makeSubstMap(ytparams, targs)
319
320                         var check *Checker   // ok to call subst on a nil *Checker
321                         ctxt := NewContext() // need a non-nil Context for the substitution below
322
323                         // Constraints must be pair-wise identical, after substitution.
324                         for i, xtparam := range xtparams {
325                                 ybound := check.subst(nopos, ytparams[i].bound, smap, nil, ctxt)
326                                 if !c.identical(xtparam.bound, ybound, p) {
327                                         return false
328                                 }
329                         }
330
331                         yparams = check.subst(nopos, y.params, smap, nil, ctxt).(*Tuple)
332                         yresults = check.subst(nopos, y.results, smap, nil, ctxt).(*Tuple)
333                 }
334
335                 return x.variadic == y.variadic &&
336                         c.identical(x.params, yparams, p) &&
337                         c.identical(x.results, yresults, p)
338
339         case *Union:
340                 if y, _ := y.(*Union); y != nil {
341                         // TODO(rfindley): can this be reached during type checking? If so,
342                         // consider passing a type set map.
343                         unionSets := make(map[*Union]*_TypeSet)
344                         xset := computeUnionTypeSet(nil, unionSets, nopos, x)
345                         yset := computeUnionTypeSet(nil, unionSets, nopos, y)
346                         return xset.terms.equal(yset.terms)
347                 }
348
349         case *Interface:
350                 // Two interface types are identical if they describe the same type sets.
351                 // With the existing implementation restriction, this simplifies to:
352                 //
353                 // Two interface types are identical if they have the same set of methods with
354                 // the same names and identical function types, and if any type restrictions
355                 // are the same. Lower-case method names from different packages are always
356                 // different. The order of the methods is irrelevant.
357                 if y, ok := y.(*Interface); ok {
358                         xset := x.typeSet()
359                         yset := y.typeSet()
360                         if xset.comparable != yset.comparable {
361                                 return false
362                         }
363                         if !xset.terms.equal(yset.terms) {
364                                 return false
365                         }
366                         a := xset.methods
367                         b := yset.methods
368                         if len(a) == len(b) {
369                                 // Interface types are the only types where cycles can occur
370                                 // that are not "terminated" via named types; and such cycles
371                                 // can only be created via method parameter types that are
372                                 // anonymous interfaces (directly or indirectly) embedding
373                                 // the current interface. Example:
374                                 //
375                                 //    type T interface {
376                                 //        m() interface{T}
377                                 //    }
378                                 //
379                                 // If two such (differently named) interfaces are compared,
380                                 // endless recursion occurs if the cycle is not detected.
381                                 //
382                                 // If x and y were compared before, they must be equal
383                                 // (if they were not, the recursion would have stopped);
384                                 // search the ifacePair stack for the same pair.
385                                 //
386                                 // This is a quadratic algorithm, but in practice these stacks
387                                 // are extremely short (bounded by the nesting depth of interface
388                                 // type declarations that recur via parameter types, an extremely
389                                 // rare occurrence). An alternative implementation might use a
390                                 // "visited" map, but that is probably less efficient overall.
391                                 q := &ifacePair{x, y, p}
392                                 for p != nil {
393                                         if p.identical(q) {
394                                                 return true // same pair was compared before
395                                         }
396                                         p = p.prev
397                                 }
398                                 if debug {
399                                         assertSortedMethods(a)
400                                         assertSortedMethods(b)
401                                 }
402                                 for i, f := range a {
403                                         g := b[i]
404                                         if f.Id() != g.Id() || !c.identical(f.typ, g.typ, q) {
405                                                 return false
406                                         }
407                                 }
408                                 return true
409                         }
410                 }
411
412         case *Map:
413                 // Two map types are identical if they have identical key and value types.
414                 if y, ok := y.(*Map); ok {
415                         return c.identical(x.key, y.key, p) && c.identical(x.elem, y.elem, p)
416                 }
417
418         case *Chan:
419                 // Two channel types are identical if they have identical value types
420                 // and the same direction.
421                 if y, ok := y.(*Chan); ok {
422                         return x.dir == y.dir && c.identical(x.elem, y.elem, p)
423                 }
424
425         case *Named:
426                 // Two named types are identical if their type names originate
427                 // in the same type declaration.
428                 if y, ok := y.(*Named); ok {
429                         xargs := x.TypeArgs().list()
430                         yargs := y.TypeArgs().list()
431
432                         if len(xargs) != len(yargs) {
433                                 return false
434                         }
435
436                         if len(xargs) > 0 {
437                                 // Instances are identical if their original type and type arguments
438                                 // are identical.
439                                 if !Identical(x.Origin(), y.Origin()) {
440                                         return false
441                                 }
442                                 for i, xa := range xargs {
443                                         if !Identical(xa, yargs[i]) {
444                                                 return false
445                                         }
446                                 }
447                                 return true
448                         }
449
450                         // TODO(gri) Why is x == y not sufficient? And if it is,
451                         //           we can just return false here because x == y
452                         //           is caught in the very beginning of this function.
453                         return x.obj == y.obj
454                 }
455
456         case *TypeParam:
457                 // nothing to do (x and y being equal is caught in the very beginning of this function)
458
459         case nil:
460                 // avoid a crash in case of nil type
461
462         default:
463                 unreachable()
464         }
465
466         return false
467 }
468
469 // identicalInstance reports if two type instantiations are identical.
470 // Instantiations are identical if their origin and type arguments are
471 // identical.
472 func identicalInstance(xorig Type, xargs []Type, yorig Type, yargs []Type) bool {
473         if len(xargs) != len(yargs) {
474                 return false
475         }
476
477         for i, xa := range xargs {
478                 if !Identical(xa, yargs[i]) {
479                         return false
480                 }
481         }
482
483         return Identical(xorig, yorig)
484 }
485
486 // Default returns the default "typed" type for an "untyped" type;
487 // it returns the incoming type for all other types. The default type
488 // for untyped nil is untyped nil.
489 func Default(t Type) Type {
490         if t, ok := t.(*Basic); ok {
491                 switch t.kind {
492                 case UntypedBool:
493                         return Typ[Bool]
494                 case UntypedInt:
495                         return Typ[Int]
496                 case UntypedRune:
497                         return universeRune // use 'rune' name
498                 case UntypedFloat:
499                         return Typ[Float64]
500                 case UntypedComplex:
501                         return Typ[Complex128]
502                 case UntypedString:
503                         return Typ[String]
504                 }
505         }
506         return t
507 }