在AST中查找包引用

时间:2020-10-12 15:38:07

标签: go abstract-syntax-tree

我正在尝试使用go / ast软件包对go程序的某些部分执行从源到源的转换。我的目标之一是从带有风格化注释的接口定义自动生成实现该接口的结构的定义。我有这个程序(https://github.com/MarkNahabedian/defimpl)可以正常工作,除了我当前的实现并不总是在输出文件中包括输出文件所需的那些来自输入文件的包。

当前的实现方式对于确定要导入的内容有些困惑。相反,我正在尝试使用ast.Walk查找程序包引用。我的明显假设是,任何程序包引用都将作为ast.BinaryExpr的X成员出现。通过检测通过代码生成此(人工测试)输出的代码

// 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
}

我看到AST中没有BinaryExpr节点。我的问题是:“ ast.Node”的AST节点类型是什么。

我希望go / ast软件包的文档在接口和它定义的结构类型之间提供清晰的关联。

1 个答案:

答案 0 :(得分:1)

表达式ast.Node是一个selector表达式。 go / ast包表示*ast.SelectorExpr类型的表达式。

要了解go / ast中语言功能的表示方式,请解析具有该功能的小程序并转储结果树。 spew package是转储树的便捷工具。运行an example on the playground

相关问题