go - 解析 go src,尝试将 *ast.GenDecl 转换为 types.Interface

标签 go

我正在尝试解析包含接口(interface)的源文件并找到接口(interface)定义的方法/签名。我正在使用 ast 来解析文件。我能够获得一些高级声明,例如 *ast.GenDecl,但我无法进入下一个级别来确定此类型是否为接口(interface)及其方法是什么。

这是我试图解决的脚手架类型问题,用户定义服务的接口(interface),工具将构建服务的骨架

package main

import (
        "fmt"
        "go/ast"
        "go/parser"
        "go/token"
        "reflect"
)

func main() {
        fset := token.NewFileSet()
        f, _ := parser.ParseFile(fset, "/tmp/tmp.go", `package service

        type ServiceInterface interface {
                        Create(NewServiceRequest) (JsonResponse, error)
                        Delete(DelServiceRequest) (JsonResponse, error)
        }`, 0)
        for _, v := range f.Decls {

            switch t := v.(type) {
            case *ast.FuncDecl:
                    fmt.Println("func ", t.Name.Name)
            case *ast.GenDecl:
                    switch x := t.Specs[0].(type) {
                    default:
                            fmt.Println(x, reflect.TypeOf(x))
                    }
            default:
                    fmt.Printf("skipping %t\n", t)
            }

    }
}

结果是,但我似乎根本找不到关于接口(interface)声明内部的任何信息。

&{<nil> ServiceInterface 0x8202d8260 <nil>} *ast.TypeSpec

最佳答案

在使用 AST 时,我发现使用 spew 转储示例很有帮助包裹:

    fset := token.NewFileSet()
    f, _ := parser.ParseFile(fset, "/tmp/tmp.go", `package service ....`)
    spew.Dump(f)

我发现从 spew 输出中编写所需的代码很容易。

这里有一些代码可以帮助您入门。它打印接口(interface)和方法名称:

package main

import (
  "fmt"
  "go/ast"
  "go/parser"
  "go/token"
)

func main() {
  fset := token.NewFileSet()
  f, _ := parser.ParseFile(fset, "/tmp/tmp.go", `package service

    type ServiceInterface interface {
                    Create(NewServiceRequest) (JsonResponse, error)
                    Delete(DelServiceRequest) (JsonResponse, error)
    }`, 0)
  for _, x := range f.Decls {
    if x, ok := x.(*ast.GenDecl); ok {
        if x.Tok != token.TYPE {
            continue
        }
        for _, x := range x.Specs {
            if x, ok := x.(*ast.TypeSpec); ok {
                iname := x.Name
                if x, ok := x.Type.(*ast.InterfaceType); ok {
                    for _, x := range x.Methods.List {
                        if len(x.Names) == 0 {
                            continue
                        }
                        mname := x.Names[0].Name
                        fmt.Println("interface:", iname, "method:", mname)

                    }
                }
            }
        }
    }
  }
}

http://play.golang.org/p/eNyB7O6FIc

关于go - 解析 go src,尝试将 *ast.GenDecl 转换为 types.Interface,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33836358/

相关文章:

Golang WMI查询XP

go - 为什么这个 Go 程序中会出现数据竞争?

go - 如何在 GO 中将 interface{} 转换为 map

tcp - Golang 1.5 io.Copy 用两个 TCPConn 阻塞

go - 在 Go 中使用 USB

go - 如何将字符串分配给字节数组

reference - 另一种类型中自定义类型的 Golang slice 作为引用

json - 在特定结构中解码 Json 数据

go - 有没有一种方法可以在不使用自定义结构的情况下检索实体?

go - 什么是 Golang 中的无效内存地址或零指针取消引用,我该如何解决?