From d413d2ffe7baa6bac63aeb9213b3cfa98019a0a4 Mon Sep 17 00:00:00 2001 From: Chyroc Date: Mon, 28 Jan 2019 10:39:45 +0800 Subject: [PATCH] feat: add builtin function: type --- docs/builtins.md | 11 +++++++++++ objects/builtin_type.go | 9 +++++++++ objects/builtins.go | 4 ++++ runtime/vm_builtin_test.go | 13 +++++++++++++ 4 files changed, 37 insertions(+) create mode 100644 objects/builtin_type.go diff --git a/docs/builtins.md b/docs/builtins.md index e512705..62b6281 100644 --- a/docs/builtins.md +++ b/docs/builtins.md @@ -91,6 +91,17 @@ Tries to convert an object to string object. See [this](https://github.com/d5/te x := string(123) // v == "123" ``` +## type_name + +Returns the type_name of an object. + +```golang +type_name(1) // int +type_name("str") // string +type_name([1, 2, 3]) // array +``` + + Optionally it can take the second argument, which will be returned if the first argument cannot be converted to string. Note that the second argument does not have to be string. ```golang diff --git a/objects/builtin_type.go b/objects/builtin_type.go new file mode 100644 index 0000000..376c26b --- /dev/null +++ b/objects/builtin_type.go @@ -0,0 +1,9 @@ +package objects + +func builtinTypeName(args ...Object) (Object, error) { + if len(args) != 1 { + return nil, ErrWrongNumArguments + } + + return &String{Value: args[0].TypeName()}, nil +} diff --git a/objects/builtins.go b/objects/builtins.go index 428cc09..11b7f22 100644 --- a/objects/builtins.go +++ b/objects/builtins.go @@ -96,4 +96,8 @@ var Builtins = []NamedBuiltinFunc{ Name: "from_json", Func: builtinFromJSON, }, + { + Name: "type_name", + Func: builtinTypeName, + }, } diff --git a/runtime/vm_builtin_test.go b/runtime/vm_builtin_test.go index dcefff8..5e853f2 100644 --- a/runtime/vm_builtin_test.go +++ b/runtime/vm_builtin_test.go @@ -149,4 +149,17 @@ func TestBuiltinFunction(t *testing.T) { expect(t, `out = sprintf("foo %v %d", [1, "bar", true], 19)`, "foo [1 bar true] 19") expectError(t, `sprintf(1)`) // format has to be String expectError(t, `sprintf('c')`) // format has to be String + + // type_name + expect(t, `out = type_name(1)`, "int") + expect(t, `out = type_name(1.1)`, "float") + expect(t, `out = type_name("a")`, "string") + expect(t, `out = type_name([1,2,3])`, "array") + expect(t, `out = type_name({k:1})`, "map") + expect(t, `out = type_name('a')`, "char") + expect(t, `out = type_name(true)`, "bool") + expect(t, `out = type_name(false)`, "bool") + expect(t, `out = type_name(bytes( 1))`, "bytes") + expect(t, `out = type_name(undefined)`, "undefined") + expect(t, `out = type_name(error("err"))`, "error") }