-
Notifications
You must be signed in to change notification settings - Fork 24
/
decoder.go
331 lines (295 loc) · 10.5 KB
/
decoder.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
package decoder
import (
"fmt"
"github.com/hashicorp/hcl-lang/lang"
"github.com/hashicorp/hcl-lang/reference"
"github.com/hashicorp/hcl-lang/schema"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/zclconf/go-cty/cty"
)
type Decoder struct {
ctx DecoderContext
pathReader PathReader
}
// NewDecoder creates a new Decoder
//
// Decoder is safe for use without any schema, but configuration files are loaded
// via LoadFile and (optionally) schema is set via SetSchema.
func NewDecoder(pathReader PathReader) *Decoder {
return &Decoder{
pathReader: pathReader,
}
}
func posEqual(pos, other hcl.Pos) bool {
return pos.Line == other.Line &&
pos.Column == other.Column &&
pos.Byte == other.Byte
}
func mergeBlockBodySchemas(block *hcl.Block, blockSchema *schema.BlockSchema) (*schema.BodySchema, error) {
mergedSchema := &schema.BodySchema{}
if blockSchema.Body != nil {
mergedSchema = blockSchema.Body.Copy()
}
if mergedSchema.Attributes == nil {
mergedSchema.Attributes = make(map[string]*schema.AttributeSchema, 0)
}
if mergedSchema.Blocks == nil {
mergedSchema.Blocks = make(map[string]*schema.BlockSchema, 0)
}
if mergedSchema.TargetableAs == nil {
mergedSchema.TargetableAs = make([]*schema.Targetable, 0)
}
if mergedSchema.ImpliedOrigins == nil {
mergedSchema.ImpliedOrigins = make([]schema.ImpliedOrigin, 0)
}
depSchema, _, ok := NewBlockSchema(blockSchema).DependentBodySchema(block)
if ok {
for name, attr := range depSchema.Attributes {
if _, exists := mergedSchema.Attributes[name]; !exists {
mergedSchema.Attributes[name] = attr
} else {
// Skip duplicate attribute
continue
}
}
for bType, block := range depSchema.Blocks {
if _, exists := mergedSchema.Blocks[bType]; !exists {
// propagate DynamicBlocks extension to any nested blocks
if mergedSchema.Extensions != nil && mergedSchema.Extensions.DynamicBlocks {
if block.Body.Extensions == nil {
block.Body.Extensions = &schema.BodyExtensions{}
}
block.Body.Extensions.DynamicBlocks = true
}
mergedSchema.Blocks[bType] = block
} else {
// Skip duplicate block type
continue
}
}
if mergedSchema.Extensions != nil && mergedSchema.Extensions.DynamicBlocks && len(depSchema.Blocks) > 0 {
mergedSchema.Blocks["dynamic"] = buildDynamicBlockSchema(depSchema)
}
mergedSchema.TargetableAs = append(mergedSchema.TargetableAs, depSchema.TargetableAs...)
mergedSchema.ImpliedOrigins = append(mergedSchema.ImpliedOrigins, depSchema.ImpliedOrigins...)
// TODO: avoid resetting?
mergedSchema.Targets = depSchema.Targets.Copy()
// TODO: avoid resetting?
mergedSchema.DocsLink = depSchema.DocsLink.Copy()
// use extensions of DependentBody if not nil
// (to avoid resetting to nil)
if depSchema.Extensions != nil {
mergedSchema.Extensions = depSchema.Extensions.Copy()
}
} else if !ok && mergedSchema.Extensions != nil && mergedSchema.Extensions.DynamicBlocks && len(mergedSchema.Blocks) > 0 {
// dynamic blocks are only relevant for dependent schemas,
// but we may end up here because the schema is a result
// of merged static + dependent schema from previous iteration
// propagate DynamicBlocks extension to any nested blocks
if mergedSchema.Extensions != nil && mergedSchema.Extensions.DynamicBlocks {
for bType, block := range mergedSchema.Blocks {
if block.Body.Extensions == nil {
block.Body.Extensions = &schema.BodyExtensions{}
}
block.Body.Extensions.DynamicBlocks = true
mergedSchema.Blocks[bType] = block
}
}
mergedSchema.Blocks["dynamic"] = buildDynamicBlockSchema(mergedSchema)
}
return mergedSchema, nil
}
// blockContent represents HCL or JSON block content
type blockContent struct {
*hcl.Block
// Range represents range of the block in HCL syntax
// or closest available representative range in JSON
Range hcl.Range
}
// bodyContent represents an HCL or JSON body content
type bodyContent struct {
Attributes hcl.Attributes
Blocks []*blockContent
RangePtr *hcl.Range
}
// decodeBody produces content of either HCL or JSON body
//
// JSON body requires schema for decoding, empty bodyContent
// is returned if nil schema is provided
func decodeBody(body hcl.Body, bodySchema *schema.BodySchema) bodyContent {
content := bodyContent{
Attributes: make(hcl.Attributes, 0),
Blocks: make([]*blockContent, 0),
}
// More common HCL syntax is processed directly (without schema)
// which also better represents the reality in symbol lookups
// i.e. expressions written as opposed to schema requirements
if hclBody, ok := body.(*hclsyntax.Body); ok {
for name, attr := range hclBody.Attributes {
content.Attributes[name] = attr.AsHCLAttribute()
}
for _, block := range hclBody.Blocks {
content.Blocks = append(content.Blocks, &blockContent{
Block: block.AsHCLBlock(),
Range: block.Range(),
})
}
content.RangePtr = hclBody.Range().Ptr()
return content
}
// JSON syntax cannot be decoded without schema as attributes
// and blocks are otherwise ambiguous
if bodySchema != nil {
hclSchema := bodySchema.ToHCLSchema()
bContent, remainingBody, _ := body.PartialContent(hclSchema)
content.Attributes = bContent.Attributes
if bodySchema.AnyAttribute != nil {
// Remaining unknown fields may also be blocks in JSON,
// but we blindly treat them as attributes here
// as we cannot do any better without upstream HCL changes.
remainingAttrs, _ := remainingBody.JustAttributes()
for name, attr := range remainingAttrs {
content.Attributes[name] = attr
}
}
for _, block := range bContent.Blocks {
// hcl.Block interface (as the only way of accessing block in JSON)
// does not come with Range for the block, so we calculate it here
rng := hcl.RangeBetween(block.DefRange, block.Body.MissingItemRange())
content.Blocks = append(content.Blocks, &blockContent{
Block: block,
Range: rng,
})
}
}
return content
}
func stringPos(pos hcl.Pos) string {
return fmt.Sprintf("%d,%d", pos.Line, pos.Column)
}
func countAttributeSchema() *schema.AttributeSchema {
return &schema.AttributeSchema{
IsOptional: true,
Expr: schema.ExprConstraints{
schema.TraversalExpr{OfType: cty.Number},
schema.LiteralTypeExpr{Type: cty.Number},
},
Description: lang.Markdown("Total number of instances of this block.\n\n" +
"**Note**: A given block cannot use both `count` and `for_each`."),
}
}
func forEachAttributeSchema() *schema.AttributeSchema {
return &schema.AttributeSchema{
IsOptional: true,
Expr: schema.ExprConstraints{
schema.TraversalExpr{OfType: cty.Map(cty.DynamicPseudoType)},
schema.TraversalExpr{OfType: cty.Set(cty.String)},
schema.LiteralTypeExpr{Type: cty.Map(cty.DynamicPseudoType)},
schema.LiteralTypeExpr{Type: cty.Set(cty.String)},
},
Description: lang.Markdown("A meta-argument that accepts a map or a set of strings, and creates an instance for each item in that map or set.\n\n" +
"**Note**: A given block cannot use both `count` and `for_each`."),
}
}
func buildDynamicBlockSchema(inputSchema *schema.BodySchema) *schema.BlockSchema {
dependentBody := make(map[schema.SchemaKey]*schema.BodySchema)
for blockName, block := range inputSchema.Blocks {
dependentBody[schema.NewSchemaKey(schema.DependencyKeys{
Labels: []schema.LabelDependent{
{Index: 0, Value: blockName},
},
})] = &schema.BodySchema{
Blocks: map[string]*schema.BlockSchema{
"content": {
Description: lang.PlainText("The body of each generated block"),
MaxItems: 1,
Body: block.Body.Copy(),
},
},
}
}
return &schema.BlockSchema{
Description: lang.Markdown("A dynamic block to produce blocks dynamically by iterating over a given complex value"),
Labels: []*schema.LabelSchema{
{
Name: "name",
Completable: true,
IsDepKey: true,
},
},
Body: &schema.BodySchema{
Attributes: map[string]*schema.AttributeSchema{
"for_each": {
Expr: schema.ExprConstraints{
schema.TraversalExpr{OfType: cty.Map(cty.DynamicPseudoType)},
schema.TraversalExpr{OfType: cty.Set(cty.String)},
schema.LiteralTypeExpr{Type: cty.Map(cty.DynamicPseudoType)},
schema.LiteralTypeExpr{Type: cty.Set(cty.String)},
},
IsRequired: true,
Description: lang.Markdown("A meta-argument that accepts a map or a set of strings, and creates an instance for each item in that map or set."),
},
"iterator": {
Expr: schema.LiteralTypeOnly(cty.String),
IsOptional: true,
Description: lang.Markdown("The name of a temporary variable that represents the current " +
"element of the complex value. Defaults to the label of the dynamic block."),
},
"labels": {
Expr: schema.ExprConstraints{
schema.ListExpr{
Elem: schema.ExprConstraints{
schema.LiteralTypeExpr{Type: cty.String},
schema.TraversalExpr{OfType: cty.String},
},
},
},
IsOptional: true,
Description: lang.Markdown("A list of strings that specifies the block labels, " +
"in order, to use for each generated block."),
},
},
},
DependentBody: dependentBody,
}
}
func countIndexReferenceTarget(attr *hcl.Attribute, bodyRange hcl.Range) reference.Target {
return reference.Target{
LocalAddr: lang.Address{
lang.RootStep{Name: "count"},
lang.AttrStep{Name: "index"},
},
TargetableFromRangePtr: bodyRange.Ptr(),
Type: cty.Number,
Description: lang.Markdown("The distinct index number (starting with 0) corresponding to the instance"),
RangePtr: attr.Range.Ptr(),
DefRangePtr: attr.NameRange.Ptr(),
}
}
func forEachReferenceTargets(attr *hcl.Attribute, bodyRange hcl.Range) reference.Targets {
return reference.Targets{
{
LocalAddr: lang.Address{
lang.RootStep{Name: "each"},
lang.AttrStep{Name: "key"},
},
TargetableFromRangePtr: bodyRange.Ptr(),
Type: cty.String,
Description: lang.Markdown("The map key (or set member) corresponding to this instance"),
RangePtr: attr.Range.Ptr(),
DefRangePtr: attr.NameRange.Ptr(),
},
{
LocalAddr: lang.Address{
lang.RootStep{Name: "each"},
lang.AttrStep{Name: "value"},
},
TargetableFromRangePtr: bodyRange.Ptr(),
Type: cty.DynamicPseudoType,
Description: lang.Markdown("The map value corresponding to this instance. (If a set was provided, this is the same as `each.key`.)"),
RangePtr: attr.Range.Ptr(),
DefRangePtr: attr.NameRange.Ptr(),
},
}
}