Skip to content

Commit

Permalink
fix: make deref commutative
Browse files Browse the repository at this point in the history
Fixes #490
  • Loading branch information
antonmedv committed Dec 10, 2023
1 parent 9ba5094 commit 515f38b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
4 changes: 2 additions & 2 deletions compiler/compiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ func (c *compiler) BinaryNode(node *ast.BinaryNode) {
c.compile(node.Left)
c.derefInNeeded(node.Left)
c.compile(node.Right)
c.derefInNeeded(node.Left)
c.derefInNeeded(node.Right)

if l == r && l == reflect.Int && leftAndRightAreSimple {
c.emit(OpEqualInt)
Expand All @@ -382,7 +382,7 @@ func (c *compiler) BinaryNode(node *ast.BinaryNode) {
c.compile(node.Left)
c.derefInNeeded(node.Left)
c.compile(node.Right)
c.derefInNeeded(node.Left)
c.derefInNeeded(node.Right)
c.emit(OpEqual)
c.emit(OpNot)

Expand Down
39 changes: 38 additions & 1 deletion test/deref/deref_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import (
"context"
"testing"

"github.com/expr-lang/expr"
"github.com/stretchr/testify/require"

"github.com/expr-lang/expr"
)

func TestDeref_binary(t *testing.T) {
Expand Down Expand Up @@ -200,3 +201,39 @@ func TestDeref_nil_in_pointer_of_interface(t *testing.T) {
require.Equal(t, true, output)
})
}

func TestDeref_сommutative(t *testing.T) {
a := "ok"
b := "ok"

type Env struct {
A string
B *string
}

env := Env{
A: a,
B: &b,
}

tests := []struct {
code string
want bool
}{
{`A == B`, true},
{`B == A`, true},
{`A != B`, false},
{`B != A`, false},
}

for _, test := range tests {
t.Run(test.code, func(t *testing.T) {
program, err := expr.Compile(test.code, expr.Env(env))
require.NoError(t, err)

out, err := expr.Run(program, env)
require.NoError(t, err)
require.Equal(t, test.want, out)
})
}
}

0 comments on commit 515f38b

Please sign in to comment.