From 6cf1eb6d49482ae5591aa0dc59ddbfe60ee78af9 Mon Sep 17 00:00:00 2001 From: Andrew LeFevre Date: Fri, 30 Oct 2020 20:12:07 -0400 Subject: [PATCH] keep init funcs in original order (#165) --- main.go | 14 ++++++-- testdata/scripts/init.txt | 73 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 3 deletions(-) create mode 100644 testdata/scripts/init.txt diff --git a/main.go b/main.go index b38a616..9e7c99f 100644 --- a/main.go +++ b/main.go @@ -1002,11 +1002,19 @@ func transformGo(file *ast.File, info *types.Info, blacklist map[types.Object]st decl2 := file.Decls[j] // Import declarations must remain at the top of the file. - gd1, ok1 := decl1.(*ast.GenDecl) - gd2, ok2 := decl2.(*ast.GenDecl) - if (ok1 && gd1.Tok == token.IMPORT) || (ok2 && gd2.Tok == token.IMPORT) { + gd1, iok1 := decl1.(*ast.GenDecl) + gd2, iok2 := decl2.(*ast.GenDecl) + if (iok1 && gd1.Tok == token.IMPORT) || (iok2 && gd2.Tok == token.IMPORT) { return } + + // init function declarations must remain in order. + fd1, fok1 := decl1.(*ast.FuncDecl) + fd2, fok2 := decl2.(*ast.FuncDecl) + if (fok1 && fd1.Name.Name == "init") || (fok2 && fd2.Name.Name == "init") { + return + } + file.Decls[i], file.Decls[j] = decl2, decl1 }) diff --git a/testdata/scripts/init.txt b/testdata/scripts/init.txt new file mode 100644 index 0000000..c15f689 --- /dev/null +++ b/testdata/scripts/init.txt @@ -0,0 +1,73 @@ +# Test that garble keeps init functions in the order they were declared in + +garble build +exec ./main +cmp stdout main.stdout + +[short] stop # no need to verify this with -short + +go build +exec ./main +cmp stdout main.stdout + +-- go.mod -- +module test/main +-- main.go -- +package main + +import ( + "fmt" + "strings" +) + +var exploded []string + +func init() { + exploded = append(exploded, "B") +} + +func init() { + exploded = append(exploded, "i") +} + +func init() { + exploded = append(exploded, "g") +} + +func init() { + exploded = append(exploded, " ") +} + +func init() { + exploded = append(exploded, "C") +} + +func init() { + exploded = append(exploded, "h") +} + +func init() { + exploded = append(exploded, "u") +} + +func init() { + exploded = append(exploded, "n") +} + +func init() { + exploded = append(exploded, "g") +} + +func init() { + exploded = append(exploded, "u") +} + +func init() { + exploded = append(exploded, "s") +} + +func main() { + fmt.Println(strings.Join(exploded, "")) +} +-- main.stdout -- +Big Chungus