-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
gen_spill.go
75 lines (63 loc) 路 1.55 KB
/
gen_spill.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
package gen
import (
"fmt"
"github.com/hashicorp/hcl/v2"
"github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/model"
)
type spillFunc func(x model.Expression) (string, model.Expression, bool)
type spillTemp struct {
Kind string
Variable *model.Variable
Value model.Expression
}
type spills struct {
counts map[string]int
}
func (s *spills) newTemp(kind string, value model.Expression) *spillTemp {
i := s.counts[kind]
s.counts[kind] = i + 1
v := &model.Variable{
Name: fmt.Sprintf("%s%d", kind, i),
VariableType: value.Type(),
}
return &spillTemp{
Variable: v,
Value: value,
}
}
type spiller struct {
spills *spills
temps []*spillTemp
spill spillFunc
disabled bool
}
func (s *spiller) preVisit(x model.Expression) (model.Expression, hcl.Diagnostics) {
_, isfn := x.(*model.AnonymousFunctionExpression)
if isfn {
s.disabled = true
}
return x, nil
}
func (s *spiller) postVisit(x model.Expression) (model.Expression, hcl.Diagnostics) {
_, isfn := x.(*model.AnonymousFunctionExpression)
if isfn {
s.disabled = false
} else if !s.disabled {
if kind, value, ok := s.spill(x); ok {
t := s.spills.newTemp(kind, value)
s.temps = append(s.temps, t)
return model.VariableReference(t.Variable), nil
}
}
return x, nil
}
func (g *generator) rewriteSpills(
x model.Expression, spill spillFunc,
) (model.Expression, []*spillTemp, hcl.Diagnostics) {
spiller := &spiller{
spills: g.spills,
spill: spill,
}
x, diags := model.VisitExpression(x, spiller.preVisit, spiller.postVisit)
return x, spiller.temps, diags
}