Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add math support to embedded interpolation language #1068

Merged
merged 6 commits into from
Feb 27, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions config/lang/ast/arithmetic.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package ast

import (
"bytes"
"fmt"
)

// Arithmetic represents a node where the result is arithmetic of
// two or more operands in the order given.
type Arithmetic struct {
Op ArithmeticOp
Exprs []Node
Posx Pos
}

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

return v(n)
}

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

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

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

return b.String()
}

func (n *Arithmetic) Type(Scope) (Type, error) {
return TypeInt, nil
}
13 changes: 13 additions & 0 deletions config/lang/ast/arithmetic_op.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package ast

// ArithmeticOp is the operation to use for the math.
type ArithmeticOp int

const (
ArithmeticOpInvalid ArithmeticOp = 0
ArithmeticOpAdd ArithmeticOp = iota
ArithmeticOpSub
ArithmeticOpMul
ArithmeticOpDiv
ArithmeticOpMod
)
98 changes: 98 additions & 0 deletions config/lang/builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,109 @@ func registerBuiltins(scope *ast.BasicScope) *ast.BasicScope {
if scope.FuncMap == nil {
scope.FuncMap = make(map[string]ast.Function)
}

// Implicit conversions
scope.FuncMap["__builtin_FloatToInt"] = builtinFloatToInt()
scope.FuncMap["__builtin_FloatToString"] = builtinFloatToString()
scope.FuncMap["__builtin_IntToFloat"] = builtinIntToFloat()
scope.FuncMap["__builtin_IntToString"] = builtinIntToString()
scope.FuncMap["__builtin_StringToInt"] = builtinStringToInt()

// Math operations
scope.FuncMap["__builtin_IntMath"] = builtinIntMath()
scope.FuncMap["__builtin_FloatMath"] = builtinFloatMath()
return scope
}

