Handle simple string slice

This commit is contained in:
Thomas Pelletier
2021-03-13 18:45:03 -05:00
parent 21d3e85fcc
commit d8be04d4a8
4 changed files with 145 additions and 33 deletions
+54 -24
View File
@@ -8,16 +8,18 @@ import (
)
func FromAst(tree ast.Root, target interface{}) error {
x := reflect.ValueOf(target)
if x.Kind() != reflect.Ptr {
return fmt.Errorf("need to target a pointer, not %s", x.Kind())
v := reflect.ValueOf(target)
if v.Kind() != reflect.Ptr {
return fmt.Errorf("need to target a pointer, not %s", v.Kind())
}
if x.IsNil() {
if v.IsNil() {
return fmt.Errorf("target pointer must be non-nil")
}
x := valueTarget(v.Elem())
for _, node := range tree {
err := topLevelNode(x, &node)
err := unmarshalTopLevelNode(x, &node)
if err != nil {
return err
}
@@ -26,33 +28,67 @@ func FromAst(tree ast.Root, target interface{}) error {
return nil
}
func topLevelNode(x reflect.Value, node *ast.Node) error {
if x.Kind() != reflect.Ptr {
panic("topLevelNode should receive target, which should be a pointer")
}
if x.IsNil() {
panic("topLevelNode should receive target, which should not be a nil pointer")
}
func unmarshalTopLevelNode(x target, node *ast.Node) error {
switch node.Kind {
case ast.Table:
panic("TODO")
case ast.ArrayTable:
panic("TODO")
case ast.KeyValue:
return keyValue(x, node)
return unmarshalKeyValue(x, node)
default:
panic(fmt.Errorf("this should not be a top level node type: %s", node.Kind))
}
}
func keyValue(x reflect.Value, node *ast.Node) error {
func unmarshalKeyValue(x target, node *ast.Node) error {
assertNode(ast.KeyValue, node)
assertPtr(x)
key := node.Key()
key = key
// TODO
var err error
for _, n := range key {
x, err = scopeTarget(x, string(n.Data))
if err != nil {
return err
}
}
return unmarshalValue(x, node.Value())
}
func unmarshalValue(x target, node *ast.Node) error {
switch node.Kind {
case ast.String:
return unmarshalString(x, node)
case ast.Array:
return unmarshalArray(x, node)
default:
panic(fmt.Errorf("unhandled unmarshalValue kind %s", node.Kind))
}
}
func unmarshalString(x target, node *ast.Node) error {
assertNode(ast.String, node)
return x.setString(string(node.Data))
}
func unmarshalArray(x target, node *ast.Node) error {
assertNode(ast.Array, node)
x.ensure()
for _, n := range node.Children {
v, err := x.pushNew()
if err != nil {
return err
}
err = unmarshalValue(v, &n)
if err != nil {
return err
}
}
return nil
}
@@ -61,9 +97,3 @@ func assertNode(expected ast.Kind, node *ast.Node) {
panic(fmt.Errorf("expected node of kind %s, not %s", expected, node.Kind))
}
}
func assertPtr(x reflect.Value) {
if x.Kind() != reflect.Ptr {
panic(fmt.Errorf("should be a pointer, not a %s", x.Kind()))
}
}