Skip to content

Commit

Permalink
codegen: deterministic order for types in output.
Browse files Browse the repository at this point in the history
I'd still probably prefer to replace this with simply having a stable
order that is carried through consistently, but that remains blocked
behind getting self-hosted types, and while it so happens I also got
about 80% of the way there on those today, the second 80% may take
another day.  Better make this stable rather than wait.
  • Loading branch information
warpfork committed Oct 30, 2020
1 parent ec2129b commit 1eaa24c
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions schema/gen/go/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"io"
"os"
"path/filepath"
"sort"

"github.com/ipld/go-ipld-prime/schema"
)
Expand All @@ -22,9 +23,16 @@ func Generate(pth string, pkgName string, ts schema.TypeSystem, adjCfg *AdjunctC
// Local helper function for applying generation logic to each type.
// We will end up doing this more than once because in this layout, more than one file contains part of the story for each type.
applyToEachType := func(fn func(tg TypeGenerator, w io.Writer), f io.Writer) {
// FIXME: the order of this iteration is not stable, and it should be, because it affects determinism of the output.
for _, typ := range ts.GetTypes() {
switch t2 := typ.(type) {
// Sort the type names so we have a determinisic order; this affects output consistency.
// Any stable order would do, but we don't presently have one, so a sort is necessary.
types := ts.GetTypes()
keys := make(sortableTypeNames, 0, len(types))
for tn := range types {
keys = append(keys, tn)
}
sort.Sort(keys)
for _, tn := range keys {
switch t2 := types[tn].(type) {
case *schema.TypeBool:
fn(NewBoolReprBoolGenerator(pkgName, t2, adjCfg), f)
case *schema.TypeInt:
Expand Down Expand Up @@ -188,3 +196,9 @@ func withFile(filename string, fn func(io.Writer)) {
defer f.Close()
fn(f)
}

type sortableTypeNames []schema.TypeName

func (a sortableTypeNames) Len() int { return len(a) }
func (a sortableTypeNames) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a sortableTypeNames) Less(i, j int) bool { return a[i] < a[j] }

0 comments on commit 1eaa24c

Please sign in to comment.