]> Cypherpunks.ru repositories - gostls13.git/blobdiff - src/cmd/compile/internal/types2/predicates.go
go/types, types2: introduce _Alias type node
[gostls13.git] / src / cmd / compile / internal / types2 / predicates.go
index 7fbb91eb61256495fc20903937b41a4fb7c417fa..9ec7d58d6fbab69a18fbf509e0fff95b867dfecf 100644 (file)
@@ -6,6 +6,9 @@
 
 package types2
 
+// isValid reports whether t is a valid type.
+func isValid(t Type) bool { return _Unalias(t) != Typ[Invalid] }
+
 // The isX predicates below report whether t is an X.
 // If t is a type parameter the result is false; i.e.,
 // these predicates don't look inside a type parameter.
@@ -31,7 +34,7 @@ func isBasic(t Type, info BasicInfo) bool {
 // The allX predicates below report whether t is an X.
 // If t is a type parameter the result is true if isX is true
 // for all specified types of the type parameter's type set.
-// allX is an optimized version of isX(structure(t)) (which
+// allX is an optimized version of isX(coreType(t)) (which
 // is the same as underIs(t, isX)).
 
 func allBoolean(t Type) bool         { return allBasic(t, IsBoolean) }
@@ -45,34 +48,44 @@ func allNumericOrString(t Type) bool { return allBasic(t, IsNumeric|IsString) }
 // allBasic reports whether under(t) is a basic type with the specified info.
 // If t is a type parameter, the result is true if isBasic(t, info) is true
 // for all specific types of the type parameter's type set.
-// allBasic(t, info) is an optimized version of isBasic(structure(t), info).
+// allBasic(t, info) is an optimized version of isBasic(coreType(t), info).
 func allBasic(t Type, info BasicInfo) bool {
-       switch u := under(t).(type) {
-       case *Basic:
-               return u.info&info != 0
-       case *TypeParam:
-               return u.is(func(t *term) bool { return t != nil && isBasic(t.typ, info) })
+       if tpar, _ := _Unalias(t).(*TypeParam); tpar != nil {
+               return tpar.is(func(t *term) bool { return t != nil && isBasic(t.typ, info) })
        }
-       return false
+       return isBasic(t, info)
 }
 
 // hasName reports whether t has a name. This includes
 // predeclared types, defined types, and type parameters.
 // hasName may be called with types that are not fully set up.
 func hasName(t Type) bool {
-       switch t.(type) {
+       switch _Unalias(t).(type) {
        case *Basic, *Named, *TypeParam:
                return true
        }
        return false
 }
 
+// isTypeLit reports whether t is a type literal.
+// This includes all non-defined types, but also basic types.
+// isTypeLit may be called with types that are not fully set up.
+func isTypeLit(t Type) bool {
+       switch _Unalias(t).(type) {
+       case *Named, *TypeParam:
+               return false
+       }
+       return true
+}
+
 // isTyped reports whether t is typed; i.e., not an untyped
 // constant or boolean. isTyped may be called with types that
 // are not fully set up.
 func isTyped(t Type) bool {
-       // isTyped is called with types that are not fully
-       // set up. Must not call asBasic()!
+       // Alias or Named types cannot denote untyped types,
+       // thus we don't need to call _Unalias or under
+       // (which would be unsafe to do for types that are
+       // not fully set up).
        b, _ := t.(*Basic)
        return b == nil || b.info&IsUntyped == 0
 }
@@ -84,30 +97,50 @@ func isUntyped(t Type) bool {
 
 // IsInterface reports whether t is an interface type.
 func IsInterface(t Type) bool {
-       return asInterface(t) != nil
+       _, ok := under(t).(*Interface)
+       return ok
+}
+
+// isNonTypeParamInterface reports whether t is an interface type but not a type parameter.
+func isNonTypeParamInterface(t Type) bool {
+       return !isTypeParam(t) && IsInterface(t)
 }
 
 // isTypeParam reports whether t is a type parameter.
 func isTypeParam(t Type) bool {
-       _, ok := under(t).(*TypeParam)
+       _, ok := _Unalias(t).(*TypeParam)
        return ok
 }
 
+// hasEmptyTypeset reports whether t is a type parameter with an empty type set.
+// The function does not force the computation of the type set and so is safe to
+// use anywhere, but it may report a false negative if the type set has not been
+// computed yet.
+func hasEmptyTypeset(t Type) bool {
+       if tpar, _ := _Unalias(t).(*TypeParam); tpar != nil && tpar.bound != nil {
+               iface, _ := safeUnderlying(tpar.bound).(*Interface)
+               return iface != nil && iface.tset != nil && iface.tset.IsEmpty()
+       }
+       return false
+}
+
 // isGeneric reports whether a type is a generic, uninstantiated type
 // (generic signatures are not included).
 // TODO(gri) should we include signatures or assert that they are not present?
 func isGeneric(t Type) bool {
        // A parameterized type is only generic if it doesn't have an instantiation already.
-       named, _ := t.(*Named)
-       return named != nil && named.obj != nil && named.targs == nil && named.TypeParams() != nil
+       named := asNamed(t)
+       return named != nil && named.obj != nil && named.inst == nil && named.TypeParams().Len() > 0
 }
 
 // Comparable reports whether values of type T are comparable.
 func Comparable(T Type) bool {
-       return comparable(T, nil)
+       return comparable(T, true, nil, nil)
 }
 
-func comparable(T Type, seen map[Type]bool) bool {
+// If dynamic is set, non-type parameter interfaces are always comparable.
+// If reportf != nil, it may be used to report why T is not comparable.
+func comparable(T Type, dynamic bool, seen map[Type]bool, reportf func(string, ...interface{})) bool {
        if seen[T] {
                return true
        }
@@ -121,19 +154,38 @@ func comparable(T Type, seen map[Type]bool) bool {
                // assume invalid types to be comparable
                // to avoid follow-up errors
                return t.kind != UntypedNil
-       case *Pointer, *Interface, *Chan:
+       case *Pointer, *Chan:
                return true
        case *Struct:
                for _, f := range t.fields {
-                       if !comparable(f.typ, seen) {
+                       if !comparable(f.typ, dynamic, seen, nil) {
+                               if reportf != nil {
+                                       reportf("struct containing %s cannot be compared", f.typ)
+                               }
                                return false
                        }
                }
                return true
        case *Array:
-               return comparable(t.elem, seen)
-       case *TypeParam:
-               return t.iface().IsComparable()
+               if !comparable(t.elem, dynamic, seen, nil) {
+                       if reportf != nil {
+                               reportf("%s cannot be compared", t)
+                       }
+                       return false
+               }
+               return true
+       case *Interface:
+               if dynamic && !isTypeParam(T) || t.typeSet().IsComparable(seen) {
+                       return true
+               }
+               if reportf != nil {
+                       if t.typeSet().IsEmpty() {
+                               reportf("empty type set")
+                       } else {
+                               reportf("incomparable types in type set")
+                       }
+               }
+               // fallthrough
        }
        return false
 }
@@ -143,10 +195,12 @@ func hasNil(t Type) bool {
        switch u := under(t).(type) {
        case *Basic:
                return u.kind == UnsafePointer
-       case *Slice, *Pointer, *Signature, *Interface, *Map, *Chan:
+       case *Slice, *Pointer, *Signature, *Map, *Chan:
                return true
-       case *TypeParam:
-               return u.underIs(hasNil)
+       case *Interface:
+               return !isTypeParam(t) || u.typeSet().underIs(func(u Type) bool {
+                       return u != nil && hasNil(u)
+               })
        }
        return false
 }
@@ -161,12 +215,25 @@ func (p *ifacePair) identical(q *ifacePair) bool {
        return p.x == q.x && p.y == q.y || p.x == q.y && p.y == q.x
 }
 
+// A comparer is used to compare types.
+type comparer struct {
+       ignoreTags     bool // if set, identical ignores struct tags
+       ignoreInvalids bool // if set, identical treats an invalid type as identical to any type
+}
+
 // For changes to this code the corresponding changes should be made to unifier.nify.
-func identical(x, y Type, cmpTags bool, p *ifacePair) bool {
+func (c *comparer) identical(x, y Type, p *ifacePair) bool {
+       x = _Unalias(x)
+       y = _Unalias(y)
+
        if x == y {
                return true
        }
 
+       if c.ignoreInvalids && (!isValid(x) || !isValid(y)) {
+               return true
+       }
+
        switch x := x.(type) {
        case *Basic:
                // Basic types are singletons except for the rune and byte
@@ -182,13 +249,13 @@ func identical(x, y Type, cmpTags bool, p *ifacePair) bool {
                if y, ok := y.(*Array); ok {
                        // If one or both array lengths are unknown (< 0) due to some error,
                        // assume they are the same to avoid spurious follow-on errors.
-                       return (x.len < 0 || y.len < 0 || x.len == y.len) && identical(x.elem, y.elem, cmpTags, p)
+                       return (x.len < 0 || y.len < 0 || x.len == y.len) && c.identical(x.elem, y.elem, p)
                }
 
        case *Slice:
                // Two slice types are identical if they have identical element types.
                if y, ok := y.(*Slice); ok {
-                       return identical(x.elem, y.elem, cmpTags, p)
+                       return c.identical(x.elem, y.elem, p)
                }
 
        case *Struct:
@@ -201,9 +268,9 @@ func identical(x, y Type, cmpTags bool, p *ifacePair) bool {
                                for i, f := range x.fields {
                                        g := y.fields[i]
                                        if f.embedded != g.embedded ||
-                                               cmpTags && x.Tag(i) != y.Tag(i) ||
+                                               !c.ignoreTags && x.Tag(i) != y.Tag(i) ||
                                                !f.sameId(g.pkg, g.name) ||
-                                               !identical(f.typ, g.typ, cmpTags, p) {
+                                               !c.identical(f.typ, g.typ, p) {
                                                return false
                                        }
                                }
@@ -214,7 +281,7 @@ func identical(x, y Type, cmpTags bool, p *ifacePair) bool {
        case *Pointer:
                // Two pointer types are identical if they have identical base types.
                if y, ok := y.(*Pointer); ok {
-                       return identical(x.base, y.base, cmpTags, p)
+                       return c.identical(x.base, y.base, p)
                }
 
        case *Tuple:
@@ -225,7 +292,7 @@ func identical(x, y Type, cmpTags bool, p *ifacePair) bool {
                                if x != nil {
                                        for i, v := range x.vars {
                                                w := y.vars[i]
-                                               if !identical(v.typ, w.typ, cmpTags, p) {
+                                               if !c.identical(v.typ, w.typ, p) {
                                                        return false
                                                }
                                        }
@@ -235,23 +302,64 @@ func identical(x, y Type, cmpTags bool, p *ifacePair) bool {
                }
 
        case *Signature:
-               // Two function types are identical if they have the same number of parameters
-               // and result values, corresponding parameter and result types are identical,
-               // and either both functions are variadic or neither is. Parameter and result
-               // names are not required to match.
-               // Generic functions must also have matching type parameter lists, but for the
-               // parameter names.
-               if y, ok := y.(*Signature); ok {
-                       return x.variadic == y.variadic &&
-                               identicalTParams(x.TypeParams().list(), y.TypeParams().list(), cmpTags, p) &&
-                               identical(x.params, y.params, cmpTags, p) &&
-                               identical(x.results, y.results, cmpTags, p)
+               y, _ := y.(*Signature)
+               if y == nil {
+                       return false
+               }
+
+               // Two function types are identical if they have the same number of
+               // parameters and result values, corresponding parameter and result types
+               // are identical, and either both functions are variadic or neither is.
+               // Parameter and result names are not required to match, and type
+               // parameters are considered identical modulo renaming.
+
+               if x.TypeParams().Len() != y.TypeParams().Len() {
+                       return false
                }
 
+               // In the case of generic signatures, we will substitute in yparams and
+               // yresults.
+               yparams := y.params
+               yresults := y.results
+
+               if x.TypeParams().Len() > 0 {
+                       // We must ignore type parameter names when comparing x and y. The
+                       // easiest way to do this is to substitute x's type parameters for y's.
+                       xtparams := x.TypeParams().list()
+                       ytparams := y.TypeParams().list()
+
+                       var targs []Type
+                       for i := range xtparams {
+                               targs = append(targs, x.TypeParams().At(i))
+                       }
+                       smap := makeSubstMap(ytparams, targs)
+
+                       var check *Checker   // ok to call subst on a nil *Checker
+                       ctxt := NewContext() // need a non-nil Context for the substitution below
+
+                       // Constraints must be pair-wise identical, after substitution.
+                       for i, xtparam := range xtparams {
+                               ybound := check.subst(nopos, ytparams[i].bound, smap, nil, ctxt)
+                               if !c.identical(xtparam.bound, ybound, p) {
+                                       return false
+                               }
+                       }
+
+                       yparams = check.subst(nopos, y.params, smap, nil, ctxt).(*Tuple)
+                       yresults = check.subst(nopos, y.results, smap, nil, ctxt).(*Tuple)
+               }
+
+               return x.variadic == y.variadic &&
+                       c.identical(x.params, yparams, p) &&
+                       c.identical(x.results, yresults, p)
+
        case *Union:
                if y, _ := y.(*Union); y != nil {
-                       xset := computeUnionTypeSet(nil, nopos, x)
-                       yset := computeUnionTypeSet(nil, nopos, y)
+                       // TODO(rfindley): can this be reached during type checking? If so,
+                       // consider passing a type set map.
+                       unionSets := make(map[*Union]*_TypeSet)
+                       xset := computeUnionTypeSet(nil, unionSets, nopos, x)
+                       yset := computeUnionTypeSet(nil, unionSets, nopos, y)
                        return xset.terms.equal(yset.terms)
                }
 
@@ -266,6 +374,9 @@ func identical(x, y Type, cmpTags bool, p *ifacePair) bool {
                if y, ok := y.(*Interface); ok {
                        xset := x.typeSet()
                        yset := y.typeSet()
+                       if xset.comparable != yset.comparable {
+                               return false
+                       }
                        if !xset.terms.equal(yset.terms) {
                                return false
                        }
@@ -307,7 +418,7 @@ func identical(x, y Type, cmpTags bool, p *ifacePair) bool {
                                }
                                for i, f := range a {
                                        g := b[i]
-                                       if f.Id() != g.Id() || !identical(f.typ, g.typ, cmpTags, q) {
+                                       if f.Id() != g.Id() || !c.identical(f.typ, g.typ, q) {
                                                return false
                                        }
                                }
@@ -318,45 +429,35 @@ func identical(x, y Type, cmpTags bool, p *ifacePair) bool {
        case *Map:
                // Two map types are identical if they have identical key and value types.
                if y, ok := y.(*Map); ok {
-                       return identical(x.key, y.key, cmpTags, p) && identical(x.elem, y.elem, cmpTags, p)
+                       return c.identical(x.key, y.key, p) && c.identical(x.elem, y.elem, p)
                }
 
        case *Chan:
                // Two channel types are identical if they have identical value types
                // and the same direction.
                if y, ok := y.(*Chan); ok {
-                       return x.dir == y.dir && identical(x.elem, y.elem, cmpTags, p)
+                       return x.dir == y.dir && c.identical(x.elem, y.elem, p)
                }
 
        case *Named:
                // Two named types are identical if their type names originate
-               // in the same type declaration.
-               if y, ok := y.(*Named); ok {
+               // in the same type declaration; if they are instantiated they
+               // must have identical type argument lists.
+               if y := asNamed(y); y != nil {
+                       // check type arguments before origins to match unifier
+                       // (for correct source code we need to do all checks so
+                       // order doesn't matter)
                        xargs := x.TypeArgs().list()
                        yargs := y.TypeArgs().list()
-
                        if len(xargs) != len(yargs) {
                                return false
                        }
-
-                       if len(xargs) > 0 {
-                               // Instances are identical if their original type and type arguments
-                               // are identical.
-                               if !Identical(x.orig, y.orig) {
+                       for i, xarg := range xargs {
+                               if !Identical(xarg, yargs[i]) {
                                        return false
                                }
-                               for i, xa := range xargs {
-                                       if !Identical(xa, yargs[i]) {
-                                               return false
-                                       }
-                               }
-                               return true
                        }
-
-                       // TODO(gri) Why is x == y not sufficient? And if it is,
-                       //           we can just return false here because x == y
-                       //           is caught in the very beginning of this function.
-                       return x.obj == y.obj
+                       return identicalOrigin(x, y)
                }
 
        case *TypeParam:
@@ -372,24 +473,34 @@ func identical(x, y Type, cmpTags bool, p *ifacePair) bool {
        return false
 }
 
-func identicalTParams(x, y []*TypeParam, cmpTags bool, p *ifacePair) bool {
-       if len(x) != len(y) {
+// identicalOrigin reports whether x and y originated in the same declaration.
+func identicalOrigin(x, y *Named) bool {
+       // TODO(gri) is this correct?
+       return x.Origin().obj == y.Origin().obj
+}
+
+// identicalInstance reports if two type instantiations are identical.
+// Instantiations are identical if their origin and type arguments are
+// identical.
+func identicalInstance(xorig Type, xargs []Type, yorig Type, yargs []Type) bool {
+       if len(xargs) != len(yargs) {
                return false
        }
-       for i, x := range x {
-               y := y[i]
-               if !identical(x.bound, y.bound, cmpTags, p) {
+
+       for i, xa := range xargs {
+               if !Identical(xa, yargs[i]) {
                        return false
                }
        }
-       return true
+
+       return Identical(xorig, yorig)
 }
 
 // Default returns the default "typed" type for an "untyped" type;
 // it returns the incoming type for all other types. The default type
 // for untyped nil is untyped nil.
 func Default(t Type) Type {
-       if t, ok := t.(*Basic); ok {
+       if t, ok := _Unalias(t).(*Basic); ok {
                switch t.kind {
                case UntypedBool:
                        return Typ[Bool]
@@ -407,3 +518,29 @@ func Default(t Type) Type {
        }
        return t
 }
+
+// maxType returns the "largest" type that encompasses both x and y.
+// If x and y are different untyped numeric types, the result is the type of x or y
+// that appears later in this list: integer, rune, floating-point, complex.
+// Otherwise, if x != y, the result is nil.
+func maxType(x, y Type) Type {
+       // We only care about untyped types (for now), so == is good enough.
+       // TODO(gri) investigate generalizing this function to simplify code elsewhere
+       if x == y {
+               return x
+       }
+       if isUntyped(x) && isUntyped(y) && isNumeric(x) && isNumeric(y) {
+               // untyped types are basic types
+               if x.(*Basic).kind > y.(*Basic).kind {
+                       return x
+               }
+               return y
+       }
+       return nil
+}
+
+// clone makes a "flat copy" of *p and returns a pointer to the copy.
+func clone[P *T, T any](p P) P {
+       c := *p
+       return &c
+}