config/lang: string to int

This commit is contained in:
Mitchell Hashimoto 2015-01-14 12:02:26 -08:00
parent d12bf66403
commit 591610deea
3 changed files with 40 additions and 0 deletions

View File

@ -6,11 +6,14 @@ import (
"github.com/hashicorp/terraform/config/lang/ast" "github.com/hashicorp/terraform/config/lang/ast"
) )
// NOTE: All builtins are tested in engine_test.go
func registerBuiltins(scope *Scope) { func registerBuiltins(scope *Scope) {
if scope.FuncMap == nil { if scope.FuncMap == nil {
scope.FuncMap = make(map[string]Function) scope.FuncMap = make(map[string]Function)
} }
scope.FuncMap["__builtin_IntToString"] = builtinIntToString() scope.FuncMap["__builtin_IntToString"] = builtinIntToString()
scope.FuncMap["__builtin_StringToInt"] = builtinStringToInt()
} }
func builtinIntToString() Function { func builtinIntToString() Function {
@ -22,3 +25,18 @@ func builtinIntToString() Function {
}, },
} }
} }
func builtinStringToInt() Function {
return Function{
ArgTypes: []ast.Type{ast.TypeInt},
ReturnType: ast.TypeString,
Callback: func(args []interface{}) (interface{}, error) {
v, err := strconv.ParseInt(args[0].(string), 0, 0)
if err != nil {
return nil, err
}
return int(v), nil
},
}
}

View File

@ -33,6 +33,9 @@ func (e *Engine) Execute(root ast.Node) (interface{}, ast.Type, error) {
ast.TypeInt: { ast.TypeInt: {
ast.TypeString: "__builtin_IntToString", ast.TypeString: "__builtin_IntToString",
}, },
ast.TypeString: {
ast.TypeInt: "__builtin_StringToInt",
},
} }
// Build our own semantic checks that we always run // Build our own semantic checks that we always run

View File

@ -2,6 +2,7 @@ package lang
import ( import (
"reflect" "reflect"
"strconv"
"testing" "testing"
"github.com/hashicorp/terraform/config/lang/ast" "github.com/hashicorp/terraform/config/lang/ast"
@ -94,6 +95,24 @@ func TestEngineExecute(t *testing.T) {
"foo 42", "foo 42",
ast.TypeString, ast.TypeString,
}, },
{
`foo ${foo("42")}`,
&Scope{
FuncMap: map[string]Function{
"foo": Function{
ArgTypes: []ast.Type{ast.TypeInt},
ReturnType: ast.TypeString,
Callback: func(args []interface{}) (interface{}, error) {
return strconv.FormatInt(int64(args[0].(int)), 10), nil
},
},
},
},
false,
"foo 42",
ast.TypeString,
},
} }
for _, tc := range cases { for _, tc := range cases {