Skip to content

Commit

Permalink
interp: catch mismatched types for other comparisons
Browse files Browse the repository at this point in the history
The check for mismatched types was already added recently for ==  and != comparisons.
This PR now adds it for other comparisons ( < , <=, > , >=).
  • Loading branch information
mpl authored Jun 14, 2022
1 parent 236a0ef commit 996b1e3
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
14 changes: 13 additions & 1 deletion interp/interp_eval_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,7 @@ func TestEvalComparison(t *testing.T) {
{src: `a, b, c := 1, 1, false; if a == b { c = true }; c`, res: "true"},
{src: `a, b, c := 1, 2, false; if a != b { c = true }; c`, res: "true"},
{
desc: "mismatched types",
desc: "mismatched types equality",
src: `
type Foo string
type Bar string
Expand All @@ -451,6 +451,18 @@ func TestEvalComparison(t *testing.T) {
`,
err: "7:13: invalid operation: mismatched types main.Foo and main.Bar",
},
{
desc: "mismatched types less than",
src: `
type Foo string
type Bar string
var a = Foo("test")
var b = Bar("test")
var c = a < b
`,
err: "7:13: invalid operation: mismatched types main.Foo and main.Bar",
},
{src: `1 > _`, err: "1:28: cannot use _ as value"},
{src: `(_) > 1`, err: "1:28: cannot use _ as value"},
{src: `v := interface{}(2); v == 2`, res: "true"},
Expand Down
10 changes: 6 additions & 4 deletions interp/typecheck.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,12 +191,14 @@ func (check typecheck) comparison(n *node) error {
}

ok := false

if !isInterface(t0) && !isInterface(t1) && !t0.isNil() && !t1.isNil() && t0.untyped == t1.untyped && t0.id() != t1.id() {
// Non interface types must be really equals.
return n.cfgErrorf("invalid operation: mismatched types %s and %s", t0.id(), t1.id())
}

switch n.action {
case aEqual, aNotEqual:
if !isInterface(t0) && !isInterface(t1) && !t0.isNil() && !t1.isNil() && t0.untyped == t1.untyped && t0.id() != t1.id() {
// Non interface types must be really equals.
return n.cfgErrorf("invalid operation: mismatched types %s and %s", t0.id(), t1.id())
}
ok = t0.comparable() && t1.comparable() || t0.isNil() && t1.hasNil() || t1.isNil() && t0.hasNil()
case aLower, aLowerEqual, aGreater, aGreaterEqual:
ok = t0.ordered() && t1.ordered()
Expand Down

0 comments on commit 996b1e3

Please sign in to comment.