| 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 typeindex provides an [Index] of type information for a |
| 6 | // package, allowing efficient lookup of, say, whether a given symbol |
| 7 | // is referenced and, if so, where from; or of the [inspector.Cursor] for |
| 8 | // the declaration of a particular [types.Object] symbol. |
| 9 | package typeindex |
| 10 | |
| 11 | import ( |
| 12 | "encoding/binary" |
| 13 | "go/ast" |
| 14 | "go/types" |
| 15 | "iter" |
| 16 | |
| 17 | "golang.org/x/tools/go/ast/edge" |
| 18 | "golang.org/x/tools/go/ast/inspector" |
| 19 | "golang.org/x/tools/go/types/typeutil" |
| 20 | "golang.org/x/tools/internal/astutil" |
| 21 | "golang.org/x/tools/internal/typesinternal" |
| 22 | ) |
| 23 | |
| 24 | // New constructs an Index for the package of type-annotated syntax |
| 25 | // |
| 26 | // TODO(adonovan): accept a FileSet too? |
| 27 | // We regret not requiring one in inspector.New. |
| 28 | func New(inspect *inspector.Inspector, pkg *types.Package, info *types.Info) *Index { |
| 29 | ix := &Index{ |
| 30 | inspect: inspect, |
| 31 | info: info, |
| 32 | packages: make(map[string]*types.Package), |
| 33 | def: make(map[types.Object]inspector.Cursor), |
| 34 | uses: make(map[types.Object]*uses), |
| 35 | } |
| 36 | |
| 37 | addPackage := func(pkg2 *types.Package) { |
| 38 | if pkg2 != nil && pkg2 != pkg { |
| 39 | ix.packages[pkg2.Path()] = pkg2 |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | for cur := range inspect.Root().Preorder((*ast.ImportSpec)(nil), (*ast.Ident)(nil)) { |
| 44 | switch n := cur.Node().(type) { |
| 45 | case *ast.ImportSpec: |
| 46 | // Index direct imports, including blank ones. |
| 47 | if pkgname := info.PkgNameOf(n); pkgname != nil { |
| 48 | addPackage(pkgname.Imported()) |
| 49 | } |
| 50 | |
| 51 | case *ast.Ident: |
| 52 | // Index all defining and using identifiers. |
| 53 | if obj := info.Defs[n]; obj != nil { |
| 54 | ix.def[obj] = cur |
| 55 | } |
| 56 | |
| 57 | if obj := info.Uses[n]; obj != nil { |
| 58 | // Index indirect dependencies (via fields and methods). |
| 59 | if !typesinternal.IsPackageLevel(obj) { |
| 60 | addPackage(obj.Pkg()) |
| 61 | } |
| 62 | |
| 63 | for { |
| 64 | us, ok := ix.uses[obj] |
| 65 | if !ok { |
| 66 | us = &uses{} |
| 67 | us.code = us.initial[:0] |
| 68 | ix.uses[obj] = us |
| 69 | } |
| 70 | delta := cur.Index() - us.last |
| 71 | if delta < 0 { |
| 72 | panic("non-monotonic") |
| 73 | } |
| 74 | us.code = binary.AppendUvarint(us.code, uint64(delta)) |
| 75 | us.last = cur.Index() |
| 76 | |
| 77 | // If n is a selection of a field or method of an instantiated |
| 78 | // type, also record a use of the generic field or method. |
| 79 | obj, ok = objectOrigin(obj) |
| 80 | if !ok { |
| 81 | break |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | } |
| 86 | } |
| 87 | return ix |
| 88 | } |
| 89 | |
| 90 | // objectOrigin returns the generic object for obj if it is a field or |
| 91 | // method of an instantied type; zero otherwise. |
| 92 | // |
| 93 | // (This operation is appropriate only for selections. |
| 94 | // Lexically resolved references always resolve to the generic. |
| 95 | // Although Named and Alias types also use Origin to express |
| 96 | // an instance/generic distinction, that's in the domain |
| 97 | // of Types; their TypeName objects always refer to the generic.) |
| 98 | func objectOrigin(obj types.Object) (types.Object, bool) { |
| 99 | var origin types.Object |
| 100 | switch obj := obj.(type) { |
| 101 | case *types.Func: |
| 102 | if obj.Signature().Recv() != nil { |
| 103 | origin = obj.Origin() // G[int].method -> G[T].method |
| 104 | } |
| 105 | case *types.Var: |
| 106 | if obj.IsField() { |
| 107 | origin = obj.Origin() // G[int].field -> G[T].field |
| 108 | } |
| 109 | } |
| 110 | if origin != nil && origin != obj { |
| 111 | return origin, true |
| 112 | } |
| 113 | return nil, false |
| 114 | } |
| 115 | |
| 116 | // An Index holds an index mapping [types.Object] symbols to their syntax. |
| 117 | // In effect, it is the inverse of [types.Info]. |
| 118 | type Index struct { |
| 119 | inspect *inspector.Inspector |
| 120 | info *types.Info |
| 121 | packages map[string]*types.Package // packages of all symbols referenced from this package |
| 122 | def map[types.Object]inspector.Cursor // Cursor of *ast.Ident that defines the Object |
| 123 | uses map[types.Object]*uses // Cursors of *ast.Idents that use the Object |
| 124 | } |
| 125 | |
| 126 | // A uses holds the list of Cursors of Idents that use a given symbol. |
| 127 | // |
| 128 | // The Uses map of [types.Info] is substantial, so it pays to compress |
| 129 | // its inverse mapping here, both in space and in CPU due to reduced |
| 130 | // allocation. A Cursor is 2 words; a Cursor.Index is 4 bytes; but |
| 131 | // since Cursors are naturally delivered in ascending order, we can |
| 132 | // use varint-encoded deltas at a cost of only ~1.7-2.2 bytes per use. |
| 133 | // |
| 134 | // Many variables have only one or two uses, so their encoded uses may |
| 135 | // fit in the 4 bytes of initial, saving further CPU and space |
| 136 | // essentially for free since the struct's size class is 4 words. |
| 137 | type uses struct { |
| 138 | code []byte // varint-encoded deltas of successive Cursor.Index values |
| 139 | last int32 // most recent Cursor.Index value; used during encoding |
| 140 | initial [4]byte // use slack in size class as initial space for code |
| 141 | } |
| 142 | |
| 143 | // Uses returns the sequence of Cursors of [*ast.Ident]s in this package |
| 144 | // that refer to obj. If obj is nil, the sequence is empty. |
| 145 | // |
| 146 | // Uses, unlike the Uses field of [types.Info], records additional |
| 147 | // entries mapping fields and methods of generic types to references |
| 148 | // through their corresponding instantiated objects. |
| 149 | func (ix *Index) Uses(obj types.Object) iter.Seq[inspector.Cursor] { |
| 150 | return func(yield func(inspector.Cursor) bool) { |
| 151 | if uses := ix.uses[obj]; uses != nil { |
| 152 | var last int32 |
| 153 | for code := uses.code; len(code) > 0; { |
| 154 | delta, n := binary.Uvarint(code) |
| 155 | last += int32(delta) |
| 156 | if !yield(ix.inspect.At(last)) { |
| 157 | return |
| 158 | } |
| 159 | code = code[n:] |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | // Used reports whether any of the specified objects are used, in |
| 166 | // other words, obj != nil && Uses(obj) is non-empty for some obj in objs. |
| 167 | // |
| 168 | // (This treatment of nil allows Used to be called directly on the |
| 169 | // result of [Index.Object] so that analyzers can conveniently skip |
| 170 | // packages that don't use a symbol of interest.) |
| 171 | func (ix *Index) Used(objs ...types.Object) bool { |
| 172 | for _, obj := range objs { |
| 173 | if obj != nil && ix.uses[obj] != nil { |
| 174 | return true |
| 175 | } |
| 176 | } |
| 177 | return false |
| 178 | } |
| 179 | |
| 180 | // Def returns the Cursor of the [*ast.Ident] in this package |
| 181 | // that declares the specified object, if any. |
| 182 | func (ix *Index) Def(obj types.Object) (inspector.Cursor, bool) { |
| 183 | cur, ok := ix.def[obj] |
| 184 | return cur, ok |
| 185 | } |
| 186 | |
| 187 | // Package returns the package of the specified path, |
| 188 | // or nil if it is not referenced from this package. |
| 189 | func (ix *Index) Package(path string) *types.Package { |
| 190 | return ix.packages[path] |
| 191 | } |
| 192 | |
| 193 | // Object returns the package-level symbol name within the package of |
| 194 | // the specified path, or nil if the package or symbol does not exist |
| 195 | // or is not visible from this package. |
| 196 | func (ix *Index) Object(path, name string) types.Object { |
| 197 | if pkg := ix.Package(path); pkg != nil { |
| 198 | return pkg.Scope().Lookup(name) |
| 199 | } |
| 200 | return nil |
| 201 | } |
| 202 | |
| 203 | // Selection returns the named method or field belonging to the |
| 204 | // package-level type returned by Object(path, typename). |
| 205 | func (ix *Index) Selection(path, typename, name string) types.Object { |
| 206 | if obj := ix.Object(path, typename); obj != nil { |
| 207 | if tname, ok := obj.(*types.TypeName); ok { |
| 208 | obj, _, _ := types.LookupFieldOrMethod(tname.Type(), true, obj.Pkg(), name) |
| 209 | return obj |
| 210 | } |
| 211 | } |
| 212 | return nil |
| 213 | } |
| 214 | |
| 215 | // Calls returns the sequence of cursors for *ast.CallExpr nodes that |
| 216 | // call the specified callee, as defined by [typeutil.Callee]. |
| 217 | // If callee is nil, the sequence is empty. |
| 218 | func (ix *Index) Calls(callee types.Object) iter.Seq[inspector.Cursor] { |
| 219 | return func(yield func(inspector.Cursor) bool) { |
| 220 | for cur := range ix.Uses(callee) { |
| 221 | // The call may be of the form f() or x.f(), |
| 222 | // optionally with parens; ascend from f to call. |
| 223 | // See logic in [typesinternal.UsedIdent], to which this is dual. |
| 224 | // |
| 225 | // It is tempting but wrong to use the first |
| 226 | // CallExpr ancestor: we have to make sure the |
| 227 | // ident is in the CallExpr.Fun position, otherwise |
| 228 | // f(f, f) would have two spurious matches. |
| 229 | // Avoiding Enclosing is also significantly faster. |
| 230 | |
| 231 | // inverse unparen: f -> (f) |
| 232 | cur = astutil.UnparenEnclosingCursor(cur) |
| 233 | |
| 234 | // ascend selector (or qualified identifier): f -> x.f |
| 235 | if cur.ParentEdgeKind() == edge.SelectorExpr_Sel { |
| 236 | cur = astutil.UnparenEnclosingCursor(cur.Parent()) |
| 237 | } |
| 238 | |
| 239 | // ascend typeparams: f -> f[T]; f -> f[T1, T2] |
| 240 | if ek := cur.ParentEdgeKind(); ek == edge.IndexExpr_X || ek == edge.IndexListExpr_X { |
| 241 | cur = astutil.UnparenEnclosingCursor(cur.Parent()) |
| 242 | } |
| 243 | |
| 244 | // ascend from f or x.f to call |
| 245 | if cur.ParentEdgeKind() == edge.CallExpr_Fun { |
| 246 | curCall := cur.Parent() |
| 247 | call := curCall.Node().(*ast.CallExpr) |
| 248 | if typeutil.Callee(ix.info, call) == callee { |
| 249 | if !yield(curCall) { |
| 250 | return |
| 251 | } |
| 252 | } |
| 253 | } |
| 254 | } |
| 255 | } |
| 256 | } |