1// Copyright 2015 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// This file is a copy of $GOROOT/src/go/internal/gcimporter/bimport.go. 6 7package gcimporter 8 9import ( 10 "encoding/binary" 11 "fmt" 12 "go/constant" 13 "go/token" 14 "go/types" 15 "sort" 16 "strconv" 17 "strings" 18 "sync" 19 "unicode" 20 "unicode/utf8" 21) 22 23type importer struct { 24 imports map[string]*types.Package 25 data []byte 26 importpath string 27 buf []byte // for reading strings 28 version int // export format version 29 30 // object lists 31 strList []string // in order of appearance 32 pathList []string // in order of appearance 33 pkgList []*types.Package // in order of appearance 34 typList []types.Type // in order of appearance 35 interfaceList []*types.Interface // for delayed completion only 36 trackAllTypes bool 37 38 // position encoding 39 posInfoFormat bool 40 prevFile string 41 prevLine int 42 fake fakeFileSet 43 44 // debugging support 45 debugFormat bool 46 read int // bytes read 47} 48 49// BImportData imports a package from the serialized package data 50// and returns the number of bytes consumed and a reference to the package. 51// If the export data version is not recognized or the format is otherwise 52// compromised, an error is returned. 53func BImportData(fset *token.FileSet, imports map[string]*types.Package, data []byte, path string) (_ int, pkg *types.Package, err error) { 54 // catch panics and return them as errors 55 const currentVersion = 6 56 version := -1 // unknown version 57 defer func() { 58 if e := recover(); e != nil { 59 // Return a (possibly nil or incomplete) package unchanged (see #16088). 60 if version > currentVersion { 61 err = fmt.Errorf("cannot import %q (%v), export data is newer version - update tool", path, e) 62 } else { 63 err = fmt.Errorf("cannot import %q (%v), possibly version skew - reinstall package", path, e) 64 } 65 } 66 }() 67 68 p := importer{ 69 imports: imports, 70 data: data, 71 importpath: path, 72 version: version, 73 strList: []string{""}, // empty string is mapped to 0 74 pathList: []string{""}, // empty string is mapped to 0 75 fake: fakeFileSet{ 76 fset: fset, 77 files: make(map[string]*token.File), 78 }, 79 } 80 81 // read version info 82 var versionstr string 83 if b := p.rawByte(); b == 'c' || b == 'd' { 84 // Go1.7 encoding; first byte encodes low-level 85 // encoding format (compact vs debug). 86 // For backward-compatibility only (avoid problems with 87 // old installed packages). Newly compiled packages use 88 // the extensible format string. 89 // TODO(gri) Remove this support eventually; after Go1.8. 90 if b == 'd' { 91 p.debugFormat = true 92 } 93 p.trackAllTypes = p.rawByte() == 'a' 94 p.posInfoFormat = p.int() != 0 95 versionstr = p.string() 96 if versionstr == "v1" { 97 version = 0 98 } 99 } else { 100 // Go1.8 extensible encoding 101 // read version string and extract version number (ignore anything after the version number) 102 versionstr = p.rawStringln(b) 103 if s := strings.SplitN(versionstr, " ", 3); len(s) >= 2 && s[0] == "version" { 104 if v, err := strconv.Atoi(s[1]); err == nil && v > 0 { 105 version = v 106 } 107 } 108 } 109 p.version = version 110 111 // read version specific flags - extend as necessary 112 switch p.version { 113 // case currentVersion: 114 // ... 115 // fallthrough 116 case currentVersion, 5, 4, 3, 2, 1: 117 p.debugFormat = p.rawStringln(p.rawByte()) == "debug" 118 p.trackAllTypes = p.int() != 0 119 p.posInfoFormat = p.int() != 0 120 case 0: 121 // Go1.7 encoding format - nothing to do here 122 default: 123 errorf("unknown bexport format version %d (%q)", p.version, versionstr) 124 } 125 126 // --- generic export data --- 127 128 // populate typList with predeclared "known" types 129 p.typList = append(p.typList, predeclared()...) 130 131 // read package data 132 pkg = p.pkg() 133 134 // read objects of phase 1 only (see cmd/compile/internal/gc/bexport.go) 135 objcount := 0 136 for { 137 tag := p.tagOrIndex() 138 if tag == endTag { 139 break 140 } 141 p.obj(tag) 142 objcount++ 143 } 144 145 // self-verification 146 if count := p.int(); count != objcount { 147 errorf("got %d objects; want %d", objcount, count) 148 } 149 150 // ignore compiler-specific import data 151 152 // complete interfaces 153 // TODO(gri) re-investigate if we still need to do this in a delayed fashion 154 for _, typ := range p.interfaceList { 155 typ.Complete() 156 } 157 158 // record all referenced packages as imports 159 list := append(([]*types.Package)(nil), p.pkgList[1:]...) 160 sort.Sort(byPath(list)) 161 pkg.SetImports(list) 162 163 // package was imported completely and without errors 164 pkg.MarkComplete() 165 166 return p.read, pkg, nil 167} 168 169func errorf(format string, args ...interface{}) { 170 panic(fmt.Sprintf(format, args...)) 171} 172 173func (p *importer) pkg() *types.Package { 174 // if the package was seen before, i is its index (>= 0) 175 i := p.tagOrIndex() 176 if i >= 0 { 177 return p.pkgList[i] 178 } 179 180 // otherwise, i is the package tag (< 0) 181 if i != packageTag { 182 errorf("unexpected package tag %d version %d", i, p.version) 183 } 184 185 // read package data 186 name := p.string() 187 var path string 188 if p.version >= 5 { 189 path = p.path() 190 } else { 191 path = p.string() 192 } 193 if p.version >= 6 { 194 p.int() // package height; unused by go/types 195 } 196 197 // we should never see an empty package name 198 if name == "" { 199 errorf("empty package name in import") 200 } 201 202 // an empty path denotes the package we are currently importing; 203 // it must be the first package we see 204 if (path == "") != (len(p.pkgList) == 0) { 205 errorf("package path %q for pkg index %d", path, len(p.pkgList)) 206 } 207 208 // if the package was imported before, use that one; otherwise create a new one 209 if path == "" { 210 path = p.importpath 211 } 212 pkg := p.imports[path] 213 if pkg == nil { 214 pkg = types.NewPackage(path, name) 215 p.imports[path] = pkg 216 } else if pkg.Name() != name { 217 errorf("conflicting names %s and %s for package %q", pkg.Name(), name, path) 218 } 219 p.pkgList = append(p.pkgList, pkg) 220 221 return pkg 222} 223 224// objTag returns the tag value for each object kind. 225func objTag(obj types.Object) int { 226 switch obj.(type) { 227 case *types.Const: 228 return constTag 229 case *types.TypeName: 230 return typeTag 231 case *types.Var: 232 return varTag 233 case *types.Func: 234 return funcTag 235 default: 236 errorf("unexpected object: %v (%T)", obj, obj) // panics 237 panic("unreachable") 238 } 239} 240 241func sameObj(a, b types.Object) bool { 242 // Because unnamed types are not canonicalized, we cannot simply compare types for 243 // (pointer) identity. 244 // Ideally we'd check equality of constant values as well, but this is good enough. 245 return objTag(a) == objTag(b) && types.Identical(a.Type(), b.Type()) 246} 247 248func (p *importer) declare(obj types.Object) { 249 pkg := obj.Pkg() 250 if alt := pkg.Scope().Insert(obj); alt != nil { 251 // This can only trigger if we import a (non-type) object a second time. 252 // Excluding type aliases, this cannot happen because 1) we only import a package 253 // once; and b) we ignore compiler-specific export data which may contain 254 // functions whose inlined function bodies refer to other functions that 255 // were already imported. 256 // However, type aliases require reexporting the original type, so we need 257 // to allow it (see also the comment in cmd/compile/internal/gc/bimport.go, 258 // method importer.obj, switch case importing functions). 259 // TODO(gri) review/update this comment once the gc compiler handles type aliases. 260 if !sameObj(obj, alt) { 261 errorf("inconsistent import:\n\t%v\npreviously imported as:\n\t%v\n", obj, alt) 262 } 263 } 264} 265 266func (p *importer) obj(tag int) { 267 switch tag { 268 case constTag: 269 pos := p.pos() 270 pkg, name := p.qualifiedName() 271 typ := p.typ(nil, nil) 272 val := p.value() 273 p.declare(types.NewConst(pos, pkg, name, typ, val)) 274 275 case aliasTag: 276 // TODO(gri) verify type alias hookup is correct 277 pos := p.pos() 278 pkg, name := p.qualifiedName() 279 typ := p.typ(nil, nil) 280 p.declare(types.NewTypeName(pos, pkg, name, typ)) 281 282 case typeTag: 283 p.typ(nil, nil) 284 285 case varTag: 286 pos := p.pos() 287 pkg, name := p.qualifiedName() 288 typ := p.typ(nil, nil) 289 p.declare(types.NewVar(pos, pkg, name, typ)) 290 291 case funcTag: 292 pos := p.pos() 293 pkg, name := p.qualifiedName() 294 params, isddd := p.paramList() 295 result, _ := p.paramList() 296 sig := types.NewSignature(nil, params, result, isddd) 297 p.declare(types.NewFunc(pos, pkg, name, sig)) 298 299 default: 300 errorf("unexpected object tag %d", tag) 301 } 302} 303 304const deltaNewFile = -64 // see cmd/compile/internal/gc/bexport.go 305 306func (p *importer) pos() token.Pos { 307 if !p.posInfoFormat { 308 return token.NoPos 309 } 310 311 file := p.prevFile 312 line := p.prevLine 313 delta := p.int() 314 line += delta 315 if p.version >= 5 { 316 if delta == deltaNewFile { 317 if n := p.int(); n >= 0 { 318 // file changed 319 file = p.path() 320 line = n 321 } 322 } 323 } else { 324 if delta == 0 { 325 if n := p.int(); n >= 0 { 326 // file changed 327 file = p.prevFile[:n] + p.string() 328 line = p.int() 329 } 330 } 331 } 332 p.prevFile = file 333 p.prevLine = line 334 335 return p.fake.pos(file, line) 336} 337 338// Synthesize a token.Pos 339type fakeFileSet struct { 340 fset *token.FileSet 341 files map[string]*token.File 342} 343 344func (s *fakeFileSet) pos(file string, line int) token.Pos { 345 // Since we don't know the set of needed file positions, we 346 // reserve maxlines positions per file. 347 const maxlines = 64 * 1024 348 f := s.files[file] 349 if f == nil { 350 f = s.fset.AddFile(file, -1, maxlines) 351 s.files[file] = f 352 // Allocate the fake linebreak indices on first use. 353 // TODO(adonovan): opt: save ~512KB using a more complex scheme? 354 fakeLinesOnce.Do(func() { 355 fakeLines = make([]int, maxlines) 356 for i := range fakeLines { 357 fakeLines[i] = i 358 } 359 }) 360 f.SetLines(fakeLines) 361 } 362 363 if line > maxlines { 364 line = 1 365 } 366 367 // Treat the file as if it contained only newlines 368 // and column=1: use the line number as the offset. 369 return f.Pos(line - 1) 370} 371 372var ( 373 fakeLines []int 374 fakeLinesOnce sync.Once 375) 376 377func (p *importer) qualifiedName() (pkg *types.Package, name string) { 378 name = p.string() 379 pkg = p.pkg() 380 return 381} 382 383func (p *importer) record(t types.Type) { 384 p.typList = append(p.typList, t) 385} 386 387// A dddSlice is a types.Type representing ...T parameters. 388// It only appears for parameter types and does not escape 389// the importer. 390type dddSlice struct { 391 elem types.Type 392} 393 394func (t *dddSlice) Underlying() types.Type { return t } 395func (t *dddSlice) String() string { return "..." + t.elem.String() } 396 397// parent is the package which declared the type; parent == nil means 398// the package currently imported. The parent package is needed for 399// exported struct fields and interface methods which don't contain 400// explicit package information in the export data. 401// 402// A non-nil tname is used as the "owner" of the result type; i.e., 403// the result type is the underlying type of tname. tname is used 404// to give interface methods a named receiver type where possible. 405func (p *importer) typ(parent *types.Package, tname *types.Named) types.Type { 406 // if the type was seen before, i is its index (>= 0) 407 i := p.tagOrIndex() 408 if i >= 0 { 409 return p.typList[i] 410 } 411 412 // otherwise, i is the type tag (< 0) 413 switch i { 414 case namedTag: 415 // read type object 416 pos := p.pos() 417 parent, name := p.qualifiedName() 418 scope := parent.Scope() 419 obj := scope.Lookup(name) 420 421 // if the object doesn't exist yet, create and insert it 422 if obj == nil { 423 obj = types.NewTypeName(pos, parent, name, nil) 424 scope.Insert(obj) 425 } 426 427 if _, ok := obj.(*types.TypeName); !ok { 428 errorf("pkg = %s, name = %s => %s", parent, name, obj) 429 } 430 431 // associate new named type with obj if it doesn't exist yet 432 t0 := types.NewNamed(obj.(*types.TypeName), nil, nil) 433 434 // but record the existing type, if any 435 tname := obj.Type().(*types.Named) // tname is either t0 or the existing type 436 p.record(tname) 437 438 // read underlying type 439 t0.SetUnderlying(p.typ(parent, t0)) 440 441 // interfaces don't have associated methods 442 if types.IsInterface(t0) { 443 return tname 444 } 445 446 // read associated methods 447 for i := p.int(); i > 0; i-- { 448 // TODO(gri) replace this with something closer to fieldName 449 pos := p.pos() 450 name := p.string() 451 if !exported(name) { 452 p.pkg() 453 } 454 455 recv, _ := p.paramList() // TODO(gri) do we need a full param list for the receiver? 456 params, isddd := p.paramList() 457 result, _ := p.paramList() 458 p.int() // go:nointerface pragma - discarded 459 460 sig := types.NewSignature(recv.At(0), params, result, isddd) 461 t0.AddMethod(types.NewFunc(pos, parent, name, sig)) 462 } 463 464 return tname 465 466 case arrayTag: 467 t := new(types.Array) 468 if p.trackAllTypes { 469 p.record(t) 470 } 471 472 n := p.int64() 473 *t = *types.NewArray(p.typ(parent, nil), n) 474 return t 475 476 case sliceTag: 477 t := new(types.Slice) 478 if p.trackAllTypes { 479 p.record(t) 480 } 481 482 *t = *types.NewSlice(p.typ(parent, nil)) 483 return t 484 485 case dddTag: 486 t := new(dddSlice) 487 if p.trackAllTypes { 488 p.record(t) 489 } 490 491 t.elem = p.typ(parent, nil) 492 return t 493 494 case structTag: 495 t := new(types.Struct) 496 if p.trackAllTypes { 497 p.record(t) 498 } 499 500 *t = *types.NewStruct(p.fieldList(parent)) 501 return t 502 503 case pointerTag: 504 t := new(types.Pointer) 505 if p.trackAllTypes { 506 p.record(t) 507 } 508 509 *t = *types.NewPointer(p.typ(parent, nil)) 510 return t 511 512 case signatureTag: 513 t := new(types.Signature) 514 if p.trackAllTypes { 515 p.record(t) 516 } 517 518 params, isddd := p.paramList() 519 result, _ := p.paramList() 520 *t = *types.NewSignature(nil, params, result, isddd) 521 return t 522 523 case interfaceTag: 524 // Create a dummy entry in the type list. This is safe because we 525 // cannot expect the interface type to appear in a cycle, as any 526 // such cycle must contain a named type which would have been 527 // first defined earlier. 528 // TODO(gri) Is this still true now that we have type aliases? 529 // See issue #23225. 530 n := len(p.typList) 531 if p.trackAllTypes { 532 p.record(nil) 533 } 534 535 var embeddeds []types.Type 536 for n := p.int(); n > 0; n-- { 537 p.pos() 538 embeddeds = append(embeddeds, p.typ(parent, nil)) 539 } 540 541 t := newInterface(p.methodList(parent, tname), embeddeds) 542 p.interfaceList = append(p.interfaceList, t) 543 if p.trackAllTypes { 544 p.typList[n] = t 545 } 546 return t 547 548 case mapTag: 549 t := new(types.Map) 550 if p.trackAllTypes { 551 p.record(t) 552 } 553 554 key := p.typ(parent, nil) 555 val := p.typ(parent, nil) 556 *t = *types.NewMap(key, val) 557 return t 558 559 case chanTag: 560 t := new(types.Chan) 561 if p.trackAllTypes { 562 p.record(t) 563 } 564 565 dir := chanDir(p.int()) 566 val := p.typ(parent, nil) 567 *t = *types.NewChan(dir, val) 568 return t 569 570 default: 571 errorf("unexpected type tag %d", i) // panics 572 panic("unreachable") 573 } 574} 575 576func chanDir(d int) types.ChanDir { 577 // tag values must match the constants in cmd/compile/internal/gc/go.go 578 switch d { 579 case 1 /* Crecv */ : 580 return types.RecvOnly 581 case 2 /* Csend */ : 582 return types.SendOnly 583 case 3 /* Cboth */ : 584 return types.SendRecv 585 default: 586 errorf("unexpected channel dir %d", d) 587 return 0 588 } 589} 590 591func (p *importer) fieldList(parent *types.Package) (fields []*types.Var, tags []string) { 592 if n := p.int(); n > 0 { 593 fields = make([]*types.Var, n) 594 tags = make([]string, n) 595 for i := range fields { 596 fields[i], tags[i] = p.field(parent) 597 } 598 } 599 return 600} 601 602func (p *importer) field(parent *types.Package) (*types.Var, string) { 603 pos := p.pos() 604 pkg, name, alias := p.fieldName(parent) 605 typ := p.typ(parent, nil) 606 tag := p.string() 607 608 anonymous := false 609 if name == "" { 610 // anonymous field - typ must be T or *T and T must be a type name 611 switch typ := deref(typ).(type) { 612 case *types.Basic: // basic types are named types 613 pkg = nil // // objects defined in Universe scope have no package 614 name = typ.Name() 615 case *types.Named: 616 name = typ.Obj().Name() 617 default: 618 errorf("named base type expected") 619 } 620 anonymous = true 621 } else if alias { 622 // anonymous field: we have an explicit name because it's an alias 623 anonymous = true 624 } 625 626 return types.NewField(pos, pkg, name, typ, anonymous), tag 627} 628 629func (p *importer) methodList(parent *types.Package, baseType *types.Named) (methods []*types.Func) { 630 if n := p.int(); n > 0 { 631 methods = make([]*types.Func, n) 632 for i := range methods { 633 methods[i] = p.method(parent, baseType) 634 } 635 } 636 return 637} 638 639func (p *importer) method(parent *types.Package, baseType *types.Named) *types.Func { 640 pos := p.pos() 641 pkg, name, _ := p.fieldName(parent) 642 // If we don't have a baseType, use a nil receiver. 643 // A receiver using the actual interface type (which 644 // we don't know yet) will be filled in when we call 645 // types.Interface.Complete. 646 var recv *types.Var 647 if baseType != nil { 648 recv = types.NewVar(token.NoPos, parent, "", baseType) 649 } 650 params, isddd := p.paramList() 651 result, _ := p.paramList() 652 sig := types.NewSignature(recv, params, result, isddd) 653 return types.NewFunc(pos, pkg, name, sig) 654} 655 656func (p *importer) fieldName(parent *types.Package) (pkg *types.Package, name string, alias bool) { 657 name = p.string() 658 pkg = parent 659 if pkg == nil { 660 // use the imported package instead 661 pkg = p.pkgList[0] 662 } 663 if p.version == 0 && name == "_" { 664 // version 0 didn't export a package for _ fields 665 return 666 } 667 switch name { 668 case "": 669 // 1) field name matches base type name and is exported: nothing to do 670 case "?": 671 // 2) field name matches base type name and is not exported: need package 672 name = "" 673 pkg = p.pkg() 674 case "@": 675 // 3) field name doesn't match type name (alias) 676 name = p.string() 677 alias = true 678 fallthrough 679 default: 680 if !exported(name) { 681 pkg = p.pkg() 682 } 683 } 684 return 685} 686 687func (p *importer) paramList() (*types.Tuple, bool) { 688 n := p.int() 689 if n == 0 { 690 return nil, false 691 } 692 // negative length indicates unnamed parameters 693 named := true 694 if n < 0 { 695 n = -n 696 named = false 697 } 698 // n > 0 699 params := make([]*types.Var, n) 700 isddd := false 701 for i := range params { 702 params[i], isddd = p.param(named) 703 } 704 return types.NewTuple(params...), isddd 705} 706 707func (p *importer) param(named bool) (*types.Var, bool) { 708 t := p.typ(nil, nil) 709 td, isddd := t.(*dddSlice) 710 if isddd { 711 t = types.NewSlice(td.elem) 712 } 713 714 var pkg *types.Package 715 var name string 716 if named { 717 name = p.string() 718 if name == "" { 719 errorf("expected named parameter") 720 } 721 if name != "_" { 722 pkg = p.pkg() 723 } 724 if i := strings.Index(name, "·"); i > 0 { 725 name = name[:i] // cut off gc-specific parameter numbering 726 } 727 } 728 729 // read and discard compiler-specific info 730 p.string() 731 732 return types.NewVar(token.NoPos, pkg, name, t), isddd 733} 734 735func exported(name string) bool { 736 ch, _ := utf8.DecodeRuneInString(name) 737 return unicode.IsUpper(ch) 738} 739 740func (p *importer) value() constant.Value { 741 switch tag := p.tagOrIndex(); tag { 742 case falseTag: 743 return constant.MakeBool(false) 744 case trueTag: 745 return constant.MakeBool(true) 746 case int64Tag: 747 return constant.MakeInt64(p.int64()) 748 case floatTag: 749 return p.float() 750 case complexTag: 751 re := p.float() 752 im := p.float() 753 return constant.BinaryOp(re, token.ADD, constant.MakeImag(im)) 754 case stringTag: 755 return constant.MakeString(p.string()) 756 case unknownTag: 757 return constant.MakeUnknown() 758 default: 759 errorf("unexpected value tag %d", tag) // panics 760 panic("unreachable") 761 } 762} 763 764func (p *importer) float() constant.Value { 765 sign := p.int() 766 if sign == 0 { 767 return constant.MakeInt64(0) 768 } 769 770 exp := p.int() 771 mant := []byte(p.string()) // big endian 772 773 // remove leading 0's if any 774 for len(mant) > 0 && mant[0] == 0 { 775 mant = mant[1:] 776 } 777 778 // convert to little endian 779 // TODO(gri) go/constant should have a more direct conversion function 780 // (e.g., once it supports a big.Float based implementation) 781 for i, j := 0, len(mant)-1; i < j; i, j = i+1, j-1 { 782 mant[i], mant[j] = mant[j], mant[i] 783 } 784 785 // adjust exponent (constant.MakeFromBytes creates an integer value, 786 // but mant represents the mantissa bits such that 0.5 <= mant < 1.0) 787 exp -= len(mant) << 3 788 if len(mant) > 0 { 789 for msd := mant[len(mant)-1]; msd&0x80 == 0; msd <<= 1 { 790 exp++ 791 } 792 } 793 794 x := constant.MakeFromBytes(mant) 795 switch { 796 case exp < 0: 797 d := constant.Shift(constant.MakeInt64(1), token.SHL, uint(-exp)) 798 x = constant.BinaryOp(x, token.QUO, d) 799 case exp > 0: 800 x = constant.Shift(x, token.SHL, uint(exp)) 801 } 802 803 if sign < 0 { 804 x = constant.UnaryOp(token.SUB, x, 0) 805 } 806 return x 807} 808 809// ---------------------------------------------------------------------------- 810// Low-level decoders 811 812func (p *importer) tagOrIndex() int { 813 if p.debugFormat { 814 p.marker('t') 815 } 816 817 return int(p.rawInt64()) 818} 819 820func (p *importer) int() int { 821 x := p.int64() 822 if int64(int(x)) != x { 823 errorf("exported integer too large") 824 } 825 return int(x) 826} 827 828func (p *importer) int64() int64 { 829 if p.debugFormat { 830 p.marker('i') 831 } 832 833 return p.rawInt64() 834} 835 836func (p *importer) path() string { 837 if p.debugFormat { 838 p.marker('p') 839 } 840 // if the path was seen before, i is its index (>= 0) 841 // (the empty string is at index 0) 842 i := p.rawInt64() 843 if i >= 0 { 844 return p.pathList[i] 845 } 846 // otherwise, i is the negative path length (< 0) 847 a := make([]string, -i) 848 for n := range a { 849 a[n] = p.string() 850 } 851 s := strings.Join(a, "/") 852 p.pathList = append(p.pathList, s) 853 return s 854} 855 856func (p *importer) string() string { 857 if p.debugFormat { 858 p.marker('s') 859 } 860 // if the string was seen before, i is its index (>= 0) 861 // (the empty string is at index 0) 862 i := p.rawInt64() 863 if i >= 0 { 864 return p.strList[i] 865 } 866 // otherwise, i is the negative string length (< 0) 867 if n := int(-i); n <= cap(p.buf) { 868 p.buf = p.buf[:n] 869 } else { 870 p.buf = make([]byte, n) 871 } 872 for i := range p.buf { 873 p.buf[i] = p.rawByte() 874 } 875 s := string(p.buf) 876 p.strList = append(p.strList, s) 877 return s 878} 879 880func (p *importer) marker(want byte) { 881 if got := p.rawByte(); got != want { 882 errorf("incorrect marker: got %c; want %c (pos = %d)", got, want, p.read) 883 } 884 885 pos := p.read 886 if n := int(p.rawInt64()); n != pos { 887 errorf("incorrect position: got %d; want %d", n, pos) 888 } 889} 890 891// rawInt64 should only be used by low-level decoders. 892func (p *importer) rawInt64() int64 { 893 i, err := binary.ReadVarint(p) 894 if err != nil { 895 errorf("read error: %v", err) 896 } 897 return i 898} 899 900// rawStringln should only be used to read the initial version string. 901func (p *importer) rawStringln(b byte) string { 902 p.buf = p.buf[:0] 903 for b != '\n' { 904 p.buf = append(p.buf, b) 905 b = p.rawByte() 906 } 907 return string(p.buf) 908} 909 910// needed for binary.ReadVarint in rawInt64 911func (p *importer) ReadByte() (byte, error) { 912 return p.rawByte(), nil 913} 914 915// byte is the bottleneck interface for reading p.data. 916// It unescapes '|' 'S' to '$' and '|' '|' to '|'. 917// rawByte should only be used by low-level decoders. 918func (p *importer) rawByte() byte { 919 b := p.data[0] 920 r := 1 921 if b == '|' { 922 b = p.data[1] 923 r = 2 924 switch b { 925 case 'S': 926 b = '$' 927 case '|': 928 // nothing to do 929 default: 930 errorf("unexpected escape sequence in export data") 931 } 932 } 933 p.data = p.data[r:] 934 p.read += r 935 return b 936 937} 938 939// ---------------------------------------------------------------------------- 940// Export format 941 942// Tags. Must be < 0. 943const ( 944 // Objects 945 packageTag = -(iota + 1) 946 constTag 947 typeTag 948 varTag 949 funcTag 950 endTag 951 952 // Types 953 namedTag 954 arrayTag 955 sliceTag 956 dddTag 957 structTag 958 pointerTag 959 signatureTag 960 interfaceTag 961 mapTag 962 chanTag 963 964 // Values 965 falseTag 966 trueTag 967 int64Tag 968 floatTag 969 fractionTag // not used by gc 970 complexTag 971 stringTag 972 nilTag // only used by gc (appears in exported inlined function bodies) 973 unknownTag // not used by gc (only appears in packages with errors) 974 975 // Type aliases 976 aliasTag 977) 978 979var predecl []types.Type // initialized lazily 980 981func predeclared() []types.Type { 982 if predecl == nil { 983 // initialize lazily to be sure that all 984 // elements have been initialized before 985 predecl = []types.Type{ // basic types 986 types.Typ[types.Bool], 987 types.Typ[types.Int], 988 types.Typ[types.Int8], 989 types.Typ[types.Int16], 990 types.Typ[types.Int32], 991 types.Typ[types.Int64], 992 types.Typ[types.Uint], 993 types.Typ[types.Uint8], 994 types.Typ[types.Uint16], 995 types.Typ[types.Uint32], 996 types.Typ[types.Uint64], 997 types.Typ[types.Uintptr], 998 types.Typ[types.Float32], 999 types.Typ[types.Float64], 1000 types.Typ[types.Complex64], 1001 types.Typ[types.Complex128], 1002 types.Typ[types.String], 1003 1004 // basic type aliases 1005 types.Universe.Lookup("byte").Type(), 1006 types.Universe.Lookup("rune").Type(), 1007 1008 // error 1009 types.Universe.Lookup("error").Type(), 1010 1011 // untyped types 1012 types.Typ[types.UntypedBool], 1013 types.Typ[types.UntypedInt], 1014 types.Typ[types.UntypedRune], 1015 types.Typ[types.UntypedFloat], 1016 types.Typ[types.UntypedComplex], 1017 types.Typ[types.UntypedString], 1018 types.Typ[types.UntypedNil], 1019 1020 // package unsafe 1021 types.Typ[types.UnsafePointer], 1022 1023 // invalid type 1024 types.Typ[types.Invalid], // only appears in packages with errors 1025 1026 // used internally by gc; never used by this package or in .a files 1027 anyType{}, 1028 } 1029 } 1030 return predecl 1031} 1032 1033type anyType struct{} 1034 1035func (t anyType) Underlying() types.Type { return t } 1036func (t anyType) String() string { return "any" } 1037