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