-
-
Notifications
You must be signed in to change notification settings - Fork 306
/
interpolate.go
364 lines (317 loc) · 9.6 KB
/
interpolate.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
// Mgmt
// Copyright (C) 2013-2021+ James Shubin and the project contributors
// Written by James Shubin <james@shubin.ca> and the project contributors
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package lang // TODO: move this into a sub package of lang/$name?
import (
"fmt"
"github.com/purpleidea/mgmt/lang/interfaces"
"github.com/purpleidea/mgmt/lang/interpolate"
"github.com/purpleidea/mgmt/util/errwrap"
"github.com/hashicorp/hil"
hilast "github.com/hashicorp/hil/ast"
)
const (
// UseHilInterpolation specifies that we use the legacy Hil interpolate.
// This can't properly escape a $ in the standard way. It's here in case
// someone wants to play with it and examine how the AST stuff worked...
UseHilInterpolation = false
)
// Pos represents a position in the code.
// TODO: consider expanding with range characteristics.
type Pos struct {
Line int // line number starting at 1
Column int // column number starting at 1
Filename string // optional source filename, if known
}
// InterpolateStr interpolates a string and returns the representative AST.
func InterpolateStr(str string, pos *Pos, data *interfaces.Data) (interfaces.Expr, error) {
if data.Debug {
data.Logf("interpolating: %s", str)
}
if UseHilInterpolation {
return InterpolateHil(str, pos, data)
}
return InterpolateRagel(str, pos, data)
}
// InterpolateRagel interpolates a string and returns the representative AST. It
// uses the ragel parser to perform the string interpolation.
func InterpolateRagel(str string, pos *Pos, data *interfaces.Data) (interfaces.Expr, error) {
sequence, err := interpolate.Parse(str)
if err != nil {
return nil, errwrap.Wrapf(err, "parser failed")
}
exprs := []interfaces.Expr{}
for _, term := range sequence {
switch t := term.(type) {
case interpolate.Literal:
expr := &ExprStr{
V: t.Value,
}
exprs = append(exprs, expr)
case interpolate.Variable:
expr := &ExprVar{
Name: t.Name,
}
exprs = append(exprs, expr)
default:
return nil, fmt.Errorf("unknown term (%T): %+v", t, t)
}
}
// If we didn't find anything of value, we got an empty string...
if len(sequence) == 0 && str == "" { // be doubly sure...
expr := &ExprStr{
V: "",
}
exprs = append(exprs, expr)
}
// The parser produces non-optimal results where two strings are next to
// each other, when they could be statically combined together.
simplified, err := simplifyExprList(exprs)
if err != nil {
return nil, errwrap.Wrapf(err, "expr list simplify failed")
}
result, err := concatExprListIntoCall(simplified)
if err != nil {
return nil, errwrap.Wrapf(err, "concat expr list failed")
}
return result, errwrap.Wrapf(result.Init(data), "init failed")
}
// InterpolateHil interpolates a string and returns the representative AST. This
// particular implementation uses the hashicorp hil library and syntax to do so.
func InterpolateHil(str string, pos *Pos, data *interfaces.Data) (interfaces.Expr, error) {
var line, column int = -1, -1
var filename string
if pos != nil {
line = pos.Line
column = pos.Column
filename = pos.Filename
}
hilPos := hilast.Pos{
Line: line,
Column: column,
Filename: filename,
}
// should not error on plain strings
tree, err := hil.ParseWithPosition(str, hilPos)
if err != nil {
return nil, errwrap.Wrapf(err, "can't parse string interpolation: `%s`", str)
}
if data.Debug {
data.Logf("tree: %+v", tree)
}
transformData := &interfaces.Data{
// TODO: add missing fields here if/when needed
Fs: data.Fs,
FsURI: data.FsURI,
Base: data.Base,
Files: data.Files,
Imports: data.Imports,
Metadata: data.Metadata,
Modules: data.Modules,
Downloader: data.Downloader,
//World: data.World,
Prefix: data.Prefix,
Debug: data.Debug,
Logf: func(format string, v ...interface{}) {
data.Logf("transform: "+format, v...)
},
}
result, err := hilTransform(tree, transformData)
if err != nil {
return nil, errwrap.Wrapf(err, "error running AST map: `%s`", str)
}
if data.Debug {
data.Logf("transform: %+v", result)
}
// make sure to run the Init on the new expression
return result, errwrap.Wrapf(result.Init(data), "init failed")
}
// hilTransform returns the AST equivalent of the hil AST.
func hilTransform(root hilast.Node, data *interfaces.Data) (interfaces.Expr, error) {
switch node := root.(type) {
case *hilast.Output: // common root node
if data.Debug {
data.Logf("got output type: %+v", node)
}
if len(node.Exprs) == 0 {
return nil, fmt.Errorf("no expressions found")
}
if len(node.Exprs) == 1 {
return hilTransform(node.Exprs[0], data)
}
// assumes len > 1
args := []interfaces.Expr{}
for _, n := range node.Exprs {
expr, err := hilTransform(n, data)
if err != nil {
return nil, errwrap.Wrapf(err, "root failed")
}
args = append(args, expr)
}
// XXX: i think we should be adding these args together, instead
// of grouping for example...
result, err := concatExprListIntoCall(args)
if err != nil {
return nil, errwrap.Wrapf(err, "function grouping failed")
}
return result, nil
case *hilast.Call:
if data.Debug {
data.Logf("got function type: %+v", node)
}
args := []interfaces.Expr{}
for _, n := range node.Args {
arg, err := hilTransform(n, data)
if err != nil {
return nil, fmt.Errorf("call failed: %+v", err)
}
args = append(args, arg)
}
return &ExprCall{
Name: node.Func, // name
Args: args,
}, nil
case *hilast.LiteralNode: // string, int, etc...
if data.Debug {
data.Logf("got literal type: %+v", node)
}
switch node.Typex {
case hilast.TypeBool:
return &ExprBool{
V: node.Value.(bool),
}, nil
case hilast.TypeString:
return &ExprStr{
V: node.Value.(string),
}, nil
case hilast.TypeInt:
return &ExprInt{
// node.Value is an int stored as an interface
V: int64(node.Value.(int)),
}, nil
case hilast.TypeFloat:
return &ExprFloat{
V: node.Value.(float64),
}, nil
// TODO: should we handle these too?
//case hilast.TypeList:
//case hilast.TypeMap:
default:
return nil, fmt.Errorf("unmatched type: %T", node)
}
case *hilast.VariableAccess: // variable lookup
if data.Debug {
data.Logf("got variable access type: %+v", node)
}
return &ExprVar{
Name: node.Name,
}, nil
//case *hilast.Index:
// if va, ok := node.Target.(*hilast.VariableAccess); ok {
// v, err := NewInterpolatedVariable(va.Name)
// if err != nil {
// resultErr = err
// return n
// }
// result = append(result, v)
// }
// if va, ok := node.Key.(*hilast.VariableAccess); ok {
// v, err := NewInterpolatedVariable(va.Name)
// if err != nil {
// resultErr = err
// return n
// }
// result = append(result, v)
// }
default:
return nil, fmt.Errorf("unmatched type: %+v", node)
}
}
// concatExprListIntoCall takes a list of expressions, and combines them into an
// expression which ultimately concatenates them all together with a + operator.
// TODO: this assumes they're all strings, do we need to watch out for int's?
func concatExprListIntoCall(exprs []interfaces.Expr) (interfaces.Expr, error) {
if len(exprs) == 0 {
return nil, fmt.Errorf("empty list")
}
operator := &ExprStr{
V: "+", // for PLUS this is a `+` character
}
if len(exprs) == 1 {
return exprs[0], nil // just return self
}
//if len(exprs) == 1 {
// arg := exprs[0]
// emptyStr := &ExprStr{
// V: "", // empty str
// }
// return &ExprCall{
// Name: operatorFuncName, // concatenate the two strings with + operator
// Args: []interfaces.Expr{
// operator, // operator first
// arg, // string arg
// emptyStr,
// },
// }, nil
//}
head, tail := exprs[0], exprs[1:]
grouped, err := concatExprListIntoCall(tail)
if err != nil {
return nil, err
}
return &ExprCall{
// NOTE: if we don't set the data field we need Init() called on it!
Name: operatorFuncName, // concatenate the two strings with + operator
Args: []interfaces.Expr{
operator, // operator first
head, // string arg
grouped, // nested function call which returns a string
},
}, nil
}
// simplifyExprList takes a list of *ExprStr and *ExprVar and groups the
// sequential *ExprStr's together. If you pass it a list of Expr's that contains
// a different type of Expr, then this will error.
func simplifyExprList(exprs []interfaces.Expr) ([]interfaces.Expr, error) {
last := false
result := []interfaces.Expr{}
for _, x := range exprs {
switch v := x.(type) {
case *ExprStr:
if !last {
last = true
result = append(result, x)
continue
}
// combine!
expr := result[len(result)-1] // there has to be at least one
str, ok := expr.(*ExprStr)
if !ok {
// programming error
return nil, fmt.Errorf("unexpected type (%T)", expr)
}
str.V += v.V // combine!
//last = true // redundant, it's already true
// ... and don't append, we've combined!
case *ExprVar:
last = false // the next one can't combine with me
result = append(result, x)
default:
return nil, fmt.Errorf("unsupported type (%T)", x)
}
}
return result, nil
}