doudou5023 2018-10-25 16:53
浏览 15
已采纳

解析Golang变量

I'm trying to static analyze Go files. For this I need to parse variables of the following format:

shape.color = color.red

I need to find all variables accessed with dot notation. For example, I need to know that shape variable has the color attribute. And also need that color variable has red attribute. Im trying to use the go/ast and go/parser package but cant figure out a way to do it.

N.B. If it's something like shape.color() i.e, a method, then it shouldn't be counted

  • 写回答

3条回答 默认 最新

  • dongyuxiao6295 2018-10-26 00:09
    关注

    Ah! The following code prints all the variables accessed with dot notation!

    package main
    
    import (
        "fmt"
        "go/ast"
        "go/parser"
        "go/token"
        "log"
    )
    
    func main() {
        v := visitor{}
        filename := "test.go"
    
        fset := token.NewFileSet()
        f, err := parser.ParseFile(fset, filename, nil, 0)
    
        if err != nil {
            log.Fatal(err)
        }
    
        ast.Walk(&v, f)
    }
    
    type visitor struct {
    }
    
    func (v *visitor) Visit(n ast.Node) ast.Visitor {
        if n == nil {
            return v
        }
    
        if selectorExp, ok := n.(*ast.SelectorExpr); ok {
            if x, ok := selectorExp.X.(*ast.Ident); ok {
                if x.Obj == nil {
                    return v
                }  
    
                fmt.Printf("%s.%s
    ", x.Name, selectorExp.Sel.Name)
            }
        }
        return v
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行