Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix operator overloading #554

Merged
merged 1 commit into from
Feb 8, 2024
Merged

Conversation

3timeslazy
Copy link
Contributor

@3timeslazy 3timeslazy commented Feb 8, 2024

Hi there,

Firstly, thank you for your work!

Secondly, let me explain the context of the PR :)

While trying to get decimals and expr I encountered the following issue. When an operation is overloaded and its result becomes the object of another overloaded operation, it causes a compilation error.

Example:

Given

package main

import (
	"fmt"

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

func main() {
	code := `A + B - C`

	type Env struct {
		A, B, C   decimal.Decimal
		Sub       func(a, b decimal.Decimal) decimal.Decimal
		Add       func(a, b decimal.Decimal) 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.NewFromInt(3),
		B: decimal.NewFromInt(2),
		C: decimal.NewFromInt(1),
		Sub: func(a, b decimal.Decimal) decimal.Decimal { return a.Sub(b) },
		Add: func(a, b decimal.Decimal) decimal.Decimal { return a.Add(b)  },
	}

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

	fmt.Printf("%v", output)
}

Expected

// Output: 4

Actual

invalid operation: decimal.Decimal - decimal.Decimal (1:7)
 | A + B - C
 | ......^

The flow of the bug is the following:

1. Compile("A + B - C") 
2. Expr is "A + B + C"
3. Visit("A + B") // replaces "A + B" -> Add(A, B)
4. Expr is "Add(A, B) + C"
5. Visit("Add(A, B) + C") // mismatch between types. `Add(A, B)` is nil while `C` is decimal.Decimal

@antonmedv
Copy link
Member

Super! Clean fix and the test!

@antonmedv antonmedv merged commit 013c32f into expr-lang:master Feb 8, 2024
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants