-
Notifications
You must be signed in to change notification settings - Fork 265
/
stdlib.go
308 lines (299 loc) · 10.5 KB
/
stdlib.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
// Copyright 2021-present The Atlas Authors. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package schemahcl
import (
"net/url"
"strconv"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/ext/tryfunc"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/convert"
"github.com/zclconf/go-cty/cty/function"
"github.com/zclconf/go-cty/cty/function/stdlib"
)
func stdTypes(ctx *hcl.EvalContext) *hcl.EvalContext {
ctx = ctx.NewChild()
ctx.Variables = map[string]cty.Value{
"string": cty.CapsuleVal(ctyNilType, &cty.String),
"bool": cty.CapsuleVal(ctyNilType, &cty.Bool),
"number": cty.CapsuleVal(ctyNilType, &cty.Number),
// Exists for backwards compatibility.
"int": cty.CapsuleVal(ctyNilType, &cty.Number),
}
ctx.Functions = map[string]function.Function{
"list": function.New(&function.Spec{
Params: []function.Parameter{
{Name: "elem_type", Type: ctyNilType},
},
Type: function.StaticReturnType(ctyNilType),
Impl: func(args []cty.Value, _ cty.Type) (cty.Value, error) {
argT := args[0].EncapsulatedValue().(*cty.Type)
listT := cty.List(*argT)
return cty.CapsuleVal(ctyNilType, &listT), nil
},
}),
"set": function.New(&function.Spec{
Params: []function.Parameter{
{Name: "elem_type", Type: ctyNilType},
},
Type: function.StaticReturnType(ctyNilType),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
argT := args[0].EncapsulatedValue().(*cty.Type)
setT := cty.Set(*argT)
return cty.CapsuleVal(ctyNilType, &setT), nil
},
}),
"map": function.New(&function.Spec{
Params: []function.Parameter{
{Name: "elem_type", Type: ctyNilType},
},
Type: function.StaticReturnType(ctyNilType),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
argT := args[0].EncapsulatedValue().(*cty.Type)
mapT := cty.Map(*argT)
return cty.CapsuleVal(ctyNilType, &mapT), nil
},
}),
"tuple": function.New(&function.Spec{
Params: []function.Parameter{
{Name: "elem_type", Type: cty.List(ctyNilType)},
},
Type: function.StaticReturnType(ctyNilType),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
argV := args[0]
argsT := make([]cty.Type, 0, argV.LengthInt())
for it := argV.ElementIterator(); it.Next(); {
_, ev := it.Element()
argsT = append(argsT, *ev.EncapsulatedValue().(*cty.Type))
}
tupleT := cty.Tuple(argsT)
return cty.CapsuleVal(ctyNilType, &tupleT), nil
},
}),
"object": function.New(&function.Spec{
Params: []function.Parameter{
{Name: "attr_type", Type: cty.Map(ctyNilType)},
},
Type: function.StaticReturnType(ctyNilType),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
argV := args[0]
argsT := make(map[string]cty.Type)
for it := argV.ElementIterator(); it.Next(); {
nameV, typeV := it.Element()
name := nameV.AsString()
argsT[name] = *typeV.EncapsulatedValue().(*cty.Type)
}
objT := cty.Object(argsT)
return cty.CapsuleVal(ctyNilType, &objT), nil
},
}),
}
return ctx
}
// standard functions exist in schemahcl language.
func stdFuncs() map[string]function.Function {
return map[string]function.Function{
"abs": stdlib.AbsoluteFunc,
"ceil": stdlib.CeilFunc,
"chomp": stdlib.ChompFunc,
"chunklist": stdlib.ChunklistFunc,
"coalescelist": stdlib.CoalesceListFunc,
"compact": stdlib.CompactFunc,
"concat": stdlib.ConcatFunc,
"contains": stdlib.ContainsFunc,
"csvdecode": stdlib.CSVDecodeFunc,
"distinct": stdlib.DistinctFunc,
"element": stdlib.ElementFunc,
"flatten": stdlib.FlattenFunc,
"floor": stdlib.FloorFunc,
"format": stdlib.FormatFunc,
"formatdate": stdlib.FormatDateFunc,
"formatlist": stdlib.FormatListFunc,
"indent": stdlib.IndentFunc,
"index": stdlib.IndexFunc,
"join": stdlib.JoinFunc,
"jsondecode": stdlib.JSONDecodeFunc,
"jsonencode": stdlib.JSONEncodeFunc,
"keys": stdlib.KeysFunc,
"log": stdlib.LogFunc,
"lower": stdlib.LowerFunc,
"max": stdlib.MaxFunc,
"merge": stdlib.MergeFunc,
"min": stdlib.MinFunc,
"parseint": stdlib.ParseIntFunc,
"pow": stdlib.PowFunc,
"range": stdlib.RangeFunc,
"regex": stdlib.RegexFunc,
"regexall": stdlib.RegexAllFunc,
"regexreplace": stdlib.RegexReplaceFunc,
"reverse": stdlib.ReverseListFunc,
"setintersection": stdlib.SetIntersectionFunc,
"setproduct": stdlib.SetProductFunc,
"setsubtract": stdlib.SetSubtractFunc,
"setunion": stdlib.SetUnionFunc,
"signum": stdlib.SignumFunc,
"slice": stdlib.SliceFunc,
"sort": stdlib.SortFunc,
"split": stdlib.SplitFunc,
"strrev": stdlib.ReverseFunc,
"substr": stdlib.SubstrFunc,
"timeadd": stdlib.TimeAddFunc,
"title": stdlib.TitleFunc,
"tobool": makeToFunc(cty.Bool),
"tolist": makeToFunc(cty.List(cty.DynamicPseudoType)),
"tonumber": makeToFunc(cty.Number),
"toset": makeToFunc(cty.Set(cty.DynamicPseudoType)),
"tostring": makeToFunc(cty.String),
"trim": stdlib.TrimFunc,
"trimprefix": stdlib.TrimPrefixFunc,
"trimspace": stdlib.TrimSpaceFunc,
"trimsuffix": stdlib.TrimSuffixFunc,
"try": tryfunc.TryFunc,
"upper": stdlib.UpperFunc,
"urlescape": urlEscape,
"urlqueryset": urlQuerySetFunc,
"urlsetpath": urlSetPathFunc,
"values": stdlib.ValuesFunc,
"zipmap": stdlib.ZipmapFunc,
// A patch from the past. Should be moved
// to specific scopes in the future.
"sql": rawExprImpl(),
}
}
// makeToFunc constructs a "to..." function, like "tostring", which converts
// its argument to a specific type or type kind. Code was copied from:
// github.com/hashicorp/terraform/blob/master/internal/lang/funcs/conversion.go
func makeToFunc(wantTy cty.Type) function.Function {
return function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "v",
// We use DynamicPseudoType rather than wantTy here so that
// all values will pass through the function API verbatim and
// we can handle the conversion logic within the Type and
// Impl functions. This allows us to customize the error
// messages to be more appropriate for an explicit type
// conversion, whereas the cty function system produces
// messages aimed at _implicit_ type conversions.
Type: cty.DynamicPseudoType,
AllowNull: true,
AllowMarked: true,
AllowDynamicType: true,
},
},
Type: func(args []cty.Value) (cty.Type, error) {
gotTy := args[0].Type()
if gotTy.Equals(wantTy) {
return wantTy, nil
}
conv := convert.GetConversionUnsafe(args[0].Type(), wantTy)
if conv == nil {
// We'll use some specialized errors for some trickier cases,
// but most we can handle in a simple way.
switch {
case gotTy.IsTupleType() && wantTy.IsTupleType():
return cty.NilType, function.NewArgErrorf(0, "incompatible tuple type for conversion: %s", convert.MismatchMessage(gotTy, wantTy))
case gotTy.IsObjectType() && wantTy.IsObjectType():
return cty.NilType, function.NewArgErrorf(0, "incompatible object type for conversion: %s", convert.MismatchMessage(gotTy, wantTy))
default:
return cty.NilType, function.NewArgErrorf(0, "cannot convert %s to %s", gotTy.FriendlyName(), wantTy.FriendlyNameForConstraint())
}
}
// If a conversion is available then everything is fine.
return wantTy, nil
},
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
// We didn't set "AllowUnknown" on our argument, so it is guaranteed
// to be known here but may still be null.
ret, err := convert.Convert(args[0], retType)
if err != nil {
val, _ := args[0].UnmarkDeep()
// Because we used GetConversionUnsafe above, conversion can
// still potentially fail in here. For example, if the user
// asks to convert the string "a" to bool then we'll
// optimistically permit it during type checking but fail here
// once we note that the value isn't either "true" or "false".
gotTy := val.Type()
switch {
case gotTy == cty.String && wantTy == cty.Bool:
what := "string"
if !val.IsNull() {
what = strconv.Quote(val.AsString())
}
return cty.NilVal, function.NewArgErrorf(0, `cannot convert %s to bool; only the strings "true" or "false" are allowed`, what)
case gotTy == cty.String && wantTy == cty.Number:
what := "string"
if !val.IsNull() {
what = strconv.Quote(val.AsString())
}
return cty.NilVal, function.NewArgErrorf(0, `cannot convert %s to number; given string must be a decimal representation of a number`, what)
default:
return cty.NilVal, function.NewArgErrorf(0, "cannot convert %s to %s", gotTy.FriendlyName(), wantTy.FriendlyNameForConstraint())
}
}
return ret, nil
},
})
}
var urlQuerySetFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "url",
Type: cty.String,
},
{
Name: "key",
Type: cty.String,
},
{
Name: "value",
Type: cty.String,
},
},
Type: function.StaticReturnType(cty.String),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
u, err := url.Parse(args[0].AsString())
if err != nil {
return cty.NilVal, err
}
q := u.Query()
q.Set(args[1].AsString(), args[2].AsString())
u.RawQuery = q.Encode()
return cty.StringVal(u.String()), nil
},
})
var urlSetPathFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "url",
Type: cty.String,
},
{
Name: "path",
Type: cty.String,
},
},
Type: function.StaticReturnType(cty.String),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
u, err := url.Parse(args[0].AsString())
if err != nil {
return cty.NilVal, err
}
u.Path = args[1].AsString()
return cty.StringVal(u.String()), nil
},
})
var urlEscape = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "string",
Type: cty.String,
},
},
Type: function.StaticReturnType(cty.String),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
u := url.QueryEscape(args[0].AsString())
return cty.StringVal(u), nil
},
})