github.com/myhau/pulumi/pkg/v3@v3.70.2-0.20221116134521-f2775972e587/codegen/go/gen_program_ternaries.go (about)

     1  package gen
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/hashicorp/hcl/v2"
     7  	"github.com/hashicorp/hcl/v2/hclsyntax"
     8  	"github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/model"
     9  	"github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/syntax"
    10  )
    11  
    12  type ternaryTemp struct {
    13  	Name  string
    14  	Value *model.ConditionalExpression
    15  }
    16  
    17  func (tt *ternaryTemp) Type() model.Type {
    18  	return tt.Value.Type()
    19  }
    20  
    21  func (tt *ternaryTemp) Traverse(traverser hcl.Traverser) (model.Traversable, hcl.Diagnostics) {
    22  	return tt.Type().Traverse(traverser)
    23  }
    24  
    25  func (tt *ternaryTemp) SyntaxNode() hclsyntax.Node {
    26  	return syntax.None
    27  }
    28  
    29  type tempSpiller struct {
    30  	temps []*ternaryTemp
    31  	count int
    32  }
    33  
    34  func (ta *tempSpiller) spillExpression(x model.Expression) (model.Expression, hcl.Diagnostics) {
    35  	var temp *ternaryTemp
    36  	switch x := x.(type) {
    37  	case *model.ConditionalExpression:
    38  		x.Condition, _ = ta.spillExpression(x.Condition)
    39  		x.TrueResult, _ = ta.spillExpression(x.TrueResult)
    40  		x.FalseResult, _ = ta.spillExpression(x.FalseResult)
    41  
    42  		temp = &ternaryTemp{
    43  			Name:  fmt.Sprintf("tmp%d", ta.count),
    44  			Value: x,
    45  		}
    46  		ta.temps = append(ta.temps, temp)
    47  		ta.count++
    48  	default:
    49  		return x, nil
    50  	}
    51  	return &model.ScopeTraversalExpression{
    52  		RootName:  temp.Name,
    53  		Traversal: hcl.Traversal{hcl.TraverseRoot{Name: ""}},
    54  		Parts:     []model.Traversable{temp},
    55  	}, nil
    56  }
    57  
    58  func (g *generator) rewriteTernaries(
    59  	x model.Expression,
    60  	spiller *tempSpiller,
    61  ) (model.Expression, []*ternaryTemp, hcl.Diagnostics) {
    62  	spiller.temps = nil
    63  	x, diags := model.VisitExpression(x, spiller.spillExpression, nil)
    64  
    65  	return x, spiller.temps, diags
    66  
    67  }