-
Notifications
You must be signed in to change notification settings - Fork 1
/
context.go
109 lines (90 loc) · 1.83 KB
/
context.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package liquid
import (
"errors"
"fmt"
)
var (
ErrNoScope = errors.New(`no scopes to pop`)
ErrVarNotFound = errors.New(`variable not found`)
)
type Context struct {
scopes scopeStack
}
func newContext() Context {
s := scopeStack{}
return Context{s}
}
func (c *Context) Assign(k string, v interface{}) error {
scope, err := c.scopes.curr()
if err != nil {
return err
}
scope[k] = v
return nil
}
func (c *Context) Get(k string) (interface{}, error) {
if len(c.scopes) < 1 {
return nil, ErrNoScope
}
for i := len(c.scopes) - 1; i >= 0; i-- {
if val, ok := c.scopes[i][k]; ok {
return val, nil
}
}
return nil, ErrVarNotFound
}
func interfaceToExpression(v interface{}) Expression {
switch v.(type) {
case string:
return stringExpr(v.(string))
case int:
return integerExpr(v.(int))
case float64:
return floatExpr(v.(float64))
case []interface{}:
return arrayExpr(v.([]interface{}))
}
panic(fmt.Sprintf("DONT UNDERSTAND %v", v))
}
func (c *Context) FindVariable(e Expression) (Expression, error) {
var key string
switch e.(type) {
case stringExpr:
key = string(e.(stringExpr))
case literalExpr:
key = string(e.(literalExpr))
default:
return nil, fmt.Errorf("DUNNO WHAT TO DO WITH %v OMG", e)
}
value, err := c.Get(key)
if err != nil {
if err == ErrVarNotFound {
return nil, ErrNotFound(key)
}
return nil, err
}
return interfaceToExpression(value), nil
}
func (c *Context) lookupAndEvaluate() {
}
type scopeStack []Vars
// Adds a new scope to the scopeStack
func (s *scopeStack) push() {
*s = append(*s, Vars{})
}
// Removes scope from the scopeStack
func (s *scopeStack) pop() error {
l := len(*s)
if l < 1 {
return ErrNoScope
}
*s = (*s)[:l-1]
return nil
}
func (s *scopeStack) curr() (Vars, error) {
l := len(*s)
if l < 1 {
return nil, ErrNoScope
}
return (*s)[l-1], nil
}