Back to godoc.org
github.com/hashicorp/hil

Package hil

v0.0.0 (a18a1cd)
Latest Go to latest
Published: Apr 23, 2020 | License: MPL-2.0 | Module: github.com/hashicorp/hil

Overview

Example (Basic)

Code:

input := "${6 + 2}"

tree, err := hil.Parse(input)
if err != nil {
	log.Fatal(err)
}

result, err := hil.Eval(tree, &hil.EvalConfig{})
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Type: %s\n", result.Type)
fmt.Printf("Value: %s\n", result.Value)
Type: TypeString
Value: 8
Example (Functions)

Code:

input := "${lower(var.test)} - ${6 + 2}"

tree, err := hil.Parse(input)
if err != nil {
	log.Fatal(err)
}

lowerCase := ast.Function{
	ArgTypes:   []ast.Type{ast.TypeString},
	ReturnType: ast.TypeString,
	Variadic:   false,
	Callback: func(inputs []interface{}) (interface{}, error) {
		input := inputs[0].(string)
		return strings.ToLower(input), nil
	},
}

config := &hil.EvalConfig{
	GlobalScope: &ast.BasicScope{
		VarMap: map[string]ast.Variable{
			"var.test": ast.Variable{
				Type:  ast.TypeString,
				Value: "TEST STRING",
			},
		},
		FuncMap: map[string]ast.Function{
			"lower": lowerCase,
		},
	},
}

result, err := hil.Eval(tree, config)
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Type: %s\n", result.Type)
fmt.Printf("Value: %s\n", result.Value)
Type: TypeString
Value: test string - 8
Example (Variables)

Code:

input := "${var.test} - ${6 + 2}"

tree, err := hil.Parse(input)
if err != nil {
	log.Fatal(err)
}

config := &hil.EvalConfig{
	GlobalScope: &ast.BasicScope{
		VarMap: map[string]ast.Variable{
			"var.test": ast.Variable{
				Type:  ast.TypeString,
				Value: "TEST STRING",
			},
		},
	},
}

result, err := hil.Eval(tree, config)
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Type: %s\n", result.Type)
fmt.Printf("Value: %s\n", result.Value)
Type: TypeString
Value: TEST STRING - 8

Index

Examples

Package Files

Constants

const UnknownValue = "74D93920-ED26-11E3-AC10-0800200C9A66"

UnknownValue is a sentinel value that can be used to denote that a value of a variable (or map element, list element, etc.) is unknown. This will always have the type ast.TypeUnknown.

Variables

var InvalidResult = EvaluationResult{Type: TypeInvalid, Value: nil}

InvalidResult is a structure representing the result of a HIL interpolation which has invalid syntax, missing variables, or some other type of error. The error is described out of band in the accompanying error return value.

func FixedValueTransform

func FixedValueTransform(root ast.Node, Value *ast.LiteralNode) ast.Node

FixedValueTransform transforms an AST to return a fixed value for all interpolations. i.e. you can make "hi ${anything}" always turn into "hi foo".

The primary use case for this is for config validations where you can verify that interpolations result in a certain type of string.

func InterfaceToVariable

func InterfaceToVariable(input interface{}) (ast.Variable, error)

func Parse

func Parse(v string) (ast.Node, error)

Parse parses the given program and returns an executable AST tree.

Syntax errors are returned with error having the dynamic type *parser.ParseError, which gives the caller access to the source position where the error was found, which allows (for example) combining it with a known source filename to add context to the error message.

func ParseWithPosition

func ParseWithPosition(v string, pos ast.Pos) (ast.Node, error)

ParseWithPosition is like Parse except that it overrides the source row and column position of the first character in the string, which should be 1-based.

This can be used when HIL is embedded in another language and the outer parser knows the row and column where the HIL expression started within the overall source file.

func VariableToInterface

func VariableToInterface(input ast.Variable) (interface{}, error)

func Walk

func Walk(v interface{}, cb WalkFn) error

Walk will walk an arbitrary Go structure and parse any string as an HIL program and call the callback cb to determine what to replace it with.

This function is very useful for arbitrary HIL program interpolation across a complex configuration structure. Due to the heavy use of reflection in this function, it is recommend to write many unit tests with your typical configuration structures to hilp mitigate the risk of panics.

type EvalConfig

type EvalConfig struct {
	// GlobalScope is the global scope of execution for evaluation.
	GlobalScope *ast.BasicScope

	// SemanticChecks is a list of additional semantic checks that will be run
	// on the tree prior to evaluating it. The type checker, identifier checker,
	// etc. will be run before these automatically.
	SemanticChecks []SemanticChecker
}

