github.com/hashicorp/hcl/v2@v2.20.0/ext/dynblock/iteration.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package dynblock
     5  
     6  import (
     7  	"github.com/hashicorp/hcl/v2"
     8  	"github.com/zclconf/go-cty/cty"
     9  )
    10  
    11  type iteration struct {
    12  	IteratorName string
    13  	Key          cty.Value
    14  	Value        cty.Value
    15  	Inherited    map[string]*iteration
    16  }
    17  
    18  func (s *expandSpec) MakeIteration(key, value cty.Value) *iteration {
    19  	return &iteration{
    20  		IteratorName: s.iteratorName,
    21  		Key:          key,
    22  		Value:        value,
    23  		Inherited:    s.inherited,
    24  	}
    25  }
    26  
    27  func (i *iteration) Object() cty.Value {
    28  	return cty.ObjectVal(map[string]cty.Value{
    29  		"key":   i.Key,
    30  		"value": i.Value,
    31  	})
    32  }
    33  
    34  func (i *iteration) EvalContext(base *hcl.EvalContext) *hcl.EvalContext {
    35  	new := base.NewChild()
    36  
    37  	if i != nil {
    38  		new.Variables = map[string]cty.Value{}
    39  		for name, otherIt := range i.Inherited {
    40  			new.Variables[name] = otherIt.Object()
    41  		}
    42  		new.Variables[i.IteratorName] = i.Object()
    43  	}
    44  
    45  	return new
    46  }
    47  
    48  func (i *iteration) MakeChild(iteratorName string, key, value cty.Value) *iteration {
    49  	if i == nil {
    50  		// Create entirely new root iteration, then
    51  		return &iteration{
    52  			IteratorName: iteratorName,
    53  			Key:          key,
    54  			Value:        value,
    55  		}
    56  	}
    57  
    58  	inherited := map[string]*iteration{}
    59  	for name, otherIt := range i.Inherited {
    60  		inherited[name] = otherIt
    61  	}
    62  	inherited[i.IteratorName] = i
    63  	return &iteration{
    64  		IteratorName: iteratorName,
    65  		Key:          key,
    66  		Value:        value,
    67  		Inherited:    inherited,
    68  	}
    69  }