/
binder_component.go
377 lines (328 loc) 路 11.6 KB
/
binder_component.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
377
// Copyright 2016-2020, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pcl
import (
"os"
"path/filepath"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/model"
syntax "github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/syntax"
)
// componentVariableType returns the type of the variable of which the value is a component.
// The type is derived from the outputs of the sub-program of the component into an ObjectType
func componentVariableType(program *Program) model.Type {
properties := map[string]model.Type{}
for _, node := range program.Nodes {
switch node := node.(type) {
case *OutputVariable:
switch nodeType := node.Type().(type) {
case *model.OutputType:
// if the output variable is already an Output<T>, keep it as is
properties[node.LogicalName()] = nodeType
default:
// otherwise, wrap it as an output
properties[node.LogicalName()] = &model.OutputType{
ElementType: nodeType,
}
}
}
}
return &model.ObjectType{Properties: properties}
}
type componentScopes struct {
root *model.Scope
withRange *model.Scope
component *Component
}
func newComponentScopes(
root *model.Scope,
component *Component,
rangeKeyType model.Type,
rangeValueType model.Type,
) model.Scopes {
scopes := &componentScopes{
root: root,
withRange: root,
component: component,
}
if rangeValueType != nil {
properties := map[string]model.Type{
"value": rangeValueType,
}
if rangeKeyType != nil {
properties["key"] = rangeKeyType
}
scopes.withRange = root.Push(syntax.None)
scopes.withRange.Define("range", &model.Variable{
Name: "range",
VariableType: model.NewObjectType(properties),
})
}
return scopes
}
func (s *componentScopes) GetScopesForBlock(block *hclsyntax.Block) (model.Scopes, hcl.Diagnostics) {
return model.StaticScope(s.withRange), nil
}
func (s *componentScopes) GetScopeForAttribute(attr *hclsyntax.Attribute) (*model.Scope, hcl.Diagnostics) {
return s.withRange, nil
}
type componentInput struct {
key string
required bool
}
func componentInputs(program *Program) map[string]componentInput {
inputs := map[string]componentInput{}
for _, node := range program.Nodes {
switch node := node.(type) {
case *ConfigVariable:
inputs[node.LogicalName()] = componentInput{
required: node.DefaultValue == nil && !node.Nullable,
key: node.LogicalName(),
}
}
}
return inputs
}
func contains(slice []string, item string) bool {
set := make(map[string]struct{}, len(slice))
for _, s := range slice {
set[s] = struct{}{}
}
_, ok := set[item]
return ok
}
// ComponentProgramBinderFromFileSystem returns the default component program binder which uses the file system
// to parse and bind PCL files into a program.
func ComponentProgramBinderFromFileSystem() ComponentProgramBinder {
return func(args ComponentProgramBinderArgs) (*Program, hcl.Diagnostics, error) {
var diagnostics hcl.Diagnostics
binderDirPath := args.BinderDirPath
componentSource := args.ComponentSource
nodeRange := args.ComponentNodeRange
loader := args.BinderLoader
// bind the component here as if it was a new program
// this becomes the DirPath for the new binder
componentSourceDir := filepath.Join(binderDirPath, componentSource)
parser := syntax.NewParser()
// Load all .pp files in the components' directory
files, err := os.ReadDir(componentSourceDir)
if err != nil {
diagnostics = diagnostics.Append(errorf(nodeRange, err.Error()))
return nil, diagnostics, nil
}
if len(files) == 0 {
diagnostics = diagnostics.Append(errorf(nodeRange, "no files found"))
return nil, diagnostics, nil
}
for _, file := range files {
if file.IsDir() {
continue
}
fileName := file.Name()
path := filepath.Join(componentSourceDir, fileName)
if filepath.Ext(fileName) == ".pp" {
file, err := os.Open(path)
if err != nil {
diagnostics = diagnostics.Append(errorf(nodeRange, err.Error()))
return nil, diagnostics, err
}
err = parser.ParseFile(file, fileName)
if err != nil {
diagnostics = diagnostics.Append(errorf(nodeRange, err.Error()))
return nil, diagnostics, err
}
diags := parser.Diagnostics
if diags.HasErrors() {
return nil, diagnostics, err
}
}
}
opts := []BindOption{
Loader(loader),
DirPath(componentSourceDir),
ComponentBinder(ComponentProgramBinderFromFileSystem()),
}
if args.AllowMissingVariables {
opts = append(opts, AllowMissingVariables)
}
if args.AllowMissingProperties {
opts = append(opts, AllowMissingProperties)
}
if args.SkipResourceTypecheck {
opts = append(opts, SkipResourceTypechecking)
}
if args.PreferOutputVersionedInvokes {
opts = append(opts, PreferOutputVersionedInvokes)
}
if args.SkipInvokeTypecheck {
opts = append(opts, SkipInvokeTypechecking)
}
if args.SkipRangeTypecheck {
opts = append(opts, SkipRangeTypechecking)
}
componentProgram, programDiags, err := BindProgram(parser.Files, opts...)
includeSourceDirectoryInDiagnostics(programDiags, componentSourceDir)
return componentProgram, programDiags, err
}
}
// Replaces the Subject of the input diagnostics from just a file name to the full path of the component directory.
func includeSourceDirectoryInDiagnostics(diags hcl.Diagnostics, componentSourceDir string) {
for _, diag := range diags {
start := hcl.Pos{}
end := hcl.Pos{}
if diag.Subject != nil {
start = diag.Subject.Start
end = diag.Subject.End
componentSourceDir = filepath.Join(componentSourceDir, diag.Subject.Filename)
}
diag.Subject = &hcl.Range{
Filename: componentSourceDir,
Start: start,
End: end,
}
}
}
func (b *binder) bindComponent(node *Component) hcl.Diagnostics {
// When options { range = <expr> } is present
// We create a new scope for binding the component.
// This range expression is potentially a key/value object
// So here we compute the types for the key and value property of that object
var rangeKeyType, rangeValueType model.Type
transformComponentType := func(variableType model.Type) model.Type {
return variableType
}
for _, block := range node.syntax.Body.Blocks {
if block.Type == "options" {
if rng, hasRange := block.Body.Attributes["range"]; hasRange {
expr, _ := model.BindExpression(rng.Expr, b.root, b.tokens, b.options.modelOptions()...)
typ := model.ResolveOutputs(expr.Type())
switch {
case model.InputType(model.BoolType).ConversionFrom(typ) == model.SafeConversion:
// if range expression has a boolean type
// then variable type T of the component becomes Option<T>
transformComponentType = func(variableType model.Type) model.Type {
return model.NewOptionalType(variableType)
}
case model.InputType(model.NumberType).ConversionFrom(typ) == model.SafeConversion:
// if the range expression has a numeric type
// then value of the iteration is a number
// and the variable type T of the component becomes List<T>
rangeValueType = model.IntType
transformComponentType = func(variableType model.Type) model.Type {
return model.NewListType(variableType)
}
default:
// for any other generic type iterations
// we compute the range key and range value types
// and the variable type T of the component becomes List<T>
strict := !b.options.skipRangeTypecheck
rangeKeyType, rangeValueType, _ = model.GetCollectionTypes(typ, rng.Range(), strict)
transformComponentType = func(variableType model.Type) model.Type {
return model.NewListType(variableType)
}
}
}
}
}
scopes := newComponentScopes(b.root, node, rangeKeyType, rangeValueType)
block, diagnostics := model.BindBlock(node.syntax, scopes, b.tokens, b.options.modelOptions()...)
node.Definition = block
// check we can use components and load the program
if b.options.dirPath == "" {
diagnostics = diagnostics.Append(errorf(node.SyntaxNode().Range(),
"components require the binder to have set a directory path"))
return diagnostics
}
if b.options.componentProgramBinder == nil {
diagnostics = diagnostics.Append(errorf(node.SyntaxNode().Range(),
"components require the binder to have set the component program binder"))
return diagnostics
}
componentProgram, programDiags, err := b.options.componentProgramBinder(ComponentProgramBinderArgs{
AllowMissingVariables: b.options.allowMissingVariables,
AllowMissingProperties: b.options.allowMissingProperties,
SkipResourceTypecheck: b.options.skipResourceTypecheck,
SkipInvokeTypecheck: b.options.skipInvokeTypecheck,
SkipRangeTypecheck: b.options.skipRangeTypecheck,
PreferOutputVersionedInvokes: b.options.preferOutputVersionedInvokes,
BinderLoader: b.options.loader,
BinderDirPath: b.options.dirPath,
ComponentSource: node.source,
ComponentNodeRange: node.SyntaxNode().Range(),
})
if err != nil {
diagnostics = diagnostics.Append(errorf(node.SyntaxNode().Range(), err.Error()))
node.VariableType = model.DynamicType
return diagnostics
}
if programDiags.HasErrors() || componentProgram == nil {
diagnostics = diagnostics.Append(errorf(node.SyntaxNode().Range(), programDiags.Error()))
node.VariableType = model.DynamicType
return diagnostics
}
node.Program = componentProgram
programVariableType := componentVariableType(componentProgram)
node.VariableType = transformComponentType(programVariableType)
node.dirPath = filepath.Join(b.options.dirPath, node.source)
componentInputs := componentInputs(componentProgram)
providedInputs := []string{}
var options *model.Block
for _, item := range block.Body.Items {
switch item := item.(type) {
case *model.Attribute:
// logical name is a special attribute
if item.Name == LogicalNamePropertyKey {
logicalName, lDiags := getStringAttrValue(item)
if lDiags != nil {
diagnostics = diagnostics.Append(lDiags)
} else {
node.logicalName = logicalName
}
continue
}
// all other attributes are part of the inputs
_, knownInput := componentInputs[item.Name]
if !knownInput {
diagnostics = append(diagnostics, unsupportedAttribute(item.Name, item.Syntax.NameRange))
return diagnostics
}
node.Inputs = append(node.Inputs, item)
providedInputs = append(providedInputs, item.Name)
case *model.Block:
switch item.Type {
case "options":
if options != nil {
diagnostics = append(diagnostics, duplicateBlock(item.Type, item.Syntax.TypeRange))
} else {
options = item
}
default:
diagnostics = append(diagnostics, unsupportedBlock(item.Type, item.Syntax.TypeRange))
}
}
}
// check that all required inputs are actually set
for inputKey, componentInput := range componentInputs {
if componentInput.required && !contains(providedInputs, inputKey) {
diagnostics = append(diagnostics, missingRequiredAttribute(inputKey, node.SyntaxNode().Range()))
}
}
if options != nil {
resourceOptions, optionsDiags := bindResourceOptions(options)
diagnostics = append(diagnostics, optionsDiags...)
node.Options = resourceOptions
}
return diagnostics
}