1 回答

TA貢獻1921條經(jīng)驗 獲得超9個贊
你在尋找方法嗎?以下是經(jīng)過一些修改的版本:ObjectOf
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
}
fmt.Println("ident:", nodeString(node, pass.Fset))
obj := pass.TypesInfo.ObjectOf(name)
fmt.Println(obj)
if obj != nil {
fmt.Println(" pos:", pass.Fset.Position(obj.Pos()))
}
return true
})
}
return nil, nil
}
// nodeString formats a syntax tree in the style of gofmt.
func nodeString(n ast.Node, fset *token.FileSet) string {
var buf bytes.Buffer
format.Node(&buf, fset, n)
return buf.String()
}
在示例輸入文件上運行時,它顯示:
ident: randomcheck
<nil>
ident: xxx
func command-line-arguments.xxx()
pos: /home/eliben/temp/randomcheck.go:3:6
ident: demo
func command-line-arguments.demo()
pos: /home/eliben/temp/randomcheck.go:5:6
ident: xxx
func command-line-arguments.xxx()
pos: /home/eliben/temp/randomcheck.go:3:6
請注意,最后一個 id 是作為對頂級函數(shù)的引用及其正確位置等找到的。xxxxxx()
- 1 回答
- 0 關(guān)注
- 100 瀏覽
添加回答
舉報