-
Notifications
You must be signed in to change notification settings - Fork 15
/
expr_cond_control_var.go
74 lines (65 loc) · 2.15 KB
/
expr_cond_control_var.go
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
package rel
import (
"bytes"
"fmt"
"github.com/arr-ai/wbnf/parser"
)
// CondControlVarExpr returns the tuple applied to a function, the expression looks like:
// let a = 1 + 1; a cond (1 : 2 + 1, 2 : 5, *: 10)
// let a = 1 + 1; let b = a cond (1 : 2 + 1, 2 : 5, *: 10); b
type CondControlVarExpr struct {
ExprScanner
controlVarExpr Expr
standardExpr CondExpr
}
// NewCondControlVarExpr returns a new CondControlVarExpr.
func NewCondControlVarExpr(scanner parser.Scanner, controlVar Expr, dictExpr Expr) Expr {
return CondControlVarExpr{ExprScanner{scanner}, controlVar,
CondExpr{ExprScanner{scanner}, dictExpr, func(condition Value, local Scope) (bool, error) {
controlVarVal, has := local.Get("controlVarVal")
if !has {
return false, fmt.Errorf("couldn't get 'controlVarVal' in Scope, and it is expected")
}
// process "(1,2):11" in case arrai e "(2) cond ((1,2):11,2:12,*:13)"
switch condition := condition.(type) {
case Array:
varVal, err := controlVarVal.Eval(local)
if err != nil {
currentExpr, has := local.Get("currentExpr")
if !has {
return false, fmt.Errorf("%s", err.Error())
}
return false, wrapContext(err, currentExpr, local)
}
for _, exprVal := range condition.Values() {
if exprVal.Equal(varVal) {
return true, nil
}
}
return false, nil
}
return condition.Equal(controlVarVal), nil
}}}
}
// String returns a string representation of the expression.
func (e CondControlVarExpr) String() string {
var b bytes.Buffer
b.WriteByte('(')
fmt.Fprintf(&b, "(control_var: %v)", e.controlVarExpr.String())
standardExprStr := e.standardExpr.String()
if len(standardExprStr) != 0 {
b.WriteString("," + standardExprStr)
}
b.WriteByte(')')
return b.String()
}
// Eval returns the value of valid condition and whose value equals to the control var value,
// or the value of default condition.
func (e CondControlVarExpr) Eval(local Scope) (Value, error) {
controlVarVal, err := e.controlVarExpr.Eval(local)
if err != nil {
return nil, wrapContext(err, e, local)
}
local = local.With("controlVarVal", controlVarVal).With("currentExpr", e)
return e.standardExpr.Eval(local)
}