From c15ac5010d38d6ac483fa22275c08e8790c45951 Mon Sep 17 00:00:00 2001 From: Kostiantyn Masliuk <1pkg@protonmail.com> Date: Mon, 5 Apr 2021 15:33:00 +0200 Subject: [PATCH] use type for embedded fields sorting --- fmtio/ast.go | 23 ++++++++++++++++------- fmtio/ast_test.go | 10 ++++++++++ walkers/wast_test.go | 8 ++++---- 3 files changed, 30 insertions(+), 11 deletions(-) diff --git a/fmtio/ast.go b/fmtio/ast.go index a9f892d..5a0dbda 100644 --- a/fmtio/ast.go +++ b/fmtio/ast.go @@ -119,17 +119,18 @@ func fpadfilter(ts *ast.TypeSpec, st gopium.Struct) error { } // shuffle helps to sort fields list -// for ast type spec accordingly to result struct, -// -// note shuffle works properly on structs with -// one or less embedded fields +// for ast type spec accordingly to result struct func shuffle(ts *ast.TypeSpec, st gopium.Struct) error { // collect fields indexes tts := ts.Type.(*ast.StructType) fields := make(map[string]int, len(st.Fields)) - // in case struct have two or more embedded fields - // this solution will not work as expected + // in case of embedded fields + // use types to uniquely discern them for i, f := range st.Fields { + if f.Name == "" { + fields[f.Type] = i + continue + } fields[f.Name] = i } // shuffle fields list @@ -138,13 +139,21 @@ func shuffle(ts *ast.TypeSpec, st gopium.Struct) error { // for flat structure non embedded // ast's i-th and j-th fields // in case fields are embedded - // use empty name by default + // use type instead if possible var ni, nj string if fni := tts.Fields.List[i]; len(fni.Names) == 1 { ni = fni.Names[0].Name + } else if len(fni.Names) == 0 { + if it, ok := fni.Type.(*ast.Ident); ok { + ni = it.Name + } } if fnj := tts.Fields.List[j]; len(fnj.Names) == 1 { nj = fnj.Names[0].Name + } else if len(fnj.Names) == 0 { + if it, ok := fnj.Type.(*ast.Ident); ok { + nj = it.Name + } } // prepare comparison indexes // and search for them in resulted structure diff --git a/fmtio/ast_test.go b/fmtio/ast_test.go index 5cd42b6..50e390b 100644 --- a/fmtio/ast_test.go +++ b/fmtio/ast_test.go @@ -114,6 +114,11 @@ func TestAst(t *testing.T) { Value: "embedded", }, }, + { + Type: &ast.Ident{ + Name: "int64", + }, + }, }, }, }, @@ -144,6 +149,10 @@ func TestAst(t *testing.T) { Name: "test-5", Type: "int64", }, + { + Type: "int64", + Embedded: true, + }, { Type: "float32", Embedded: true, @@ -158,6 +167,7 @@ test struct { test-4 int64 test-5 int64// random // random + int64 float32 embedded } `), diff --git a/walkers/wast_test.go b/walkers/wast_test.go index 67f1bb3..497c51b 100644 --- a/walkers/wast_test.go +++ b/walkers/wast_test.go @@ -243,10 +243,10 @@ type ze interface { } type Zeze struct { - ze - D AZ + D AWA D + ze } // test comment @@ -332,10 +332,10 @@ type ze interface { } type Zeze struct { - ze - D AZ + D AWA D + ze } // test comment