sh icon indicating copy to clipboard operation
sh copied to clipboard

Feature Request: Allow replacing current node during Walk

Open mgrubb opened this issue 6 months ago • 1 comments

I'm working on a program similar to webpack for Bash. A bash script can be developed across multiple files and source library files, this program would go through the scripts and inline all the sourced files to make one "uber" script. I'm also thinking of adding some tree-shaking capabilities so that only used library functions will get inlined but that is not part of the mvp. What I'd like to be able to do at first is find all instances where a file is sourced (I can already do this with current Walk) and then create a new syntax node for a function definition and replace the CallExpr node with the newly constructed node. Alternatively perhaps something a bit easier would be to construct a whole new syntax tree during the walk by adding nodes to the empty tree and then when the walk finds something it's interested in it can insert a different node into the second tree. This would also open up features for creating more general pre-processor programs.

Is this feasible without drastically altering the architecture, or are there major challenges that would make this infeasible or too complex? I'd be happy to give the implementation a try if it's not something you're opposed to.

mgrubb avatar Jun 06 '25 16:06 mgrubb

This is doable, but it would need a new API. For example, see https://pkg.go.dev/golang.org/x/tools/go/ast/astutil#Apply, which uses a "cursor" to get the current node, and allow replacing it or deleting it.

A new iteration of that is now available at https://pkg.go.dev/golang.org/x/tools/go/ast/inspector, with learned lessons from the older API above. I'd take that as an example to implement a smaller initial version of the API.

Patches welcome if you'd like to try. Some tests would be needed as well.

mvdan avatar Jun 25 '25 22:06 mvdan