猿问

如何从 *types.Named 获取类型

我试图找到作为第一个参数的funcs 的函数调用。context.Context


我已经能够执行下面显示的操作,但我一直坚持从*types.Named. 我怎样才能做到这一点?


package main


import (

    "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.Signature

Type :  *types.Named

named : *types.Named

named.Obj() : *types.TypeName

typ:  *types.Interface


MMTTMM
浏览 102回答 1
1回答

幕布斯6054654

我最终得到了这样的结果:func funcHasContextContextAsFirstParam(pass *analysis.Pass, expr ast.Expr) bool {&nbsp; &nbsp; t := pass.TypesInfo.TypeOf(expr)&nbsp; &nbsp; if t == nil {&nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; }&nbsp; &nbsp; bt, ok := t.Underlying().(*types.Signature)&nbsp; &nbsp; if !ok {&nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; }&nbsp; &nbsp; params := bt.Params()&nbsp; &nbsp; if params.Len() < 1 {&nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; }&nbsp; &nbsp; param := params.At(0)&nbsp; &nbsp; named, ok := param.Type().(*types.Named)&nbsp; &nbsp; if !ok {&nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; }&nbsp; &nbsp; namedObj := named.Obj()&nbsp; &nbsp; if namedObj.Name() != "Context" || namedObj.Pkg().Name() != "context" {&nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; }&nbsp; &nbsp; return true}
随时随地看视频慕课网APP

相关分类

Go
我要回答