|
| 1 | +package expr |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "reflect" |
| 6 | + |
| 7 | + "github.com/expr-lang/expr/checker/nature" |
| 8 | + "github.com/expr-lang/expr/compiler" |
| 9 | + "github.com/expr-lang/expr/parser" |
| 10 | + "github.com/expr-lang/expr/vm/runtime" |
| 11 | +) |
| 12 | + |
| 13 | +// This file installs the method-dispatch hooks that the shared packages |
| 14 | +// (vm/runtime, checker/nature, builtin) consult to perform reflective method |
| 15 | +// lookups. The hooks are installed only when the parent expr package is |
| 16 | +// imported. |
| 17 | +// |
| 18 | +// All four reflect.* method-resolution call sites that the linker treats as |
| 19 | +// REFLECTMETHOD live exclusively in this file (or in functions reachable |
| 20 | +// only from this file's hooks): |
| 21 | +// |
| 22 | +// - reflect.Value.MethodByName in fetchMethodByName |
| 23 | +// - reflect.Value.Method in fetchMethodIndexed |
| 24 | +// - reflect.Type.Method in nature.LookupMethod (transitively) |
| 25 | +// - reflect.Type.MethodByName not used |
| 26 | + |
| 27 | +func init() { |
| 28 | + runtime.MethodByNameHook = fetchMethodByName |
| 29 | + runtime.MethodIndexedHook = fetchMethodIndexed |
| 30 | + nature.MethodByNameHook = nature.LookupMethod |
| 31 | +} |
| 32 | + |
| 33 | +func fetchMethodByName(v reflect.Value, name string) (any, bool) { |
| 34 | + method := v.MethodByName(name) |
| 35 | + if method.IsValid() { |
| 36 | + return method.Interface(), true |
| 37 | + } |
| 38 | + return nil, false |
| 39 | +} |
| 40 | + |
| 41 | +func fetchMethodIndexed(v reflect.Value, index int) (any, bool) { |
| 42 | + method := v.Method(index) |
| 43 | + if method.IsValid() { |
| 44 | + return method.Interface(), true |
| 45 | + } |
| 46 | + return nil, false |
| 47 | +} |
| 48 | + |
| 49 | +// Eval parses, compiles and runs given input. |
| 50 | +func Eval(input string, env any) (any, error) { |
| 51 | + if _, ok := env.(Option); ok { |
| 52 | + return nil, fmt.Errorf("misused expr.Eval: second argument (env) should be passed without expr.Env") |
| 53 | + } |
| 54 | + |
| 55 | + tree, err := parser.Parse(input) |
| 56 | + if err != nil { |
| 57 | + return nil, err |
| 58 | + } |
| 59 | + |
| 60 | + program, err := compiler.Compile(tree, nil) |
| 61 | + if err != nil { |
| 62 | + return nil, err |
| 63 | + } |
| 64 | + |
| 65 | + output, err := Run(program, env) |
| 66 | + if err != nil { |
| 67 | + return nil, err |
| 68 | + } |
| 69 | + |
| 70 | + return output, nil |
| 71 | +} |
0 commit comments