Skip to content

go/ast: CommentMap heuristic sensitive to parentheses around unnamed result type #23040

Description

@bcmills

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:

go/src/go/printer/nodes.go

Lines 344 to 348 in 7c46b62

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)) {

Metadata

Metadata

Assignees

No one assigned

    Labels

    NeedsFixThe path to resolution is known, but the work has not been done.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions