如何找到golang SSA函数的返回类型

huangapple go评论78阅读模式
英文:

How to find out golang SSA function return type

问题

你好,我是你的中文翻译助手。以下是你要翻译的内容:

你好,我是新手,正在尝试使用Go语言的SSA包来分析我们的代码。例如,我想打印出包中所有函数的信息,示例代码如下:

dir := 项目路径
cfg := packages.Config{
	Mode: packages.LoadAllSyntax,
	Dir: dir,
}

initial, _ := packages.Load(&cfg, "./")

// 为类型正确的包及其依赖项创建SSA包。
prog, _ := ssautil.AllPackages(initial, 0)

// 为整个程序构建SSA代码。
prog.Build()
callGraph = cha.CallGraph(prog)

for f, node := range callGraph.Nodes{
    // f 是 ssa.Function 类型
    fmt.Println("func:", f, f.Name(), f.Syntax(), f.Params)
}

然后我发现无法通过使用SSA工具或其他工具来访问此函数的返回值类型(参考文档 https://pkg.go.dev/golang.org/x/tools/go/ssa#Function)。是否有办法通过使用SSA工具或其他工具来分析函数的返回值类型?

英文:

hello i am new to static analysis and try to use golang's SSA package to analyze our code. For example i want to print all function infos in the package, the example code is:

dir := PROJECT_PATH
cfg := packages.Config{
	Mode: packages.LoadAllSyntax,
	Dir: dir,
}

initial, _ := packages.Load(&cfg, "./")

// Create SSA packages for well-typed packages and their dependencies.
prog, _ := ssautil.AllPackages(initial, 0)

// Build SSA code for the whole program.
prog.Build()
callGraph = cha.CallGraph(prog)

for f, node := range callGraph.Nodes{
    // f is of ssa.Function 
    fmt.Println("func:", f, f.Name(), f.Syntax(), f.Params)
}

then i found i have no way to access the type of return values for this function (refering to the documents https://pkg.go.dev/golang.org/x/tools/go/ssa#Function)
Is there any way to analyze the type of function's return value by using ssa tools or other tools?

答案1

得分: 1

你可以通过f.Signature.Results()来获取函数的签名和返回类型。

如果你不需要调用图遍历,你可以直接从ssa.package结构中获取函数信息。

for k, v := range pckg.Members {
   c, ok := v.(*ssa.Function)
   if ok{
    ...
   }
}
英文:

You can get the signature and therefore return type of a function via

 f.Signature.Results()

If you don't need callgraph traversal you can directly get function info from ssa.package struct

for k, v := range pckg.Members {
   c, ok := v.(*ssa.Function)
   if ok{
    ...
   }
}

huangapple
  • 本文由 发表于 2021年5月20日 12:09:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/67613864.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定