go/analysis/passes/fieldalignment: support fields without name

The flattening didn't account for fields without name resulting in a
panic when calculating suggested fixes for such struct.

They are now added while flattening and there is also a test to ensure
that it works.

Change-Id: I8f8740c8d9132d10fb09053a322633eb29e8bcf8
Reviewed-on: https://go-review.googlesource.com/c/tools/+/278372
Trust: Pontus Leitzler <leitzler@gmail.com>
Run-TryBot: Pontus Leitzler <leitzler@gmail.com>
gopls-CI: kokoro <noreply+kokoro@google.com>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
This commit is contained in:
Pontus Leitzler 2020-12-15 17:36:55 +01:00 committed by Rebecca Stambler
parent d93e913c1a
commit 6307297f46
3 changed files with 29 additions and 1 deletions

View File

@ -76,7 +76,7 @@ func fieldalignment(pass *analysis.Pass, node *ast.StructType, typ *types.Struct
// TODO: Preserve multi-named fields instead of flattening.
var flat []*ast.Field
for _, f := range node.Fields.List {
if len(f.Names) == 1 {
if len(f.Names) <= 1 {
flat = append(flat, f)
continue
}

View File

@ -21,3 +21,17 @@ type ZeroBad struct { // want "struct of size 8 could be 4"
a uint32
b [0]byte
}
type NoNameGood struct {
Good
y int32
x byte
z byte
}
type NoNameBad struct { // want "struct of size 20 could be 16"
Good
x byte
y int32
z byte
}

View File

@ -21,3 +21,17 @@ type ZeroBad struct {
b [0]byte
a uint32
}
type NoNameGood struct {
Good
y int32
x byte
z byte
}
type NoNameBad struct {
Good
y int32
x byte
z byte
}