Skip to content

Commit

Permalink
format: account for leading comments in composite literals
Browse files Browse the repository at this point in the history
For an input such as:

	var _ = map[string]string{
		/*
			joint comment
		*/
		"foo": "bar",
	}

We would incorrectly join the comment with the first element:

	var _ = map[string]string{
		/*
			joint comment
		*/ "foo": "bar",
	}

Just like in other parts of the codebase,
consider the first comment's position if it exists.

Fixes #170.
  • Loading branch information
mvdan committed Dec 5, 2021
1 parent 93927ca commit 872763c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 11 deletions.
13 changes: 10 additions & 3 deletions format/format.go
Expand Up @@ -655,19 +655,26 @@ func (f *fumpter) applyPost(c *astutil.Cursor) {

newlineAroundElems := false
newlineBetweenElems := false
lastEnd := node.Lbrace
lastLine := openLine
for i, elem := range node.Elts {
if elPos := f.Line(elem.Pos()); elPos > lastLine {
pos := elem.Pos()
comments := f.commentsBetween(lastEnd, pos)
if len(comments) > 0 {
pos = comments[0].Pos()
}
if curLine := f.Line(pos); curLine > lastLine {
if i == 0 {
newlineAroundElems = true

// remove leading lines if they exist
f.removeLines(openLine+1, elPos)
f.removeLines(openLine+1, curLine)
} else {
newlineBetweenElems = true
}
}
lastLine = f.Line(elem.End())
lastEnd = elem.End()
lastLine = f.Line(lastEnd)
}
if closeLine > lastLine {
newlineAroundElems = true
Expand Down
32 changes: 24 additions & 8 deletions testdata/scripts/composite-literals-leading-lines.txt
Expand Up @@ -20,12 +20,12 @@ var _ = []string{

var _ = []string{

// comment
// joint comment
"foo",
}

var _ = []string{
// comment
// separate comment

"foo",
}
Expand All @@ -43,16 +43,23 @@ var _ = map[string]string{

var _ = map[string]string{

// comment
// joint comment
"foo": "bar",
}

var _ = map[string]string{
// comment
// separate comment

"foo": "bar",
}

var _ = map[string]string{
/*
joint comment
*/
"foo": "bar",
}

-- foo.go.golden --
package p

Expand All @@ -65,12 +72,13 @@ var _ = []string{
}

var _ = []string{
// comment
// joint comment
"foo",
}

var _ = []string{
// comment
// separate comment

"foo",
}

Expand All @@ -83,11 +91,19 @@ var _ = map[string]string{
}

var _ = map[string]string{
// comment
// joint comment
"foo": "bar",
}

var _ = map[string]string{
// separate comment

"foo": "bar",
}

var _ = map[string]string{
// comment
/*
joint comment
*/
"foo": "bar",
}

0 comments on commit 872763c

Please sign in to comment.