-
Notifications
You must be signed in to change notification settings - Fork 136
/
compiled_template.go
268 lines (211 loc) · 7.05 KB
/
compiled_template.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package template
import (
"fmt"
"strings"
"github.com/k14s/ytt/pkg/filepos"
tplcore "github.com/k14s/ytt/pkg/template/core"
"go.starlark.net/resolve"
"go.starlark.net/starlark"
"go.starlark.net/syntax"
)
type EvaluationCtxDialectName string
type EvaluationCtxDialects map[EvaluationCtxDialectName]EvaluationCtxDialect
type CompiledTemplate struct {
name string
code []TemplateLine
instructions *InstructionSet
nodes *Nodes
evalDialects EvaluationCtxDialects
rootCtx *EvaluationCtx
ctxs []*EvaluationCtx
}
func NewCompiledTemplate(name string, code []TemplateLine,
instructions *InstructionSet, nodes *Nodes,
evalDialects EvaluationCtxDialects) *CompiledTemplate {
// TODO package globals
resolve.AllowFloat = true
resolve.AllowSet = true
resolve.AllowLambda = true
resolve.AllowNestedDef = true
resolve.AllowBitwise = true
resolve.AllowRecursion = true
resolve.AllowGlobalReassign = true
return &CompiledTemplate{
name: name,
code: code,
instructions: instructions,
nodes: nodes,
evalDialects: evalDialects,
}
}
func (e *CompiledTemplate) Code() []TemplateLine { return e.code }
func (e *CompiledTemplate) CodeAtLine(pos *filepos.Position) *TemplateLine {
for i, line := range e.code {
if i+1 == pos.Line() {
return &line
}
}
return nil
}
func (e *CompiledTemplate) CodeAsString() string {
result := []string{}
for _, line := range e.code {
result = append(result, line.Instruction.AsString())
}
// Do not add any unnecessary newlines to match code lines
return strings.Join(result, "\n")
}
func (e *CompiledTemplate) DebugCodeAsString() string {
result := []string{"src: tmpl: code: | srccode"}
for i, line := range e.code {
src := ""
pos := filepos.NewUnknownPosition()
if line.SourceLine != nil {
src = line.SourceLine.Content
pos = line.SourceLine.Position
}
result = append(result, fmt.Sprintf("%s: %4d: %s | %s",
pos.As4DigitString(), i+1, line.Instruction.AsString(), src))
}
// Do not add any unnecessary newlines to match code lines
return strings.Join(result, "\n")
}
func (e *CompiledTemplate) Eval(thread *starlark.Thread, loader CompiledTemplateLoader) (
starlark.StringDict, interface{}, error) {
globals := make(starlark.StringDict)
if e.nodes != nil {
instructionBindings := map[string]tplcore.StarlarkFunc{
// TODO ProgramAST should get rid of set ctx type calls
e.instructions.SetCtxType.Name: e.tplSetCtxType,
e.instructions.StartCtx.Name: e.tplStartCtx,
e.instructions.EndCtx.Name: e.tplEndCtx,
e.instructions.StartNodeAnnotation.Name: e.tplStartNodeAnnotation,
e.instructions.CollectNodeAnnotation.Name: e.tplCollectNodeAnnotation,
e.instructions.StartNode.Name: e.tplStartNode,
e.instructions.SetNode.Name: e.tplSetNode,
e.instructions.SetMapItemKey.Name: e.tplSetMapItemKey,
}
for name, f := range instructionBindings {
globals[name] = starlark.NewBuiltin(name, tplcore.ErrWrapper(f))
}
}
updatedGlobals, val, err := e.eval(thread, globals)
if err != nil {
return nil, nil, NewCompiledTemplateMultiError(err, loader)
}
return updatedGlobals, val, nil
}
func (e *CompiledTemplate) eval(
thread *starlark.Thread, globals starlark.StringDict) (
gs starlark.StringDict, resultVal interface{}, resultErr error) {
// Catch any panics to give a better contextual information
defer func() {
if err := recover(); err != nil {
if typedErr, ok := err.(error); ok {
resultErr = typedErr
} else {
resultErr = fmt.Errorf("(p) %s", err)
}
}
}()
f, err := syntax.Parse(e.name, e.CodeAsString(), 0)
if err != nil {
return nil, nil, err
}
NewProgramAST(f, e.instructions).InsertTplCtxs()
prog, err := starlark.FileProgram(f, globals.Has)
if err != nil {
return nil, nil, err
}
// clear before execution
e.rootCtx = nil
e.ctxs = nil
updatedGlobals, err := prog.Init(thread, globals)
if err != nil {
return nil, nil, err
}
updatedGlobals.Freeze()
if len(e.ctxs) > 0 {
panic("expected all ctxs to end")
}
// Plain starlark programs do not have any ctxs
if e.rootCtx != nil {
resultVal = e.rootCtx.RootNode()
}
return updatedGlobals, resultVal, nil
}
func (e *CompiledTemplate) newCtx(ctxType EvaluationCtxDialectName) *EvaluationCtx {
return &EvaluationCtx{
nodes: e.nodes,
ancestors: e.nodes.Ancestors(),
dialect: e.evalDialects[ctxType],
pendingAnnotations: map[NodeTag]NodeAnnotations{},
pendingMapItemKeys: map[NodeTag]interface{}{},
}
}
func (e *CompiledTemplate) tplSetCtxType(
thread *starlark.Thread, _ *starlark.Builtin,
args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
return starlark.None, nil
}
func (e *CompiledTemplate) tplStartCtx(
thread *starlark.Thread, _ *starlark.Builtin,
args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
ctxType, err := tplcore.NewStarlarkValue(args.Index(0)).AsString()
if err != nil {
return starlark.None, err
}
e.ctxs = append(e.ctxs, e.newCtx(EvaluationCtxDialectName(ctxType)))
if len(e.ctxs) == 1 && e.rootCtx == nil {
e.rootCtx = e.ctxs[0]
}
return starlark.None, nil
}
func (e *CompiledTemplate) tplEndCtx(
thread *starlark.Thread, _ *starlark.Builtin,
args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
if len(e.ctxs) == 0 {
panic("unexpected ctx end")
}
var returnVal starlark.Value
switch args.Len() {
case 0:
returnVal = e.ctxs[len(e.ctxs)-1].RootNodeAsStarlarkValue()
case 1:
returnVal = args.Index(0)
default:
return starlark.None, fmt.Errorf("expected zero or one argument")
}
e.ctxs = e.ctxs[:len(e.ctxs)-1]
return returnVal, nil
}
func (e *CompiledTemplate) tplSetNode(
thread *starlark.Thread, f *starlark.Builtin,
args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
return e.ctxs[len(e.ctxs)-1].TplSetNode(thread, f, args, kwargs)
}
func (e *CompiledTemplate) tplSetMapItemKey(
thread *starlark.Thread, f *starlark.Builtin,
args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
return e.ctxs[len(e.ctxs)-1].TplSetMapItemKey(thread, f, args, kwargs)
}
func (e *CompiledTemplate) tplStartNodeAnnotation(
thread *starlark.Thread, f *starlark.Builtin,
args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
return e.ctxs[len(e.ctxs)-1].TplStartNodeAnnotation(thread, f, args, kwargs)
}
func (e *CompiledTemplate) tplCollectNodeAnnotation(
thread *starlark.Thread, f *starlark.Builtin,
args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
return e.ctxs[len(e.ctxs)-1].TplCollectNodeAnnotation(thread, f, args, kwargs)
}
func (e *CompiledTemplate) tplStartNode(
thread *starlark.Thread, f *starlark.Builtin,
args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
return e.ctxs[len(e.ctxs)-1].TplStartNode(thread, f, args, kwargs)
}
func (e *CompiledTemplate) TplReplaceNode(
thread *starlark.Thread, f *starlark.Builtin,
args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
return e.ctxs[len(e.ctxs)-1].TplReplace(thread, f, args, kwargs)
}