golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
123.96k stars 17.66k forks source link

x/tools/go/analysis/passes/fieldalignment: mutates AST #68735

Open adonovan opened 3 months ago

adonovan commented 3 months ago

Noticed in passing: the fieldalignment analyzer (which as of gopls/v0.17.0 is now used in x/tools only by its tests) potentially mutates the AST it is passed by the analysis framework:

x/tools/go/analysis/passes/fieldalignment/fieldalignment.go:

func fieldalignment(pass *analysis.Pass, node *ast.StructType, typ *types.Struct) {
    ...
    for _, f := range node.Fields.List {
        // TODO: Preserve comment, for now get rid of them.
        //       See https://github.com/golang/go/issues/20744
        f.Comment = nil
        f.Doc = nil

No analyzer should do that. Similar mutations in other analyzers could be a cause of a variety of bugs, inconsistencies, and crashes in tools such as gopls.

We should consider developing the deepHash approach used in x/tools/internal/refactor/inline/inline_test.go so that we can dynamically check for unwanted AST mutations around certain operations such as Analyzer.Run. (Of course, it is not cheap, and is only as good as the test coverage.)

gabyhelp commented 3 months ago

Related Issues and Documentation

(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)