Skip to content

Commit

Permalink
use type for embedded fields sorting
Browse files Browse the repository at this point in the history
  • Loading branch information
1pkg committed Apr 5, 2021
1 parent ea2463f commit c15ac50
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 11 deletions.
23 changes: 16 additions & 7 deletions fmtio/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
10 changes: 10 additions & 0 deletions fmtio/ast_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,11 @@ func TestAst(t *testing.T) {
Value: "embedded",
},
},
{
Type: &ast.Ident{
Name: "int64",
},
},
},
},
},
Expand Down Expand Up @@ -144,6 +149,10 @@ func TestAst(t *testing.T) {
Name: "test-5",
Type: "int64",
},
{
Type: "int64",
Embedded: true,
},
{
Type: "float32",
Embedded: true,
Expand All @@ -158,6 +167,7 @@ test struct {
test-4 int64
test-5 int64// random
// random
int64
float32 embedded
}
`),
Expand Down
8 changes: 4 additions & 4 deletions walkers/wast_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,10 +243,10 @@ type ze interface {
}
type Zeze struct {
ze
D
AZ
D
AWA D
ze
}
// test comment
Expand Down Expand Up @@ -332,10 +332,10 @@ type ze interface {
}
type Zeze struct {
ze
D
AZ
D
AWA D
ze
}
// test comment
Expand Down

0 comments on commit c15ac50

Please sign in to comment.