elvish/eval/value.go
Qi Xiao 2ce05eb155 Basic support for float64 as an Elvish type. This addresses #816.
Float64 values are printed like (float64 42). However, the float64
builtin does not actually exist yet, and builtin math functions do not
accept float64 arguments either.

However, after this CL, from-json | to-json is now an identity operator.
Previously:

~> echo '[1]' | from-json | to-json
["1"]

Now:

~> echo '[1]' | from-json | to-json
[1]

It is also possible to use from-json to construct float64 values before
the float64 builtin is actually implemented.
2019-04-09 23:46:04 +01:00

53 lines
1.2 KiB
Go

package eval
import (
"fmt"
"github.com/elves/elvish/eval/vals"
)
// Callable wraps the Call method.
type Callable interface {
// Call calls the receiver in a Frame with arguments and options.
Call(fm *Frame, args []interface{}, opts map[string]interface{}) error
}
var (
// NoArgs is an empty argument list. It can be used as an argument to Call.
NoArgs = []interface{}{}
// NoOpts is an empty option map. It can be used as an argument to Call.
NoOpts = map[string]interface{}{}
)
// Converts a interface{} that results from json.Unmarshal to an Elvish value.
func fromJSONInterface(v interface{}) (interface{}, error) {
switch v := v.(type) {
case nil, bool, string:
return v, nil
case float64:
return v, nil
case []interface{}:
vec := vals.EmptyList
for _, elem := range v {
converted, err := fromJSONInterface(elem)
if err != nil {
return nil, err
}
vec = vec.Cons(converted)
}
return vec, nil
case map[string]interface{}:
m := vals.EmptyMap
for key, val := range v {
convertedVal, err := fromJSONInterface(val)
if err != nil {
return nil, err
}
m = m.Assoc(key, convertedVal)
}
return m, nil
default:
return nil, fmt.Errorf("unexpected json type: %T", v)
}
}