1 // Copyright 2018 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 package import.
6 // See cmd/compile/internal/gc/iexport.go for the export data format.
8 // This file is a copy of $GOROOT/src/go/internal/gcimporter/iimport.go.
23 type intReader struct {
28 func (r *intReader) int64() int64 {
29 i, err := binary.ReadVarint(r.Reader)
31 errorf("import %q: read varint error: %v", r.path, err)
36 func (r *intReader) uint64() uint64 {
37 i, err := binary.ReadUvarint(r.Reader)
39 errorf("import %q: read varint error: %v", r.path, err)
44 const predeclReserved = 32
50 definedType itag = iota
61 // IImportData imports a package from the serialized package data
62 // and returns the number of bytes consumed and a reference to the package.
63 // If the export data version is not recognized or the format is otherwise
64 // compromised, an error is returned.
65 func IImportData(fset *token.FileSet, imports map[string]*types.Package, data []byte, path string) (_ int, pkg *types.Package, err error) {
66 const currentVersion = 1
69 if e := recover(); e != nil {
70 if version > currentVersion {
71 err = fmt.Errorf("cannot import %q (%v), export data is newer version - update tool", path, e)
73 err = fmt.Errorf("cannot import %q (%v), possibly version skew - reinstall package", path, e)
78 r := &intReader{bytes.NewReader(data), path}
80 version = int64(r.uint64())
82 case currentVersion, 0:
84 errorf("unknown iexport format version %d", version)
87 sLen := int64(r.uint64())
88 dLen := int64(r.uint64())
90 whence, _ := r.Seek(0, io.SeekCurrent)
91 stringData := data[whence : whence+sLen]
92 declData := data[whence+sLen : whence+sLen+dLen]
93 r.Seek(sLen+dLen, io.SeekCurrent)
97 version: int(version),
99 stringData: stringData,
100 stringCache: make(map[uint64]string),
101 pkgCache: make(map[uint64]*types.Package),
104 pkgIndex: make(map[*types.Package]map[string]uint64),
105 typCache: make(map[uint64]types.Type),
109 files: make(map[string]*token.File),
113 for i, pt := range predeclared() {
114 p.typCache[uint64(i)] = pt
117 pkgList := make([]*types.Package, r.uint64())
118 for i := range pkgList {
119 pkgPathOff := r.uint64()
120 pkgPath := p.stringAt(pkgPathOff)
121 pkgName := p.stringAt(r.uint64())
122 _ = r.uint64() // package height; unused by go/types
127 pkg := imports[pkgPath]
129 pkg = types.NewPackage(pkgPath, pkgName)
130 imports[pkgPath] = pkg
131 } else if pkg.Name() != pkgName {
132 errorf("conflicting names %s and %s for package %q", pkg.Name(), pkgName, path)
135 p.pkgCache[pkgPathOff] = pkg
137 nameIndex := make(map[string]uint64)
138 for nSyms := r.uint64(); nSyms > 0; nSyms-- {
139 name := p.stringAt(r.uint64())
140 nameIndex[name] = r.uint64()
143 p.pkgIndex[pkg] = nameIndex
146 if len(pkgList) == 0 {
147 errorf("no packages found for %s", path)
151 names := make([]string, 0, len(p.pkgIndex[p.ipkg]))
152 for name := range p.pkgIndex[p.ipkg] {
153 names = append(names, name)
156 for _, name := range names {
157 p.doDecl(p.ipkg, name)
160 for _, typ := range p.interfaceList {
164 // record all referenced packages as imports
165 list := append(([]*types.Package)(nil), pkgList[1:]...)
166 sort.Sort(byPath(list))
167 p.ipkg.SetImports(list)
169 // package was imported completely and without errors
170 p.ipkg.MarkComplete()
172 consumed, _ := r.Seek(0, io.SeekCurrent)
173 return int(consumed), p.ipkg, nil
176 type iimporter struct {
182 stringCache map[uint64]string
183 pkgCache map[uint64]*types.Package
186 pkgIndex map[*types.Package]map[string]uint64
187 typCache map[uint64]types.Type
190 interfaceList []*types.Interface
193 func (p *iimporter) doDecl(pkg *types.Package, name string) {
194 // See if we've already imported this declaration.
195 if obj := pkg.Scope().Lookup(name); obj != nil {
199 off, ok := p.pkgIndex[pkg][name]
201 errorf("%v.%v not in index", pkg, name)
204 r := &importReader{p: p, currPkg: pkg}
205 r.declReader.Reset(p.declData[off:])
210 func (p *iimporter) stringAt(off uint64) string {
211 if s, ok := p.stringCache[off]; ok {
215 slen, n := binary.Uvarint(p.stringData[off:])
217 errorf("varint failed")
219 spos := off + uint64(n)
220 s := string(p.stringData[spos : spos+slen])
221 p.stringCache[off] = s
225 func (p *iimporter) pkgAt(off uint64) *types.Package {
226 if pkg, ok := p.pkgCache[off]; ok {
229 path := p.stringAt(off)
233 errorf("missing package %q in %q", path, p.ipath)
237 func (p *iimporter) typAt(off uint64, base *types.Named) types.Type {
238 if t, ok := p.typCache[off]; ok && (base == nil || !isInterface(t)) {
242 if off < predeclReserved {
243 errorf("predeclared type missing from cache: %v", off)
246 r := &importReader{p: p}
247 r.declReader.Reset(p.declData[off-predeclReserved:])
250 if base == nil || !isInterface(t) {
256 type importReader struct {
258 declReader bytes.Reader
259 currPkg *types.Package
265 func (r *importReader) obj(name string) {
273 r.declare(types.NewTypeName(pos, r.currPkg, name, typ))
276 typ, val := r.value()
278 r.declare(types.NewConst(pos, r.currPkg, name, typ, val))
281 sig := r.signature(nil)
283 r.declare(types.NewFunc(pos, r.currPkg, name, sig))
286 // Types can be recursive. We need to setup a stub
287 // declaration before recursing.
288 obj := types.NewTypeName(pos, r.currPkg, name, nil)
289 named := types.NewNamed(obj, nil, nil)
292 underlying := r.p.typAt(r.uint64(), named).Underlying()
293 named.SetUnderlying(underlying)
295 if !isInterface(underlying) {
296 for n := r.uint64(); n > 0; n-- {
300 msig := r.signature(recv)
302 named.AddMethod(types.NewFunc(mpos, r.currPkg, mname, msig))
309 r.declare(types.NewVar(pos, r.currPkg, name, typ))
312 errorf("unexpected tag: %v", tag)
316 func (r *importReader) declare(obj types.Object) {
317 obj.Pkg().Scope().Insert(obj)
320 func (r *importReader) value() (typ types.Type, val constant.Value) {
323 switch b := typ.Underlying().(*types.Basic); b.Info() & types.IsConstType {
324 case types.IsBoolean:
325 val = constant.MakeBool(r.bool())
328 val = constant.MakeString(r.string())
330 case types.IsInteger:
336 case types.IsComplex:
339 val = constant.BinaryOp(re, token.ADD, constant.MakeImag(im))
342 if b.Kind() == types.Invalid {
343 val = constant.MakeUnknown()
346 errorf("unexpected type %v", typ) // panics
353 func intSize(b *types.Basic) (signed bool, maxBytes uint) {
354 if (b.Info() & types.IsUntyped) != 0 {
359 case types.Float32, types.Complex64:
361 case types.Float64, types.Complex128:
365 signed = (b.Info() & types.IsUnsigned) == 0
367 case types.Int8, types.Uint8:
369 case types.Int16, types.Uint16:
371 case types.Int32, types.Uint32:
380 func (r *importReader) mpint(b *types.Basic) constant.Value {
381 signed, maxBytes := intSize(b)
383 maxSmall := 256 - maxBytes
385 maxSmall = 256 - 2*maxBytes
391 n, _ := r.declReader.ReadByte()
392 if uint(n) < maxSmall {
400 return constant.MakeInt64(v)
407 if v < 1 || uint(v) > maxBytes {
408 errorf("weird decoding: %v, %v => %v", n, signed, v)
411 buf := make([]byte, v)
412 io.ReadFull(&r.declReader, buf)
414 // convert to little endian
415 // TODO(gri) go/constant should have a more direct conversion function
416 // (e.g., once it supports a big.Float based implementation)
417 for i, j := 0, len(buf)-1; i < j; i, j = i+1, j-1 {
418 buf[i], buf[j] = buf[j], buf[i]
421 x := constant.MakeFromBytes(buf)
422 if signed && n&1 != 0 {
423 x = constant.UnaryOp(token.SUB, x, 0)
428 func (r *importReader) mpfloat(b *types.Basic) constant.Value {
430 if constant.Sign(x) == 0 {
437 x = constant.Shift(x, token.SHL, uint(exp))
439 d := constant.Shift(constant.MakeInt64(1), token.SHL, uint(-exp))
440 x = constant.BinaryOp(x, token.QUO, d)
445 func (r *importReader) ident() string {
449 func (r *importReader) qualifiedIdent() (*types.Package, string) {
455 func (r *importReader) pos() token.Pos {
456 if r.p.version >= 1 {
462 if r.prevFile == "" && r.prevLine == 0 && r.prevColumn == 0 {
465 return r.p.fake.pos(r.prevFile, int(r.prevLine), int(r.prevColumn))
468 func (r *importReader) posv0() {
470 if delta != deltaNewFile {
472 } else if l := r.int64(); l == -1 {
473 r.prevLine += deltaNewFile
475 r.prevFile = r.string()
480 func (r *importReader) posv1() {
482 r.prevColumn += delta >> 1
485 r.prevLine += delta >> 1
487 r.prevFile = r.string()
492 func (r *importReader) typ() types.Type {
493 return r.p.typAt(r.uint64(), nil)
496 func isInterface(t types.Type) bool {
497 _, ok := t.(*types.Interface)
501 func (r *importReader) pkg() *types.Package { return r.p.pkgAt(r.uint64()) }
502 func (r *importReader) string() string { return r.p.stringAt(r.uint64()) }
504 func (r *importReader) doType(base *types.Named) types.Type {
505 switch k := r.kind(); k {
507 errorf("unexpected kind tag in %q: %v", r.p.ipath, k)
511 pkg, name := r.qualifiedIdent()
512 r.p.doDecl(pkg, name)
513 return pkg.Scope().Lookup(name).(*types.TypeName).Type()
515 return types.NewPointer(r.typ())
517 return types.NewSlice(r.typ())
520 return types.NewArray(r.typ(), int64(n))
522 dir := chanDir(int(r.uint64()))
523 return types.NewChan(dir, r.typ())
525 return types.NewMap(r.typ(), r.typ())
528 return r.signature(nil)
533 fields := make([]*types.Var, r.uint64())
534 tags := make([]string, len(fields))
535 for i := range fields {
542 fields[i] = types.NewField(fpos, r.currPkg, fname, ftyp, emb)
545 return types.NewStruct(fields, tags)
550 embeddeds := make([]types.Type, r.uint64())
551 for i := range embeddeds {
553 embeddeds[i] = r.typ()
556 methods := make([]*types.Func, r.uint64())
557 for i := range methods {
561 // TODO(mdempsky): Matches bimport.go, but I
562 // don't agree with this.
565 recv = types.NewVar(token.NoPos, r.currPkg, "", base)
568 msig := r.signature(recv)
569 methods[i] = types.NewFunc(mpos, r.currPkg, mname, msig)
572 typ := newInterface(methods, embeddeds)
573 r.p.interfaceList = append(r.p.interfaceList, typ)
578 func (r *importReader) kind() itag {
579 return itag(r.uint64())
582 func (r *importReader) signature(recv *types.Var) *types.Signature {
583 params := r.paramList()
584 results := r.paramList()
585 variadic := params.Len() > 0 && r.bool()
586 return types.NewSignature(recv, params, results, variadic)
589 func (r *importReader) paramList() *types.Tuple {
590 xs := make([]*types.Var, r.uint64())
594 return types.NewTuple(xs...)
597 func (r *importReader) param() *types.Var {
601 return types.NewParam(pos, r.currPkg, name, typ)
604 func (r *importReader) bool() bool {
605 return r.uint64() != 0
608 func (r *importReader) int64() int64 {
609 n, err := binary.ReadVarint(&r.declReader)
611 errorf("readVarint: %v", err)
616 func (r *importReader) uint64() uint64 {
617 n, err := binary.ReadUvarint(&r.declReader)
619 errorf("readUvarint: %v", err)
624 func (r *importReader) byte() byte {
625 x, err := r.declReader.ReadByte()
627 errorf("declReader.ReadByte: %v", err)