goabstract-syntax-treelint

How to use AST to understand how a golang struct field is created?


First time asking a question here, apologies if this isn't sufficiently clear :)

I have a list of Foos, where Foo is some struct type imported upstream. Foo has some field Bar that is a bit complicated to calculate. Historically creation of a Foo has looked like this:

bar := someComplicatedAndBespokeBarCalculator(...)
myFoo := Foo{
    ...
    Bar: bar
}

but we recently created a standardized method for calculating Bar. The now-recommended design pattern is:

myFooInline := Foo{
    ...
    Bar: standardizedBarCalculator(...)
}

I would like to set up a custom linter rule that parses all my Foos with the go/ast library to assert that all Foos are created with the second, inline pattern such that we can ensure that no Foo is created without using the standardizedBarCalculator. Very possibly I'm doing something wrong, but trying to use ast.Inspect and cast an ast.Node into an ast.StructType only seems to work when I'm defining a new struct, not when I'm instantiating an instance of an upstream-defined struct. So, I'm struggling to figure out how to do this. Any guidance would be appreciated!


Solution

  • The steps you're looking for should be approximately something like this: