Debian Codegraph @

gopls/internal/golang/call_hierarchy.go

raw symbols SCIP
1 // Copyright 2020 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 golang
6
7 import (
8 "context"
9 "errors"
10 "fmt"
11 "go/ast"
12 "go/types"
13
14 goastutil "golang.org/x/tools/go/ast/astutil"
15 "golang.org/x/tools/go/types/typeutil"
16 "golang.org/x/tools/gopls/internal/cache"
17 "golang.org/x/tools/gopls/internal/cache/parsego"
18 "golang.org/x/tools/gopls/internal/file"
19 "golang.org/x/tools/gopls/internal/protocol"
20 "golang.org/x/tools/gopls/internal/util/moremaps"
21 "golang.org/x/tools/internal/astutil"
22 "golang.org/x/tools/internal/event"
23 "golang.org/x/tools/internal/typesinternal"
24 )
25
26 // PrepareCallHierarchy returns an array of CallHierarchyItem for a file and the position within the file.
27 func PrepareCallHierarchy(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, rng protocol.Range) ([]protocol.CallHierarchyItem, error) {
28 ctx, done := event.Start(ctx, "golang.PrepareCallHierarchy")
29 defer done()
30
31 pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, fh.URI())
32 if err != nil {
33 return nil, err
34 }
35 start, end, err := pgf.RangePos(rng)
36 if err != nil {
37 return nil, err
38 }
39 obj, err := callHierarchyFuncAtRange(pkg.TypesInfo(), pgf, astutil.RangeOf(start, end))
40 if err != nil {
41 return nil, err
42 }
43 declLoc, err := ObjectLocation(ctx, pkg.FileSet(), snapshot, obj)
44 if err != nil {
45 return nil, err
46 }
47
48 return []protocol.CallHierarchyItem{{
49 Name: obj.Name(),
50 Kind: protocol.Function,
51 Tags: []protocol.SymbolTag{},
52 Detail: callHierarchyItemDetail(obj, declLoc),
53 URI: declLoc.URI,
54 Range: declLoc.Range,
55 SelectionRange: declLoc.Range,
56 }}, nil
57 }
58
59 // IncomingCalls returns an array of CallHierarchyIncomingCall for a file and the position within the file.
60 func IncomingCalls(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, rng protocol.Range) ([]protocol.CallHierarchyIncomingCall, error) {
61 ctx, done := event.Start(ctx, "golang.IncomingCalls")
62 defer done()
63
64 refs, err := references(ctx, snapshot, fh, rng, false)
65 if err != nil {
66 if errors.Is(err, ErrNoIdentFound) || errors.Is(err, errNoObjectFound) {
67 return nil, nil
68 }
69 return nil, err
70 }
71
72 // Group references by their enclosing function declaration.
73 incomingCalls := make(map[protocol.Location]*protocol.CallHierarchyIncomingCall)
74 for _, ref := range refs {
75 callItem, err := enclosingNodeCallItem(ctx, snapshot, ref.pkgPath, ref.location)
76 if err != nil {
77 event.Error(ctx, fmt.Sprintf("error getting enclosing node for %q", ref.pkgPath), err)
78 continue
79 }
80 loc := callItem.URI.Location(callItem.Range)
81 call, ok := incomingCalls[loc]
82 if !ok {
83 call = &protocol.CallHierarchyIncomingCall{From: callItem}
84 incomingCalls[loc] = call
85 }
86 call.FromRanges = append(call.FromRanges, ref.location.Range)
87 }
88
89 // Flatten the map of pointers into a slice of values.
90 incomingCallItems := make([]protocol.CallHierarchyIncomingCall, 0, len(incomingCalls))
91 for _, callItem := range moremaps.SortedFunc(incomingCalls, protocol.CompareLocation) {
92 incomingCallItems = append(incomingCallItems, *callItem)
93 }
94 return incomingCallItems, nil
95 }
96
97 // enclosingNodeCallItem creates a CallHierarchyItem representing the function call at loc.
98 func enclosingNodeCallItem(ctx context.Context, snapshot *cache.Snapshot, pkgPath PackagePath, loc protocol.Location) (protocol.CallHierarchyItem, error) {
99 // Parse the file containing the reference.
100 fh, err := snapshot.ReadFile(ctx, loc.URI)
101 if err != nil {
102 return protocol.CallHierarchyItem{}, err
103 }
104 // TODO(adonovan): opt: before parsing, trim the bodies of functions
105 // that don't contain the reference, using either a scanner-based
106 // implementation such as https://go.dev/play/p/KUrObH1YkX8
107 // (~31% speedup), or a byte-oriented implementation (2x speedup).
108 pgf, err := snapshot.ParseGo(ctx, fh, parsego.Full)
109 if err != nil {
110 return protocol.CallHierarchyItem{}, err
111 }
112 start, end, err := pgf.RangePos(loc.Range)
113 if err != nil {
114 return protocol.CallHierarchyItem{}, err
115 }
116
117 // Find the enclosing named function, if any.
118 //
119 // It is tempting to treat anonymous functions as nodes in the
120 // call hierarchy, and historically we used to do that,
121 // poorly; see #64451. However, it is impossible to track
122 // references to anonymous functions without much deeper
123 // analysis. Local analysis is tractable, but ultimately it
124 // can only detect calls from the outer function to the inner
125 // function.
126 //
127 // It is simpler and clearer to treat the top-level named
128 // function and all its nested functions as one entity, and it
129 // allows users to recursively expand the tree where, before,
130 // the chain would be broken by each lambda.
131 //
132 // If the selection is in a global var initializer,
133 // default to the file's package declaration.
134 path, _ := goastutil.PathEnclosingInterval(pgf.File, start, end)
135 var (
136 name = pgf.File.Name.Name
137 kind = protocol.Package
138 )
139 start, end = pgf.File.Name.Pos(), pgf.File.Name.End()
140 for _, node := range path {
141 switch node := node.(type) {
142 case *ast.FuncDecl:
143 name = node.Name.Name
144 start, end = node.Name.Pos(), node.Name.End()
145 kind = protocol.Function
146
147 case *ast.FuncLit:
148 // If the call comes from a FuncLit with
149 // no enclosing FuncDecl, then use the
150 // FuncLit's extent.
151 name = "func"
152 start, end = node.Pos(), node.Type.End() // signature, sans body
153 kind = protocol.Function
154
155 case *ast.ValueSpec:
156 // If the call comes from a var (or,
157 // theoretically, const) initializer outside
158 // any function, then use the ValueSpec.Names span.
159 name = "init"
160 start, end = node.Names[0].Pos(), node.Names[len(node.Names)-1].End()
161 kind = protocol.Variable
162 }
163 }
164
165 rng, err := pgf.PosRange(start, end)
166 if err != nil {
167 return protocol.CallHierarchyItem{}, err
168 }
169
170 return protocol.CallHierarchyItem{
171 Name: name,
172 Kind: kind,
173 Tags: []protocol.SymbolTag{},
174 Detail: fmt.Sprintf("%s • %s", pkgPath, fh.URI().Base()),
175 URI: loc.URI,
176 Range: rng,
177 SelectionRange: rng,
178 }, nil
179 }
180
181 // OutgoingCalls returns an array of CallHierarchyOutgoingCall for a file and the position within the file.
182 func OutgoingCalls(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, pp protocol.Position) ([]protocol.CallHierarchyOutgoingCall, error) {
183 ctx, done := event.Start(ctx, "golang.OutgoingCalls")
184 defer done()
185
186 pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, fh.URI())
187 if err != nil {
188 return nil, err
189 }
190 pos, err := pgf.PositionPos(pp)
191 if err != nil {
192 return nil, err
193 }
194 obj, err := callHierarchyFuncAtRange(pkg.TypesInfo(), pgf, astutil.RangeOf(pos, pos))
195 if err != nil {
196 return nil, err
197 }
198 if isBuiltin(obj) {
199 return nil, nil // built-in functions have no outgoing calls
200 }
201
202 declPkg, declPGF, declPos, err := NarrowestDeclaringPackage(ctx, snapshot, pkg, obj)
203 if err != nil {
204 return nil, err
205 }
206
207 declNode, _, _, _ := findDeclInfo([]*ast.File{declPGF.File}, declPos)
208 if declNode == nil {
209 // TODO(rfindley): why don't we return an error here, or even bug.Errorf?
210 return nil, nil
211 // return nil, bug.Errorf("failed to find declaration for %v", obj)
212 }
213
214 // Find calls to known functions/methods,
215 // including interface methods, and built-ins.
216 var callRanges []astutil.Range
217 for n := range ast.Preorder(declNode) {
218 if call, ok := n.(*ast.CallExpr); ok {
219 callee := typeutil.Callee(pkg.TypesInfo(), call)
220 switch callee.(type) {
221 case *types.Func, *types.Builtin:
222 // Skip trivial builtins (e.g. len)
223 // but allow unsafe.Slice, etc.
224 if callee.Pkg() == nil {
225 continue
226 }
227 id := typesinternal.UsedIdent(pkg.TypesInfo(), call.Fun)
228 callRanges = append(callRanges, astutil.RangeOf(id.Pos(), id.End()))
229 }
230 }
231 }
232
233 outgoingCalls := make(map[protocol.Location]*protocol.CallHierarchyOutgoingCall)
234 for _, callRange := range callRanges {
235 obj, err := callHierarchyFuncAtRange(declPkg.TypesInfo(), declPGF, callRange)
236 if err != nil {
237 continue // ignore
238 }
239
240 loc, err := ObjectLocation(ctx, declPkg.FileSet(), snapshot, obj)
241 if err != nil {
242 return nil, err
243 }
244
245 outgoingCall, ok := outgoingCalls[loc]
246 if !ok {
247 outgoingCall = &protocol.CallHierarchyOutgoingCall{
248 To: protocol.CallHierarchyItem{
249 Name: obj.Name(),
250 Kind: protocol.Function,
251 Tags: []protocol.SymbolTag{},
252 Detail: callHierarchyItemDetail(obj, loc),
253 URI: loc.URI,
254 Range: loc.Range,
255 SelectionRange: loc.Range,
256 },
257 }
258 outgoingCalls[loc] = outgoingCall
259 }
260
261 rng, err := declPGF.PosRange(callRange.Pos(), callRange.End())
262 if err != nil {
263 return nil, err
264 }
265 outgoingCall.FromRanges = append(outgoingCall.FromRanges, rng)
266 }
267
268 outgoingCallItems := make([]protocol.CallHierarchyOutgoingCall, 0, len(outgoingCalls))
269 for _, callItem := range moremaps.SortedFunc(outgoingCalls, protocol.CompareLocation) {
270 outgoingCallItems = append(outgoingCallItems, *callItem)
271 }
272 return outgoingCallItems, nil
273 }
274
275 func callHierarchyItemDetail(obj types.Object, loc protocol.Location) string {
276 detail := loc.URI.Base()
277 if obj.Pkg() != nil {
278 detail = fmt.Sprintf("%s • %s", obj.Pkg().Path(), detail)
279 }
280 return detail
281 }
282
283 // callHierarchyFuncAtRange returns the function symbol (Func or Builtin) referred
284 // to by the identifier at the specified range.
285 func callHierarchyFuncAtRange(info *types.Info, pgf *parsego.File, rng astutil.Range) (types.Object, error) {
286 cur, ok := pgf.Cursor().FindByPos(rng.Pos(), rng.End())
287 if !ok {
288 return nil, fmt.Errorf("no enclosing syntax") // can't happen
289 }
290 id, ok := cur.Node().(*ast.Ident)
291 if !ok {
292 return nil, fmt.Errorf("identifier not found")
293 }
294 switch obj := info.ObjectOf(id).(type) {
295 case *types.Func, *types.Builtin:
296 return obj, nil
297 case nil:
298 return nil, fmt.Errorf("no symbol here")
299 default:
300 return nil, fmt.Errorf("%s is not a function", obj.Name())
301 }
302 }