Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(bindnode): support listpairs struct representation #514

Merged
merged 6 commits into from
Jun 5, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions node/bindnode/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,10 @@ var (

_ datamodel.ListAssembler = (*_listAssembler)(nil)
_ datamodel.ListAssembler = (*_listAssemblerRepr)(nil)
_ datamodel.ListAssembler = (*_listStructAssemblerRepr)(nil)
_ datamodel.ListIterator = (*_listIterator)(nil)
_ datamodel.ListIterator = (*_tupleIteratorRepr)(nil)
_ datamodel.ListIterator = (*_listpairsIteratorRepr)(nil)

_ datamodel.MapAssembler = (*_unionAssembler)(nil)
_ datamodel.MapAssembler = (*_unionAssemblerRepr)(nil)
Expand Down
101 changes: 96 additions & 5 deletions node/bindnode/repr.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func (w *_nodeRepr) Kind() datamodel.Kind {
return datamodel.Kind_String
case schema.StructRepresentation_Map:
return datamodel.Kind_Map
case schema.StructRepresentation_Tuple:
case schema.StructRepresentation_Tuple, schema.StructRepresentation_ListPairs:
return datamodel.Kind_List
case schema.UnionRepresentation_Keyed:
return datamodel.Kind_Map
Expand Down Expand Up @@ -174,6 +174,31 @@ func (w *_nodeRepr) LookupByIndex(idx int64) (datamodel.Node, error) {
return nil, err
}
return reprNode(v), nil
case schema.StructRepresentation_ListPairs:
fields := w.schemaType.(*schema.TypeStruct).Fields()
if idx < 0 || int(idx) >= len(fields)*2 {
return nil, datamodel.ErrNotExists{Segment: datamodel.PathSegmentOfInt(idx)}
}
isName := idx%2 == 0
idx = idx / 2
var curField int64
for _, field := range fields {
value, err := (*_node)(w).LookupByString(field.Name())
if err != nil {
return nil, err
}
if value.IsAbsent() {
continue
}
if curField == idx {
if isName {
return basicnode.NewString(field.Name()), nil
}
return reprNode(value), nil
}
curField++
}
return nil, datamodel.ErrNotExists{Segment: datamodel.PathSegmentOfInt(idx)}
default:
v, err := (*_node)(w).LookupByIndex(idx)
if err != nil {
Expand Down Expand Up @@ -272,6 +297,11 @@ func (w *_nodeRepr) ListIterator() datamodel.ListIterator {
iter := _tupleIteratorRepr{cfg: w.cfg, schemaType: typ, fields: typ.Fields(), val: w.val}
iter.reprEnd = int(w.lengthMinusTrailingAbsents())
return &iter
case schema.StructRepresentation_ListPairs:
typ := w.schemaType.(*schema.TypeStruct)
iter := _listpairsIteratorRepr{cfg: w.cfg, schemaType: typ, fields: typ.Fields(), val: w.val}
iter.reprEnd = int(w.lengthMinusTrailingAbsents()) * 2
return &iter
default:
iter, _ := (*_node)(w).ListIterator().(*_listIterator)
if iter == nil {
Expand Down Expand Up @@ -320,20 +350,69 @@ type _tupleIteratorRepr struct {

func (w *_tupleIteratorRepr) Next() (index int64, value datamodel.Node, _ error) {
_skipAbsent:
idx := w.nextIndex
_, value, err := (*_structIterator)(w).Next()
if err != nil {
return 0, nil, err
}
if w.nextIndex > w.reprEnd {
goto _skipAbsent
}
return int64(w.nextIndex), reprNode(value), nil
return int64(idx), reprNode(value), nil
}

func (w *_tupleIteratorRepr) Done() bool {
return w.nextIndex >= w.reprEnd
}

type _listpairsIteratorRepr struct {
cfg config
schemaType *schema.TypeStruct
fields []schema.StructField
val reflect.Value // non-pointer
nextIndex int

// these are only used in repr.go
reprEnd int
}

func (w *_listpairsIteratorRepr) Next() (index int64, value datamodel.Node, _ error) {
_skipAbsent:
idx := w.nextIndex
if w.nextIndex%2 == 0 {
// field name
if w.Done() {
return 0, nil, datamodel.ErrIteratorOverread{}
}
field := w.fields[w.nextIndex/2]
w.nextIndex++
if field.IsOptional() {
val := w.val.Field(w.nextIndex)
if val.IsNil() {
goto _skipAbsent
}
}
key := basicnode.NewString(field.Name())
return int64(idx), key, nil
}
// field value
// set nextIndex to a value that will be correct for a _structIterator#Next() call.
w.nextIndex = (idx - 1) / 2
_, value, err := (*_structIterator)(w).Next()
w.nextIndex = idx + 1
if err != nil {
return 0, nil, err
}
if value.IsAbsent() || w.nextIndex > w.reprEnd {
goto _skipAbsent
}
return int64(idx), reprNode(value), nil
}

func (w *_listpairsIteratorRepr) Done() bool {
return w.nextIndex >= w.reprEnd
}

func (w *_nodeRepr) lengthMinusTrailingAbsents() int64 {
fields := w.schemaType.(*schema.TypeStruct).Fields()
for i := len(fields) - 1; i >= 0; i-- {
Expand All @@ -353,6 +432,8 @@ func (w *_nodeRepr) Length() int64 {
return w.lengthMinusAbsents()
case schema.StructRepresentation_Tuple:
return w.lengthMinusTrailingAbsents()
case schema.StructRepresentation_ListPairs:
return w.lengthMinusAbsents() * 2
case schema.UnionRepresentation_Keyed:
return (*_node)(w).Length()
case schema.UnionRepresentation_Kinded:
Expand Down Expand Up @@ -625,7 +706,7 @@ func (w *_assemblerRepr) BeginList(sizeHint int64) (datamodel.ListAssembler, err
switch stg := reprStrategy(w.schemaType).(type) {
case schema.UnionRepresentation_Kinded:
return w.asKinded(stg, datamodel.Kind_List).BeginList(sizeHint)
case schema.StructRepresentation_Tuple:
case schema.StructRepresentation_Tuple, schema.StructRepresentation_ListPairs:
asm, err := (*_assembler)(w).BeginMap(sizeHint)
if err != nil {
return nil, err
Expand Down Expand Up @@ -860,7 +941,7 @@ func (w *_structAssemblerRepr) AssembleKey() datamodel.NodeAssembler {
AppropriateKind: datamodel.KindSet_JustMap,
ActualKind: datamodel.Kind_String,
}}
case schema.StructRepresentation_Tuple:
case schema.StructRepresentation_Tuple, schema.StructRepresentation_ListPairs:
return _errorAssembler{datamodel.ErrWrongKind{
TypeName: w.schemaType.Name() + ".Repr",
MethodName: "AssembleKey",
Expand Down Expand Up @@ -974,14 +1055,24 @@ func (w *_listStructAssemblerRepr) AssembleValue() datamodel.NodeAssembler {
}
entryAsm = assemblerRepr(entryAsm)
return entryAsm
case schema.StructRepresentation_ListPairs:
idx := w.nextIndex
w.nextIndex++
if idx%2 == 0 {
asm := (*_structAssembler)(w).AssembleKey()
// ???
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this meant to have a comment?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh, embarrassing ... that's there cause I don't actually know why I would want to put the next line there; I intended to figure this out

return (*_assemblerRepr)(asm.(*_assembler))
}
asm := (*_structAssembler)(w).AssembleValue()
return (*_assemblerRepr)(asm.(*_assembler))
default:
return _errorAssembler{fmt.Errorf("bindnode AssembleValue TODO: %T", stg)}
}
}

func (w *_listStructAssemblerRepr) Finish() error {
switch stg := reprStrategy(w.schemaType).(type) {
case schema.StructRepresentation_Tuple:
case schema.StructRepresentation_Tuple, schema.StructRepresentation_ListPairs:
return (*_structAssembler)(w).Finish()
default:
return fmt.Errorf("bindnode Finish TODO: %T", stg)
Expand Down
1 change: 1 addition & 0 deletions node/tests/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ var allSchemaTests = []struct {
{"StructNesting", SchemaTestStructNesting},
{"StructReprStringjoin", SchemaTestStructReprStringjoin},
{"StructReprTuple", SchemaTestStructReprTuple},
{"StructReprListPairs", SchemaTestStructReprListPairs},
{"StructsContainingMaybe", SchemaTestStructsContainingMaybe},
{"UnionKeyed", SchemaTestUnionKeyed},
{"UnionKeyedComplexChildren", SchemaTestUnionKeyedComplexChildren},
Expand Down
163 changes: 163 additions & 0 deletions node/tests/schemaStructReprListpairs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
package tests

import (
"testing"

qt "github.com/frankban/quicktest"

"github.com/ipld/go-ipld-prime/datamodel"
"github.com/ipld/go-ipld-prime/fluent"
"github.com/ipld/go-ipld-prime/must"
"github.com/ipld/go-ipld-prime/schema"
)

func SchemaTestStructReprListPairs(t *testing.T, engine Engine) {
ts := schema.TypeSystem{}
ts.Init()
ts.Accumulate(schema.SpawnString("String"))
ts.Accumulate(schema.SpawnStruct("OneListPair",
[]schema.StructField{
schema.SpawnStructField("field", "String", false, false),
},
schema.SpawnStructRepresentationListPairs(),
))
ts.Accumulate(schema.SpawnStruct("FourListPairs",
[]schema.StructField{
schema.SpawnStructField("foo", "String", false, true),
schema.SpawnStructField("bar", "String", true, true),
schema.SpawnStructField("baz", "String", true, false),
schema.SpawnStructField("qux", "String", false, false),
},
schema.SpawnStructRepresentationListPairs(),
))
engine.Init(t, ts)

t.Run("onelistpair works", func(t *testing.T) {
np := engine.PrototypeByName("OneListPair")
nrp := engine.PrototypeByName("OneListPair.Repr")
var n schema.TypedNode
t.Run("typed-create", func(t *testing.T) {
n = fluent.MustBuildMap(np, 1, func(ma fluent.MapAssembler) {
ma.AssembleEntry("field").AssignString("valoo")
}).(schema.TypedNode)
t.Run("typed-read", func(t *testing.T) {
qt.Assert(t, n.Kind(), qt.Equals, datamodel.Kind_Map)
qt.Check(t, n.Length(), qt.Equals, int64(1))
qt.Check(t, must.String(must.Node(n.LookupByString("field"))), qt.Equals, "valoo")
})
t.Run("repr-read", func(t *testing.T) {
nr := n.Representation()
qt.Assert(t, nr.Kind(), qt.Equals, datamodel.Kind_List)
qt.Check(t, nr.Length(), qt.Equals, int64(2))
qt.Check(t, must.String(must.Node(nr.LookupByIndex(0))), qt.Equals, "field")
qt.Check(t, must.String(must.Node(nr.LookupByIndex(1))), qt.Equals, "valoo")
})
})
t.Run("repr-create", func(t *testing.T) {
nr := fluent.MustBuildList(nrp, 2, func(la fluent.ListAssembler) {
la.AssembleValue().AssignString("field")
la.AssembleValue().AssignString("valoo")
})
qt.Check(t, n, NodeContentEquals, nr)
})
})

t.Run("fourlistpairs works", func(t *testing.T) {
np := engine.PrototypeByName("FourListPairs")
nrp := engine.PrototypeByName("FourListPairs.Repr")
var n schema.TypedNode
t.Run("typed-create", func(t *testing.T) {
n = fluent.MustBuildMap(np, 4, func(ma fluent.MapAssembler) {
ma.AssembleEntry("foo").AssignString("0")
ma.AssembleEntry("bar").AssignString("1")
ma.AssembleEntry("baz").AssignString("2")
ma.AssembleEntry("qux").AssignString("3")
}).(schema.TypedNode)
t.Run("typed-read", func(t *testing.T) {
qt.Assert(t, n.Kind(), qt.Equals, datamodel.Kind_Map)
qt.Check(t, n.Length(), qt.Equals, int64(4))
qt.Check(t, must.String(must.Node(n.LookupByString("foo"))), qt.Equals, "0")
qt.Check(t, must.String(must.Node(n.LookupByString("bar"))), qt.Equals, "1")
qt.Check(t, must.String(must.Node(n.LookupByString("baz"))), qt.Equals, "2")
qt.Check(t, must.String(must.Node(n.LookupByString("qux"))), qt.Equals, "3")
})
t.Run("repr-read", func(t *testing.T) {
nr := n.Representation()
qt.Assert(t, nr.Kind(), qt.Equals, datamodel.Kind_List)
qt.Check(t, nr.Length(), qt.Equals, int64(8))
qt.Check(t, must.String(must.Node(nr.LookupByIndex(0))), qt.Equals, "foo")
qt.Check(t, must.String(must.Node(nr.LookupByIndex(1))), qt.Equals, "0")
qt.Check(t, must.String(must.Node(nr.LookupByIndex(2))), qt.Equals, "bar")
qt.Check(t, must.String(must.Node(nr.LookupByIndex(3))), qt.Equals, "1")
qt.Check(t, must.String(must.Node(nr.LookupByIndex(4))), qt.Equals, "baz")
qt.Check(t, must.String(must.Node(nr.LookupByIndex(5))), qt.Equals, "2")
qt.Check(t, must.String(must.Node(nr.LookupByIndex(6))), qt.Equals, "qux")
qt.Check(t, must.String(must.Node(nr.LookupByIndex(7))), qt.Equals, "3")
})
})
t.Run("repr-create", func(t *testing.T) {
nr := fluent.MustBuildList(nrp, 8, func(la fluent.ListAssembler) {
la.AssembleValue().AssignString("foo")
la.AssembleValue().AssignString("0")
la.AssembleValue().AssignString("bar")
la.AssembleValue().AssignString("1")
la.AssembleValue().AssignString("baz")
la.AssembleValue().AssignString("2")
la.AssembleValue().AssignString("qux")
la.AssembleValue().AssignString("3")
})
qt.Check(t, n, NodeContentEquals, nr)
})
t.Run("repr-create out-of-order", func(t *testing.T) {
nr := fluent.MustBuildList(nrp, 8, func(la fluent.ListAssembler) {
la.AssembleValue().AssignString("bar")
la.AssembleValue().AssignString("1")
la.AssembleValue().AssignString("foo")
la.AssembleValue().AssignString("0")
la.AssembleValue().AssignString("qux")
la.AssembleValue().AssignString("3")
la.AssembleValue().AssignString("baz")
la.AssembleValue().AssignString("2")
})
qt.Check(t, n, NodeContentEquals, nr)
})
})

t.Run("fourlistpairs with absents", func(t *testing.T) {
np := engine.PrototypeByName("FourListPairs")
nrp := engine.PrototypeByName("FourListPairs.Repr")
var n schema.TypedNode
t.Run("typed-create", func(t *testing.T) {
n = fluent.MustBuildMap(np, 2, func(ma fluent.MapAssembler) {
ma.AssembleEntry("foo").AssignNull()
ma.AssembleEntry("qux").AssignString("3")
}).(schema.TypedNode)
t.Run("typed-read", func(t *testing.T) {
qt.Assert(t, n.Kind(), qt.Equals, datamodel.Kind_Map)
qt.Check(t, n.Length(), qt.Equals, int64(4))
qt.Check(t, must.Node(n.LookupByString("foo")), qt.Equals, datamodel.Null)
qt.Check(t, must.Node(n.LookupByString("bar")), qt.Equals, datamodel.Absent)
qt.Check(t, must.Node(n.LookupByString("baz")), qt.Equals, datamodel.Absent)
qt.Check(t, must.String(must.Node(n.LookupByString("qux"))), qt.Equals, "3")
})
t.Run("repr-read", func(t *testing.T) {
nr := n.Representation()
qt.Assert(t, nr.Kind(), qt.Equals, datamodel.Kind_List)
qt.Check(t, nr.Length(), qt.Equals, int64(4))
qt.Check(t, must.String(must.Node(nr.LookupByIndex(0))), qt.Equals, "foo")
qt.Check(t, must.Node(nr.LookupByIndex(1)), qt.Equals, datamodel.Null)
qt.Check(t, must.String(must.Node(nr.LookupByIndex(2))), qt.Equals, "qux")
qt.Check(t, must.String(must.Node(nr.LookupByIndex(3))), qt.Equals, "3")
})
})
t.Run("repr-create", func(t *testing.T) {
nr := fluent.MustBuildList(nrp, 4, func(la fluent.ListAssembler) {
la.AssembleValue().AssignString("foo")
la.AssembleValue().AssignNull()
la.AssembleValue().AssignString("qux")
la.AssembleValue().AssignString("3")
})
qt.Check(t, n, NodeContentEquals, nr)
})
})
}
3 changes: 3 additions & 0 deletions schema/tmpBuilders.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,9 @@ func SpawnStructRepresentationMap2(renames map[string]string, implicits map[stri
func SpawnStructRepresentationTuple() StructRepresentation_Tuple {
return StructRepresentation_Tuple{}
}
func SpawnStructRepresentationListPairs() StructRepresentation_ListPairs {
return StructRepresentation_ListPairs{}
}
func SpawnStructRepresentationStringjoin(delim string) StructRepresentation_Stringjoin {
return StructRepresentation_Stringjoin{delim}
}
Expand Down
2 changes: 2 additions & 0 deletions schema/type.go
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@ type StructRepresentation interface{ _StructRepresentation() }

func (StructRepresentation_Map) _StructRepresentation() {}
func (StructRepresentation_Tuple) _StructRepresentation() {}
func (StructRepresentation_ListPairs) _StructRepresentation() {}
func (StructRepresentation_StringPairs) _StructRepresentation() {}
func (StructRepresentation_Stringjoin) _StructRepresentation() {}

Expand All @@ -232,6 +233,7 @@ type StructRepresentation_Map struct {
implicits map[string]ImplicitValue
}
type StructRepresentation_Tuple struct{}
type StructRepresentation_ListPairs struct{}

//lint:ignore U1000 implementation TODO
type StructRepresentation_StringPairs struct{ sep1, sep2 string }
Expand Down
2 changes: 2 additions & 0 deletions schema/typeMethods.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ func (t TypeStruct) RepresentationBehavior() datamodel.Kind {
return datamodel.Kind_Map
case StructRepresentation_Tuple:
return datamodel.Kind_List
case StructRepresentation_ListPairs:
return datamodel.Kind_List
case StructRepresentation_StringPairs:
return datamodel.Kind_String
case StructRepresentation_Stringjoin:
Expand Down