func builtinFloatMath() ast.Function {
return ast.Function{
ArgTypes: []ast.Type{ast.TypeInt},
Variadic: true,
VariadicType: ast.TypeFloat,
ReturnType: ast.TypeFloat,
Callback: func(args []interface{}) (interface{}, error) {
op := args[0].(ast.ArithmeticOp)
result := args[1].(float64)
for _, raw := range args[2:] {
arg := raw.(float64)
switch op {
case ast.ArithmeticOpAdd:
result += arg
case ast.ArithmeticOpSub:
result -= arg
case ast.ArithmeticOpMul:
result *= arg
case ast.ArithmeticOpDiv:
result /= arg
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"You don't get fload mod, because if you need float mod in your terraform config, you're doing something very wrong."

^^ This the logic? Sounds about right to me. 😏

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, float modulus doesn't make sense or even work (syntax error in Go).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well there is http://golang.org/pkg/math/#Mod but the logic still stands

}

return result, nil
},
}
}

func builtinIntMath() ast.Function {
return ast.Function{
ArgTypes: []ast.Type{ast.TypeInt},
Variadic: true,
VariadicType: ast.TypeInt,
ReturnType: ast.TypeInt,
Callback: func(args []interface{}) (interface{}, error) {
op := args[0].(ast.ArithmeticOp)
result := args[1].(int)
for _, raw := range args[2:] {
arg := raw.(int)
switch op {
case ast.ArithmeticOpAdd:
result += arg
case ast.ArithmeticOpSub:
result -= arg
case ast.ArithmeticOpMul:
result *= arg
case ast.ArithmeticOpDiv:
result /= arg
case ast.ArithmeticOpMod:
result = result % arg
}
}

return result, nil
},
}
}

func builtinFloatToInt() ast.Function {
return ast.Function{
ArgTypes: []ast.Type{ast.TypeFloat},
ReturnType: ast.TypeInt,
Callback: func(args []interface{}) (interface{}, error) {
return int(args[0].(float64)), nil
},
}
}

func builtinFloatToString() ast.Function {
return ast.Function{
ArgTypes: []ast.Type{ast.TypeFloat},
ReturnType: ast.TypeString,
Callback: func(args []interface{}) (interface{}, error) {
return strconv.FormatFloat(
args[0].(float64), 'g', -1, 64), nil
},
}
}

func builtinIntToFloat() ast.Function {
return ast.Function{
ArgTypes: []ast.Type{ast.TypeInt},
ReturnType: ast.TypeFloat,
Callback: func(args []interface{}) (interface{}, error) {
return float64(args[0].(int)), nil
},
}
}

func builtinIntToString() ast.Function {
return ast.Function{
ArgTypes: []ast.Type{ast.TypeInt},
Expand Down
71 changes: 70 additions & 1 deletion config/lang/check_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ func (v *TypeCheck) visit(raw ast.Node) ast.Node {
var result ast.Node
var err error
switch n := raw.(type) {
case *ast.Arithmetic:
tc := &typeCheckArithmetic{n}
result, err = tc.TypeCheck(v)
case *ast.Call:
tc := &typeCheckCall{n}
result, err = tc.TypeCheck(v)
Expand All @@ -70,7 +73,7 @@ func (v *TypeCheck) visit(raw ast.Node) ast.Node {
default:
tc, ok := raw.(TypeCheckNode)
if !ok {
err = fmt.Errorf("unknown node: %#v", raw)
err = fmt.Errorf("unknown node for type check: %#v", raw)
break
}

Expand All @@ -86,6 +89,72 @@ func (v *TypeCheck) visit(raw ast.Node) ast.Node {
return result
}

type typeCheckArithmetic struct {
n *ast.Arithmetic
}

func (tc *typeCheckArithmetic) TypeCheck(v *TypeCheck) (ast.Node, error) {
// The arguments are on the stack in reverse order, so pop them off.
exprs := make([]ast.Type, len(tc.n.Exprs))
for i, _ := range tc.n.Exprs {
exprs[len(tc.n.Exprs)-1-i] = v.StackPop()
}

// Determine the resulting type we want
mathFunc := "__builtin_IntMath"
mathType := ast.TypeInt
switch v := exprs[0]; v {
case ast.TypeInt:
mathFunc = "__builtin_IntMath"
mathType = v
case ast.TypeFloat:
mathFunc = "__builtin_FloatMath"
mathType = v
default:
return nil, fmt.Errorf(
"Math operations can only be done with ints and floats, got %s",
v)
}

// Verify the args
for i, arg := range exprs {
if arg != mathType {
cn := v.ImplicitConversion(exprs[i], mathType, tc.n.Exprs[i])
if cn != nil {
tc.n.Exprs[i] = cn
continue
}

return nil, fmt.Errorf(
"operand %d should be %s, got %s",
i+1, mathType, arg)
}
}

// Modulo doesn't work for floats
if mathType == ast.TypeFloat && tc.n.Op == ast.ArithmeticOpMod {
return nil, fmt.Errorf("modulo cannot be used with floats")
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah here we go - very explcit


// Return type
v.StackPush(mathType)

// Replace our node with a call to the proper function. This isn't
// type checked but we already verified types.
args := make([]ast.Node, len(tc.n.Exprs)+1)
args[0] = &ast.LiteralNode{
Value: tc.n.Op,
Typex: ast.TypeInt,
Posx: tc.n.Pos(),
}
copy(args[1:], tc.n.Exprs)
return &ast.Call{
Func: mathFunc,
Args: args,
Posx: tc.n.Pos(),
}, nil
}

type typeCheckCall struct {
n *ast.Call
}
Expand Down
8 changes: 7 additions & 1 deletion config/lang/eval.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,12 @@ func Eval(root ast.Node, config *EvalConfig) (interface{}, ast.Type, error) {
}
scope := registerBuiltins(config.GlobalScope)
implicitMap := map[ast.Type]map[ast.Type]string{
ast.TypeFloat: {
ast.TypeInt: "__builtin_FloatToInt",
ast.TypeString: "__builtin_FloatToString",
},
ast.TypeInt: {
ast.TypeFloat: "__builtin_IntToFloat",
ast.TypeString: "__builtin_IntToString",
},
ast.TypeString: {
Expand All @@ -47,7 +52,8 @@ func Eval(root ast.Node, config *EvalConfig) (interface{}, ast.Type, error) {
// Build up the semantic checks for execution
checks := make(
[]SemanticChecker,
len(config.SemanticChecks), len(config.SemanticChecks)+2)
len(config.SemanticChecks),
len(config.SemanticChecks)+2)
copy(checks, config.SemanticChecks)
checks = append(checks, ic.Visit)
checks = append(checks, tv.Visit)
Expand Down
95 changes: 95 additions & 0 deletions config/lang/eval_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,101 @@ func TestEval(t *testing.T) {
ast.TypeString,
},

{
"foo ${42+1}",
nil,
false,
"foo 43",
ast.TypeString,
},

{
"foo ${42-1}",
nil,
false,
"foo 41",
ast.TypeString,
},

{
"foo ${42*2}",
nil,
false,
"foo 84",
ast.TypeString,
},

{
"foo ${42/2}",
nil,
false,
"foo 21",
ast.TypeString,
},

{
"foo ${42%4}",
nil,
false,
"foo 2",
ast.TypeString,
},

{
"foo ${42.0+1.0}",
nil,
false,
"foo 43",
ast.TypeString,
},

{
"foo ${42.0+1}",
nil,
false,
"foo 43",
ast.TypeString,
},

{
"foo ${42+1.0}",
nil,
false,
"foo 43",
ast.TypeString,
},

{
"foo ${42+2*2}",
nil,
false,
"foo 88",
ast.TypeString,
},

{
"foo ${42+(2*2)}",
nil,
false,
"foo 46",
ast.TypeString,
},

{
"foo ${bar+1}",
&ast.BasicScope{
VarMap: map[string]ast.Variable{
"bar": ast.Variable{
Value: 41,
Type: ast.TypeInt,
},
},
},
false,
"foo 42",
ast.TypeString,
},

{
"foo ${rand()}",
&ast.BasicScope{
Expand Down
Loading