Debian Codegraph @

internal/gcimporter/iexport.go

raw symbols SCIP
1 // Copyright 2019 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 // Indexed package export.
6 //
7 // The indexed export data format is an evolution of the previous
8 // binary export data format. Its chief contribution is introducing an
9 // index table, which allows efficient random access of individual
10 // declarations and inline function bodies. In turn, this allows
11 // avoiding unnecessary work for compilation units that import large
12 // packages.
13 //
14 //
15 // The top-level data format is structured as:
16 //
17 // Header struct {
18 // Tag byte // 'i'
19 // Version uvarint
20 // StringSize uvarint
21 // DataSize uvarint
22 // }
23 //
24 // Strings [StringSize]byte
25 // Data [DataSize]byte
26 //
27 // MainIndex []struct{
28 // PkgPath stringOff
29 // PkgName stringOff
30 // PkgHeight uvarint
31 //
32 // Decls []struct{
33 // Name stringOff
34 // Offset declOff
35 // }
36 // }
37 //
38 // Fingerprint [8]byte
39 //
40 // uvarint means a uint64 written out using uvarint encoding.
41 //
42 // []T means a uvarint followed by that many T objects. In other
43 // words:
44 //
45 // Len uvarint
46 // Elems [Len]T
47 //
48 // stringOff means a uvarint that indicates an offset within the
49 // Strings section. At that offset is another uvarint, followed by
50 // that many bytes, which form the string value.
51 //
52 // declOff means a uvarint that indicates an offset within the Data
53 // section where the associated declaration can be found.
54 //
55 //
56 // There are five kinds of declarations, distinguished by their first
57 // byte:
58 //
59 // type Var struct {
60 // Tag byte // 'V'
61 // Pos Pos
62 // Type typeOff
63 // }
64 //
65 // type Func struct {
66 // Tag byte // 'F' or 'G'
67 // Pos Pos
68 // TypeParams []typeOff // only present if Tag == 'G'
69 // Signature Signature
70 // }
71 //
72 // type Const struct {
73 // Tag byte // 'C'
74 // Pos Pos
75 // Value Value
76 // }
77 //
78 // type Type struct {
79 // Tag byte // 'T' or 'U'
80 // Pos Pos
81 // TypeParams []typeOff // only present if Tag == 'U'
82 // Underlying typeOff
83 //
84 // Methods []struct{ // omitted if Underlying is an interface type
85 // Pos Pos
86 // Name stringOff
87 // Recv Param
88 // Signature Signature
89 // }
90 // }
91 //
92 // type Alias struct {
93 // Tag byte // 'A' or 'B'
94 // Pos Pos
95 // TypeParams []typeOff // only present if Tag == 'B'
96 // Type typeOff
97 // }
98 //
99 // // "Automatic" declaration of each typeparam
100 // type TypeParam struct {
101 // Tag byte // 'P'
102 // Pos Pos
103 // Implicit bool
104 // Constraint typeOff
105 // }
106 //
107 // typeOff means a uvarint that either indicates a predeclared type,
108 // or an offset into the Data section. If the uvarint is less than
109 // predeclReserved, then it indicates the index into the predeclared
110 // types list (see predeclared in bexport.go for order). Otherwise,
111 // subtracting predeclReserved yields the offset of a type descriptor.
112 //
113 // Value means a type, kind, and type-specific value. See
114 // (*exportWriter).value for details.
115 //
116 //
117 // There are twelve kinds of type descriptors, distinguished by an itag:
118 //
119 // type DefinedType struct {
120 // Tag itag // definedType
121 // Name stringOff
122 // PkgPath stringOff
123 // }
124 //
125 // type PointerType struct {
126 // Tag itag // pointerType
127 // Elem typeOff
128 // }
129 //
130 // type SliceType struct {
131 // Tag itag // sliceType
132 // Elem typeOff
133 // }
134 //
135 // type ArrayType struct {
136 // Tag itag // arrayType
137 // Len uint64
138 // Elem typeOff
139 // }
140 //
141 // type ChanType struct {
142 // Tag itag // chanType
143 // Dir uint64 // 1 RecvOnly; 2 SendOnly; 3 SendRecv
144 // Elem typeOff
145 // }
146 //
147 // type MapType struct {
148 // Tag itag // mapType
149 // Key typeOff
150 // Elem typeOff
151 // }
152 //
153 // type FuncType struct {
154 // Tag itag // signatureType
155 // PkgPath stringOff
156 // Signature Signature
157 // }
158 //
159 // type StructType struct {
160 // Tag itag // structType
161 // PkgPath stringOff
162 // Fields []struct {
163 // Pos Pos
164 // Name stringOff
165 // Type typeOff
166 // Embedded bool
167 // Note stringOff
168 // }
169 // }
170 //
171 // type InterfaceType struct {
172 // Tag itag // interfaceType
173 // PkgPath stringOff
174 // Embeddeds []struct {
175 // Pos Pos
176 // Type typeOff
177 // }
178 // Methods []struct {
179 // Pos Pos
180 // Name stringOff
181 // Signature Signature
182 // }
183 // }
184 //
185 // // Reference to a type param declaration
186 // type TypeParamType struct {
187 // Tag itag // typeParamType
188 // Name stringOff
189 // PkgPath stringOff
190 // }
191 //
192 // // Instantiation of a generic type (like List[T2] or List[int])
193 // type InstanceType struct {
194 // Tag itag // instanceType
195 // Pos pos
196 // TypeArgs []typeOff
197 // BaseType typeOff
198 // }
199 //
200 // type UnionType struct {
201 // Tag itag // interfaceType
202 // Terms []struct {
203 // tilde bool
204 // Type typeOff
205 // }
206 // }
207 //
208 //
209 //
210 // type Signature struct {
211 // Params []Param
212 // Results []Param
213 // Variadic bool // omitted if Results is empty
214 // }
215 //
216 // type Param struct {
217 // Pos Pos
218 // Name stringOff
219 // Type typOff
220 // }
221 //
222 //
223 // Pos encodes a file:line:column triple, incorporating a simple delta
224 // encoding scheme within a data object. See exportWriter.pos for
225 // details.
226
227 package gcimporter
228
229 import (
230 "bytes"
231 "encoding/binary"
232 "fmt"
233 "go/constant"
234 "go/token"
235 "go/types"
236 "io"
237 "math/big"
238 "reflect"
239 "slices"
240 "sort"
241 "strconv"
242 "strings"
243
244 "golang.org/x/tools/go/types/objectpath"
245 )
246
247 // IExportShallow encodes "shallow" export data for the specified package.
248 //
249 // For types, we use "shallow" export data. Historically, the Go
250 // compiler always produced a summary of the types for a given package
251 // that included types from other packages that it indirectly
252 // referenced: "deep" export data. This had the advantage that the
253 // compiler (and analogous tools such as gopls) need only load one
254 // file per direct import. However, it meant that the files tended to
255 // get larger based on the level of the package in the import
256 // graph. For example, higher-level packages in the kubernetes module
257 // have over 1MB of "deep" export data, even when they have almost no
258 // content of their own, merely because they mention a major type that
259 // references many others. In pathological cases the export data was
260 // 300x larger than the source for a package due to this quadratic
261 // growth.
262 //
263 // "Shallow" export data means that the serialized types describe only
264 // a single package. If those types mention types from other packages,
265 // the type checker may need to request additional packages beyond
266 // just the direct imports. Type information for the entire transitive
267 // closure of imports is provided (lazily) by the DAG.
268 //
269 // No promises are made about the encoding other than that it can be decoded by
270 // the same version of IIExportShallow. If you plan to save export data in the
271 // file system, be sure to include a cryptographic digest of the executable in
272 // the key to avoid version skew.
273 //
274 // If the provided reportf func is non-nil, it is used for reporting
275 // bugs (e.g. recovered panics) encountered during export, enabling us
276 // to obtain via telemetry the stack that would otherwise be lost by
277 // merely returning an error.
278 func IExportShallow(fset *token.FileSet, pkg *types.Package, reportf ReportFunc) ([]byte, error) {
279 // In principle this operation can only fail if out.Write fails,
280 // but that's impossible for bytes.Buffer---and as a matter of
281 // fact iexportCommon doesn't even check for I/O errors.
282 // TODO(adonovan): handle I/O errors properly.
283 // TODO(adonovan): use byte slices throughout, avoiding copying.
284 const bundle, shallow = false, true
285 var out bytes.Buffer
286 err := iexportCommon(&out, fset, bundle, shallow, iexportVersion, []*types.Package{pkg}, reportf)
287 return out.Bytes(), err
288 }
289
290 // IImportShallow decodes "shallow" types.Package data encoded by
291 // [IExportShallow] in the same executable. This function cannot import data
292 // from cmd/compile or gcexportdata.Write.
293 //
294 // The importer calls getPackages to obtain package symbols for all
295 // packages mentioned in the export data, including the one being
296 // decoded.
297 //
298 // If the provided reportf func is non-nil, it will be used for reporting bugs
299 // encountered during import.
300 // TODO(rfindley): remove reportf when we are confident enough in the new
301 // objectpath encoding.
302 func IImportShallow(fset *token.FileSet, getPackages GetPackagesFunc, data []byte, path string, reportf ReportFunc) (*types.Package, error) {
303 const bundle = false
304 const shallow = true
305 pkgs, err := iimportCommon(fset, getPackages, data, bundle, path, shallow, reportf)
306 if err != nil {
307 return nil, err
308 }
309 return pkgs[0], nil
310 }
311
312 // ReportFunc is the type of a function used to report formatted bugs.
313 type ReportFunc = func(string, ...any)
314
315 // Current bundled export format version. Increase with each format change.
316 // 0: initial implementation
317 const bundleVersion = 0
318
319 // IExportData writes indexed export data for pkg to out.
320 //
321 // If no file set is provided, position info will be missing.
322 // The package path of the top-level package will not be recorded,
323 // so that calls to IImportData can override with a provided package path.
324 func IExportData(out io.Writer, fset *token.FileSet, pkg *types.Package) error {
325 const bundle, shallow = false, false
326 return iexportCommon(out, fset, bundle, shallow, iexportVersion, []*types.Package{pkg}, nil)
327 }
328
329 // IExportBundle writes an indexed export bundle for pkgs to out.
330 func IExportBundle(out io.Writer, fset *token.FileSet, pkgs []*types.Package) error {
331 const bundle, shallow = true, false
332 return iexportCommon(out, fset, bundle, shallow, iexportVersion, pkgs, nil)
333 }
334
335 func iexportCommon(out io.Writer, fset *token.FileSet, bundle, shallow bool, version int, pkgs []*types.Package, reportf ReportFunc) (err error) {
336 if !debug {
337 defer func() {
338 if e := recover(); e != nil {
339 // Report the stack via telemetry (see #71067).
340 if reportf != nil {
341 reportf("panic in exporter")
342 }
343 if ierr, ok := e.(internalError); ok {
344 // internalError usually means we exported a
345 // bad go/types data structure: a violation
346 // of an implicit precondition of Export.
347 err = ierr
348 return
349 }
350 // Not an internal error; panic again.
351 panic(e)
352 }
353 }()
354 }
355
356 p := iexporter{
357 fset: fset,
358 version: version,
359 shallow: shallow,
360 allPkgs: map[*types.Package]bool{},
361 stringIndex: map[string]uint64{},
362 declIndex: map[types.Object]uint64{},
363 tparamNames: map[types.Object]string{},
364 typIndex: map[types.Type]uint64{},
365 }
366 if !bundle {
367 p.localpkg = pkgs[0]
368 }
369
370 for i, pt := range predeclared() {
371 p.typIndex[pt] = uint64(i)
372 }
373 if len(p.typIndex) > predeclReserved {
374 panic(internalErrorf("too many predeclared types: %d > %d", len(p.typIndex), predeclReserved))
375 }
376
377 // Initialize work queue with exported declarations.
378 for _, pkg := range pkgs {
379 scope := pkg.Scope()
380 for _, name := range scope.Names() {
381 if token.IsExported(name) {
382 p.pushDecl(scope.Lookup(name))
383 }
384 }
385
386 if bundle {
387 // Ensure pkg and its imports are included in the index.
388 p.allPkgs[pkg] = true
389 for _, imp := range pkg.Imports() {
390 p.allPkgs[imp] = true
391 }
392 }
393 }
394
395 // Loop until no more work.
396 for !p.declTodo.empty() {
397 p.doDecl(p.declTodo.popHead())
398 }
399
400 // Produce index of offset of each file record in files.
401 var files intWriter
402 var fileOffset []uint64 // fileOffset[i] is offset in files of file encoded as i
403 if p.shallow {
404 fileOffset = make([]uint64, len(p.fileInfos))
405 for i, info := range p.fileInfos {
406 fileOffset[i] = uint64(files.Len())
407 p.encodeFile(&files, info.file, info.needed)
408 }
409 }
410
411 // Append indices to data0 section.
412 dataLen := uint64(p.data0.Len())
413 w := p.newWriter()
414 w.writeIndex(p.declIndex)
415
416 if bundle {
417 w.uint64(uint64(len(pkgs)))
418 for _, pkg := range pkgs {
419 w.pkg(pkg)
420 imps := pkg.Imports()
421 w.uint64(uint64(len(imps)))
422 for _, imp := range imps {
423 w.pkg(imp)
424 }
425 }
426 }
427 w.flush()
428
429 // Assemble header.
430 var hdr intWriter
431 if bundle {
432 hdr.uint64(bundleVersion)
433 }
434 hdr.uint64(uint64(p.version))
435 hdr.uint64(uint64(p.strings.Len()))
436 if p.shallow {
437 hdr.uint64(uint64(files.Len()))
438 hdr.uint64(uint64(len(fileOffset)))
439 for _, offset := range fileOffset {
440 hdr.uint64(offset)
441 }
442 }
443 hdr.uint64(dataLen)
444
445 // Flush output.
446 io.Copy(out, &hdr)
447 io.Copy(out, &p.strings)
448 if p.shallow {
449 io.Copy(out, &files)
450 }
451 io.Copy(out, &p.data0)
452
453 return nil
454 }
455
456 // encodeFile writes to w a representation of the file sufficient to
457 // faithfully restore position information about all needed offsets.
458 // Mutates the needed array.
459 func (p *iexporter) encodeFile(w *intWriter, file *token.File, needed []uint64) {
460 _ = needed[0] // precondition: needed is non-empty
461
462 w.uint64(p.stringOff(file.Name()))
463
464 size := uint64(file.Size())
465 w.uint64(size)
466
467 // Sort the set of needed offsets. Duplicates are harmless.
468 slices.Sort(needed)
469
470 lines := file.Lines() // byte offset of each line start
471 w.uint64(uint64(len(lines)))
472
473 // Rather than record the entire array of line start offsets,
474 // we save only a sparse list of (index, offset) pairs for
475 // the start of each line that contains a needed position.
476 var sparse [][2]int // (index, offset) pairs
477 outer:
478 for i, lineStart := range lines {
479 lineEnd := size
480 if i < len(lines)-1 {
481 lineEnd = uint64(lines[i+1])
482 }
483 // Does this line contains a needed offset?
484 if needed[0] < lineEnd {
485 sparse = append(sparse, [2]int{i, lineStart})
486 for needed[0] < lineEnd {
487 needed = needed[1:]
488 if len(needed) == 0 {
489 break outer
490 }
491 }
492 }
493 }
494
495 // Delta-encode the columns.
496 w.uint64(uint64(len(sparse)))
497 var prev [2]int
498 for _, pair := range sparse {
499 w.uint64(uint64(pair[0] - prev[0]))
500 w.uint64(uint64(pair[1] - prev[1]))
501 prev = pair
502 }
503 }
504
505 // writeIndex writes out an object index. mainIndex indicates whether
506 // we're writing out the main index, which is also read by
507 // non-compiler tools and includes a complete package description
508 // (i.e., name and height).
509 func (w *exportWriter) writeIndex(index map[types.Object]uint64) {
510 type pkgObj struct {
511 obj types.Object
512 name string // qualified name; differs from obj.Name for type params
513 }
514 // Build a map from packages to objects from that package.
515 pkgObjs := map[*types.Package][]pkgObj{}
516
517 // For the main index, make sure to include every package that
518 // we reference, even if we're not exporting (or reexporting)
519 // any symbols from it.
520 if w.p.localpkg != nil {
521 pkgObjs[w.p.localpkg] = nil
522 }
523 for pkg := range w.p.allPkgs {
524 pkgObjs[pkg] = nil
525 }
526
527 for obj := range index {
528 name := w.p.exportName(obj)
529 pkgObjs[obj.Pkg()] = append(pkgObjs[obj.Pkg()], pkgObj{obj, name})
530 }
531
532 var pkgs []*types.Package
533 for pkg, objs := range pkgObjs {
534 pkgs = append(pkgs, pkg)
535
536 sort.Slice(objs, func(i, j int) bool {
537 return objs[i].name < objs[j].name
538 })
539 }
540
541 sort.Slice(pkgs, func(i, j int) bool {
542 return w.exportPath(pkgs[i]) < w.exportPath(pkgs[j])
543 })
544
545 w.uint64(uint64(len(pkgs)))
546 for _, pkg := range pkgs {
547 w.string(w.exportPath(pkg))
548 w.string(pkg.Name())
549 w.uint64(uint64(0)) // package height is not needed for go/types
550
551 objs := pkgObjs[pkg]
552 w.uint64(uint64(len(objs)))
553 for _, obj := range objs {
554 w.string(obj.name)
555 w.uint64(index[obj.obj])
556 }
557 }
558 }
559
560 // exportName returns the 'exported' name of an object. It differs from
561 // obj.Name() only for type parameters (see tparamExportName for details).
562 func (p *iexporter) exportName(obj types.Object) (res string) {
563 if name := p.tparamNames[obj]; name != "" {
564 return name
565 }
566 return obj.Name()
567 }
568
569 type iexporter struct {
570 fset *token.FileSet
571 version int
572
573 shallow bool // don't put types from other packages in the index
574 objEncoder *objectpath.Encoder // encodes objects from other packages in shallow mode; lazily allocated
575 localpkg *types.Package // (nil in bundle mode)
576
577 // allPkgs tracks all packages that have been referenced by
578 // the export data, so we can ensure to include them in the
579 // main index.
580 allPkgs map[*types.Package]bool
581
582 declTodo objQueue
583
584 strings intWriter
585 stringIndex map[string]uint64
586
587 // In shallow mode, object positions are encoded as (file, offset).
588 // Each file is recorded as a line-number table.
589 // Only the lines of needed positions are saved faithfully.
590 fileInfo map[*token.File]uint64 // value is index in fileInfos
591 fileInfos []*filePositions
592
593 data0 intWriter
594 declIndex map[types.Object]uint64
595 tparamNames map[types.Object]string // typeparam->exported name
596 typIndex map[types.Type]uint64
597
598 indent int // for tracing support
599 }
600
601 type filePositions struct {
602 file *token.File
603 needed []uint64 // unordered list of needed file offsets
604 }
605
606 func (p *iexporter) trace(format string, args ...any) {
607 if !trace {
608 // Call sites should also be guarded, but having this check here allows
609 // easily enabling/disabling debug trace statements.
610 return
611 }
612 fmt.Printf(strings.Repeat("..", p.indent)+format+"\n", args...)
613 }
614
615 // objectpathEncoder returns the lazily allocated objectpath.Encoder to use
616 // when encoding objects in other packages during shallow export.
617 //
618 // Using a shared Encoder amortizes some of cost of objectpath search.
619 func (p *iexporter) objectpathEncoder() *objectpath.Encoder {
620 if p.objEncoder == nil {
621 p.objEncoder = new(objectpath.Encoder)
622 }
623 return p.objEncoder
624 }
625
626 // stringOff returns the offset of s within the string section.
627 // If not already present, it's added to the end.
628 func (p *iexporter) stringOff(s string) uint64 {
629 off, ok := p.stringIndex[s]
630 if !ok {
631 off = uint64(p.strings.Len())
632 p.stringIndex[s] = off
633
634 p.strings.uint64(uint64(len(s)))
635 p.strings.WriteString(s)
636 }
637 return off
638 }
639
640 // fileIndexAndOffset returns the index of the token.File and the byte offset of pos within it.
641 func (p *iexporter) fileIndexAndOffset(file *token.File, pos token.Pos) (uint64, uint64) {
642 index, ok := p.fileInfo[file]
643 if !ok {
644 index = uint64(len(p.fileInfo))
645 p.fileInfos = append(p.fileInfos, &filePositions{file: file})
646 if p.fileInfo == nil {
647 p.fileInfo = make(map[*token.File]uint64)
648 }
649 p.fileInfo[file] = index
650 }
651 // Record each needed offset.
652 info := p.fileInfos[index]
653 offset := uint64(file.Offset(pos))
654 info.needed = append(info.needed, offset)
655
656 return index, offset
657 }
658
659 // pushDecl adds n to the declaration work queue, if not already present.
660 func (p *iexporter) pushDecl(obj types.Object) {
661 // Package unsafe is known to the compiler and predeclared.
662 // Caller should not ask us to do export it.
663 if obj.Pkg() == types.Unsafe {
664 panic("cannot export package unsafe")
665 }
666
667 // Shallow export data: don't index decls from other packages.
668 if p.shallow && obj.Pkg() != p.localpkg {
669 return
670 }
671
672 if _, ok := p.declIndex[obj]; ok {
673 return
674 }
675
676 p.declIndex[obj] = ^uint64(0) // mark obj present in work queue
677 p.declTodo.pushTail(obj)
678 }
679
680 // exportWriter handles writing out individual data section chunks.
681 type exportWriter struct {
682 p *iexporter
683
684 data intWriter
685 prevFile string
686 prevLine int64
687 prevColumn int64
688 }
689
690 func (w *exportWriter) exportPath(pkg *types.Package) string {
691 if pkg == w.p.localpkg {
692 return ""
693 }
694 return pkg.Path()
695 }
696
697 func (p *iexporter) doDecl(obj types.Object) {
698 if trace {
699 p.trace("exporting decl %v (%T)", obj, obj)
700 p.indent++
701 defer func() {
702 p.indent--
703 p.trace("=> %s", obj)
704 }()
705 }
706 w := p.newWriter()
707
708 switch obj := obj.(type) {
709 case *types.Var:
710 w.tag(varTag)
711 w.pos(obj.Pos())
712 w.typ(obj.Type(), obj.Pkg())
713
714 case *types.Func:
715 sig, _ := obj.Type().(*types.Signature)
716 if sig.Recv() != nil {
717 // We shouldn't see methods in the package scope,
718 // but the type checker may repair "func () F() {}"
719 // to "func (Invalid) F()" and then treat it like "func F()",
720 // so allow that. See golang/go#57729.
721 if sig.Recv().Type() != types.Typ[types.Invalid] {
722 panic(internalErrorf("unexpected method: %v", sig))
723 }
724 }
725
726 // Function.
727 if sig.TypeParams().Len() == 0 {
728 w.tag(funcTag)
729 } else {
730 w.tag(genericFuncTag)
731 }
732 w.pos(obj.Pos())
733 // The tparam list of the function type is the declaration of the type
734 // params. So, write out the type params right now. Then those type params
735 // will be referenced via their type offset (via typOff) in all other
736 // places in the signature and function where they are used.
737 //
738 // While importing the type parameters, tparamList computes and records
739 // their export name, so that it can be later used when writing the index.
740 if tparams := sig.TypeParams(); tparams.Len() > 0 {
741 w.tparamList(obj.Name(), tparams, obj.Pkg())
742 }
743 w.signature(sig)
744
745 case *types.Const:
746 w.tag(constTag)
747 w.pos(obj.Pos())
748 w.value(obj.Type(), obj.Val())
749
750 case *types.TypeName:
751 t := obj.Type()
752
753 if tparam, ok := types.Unalias(t).(*types.TypeParam); ok {
754 w.tag(typeParamTag)
755 w.pos(obj.Pos())
756 constraint := tparam.Constraint()
757 if p.version >= iexportVersionGo1_18 {
758 implicit := false
759 if iface, _ := types.Unalias(constraint).(*types.Interface); iface != nil {
760 implicit = iface.IsImplicit()
761 }
762 w.bool(implicit)
763 }
764 w.typ(constraint, obj.Pkg())
765 break
766 }
767
768 if obj.IsAlias() {
769 alias, materialized := t.(*types.Alias) // perhaps false for certain built-ins?
770
771 var tparams *types.TypeParamList
772 if materialized {
773 tparams = alias.TypeParams()
774 }
775 if tparams.Len() == 0 {
776 w.tag(aliasTag)
777 } else {
778 w.tag(genericAliasTag)
779 }
780 w.pos(obj.Pos())
781 if tparams.Len() > 0 {
782 w.tparamList(obj.Name(), tparams, obj.Pkg())
783 }
784 if materialized {
785 // Preserve materialized aliases,
786 // even of non-exported types.
787 t = alias.Rhs()
788 }
789 w.typ(t, obj.Pkg())
790 break
791 }
792
793 // Defined type.
794 named, ok := t.(*types.Named)
795 if !ok {
796 panic(internalErrorf("%s is not a defined type", t))
797 }
798
799 if named.TypeParams().Len() == 0 {
800 w.tag(typeTag)
801 } else {
802 w.tag(genericTypeTag)
803 }
804 w.pos(obj.Pos())
805
806 if named.TypeParams().Len() > 0 {
807 // While importing the type parameters, tparamList computes and records
808 // their export name, so that it can be later used when writing the index.
809 w.tparamList(obj.Name(), named.TypeParams(), obj.Pkg())
810 }
811
812 underlying := named.Underlying()
813 w.typ(underlying, obj.Pkg())
814
815 if types.IsInterface(t) {
816 break
817 }
818
819 n := named.NumMethods()
820 w.uint64(uint64(n))
821 for i := range n {
822 m := named.Method(i)
823 w.pos(m.Pos())
824 w.string(m.Name())
825 sig, _ := m.Type().(*types.Signature)
826
827 // Receiver type parameters are type arguments of the receiver type, so
828 // their name must be qualified before exporting recv.
829 if rparams := sig.RecvTypeParams(); rparams.Len() > 0 {
830 prefix := obj.Name() + "." + m.Name()
831 for rparam := range rparams.TypeParams() {
832 name := tparamExportName(prefix, rparam)
833 w.p.tparamNames[rparam.Obj()] = name
834 }
835 }
836 w.param(sig.Recv())
837 w.signature(sig)
838 }
839
840 default:
841 panic(internalErrorf("unexpected object: %v", obj))
842 }
843
844 p.declIndex[obj] = w.flush()
845 }
846
847 func (w *exportWriter) tag(tag byte) {
848 w.data.WriteByte(tag)
849 }
850
851 func (w *exportWriter) pos(pos token.Pos) {
852 if w.p.shallow {
853 w.posV2(pos)
854 } else if w.p.version >= iexportVersionPosCol {
855 w.posV1(pos)
856 } else {
857 w.posV0(pos)
858 }
859 }
860
861 // posV2 encoding (used only in shallow mode) records positions as
862 // (file, offset), where file is the index in the token.File table
863 // (which records the file name and newline offsets) and offset is a
864 // byte offset. It effectively ignores //line directives.
865 func (w *exportWriter) posV2(pos token.Pos) {
866 if pos == token.NoPos {
867 w.uint64(0)
868 return
869 }
870 file := w.p.fset.File(pos) // fset must be non-nil
871 index, offset := w.p.fileIndexAndOffset(file, pos)
872 w.uint64(1 + index)
873 w.uint64(offset)
874 }
875
876 func (w *exportWriter) posV1(pos token.Pos) {
877 if w.p.fset == nil {
878 w.int64(0)
879 return
880 }
881
882 p := w.p.fset.Position(pos)
883 file := p.Filename
884 line := int64(p.Line)
885 column := int64(p.Column)
886
887 deltaColumn := (column - w.prevColumn) << 1
888 deltaLine := (line - w.prevLine) << 1
889
890 if file != w.prevFile {
891 deltaLine |= 1
892 }
893 if deltaLine != 0 {
894 deltaColumn |= 1
895 }
896
897 w.int64(deltaColumn)
898 if deltaColumn&1 != 0 {
899 w.int64(deltaLine)
900 if deltaLine&1 != 0 {
901 w.string(file)
902 }
903 }
904
905 w.prevFile = file
906 w.prevLine = line
907 w.prevColumn = column
908 }
909
910 func (w *exportWriter) posV0(pos token.Pos) {
911 if w.p.fset == nil {
912 w.int64(0)
913 return
914 }
915
916 p := w.p.fset.Position(pos)
917 file := p.Filename
918 line := int64(p.Line)
919
920 // When file is the same as the last position (common case),
921 // we can save a few bytes by delta encoding just the line
922 // number.
923 //
924 // Note: Because data objects may be read out of order (or not
925 // at all), we can only apply delta encoding within a single
926 // object. This is handled implicitly by tracking prevFile and
927 // prevLine as fields of exportWriter.
928
929 if file == w.prevFile {
930 delta := line - w.prevLine
931 w.int64(delta)
932 if delta == deltaNewFile {
933 w.int64(-1)
934 }
935 } else {
936 w.int64(deltaNewFile)
937 w.int64(line) // line >= 0
938 w.string(file)
939 w.prevFile = file
940 }
941 w.prevLine = line
942 }
943
944 func (w *exportWriter) pkg(pkg *types.Package) {
945 if pkg == nil {
946 // [exportWriter.typ] accepts a nil pkg only for types
947 // of constants, which cannot contain named objects
948 // such as fields or methods and thus should never
949 // reach this method (#76222).
950 panic("nil package")
951 }
952 // Ensure any referenced packages are declared in the main index.
953 w.p.allPkgs[pkg] = true
954
955 w.string(w.exportPath(pkg))
956 }
957
958 func (w *exportWriter) qualifiedType(obj *types.TypeName) {
959 name := w.p.exportName(obj)
960
961 // Ensure any referenced declarations are written out too.
962 w.p.pushDecl(obj)
963 w.string(name)
964 w.pkg(obj.Pkg())
965 }
966
967 // typ emits the specified type.
968 //
969 // Objects within the type (struct fields and interface methods) are
970 // qualified by pkg. It may be nil if the type cannot contain objects,
971 // such as the type of a constant.
972 func (w *exportWriter) typ(t types.Type, pkg *types.Package) {
973 w.data.uint64(w.p.typOff(t, pkg))
974 }
975
976 func (p *iexporter) newWriter() *exportWriter {
977 return &exportWriter{p: p}
978 }
979
980 func (w *exportWriter) flush() uint64 {
981 off := uint64(w.p.data0.Len())
982 io.Copy(&w.p.data0, &w.data)
983 return off
984 }
985
986 func (p *iexporter) typOff(t types.Type, pkg *types.Package) uint64 {
987 off, ok := p.typIndex[t]
988 if !ok {
989 w := p.newWriter()
990 w.doTyp(t, pkg)
991 off = predeclReserved + w.flush()
992 p.typIndex[t] = off
993 }
994 return off
995 }
996
997 func (w *exportWriter) startType(k itag) {
998 w.data.uint64(uint64(k))
999 }
1000
1001 // doTyp is the implementation of [exportWriter.typ].
1002 func (w *exportWriter) doTyp(t types.Type, pkg *types.Package) {
1003 if trace {
1004 w.p.trace("exporting type %s (%T)", t, t)
1005 w.p.indent++
1006 defer func() {
1007 w.p.indent--
1008 w.p.trace("=> %s", t)
1009 }()
1010 }
1011 switch t := t.(type) {
1012 case *types.Alias:
1013 if targs := t.TypeArgs(); targs.Len() > 0 {
1014 w.startType(instanceType)
1015 w.pos(t.Obj().Pos())
1016 w.typeList(targs, pkg)
1017 w.typ(t.Origin(), pkg)
1018 return
1019 }
1020 w.startType(aliasType)
1021 w.qualifiedType(t.Obj())
1022
1023 case *types.Named:
1024 if targs := t.TypeArgs(); targs.Len() > 0 {
1025 w.startType(instanceType)
1026 // TODO(rfindley): investigate if this position is correct, and if it
1027 // matters.
1028 w.pos(t.Obj().Pos())
1029 w.typeList(targs, pkg)
1030 w.typ(t.Origin(), pkg)
1031 return
1032 }
1033 w.startType(definedType)
1034 w.qualifiedType(t.Obj())
1035
1036 case *types.TypeParam:
1037 w.startType(typeParamType)
1038 w.qualifiedType(t.Obj())
1039
1040 case *types.Pointer:
1041 w.startType(pointerType)
1042 w.typ(t.Elem(), pkg)
1043
1044 case *types.Slice:
1045 w.startType(sliceType)
1046 w.typ(t.Elem(), pkg)
1047
1048 case *types.Array:
1049 w.startType(arrayType)
1050 w.uint64(uint64(t.Len()))
1051 w.typ(t.Elem(), pkg)
1052
1053 case *types.Chan:
1054 w.startType(chanType)
1055 // 1 RecvOnly; 2 SendOnly; 3 SendRecv
1056 var dir uint64
1057 switch t.Dir() {
1058 case types.RecvOnly:
1059 dir = 1
1060 case types.SendOnly:
1061 dir = 2
1062 case types.SendRecv:
1063 dir = 3
1064 }
1065 w.uint64(dir)
1066 w.typ(t.Elem(), pkg)
1067
1068 case *types.Map:
1069 w.startType(mapType)
1070 w.typ(t.Key(), pkg)
1071 w.typ(t.Elem(), pkg)
1072
1073 case *types.Signature:
1074 w.startType(signatureType)
1075 w.pkg(pkg) // qualifies param/result vars
1076 w.signature(t)
1077
1078 case *types.Struct:
1079 w.startType(structType)
1080 n := t.NumFields()
1081 // Even for struct{} we must emit some qualifying package, because that's
1082 // what the compiler does, and thus that's what the importer expects.
1083 fieldPkg := pkg
1084 if n > 0 {
1085 fieldPkg = t.Field(0).Pkg()
1086 }
1087 if fieldPkg == nil {
1088 // TODO(rfindley): improve this very hacky logic.
1089 //
1090 // The importer expects a package to be set for all struct types, even
1091 // those with no fields. A better encoding might be to set NumFields
1092 // before pkg. setPkg panics with a nil package, which may be possible
1093 // to reach with invalid packages (and perhaps valid packages, too?), so
1094 // (arbitrarily) set the localpkg if available.
1095 //
1096 // Alternatively, we may be able to simply guarantee that pkg != nil, by
1097 // reconsidering the encoding of constant values.
1098 if w.p.shallow {
1099 fieldPkg = w.p.localpkg
1100 } else {
1101 panic(internalErrorf("no package to set for empty struct"))
1102 }
1103 }
1104 w.pkg(fieldPkg)
1105 w.uint64(uint64(n))
1106
1107 for i := range n {
1108 f := t.Field(i)
1109 if w.p.shallow {
1110 w.objectPath(f)
1111 }
1112 w.pos(f.Pos())
1113 w.string(f.Name()) // unexported fields implicitly qualified by prior setPkg
1114 w.typ(f.Type(), fieldPkg)
1115 w.bool(f.Anonymous())
1116 w.string(t.Tag(i)) // note (or tag)
1117 }
1118
1119 case *types.Interface:
1120 w.startType(interfaceType)
1121 w.pkg(pkg) // qualifies unexported method funcs
1122
1123 n := t.NumEmbeddeds()
1124 w.uint64(uint64(n))
1125 for i := 0; i < n; i++ {
1126 ft := t.EmbeddedType(i)
1127 if named, _ := types.Unalias(ft).(*types.Named); named != nil {
1128 w.pos(named.Obj().Pos())
1129 } else {
1130 // e.g. ~int
1131 w.pos(token.NoPos)
1132 }
1133 w.typ(ft, pkg)
1134 }
1135
1136 // See comment for struct fields. In shallow mode we change the encoding
1137 // for interface methods that are promoted from other packages.
1138
1139 n = t.NumExplicitMethods()
1140 w.uint64(uint64(n))
1141 for i := 0; i < n; i++ {
1142 m := t.ExplicitMethod(i)
1143 if w.p.shallow {
1144 w.objectPath(m)
1145 }
1146 w.pos(m.Pos())
1147 w.string(m.Name())
1148 sig, _ := m.Type().(*types.Signature)
1149 w.signature(sig)
1150 }
1151
1152 case *types.Union:
1153 w.startType(unionType)
1154 nt := t.Len()
1155 w.uint64(uint64(nt))
1156 for i := range nt {
1157 term := t.Term(i)
1158 w.bool(term.Tilde())
1159 w.typ(term.Type(), pkg)
1160 }
1161
1162 default:
1163 panic(internalErrorf("unexpected type: %v, %v", t, reflect.TypeOf(t)))
1164 }
1165 }
1166
1167 // objectPath writes the package and objectPath to use to look up obj in a
1168 // different package, when encoding in "shallow" mode.
1169 //
1170 // When doing a shallow import, the importer creates only the local package,
1171 // and requests package symbols for dependencies from the client.
1172 // However, certain types defined in the local package may hold objects defined
1173 // (perhaps deeply) within another package.
1174 //
1175 // For example, consider the following:
1176 //
1177 // package a
1178 // func F() chan * map[string] struct { X int }
1179 //
1180 // package b
1181 // import "a"
1182 // var B = a.F()
1183 //
1184 // In this example, the type of b.B holds fields defined in package a.
1185 // In order to have the correct canonical objects for the field defined in the
1186 // type of B, they are encoded as objectPaths and later looked up in the
1187 // importer. The same problem applies to interface methods.
1188 func (w *exportWriter) objectPath(obj types.Object) {
1189 if obj.Pkg() == nil || obj.Pkg() == w.p.localpkg {
1190 // obj.Pkg() may be nil for the builtin error.Error.
1191 // In this case, or if obj is declared in the local package, no need to
1192 // encode.
1193 w.string("")
1194 return
1195 }
1196 objectPath, err := w.p.objectpathEncoder().For(obj)
1197 if err != nil {
1198 // Fall back to the empty string, which will cause the importer to create a
1199 // new object, which matches earlier behavior. Creating a new object is
1200 // sufficient for many purposes (such as type checking), but causes certain
1201 // references algorithms to fail (golang/go#60819). However, we didn't
1202 // notice this problem during months of [email protected] testing.
1203 //
1204 // TODO(golang/go#61674): this workaround is insufficient, as in the case
1205 // where the field forwarded from an instantiated type that may not appear
1206 // in the export data of the original package:
1207 //
1208 // // package a
1209 // type A[P any] struct{ F P }
1210 //
1211 // // package b
1212 // type B a.A[int]
1213 //
1214 // We need to update references algorithms not to depend on this
1215 // de-duplication, at which point we may want to simply remove the
1216 // workaround here.
1217 w.string("")
1218 return
1219 }
1220 w.string(string(objectPath))
1221 w.pkg(obj.Pkg())
1222 }
1223
1224 func (w *exportWriter) signature(sig *types.Signature) {
1225 w.paramList(sig.Params())
1226 w.paramList(sig.Results())
1227 if sig.Params().Len() > 0 {
1228 w.bool(sig.Variadic())
1229 }
1230 }
1231
1232 func (w *exportWriter) typeList(ts *types.TypeList, pkg *types.Package) {
1233 w.uint64(uint64(ts.Len()))
1234 for t := range ts.Types() {
1235 w.typ(t, pkg)
1236 }
1237 }
1238
1239 func (w *exportWriter) tparamList(prefix string, list *types.TypeParamList, pkg *types.Package) {
1240 ll := uint64(list.Len())
1241 w.uint64(ll)
1242 for tparam := range list.TypeParams() {
1243 // Set the type parameter exportName before exporting its type.
1244 exportName := tparamExportName(prefix, tparam)
1245 w.p.tparamNames[tparam.Obj()] = exportName
1246 w.typ(tparam, pkg)
1247 }
1248 }
1249
1250 const blankMarker = "$"
1251
1252 // tparamExportName returns the 'exported' name of a type parameter, which
1253 // differs from its actual object name: it is prefixed with a qualifier, and
1254 // blank type parameter names are disambiguated by their index in the type
1255 // parameter list.
1256 func tparamExportName(prefix string, tparam *types.TypeParam) string {
1257 assert(prefix != "")
1258 name := tparam.Obj().Name()
1259 if name == "_" {
1260 name = blankMarker + strconv.Itoa(tparam.Index())
1261 }
1262 return prefix + "." + name
1263 }
1264
1265 // tparamName returns the real name of a type parameter, after stripping its
1266 // qualifying prefix and reverting blank-name encoding. See tparamExportName
1267 // for details.
1268 func tparamName(exportName string) string {
1269 // Remove the "path" from the type param name that makes it unique.
1270 ix := strings.LastIndex(exportName, ".")
1271 if ix < 0 {
1272 errorf("malformed type parameter export name %s: missing prefix", exportName)
1273 }
1274 name := exportName[ix+1:]
1275 if strings.HasPrefix(name, blankMarker) {
1276 return "_"
1277 }
1278 return name
1279 }
1280
1281 func (w *exportWriter) paramList(tup *types.Tuple) {
1282 n := tup.Len()
1283 w.uint64(uint64(n))
1284 for i := range n {
1285 w.param(tup.At(i))
1286 }
1287 }
1288
1289 func (w *exportWriter) param(obj types.Object) {
1290 w.pos(obj.Pos())
1291 w.localIdent(obj)
1292 w.typ(obj.Type(), obj.Pkg())
1293 }
1294
1295 func (w *exportWriter) value(typ types.Type, v constant.Value) {
1296 w.typ(typ, nil)
1297 if w.p.version >= iexportVersionGo1_18 {
1298 w.int64(int64(v.Kind()))
1299 }
1300
1301 if v.Kind() == constant.Unknown {
1302 // golang/go#60605: treat unknown constant values as if they have invalid type
1303 //
1304 // This loses some fidelity over the package type-checked from source, but that
1305 // is acceptable.
1306 //
1307 // TODO(rfindley): we should switch on the recorded constant kind rather
1308 // than the constant type
1309 return
1310 }
1311
1312 switch b := typ.Underlying().(*types.Basic); b.Info() & types.IsConstType {
1313 case types.IsBoolean:
1314 w.bool(constant.BoolVal(v))
1315 case types.IsInteger:
1316 var i big.Int
1317 if i64, exact := constant.Int64Val(v); exact {
1318 i.SetInt64(i64)
1319 } else if ui64, exact := constant.Uint64Val(v); exact {
1320 i.SetUint64(ui64)
1321 } else {
1322 i.SetString(v.ExactString(), 10)
1323 }
1324 w.mpint(&i, typ)
1325 case types.IsFloat:
1326 f := constantToFloat(v)
1327 w.mpfloat(f, typ)
1328 case types.IsComplex:
1329 w.mpfloat(constantToFloat(constant.Real(v)), typ)
1330 w.mpfloat(constantToFloat(constant.Imag(v)), typ)
1331 case types.IsString:
1332 w.string(constant.StringVal(v))
1333 default:
1334 if b.Kind() == types.Invalid {
1335 // package contains type errors
1336 break
1337 }
1338 panic(internalErrorf("unexpected type %v (%v)", typ, typ.Underlying()))
1339 }
1340 }
1341
1342 // constantToFloat converts a constant.Value with kind constant.Float to a
1343 // big.Float.
1344 func constantToFloat(x constant.Value) *big.Float {
1345 x = constant.ToFloat(x)
1346 // Use the same floating-point precision (512) as cmd/compile
1347 // (see Mpprec in cmd/compile/internal/gc/mpfloat.go).
1348 const mpprec = 512
1349 var f big.Float
1350 f.SetPrec(mpprec)
1351 if v, exact := constant.Float64Val(x); exact {
1352 // float64
1353 f.SetFloat64(v)
1354 } else if num, denom := constant.Num(x), constant.Denom(x); num.Kind() == constant.Int {
1355 // TODO(gri): add big.Rat accessor to constant.Value.
1356 n := valueToRat(num)
1357 d := valueToRat(denom)
1358 f.SetRat(n.Quo(n, d))
1359 } else {
1360 // Value too large to represent as a fraction => inaccessible.
1361 // TODO(gri): add big.Float accessor to constant.Value.
1362 _, ok := f.SetString(x.ExactString())
1363 assert(ok)
1364 }
1365 return &f
1366 }
1367
1368 func valueToRat(x constant.Value) *big.Rat {
1369 // Convert little-endian to big-endian.
1370 // I can't believe this is necessary.
1371 bytes := constant.Bytes(x)
1372 for i := 0; i < len(bytes)/2; i++ {
1373 bytes[i], bytes[len(bytes)-1-i] = bytes[len(bytes)-1-i], bytes[i]
1374 }
1375 return new(big.Rat).SetInt(new(big.Int).SetBytes(bytes))
1376 }
1377
1378 // mpint exports a multi-precision integer.
1379 //
1380 // For unsigned types, small values are written out as a single
1381 // byte. Larger values are written out as a length-prefixed big-endian
1382 // byte string, where the length prefix is encoded as its complement.
1383 // For example, bytes 0, 1, and 2 directly represent the integer
1384 // values 0, 1, and 2; while bytes 255, 254, and 253 indicate a 1-,
1385 // 2-, and 3-byte big-endian string follow.
1386 //
1387 // Encoding for signed types use the same general approach as for
1388 // unsigned types, except small values use zig-zag encoding and the
1389 // bottom bit of length prefix byte for large values is reserved as a
1390 // sign bit.
1391 //
1392 // The exact boundary between small and large encodings varies
1393 // according to the maximum number of bytes needed to encode a value
1394 // of type typ. As a special case, 8-bit types are always encoded as a
1395 // single byte.
1396 //
1397 // TODO(mdempsky): Is this level of complexity really worthwhile?
1398 func (w *exportWriter) mpint(x *big.Int, typ types.Type) {
1399 basic, ok := typ.Underlying().(*types.Basic)
1400 if !ok {
1401 panic(internalErrorf("unexpected type %v (%T)", typ.Underlying(), typ.Underlying()))
1402 }
1403
1404 signed, maxBytes := intSize(basic)
1405
1406 negative := x.Sign() < 0
1407 if !signed && negative {
1408 panic(internalErrorf("negative unsigned integer; type %v, value %v", typ, x))
1409 }
1410
1411 b := x.Bytes()
1412 if len(b) > 0 && b[0] == 0 {
1413 panic(internalErrorf("leading zeros"))
1414 }
1415 if uint(len(b)) > maxBytes {
1416 panic(internalErrorf("bad mpint length: %d > %d (type %v, value %v)", len(b), maxBytes, typ, x))
1417 }
1418
1419 maxSmall := 256 - maxBytes
1420 if signed {
1421 maxSmall = 256 - 2*maxBytes
1422 }
1423 if maxBytes == 1 {
1424 maxSmall = 256
1425 }
1426
1427 // Check if x can use small value encoding.
1428 if len(b) <= 1 {
1429 var ux uint
1430 if len(b) == 1 {
1431 ux = uint(b[0])
1432 }
1433 if signed {
1434 ux <<= 1
1435 if negative {
1436 ux--
1437 }
1438 }
1439 if ux < maxSmall {
1440 w.data.WriteByte(byte(ux))
1441 return
1442 }
1443 }
1444
1445 n := 256 - uint(len(b))
1446 if signed {
1447 n = 256 - 2*uint(len(b))
1448 if negative {
1449 n |= 1
1450 }
1451 }
1452 if n < maxSmall || n >= 256 {
1453 panic(internalErrorf("encoding mistake: %d, %v, %v => %d", len(b), signed, negative, n))
1454 }
1455
1456 w.data.WriteByte(byte(n))
1457 w.data.Write(b)
1458 }
1459
1460 // mpfloat exports a multi-precision floating point number.
1461 //
1462 // The number's value is decomposed into mantissa × 2**exponent, where
1463 // mantissa is an integer. The value is written out as mantissa (as a
1464 // multi-precision integer) and then the exponent, except exponent is
1465 // omitted if mantissa is zero.
1466 func (w *exportWriter) mpfloat(f *big.Float, typ types.Type) {
1467 if f.IsInf() {
1468 panic("infinite constant")
1469 }
1470
1471 // Break into f = mant × 2**exp, with 0.5 <= mant < 1.
1472 var mant big.Float
1473 exp := int64(f.MantExp(&mant))
1474
1475 // Scale so that mant is an integer.
1476 prec := mant.MinPrec()
1477 mant.SetMantExp(&mant, int(prec))
1478 exp -= int64(prec)
1479
1480 manti, acc := mant.Int(nil)
1481 if acc != big.Exact {
1482 panic(internalErrorf("mantissa scaling failed for %f (%s)", f, acc))
1483 }
1484 w.mpint(manti, typ)
1485 if manti.Sign() != 0 {
1486 w.int64(exp)
1487 }
1488 }
1489
1490 func (w *exportWriter) bool(b bool) bool {
1491 var x uint64
1492 if b {
1493 x = 1
1494 }
1495 w.uint64(x)
1496 return b
1497 }
1498
1499 func (w *exportWriter) int64(x int64) { w.data.int64(x) }
1500 func (w *exportWriter) uint64(x uint64) { w.data.uint64(x) }
1501 func (w *exportWriter) string(s string) { w.uint64(w.p.stringOff(s)) }
1502
1503 func (w *exportWriter) localIdent(obj types.Object) {
1504 // Anonymous parameters.
1505 if obj == nil {
1506 w.string("")
1507 return
1508 }
1509
1510 name := obj.Name()
1511 if name == "_" {
1512 w.string("_")
1513 return
1514 }
1515
1516 w.string(name)
1517 }
1518
1519 type intWriter struct {
1520 bytes.Buffer
1521 }
1522
1523 func (w *intWriter) int64(x int64) {
1524 var buf [binary.MaxVarintLen64]byte
1525 n := binary.PutVarint(buf[:], x)
1526 w.Write(buf[:n])
1527 }
1528
1529 func (w *intWriter) uint64(x uint64) {
1530 var buf [binary.MaxVarintLen64]byte
1531 n := binary.PutUvarint(buf[:], x)
1532 w.Write(buf[:n])
1533 }
1534
1535 func assert(cond bool) {
1536 if !cond {
1537 panic("internal error: assertion failed")
1538 }
1539 }
1540
1541 // The below is copied from go/src/cmd/compile/internal/gc/syntax.go.
1542
1543 // objQueue is a FIFO queue of types.Object. The zero value of objQueue is
1544 // a ready-to-use empty queue.
1545 type objQueue struct {
1546 ring []types.Object
1547 head, tail int
1548 }
1549
1550 // empty returns true if q contains no Nodes.
1551 func (q *objQueue) empty() bool {
1552 return q.head == q.tail
1553 }
1554
1555 // pushTail appends n to the tail of the queue.
1556 func (q *objQueue) pushTail(obj types.Object) {
1557 if len(q.ring) == 0 {
1558 q.ring = make([]types.Object, 16)
1559 } else if q.head+len(q.ring) == q.tail {
1560 // Grow the ring.
1561 nring := make([]types.Object, len(q.ring)*2)
1562 // Copy the old elements.
1563 part := q.ring[q.head%len(q.ring):]
1564 if q.tail-q.head <= len(part) {
1565 part = part[:q.tail-q.head]
1566 copy(nring, part)
1567 } else {
1568 pos := copy(nring, part)
1569 copy(nring[pos:], q.ring[:q.tail%len(q.ring)])
1570 }
1571 q.ring, q.head, q.tail = nring, 0, q.tail-q.head
1572 }
1573
1574 q.ring[q.tail%len(q.ring)] = obj
1575 q.tail++
1576 }
1577
1578 // popHead pops a node from the head of the queue. It panics if q is empty.
1579 func (q *objQueue) popHead() types.Object {
1580 if q.empty() {
1581 panic("dequeue empty")
1582 }
1583 obj := q.ring[q.head%len(q.ring)]
1584 q.head++
1585 return obj
1586 }
1587
1588 // internalError represents an error generated inside this package.
1589 type internalError string
1590
1591 func (e internalError) Error() string { return "gcimporter: " + string(e) }
1592
1593 // TODO(adonovan): make this call panic, so that it's symmetric with errorf.
1594 // Otherwise it's easy to forget to do anything with the error.
1595 //
1596 // TODO(adonovan): also, consider switching the names "errorf" and
1597 // "internalErrorf" as the former is used for bugs, whose cause is
1598 // internal inconsistency, whereas the latter is used for ordinary
1599 // situations like bad input, whose cause is external.
1600 func internalErrorf(format string, args ...any) error {
1601 return internalError(fmt.Sprintf(format, args...))
1602 }