if x.mode == invalid || isTyped(x.typ) || target == Typ[Invalid] {
return x.typ, nil, 0
}
+ // x is untyped
if isUntyped(target) {
// both x and target are untyped
- xkind := x.typ.(*Basic).kind
- tkind := target.(*Basic).kind
- if isNumeric(x.typ) && isNumeric(target) {
- if xkind < tkind {
- return target, nil, 0
- }
- } else if xkind != tkind {
- return nil, nil, InvalidUntypedConversion
+ if m := maxType(x.typ, target); m != nil {
+ return m, nil, 0
}
- return x.typ, nil, 0
+ return nil, nil, InvalidUntypedConversion
}
if x.isNil() {
}
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
+}
if x.mode == invalid || isTyped(x.typ) || target == Typ[Invalid] {
return x.typ, nil, 0
}
+ // x is untyped
if isUntyped(target) {
// both x and target are untyped
- xkind := x.typ.(*Basic).kind
- tkind := target.(*Basic).kind
- if isNumeric(x.typ) && isNumeric(target) {
- if xkind < tkind {
- return target, nil, 0
- }
- } else if xkind != tkind {
- return nil, nil, InvalidUntypedConversion
+ if m := maxType(x.typ, target); m != nil {
+ return m, nil, 0
}
- return x.typ, nil, 0
+ return nil, nil, InvalidUntypedConversion
}
switch u := under(target).(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
+}