Background
I want to use structured comments to associate metadata with function parameter types in Go source code, with the function bodies automatically generated by an external tool.
Problem
There is a bad interaction between (*printer.Config).Fprint and ast.NewCommentMap for comments on function results.
If a function returns only one result, has an associated trailing comment, and lacks a body (e.g., because it is implemented in assembly), NewCommentMap will only associate the comment with the result if both are enclosed in parentheses. (Otherwise, the algorithm of NewCommentMap instead associates the comment with the entire file.)
Unfortunately, (*printer.Config).Fprint omits those parentheses, so running gofmt on such a file breaks the association between the metadata and the function result.
Example: https://play.golang.org/p/ovMOY6e5pB
package foo
func Foo() (error /*metadata*/)
formats to
package foo
func Foo() error /*metadata*/
Proposal
The problematic check is here:
|
if n == 1 && result.List[0].Names == nil { |
|
// single anonymous result; no ()'s |
|
p.expr(stripParensAlways(result.List[0].Type)) |
|
return |
|
} |
I suspect it would be fixed by weakening that condition to:
if n == 1 && result.List[0].Names == nil &&
(!result.Closing.IsValid() || !p.commentBefore(p.posFor(result.Closing)) {
Background
I want to use structured comments to associate metadata with function parameter types in Go source code, with the function bodies automatically generated by an external tool.
Problem
There is a bad interaction between
(*printer.Config).Fprintandast.NewCommentMapfor comments on function results.If a function returns only one result, has an associated trailing comment, and lacks a body (e.g., because it is implemented in assembly),
NewCommentMapwill only associate the comment with the result if both are enclosed in parentheses. (Otherwise, the algorithm ofNewCommentMapinstead associates the comment with the entire file.)Unfortunately,
(*printer.Config).Fprintomits those parentheses, so runninggofmton such a file breaks the association between the metadata and the function result.Example: https://play.golang.org/p/ovMOY6e5pB
formats to
Proposal
The problematic check is here:
go/src/go/printer/nodes.go
Lines 344 to 348 in 7c46b62
I suspect it would be fixed by weakening that condition to: