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.
5 // Indexed binary package export.
6 // This file was derived from $GOROOT/src/cmd/compile/internal/gc/iexport.go;
7 // see that file for specification of the format.
24 // Current indexed export format version. Increase with each format change.
26 const iexportVersion = 0
28 // IExportData returns the binary export data for pkg.
30 // If no file set is provided, position info will be missing.
31 // The package path of the top-level package will not be recorded,
32 // so that calls to IImportData can override with a provided package path.
33 func IExportData(fset *token.FileSet, pkg *types.Package) (b []byte, err error) {
35 if e := recover(); e != nil {
36 if ierr, ok := e.(internalError); ok {
40 // Not an internal error; panic again.
46 out: bytes.NewBuffer(nil),
48 allPkgs: map[*types.Package]bool{},
49 stringIndex: map[string]uint64{},
50 declIndex: map[types.Object]uint64{},
51 typIndex: map[types.Type]uint64{},
55 for i, pt := range predeclared() {
56 p.typIndex[pt] = uint64(i)
58 if len(p.typIndex) > predeclReserved {
59 panic(internalErrorf("too many predeclared types: %d > %d", len(p.typIndex), predeclReserved))
62 // Initialize work queue with exported declarations.
64 for _, name := range scope.Names() {
65 if ast.IsExported(name) {
66 p.pushDecl(scope.Lookup(name))
70 // Loop until no more work.
71 for !p.declTodo.empty() {
72 p.doDecl(p.declTodo.popHead())
75 // Append indices to data0 section.
76 dataLen := uint64(p.data0.Len())
78 w.writeIndex(p.declIndex)
84 hdr.uint64(iexportVersion)
85 hdr.uint64(uint64(p.strings.Len()))
90 io.Copy(p.out, &p.strings)
91 io.Copy(p.out, &p.data0)
93 return p.out.Bytes(), nil
96 // writeIndex writes out an object index. mainIndex indicates whether
97 // we're writing out the main index, which is also read by
98 // non-compiler tools and includes a complete package description
99 // (i.e., name and height).
100 func (w *exportWriter) writeIndex(index map[types.Object]uint64) {
101 // Build a map from packages to objects from that package.
102 pkgObjs := map[*types.Package][]types.Object{}
104 // For the main index, make sure to include every package that
105 // we reference, even if we're not exporting (or reexporting)
106 // any symbols from it.
107 pkgObjs[w.p.localpkg] = nil
108 for pkg := range w.p.allPkgs {
112 for obj := range index {
113 pkgObjs[obj.Pkg()] = append(pkgObjs[obj.Pkg()], obj)
116 var pkgs []*types.Package
117 for pkg, objs := range pkgObjs {
118 pkgs = append(pkgs, pkg)
120 sort.Slice(objs, func(i, j int) bool {
121 return objs[i].Name() < objs[j].Name()
125 sort.Slice(pkgs, func(i, j int) bool {
126 return w.exportPath(pkgs[i]) < w.exportPath(pkgs[j])
129 w.uint64(uint64(len(pkgs)))
130 for _, pkg := range pkgs {
131 w.string(w.exportPath(pkg))
133 w.uint64(uint64(0)) // package height is not needed for go/types
136 w.uint64(uint64(len(objs)))
137 for _, obj := range objs {
144 type iexporter struct {
148 localpkg *types.Package
150 // allPkgs tracks all packages that have been referenced by
151 // the export data, so we can ensure to include them in the
153 allPkgs map[*types.Package]bool
158 stringIndex map[string]uint64
161 declIndex map[types.Object]uint64
162 typIndex map[types.Type]uint64
165 // stringOff returns the offset of s within the string section.
166 // If not already present, it's added to the end.
167 func (p *iexporter) stringOff(s string) uint64 {
168 off, ok := p.stringIndex[s]
170 off = uint64(p.strings.Len())
171 p.stringIndex[s] = off
173 p.strings.uint64(uint64(len(s)))
174 p.strings.WriteString(s)
179 // pushDecl adds n to the declaration work queue, if not already present.
180 func (p *iexporter) pushDecl(obj types.Object) {
181 // Package unsafe is known to the compiler and predeclared.
182 assert(obj.Pkg() != types.Unsafe)
184 if _, ok := p.declIndex[obj]; ok {
188 p.declIndex[obj] = ^uint64(0) // mark n present in work queue
189 p.declTodo.pushTail(obj)
192 // exportWriter handles writing out individual data section chunks.
193 type exportWriter struct {
197 currPkg *types.Package
202 func (w *exportWriter) exportPath(pkg *types.Package) string {
203 if pkg == w.p.localpkg {
209 func (p *iexporter) doDecl(obj types.Object) {
211 w.setPkg(obj.Pkg(), false)
213 switch obj := obj.(type) {
217 w.typ(obj.Type(), obj.Pkg())
220 sig, _ := obj.Type().(*types.Signature)
221 if sig.Recv() != nil {
222 panic(internalErrorf("unexpected method: %v", sig))
231 w.value(obj.Type(), obj.Val())
233 case *types.TypeName:
237 w.typ(obj.Type(), obj.Pkg())
245 underlying := obj.Type().Underlying()
246 w.typ(underlying, obj.Pkg())
249 if types.IsInterface(t) {
253 named, ok := t.(*types.Named)
255 panic(internalErrorf("%s is not a defined type", t))
258 n := named.NumMethods()
260 for i := 0; i < n; i++ {
264 sig, _ := m.Type().(*types.Signature)
270 panic(internalErrorf("unexpected object: %v", obj))
273 p.declIndex[obj] = w.flush()
276 func (w *exportWriter) tag(tag byte) {
277 w.data.WriteByte(tag)
280 func (w *exportWriter) pos(pos token.Pos) {
286 p := w.p.fset.Position(pos)
288 line := int64(p.Line)
290 // When file is the same as the last position (common case),
291 // we can save a few bytes by delta encoding just the line
294 // Note: Because data objects may be read out of order (or not
295 // at all), we can only apply delta encoding within a single
296 // object. This is handled implicitly by tracking prevFile and
297 // prevLine as fields of exportWriter.
299 if file == w.prevFile {
300 delta := line - w.prevLine
302 if delta == deltaNewFile {
306 w.int64(deltaNewFile)
307 w.int64(line) // line >= 0
314 func (w *exportWriter) pkg(pkg *types.Package) {
315 // Ensure any referenced packages are declared in the main index.
316 w.p.allPkgs[pkg] = true
318 w.string(w.exportPath(pkg))
321 func (w *exportWriter) qualifiedIdent(obj types.Object) {
322 // Ensure any referenced declarations are written out too.
329 func (w *exportWriter) typ(t types.Type, pkg *types.Package) {
330 w.data.uint64(w.p.typOff(t, pkg))
333 func (p *iexporter) newWriter() *exportWriter {
334 return &exportWriter{p: p}
337 func (w *exportWriter) flush() uint64 {
338 off := uint64(w.p.data0.Len())
339 io.Copy(&w.p.data0, &w.data)
343 func (p *iexporter) typOff(t types.Type, pkg *types.Package) uint64 {
344 off, ok := p.typIndex[t]
348 off = predeclReserved + w.flush()
354 func (w *exportWriter) startType(k itag) {
355 w.data.uint64(uint64(k))
358 func (w *exportWriter) doTyp(t types.Type, pkg *types.Package) {
359 switch t := t.(type) {
361 w.startType(definedType)
362 w.qualifiedIdent(t.Obj())
365 w.startType(pointerType)
369 w.startType(sliceType)
373 w.startType(arrayType)
374 w.uint64(uint64(t.Len()))
378 w.startType(chanType)
379 // 1 RecvOnly; 2 SendOnly; 3 SendRecv
397 case *types.Signature:
398 w.startType(signatureType)
403 w.startType(structType)
408 for i := 0; i < n; i++ {
413 w.bool(f.Anonymous())
414 w.string(t.Tag(i)) // note (or tag)
417 case *types.Interface:
418 w.startType(interfaceType)
421 n := t.NumEmbeddeds()
423 for i := 0; i < n; i++ {
426 w.typ(f.Obj().Type(), f.Obj().Pkg())
429 n = t.NumExplicitMethods()
431 for i := 0; i < n; i++ {
432 m := t.ExplicitMethod(i)
435 sig, _ := m.Type().(*types.Signature)
440 panic(internalErrorf("unexpected type: %v, %v", t, reflect.TypeOf(t)))
444 func (w *exportWriter) setPkg(pkg *types.Package, write bool) {
452 func (w *exportWriter) signature(sig *types.Signature) {
453 w.paramList(sig.Params())
454 w.paramList(sig.Results())
455 if sig.Params().Len() > 0 {
456 w.bool(sig.Variadic())
460 func (w *exportWriter) paramList(tup *types.Tuple) {
463 for i := 0; i < n; i++ {
468 func (w *exportWriter) param(obj types.Object) {
471 w.typ(obj.Type(), obj.Pkg())
474 func (w *exportWriter) value(typ types.Type, v constant.Value) {
479 w.bool(constant.BoolVal(v))
482 if i64, exact := constant.Int64Val(v); exact {
484 } else if ui64, exact := constant.Uint64Val(v); exact {
487 i.SetString(v.ExactString(), 10)
491 f := constantToFloat(v)
493 case constant.Complex:
494 w.mpfloat(constantToFloat(constant.Real(v)), typ)
495 w.mpfloat(constantToFloat(constant.Imag(v)), typ)
496 case constant.String:
497 w.string(constant.StringVal(v))
498 case constant.Unknown:
499 // package contains type errors
501 panic(internalErrorf("unexpected value %v (%T)", v, v))
505 // constantToFloat converts a constant.Value with kind constant.Float to a
507 func constantToFloat(x constant.Value) *big.Float {
508 assert(x.Kind() == constant.Float)
509 // Use the same floating-point precision (512) as cmd/compile
510 // (see Mpprec in cmd/compile/internal/gc/mpfloat.go).
514 if v, exact := constant.Float64Val(x); exact {
517 } else if num, denom := constant.Num(x), constant.Denom(x); num.Kind() == constant.Int {
518 // TODO(gri): add big.Rat accessor to constant.Value.
520 d := valueToRat(denom)
521 f.SetRat(n.Quo(n, d))
523 // Value too large to represent as a fraction => inaccessible.
524 // TODO(gri): add big.Float accessor to constant.Value.
525 _, ok := f.SetString(x.ExactString())
531 // mpint exports a multi-precision integer.
533 // For unsigned types, small values are written out as a single
534 // byte. Larger values are written out as a length-prefixed big-endian
535 // byte string, where the length prefix is encoded as its complement.
536 // For example, bytes 0, 1, and 2 directly represent the integer
537 // values 0, 1, and 2; while bytes 255, 254, and 253 indicate a 1-,
538 // 2-, and 3-byte big-endian string follow.
540 // Encoding for signed types use the same general approach as for
541 // unsigned types, except small values use zig-zag encoding and the
542 // bottom bit of length prefix byte for large values is reserved as a
545 // The exact boundary between small and large encodings varies
546 // according to the maximum number of bytes needed to encode a value
547 // of type typ. As a special case, 8-bit types are always encoded as a
550 // TODO(mdempsky): Is this level of complexity really worthwhile?
551 func (w *exportWriter) mpint(x *big.Int, typ types.Type) {
552 basic, ok := typ.Underlying().(*types.Basic)
554 panic(internalErrorf("unexpected type %v (%T)", typ.Underlying(), typ.Underlying()))
557 signed, maxBytes := intSize(basic)
559 negative := x.Sign() < 0
560 if !signed && negative {
561 panic(internalErrorf("negative unsigned integer; type %v, value %v", typ, x))
565 if len(b) > 0 && b[0] == 0 {
566 panic(internalErrorf("leading zeros"))
568 if uint(len(b)) > maxBytes {
569 panic(internalErrorf("bad mpint length: %d > %d (type %v, value %v)", len(b), maxBytes, typ, x))
572 maxSmall := 256 - maxBytes
574 maxSmall = 256 - 2*maxBytes
580 // Check if x can use small value encoding.
593 w.data.WriteByte(byte(ux))
598 n := 256 - uint(len(b))
600 n = 256 - 2*uint(len(b))
605 if n < maxSmall || n >= 256 {
606 panic(internalErrorf("encoding mistake: %d, %v, %v => %d", len(b), signed, negative, n))
609 w.data.WriteByte(byte(n))
613 // mpfloat exports a multi-precision floating point number.
615 // The number's value is decomposed into mantissa × 2**exponent, where
616 // mantissa is an integer. The value is written out as mantissa (as a
617 // multi-precision integer) and then the exponent, except exponent is
618 // omitted if mantissa is zero.
619 func (w *exportWriter) mpfloat(f *big.Float, typ types.Type) {
621 panic("infinite constant")
624 // Break into f = mant × 2**exp, with 0.5 <= mant < 1.
626 exp := int64(f.MantExp(&mant))
628 // Scale so that mant is an integer.
629 prec := mant.MinPrec()
630 mant.SetMantExp(&mant, int(prec))
633 manti, acc := mant.Int(nil)
634 if acc != big.Exact {
635 panic(internalErrorf("mantissa scaling failed for %f (%s)", f, acc))
638 if manti.Sign() != 0 {
643 func (w *exportWriter) bool(b bool) bool {
652 func (w *exportWriter) int64(x int64) { w.data.int64(x) }
653 func (w *exportWriter) uint64(x uint64) { w.data.uint64(x) }
654 func (w *exportWriter) string(s string) { w.uint64(w.p.stringOff(s)) }
656 func (w *exportWriter) localIdent(obj types.Object) {
657 // Anonymous parameters.
672 type intWriter struct {
676 func (w *intWriter) int64(x int64) {
677 var buf [binary.MaxVarintLen64]byte
678 n := binary.PutVarint(buf[:], x)
682 func (w *intWriter) uint64(x uint64) {
683 var buf [binary.MaxVarintLen64]byte
684 n := binary.PutUvarint(buf[:], x)
688 func assert(cond bool) {
690 panic("internal error: assertion failed")
694 // The below is copied from go/src/cmd/compile/internal/gc/syntax.go.
696 // objQueue is a FIFO queue of types.Object. The zero value of objQueue is
697 // a ready-to-use empty queue.
698 type objQueue struct {
703 // empty returns true if q contains no Nodes.
704 func (q *objQueue) empty() bool {
705 return q.head == q.tail
708 // pushTail appends n to the tail of the queue.
709 func (q *objQueue) pushTail(obj types.Object) {
710 if len(q.ring) == 0 {
711 q.ring = make([]types.Object, 16)
712 } else if q.head+len(q.ring) == q.tail {
714 nring := make([]types.Object, len(q.ring)*2)
715 // Copy the old elements.
716 part := q.ring[q.head%len(q.ring):]
717 if q.tail-q.head <= len(part) {
718 part = part[:q.tail-q.head]
721 pos := copy(nring, part)
722 copy(nring[pos:], q.ring[:q.tail%len(q.ring)])
724 q.ring, q.head, q.tail = nring, 0, q.tail-q.head
727 q.ring[q.tail%len(q.ring)] = obj
731 // popHead pops a node from the head of the queue. It panics if q is empty.
732 func (q *objQueue) popHead() types.Object {
734 panic("dequeue empty")
736 obj := q.ring[q.head%len(q.ring)]