File: config.go

package info (click to toggle)
golang-github-antonmedv-expr 1.8.9-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 4,524 kB
  • sloc: makefile: 6
file content (89 lines) | stat: -rw-r--r-- 2,116 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package conf

import (
	"fmt"
	"reflect"

	"github.com/antonmedv/expr/ast"
	"github.com/antonmedv/expr/vm"
)

type Config struct {
	Env          interface{}
	MapEnv       bool
	Types        TypesTable
	Operators    OperatorsTable
	Expect       reflect.Kind
	Optimize     bool
	Strict       bool
	DefaultType  reflect.Type
	ConstExprFns map[string]reflect.Value
	Visitors     []ast.Visitor
	err          error
}

func New(env interface{}) *Config {
	var mapEnv bool
	var mapValueType reflect.Type
	if _, ok := env.(map[string]interface{}); ok {
		mapEnv = true
	} else {
		if reflect.ValueOf(env).Kind() == reflect.Map {
			mapValueType = reflect.TypeOf(env).Elem()
		}
	}

	return &Config{
		Env:          env,
		MapEnv:       mapEnv,
		Types:        CreateTypesTable(env),
		Optimize:     true,
		Strict:       true,
		DefaultType:  mapValueType,
		ConstExprFns: make(map[string]reflect.Value),
	}
}

// Check validates the compiler configuration.
func (c *Config) Check() error {
	// Check that all functions that define operator overloading
	// exist in environment and have correct signatures.
	for op, fns := range c.Operators {
		for _, fn := range fns {
			fnType, ok := c.Types[fn]
			if !ok || fnType.Type.Kind() != reflect.Func {
				return fmt.Errorf("function %s for %s operator does not exist in environment", fn, op)
			}
			requiredNumIn := 2
			if fnType.Method {
				requiredNumIn = 3 // As first argument of method is receiver.
			}
			if fnType.Type.NumIn() != requiredNumIn || fnType.Type.NumOut() != 1 {
				return fmt.Errorf("function %s for %s operator does not have a correct signature", fn, op)
			}
		}
	}

	// Check that all ConstExprFns are functions.
	for name, fn := range c.ConstExprFns {
		if fn.Kind() != reflect.Func {
			return fmt.Errorf("const expression %q must be a function", name)
		}
	}

	return c.err
}

func (c *Config) ConstExpr(name string) {
	if c.Env == nil {
		c.Error(fmt.Errorf("no environment for const expression: %v", name))
		return
	}
	c.ConstExprFns[name] = vm.FetchFn(c.Env, name)
}

func (c *Config) Error(err error) {
	if c.err == nil {
		c.err = err
	}
}