Skip to content

Commit

Permalink
Fix operator overloading (#554)
Browse files Browse the repository at this point in the history
  • Loading branch information
3timeslazy authored Feb 8, 2024
1 parent c7658ac commit 013c32f
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
3 changes: 2 additions & 1 deletion conf/operators.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,13 @@ func (p *OperatorPatcher) Visit(node *ast.Node) {
leftType := binaryNode.Left.Type()
rightType := binaryNode.Right.Type()

_, fn, ok := FindSuitableOperatorOverload(fns, p.Types, leftType, rightType)
ret, fn, ok := FindSuitableOperatorOverload(fns, p.Types, leftType, rightType)
if ok {
newNode := &ast.CallNode{
Callee: &ast.IdentifierNode{Value: fn},
Arguments: []ast.Node{binaryNode.Left, binaryNode.Right},
}
newNode.SetType(ret)
ast.Patch(node, newNode)
}
}
41 changes: 41 additions & 0 deletions expr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,47 @@ func ExampleOperator() {
// Output: true
}

func ExampleOperator_Decimal() {
type Decimal struct{ N float64 }
code := `A + B - C`

type Env struct {
A, B, C Decimal
Sub func(a, b Decimal) Decimal
Add func(a, b Decimal) Decimal
}

options := []expr.Option{
expr.Env(Env{}),
expr.Operator("+", "Add"),
expr.Operator("-", "Sub"),
}

program, err := expr.Compile(code, options...)
if err != nil {
fmt.Printf("Compile error: %v", err)
return
}

env := Env{
A: Decimal{3},
B: Decimal{2},
C: Decimal{1},
Sub: func(a, b Decimal) Decimal { return Decimal{a.N - b.N} },
Add: func(a, b Decimal) Decimal { return Decimal{a.N + b.N} },
}

output, err := expr.Run(program, env)
if err != nil {
fmt.Printf("%v", err)
return
}

fmt.Printf("%v", output)

// Output: {4}
}

func fib(n int) int {
if n <= 1 {
return n
Expand Down

0 comments on commit 013c32f

Please sign in to comment.