Skip to content

Commit 9827b59

Browse files
authored
remove empty lines surrounding lone comments in field lists
1 parent d74ca43 commit 9827b59

File tree

2 files changed

+73
-1
lines changed

2 files changed

+73
-1
lines changed

format/format.go

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -562,13 +562,34 @@ func (f *fumpter) applyPre(c *astutil.Cursor) {
562562
f.stmts(node.Body)
563563

564564
case *ast.FieldList:
565-
if node.NumFields() == 0 && len(f.commentsBetween(node.Pos(), node.End())) == 0 {
565+
numFields := node.NumFields()
566+
comments := f.commentsBetween(node.Pos(), node.End())
567+
568+
if numFields == 0 && len(comments) == 0 {
566569
// Empty field lists should not contain a newline.
567570
// Do not join the two lines if the first has an inline
568571
// comment, as that can result in broken formatting.
569572
openLine := f.Line(node.Pos())
570573
closeLine := f.Line(node.End())
571574
f.removeLines(openLine, closeLine)
575+
} else {
576+
// Remove lines before first comment/field and lines after last
577+
// comment/field
578+
var bodyPos, bodyEnd token.Pos
579+
if numFields > 0 {
580+
bodyPos = node.List[0].Pos()
581+
bodyEnd = node.List[len(node.List)-1].End()
582+
}
583+
if len(comments) > 0 {
584+
if pos := comments[0].Pos(); !bodyPos.IsValid() || pos < bodyPos {
585+
bodyPos = pos
586+
}
587+
if pos := comments[len(comments)-1].End(); !bodyPos.IsValid() || pos > bodyEnd {
588+
bodyEnd = pos
589+
}
590+
}
591+
f.removeLinesBetween(node.Pos(), bodyPos)
592+
f.removeLinesBetween(bodyEnd, node.End())
572593
}
573594

574595
// Merging adjacent fields (e.g. parameters) is disabled by default.

testdata/scripts/block-empty.txt

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,42 @@ func f() {
2020
// lone comment
2121

2222
}
23+
24+
type S struct {
25+
26+
27+
// lone comment
28+
29+
30+
}
31+
32+
type I interface {
33+
34+
35+
// lone comment
36+
37+
38+
}
39+
40+
41+
}
42+
43+
type SOut struct {
44+
45+
// lone comment
46+
2347
}
48+
49+
type IOut interface {
50+
51+
52+
// lone comment
53+
54+
55+
}
56+
57+
58+
2459
-- foo.go.golden --
2560
package p
2661

@@ -34,4 +69,20 @@ func f() {
3469
{
3570
// lone comment
3671
}
72+
73+
type S struct {
74+
// lone comment
75+
}
76+
77+
type I interface {
78+
// lone comment
79+
}
80+
}
81+
82+
type SOut struct {
83+
// lone comment
84+
}
85+
86+
type IOut interface {
87+
// lone comment
3788
}

0 commit comments

Comments
 (0)