/
gen_program_lower.go
59 lines (50 loc) 路 2.07 KB
/
gen_program_lower.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
package python
import (
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/pulumi/pulumi/pkg/codegen/hcl2"
"github.com/pulumi/pulumi/pkg/codegen/hcl2/model"
"github.com/pulumi/pulumi/sdk/go/common/util/contract"
)
// parseProxyApply attempts to match the given parsed apply against the pattern (call __applyArg 0). If the call
// matches, it returns the ScopeTraversalExpression that corresponds to argument zero, which can then be generated as a
// proxied apply call.
func (g *generator) parseProxyApply(args []*model.ScopeTraversalExpression,
then *model.AnonymousFunctionExpression) (*model.ScopeTraversalExpression, bool) {
if len(args) != 1 {
return nil, false
}
thenTraversal, ok := then.Body.(*model.ScopeTraversalExpression)
if !ok || thenTraversal.Parts[0] != then.Parameters[0] {
return nil, false
}
traversal := hcl.TraversalJoin(args[0].Syntax.Traversal, thenTraversal.Syntax.Traversal[1:])
expr, diags := g.program.BindExpression(&hclsyntax.ScopeTraversalExpr{
Traversal: traversal,
SrcRange: traversal.SourceRange(),
})
contract.Assert(len(diags) == 0)
return expr.(*model.ScopeTraversalExpression), true
}
// lowerProxyApplies lowers certain calls to the apply intrinsic into proxied property accesses. Concretely, this boils
// down to rewriting the following shape:
// - (call __apply (resource variable access) (call __applyArg 0))
// into
// - (resource variable access)
func (g *generator) lowerProxyApplies(expr model.Expression) (model.Expression, hcl.Diagnostics) {
rewriter := func(expr model.Expression) (model.Expression, hcl.Diagnostics) {
// Ignore the node if it is not a call to the apply intrinsic.
apply, ok := expr.(*model.FunctionCallExpression)
if !ok || apply.Name != hcl2.IntrinsicApply {
return expr, nil
}
// Parse the apply call.
args, then := hcl2.ParseApplyCall(apply)
// Attempt to match (call __apply (rvar) (call __applyArg 0))
if v, ok := g.parseProxyApply(args, then); ok {
return v, nil
}
return expr, nil
}
return model.VisitExpression(expr, model.IdentityVisitor, rewriter)
}