From f9a1c7a5513b04ccff79b1fcae3a071d809a7577 Mon Sep 17 00:00:00 2001 From: Thomas Pelletier Date: Fri, 15 Dec 2023 11:23:26 -0500 Subject: [PATCH 1/2] Sort imports of durable code for output stability It avoids sometimes getting unexpected diffs when re-compiling the same program on a different machine. --- compiler/compile.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/compiler/compile.go b/compiler/compile.go index 9b3d927..dd29edd 100644 --- a/compiler/compile.go +++ b/compiler/compile.go @@ -12,6 +12,7 @@ import ( "path/filepath" "runtime" "slices" + "sort" "strconv" "strings" @@ -402,6 +403,12 @@ func addImports(p *packages.Package, gen *ast.File) *ast.File { }) } + // Imports don't require to be sorted but it helps with output + // stability. The format pass does not take care of this. + sort.Slice(importspecs, func(i, j int) bool { + return importspecs[i].(*ast.ImportSpec).Name.Name < importspecs[j].(*ast.ImportSpec).Name.Name + }) + gen.Decls = append([]ast.Decl{&ast.GenDecl{ Tok: token.IMPORT, Specs: importspecs, From cc9c20bd96026fdb876eb9d0038f39285707a4d0 Mon Sep 17 00:00:00 2001 From: Thomas Pelletier Date: Fri, 15 Dec 2023 11:38:49 -0500 Subject: [PATCH 2/2] Use slices.SortFunc --- compiler/compile.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/compiler/compile.go b/compiler/compile.go index dd29edd..a735dc2 100644 --- a/compiler/compile.go +++ b/compiler/compile.go @@ -1,6 +1,7 @@ package compiler import ( + "cmp" "fmt" "go/ast" "go/build/constraint" @@ -12,7 +13,6 @@ import ( "path/filepath" "runtime" "slices" - "sort" "strconv" "strings" @@ -405,8 +405,8 @@ func addImports(p *packages.Package, gen *ast.File) *ast.File { // Imports don't require to be sorted but it helps with output // stability. The format pass does not take care of this. - sort.Slice(importspecs, func(i, j int) bool { - return importspecs[i].(*ast.ImportSpec).Name.Name < importspecs[j].(*ast.ImportSpec).Name.Name + slices.SortFunc(importspecs, func(a, b ast.Spec) int { + return cmp.Compare(a.(*ast.ImportSpec).Name.Name, b.(*ast.ImportSpec).Name.Name) }) gen.Decls = append([]ast.Decl{&ast.GenDecl{