Debian Codegraph @

go/types/typeutil/callee.go

raw symbols SCIP
1 // Copyright 2018 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package typeutil
6
7 import (
8 "go/ast"
9 "go/types"
10 _ "unsafe" // for linkname
11 )
12
13 // Callee returns the named target of a function call, if any:
14 // a function, method, builtin, or variable.
15 // It returns nil for a T(x) conversion.
16 //
17 // Functions and methods may potentially have type parameters.
18 //
19 // Note: for calls of instantiated functions and methods, Callee returns
20 // the corresponding generic function or method on the generic type.
21 func Callee(info *types.Info, call *ast.CallExpr) types.Object {
22 obj := info.Uses[usedIdent(info, call.Fun)]
23 if obj == nil {
24 return nil
25 }
26 if _, ok := obj.(*types.TypeName); ok {
27 return nil
28 }
29 return obj
30 }
31
32 // StaticCallee returns the target (function or method) of a static function
33 // call, if any. It returns nil for calls to builtins.
34 //
35 // Note: for calls of instantiated functions and methods, StaticCallee returns
36 // the corresponding generic function or method on the generic type.
37 func StaticCallee(info *types.Info, call *ast.CallExpr) *types.Func {
38 obj := info.Uses[usedIdent(info, call.Fun)]
39 fn, _ := obj.(*types.Func)
40 if fn == nil || interfaceMethod(fn) {
41 return nil
42 }
43 return fn
44 }
45
46 // usedIdent is the implementation of [internal/typesinternal.UsedIdent].
47 // It returns the identifier associated with e.
48 // See typesinternal.UsedIdent for a fuller description.
49 // This function should live in typesinternal, but cannot because it would
50 // create an import cycle.
51 //
52 //go:linkname usedIdent golang.org/x/tools/go/types/typeutil.usedIdent
53 func usedIdent(info *types.Info, e ast.Expr) *ast.Ident {
54 if info.Types == nil || info.Uses == nil {
55 panic("one of info.Types or info.Uses is nil; both must be populated")
56 }
57 // Look through type instantiation if necessary.
58 switch d := ast.Unparen(e).(type) {
59 case *ast.IndexExpr:
60 if info.Types[d.Index].IsType() {
61 e = d.X
62 }
63 case *ast.IndexListExpr:
64 e = d.X
65 }
66
67 switch e := ast.Unparen(e).(type) {
68 // info.Uses always has the object we want, even for selector expressions.
69 // We don't need info.Selections.
70 // See go/types/recording.go:recordSelection.
71 case *ast.Ident:
72 return e
73 case *ast.SelectorExpr:
74 return e.Sel
75 }
76 return nil
77 }
78
79 // interfaceMethod reports whether its argument is a method of an interface.
80 // This function should live in typesinternal, but cannot because it would create an import cycle.
81 //
82 //go:linkname interfaceMethod golang.org/x/tools/go/types/typeutil.interfaceMethod
83 func interfaceMethod(f *types.Func) bool {
84 recv := f.Signature().Recv()
85 return recv != nil && types.IsInterface(recv.Type())
86 }