aboutsummaryrefslogtreecommitdiffhomepage
path: root/vendor/github.com/hashicorp/hil/ast/output.go
blob: 1e27f970b33b53a067012a461d8911d1fa64f986 (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
67
68
69
70
71
72
73
74
75
76
77
78
package ast

import (
	"bytes"
	"fmt"
)

// Output represents the root node of all interpolation evaluations. If the
// output only has one expression which is either a TypeList or TypeMap, the
// Output can be type-asserted to []interface{} or map[string]interface{}
// respectively. Otherwise the Output evaluates as a string, and concatenates
// the evaluation of each expression.
type Output struct {
	Exprs []Node
	Posx  Pos
}

func (n *Output) Accept(v Visitor) Node {
	for i, expr := range n.Exprs {
		n.Exprs[i] = expr.Accept(v)
	}

	return v(n)
}

func (n *Output) Pos() Pos {
	return n.Posx
}

func (n *Output) GoString() string {
	return fmt.Sprintf("*%#v", *n)
}

func (n *Output) String() string {
	var b bytes.Buffer
	for _, expr := range n.Exprs {
		b.WriteString(fmt.Sprintf("%s", expr))
	}

	return b.String()
}

func (n *Output) Type(s Scope) (Type, error) {
	// Special case no expressions for backward compatibility
	if len(n.Exprs) == 0 {
		return TypeString, nil
	}

	// Special case a single expression of types list or map
	if len(n.Exprs) == 1 {
		exprType, err := n.Exprs[0].Type(s)
		if err != nil {
			return TypeInvalid, err
		}
		switch exprType {
		case TypeList:
			return TypeList, nil
		case TypeMap:
			return TypeMap, nil
		}
	}

	// Otherwise ensure all our expressions are strings
	for index, expr := range n.Exprs {
		exprType, err := expr.Type(s)
		if err != nil {
			return TypeInvalid, err
		}
		// We only look for things we know we can't coerce with an implicit conversion func
		if exprType == TypeList || exprType == TypeMap {
			return TypeInvalid, fmt.Errorf(
				"multi-expression HIL outputs may only have string inputs: %d is type %s",
				index, exprType)
		}
	}

	return TypeString, nil
}