我试图找到作为第一个参数的funcs 的函数调用。context.Context我已经能够执行下面显示的操作,但我一直坚持从*types.Named. 我怎样才能做到这一点?package mainimport ( "bytes" "context" "fmt" "go/ast" "go/printer" "go/token" "go/types" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/singlechecker")var Analyzer = &analysis.Analyzer{ Name: "addlint", Doc: "reports integer additions", Run: run,}func main() { singlechecker.Main(Analyzer)}func funcHasContextContextAsFirstParam(pass *analysis.Pass, expr ast.Expr) bool { t := pass.TypesInfo.TypeOf(expr) if t == nil { return false } bt, ok := t.Underlying().(*types.Signature) if !ok { return false } fmt.Printf("signature: %+v - %T\n", bt, bt) params := bt.Params() for i := 0; i < params.Len(); i++ { v := params.At(i) fmt.Printf("Type : %T\n", v.Type()) if named, ok := v.Type().(*types.Named); ok { // fmt.Printf("named : %v - %T\n", named.Obj(), named.Obj()) fmt.Printf("named : %T\n", named) fmt.Printf("named.Obj() : %T\n", named.Obj()) typ := named.Underlying() fmt.Printf("typ: %T\n", typ.Underlying()) if _, ok = typ.(context.Context); ok { fmt.Printf("context.Context type!\n") } } } return true}func run(pass *analysis.Pass) (interface{}, error) { for _, file := range pass.Files { ast.Inspect(file, func(n ast.Node) bool { be, ok := n.(*ast.CallExpr) if !ok { return true }这就是我得到的输出:call expression &{Fun:foo Lparen:6160580 Args:[c 0xc0003c5780 0xc0003c57c0] Ellipsis:0 Rparen:6160596}signature: func(ctx context.Context, n int, str string) - *types.SignatureType : *types.Namednamed : *types.Namednamed.Obj() : *types.TypeNametyp: *types.Interface
1 回答
幕布斯6054654
TA贡献1876条经验 获得超7个赞
我最终得到了这样的结果:
func funcHasContextContextAsFirstParam(pass *analysis.Pass, expr ast.Expr) bool {
t := pass.TypesInfo.TypeOf(expr)
if t == nil {
return false
}
bt, ok := t.Underlying().(*types.Signature)
if !ok {
return false
}
params := bt.Params()
if params.Len() < 1 {
return false
}
param := params.At(0)
named, ok := param.Type().(*types.Named)
if !ok {
return false
}
namedObj := named.Obj()
if namedObj.Name() != "Context" || namedObj.Pkg().Name() != "context" {
return false
}
return true
}
- 1 回答
- 0 关注
- 101 浏览
添加回答
举报
0/150
提交
取消