github.com/dannin/go@v0.0.0-20161031215817-d35dfd405eaa/src/go/internal/gcimporter/bimport.go (about)

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