Reputation: 17
I'm trying to use the go/ast package to perform a source to source transformation on parts of a go program. One of my goals is to automatically generate from an interface definition with stylized comments, the definition of a struct that implements that interface. I have this program (https://github.com/MarkNahabedian/defimpl) working except that my present implementation doesn't always include in the output file those packages from the input file that are required by the output file.
The current implementation is a bit kludgy in how it determines what to import. Instead I'm tryiing to use ast.Walk to look for package references. My apparently nieve assumption is that any package refe3rence would appear as the X member of an ast.BinaryExpr. From instrumenting the code that generated this (contrived test) output though
// This file was automatically generated by defimpl from c:\Users\Mark Nahabedian\go\src\defimpl\test\code.go.
package test
import "reflect"
import "defimpl/runtime"
type ThingImpl struct {
node ast.Node
}
var _ Thing = (*ThingImpl)(nil)
func init() {
inter := reflect.TypeOf(func(t Thing) {}).In(0)
var impl *ThingImpl
runtime.Register(inter, reflect.TypeOf(impl))
}
// Node is part of the Thing interface.
func (x *ThingImpl) Node() ast.Node {
return x.node
}
I see that there are no BinaryExpr nodes in the AST. My question is: what is the AST node type of "ast.Node".
I wish that the documentation of the go/ast package provided a clear association between the interface and struct types it defines.
Upvotes: 1
Views: 1030
Reputation:
The expression ast.Node
is a selector expression. The go/ast package represents the expression with the *ast.SelectorExpr type.
To understand how a language feature is represented in go/ast, parse a small program with the feature and dump the resulting tree. The spew package is a convenient tool for dumping the tree. Run an example on the playground.
Upvotes: 1