Debian Codegraph @

gopls/internal/cache/xrefs/xrefs.go

raw symbols SCIP
1 // Copyright 2022 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 xrefs defines the serializable index of cross-package
6 // references that is computed during type checking.
7 //
8 // See ../references.go for the 'references' query.
9 package xrefs
10
11 import (
12 "go/ast"
13 "go/types"
14 "sort"
15
16 "golang.org/x/tools/go/types/objectpath"
17 "golang.org/x/tools/gopls/internal/cache/metadata"
18 "golang.org/x/tools/gopls/internal/cache/parsego"
19 "golang.org/x/tools/gopls/internal/protocol"
20 "golang.org/x/tools/gopls/internal/util/bug"
21 "golang.org/x/tools/gopls/internal/util/frob"
22 )
23
24 // NewIndex constructs an index of outbound cross-references for the
25 // specified type-checked package.
26 func NewIndex(files []*parsego.File, pkg *types.Package, info *types.Info) *Index {
27 // pkgObjects maps each referenced package Q to a mapping:
28 // from each referenced symbol in Q to the ordered list
29 // of references to that symbol from this package.
30 // A nil types.Object indicates a reference
31 // to the package as a whole: an import.
32 pkgObjects := make(map[*types.Package]map[types.Object]*gobObject)
33
34 // getObjects returns the object-to-references mapping for a package.
35 getObjects := func(pkg *types.Package) map[types.Object]*gobObject {
36 objects, ok := pkgObjects[pkg]
37 if !ok {
38 objects = make(map[types.Object]*gobObject)
39 pkgObjects[pkg] = objects
40 }
41 return objects
42 }
43
44 objectpathFor := new(objectpath.Encoder).For
45
46 for fileIndex, pgf := range files {
47 for cur := range pgf.Cursor().Preorder((*ast.Ident)(nil), (*ast.ImportSpec)(nil)) {
48 switch n := cur.Node().(type) {
49 case *ast.Ident:
50 // Report a reference for each identifier that
51 // uses a symbol exported from another package.
52 // (The built-in error.Error method has no package.)
53 if n.IsExported() {
54 if obj, ok := info.Uses[n]; ok &&
55 obj.Pkg() != nil &&
56 obj.Pkg() != pkg {
57
58 // For instantiations of generic methods,
59 // use the generic object (see issue #60622).
60 if fn, ok := obj.(*types.Func); ok {
61 obj = fn.Origin()
62 }
63
64 objects := getObjects(obj.Pkg())
65 gobObj, ok := objects[obj]
66 if !ok {
67 path, err := objectpathFor(obj)
68 if err != nil {
69 // Capitalized but not exported
70 // (e.g. local const/var/type).
71 continue
72 }
73 gobObj = &gobObject{Path: path}
74 objects[obj] = gobObj
75 }
76
77 // golang/go#66683: nodes can under/overflow the file.
78 // For example, "var _ = x." creates a SelectorExpr(Sel=Ident("_"))
79 // that is beyond EOF. (Arguably Ident.Name should be "".)
80 if rng, err := pgf.NodeRange(n); err == nil {
81 gobObj.Refs = append(gobObj.Refs, gobRef{
82 FileIndex: fileIndex,
83 Range: rng,
84 })
85 }
86 }
87 }
88
89 case *ast.ImportSpec:
90 // Report a reference from each import path
91 // string to the imported package.
92 pkgname := info.PkgNameOf(n)
93 if pkgname == nil {
94 continue // missing import
95 }
96 objects := getObjects(pkgname.Imported())
97 gobObj, ok := objects[nil]
98 if !ok {
99 gobObj = &gobObject{Path: ""}
100 objects[nil] = gobObj
101 }
102 // golang/go#66683: nodes can under/overflow the file.
103 if rng, err := pgf.NodeRange(n.Path); err == nil {
104 gobObj.Refs = append(gobObj.Refs, gobRef{
105 FileIndex: fileIndex,
106 Range: rng,
107 })
108 } else {
109 bug.Reportf("out of bounds import spec %+v", n.Path)
110 }
111 }
112 }
113 }
114
115 // Flatten the maps into slices, and sort for determinism.
116 var packages []*gobPackage
117 for p := range pkgObjects {
118 objects := pkgObjects[p]
119 gp := &gobPackage{
120 PkgPath: metadata.PackagePath(p.Path()),
121 Objects: make([]*gobObject, 0, len(objects)),
122 }
123 for _, gobObj := range objects {
124 gp.Objects = append(gp.Objects, gobObj)
125 }
126 sort.Slice(gp.Objects, func(i, j int) bool {
127 return gp.Objects[i].Path < gp.Objects[j].Path
128 })
129 packages = append(packages, gp)
130 }
131 sort.Slice(packages, func(i, j int) bool {
132 return packages[i].PkgPath < packages[j].PkgPath
133 })
134
135 return &Index{packages: packages}
136 }
137
138 // An Index is an index of outbound symbol references for one
139 // specific package.
140 type Index struct {
141 packages []*gobPackage
142 }
143
144 // Encode encodes the index for storage.
145 func (idx *Index) Encode() []byte {
146 return packageCodec.Encode(idx.packages)
147 }
148
149 // Decode decodes a serialized cross-reference index.
150 // It is suitable for use as a filecache.Get decoder.
151 func Decode(data []byte) *Index {
152 return &Index{packages: packageCodec.Decode(data)}
153 }
154
155 // Lookup searches the index for references to any object in the target set,
156 // returning their locations within the package described by mp.
157 // Each target object is denoted by a pair of (package path, object path).
158 func (idx *Index) Lookup(mp *metadata.Package, targets map[metadata.PackagePath]map[objectpath.Path]struct{}) (locs []protocol.Location) {
159 for _, gp := range idx.packages {
160 if objectSet, ok := targets[gp.PkgPath]; ok {
161 for _, gobObj := range gp.Objects {
162 if _, ok := objectSet[gobObj.Path]; ok {
163 for _, ref := range gobObj.Refs {
164 uri := mp.CompiledGoFiles[ref.FileIndex]
165 locs = append(locs, protocol.Location{
166 URI: uri,
167 Range: ref.Range,
168 })
169 }
170 }
171 }
172 }
173 }
174
175 return locs
176 }
177
178 // -- serialized representation --
179
180 // The cross-reference index records the location of all references
181 // from one package to symbols defined in other packages
182 // (dependencies). It does not record within-package references.
183 // The index for package P consists of a list of gopPackage records,
184 // each enumerating references to symbols defined a single dependency, Q.
185
186 // TODO(adonovan): opt: choose a more compact encoding.
187 // The gobRef.Range field is the obvious place to begin.
188
189 // (The name says gob but in fact we use frob.)
190 var packageCodec = frob.CodecFor[[]*gobPackage]()
191
192 // A gobPackage records the set of outgoing references from the index
193 // package to symbols defined in a dependency package.
194 type gobPackage struct {
195 PkgPath metadata.PackagePath // defining package (Q)
196 Objects []*gobObject // set of Q objects referenced by P
197 }
198
199 // A gobObject records all references to a particular symbol.
200 type gobObject struct {
201 Path objectpath.Path // symbol name within package; "" => import of package itself
202 Refs []gobRef // locations of references within P, in lexical order
203 }
204
205 type gobRef struct {
206 FileIndex int // index of enclosing file within P's CompiledGoFiles
207 Range protocol.Range // source range of reference
208 }