Skip to content

Commit 1eaa24c

Browse files
committed
codegen: deterministic order for types in output.
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.
1 parent ec2129b commit 1eaa24c

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

schema/gen/go/generate.go

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"io"
66
"os"
77
"path/filepath"
8+
"sort"
89

910
"github.com/ipld/go-ipld-prime/schema"
1011
)
@@ -22,9 +23,16 @@ func Generate(pth string, pkgName string, ts schema.TypeSystem, adjCfg *AdjunctC
2223
// Local helper function for applying generation logic to each type.
2324
// 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.
2425
applyToEachType := func(fn func(tg TypeGenerator, w io.Writer), f io.Writer) {
25-
// FIXME: the order of this iteration is not stable, and it should be, because it affects determinism of the output.
26-
for _, typ := range ts.GetTypes() {
27-
switch t2 := typ.(type) {
26+
// Sort the type names so we have a determinisic order; this affects output consistency.
27+
// Any stable order would do, but we don't presently have one, so a sort is necessary.
28+
types := ts.GetTypes()
29+
keys := make(sortableTypeNames, 0, len(types))
30+
for tn := range types {
31+
keys = append(keys, tn)
32+
}
33+
sort.Sort(keys)
34+
for _, tn := range keys {
35+
switch t2 := types[tn].(type) {
2836
case *schema.TypeBool:
2937
fn(NewBoolReprBoolGenerator(pkgName, t2, adjCfg), f)
3038
case *schema.TypeInt:
@@ -188,3 +196,9 @@ func withFile(filename string, fn func(io.Writer)) {
188196
defer f.Close()
189197
fn(f)
190198
}
199+
200+
type sortableTypeNames []schema.TypeName
201+
202+
func (a sortableTypeNames) Len() int { return len(a) }
203+
func (a sortableTypeNames) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
204+
func (a sortableTypeNames) Less(i, j int) bool { return a[i] < a[j] }

0 commit comments

Comments
 (0)