profile
viewpoint

Ask questionsadd newlines in nested expressions to fix confusing indentation

gofmt is special in that it doesn't allow increasing the indentation level more than once per line. This can result in the following gofmt-valid code:

package p

var _ = foo(x, y, bar(
	"baz",
),
	z,
)

Note that line "baz", would deserve 2 indentation levels, but because the parent has 0, it gets 1. Then, its closing token line, which should have 1 indentation level, gets 0. This is very confusing, because to the human eye it seems like it's closing the foo call, not the bar call, which is actually closed two lines further below.

In cases where the inner closing token is on a separate line, and its indentation is messed up in a way that could confuse the reader, gofumpt should do something. I propose to add a newline at the start of the inner expression, forcing the two indentation levels to actually happen on different lines, resulting in less confusion:

var _ = foo(x, y,
	bar(
		"baz",
	),
	z,
)

The user could also make the bar call a single line, but that's their choice. This is just an example; its argument list could be long or span multiple lines.

Other variations:

// top-level closing token isn't on a separate line
var _ = foo(x, y, bar(
	"baz",
),
	z)

// inner expression uses different closing tokens
var _ = foo(x, y, map[string]string{
	"bar": "baz",
},
	z)
mvdan/gofumpt

Answer questions mvdan

In cases where the inner closing token is on a separate line, and its indentation is messed up in a way that could confuse the reader

Here are some examples of two indentation levels joined into a single line, which don't result in confusing indentation. I don't think gofumpt should modify these programs.

var _ = foo(x, y, bar(
	"baz",
), z)

var _ = foo{x: y, bar: bar{
	z: "baz",
}}

The difference here is that both indentation levels begin on the same line, but also end on the same line.

useful!

Related questions

No questions were found.
source:https://uonfu.com/
answerer
Daniel Martí mvdan @protocol Sheffield, United Kingdom https://mvdan.cc I work on stuff in Go.
Github User Rank List