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条)

报告相同问题?

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)