forked from hashicorp/hil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck_types.go
376 lines (316 loc) · 8.61 KB
/
check_types.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
365
366
367
368
369
370
371
372
373
374
375
376
package hil
import (
"fmt"
"sync"
"github.com/songkick/hil/ast"
)
// TypeCheck implements ast.Visitor for type checking an AST tree.
// It requires some configuration to look up the type of nodes.
//
// It also optionally will not type error and will insert an implicit
// type conversions for specific types if specified by the Implicit
// field. Note that this is kind of organizationally weird to put into
// this structure but we'd rather do that than duplicate the type checking
// logic multiple times.
type TypeCheck struct {
Scope ast.Scope
// Implicit is a map of implicit type conversions that we can do,
// and that shouldn't error. The key of the first map is the from type,
// the key of the second map is the to type, and the final string
// value is the function to call (which must be registered in the Scope).
Implicit map[ast.Type]map[ast.Type]string
// Stack of types. This shouldn't be used directly except by implementations
// of TypeCheckNode.
Stack []ast.Type
err error
lock sync.Mutex
}
// TypeCheckNode is the interface that must be implemented by any
// ast.Node that wants to support type-checking. If the type checker
// encounters a node that doesn't implement this, it will error.
type TypeCheckNode interface {
TypeCheck(*TypeCheck) (ast.Node, error)
}
func (v *TypeCheck) Visit(root ast.Node) error {
v.lock.Lock()
defer v.lock.Unlock()
defer v.reset()
root.Accept(v.visit)
return v.err
}
func (v *TypeCheck) visit(raw ast.Node) ast.Node {
if v.err != nil {
return raw
}
var result ast.Node
var err error
switch n := raw.(type) {
case *ast.Arithmetic:
tc := &typeCheckArithmetic{n}
result, err = tc.TypeCheck(v)
case *ast.Call:
tc := &typeCheckCall{n}
result, err = tc.TypeCheck(v)
case *ast.Index:
tc := &typeCheckIndex{n}
result, err = tc.TypeCheck(v)
case *ast.Concat:
tc := &typeCheckConcat{n}
result, err = tc.TypeCheck(v)
case *ast.LiteralNode:
tc := &typeCheckLiteral{n}
result, err = tc.TypeCheck(v)
case *ast.VariableAccess:
tc := &typeCheckVariableAccess{n}
result, err = tc.TypeCheck(v)
default:
tc, ok := raw.(TypeCheckNode)
if !ok {
err = fmt.Errorf("unknown node for type check: %#v", raw)
break
}
result, err = tc.TypeCheck(v)
}
if err != nil {
pos := raw.Pos()
v.err = fmt.Errorf("At column %d, line %d: %s",
pos.Column, pos.Line, err)
}
return result
}
type typeCheckArithmetic struct {
n *ast.Arithmetic
}
func (tc *typeCheckArithmetic) TypeCheck(v *TypeCheck) (ast.Node, error) {
// The arguments are on the stack in reverse order, so pop them off.
exprs := make([]ast.Type, len(tc.n.Exprs))
for i, _ := range tc.n.Exprs {
exprs[len(tc.n.Exprs)-1-i] = v.StackPop()
}
// Determine the resulting type we want. We do this by going over
// every expression until we find one with a type we recognize.
// We do this because the first expr might be a string ("var.foo")
// and we need to know what to implicit to.
mathFunc := "__builtin_IntMath"
mathType := ast.TypeInt
for _, v := range exprs {
exit := true
switch v {
case ast.TypeInt:
mathFunc = "__builtin_IntMath"
mathType = v
case ast.TypeFloat:
mathFunc = "__builtin_FloatMath"
mathType = v
default:
exit = false
}
// We found the type, so leave
if exit {
break
}
}
// Verify the args
for i, arg := range exprs {
if arg != mathType {
cn := v.ImplicitConversion(exprs[i], mathType, tc.n.Exprs[i])
if cn != nil {
tc.n.Exprs[i] = cn
continue
}
return nil, fmt.Errorf(
"operand %d should be %s, got %s",
i+1, mathType, arg)
}
}
// Modulo doesn't work for floats
if mathType == ast.TypeFloat && tc.n.Op == ast.ArithmeticOpMod {
return nil, fmt.Errorf("modulo cannot be used with floats")
}
// Return type
v.StackPush(mathType)
// Replace our node with a call to the proper function. This isn't
// type checked but we already verified types.
args := make([]ast.Node, len(tc.n.Exprs)+1)
args[0] = &ast.LiteralNode{
Value: tc.n.Op,
Typex: ast.TypeInt,
Posx: tc.n.Pos(),
}
copy(args[1:], tc.n.Exprs)
return &ast.Call{
Func: mathFunc,
Args: args,
Posx: tc.n.Pos(),
}, nil
}
type typeCheckCall struct {
n *ast.Call
}
func (tc *typeCheckCall) TypeCheck(v *TypeCheck) (ast.Node, error) {
// Look up the function in the map
function, ok := v.Scope.LookupFunc(tc.n.Func)
if !ok {
return nil, fmt.Errorf("unknown function called: %s", tc.n.Func)
}
// The arguments are on the stack in reverse order, so pop them off.
args := make([]ast.Type, len(tc.n.Args))
for i, _ := range tc.n.Args {
args[len(tc.n.Args)-1-i] = v.StackPop()
}
// Verify the args
for i, expected := range function.ArgTypes {
if expected == ast.TypeAny {
continue
}
if args[i] != expected {
cn := v.ImplicitConversion(args[i], expected, tc.n.Args[i])
if cn != nil {
tc.n.Args[i] = cn
continue
}
return nil, fmt.Errorf(
"%s: argument %d should be %s, got %s",
tc.n.Func, i+1, expected, args[i])
}
}
// If we're variadic, then verify the types there
if function.Variadic && function.VariadicType != ast.TypeAny {
args = args[len(function.ArgTypes):]
for i, t := range args {
if t != function.VariadicType {
realI := i + len(function.ArgTypes)
cn := v.ImplicitConversion(
t, function.VariadicType, tc.n.Args[realI])
if cn != nil {
tc.n.Args[realI] = cn
continue
}
return nil, fmt.Errorf(
"%s: argument %d should be %s, got %s",
tc.n.Func, realI,
function.VariadicType, t)
}
}
}
// Return type
v.StackPush(function.ReturnType)
return tc.n, nil
}
type typeCheckConcat struct {
n *ast.Concat
}
func (tc *typeCheckConcat) TypeCheck(v *TypeCheck) (ast.Node, error) {
n := tc.n
types := make([]ast.Type, len(n.Exprs))
for i, _ := range n.Exprs {
types[len(n.Exprs)-1-i] = v.StackPop()
}
// All concat args must be strings, so validate that
for i, t := range types {
if t != ast.TypeString {
cn := v.ImplicitConversion(t, ast.TypeString, n.Exprs[i])
if cn != nil {
n.Exprs[i] = cn
continue
}
return nil, fmt.Errorf(
"output of an HIL expression must be a string (argument %d is %s)", i+1, t)
}
}
// This always results in type string
v.StackPush(ast.TypeString)
return n, nil
}
type typeCheckLiteral struct {
n *ast.LiteralNode
}
func (tc *typeCheckLiteral) TypeCheck(v *TypeCheck) (ast.Node, error) {
v.StackPush(tc.n.Typex)
return tc.n, nil
}
type typeCheckVariableAccess struct {
n *ast.VariableAccess
}
func (tc *typeCheckVariableAccess) TypeCheck(v *TypeCheck) (ast.Node, error) {
// Look up the variable in the map
variable, ok := v.Scope.LookupVar(tc.n.Name)
if !ok {
return nil, fmt.Errorf(
"unknown variable accessed: %s", tc.n.Name)
}
// Add the type to the stack
v.StackPush(variable.Type)
return tc.n, nil
}
type typeCheckIndex struct {
n *ast.Index
}
func (tc *typeCheckIndex) TypeCheck(v *TypeCheck) (ast.Node, error) {
value, err := tc.n.Key.Type(v.Scope)
if err != nil {
return nil, err
}
if value != ast.TypeInt {
return nil, fmt.Errorf("key of an index must be an int, was %s", value)
}
// Ensure we have a VariableAccess as the target
varAccessNode, ok := tc.n.Target.(*ast.VariableAccess)
if !ok {
return nil, fmt.Errorf("target of an index must be a VariableAccess node, was %T", tc.n.Target)
}
// Get the variable
variable, ok := v.Scope.LookupVar(varAccessNode.Name)
if !ok {
return nil, fmt.Errorf("unknown variable accessed: %s", varAccessNode.Name)
}
if variable.Type != ast.TypeList {
return nil, fmt.Errorf("invalid index operation into non-indexable type: %s", variable.Type)
}
list := variable.Value.([]ast.Variable)
// Ensure that the types of the list elements are homogenous
listTypes := make(map[ast.Type]struct{})
for _, v := range list {
if _, ok := listTypes[v.Type]; ok {
continue
}
listTypes[v.Type] = struct{}{}
}
if len(listTypes) != 1 {
return nil, fmt.Errorf("list %q does not have homogenous types (%s)", varAccessNode.Name)
}
// This is the type since the list is homogenous in type
v.StackPush(list[0].Type)
return tc.n, nil
}
func (v *TypeCheck) ImplicitConversion(
actual ast.Type, expected ast.Type, n ast.Node) ast.Node {
if v.Implicit == nil {
return nil
}
fromMap, ok := v.Implicit[actual]
if !ok {
return nil
}
toFunc, ok := fromMap[expected]
if !ok {
return nil
}
return &ast.Call{
Func: toFunc,
Args: []ast.Node{n},
Posx: n.Pos(),
}
}
func (v *TypeCheck) reset() {
v.Stack = nil
v.err = nil
}
func (v *TypeCheck) StackPush(t ast.Type) {
v.Stack = append(v.Stack, t)
}
func (v *TypeCheck) StackPop() ast.Type {
var x ast.Type
x, v.Stack = v.Stack[len(v.Stack)-1], v.Stack[:len(v.Stack)-1]
return x
}