Skip to content

Commit 013c32f

Browse files
authored
Fix operator overloading (#554)
1 parent c7658ac commit 013c32f

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

conf/operators.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,13 @@ func (p *OperatorPatcher) Visit(node *ast.Node) {
4848
leftType := binaryNode.Left.Type()
4949
rightType := binaryNode.Right.Type()
5050

51-
_, fn, ok := FindSuitableOperatorOverload(fns, p.Types, leftType, rightType)
51+
ret, fn, ok := FindSuitableOperatorOverload(fns, p.Types, leftType, rightType)
5252
if ok {
5353
newNode := &ast.CallNode{
5454
Callee: &ast.IdentifierNode{Value: fn},
5555
Arguments: []ast.Node{binaryNode.Left, binaryNode.Right},
5656
}
57+
newNode.SetType(ret)
5758
ast.Patch(node, newNode)
5859
}
5960
}

expr_test.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,47 @@ func ExampleOperator() {
311311
// Output: true
312312
}
313313

314+
func ExampleOperator_Decimal() {
315+
type Decimal struct{ N float64 }
316+
code := `A + B - C`
317+
318+
type Env struct {
319+
A, B, C Decimal
320+
Sub func(a, b Decimal) Decimal
321+
Add func(a, b Decimal) Decimal
322+
}
323+
324+
options := []expr.Option{
325+
expr.Env(Env{}),
326+
expr.Operator("+", "Add"),
327+
expr.Operator("-", "Sub"),
328+
}
329+
330+
program, err := expr.Compile(code, options...)
331+
if err != nil {
332+
fmt.Printf("Compile error: %v", err)
333+
return
334+
}
335+
336+
env := Env{
337+
A: Decimal{3},
338+
B: Decimal{2},
339+
C: Decimal{1},
340+
Sub: func(a, b Decimal) Decimal { return Decimal{a.N - b.N} },
341+
Add: func(a, b Decimal) Decimal { return Decimal{a.N + b.N} },
342+
}
343+
344+
output, err := expr.Run(program, env)
345+
if err != nil {
346+
fmt.Printf("%v", err)
347+
return
348+
}
349+
350+
fmt.Printf("%v", output)
351+
352+
// Output: {4}
353+
}
354+
314355
func fib(n int) int {
315356
if n <= 1 {
316357
return n

0 commit comments

Comments
 (0)