EvalConfig is the configuration for evaluating.

type EvalNode

type EvalNode interface {
	Eval(ast.Scope, *ast.Stack) (interface{}, ast.Type, error)
}

EvalNode is the interface that must be implemented by any ast.Node to support evaluation. This will be called in visitor pattern order. The result of each call to Eval is automatically pushed onto the stack as a LiteralNode. Pop elements off the stack to get child values.

type EvalType

type EvalType uint32

EvalType represents the type of the output returned from a HIL evaluation.

const (
	TypeInvalid EvalType = 0
	TypeString  EvalType = 1 << iota
	TypeBool
	TypeList
	TypeMap
	TypeUnknown
)

func (EvalType) String

func (i EvalType) String() string

type EvaluationResult

type EvaluationResult struct {
	Type  EvalType
	Value interface{}
}

EvaluationResult is a struct returned from the hil.Eval function, representing the result of an interpolation. Results are returned in their "natural" Go structure rather than in terms of the HIL AST. For the types currently implemented, this means that the Value field can be interpreted as the following Go types:

TypeInvalid: undefined
TypeString:  string
TypeList:    []interface{}
TypeMap:     map[string]interface{}
TypBool:     bool

func Eval

func Eval(root ast.Node, config *EvalConfig) (EvaluationResult, error)

type IdentifierCheck

type IdentifierCheck struct {
	Scope ast.Scope
	// contains filtered or unexported fields
}

IdentifierCheck is a SemanticCheck that checks that all identifiers resolve properly and that the right number of arguments are passed to functions.

func (*IdentifierCheck) Visit

func (c *IdentifierCheck) Visit(root ast.Node) error

type SemanticChecker

type SemanticChecker func(ast.Node) error

SemanticChecker is the type that must be implemented to do a semantic check on an AST tree. This will be called with the root node.

type TypeCheck

type TypeCheck struct {
	Scope ast.Scope

	// Implicit is a map of implicit type conversions that we can do,
	// and that shouldn't error. The key of the first map is the from type,
	// the key of the second map is the to type, and the final string
	// value is the function to call (which must be registered in the Scope).
	Implicit map[ast.Type]map[ast.Type]string

	// Stack of types. This shouldn't be used directly except by implementations
	// of TypeCheckNode.
	Stack []ast.Type
	// contains filtered or unexported fields
}

TypeCheck implements ast.Visitor for type checking an AST tree. It requires some configuration to look up the type of nodes.

It also optionally will not type error and will insert an implicit type conversions for specific types if specified by the Implicit field. Note that this is kind of organizationally weird to put into this structure but we'd rather do that than duplicate the type checking logic multiple times.

func (*TypeCheck) ImplicitConversion

func (v *TypeCheck) ImplicitConversion(
	actual ast.Type, expected ast.Type, n ast.Node) ast.Node

func (*TypeCheck) StackPeek

func (v *TypeCheck) StackPeek() ast.Type

func (*TypeCheck) StackPop

func (v *TypeCheck) StackPop() ast.Type

func (*TypeCheck) StackPush

func (v *TypeCheck) StackPush(t ast.Type)

func (*TypeCheck) Visit

func (v *TypeCheck) Visit(root ast.Node) error

type TypeCheckNode

type TypeCheckNode interface {
	TypeCheck(*TypeCheck) (ast.Node, error)
}

TypeCheckNode is the interface that must be implemented by any ast.Node that wants to support type-checking. If the type checker encounters a node that doesn't implement this, it will error.

type WalkData

type WalkData struct {
	// Root is the parsed root of this HIL program
	Root ast.Node

	// Location is the location within the structure where this
	// value was found. This can be used to modify behavior within
	// slices and so on.
	Location reflectwalk.Location

	// The below two values must be set by the callback to have any effect.
	//
	// Replace, if true, will replace the value in the structure with
	// ReplaceValue. It is up to the caller to make sure this is a string.
	Replace      bool
	ReplaceValue string
}

WalkData is the structure passed to the callback of the Walk function.

This structure contains data passed in as well as fields that are expected to be written by the caller as a result. Please see the documentation for each field for more information.

type WalkFn

type WalkFn func(*WalkData) error

WalkFn is the type of function to pass to Walk. Modify fields within WalkData to control whether replacement happens.

Documentation was rendered with GOOS=linux and GOARCH=amd64.

Jump to identifier

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to identifier