/
context.go
86 lines (77 loc) · 2.13 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
package jigo
import (
"fmt"
"reflect"
)
// A context represents an environment passed in by a user to a template. Certain
// tags can create temporary contexts (for, macro, etc), which get created at eval
// time.
type Context struct {
ctx interface{}
kind reflect.Kind
value reflect.Value
}
// Contexts can be structs or maps, or pointers to these types, but no other type.
func NewContext(i interface{}) (*Context, error) {
// save the original value, though we likely won't use it
var v reflect.Value
c := &Context{ctx: i}
// indirect v
for v = reflect.ValueOf(i); v.Kind() == reflect.Ptr; v = reflect.Indirect(v) {
}
c.kind = v.Kind()
c.value = v
if c.kind != reflect.Map && c.kind != reflect.Struct {
return c, fmt.Errorf("Context must be a struct or map, not %s")
}
return c, nil
}
// lookup finds a single name in a single context. If no name is found, then
// an empty Value is returned and ok is False.
func (c Context) lookup(name string) (v reflect.Value, ok bool) {
switch c.kind {
case reflect.Map:
v := c.value.MapIndex(reflect.ValueOf(name))
return v, v.IsValid()
case reflect.Struct:
// FIXME: reflectx fieldmaps will be much faster but a fair bit more code.
// We should use them eventually.
v := c.value.FieldByName(name)
return v, v.IsValid()
default:
return v, false
}
}
// A stack of contexts. Lookup failures go up the stack until there's a success
// or a final failure. This is the way you get nested scopes.
type contextStack []*Context
func NewContextStack(i interface{}) contextStack {
c := make(contextStack, 0, 4)
ctx, err := NewContext(i)
if err != nil {
panic(err)
}
c.push(ctx)
return c
}
func (c *contextStack) push(ctx *Context) {
*c = append(*c, ctx)
}
func (c *contextStack) pop() (ctx *Context) {
ctx = (*c)[len(*c)-1]
*c = (*c)[:len(*c)-1]
return ctx
}
// lookup finds a name in the context stack. If no name is found, then an undefined
// sentinel is returned.
func (c contextStack) lookup(name string) (v reflect.Value, ok bool) {
var ctx *Context
for i := len(c) - 1; i >= 0; i-- {
ctx = c[i]
v, ok = ctx.lookup(name)
if ok {
return v, ok
}
}
return v, ok
}