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.
26 // Current indexed export format version. Increase with each format change.
28 const iexportVersion = 0
30 // IExportData returns the binary export data for pkg.
31 // If no file set is provided, position info will be missing.
32 func IExportData(fset *token.FileSet, pkg *types.Package) (b []byte, err error) {
34 if e := recover(); e != nil {
35 if ierr, ok := e.(internalError); ok {
39 // Not an internal error; panic again.
45 out: bytes.NewBuffer(nil),
47 allPkgs: map[*types.Package]bool{},
48 stringIndex: map[string]uint64{},
49 declIndex: map[types.Object]uint64{},
50 typIndex: map[types.Type]uint64{},
53 for i, pt := range predeclared() {
54 p.typIndex[pt] = uint64(i)
56 if len(p.typIndex) > predeclReserved {
57 panic(internalErrorf("too many predeclared types: %d > %d", len(p.typIndex), predeclReserved))
60 // Initialize work queue with exported declarations.
62 for _, name := range scope.Names() {
63 if ast.IsExported(name) {
64 p.pushDecl(scope.Lookup(name))
68 // Loop until no more work.
69 for !p.declTodo.empty() {
70 p.doDecl(p.declTodo.popHead())
73 // Append indices to data0 section.
74 dataLen := uint64(p.data0.Len())
76 w.writeIndex(p.declIndex, pkg)
82 hdr.uint64(iexportVersion)
83 hdr.uint64(uint64(p.strings.Len()))
88 io.Copy(p.out, &p.strings)
89 io.Copy(p.out, &p.data0)
91 return p.out.Bytes(), nil
94 // writeIndex writes out an object index. mainIndex indicates whether
95 // we're writing out the main index, which is also read by
96 // non-compiler tools and includes a complete package description
97 // (i.e., name and height).
98 func (w *exportWriter) writeIndex(index map[types.Object]uint64, localpkg *types.Package) {
99 // Build a map from packages to objects from that package.
100 pkgObjs := map[*types.Package][]types.Object{}
102 // For the main index, make sure to include every package that
103 // we reference, even if we're not exporting (or reexporting)
104 // any symbols from it.
105 pkgObjs[localpkg] = nil
106 for pkg := range w.p.allPkgs {
110 for obj := range index {
111 pkgObjs[obj.Pkg()] = append(pkgObjs[obj.Pkg()], obj)
114 var pkgs []*types.Package
115 for pkg, objs := range pkgObjs {
116 pkgs = append(pkgs, pkg)
118 sort.Slice(objs, func(i, j int) bool {
119 return objs[i].Name() < objs[j].Name()
123 sort.Slice(pkgs, func(i, j int) bool {
124 return pkgs[i].Path() < pkgs[j].Path()
127 w.uint64(uint64(len(pkgs)))
128 for _, pkg := range pkgs {
131 w.uint64(uint64(0)) // package height is not needed for go/types
134 w.uint64(uint64(len(objs)))
135 for _, obj := range objs {
142 type iexporter struct {
146 // allPkgs tracks all packages that have been referenced by
147 // the export data, so we can ensure to include them in the
149 allPkgs map[*types.Package]bool
154 stringIndex map[string]uint64
157 declIndex map[types.Object]uint64
158 typIndex map[types.Type]uint64
161 // stringOff returns the offset of s within the string section.
162 // If not already present, it's added to the end.
163 func (p *iexporter) stringOff(s string) uint64 {
164 off, ok := p.stringIndex[s]
166 off = uint64(p.strings.Len())
167 p.stringIndex[s] = off
169 p.strings.uint64(uint64(len(s)))
170 p.strings.WriteString(s)
175 // pushDecl adds n to the declaration work queue, if not already present.
176 func (p *iexporter) pushDecl(obj types.Object) {
177 // Package unsafe is known to the compiler and predeclared.
178 assert(obj.Pkg() != types.Unsafe)
180 if _, ok := p.declIndex[obj]; ok {
184 p.declIndex[obj] = ^uint64(0) // mark n present in work queue
185 p.declTodo.pushTail(obj)
188 // exportWriter handles writing out individual data section chunks.
189 type exportWriter struct {
193 currPkg *types.Package
198 func (p *iexporter) doDecl(obj types.Object) {
200 w.setPkg(obj.Pkg(), false)
202 switch obj := obj.(type) {
206 w.typ(obj.Type(), obj.Pkg())
209 sig, _ := obj.Type().(*types.Signature)
210 if sig.Recv() != nil {
211 panic(internalErrorf("unexpected method: %v", sig))
220 w.value(obj.Type(), obj.Val())
222 case *types.TypeName:
226 w.typ(obj.Type(), obj.Pkg())
234 underlying := obj.Type().Underlying()
235 w.typ(underlying, obj.Pkg())
238 if types.IsInterface(t) {
242 named, ok := t.(*types.Named)
244 panic(internalErrorf("%s is not a defined type", t))
247 n := named.NumMethods()
249 for i := 0; i < n; i++ {
253 sig, _ := m.Type().(*types.Signature)
259 panic(internalErrorf("unexpected object: %v", obj))
262 p.declIndex[obj] = w.flush()
265 func (w *exportWriter) tag(tag byte) {
266 w.data.WriteByte(tag)
269 func (w *exportWriter) pos(pos token.Pos) {
270 p := w.p.fset.Position(pos)
272 line := int64(p.Line)
274 // When file is the same as the last position (common case),
275 // we can save a few bytes by delta encoding just the line
278 // Note: Because data objects may be read out of order (or not
279 // at all), we can only apply delta encoding within a single
280 // object. This is handled implicitly by tracking prevFile and
281 // prevLine as fields of exportWriter.
283 if file == w.prevFile {
284 delta := line - w.prevLine
286 if delta == deltaNewFile {
290 w.int64(deltaNewFile)
291 w.int64(line) // line >= 0
298 func (w *exportWriter) pkg(pkg *types.Package) {
299 // Ensure any referenced packages are declared in the main index.
300 w.p.allPkgs[pkg] = true
305 func (w *exportWriter) qualifiedIdent(obj types.Object) {
306 // Ensure any referenced declarations are written out too.
313 func (w *exportWriter) typ(t types.Type, pkg *types.Package) {
314 w.data.uint64(w.p.typOff(t, pkg))
317 func (p *iexporter) newWriter() *exportWriter {
318 return &exportWriter{p: p}
321 func (w *exportWriter) flush() uint64 {
322 off := uint64(w.p.data0.Len())
323 io.Copy(&w.p.data0, &w.data)
327 func (p *iexporter) typOff(t types.Type, pkg *types.Package) uint64 {
328 off, ok := p.typIndex[t]
332 off = predeclReserved + w.flush()
338 func (w *exportWriter) startType(k itag) {
339 w.data.uint64(uint64(k))
342 func (w *exportWriter) doTyp(t types.Type, pkg *types.Package) {
343 switch t := t.(type) {
345 w.startType(definedType)
346 w.qualifiedIdent(t.Obj())
349 w.startType(pointerType)
353 w.startType(sliceType)
357 w.startType(arrayType)
358 w.uint64(uint64(t.Len()))
362 w.startType(chanType)
363 // 1 RecvOnly; 2 SendOnly; 3 SendRecv
381 case *types.Signature:
382 w.startType(signatureType)
387 w.startType(structType)
392 for i := 0; i < n; i++ {
398 w.string(t.Tag(i)) // note (or tag)
401 case *types.Interface:
402 w.startType(interfaceType)
405 n := t.NumEmbeddeds()
407 for i := 0; i < n; i++ {
410 w.typ(f.Obj().Type(), f.Obj().Pkg())
413 n = t.NumExplicitMethods()
415 for i := 0; i < n; i++ {
416 m := t.ExplicitMethod(i)
419 sig, _ := m.Type().(*types.Signature)
424 panic(internalErrorf("unexpected type: %v, %v", t, reflect.TypeOf(t)))
428 func (w *exportWriter) setPkg(pkg *types.Package, write bool) {
436 func (w *exportWriter) signature(sig *types.Signature) {
437 w.paramList(sig.Params())
438 w.paramList(sig.Results())
439 if sig.Params().Len() > 0 {
440 w.bool(sig.Variadic())
444 func (w *exportWriter) paramList(tup *types.Tuple) {
447 for i := 0; i < n; i++ {
452 func (w *exportWriter) param(obj types.Object) {
455 w.typ(obj.Type(), obj.Pkg())
458 func (w *exportWriter) value(typ types.Type, v constant.Value) {
463 w.bool(constant.BoolVal(v))
466 if i64, exact := constant.Int64Val(v); exact {
468 } else if ui64, exact := constant.Uint64Val(v); exact {
471 i.SetString(v.ExactString(), 10)
475 f := constantToFloat(v)
477 case constant.Complex:
478 w.mpfloat(constantToFloat(constant.Real(v)), typ)
479 w.mpfloat(constantToFloat(constant.Imag(v)), typ)
480 case constant.String:
481 w.string(constant.StringVal(v))
482 case constant.Unknown:
483 // package contains type errors
485 panic(internalErrorf("unexpected value %v (%T)", v, v))
489 // constantToFloat converts a constant.Value with kind constant.Float to a
491 func constantToFloat(x constant.Value) *big.Float {
492 assert(x.Kind() == constant.Float)
493 // Use the same floating-point precision (512) as cmd/compile
494 // (see Mpprec in cmd/compile/internal/gc/mpfloat.go).
498 if v, exact := constant.Float64Val(x); exact {
501 } else if num, denom := constant.Num(x), constant.Denom(x); num.Kind() == constant.Int {
502 // TODO(gri): add big.Rat accessor to constant.Value.
504 d := valueToRat(denom)
505 f.SetRat(n.Quo(n, d))
507 // Value too large to represent as a fraction => inaccessible.
508 // TODO(gri): add big.Float accessor to constant.Value.
509 _, ok := f.SetString(x.ExactString())
515 // mpint exports a multi-precision integer.
517 // For unsigned types, small values are written out as a single
518 // byte. Larger values are written out as a length-prefixed big-endian
519 // byte string, where the length prefix is encoded as its complement.
520 // For example, bytes 0, 1, and 2 directly represent the integer
521 // values 0, 1, and 2; while bytes 255, 254, and 253 indicate a 1-,
522 // 2-, and 3-byte big-endian string follow.
524 // Encoding for signed types use the same general approach as for
525 // unsigned types, except small values use zig-zag encoding and the
526 // bottom bit of length prefix byte for large values is reserved as a
529 // The exact boundary between small and large encodings varies
530 // according to the maximum number of bytes needed to encode a value
531 // of type typ. As a special case, 8-bit types are always encoded as a
534 // TODO(mdempsky): Is this level of complexity really worthwhile?
535 func (w *exportWriter) mpint(x *big.Int, typ types.Type) {
536 basic, ok := typ.Underlying().(*types.Basic)
538 panic(internalErrorf("unexpected type %v (%T)", typ.Underlying(), typ.Underlying()))
541 signed, maxBytes := intSize(basic)
543 negative := x.Sign() < 0
544 if !signed && negative {
545 panic(internalErrorf("negative unsigned integer; type %v, value %v", typ, x))
549 if len(b) > 0 && b[0] == 0 {
550 panic(internalErrorf("leading zeros"))
552 if uint(len(b)) > maxBytes {
553 panic(internalErrorf("bad mpint length: %d > %d (type %v, value %v)", len(b), maxBytes, typ, x))
556 maxSmall := 256 - maxBytes
558 maxSmall = 256 - 2*maxBytes
564 // Check if x can use small value encoding.
577 w.data.WriteByte(byte(ux))
582 n := 256 - uint(len(b))
584 n = 256 - 2*uint(len(b))
589 if n < maxSmall || n >= 256 {
590 panic(internalErrorf("encoding mistake: %d, %v, %v => %d", len(b), signed, negative, n))
593 w.data.WriteByte(byte(n))
597 // mpfloat exports a multi-precision floating point number.
599 // The number's value is decomposed into mantissa × 2**exponent, where
600 // mantissa is an integer. The value is written out as mantissa (as a
601 // multi-precision integer) and then the exponent, except exponent is
602 // omitted if mantissa is zero.
603 func (w *exportWriter) mpfloat(f *big.Float, typ types.Type) {
605 panic("infinite constant")
608 // Break into f = mant × 2**exp, with 0.5 <= mant < 1.
610 exp := int64(f.MantExp(&mant))
612 // Scale so that mant is an integer.
613 prec := mant.MinPrec()
614 mant.SetMantExp(&mant, int(prec))
617 manti, acc := mant.Int(nil)
618 if acc != big.Exact {
619 panic(internalErrorf("mantissa scaling failed for %f (%s)", f, acc))
622 if manti.Sign() != 0 {
627 func (w *exportWriter) bool(b bool) bool {
636 func (w *exportWriter) int64(x int64) { w.data.int64(x) }
637 func (w *exportWriter) uint64(x uint64) { w.data.uint64(x) }
638 func (w *exportWriter) string(s string) { w.uint64(w.p.stringOff(s)) }
640 func (w *exportWriter) localIdent(obj types.Object) {
641 // Anonymous parameters.
656 type intWriter struct {
660 func (w *intWriter) int64(x int64) {
661 var buf [binary.MaxVarintLen64]byte
662 n := binary.PutVarint(buf[:], x)
666 func (w *intWriter) uint64(x uint64) {
667 var buf [binary.MaxVarintLen64]byte
668 n := binary.PutUvarint(buf[:], x)
672 func assert(cond bool) {
674 panic("internal error: assertion failed")
678 // The below is copied from go/src/cmd/compile/internal/gc/syntax.go.
680 // objQueue is a FIFO queue of types.Object. The zero value of objQueue is
681 // a ready-to-use empty queue.
682 type objQueue struct {
687 // empty returns true if q contains no Nodes.
688 func (q *objQueue) empty() bool {
689 return q.head == q.tail
692 // pushTail appends n to the tail of the queue.
693 func (q *objQueue) pushTail(obj types.Object) {
694 if len(q.ring) == 0 {
695 q.ring = make([]types.Object, 16)
696 } else if q.head+len(q.ring) == q.tail {
698 nring := make([]types.Object, len(q.ring)*2)
699 // Copy the old elements.
700 part := q.ring[q.head%len(q.ring):]
701 if q.tail-q.head <= len(part) {
702 part = part[:q.tail-q.head]
705 pos := copy(nring, part)
706 copy(nring[pos:], q.ring[:q.tail%len(q.ring)])
708 q.ring, q.head, q.tail = nring, 0, q.tail-q.head
711 q.ring[q.tail%len(q.ring)] = obj
715 // popHead pops a node from the head of the queue. It panics if q is empty.
716 func (q *objQueue) popHead() types.Object {
718 panic("dequeue empty")
720 obj := q.ring[q.head%len(q.ring)]