aboutsummaryrefslogtreecommitdiffhomepage
path: root/vendor/github.com/hashicorp/hcl2/ext/dynblock/iteration.go
blob: 7056d336064d0de61fc44a95f8bd5fd76f5b55b7 (plain) (blame)
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
package dynblock

import (
	"github.com/hashicorp/hcl2/hcl"
	"github.com/zclconf/go-cty/cty"
)

type iteration struct {
	IteratorName string
	Key          cty.Value
	Value        cty.Value
	Inherited    map[string]*iteration
}

func (s *expandSpec) MakeIteration(key, value cty.Value) *iteration {
	return &iteration{
		IteratorName: s.iteratorName,
		Key:          key,
		Value:        value,
		Inherited:    s.inherited,
	}
}

func (i *iteration) Object() cty.Value {
	return cty.ObjectVal(map[string]cty.Value{
		"key":   i.Key,
		"value": i.Value,
	})
}

func (i *iteration) EvalContext(base *hcl.EvalContext) *hcl.EvalContext {
	new := base.NewChild()

	if i != nil {
		new.Variables = map[string]cty.Value{}
		for name, otherIt := range i.Inherited {
			new.Variables[name] = otherIt.Object()
		}
		new.Variables[i.IteratorName] = i.Object()
	}

	return new
}

func (i *iteration) MakeChild(iteratorName string, key, value cty.Value) *iteration {
	if i == nil {
		// Create entirely new root iteration, then
		return &iteration{
			IteratorName: iteratorName,
			Key:          key,
			Value:        value,
		}
	}

	inherited := map[string]*iteration{}
	for name, otherIt := range i.Inherited {
		inherited[name] = otherIt
	}
	inherited[i.IteratorName] = i
	return &iteration{
		IteratorName: iteratorName,
		Key:          key,
		Value:        value,
		Inherited:    inherited,
	}
}