Debian Codegraph @

gopls/internal/util/cursorutil/util.go

raw symbols SCIP
1 // Copyright 2025 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 cursorutil provides utility functions for working with [inspector.Cursor].
6 //
7 // It should create no additional dependencies beyond those of Cursor
8 // itself, so that functions can be promoted to the public API of
9 // Cursor in due course.
10 package cursorutil
11
12 import (
13 "go/ast"
14
15 "golang.org/x/tools/go/ast/inspector"
16 )
17
18 // FirstEnclosing returns the first value from [cursor.Enclosing] as
19 // both a designated type and a [inspector.Cursor] pointing to it.
20 //
21 // It returns the zero value if it is not found.
22 //
23 // A common usage is:
24 //
25 // call, callCur := cursorutil.FirstEnclosing[*ast.CallExpr](cur)
26 // if call == nil {
27 // // Not Found
28 // }
29 func FirstEnclosing[N ast.Node](cur inspector.Cursor) (N, inspector.Cursor) {
30 var typ N
31 for cur := range cur.Enclosing(typ) {
32 return cur.Node().(N), cur
33 }
34 return typ, inspector.Cursor{}
35 }
36
37 // Path returns the specified node followed by all its ancestors up to the file.
38 // Use it as an adaptor between cursors and code that works with PathEnclosingInterval.
39 // Ultimately all such code should be eliminated.
40 func Path(cur inspector.Cursor) (path []ast.Node) {
41 for cur := range cur.Enclosing() {
42 path = append(path, cur.Node())
43 }
44 return
45 }