Debian Codegraph @

gopls/internal/cache/typerefs/refs.go

raw symbols SCIP
1 // Copyright 2023 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 typerefs
6
7 import (
8 "fmt"
9 "go/ast"
10 "go/token"
11 "sort"
12 "strings"
13
14 "golang.org/x/tools/gopls/internal/cache/metadata"
15 "golang.org/x/tools/gopls/internal/cache/parsego"
16 "golang.org/x/tools/gopls/internal/util/frob"
17 "golang.org/x/tools/internal/astutil"
18 )
19
20 // Encode analyzes the Go syntax trees of a package, constructs a
21 // reference graph, and uses it to compute, for each exported
22 // declaration, the set of exported symbols of directly imported
23 // packages that it references, perhaps indirectly.
24 //
25 // It returns a serializable index of this information.
26 // Use Decode to expand the result.
27 func Encode(files []*parsego.File, imports map[metadata.ImportPath]*metadata.Package) []byte {
28 return index(files, imports)
29 }
30
31 // Decode decodes a serializable index of symbol
32 // reachability produced by Encode.
33 //
34 // Because many declarations reference the exact same set of symbols,
35 // the results are grouped into equivalence classes.
36 // Classes are sorted by Decls[0], ascending.
37 // The class with empty reachability is omitted.
38 //
39 // See the package documentation for more details as to what a
40 // reference does (and does not) represent.
41 func Decode(pkgIndex *PackageIndex, data []byte) []Class {
42 return decode(pkgIndex, data)
43 }
44
45 // A Class is a reachability equivalence class.
46 //
47 // It attests that each exported package-level declaration in Decls
48 // references (perhaps indirectly) one of the external (imported)
49 // symbols in Refs.
50 //
51 // Because many Decls reach the same Refs,
52 // it is more efficient to group them into classes.
53 type Class struct {
54 Decls []string // sorted set of names of exported decls with same reachability
55 Refs []Symbol // set of external symbols, in ascending (PackageID, Name) order
56 }
57
58 // A Symbol represents an external (imported) symbol
59 // referenced by the analyzed package.
60 type Symbol struct {
61 Package IndexID // w.r.t. PackageIndex passed to decoder
62 Name string
63 }
64
65 // An IndexID is a small integer that uniquely identifies a package within a
66 // given PackageIndex.
67 type IndexID int
68
69 // -- internals --
70
71 // A symbolSet is a set of symbols used internally during index construction.
72 //
73 // TODO(adonovan): opt: evaluate unifying Symbol and symbol.
74 // (Encode would have to create a private PackageIndex.)
75 type symbolSet map[symbol]bool
76
77 // A symbol is the internal representation of an external
78 // (imported) symbol referenced by the analyzed package.
79 type symbol struct {
80 pkg metadata.PackageID
81 name string
82 }
83
84 // declNode holds information about a package-level declaration
85 // (or more than one with the same name, in ill-typed code).
86 //
87 // It is a node in the symbol reference graph, whose outgoing edges
88 // are of two kinds: intRefs and extRefs.
89 type declNode struct {
90 name string
91 rep *declNode // canonical representative of this SCC (initially self)
92
93 // outgoing graph edges
94 intRefs map[*declNode]bool // to symbols in this package
95 extRefs symbolSet // to imported symbols
96 extRefsClass int // extRefs equivalence class number (-1 until set at end)
97
98 // Tarjan's SCC algorithm
99 index, lowlink int32 // Tarjan numbering
100 scc int32 // -ve => on stack; 0 => unvisited; +ve => node is root of a found SCC
101 }
102
103 // state holds the working state of the Refs algorithm for a single package.
104 //
105 // The number of distinct symbols referenced by a single package
106 // (measured across all of kubernetes), was found to be:
107 // - max = 1750.
108 // - Several packages reference > 100 symbols.
109 // - p95 = 32, p90 = 22, p50 = 8.
110 type state struct {
111 // numbering of unique symbol sets
112 class []symbolSet // unique symbol sets
113 classIndex map[string]int // index of above (using SymbolSet.hash as key)
114
115 // Tarjan's SCC algorithm
116 index int32
117 stack []*declNode
118 }
119
120 // getClassIndex returns the small integer (an index into
121 // state.class) that identifies the given set.
122 func (st *state) getClassIndex(set symbolSet) int {
123 key := classKey(set)
124 i, ok := st.classIndex[key]
125 if !ok {
126 i = len(st.class)
127 st.classIndex[key] = i
128 st.class = append(st.class, set)
129 }
130 return i
131 }
132
133 // appendSorted appends the symbols to syms, sorts by ascending
134 // (PackageID, name), and returns the result.
135 // The argument must be an empty slice, ideally with capacity len(set).
136 func (set symbolSet) appendSorted(syms []symbol) []symbol {
137 for sym := range set {
138 syms = append(syms, sym)
139 }
140 sort.Slice(syms, func(i, j int) bool {
141 x, y := syms[i], syms[j]
142 if x.pkg != y.pkg {
143 return x.pkg < y.pkg
144 }
145 return x.name < y.name
146 })
147 return syms
148 }
149
150 // classKey returns a key such that equal keys imply equal sets.
151 // (e.g. a sorted string representation, or a cryptographic hash of same).
152 func classKey(set symbolSet) string {
153 // Sort symbols into a stable order.
154 // TODO(adonovan): opt: a cheap crypto hash (e.g. BLAKE2b) might
155 // make a cheaper map key than a large string.
156 // Try using a hasher instead of a builder.
157 var s strings.Builder
158 for _, sym := range set.appendSorted(make([]symbol, 0, len(set))) {
159 fmt.Fprintf(&s, "%s:%s;", sym.pkg, sym.name)
160 }
161 return s.String()
162 }
163
164 // index builds the reference graph and encodes the index.
165 func index(pgfs []*parsego.File, imports map[metadata.ImportPath]*metadata.Package) []byte {
166 // First pass: gather package-level names and create a declNode for each.
167 //
168 // In ill-typed code, there may be multiple declarations of the
169 // same name; a single declInfo node will represent them all.
170 decls := make(map[string]*declNode)
171 addDecl := func(id *ast.Ident) {
172 if name := id.Name; name != "_" && decls[name] == nil {
173 node := &declNode{name: name, extRefsClass: -1}
174 node.rep = node
175 decls[name] = node
176 }
177 }
178 for _, pgf := range pgfs {
179 for _, d := range pgf.File.Decls {
180 switch d := d.(type) {
181 case *ast.GenDecl:
182 switch d.Tok {
183 case token.TYPE:
184 for _, spec := range d.Specs {
185 addDecl(spec.(*ast.TypeSpec).Name)
186 }
187
188 case token.VAR, token.CONST:
189 for _, spec := range d.Specs {
190 for _, ident := range spec.(*ast.ValueSpec).Names {
191 addDecl(ident)
192 }
193 }
194 }
195
196 case *ast.FuncDecl:
197 // non-method functions
198 if d.Recv.NumFields() == 0 {
199 addDecl(d.Name)
200 }
201 }
202 }
203 }
204
205 // Second pass: process files to collect referring identifiers.
206 st := &state{classIndex: make(map[string]int)}
207 for _, pgf := range pgfs {
208 visitFile(pgf.File, imports, decls)
209 }
210
211 // Find the strong components of the declNode graph
212 // using Tarjan's algorithm, and coalesce each component.
213 st.index = 1
214 for _, decl := range decls {
215 if decl.index == 0 { // unvisited
216 st.visit(decl)
217 }
218 }
219
220 // TODO(adonovan): opt: consider compressing the serialized
221 // representation by recording not the classes but the DAG of
222 // non-trivial union operations (the "pointer equivalence"
223 // optimization of Hardekopf & Lin). Unlike that algorithm,
224 // which piggybacks on SCC coalescing, in our case it would
225 // be better to make a forward traversal from the exported
226 // decls, since it avoids visiting unreachable nodes, and
227 // results in a dense (not sparse) numbering of the sets.
228
229 // Tabulate the unique reachability sets of
230 // each exported package member.
231 classNames := make(map[int][]string) // set of decls (names) for a given reachability set
232 for name, decl := range decls {
233 if !ast.IsExported(name) {
234 continue
235 }
236
237 decl = decl.find()
238
239 // Skip decls with empty reachability.
240 if len(decl.extRefs) == 0 {
241 continue
242 }
243
244 // Canonicalize the set (and memoize).
245 class := decl.extRefsClass
246 if class < 0 {
247 class = st.getClassIndex(decl.extRefs)
248 decl.extRefsClass = class
249 }
250 classNames[class] = append(classNames[class], name)
251 }
252
253 return encode(classNames, st.class)
254 }
255
256 // visitFile inspects the file syntax for referring identifiers, and
257 // populates the internal and external references of decls.
258 func visitFile(file *ast.File, imports map[metadata.ImportPath]*metadata.Package, decls map[string]*declNode) {
259 // Import information for this file. Multiple packages
260 // may be referenced by a given name in the presence
261 // of type errors (or multiple dot imports, which are
262 // keyed by ".").
263 fileImports := make(map[string][]metadata.PackageID)
264
265 // importEdge records a reference from decl to an imported symbol
266 // (pkgname.name). The package name may be ".".
267 importEdge := func(decl *declNode, pkgname, name string) {
268 if token.IsExported(name) {
269 for _, depID := range fileImports[pkgname] {
270 if decl.extRefs == nil {
271 decl.extRefs = make(symbolSet)
272 }
273 decl.extRefs[symbol{depID, name}] = true
274 }
275 }
276 }
277
278 // visit finds refs within node and builds edges from fromId's decl.
279 // References to the type parameters are ignored.
280 visit := func(fromId *ast.Ident, node ast.Node, tparams map[string]bool) {
281 if fromId.Name == "_" {
282 return
283 }
284 from := decls[fromId.Name]
285 // When visiting a method, there may not be a valid type declaration for
286 // the receiver. In this case there is no way to refer to the method, so
287 // we need not record edges.
288 if from == nil {
289 return
290 }
291
292 // Visit each reference to name or name.sel.
293 visitDeclOrSpec(node, func(name, sel string) {
294 // Ignore references to type parameters.
295 if tparams[name] {
296 return
297 }
298
299 // If name is declared in the package scope,
300 // record an edge whether or not sel is empty.
301 // A field or method selector may affect the
302 // type of the current decl via initializers:
303 //
304 // package p
305 // var x = y.F
306 // var y = struct{ F int }{}
307 if to, ok := decls[name]; ok {
308 if from.intRefs == nil {
309 from.intRefs = make(map[*declNode]bool)
310 }
311 from.intRefs[to] = true
312
313 } else {
314 // Only record an edge to dot-imported packages
315 // if there was no edge to a local name.
316 // This assumes that there are no duplicate declarations.
317 // We conservatively, assume that this name comes from
318 // every dot-imported package.
319 importEdge(from, ".", name)
320 }
321
322 // Record an edge to an import if it matches the name, even if that
323 // name collides with a package level name. Unlike the case of dotted
324 // imports, we know the package is invalid here, and choose to fail
325 // conservatively.
326 if sel != "" {
327 importEdge(from, name, sel)
328 }
329 })
330 }
331
332 // Visit the declarations and gather reference edges.
333 // Import declarations appear before all others.
334 for _, d := range file.Decls {
335 switch d := d.(type) {
336 case *ast.GenDecl:
337 switch d.Tok {
338 case token.IMPORT:
339 // Record local import names for this file.
340 for _, spec := range d.Specs {
341 spec := spec.(*ast.ImportSpec)
342 path := metadata.UnquoteImportPath(spec)
343 if path == "" {
344 continue
345 }
346 dep := imports[path]
347 if dep == nil {
348 // Note here that we don't try to "guess"
349 // the name of an import based on e.g.
350 // its importPath. Doing so would only
351 // result in edges that don't go anywhere.
352 continue
353 }
354 name := string(dep.Name)
355 if spec.Name != nil {
356 if spec.Name.Name == "_" {
357 continue
358 }
359 name = spec.Name.Name // possibly "."
360 }
361 fileImports[name] = append(fileImports[name], dep.ID)
362 }
363
364 case token.TYPE:
365 for _, spec := range d.Specs {
366 spec := spec.(*ast.TypeSpec)
367 tparams := tparamsMap(spec.TypeParams)
368 visit(spec.Name, spec, tparams)
369 }
370
371 case token.VAR, token.CONST:
372 for _, spec := range d.Specs {
373 spec := spec.(*ast.ValueSpec)
374 for _, name := range spec.Names {
375 visit(name, spec, nil)
376 }
377 }
378 }
379
380 case *ast.FuncDecl:
381 // This check for NumFields() > 0 is consistent with go/types,
382 // which reports an error but treats the declaration like a
383 // normal function when Recv is non-nil but empty
384 // (as in func () f()).
385 if d.Recv.NumFields() > 0 {
386 // Method. Associate it with the receiver.
387 _, id, typeParams := astutil.UnpackRecv(d.Recv.List[0].Type)
388 if id != nil {
389 var tparams map[string]bool
390 if len(typeParams) > 0 {
391 tparams = make(map[string]bool)
392 for _, tparam := range typeParams {
393 if tparam.Name != "_" {
394 tparams[tparam.Name] = true
395 }
396 }
397 }
398 visit(id, d, tparams)
399 }
400 } else {
401 // Non-method.
402 tparams := tparamsMap(d.Type.TypeParams)
403 visit(d.Name, d, tparams)
404 }
405 }
406 }
407 }
408
409 // tparamsMap returns a set recording each name declared by the provided field
410 // list. It so happens that we only care about names declared by type parameter
411 // lists.
412 func tparamsMap(tparams *ast.FieldList) map[string]bool {
413 if tparams == nil || len(tparams.List) == 0 {
414 return nil
415 }
416 m := make(map[string]bool)
417 for _, f := range tparams.List {
418 for _, name := range f.Names {
419 if name.Name != "_" {
420 m[name.Name] = true
421 }
422 }
423 }
424 return m
425 }
426
427 // A refVisitor visits referring identifiers and dotted identifiers.
428 //
429 // For a referring identifier I, name="I" and sel="". For a dotted identifier
430 // q.I, name="q" and sel="I".
431 type refVisitor = func(name, sel string)
432
433 // visitDeclOrSpec visits referring idents or dotted idents that may affect
434 // the type of the declaration at the given node, which must be an ast.Decl or
435 // ast.Spec.
436 func visitDeclOrSpec(node ast.Node, f refVisitor) {
437 // Declarations
438 switch n := node.(type) {
439 // ImportSpecs should not appear here, and will panic in the default case.
440
441 case *ast.ValueSpec:
442 // Skip Doc, Names, Comments, which do not affect the decl type.
443 // Initializers only affect the type of a value spec if the type is unset.
444 if n.Type != nil {
445 visitExpr(n.Type, f)
446 } else { // only need to walk expr list if type is nil
447 visitExprList(n.Values, f)
448 }
449
450 case *ast.TypeSpec:
451 // Skip Doc, Name, and Comment, which do not affect the decl type.
452 if tparams := n.TypeParams; tparams != nil {
453 visitFieldList(tparams, f)
454 }
455 visitExpr(n.Type, f)
456
457 case *ast.BadDecl:
458 // nothing to do
459
460 // We should not reach here with a GenDecl, so panic below in the default case.
461
462 case *ast.FuncDecl:
463 // Skip Doc, Name, and Body, which do not affect the type.
464 // Recv is handled by Refs: methods are associated with their type.
465 visitExpr(n.Type, f)
466
467 default:
468 panic(fmt.Sprintf("unexpected node type %T", node))
469 }
470 }
471
472 // visitExpr visits referring idents and dotted idents that may affect the
473 // type of expr.
474 //
475 // visitExpr can't reliably distinguish a dotted ident pkg.X from a
476 // selection expr.f or T.method.
477 func visitExpr(expr ast.Expr, f refVisitor) {
478 switch n := expr.(type) {
479 // These four cases account for about two thirds of all nodes,
480 // so we place them first to shorten the common control paths.
481 // (See go.dev/cl/480915.)
482 case *ast.Ident:
483 f(n.Name, "")
484
485 case *ast.BasicLit:
486 // nothing to do
487
488 case *ast.SelectorExpr:
489 if ident, ok := n.X.(*ast.Ident); ok {
490 f(ident.Name, n.Sel.Name)
491 } else {
492 visitExpr(n.X, f)
493 // Skip n.Sel as we don't care about which field or method is selected,
494 // as we'll have recorded an edge to all declarations relevant to the
495 // receiver type via visiting n.X above.
496 }
497
498 case *ast.CallExpr:
499 visitExpr(n.Fun, f)
500 visitExprList(n.Args, f) // args affect types for unsafe.Sizeof or builtins or generics
501
502 // Expressions
503 case *ast.Ellipsis:
504 if n.Elt != nil {
505 visitExpr(n.Elt, f)
506 }
507
508 case *ast.FuncLit:
509 visitExpr(n.Type, f)
510 // Skip Body, which does not affect the type.
511
512 case *ast.CompositeLit:
513 if n.Type != nil {
514 visitExpr(n.Type, f)
515 }
516 // Skip Elts, which do not affect the type.
517
518 case *ast.ParenExpr:
519 visitExpr(n.X, f)
520
521 case *ast.IndexExpr:
522 visitExpr(n.X, f)
523 visitExpr(n.Index, f) // may affect type for instantiations
524
525 case *ast.IndexListExpr:
526 visitExpr(n.X, f)
527 for _, index := range n.Indices {
528 visitExpr(index, f) // may affect the type for instantiations
529 }
530
531 case *ast.SliceExpr:
532 visitExpr(n.X, f)
533 // skip Low, High, and Max, which do not affect type.
534
535 case *ast.TypeAssertExpr:
536 // Skip X, as it doesn't actually affect the resulting type of the type
537 // assertion.
538 if n.Type != nil {
539 visitExpr(n.Type, f)
540 }
541
542 case *ast.StarExpr:
543 visitExpr(n.X, f)
544
545 case *ast.UnaryExpr:
546 visitExpr(n.X, f)
547
548 case *ast.BinaryExpr:
549 visitExpr(n.X, f)
550 visitExpr(n.Y, f)
551
552 case *ast.KeyValueExpr:
553 panic("unreachable") // unreachable, as we don't descend into elts of composite lits.
554
555 case *ast.ArrayType:
556 if n.Len != nil {
557 visitExpr(n.Len, f)
558 }
559 visitExpr(n.Elt, f)
560
561 case *ast.StructType:
562 visitFieldList(n.Fields, f)
563
564 case *ast.FuncType:
565 if tparams := n.TypeParams; tparams != nil {
566 visitFieldList(tparams, f)
567 }
568 if n.Params != nil {
569 visitFieldList(n.Params, f)
570 }
571 if n.Results != nil {
572 visitFieldList(n.Results, f)
573 }
574
575 case *ast.InterfaceType:
576 visitFieldList(n.Methods, f)
577
578 case *ast.MapType:
579 visitExpr(n.Key, f)
580 visitExpr(n.Value, f)
581
582 case *ast.ChanType:
583 visitExpr(n.Value, f)
584
585 case *ast.BadExpr:
586 // nothing to do
587
588 default:
589 panic(fmt.Sprintf("ast.Walk: unexpected node type %T", n))
590 }
591 }
592
593 func visitExprList(list []ast.Expr, f refVisitor) {
594 for _, x := range list {
595 visitExpr(x, f)
596 }
597 }
598
599 func visitFieldList(n *ast.FieldList, f refVisitor) {
600 for _, field := range n.List {
601 visitExpr(field.Type, f)
602 }
603 }
604
605 // -- strong component graph construction (plundered from go/pointer) --
606
607 // visit implements the depth-first search of Tarjan's SCC algorithm
608 // (see https://doi.org/10.1137/0201010).
609 // Precondition: x is canonical.
610 func (st *state) visit(x *declNode) {
611 checkCanonical(x)
612 x.index = st.index
613 x.lowlink = st.index
614 st.index++
615
616 st.stack = append(st.stack, x) // push
617 assert(x.scc == 0, "node revisited")
618 x.scc = -1
619
620 for y := range x.intRefs {
621 // Loop invariant: x is canonical.
622
623 y := y.find()
624
625 if x == y {
626 continue // nodes already coalesced
627 }
628
629 switch {
630 case y.scc > 0:
631 // y is already a collapsed SCC
632
633 case y.scc < 0:
634 // y is on the stack, and thus in the current SCC.
635 if y.index < x.lowlink {
636 x.lowlink = y.index
637 }
638
639 default:
640 // y is unvisited; visit it now.
641 st.visit(y)
642 // Note: x and y are now non-canonical.
643
644 x = x.find()
645
646 if y.lowlink < x.lowlink {
647 x.lowlink = y.lowlink
648 }
649 }
650 }
651 checkCanonical(x)
652
653 // Is x the root of an SCC?
654 if x.lowlink == x.index {
655 // Coalesce all nodes in the SCC.
656 for {
657 // Pop y from stack.
658 i := len(st.stack) - 1
659 y := st.stack[i]
660 st.stack = st.stack[:i]
661
662 checkCanonical(x)
663 checkCanonical(y)
664
665 if x == y {
666 break // SCC is complete.
667 }
668 coalesce(x, y)
669 }
670
671 // Accumulate union of extRefs over
672 // internal edges (to other SCCs).
673 for y := range x.intRefs {
674 y := y.find()
675 if y == x {
676 continue // already coalesced
677 }
678 assert(y.scc == 1, "edge to non-scc node")
679 for z := range y.extRefs {
680 if x.extRefs == nil {
681 x.extRefs = make(symbolSet)
682 }
683 x.extRefs[z] = true // extRefs: x U= y
684 }
685 }
686
687 x.scc = 1
688 }
689 }
690
691 // coalesce combines two nodes in the strong component graph.
692 // Precondition: x and y are canonical.
693 func coalesce(x, y *declNode) {
694 // x becomes y's canonical representative.
695 y.rep = x
696
697 // x accumulates y's internal references.
698 for z := range y.intRefs {
699 x.intRefs[z] = true
700 }
701 y.intRefs = nil
702
703 // x accumulates y's external references.
704 for z := range y.extRefs {
705 if x.extRefs == nil {
706 x.extRefs = make(symbolSet)
707 }
708 x.extRefs[z] = true
709 }
710 y.extRefs = nil
711 }
712
713 // find returns the canonical node decl.
714 // (The nodes form a disjoint set forest.)
715 func (decl *declNode) find() *declNode {
716 rep := decl.rep
717 if rep != decl {
718 rep = rep.find()
719 decl.rep = rep // simple path compression (no union-by-rank)
720 }
721 return rep
722 }
723
724 const debugSCC = false // enable assertions in strong-component algorithm
725
726 func checkCanonical(x *declNode) {
727 if debugSCC {
728 assert(x == x.find(), "not canonical")
729 }
730 }
731
732 func assert(cond bool, msg string) {
733 if debugSCC && !cond {
734 panic(msg)
735 }
736 }
737
738 // -- serialization --
739
740 // (The name says gob but in fact we use frob.)
741 var classesCodec = frob.CodecFor[gobClasses]()
742
743 type gobClasses struct {
744 Strings []string // table of strings (PackageIDs and names)
745 Classes []gobClass
746 }
747
748 type gobClass struct {
749 Decls []int32 // indices into gobClasses.Strings
750 Refs []int32 // list of (package, name) pairs, each an index into gobClasses.Strings
751 }
752
753 // encode encodes the equivalence classes,
754 // (classNames[i], classes[i]), for i in range classes.
755 //
756 // With the current encoding, across kubernetes,
757 // the encoded size distribution has
758 // p50 = 511B, p95 = 4.4KB, max = 108K.
759 func encode(classNames map[int][]string, classes []symbolSet) []byte {
760 payload := gobClasses{
761 Classes: make([]gobClass, 0, len(classNames)),
762 }
763
764 // index of unique strings
765 strings := make(map[string]int32)
766 stringIndex := func(s string) int32 {
767 i, ok := strings[s]
768 if !ok {
769 i = int32(len(payload.Strings))
770 strings[s] = i
771 payload.Strings = append(payload.Strings, s)
772 }
773 return i
774 }
775
776 var refs []symbol // recycled temporary
777 for class, names := range classNames {
778 set := classes[class]
779
780 // names, sorted
781 sort.Strings(names)
782 gobDecls := make([]int32, len(names))
783 for i, name := range names {
784 gobDecls[i] = stringIndex(name)
785 }
786
787 // refs, sorted by ascending (PackageID, name)
788 gobRefs := make([]int32, 0, 2*len(set))
789 for _, sym := range set.appendSorted(refs[:0]) {
790 gobRefs = append(gobRefs,
791 stringIndex(string(sym.pkg)),
792 stringIndex(sym.name))
793 }
794 payload.Classes = append(payload.Classes, gobClass{
795 Decls: gobDecls,
796 Refs: gobRefs,
797 })
798 }
799
800 return classesCodec.Encode(payload)
801 }
802
803 func decode(pkgIndex *PackageIndex, data []byte) []Class {
804 payload := classesCodec.Decode(data)
805
806 classes := make([]Class, len(payload.Classes))
807 for i, gobClass := range payload.Classes {
808 decls := make([]string, len(gobClass.Decls))
809 for i, decl := range gobClass.Decls {
810 decls[i] = payload.Strings[decl]
811 }
812 refs := make([]Symbol, len(gobClass.Refs)/2)
813 for i := range refs {
814 pkgID := pkgIndex.IndexID(metadata.PackageID(payload.Strings[gobClass.Refs[2*i]]))
815 name := payload.Strings[gobClass.Refs[2*i+1]]
816 refs[i] = Symbol{Package: pkgID, Name: name}
817 }
818 classes[i] = Class{
819 Decls: decls,
820 Refs: refs,
821 }
822 }
823
824 // Sort by ascending Decls[0].
825 // TODO(adonovan): move sort to encoder. Determinism is good.
826 sort.Slice(classes, func(i, j int) bool {
827 return classes[i].Decls[0] < classes[j].Decls[0]
828 })
829
830 return classes
831 }