Skip to content

Commit

Permalink
cmd/gofmt, go/printer: fix mis-alignment of comment on one-line function
Browse files Browse the repository at this point in the history
Fixes #19544.

Change-Id: I5df67383e9471f030ddafabadf2bc19ce6816f0f
Reviewed-on: https://go-review.googlesource.com/46002
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
  • Loading branch information
griesemer committed Jun 19, 2017
1 parent 09ebbf4 commit 26b07c4
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/go/printer/nodes.go
Original file line number Diff line number Diff line change
Expand Up @@ -1532,6 +1532,16 @@ func (p *printer) nodeSize(n ast.Node, maxSize int) (size int) {
return
}

// numLines returns the number of lines spanned by node n in the original source.
func (p *printer) numLines(n ast.Node) int {
if from := n.Pos(); from.IsValid() {
if to := n.End(); to.IsValid() {
return p.lineFor(to) - p.lineFor(from) + 1
}
}
return infinity
}

// bodySize is like nodeSize but it is specialized for *ast.BlockStmt's.
func (p *printer) bodySize(b *ast.BlockStmt, maxSize int) int {
pos1 := b.Pos()
Expand Down Expand Up @@ -1668,7 +1678,9 @@ func (p *printer) declList(list []ast.Decl) {
if prev != tok || getDoc(d) != nil {
min = 2
}
p.linebreak(p.lineFor(d.Pos()), min, ignore, false)
// start a new section if the next declaration is a function
// that spans multiple lines (see also issue #19544)
p.linebreak(p.lineFor(d.Pos()), min, ignore, tok == token.FUNC && p.numLines(d) > 1)
}
p.decl(d)
}
Expand Down
6 changes: 6 additions & 0 deletions src/go/printer/testdata/declarations.golden
Original file line number Diff line number Diff line change
Expand Up @@ -778,6 +778,12 @@ func _() {
/* multi-line func because block is on multiple lines */
}

// test case for issue #19544
func _() {}
func _longer_name_() { // this comment must not force the {} from above to alignment
// multiple lines
}

// ellipsis parameters
func _(...int)
func _(...*int)
Expand Down
5 changes: 5 additions & 0 deletions src/go/printer/testdata/declarations.input
Original file line number Diff line number Diff line change
Expand Up @@ -795,6 +795,11 @@ func _() { /* multi-line function because of "long-ish" comment - much more comm
func _() {
/* multi-line func because block is on multiple lines */ }

// test case for issue #19544
func _() {}
func _longer_name_() { // this comment must not force the {} from above to alignment
// multiple lines
}

// ellipsis parameters
func _(...int)
Expand Down

0 comments on commit 26b07c4

Please sign in to comment.