Improve types pkg (#668)

This commit is contained in:
Anton Medvedev
2024-06-05 01:14:25 +02:00
committed by GitHub
parent c953d0dde1
commit d0aa2e9136
7 changed files with 150 additions and 59 deletions
+1 -1
View File
@@ -1074,7 +1074,7 @@ func TestCheck_types(t *testing.T) {
env := types.Map{
"foo": types.StrictMap{
"bar": types.Map{
"baz": "",
"baz": types.String,
},
},
}
-47
View File
@@ -1,47 +0,0 @@
package nature
import (
"fmt"
"reflect"
"github.com/expr-lang/expr/types"
)
func Of(value any) Nature {
if value == nil {
return Nature{Nil: true}
}
v := reflect.ValueOf(value)
switch v.Kind() {
case reflect.Map:
_, strict := value.(types.StrictMap)
fields := make(map[string]Nature, v.Len())
for _, key := range v.MapKeys() {
elem := v.MapIndex(key)
if !elem.IsValid() || !elem.CanInterface() {
panic(fmt.Sprintf("invalid map value: %s", key))
}
face := elem.Interface()
switch face.(type) {
case types.Map, types.StrictMap:
fields[key.String()] = Of(face)
default:
if face == nil {
fields[key.String()] = Nature{Nil: true}
continue
}
fields[key.String()] = Nature{Type: reflect.TypeOf(face)}
}
}
return Nature{
Type: v.Type(),
Fields: fields,
Strict: strict,
}
}
return Nature{Type: v.Type()}
}