From 996b1e33c8a1c308d343b8447dba6dceaa6cac60 Mon Sep 17 00:00:00 2001 From: mpl Date: Tue, 14 Jun 2022 10:52:08 +0200 Subject: [PATCH] interp: catch mismatched types for other comparisons The check for mismatched types was already added recently for == and != comparisons. This PR now adds it for other comparisons ( < , <=, > , >=). --- interp/interp_eval_test.go | 14 +++++++++++++- interp/typecheck.go | 10 ++++++---- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/interp/interp_eval_test.go b/interp/interp_eval_test.go index fa5b9e36f..22968b9a7 100644 --- a/interp/interp_eval_test.go +++ b/interp/interp_eval_test.go @@ -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 @@ -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"}, diff --git a/interp/typecheck.go b/interp/typecheck.go index 0c7b725a9..4a5c85350 100644 --- a/interp/typecheck.go +++ b/interp/typecheck.go @@ -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()