From 339b9cfc348ca5bd6912cc6def6b0210dcdd7908 Mon Sep 17 00:00:00 2001 From: Martin Atkins Date: Wed, 20 Sep 2017 16:22:05 -0700 Subject: [PATCH] hcl: StaticExpr function for making synthetic expressions Sometimes we want an expression that just wraps a static value, e.g. for testing or to provide a default value for a missing attribute. StaticExpr gives us a convenient way to do that, returning a value that implements the Expression interface by returning just the given static value. --- hcl/static_expr.go | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 hcl/static_expr.go diff --git a/hcl/static_expr.go b/hcl/static_expr.go new file mode 100644 index 0000000..98ada87 --- /dev/null +++ b/hcl/static_expr.go @@ -0,0 +1,40 @@ +package hcl + +import ( + "github.com/zclconf/go-cty/cty" +) + +type staticExpr struct { + val cty.Value + rng Range +} + +// StaticExpr returns an Expression that always evaluates to the given value. +// +// This is useful to substitute default values for expressions that are +// not explicitly given in configuration and thus would otherwise have no +// Expression to return. +// +// Since expressions are expected to have a source range, the caller must +// provide one. Ideally this should be a real source range, but it can +// be a synthetic one (with an empty-string filename) if no suitable range +// is available. +func StaticExpr(val cty.Value, rng Range) Expression { + return staticExpr{val, rng} +} + +func (e staticExpr) Value(ctx *EvalContext) (cty.Value, Diagnostics) { + return e.val, nil +} + +func (e staticExpr) Variables() []Traversal { + return nil +} + +func (e staticExpr) Range() Range { + return e.rng +} + +func (e staticExpr) StartRange() Range { + return e.rng +}