Skip to content

Functions defined on the struct are bidden to the Env they were compiled with #695

Open
@vmihailenco

Description

@vmihailenco

For example, the following program can't be reused with different environments, because functions are bidden to the Env they were compiled with:

package main

import (
	"fmt"

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

type Env struct {
	Value string
}

func (e *Env) Get(args ...any) (any, error) {
	return e.Value, nil
}

func main() {
	code := `get()`

	env := Env{Value: "<empty>"}
	program, err := expr.Compile(code,
		expr.Function("get", env.Get, new(func() any)),
		expr.Env(env))
	if err != nil {
		panic(err)
	}

	output, err := expr.Run(program, Env{Value: "hello"})
	if err != nil {
		panic(err)
	}
	fmt.Println(output)

	output, err = expr.Run(program, Env{Value: "world"})
	if err != nil {
		panic(err)
	}
	fmt.Println(output)
}

The program output:

<empty>
<empty>

Expected:

hello
world

I can patch the code to pass $env as the first arg of the function, but then users get weird error messages if compilation fails.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions