gpt4 book ai didi

parsing - 如何解析方法声明?

转载 作者:IT王子 更新时间:2023-10-29 00:42:22 24 4
gpt4 key购买 nike

我正在尝试解析方法声明。基本上,我需要获取接收者基本类型 (type hello) 和返回类型(notypeerror)的语法节点。 ast 包看起来很简单,但由于某种原因我没有得到我需要的数据(即字段报告为零)。

唯一有用的数据似乎只在类型为 interface{}Object -> Decl 字段中提供,所以我认为我无法序列化它。

如有任何帮助,我们将不胜感激。代码如下:

package main

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

func main() {
// src is the input for which we want to inspect the AST.
src := `
package mypack
// type hello is a cool type
type hello string

// type notype is not that cool
type notype int

// func printme is like nothing else.
func (x *hello)printme(s string)(notype, error){
return 0, nil
}
`
// Create the AST by parsing src.
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, "src.go", src, 0)
if err != nil {
panic(err)
}

// Inspect the AST and find our function
var mf ast.FuncDecl
ast.Inspect(f, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.FuncDecl:
mf = *x
}
return true
})

if mf.Recv != nil {
fmt.Printf("\n receivers:")
for _, v := range mf.Recv.List {
fmt.Printf(",tag %v", v.Tag)
for _, xv := range v.Names {
fmt.Printf("name %v, decl %v, data %v, type %v",
xv.Name, xv.Obj.Decl, xv.Obj.Data, xv.Obj.Type)
}
}
}
}

Playground

最佳答案

要获得类型,您需要查看 Type 属性,它可以是 ast.StarExprast.Ident

这里看看this :

package main

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

func main() {
// src is the input for which we want to inspect the AST.
src := `
package mypack
// type hello is a cool type
type hello string

// type notype is not that cool
type notype int

// printme is like nothing else.
func (x *hello)printme(s string)(notype, error){
return 0, nil
}
`
// Create the AST by parsing src.
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, "src.go", src, 0)
if err != nil {
panic(err)
}

// Inspect the AST and find our function
var mf ast.FuncDecl
ast.Inspect(f, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.FuncDecl:
mf = *x
}
return true
})

if mf.Recv != nil {
for _, v := range mf.Recv.List {
fmt.Print("recv type : ")
switch xv := v.Type.(type) {
case *ast.StarExpr:
if si, ok := xv.X.(*ast.Ident); ok {
fmt.Println(si.Name)
}
case *ast.Ident:
fmt.Println(xv.Name)
}
}
}
}

关于parsing - 如何解析方法声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28246970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com