如何使用 go/analysis 找到 Ident 的声明?

我使用go/analysis来创建自己的静态分析工具。我仍然不知道如何从ast中找到def信息。同上。


这是我的测试数据


package randomcheck

func xxx() {

}

func demo()  {

    xxx()

}


还有我自己的分析仪


import (

    "fmt"

    "go/ast"

    "golang.org/x/tools/go/analysis"

    "golang.org/x/tools/go/analysis/passes/inspect"

)


var name string // -name flag

var Analyzer = &analysis.Analyzer{

    Name:     "fft",

    Requires: []*analysis.Analyzer{inspect.Analyzer},

    Run:      run,

}

//pass.Fset.Position(name.Pos())

func run(pass *analysis.Pass) (interface{}, error) {

    for _, f := range pass.Files {

        ast.Inspect(f, func(node ast.Node) bool {

            name,ok := node.(*ast.Ident)

            if !ok {

                return true

            }

            if name == nil {

                return true

            }

            if pass.TypesInfo.Defs[name] != nil {

                fmt.Println("def: " ,name)

            } else {

                fmt.Println("use: ", name)

            }

            return true

        })

    }


    return nil, nil

}



output:


use:  randomcheck

def:  xxx

def:  demo

use:  xxx


我需要直接从 use:xxx 找到 def 信息 def:xxx,但我找不到有用的信息。类型信息


波斯汪
浏览 85回答 1
1回答

郎朗坤

你在寻找方法吗?以下是经过一些修改的版本:ObjectOffunc run(pass *analysis.Pass) (interface{}, error) {&nbsp; &nbsp; for _, f := range pass.Files {&nbsp; &nbsp; &nbsp; &nbsp; ast.Inspect(f, func(node ast.Node) bool {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name, ok := node.(*ast.Ident)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if !ok {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if name == nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("ident:", nodeString(node, pass.Fset))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; obj := pass.TypesInfo.ObjectOf(name)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(obj)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if obj != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("&nbsp; pos:", pass.Fset.Position(obj.Pos()))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; }&nbsp; &nbsp; return nil, nil}// nodeString formats a syntax tree in the style of gofmt.func nodeString(n ast.Node, fset *token.FileSet) string {&nbsp; &nbsp; var buf bytes.Buffer&nbsp; &nbsp; format.Node(&buf, fset, n)&nbsp; &nbsp; return buf.String()}在示例输入文件上运行时,它显示:ident: randomcheck<nil>ident: xxxfunc command-line-arguments.xxx()&nbsp; pos: /home/eliben/temp/randomcheck.go:3:6ident: demofunc command-line-arguments.demo()&nbsp; pos: /home/eliben/temp/randomcheck.go:5:6ident: xxxfunc command-line-arguments.xxx()&nbsp; pos: /home/eliben/temp/randomcheck.go:3:6请注意,最后一个 id 是作为对顶级函数的引用及其正确位置等找到的。xxxxxx()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go