github.com/rakyll/go@v0.0.0-20170216000551-64c02460d703/src/cmd/compile/internal/gc/subr.go (about)

     1  // Copyright 2009 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 gc
     6  
     7  import (
     8  	"bytes"
     9  	"cmd/internal/obj"
    10  	"cmd/internal/src"
    11  	"crypto/md5"
    12  	"encoding/binary"
    13  	"fmt"
    14  	"os"
    15  	"runtime/debug"
    16  	"sort"
    17  	"strconv"
    18  	"strings"
    19  	"unicode"
    20  	"unicode/utf8"
    21  )
    22  
    23  type Error struct {
    24  	pos src.XPos
    25  	msg string
    26  }
    27  
    28  var errors []Error
    29  
    30  func errorexit() {
    31  	flusherrors()
    32  	if outfile != "" {
    33  		os.Remove(outfile)
    34  	}
    35  	os.Exit(2)
    36  }
    37  
    38  func adderrorname(n *Node) {
    39  	if n.Op != ODOT {
    40  		return
    41  	}
    42  	old := fmt.Sprintf("%v: undefined: %v\n", n.Line(), n.Left)
    43  	if len(errors) > 0 && errors[len(errors)-1].pos.Line() == n.Pos.Line() && errors[len(errors)-1].msg == old {
    44  		errors[len(errors)-1].msg = fmt.Sprintf("%v: undefined: %v in %v\n", n.Line(), n.Left, n)
    45  	}
    46  }
    47  
    48  func adderr(pos src.XPos, format string, args ...interface{}) {
    49  	errors = append(errors, Error{
    50  		pos: pos,
    51  		msg: fmt.Sprintf("%v: %s\n", linestr(pos), fmt.Sprintf(format, args...)),
    52  	})
    53  }
    54  
    55  // byPos sorts errors by source position.
    56  type byPos []Error
    57  
    58  func (x byPos) Len() int           { return len(x) }
    59  func (x byPos) Less(i, j int) bool { return x[i].pos.Before(x[j].pos) }
    60  func (x byPos) Swap(i, j int)      { x[i], x[j] = x[j], x[i] }
    61  
    62  // flusherrors sorts errors seen so far by line number, prints them to stdout,
    63  // and empties the errors array.
    64  func flusherrors() {
    65  	Ctxt.Bso.Flush()
    66  	if len(errors) == 0 {
    67  		return
    68  	}
    69  	sort.Stable(byPos(errors))
    70  	for i := 0; i < len(errors); i++ {
    71  		if i == 0 || errors[i].msg != errors[i-1].msg {
    72  			fmt.Printf("%s", errors[i].msg)
    73  		}
    74  	}
    75  	errors = errors[:0]
    76  }
    77  
    78  func hcrash() {
    79  	if Debug['h'] != 0 {
    80  		flusherrors()
    81  		if outfile != "" {
    82  			os.Remove(outfile)
    83  		}
    84  		var x *int
    85  		*x = 0
    86  	}
    87  }
    88  
    89  func linestr(pos src.XPos) string {
    90  	return Ctxt.PosTable.Pos(pos).String()
    91  }
    92  
    93  // lasterror keeps track of the most recently issued error.
    94  // It is used to avoid multiple error messages on the same
    95  // line.
    96  var lasterror struct {
    97  	syntax src.XPos // source position of last syntax error
    98  	other  src.XPos // source position of last non-syntax error
    99  	msg    string   // error message of last non-syntax error
   100  }
   101  
   102  // sameline reports whether two positions a, b are on the same line.
   103  func sameline(a, b src.XPos) bool {
   104  	p := Ctxt.PosTable.Pos(a)
   105  	q := Ctxt.PosTable.Pos(b)
   106  	return p.Base() == q.Base() && p.Line() == q.Line()
   107  }
   108  
   109  func yyerrorl(pos src.XPos, format string, args ...interface{}) {
   110  	msg := fmt.Sprintf(format, args...)
   111  
   112  	if strings.HasPrefix(msg, "syntax error") {
   113  		nsyntaxerrors++
   114  		// only one syntax error per line, no matter what error
   115  		if sameline(lasterror.syntax, pos) {
   116  			return
   117  		}
   118  		lasterror.syntax = pos
   119  	} else {
   120  		// only one of multiple equal non-syntax errors per line
   121  		// (flusherrors shows only one of them, so we filter them
   122  		// here as best as we can (they may not appear in order)
   123  		// so that we don't count them here and exit early, and
   124  		// then have nothing to show for.)
   125  		if sameline(lasterror.other, pos) && lasterror.msg == msg {
   126  			return
   127  		}
   128  		lasterror.other = pos
   129  		lasterror.msg = msg
   130  	}
   131  
   132  	adderr(pos, "%s", msg)
   133  
   134  	hcrash()
   135  	nerrors++
   136  	if nsavederrors+nerrors >= 10 && Debug['e'] == 0 {
   137  		flusherrors()
   138  		fmt.Printf("%v: too many errors\n", linestr(pos))
   139  		errorexit()
   140  	}
   141  }
   142  
   143  func yyerror(format string, args ...interface{}) {
   144  	yyerrorl(lineno, format, args...)
   145  }
   146  
   147  func Warn(fmt_ string, args ...interface{}) {
   148  	adderr(lineno, fmt_, args...)
   149  
   150  	hcrash()
   151  }
   152  
   153  func Warnl(line src.XPos, fmt_ string, args ...interface{}) {
   154  	adderr(line, fmt_, args...)
   155  	if Debug['m'] != 0 {
   156  		flusherrors()
   157  	}
   158  }
   159  
   160  func Fatalf(fmt_ string, args ...interface{}) {
   161  	flusherrors()
   162  
   163  	fmt.Printf("%v: internal compiler error: ", linestr(lineno))
   164  	fmt.Printf(fmt_, args...)
   165  	fmt.Printf("\n")
   166  
   167  	// If this is a released compiler version, ask for a bug report.
   168  	if strings.HasPrefix(obj.Version, "release") {
   169  		fmt.Printf("\n")
   170  		fmt.Printf("Please file a bug report including a short program that triggers the error.\n")
   171  		fmt.Printf("https://golang.org/issue/new\n")
   172  	} else {
   173  		// Not a release; dump a stack trace, too.
   174  		fmt.Println()
   175  		os.Stdout.Write(debug.Stack())
   176  		fmt.Println()
   177  	}
   178  
   179  	hcrash()
   180  	errorexit()
   181  }
   182  
   183  func setlineno(n *Node) src.XPos {
   184  	lno := lineno
   185  	if n != nil {
   186  		switch n.Op {
   187  		case ONAME, OPACK:
   188  			break
   189  
   190  		case OLITERAL, OTYPE:
   191  			if n.Sym != nil {
   192  				break
   193  			}
   194  			fallthrough
   195  
   196  		default:
   197  			lineno = n.Pos
   198  			if !lineno.IsKnown() {
   199  				if Debug['K'] != 0 {
   200  					Warn("setlineno: unknown position (line 0)")
   201  				}
   202  				lineno = lno
   203  			}
   204  		}
   205  	}
   206  
   207  	return lno
   208  }
   209  
   210  func lookup(name string) *Sym {
   211  	return localpkg.Lookup(name)
   212  }
   213  
   214  func lookupf(format string, a ...interface{}) *Sym {
   215  	return lookup(fmt.Sprintf(format, a...))
   216  }
   217  
   218  func lookupBytes(name []byte) *Sym {
   219  	return localpkg.LookupBytes(name)
   220  }
   221  
   222  // lookupN looks up the symbol starting with prefix and ending with
   223  // the decimal n. If prefix is too long, lookupN panics.
   224  func lookupN(prefix string, n int) *Sym {
   225  	var buf [20]byte // plenty long enough for all current users
   226  	copy(buf[:], prefix)
   227  	b := strconv.AppendInt(buf[:len(prefix)], int64(n), 10)
   228  	return lookupBytes(b)
   229  }
   230  
   231  // autolabel generates a new Name node for use with
   232  // an automatically generated label.
   233  // prefix is a short mnemonic (e.g. ".s" for switch)
   234  // to help with debugging.
   235  // It should begin with "." to avoid conflicts with
   236  // user labels.
   237  func autolabel(prefix string) *Node {
   238  	if prefix[0] != '.' {
   239  		Fatalf("autolabel prefix must start with '.', have %q", prefix)
   240  	}
   241  	fn := Curfn
   242  	if Curfn == nil {
   243  		Fatalf("autolabel outside function")
   244  	}
   245  	n := fn.Func.Label
   246  	fn.Func.Label++
   247  	return newname(lookupN(prefix, int(n)))
   248  }
   249  
   250  var initSyms []*Sym
   251  
   252  var nopkg = &Pkg{
   253  	Syms: make(map[string]*Sym),
   254  }
   255  
   256  func (pkg *Pkg) Lookup(name string) *Sym {
   257  	if pkg == nil {
   258  		pkg = nopkg
   259  	}
   260  	if s := pkg.Syms[name]; s != nil {
   261  		return s
   262  	}
   263  
   264  	s := &Sym{
   265  		Name: name,
   266  		Pkg:  pkg,
   267  	}
   268  	if name == "init" {
   269  		initSyms = append(initSyms, s)
   270  	}
   271  	pkg.Syms[name] = s
   272  	return s
   273  }
   274  
   275  func (pkg *Pkg) LookupBytes(name []byte) *Sym {
   276  	if pkg == nil {
   277  		pkg = nopkg
   278  	}
   279  	if s := pkg.Syms[string(name)]; s != nil {
   280  		return s
   281  	}
   282  	str := internString(name)
   283  	return pkg.Lookup(str)
   284  }
   285  
   286  func Pkglookup(name string, pkg *Pkg) *Sym {
   287  	return pkg.Lookup(name)
   288  }
   289  
   290  func restrictlookup(name string, pkg *Pkg) *Sym {
   291  	if !exportname(name) && pkg != localpkg {
   292  		yyerror("cannot refer to unexported name %s.%s", pkg.Name, name)
   293  	}
   294  	return Pkglookup(name, pkg)
   295  }
   296  
   297  // find all the exported symbols in package opkg
   298  // and make them available in the current package
   299  func importdot(opkg *Pkg, pack *Node) {
   300  	var s1 *Sym
   301  	var pkgerror string
   302  
   303  	n := 0
   304  	for _, s := range opkg.Syms {
   305  		if s.Def == nil {
   306  			continue
   307  		}
   308  		if !exportname(s.Name) || strings.ContainsRune(s.Name, 0xb7) { // 0xb7 = center dot
   309  			continue
   310  		}
   311  		s1 = lookup(s.Name)
   312  		if s1.Def != nil {
   313  			pkgerror = fmt.Sprintf("during import %q", opkg.Path)
   314  			redeclare(s1, pkgerror)
   315  			continue
   316  		}
   317  
   318  		s1.Def = s.Def
   319  		s1.Block = s.Block
   320  		if s1.Def.Name == nil {
   321  			Dump("s1def", s1.Def)
   322  			Fatalf("missing Name")
   323  		}
   324  		s1.Def.Name.Pack = pack
   325  		s1.Origpkg = opkg
   326  		n++
   327  	}
   328  
   329  	if n == 0 {
   330  		// can't possibly be used - there were no symbols
   331  		yyerrorl(pack.Pos, "imported and not used: %q", opkg.Path)
   332  	}
   333  }
   334  
   335  func nod(op Op, nleft *Node, nright *Node) *Node {
   336  	var n *Node
   337  	switch op {
   338  	case OCLOSURE, ODCLFUNC:
   339  		var x struct {
   340  			Node
   341  			Func
   342  		}
   343  		n = &x.Node
   344  		n.Func = &x.Func
   345  		n.Func.IsHiddenClosure = Curfn != nil
   346  	case ONAME:
   347  		var x struct {
   348  			Node
   349  			Name
   350  			Param
   351  		}
   352  		n = &x.Node
   353  		n.Name = &x.Name
   354  		n.Name.Param = &x.Param
   355  	case OLABEL, OPACK:
   356  		var x struct {
   357  			Node
   358  			Name
   359  		}
   360  		n = &x.Node
   361  		n.Name = &x.Name
   362  	default:
   363  		n = new(Node)
   364  	}
   365  	n.Op = op
   366  	n.Left = nleft
   367  	n.Right = nright
   368  	n.Pos = lineno
   369  	n.Xoffset = BADWIDTH
   370  	n.Orig = n
   371  	if n.Name != nil {
   372  		n.Name.Curfn = Curfn
   373  	}
   374  	return n
   375  }
   376  
   377  // nodSym makes a Node with Op op and with the Left field set to left
   378  // and the Sym field set to sym. This is for ODOT and friends.
   379  func nodSym(op Op, left *Node, sym *Sym) *Node {
   380  	n := nod(op, left, nil)
   381  	n.Sym = sym
   382  	return n
   383  }
   384  
   385  func saveorignode(n *Node) {
   386  	if n.Orig != nil {
   387  		return
   388  	}
   389  	norig := nod(n.Op, nil, nil)
   390  	*norig = *n
   391  	n.Orig = norig
   392  }
   393  
   394  // methcmp sorts by symbol, then by package path for unexported symbols.
   395  type methcmp []*Field
   396  
   397  func (x methcmp) Len() int      { return len(x) }
   398  func (x methcmp) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
   399  func (x methcmp) Less(i, j int) bool {
   400  	a := x[i]
   401  	b := x[j]
   402  	if a.Sym == nil && b.Sym == nil {
   403  		return false
   404  	}
   405  	if a.Sym == nil {
   406  		return true
   407  	}
   408  	if b.Sym == nil {
   409  		return false
   410  	}
   411  	if a.Sym.Name != b.Sym.Name {
   412  		return a.Sym.Name < b.Sym.Name
   413  	}
   414  	if !exportname(a.Sym.Name) {
   415  		if a.Sym.Pkg.Path != b.Sym.Pkg.Path {
   416  			return a.Sym.Pkg.Path < b.Sym.Pkg.Path
   417  		}
   418  	}
   419  
   420  	return false
   421  }
   422  
   423  func nodintconst(v int64) *Node {
   424  	c := nod(OLITERAL, nil, nil)
   425  	c.Addable = true
   426  	c.SetVal(Val{new(Mpint)})
   427  	c.Val().U.(*Mpint).SetInt64(v)
   428  	c.Type = Types[TIDEAL]
   429  	ullmancalc(c)
   430  	return c
   431  }
   432  
   433  func nodfltconst(v *Mpflt) *Node {
   434  	c := nod(OLITERAL, nil, nil)
   435  	c.Addable = true
   436  	c.SetVal(Val{newMpflt()})
   437  	c.Val().U.(*Mpflt).Set(v)
   438  	c.Type = Types[TIDEAL]
   439  	ullmancalc(c)
   440  	return c
   441  }
   442  
   443  func nodconst(n *Node, t *Type, v int64) {
   444  	*n = Node{}
   445  	n.Op = OLITERAL
   446  	n.Addable = true
   447  	ullmancalc(n)
   448  	n.SetVal(Val{new(Mpint)})
   449  	n.Val().U.(*Mpint).SetInt64(v)
   450  	n.Type = t
   451  
   452  	if t.IsFloat() {
   453  		Fatalf("nodconst: bad type %v", t)
   454  	}
   455  }
   456  
   457  func nodnil() *Node {
   458  	c := nodintconst(0)
   459  	c.SetVal(Val{new(NilVal)})
   460  	c.Type = Types[TNIL]
   461  	return c
   462  }
   463  
   464  func nodbool(b bool) *Node {
   465  	c := nodintconst(0)
   466  	c.SetVal(Val{b})
   467  	c.Type = idealbool
   468  	return c
   469  }
   470  
   471  // treecopy recursively copies n, with the exception of
   472  // ONAME, OLITERAL, OTYPE, and non-iota ONONAME leaves.
   473  // Copies of iota ONONAME nodes are assigned the current
   474  // value of iota_. If pos.IsKnown(), it sets the source
   475  // position of newly allocated nodes to pos.
   476  func treecopy(n *Node, pos src.XPos) *Node {
   477  	if n == nil {
   478  		return nil
   479  	}
   480  
   481  	switch n.Op {
   482  	default:
   483  		m := *n
   484  		m.Orig = &m
   485  		m.Left = treecopy(n.Left, pos)
   486  		m.Right = treecopy(n.Right, pos)
   487  		m.List.Set(listtreecopy(n.List.Slice(), pos))
   488  		if pos.IsKnown() {
   489  			m.Pos = pos
   490  		}
   491  		if m.Name != nil && n.Op != ODCLFIELD {
   492  			Dump("treecopy", n)
   493  			Fatalf("treecopy Name")
   494  		}
   495  		return &m
   496  
   497  	case OPACK:
   498  		// OPACK nodes are never valid in const value declarations,
   499  		// but allow them like any other declared symbol to avoid
   500  		// crashing (golang.org/issue/11361).
   501  		fallthrough
   502  
   503  	case ONAME, ONONAME, OLITERAL, OTYPE:
   504  		return n
   505  
   506  	}
   507  }
   508  
   509  // isnil reports whether n represents the universal untyped zero value "nil".
   510  func isnil(n *Node) bool {
   511  	// Check n.Orig because constant propagation may produce typed nil constants,
   512  	// which don't exist in the Go spec.
   513  	return Isconst(n.Orig, CTNIL)
   514  }
   515  
   516  func isptrto(t *Type, et EType) bool {
   517  	if t == nil {
   518  		return false
   519  	}
   520  	if !t.IsPtr() {
   521  		return false
   522  	}
   523  	t = t.Elem()
   524  	if t == nil {
   525  		return false
   526  	}
   527  	if t.Etype != et {
   528  		return false
   529  	}
   530  	return true
   531  }
   532  
   533  func isblank(n *Node) bool {
   534  	if n == nil {
   535  		return false
   536  	}
   537  	return isblanksym(n.Sym)
   538  }
   539  
   540  func isblanksym(s *Sym) bool {
   541  	return s != nil && s.Name == "_"
   542  }
   543  
   544  // methtype returns the underlying type, if any,
   545  // that owns methods with receiver parameter t.
   546  // The result is either a named type or an anonymous struct.
   547  func methtype(t *Type) *Type {
   548  	if t == nil {
   549  		return nil
   550  	}
   551  
   552  	// Strip away pointer if it's there.
   553  	if t.IsPtr() {
   554  		if t.Sym != nil {
   555  			return nil
   556  		}
   557  		t = t.Elem()
   558  		if t == nil {
   559  			return nil
   560  		}
   561  	}
   562  
   563  	// Must be a named type or anonymous struct.
   564  	if t.Sym == nil && !t.IsStruct() {
   565  		return nil
   566  	}
   567  
   568  	// Check types.
   569  	if issimple[t.Etype] {
   570  		return t
   571  	}
   572  	switch t.Etype {
   573  	case TARRAY, TCHAN, TFUNC, TMAP, TSLICE, TSTRING, TSTRUCT:
   574  		return t
   575  	}
   576  	return nil
   577  }
   578  
   579  func cplxsubtype(et EType) EType {
   580  	switch et {
   581  	case TCOMPLEX64:
   582  		return TFLOAT32
   583  
   584  	case TCOMPLEX128:
   585  		return TFLOAT64
   586  	}
   587  
   588  	Fatalf("cplxsubtype: %v\n", et)
   589  	return 0
   590  }
   591  
   592  // eqtype reports whether t1 and t2 are identical, following the spec rules.
   593  //
   594  // Any cyclic type must go through a named type, and if one is
   595  // named, it is only identical to the other if they are the same
   596  // pointer (t1 == t2), so there's no chance of chasing cycles
   597  // ad infinitum, so no need for a depth counter.
   598  func eqtype(t1, t2 *Type) bool {
   599  	return eqtype1(t1, t2, true, nil)
   600  }
   601  
   602  // eqtypeIgnoreTags is like eqtype but it ignores struct tags for struct identity.
   603  func eqtypeIgnoreTags(t1, t2 *Type) bool {
   604  	return eqtype1(t1, t2, false, nil)
   605  }
   606  
   607  type typePair struct {
   608  	t1 *Type
   609  	t2 *Type
   610  }
   611  
   612  func eqtype1(t1, t2 *Type, cmpTags bool, assumedEqual map[typePair]struct{}) bool {
   613  	if t1 == t2 {
   614  		return true
   615  	}
   616  	if t1 == nil || t2 == nil || t1.Etype != t2.Etype || t1.Broke || t2.Broke {
   617  		return false
   618  	}
   619  	if t1.Sym != nil || t2.Sym != nil {
   620  		// Special case: we keep byte/uint8 and rune/int32
   621  		// separate for error messages. Treat them as equal.
   622  		switch t1.Etype {
   623  		case TUINT8:
   624  			return (t1 == Types[TUINT8] || t1 == bytetype) && (t2 == Types[TUINT8] || t2 == bytetype)
   625  		case TINT32:
   626  			return (t1 == Types[TINT32] || t1 == runetype) && (t2 == Types[TINT32] || t2 == runetype)
   627  		default:
   628  			return false
   629  		}
   630  	}
   631  
   632  	if assumedEqual == nil {
   633  		assumedEqual = make(map[typePair]struct{})
   634  	} else if _, ok := assumedEqual[typePair{t1, t2}]; ok {
   635  		return true
   636  	}
   637  	assumedEqual[typePair{t1, t2}] = struct{}{}
   638  
   639  	switch t1.Etype {
   640  	case TINTER, TSTRUCT:
   641  		t1, i1 := iterFields(t1)
   642  		t2, i2 := iterFields(t2)
   643  		for ; t1 != nil && t2 != nil; t1, t2 = i1.Next(), i2.Next() {
   644  			if t1.Sym != t2.Sym || t1.Embedded != t2.Embedded || !eqtype1(t1.Type, t2.Type, cmpTags, assumedEqual) || cmpTags && t1.Note != t2.Note {
   645  				return false
   646  			}
   647  		}
   648  
   649  		if t1 == nil && t2 == nil {
   650  			return true
   651  		}
   652  		return false
   653  
   654  	case TFUNC:
   655  		// Check parameters and result parameters for type equality.
   656  		// We intentionally ignore receiver parameters for type
   657  		// equality, because they're never relevant.
   658  		for _, f := range paramsResults {
   659  			// Loop over fields in structs, ignoring argument names.
   660  			ta, ia := iterFields(f(t1))
   661  			tb, ib := iterFields(f(t2))
   662  			for ; ta != nil && tb != nil; ta, tb = ia.Next(), ib.Next() {
   663  				if ta.Isddd != tb.Isddd || !eqtype1(ta.Type, tb.Type, cmpTags, assumedEqual) {
   664  					return false
   665  				}
   666  			}
   667  			if ta != nil || tb != nil {
   668  				return false
   669  			}
   670  		}
   671  		return true
   672  
   673  	case TARRAY:
   674  		if t1.NumElem() != t2.NumElem() {
   675  			return false
   676  		}
   677  
   678  	case TCHAN:
   679  		if t1.ChanDir() != t2.ChanDir() {
   680  			return false
   681  		}
   682  
   683  	case TMAP:
   684  		if !eqtype1(t1.Key(), t2.Key(), cmpTags, assumedEqual) {
   685  			return false
   686  		}
   687  		return eqtype1(t1.Val(), t2.Val(), cmpTags, assumedEqual)
   688  	}
   689  
   690  	return eqtype1(t1.Elem(), t2.Elem(), cmpTags, assumedEqual)
   691  }
   692  
   693  // Are t1 and t2 equal struct types when field names are ignored?
   694  // For deciding whether the result struct from g can be copied
   695  // directly when compiling f(g()).
   696  func eqtypenoname(t1 *Type, t2 *Type) bool {
   697  	if t1 == nil || t2 == nil || !t1.IsStruct() || !t2.IsStruct() {
   698  		return false
   699  	}
   700  
   701  	f1, i1 := iterFields(t1)
   702  	f2, i2 := iterFields(t2)
   703  	for {
   704  		if !eqtype(f1.Type, f2.Type) {
   705  			return false
   706  		}
   707  		if f1 == nil {
   708  			return true
   709  		}
   710  		f1 = i1.Next()
   711  		f2 = i2.Next()
   712  	}
   713  }
   714  
   715  // Is type src assignment compatible to type dst?
   716  // If so, return op code to use in conversion.
   717  // If not, return 0.
   718  func assignop(src *Type, dst *Type, why *string) Op {
   719  	if why != nil {
   720  		*why = ""
   721  	}
   722  
   723  	// TODO(rsc,lvd): This behaves poorly in the presence of inlining.
   724  	// https://golang.org/issue/2795
   725  	if safemode && importpkg == nil && src != nil && src.Etype == TUNSAFEPTR {
   726  		yyerror("cannot use unsafe.Pointer")
   727  		errorexit()
   728  	}
   729  
   730  	if src == dst {
   731  		return OCONVNOP
   732  	}
   733  	if src == nil || dst == nil || src.Etype == TFORW || dst.Etype == TFORW || src.Orig == nil || dst.Orig == nil {
   734  		return 0
   735  	}
   736  
   737  	// 1. src type is identical to dst.
   738  	if eqtype(src, dst) {
   739  		return OCONVNOP
   740  	}
   741  
   742  	// 2. src and dst have identical underlying types
   743  	// and either src or dst is not a named type or
   744  	// both are empty interface types.
   745  	// For assignable but different non-empty interface types,
   746  	// we want to recompute the itab. Recomputing the itab ensures
   747  	// that itabs are unique (thus an interface with a compile-time
   748  	// type I has an itab with interface type I).
   749  	if eqtype(src.Orig, dst.Orig) {
   750  		if src.IsEmptyInterface() {
   751  			// Conversion between two empty interfaces
   752  			// requires no code.
   753  			return OCONVNOP
   754  		}
   755  		if (src.Sym == nil || dst.Sym == nil) && !src.IsInterface() {
   756  			// Conversion between two types, at least one unnamed,
   757  			// needs no conversion. The exception is nonempty interfaces
   758  			// which need to have their itab updated.
   759  			return OCONVNOP
   760  		}
   761  	}
   762  
   763  	// 3. dst is an interface type and src implements dst.
   764  	if dst.IsInterface() && src.Etype != TNIL {
   765  		var missing, have *Field
   766  		var ptr int
   767  		if implements(src, dst, &missing, &have, &ptr) {
   768  			return OCONVIFACE
   769  		}
   770  
   771  		// we'll have complained about this method anyway, suppress spurious messages.
   772  		if have != nil && have.Sym == missing.Sym && (have.Type.Broke || missing.Type.Broke) {
   773  			return OCONVIFACE
   774  		}
   775  
   776  		if why != nil {
   777  			if isptrto(src, TINTER) {
   778  				*why = fmt.Sprintf(":\n\t%v is pointer to interface, not interface", src)
   779  			} else if have != nil && have.Sym == missing.Sym && have.Nointerface {
   780  				*why = fmt.Sprintf(":\n\t%v does not implement %v (%v method is marked 'nointerface')", src, dst, missing.Sym)
   781  			} else if have != nil && have.Sym == missing.Sym {
   782  				*why = fmt.Sprintf(":\n\t%v does not implement %v (wrong type for %v method)\n"+
   783  					"\t\thave %v%0S\n\t\twant %v%0S", src, dst, missing.Sym, have.Sym, have.Type, missing.Sym, missing.Type)
   784  			} else if ptr != 0 {
   785  				*why = fmt.Sprintf(":\n\t%v does not implement %v (%v method has pointer receiver)", src, dst, missing.Sym)
   786  			} else if have != nil {
   787  				*why = fmt.Sprintf(":\n\t%v does not implement %v (missing %v method)\n"+
   788  					"\t\thave %v%0S\n\t\twant %v%0S", src, dst, missing.Sym, have.Sym, have.Type, missing.Sym, missing.Type)
   789  			} else {
   790  				*why = fmt.Sprintf(":\n\t%v does not implement %v (missing %v method)", src, dst, missing.Sym)
   791  			}
   792  		}
   793  
   794  		return 0
   795  	}
   796  
   797  	if isptrto(dst, TINTER) {
   798  		if why != nil {
   799  			*why = fmt.Sprintf(":\n\t%v is pointer to interface, not interface", dst)
   800  		}
   801  		return 0
   802  	}
   803  
   804  	if src.IsInterface() && dst.Etype != TBLANK {
   805  		var missing, have *Field
   806  		var ptr int
   807  		if why != nil && implements(dst, src, &missing, &have, &ptr) {
   808  			*why = ": need type assertion"
   809  		}
   810  		return 0
   811  	}
   812  
   813  	// 4. src is a bidirectional channel value, dst is a channel type,
   814  	// src and dst have identical element types, and
   815  	// either src or dst is not a named type.
   816  	if src.IsChan() && src.ChanDir() == Cboth && dst.IsChan() {
   817  		if eqtype(src.Elem(), dst.Elem()) && (src.Sym == nil || dst.Sym == nil) {
   818  			return OCONVNOP
   819  		}
   820  	}
   821  
   822  	// 5. src is the predeclared identifier nil and dst is a nillable type.
   823  	if src.Etype == TNIL {
   824  		switch dst.Etype {
   825  		case TPTR32,
   826  			TPTR64,
   827  			TFUNC,
   828  			TMAP,
   829  			TCHAN,
   830  			TINTER,
   831  			TSLICE:
   832  			return OCONVNOP
   833  		}
   834  	}
   835  
   836  	// 6. rule about untyped constants - already converted by defaultlit.
   837  
   838  	// 7. Any typed value can be assigned to the blank identifier.
   839  	if dst.Etype == TBLANK {
   840  		return OCONVNOP
   841  	}
   842  
   843  	return 0
   844  }
   845  
   846  // Can we convert a value of type src to a value of type dst?
   847  // If so, return op code to use in conversion (maybe OCONVNOP).
   848  // If not, return 0.
   849  func convertop(src *Type, dst *Type, why *string) Op {
   850  	if why != nil {
   851  		*why = ""
   852  	}
   853  
   854  	if src == dst {
   855  		return OCONVNOP
   856  	}
   857  	if src == nil || dst == nil {
   858  		return 0
   859  	}
   860  
   861  	// Conversions from regular to go:notinheap are not allowed
   862  	// (unless it's unsafe.Pointer). This is a runtime-specific
   863  	// rule.
   864  	if src.IsPtr() && dst.IsPtr() && dst.Elem().NotInHeap && !src.Elem().NotInHeap {
   865  		if why != nil {
   866  			*why = fmt.Sprintf(":\n\t%v is go:notinheap, but %v is not", dst.Elem(), src.Elem())
   867  		}
   868  		return 0
   869  	}
   870  
   871  	// 1. src can be assigned to dst.
   872  	op := assignop(src, dst, why)
   873  	if op != 0 {
   874  		return op
   875  	}
   876  
   877  	// The rules for interfaces are no different in conversions
   878  	// than assignments. If interfaces are involved, stop now
   879  	// with the good message from assignop.
   880  	// Otherwise clear the error.
   881  	if src.IsInterface() || dst.IsInterface() {
   882  		return 0
   883  	}
   884  	if why != nil {
   885  		*why = ""
   886  	}
   887  
   888  	// 2. Ignoring struct tags, src and dst have identical underlying types.
   889  	if eqtypeIgnoreTags(src.Orig, dst.Orig) {
   890  		return OCONVNOP
   891  	}
   892  
   893  	// 3. src and dst are unnamed pointer types and, ignoring struct tags,
   894  	// their base types have identical underlying types.
   895  	if src.IsPtr() && dst.IsPtr() && src.Sym == nil && dst.Sym == nil {
   896  		if eqtypeIgnoreTags(src.Elem().Orig, dst.Elem().Orig) {
   897  			return OCONVNOP
   898  		}
   899  	}
   900  
   901  	// 4. src and dst are both integer or floating point types.
   902  	if (src.IsInteger() || src.IsFloat()) && (dst.IsInteger() || dst.IsFloat()) {
   903  		if simtype[src.Etype] == simtype[dst.Etype] {
   904  			return OCONVNOP
   905  		}
   906  		return OCONV
   907  	}
   908  
   909  	// 5. src and dst are both complex types.
   910  	if src.IsComplex() && dst.IsComplex() {
   911  		if simtype[src.Etype] == simtype[dst.Etype] {
   912  			return OCONVNOP
   913  		}
   914  		return OCONV
   915  	}
   916  
   917  	// 6. src is an integer or has type []byte or []rune
   918  	// and dst is a string type.
   919  	if src.IsInteger() && dst.IsString() {
   920  		return ORUNESTR
   921  	}
   922  
   923  	if src.IsSlice() && dst.IsString() {
   924  		if src.Elem().Etype == bytetype.Etype {
   925  			return OARRAYBYTESTR
   926  		}
   927  		if src.Elem().Etype == runetype.Etype {
   928  			return OARRAYRUNESTR
   929  		}
   930  	}
   931  
   932  	// 7. src is a string and dst is []byte or []rune.
   933  	// String to slice.
   934  	if src.IsString() && dst.IsSlice() {
   935  		if dst.Elem().Etype == bytetype.Etype {
   936  			return OSTRARRAYBYTE
   937  		}
   938  		if dst.Elem().Etype == runetype.Etype {
   939  			return OSTRARRAYRUNE
   940  		}
   941  	}
   942  
   943  	// 8. src is a pointer or uintptr and dst is unsafe.Pointer.
   944  	if (src.IsPtr() || src.Etype == TUINTPTR) && dst.Etype == TUNSAFEPTR {
   945  		return OCONVNOP
   946  	}
   947  
   948  	// 9. src is unsafe.Pointer and dst is a pointer or uintptr.
   949  	if src.Etype == TUNSAFEPTR && (dst.IsPtr() || dst.Etype == TUINTPTR) {
   950  		return OCONVNOP
   951  	}
   952  
   953  	return 0
   954  }
   955  
   956  func assignconv(n *Node, t *Type, context string) *Node {
   957  	return assignconvfn(n, t, func() string { return context })
   958  }
   959  
   960  // Convert node n for assignment to type t.
   961  func assignconvfn(n *Node, t *Type, context func() string) *Node {
   962  	if n == nil || n.Type == nil || n.Type.Broke {
   963  		return n
   964  	}
   965  
   966  	if t.Etype == TBLANK && n.Type.Etype == TNIL {
   967  		yyerror("use of untyped nil")
   968  	}
   969  
   970  	old := n
   971  	od := old.Diag
   972  	old.Diag = true // silence errors about n; we'll issue one below
   973  	n = defaultlit(n, t)
   974  	old.Diag = od
   975  	if t.Etype == TBLANK {
   976  		return n
   977  	}
   978  
   979  	// Convert ideal bool from comparison to plain bool
   980  	// if the next step is non-bool (like interface{}).
   981  	if n.Type == idealbool && !t.IsBoolean() {
   982  		if n.Op == ONAME || n.Op == OLITERAL {
   983  			r := nod(OCONVNOP, n, nil)
   984  			r.Type = Types[TBOOL]
   985  			r.Typecheck = 1
   986  			r.Implicit = true
   987  			n = r
   988  		}
   989  	}
   990  
   991  	if eqtype(n.Type, t) {
   992  		return n
   993  	}
   994  
   995  	var why string
   996  	op := assignop(n.Type, t, &why)
   997  	if op == 0 {
   998  		yyerror("cannot use %L as type %v in %s%s", n, t, context(), why)
   999  		op = OCONV
  1000  	}
  1001  
  1002  	r := nod(op, n, nil)
  1003  	r.Type = t
  1004  	r.Typecheck = 1
  1005  	r.Implicit = true
  1006  	r.Orig = n.Orig
  1007  	return r
  1008  }
  1009  
  1010  // IsMethod reports whether n is a method.
  1011  // n must be a function or a method.
  1012  func (n *Node) IsMethod() bool {
  1013  	return n.Type.Recv() != nil
  1014  }
  1015  
  1016  // SliceBounds returns n's slice bounds: low, high, and max in expr[low:high:max].
  1017  // n must be a slice expression. max is nil if n is a simple slice expression.
  1018  func (n *Node) SliceBounds() (low, high, max *Node) {
  1019  	if n.List.Len() == 0 {
  1020  		return nil, nil, nil
  1021  	}
  1022  
  1023  	switch n.Op {
  1024  	case OSLICE, OSLICEARR, OSLICESTR:
  1025  		s := n.List.Slice()
  1026  		return s[0], s[1], nil
  1027  	case OSLICE3, OSLICE3ARR:
  1028  		s := n.List.Slice()
  1029  		return s[0], s[1], s[2]
  1030  	}
  1031  	Fatalf("SliceBounds op %v: %v", n.Op, n)
  1032  	return nil, nil, nil
  1033  }
  1034  
  1035  // SetSliceBounds sets n's slice bounds, where n is a slice expression.
  1036  // n must be a slice expression. If max is non-nil, n must be a full slice expression.
  1037  func (n *Node) SetSliceBounds(low, high, max *Node) {
  1038  	switch n.Op {
  1039  	case OSLICE, OSLICEARR, OSLICESTR:
  1040  		if max != nil {
  1041  			Fatalf("SetSliceBounds %v given three bounds", n.Op)
  1042  		}
  1043  		s := n.List.Slice()
  1044  		if s == nil {
  1045  			if low == nil && high == nil {
  1046  				return
  1047  			}
  1048  			n.List.Set([]*Node{low, high})
  1049  			return
  1050  		}
  1051  		s[0] = low
  1052  		s[1] = high
  1053  		return
  1054  	case OSLICE3, OSLICE3ARR:
  1055  		s := n.List.Slice()
  1056  		if s == nil {
  1057  			if low == nil && high == nil && max == nil {
  1058  				return
  1059  			}
  1060  			n.List.Set([]*Node{low, high, max})
  1061  			return
  1062  		}
  1063  		s[0] = low
  1064  		s[1] = high
  1065  		s[2] = max
  1066  		return
  1067  	}
  1068  	Fatalf("SetSliceBounds op %v: %v", n.Op, n)
  1069  }
  1070  
  1071  // IsSlice3 reports whether o is a slice3 op (OSLICE3, OSLICE3ARR).
  1072  // o must be a slicing op.
  1073  func (o Op) IsSlice3() bool {
  1074  	switch o {
  1075  	case OSLICE, OSLICEARR, OSLICESTR:
  1076  		return false
  1077  	case OSLICE3, OSLICE3ARR:
  1078  		return true
  1079  	}
  1080  	Fatalf("IsSlice3 op %v", o)
  1081  	return false
  1082  }
  1083  
  1084  func syslook(name string) *Node {
  1085  	s := Pkglookup(name, Runtimepkg)
  1086  	if s == nil || s.Def == nil {
  1087  		Fatalf("syslook: can't find runtime.%s", name)
  1088  	}
  1089  	return s.Def
  1090  }
  1091  
  1092  // typehash computes a hash value for type t to use in type switch
  1093  // statements.
  1094  func typehash(t *Type) uint32 {
  1095  	// t.tconv(FmtLeft | FmtUnsigned) already contains all the necessary logic
  1096  	// to generate a representation that completely describes the type, so using
  1097  	// it here avoids duplicating that code.
  1098  	// See the comments in exprSwitch.checkDupCases.
  1099  	p := t.tconv(FmtLeft | FmtUnsigned)
  1100  
  1101  	// Using MD5 is overkill, but reduces accidental collisions.
  1102  	h := md5.Sum([]byte(p))
  1103  	return binary.LittleEndian.Uint32(h[:4])
  1104  }
  1105  
  1106  // ptrto returns the Type *t.
  1107  // The returned struct must not be modified.
  1108  func ptrto(t *Type) *Type {
  1109  	if Tptr == 0 {
  1110  		Fatalf("ptrto: no tptr")
  1111  	}
  1112  	if t == nil {
  1113  		Fatalf("ptrto: nil ptr")
  1114  	}
  1115  	return typPtr(t)
  1116  }
  1117  
  1118  func frame(context int) {
  1119  	if context != 0 {
  1120  		fmt.Printf("--- external frame ---\n")
  1121  		for _, n := range externdcl {
  1122  			printframenode(n)
  1123  		}
  1124  		return
  1125  	}
  1126  
  1127  	if Curfn != nil {
  1128  		fmt.Printf("--- %v frame ---\n", Curfn.Func.Nname.Sym)
  1129  		for _, ln := range Curfn.Func.Dcl {
  1130  			printframenode(ln)
  1131  		}
  1132  	}
  1133  }
  1134  
  1135  func printframenode(n *Node) {
  1136  	w := int64(-1)
  1137  	if n.Type != nil {
  1138  		w = n.Type.Width
  1139  	}
  1140  	switch n.Op {
  1141  	case ONAME:
  1142  		fmt.Printf("%v %v G%d %v width=%d\n", n.Op, n.Sym, n.Name.Vargen, n.Type, w)
  1143  	case OTYPE:
  1144  		fmt.Printf("%v %v width=%d\n", n.Op, n.Type, w)
  1145  	}
  1146  }
  1147  
  1148  // calculate sethi/ullman number
  1149  // roughly how many registers needed to
  1150  // compile a node. used to compile the
  1151  // hardest side first to minimize registers.
  1152  func ullmancalc(n *Node) {
  1153  	if n == nil {
  1154  		return
  1155  	}
  1156  
  1157  	var ul int
  1158  	var ur int
  1159  	if n.Ninit.Len() != 0 {
  1160  		ul = UINF
  1161  		goto out
  1162  	}
  1163  
  1164  	switch n.Op {
  1165  	case OLITERAL, ONAME:
  1166  		ul = 1
  1167  		if n.Class == PAUTOHEAP {
  1168  			ul++
  1169  		}
  1170  		goto out
  1171  
  1172  	case OAS:
  1173  		if !needwritebarrier(n.Left, n.Right) {
  1174  			break
  1175  		}
  1176  		fallthrough
  1177  	case OCALL, OCALLFUNC, OCALLMETH, OCALLINTER:
  1178  		ul = UINF
  1179  		goto out
  1180  
  1181  		// hard with instrumented code
  1182  	case OANDAND, OOROR:
  1183  		if instrumenting {
  1184  			ul = UINF
  1185  			goto out
  1186  		}
  1187  	case OINDEX, OSLICE, OSLICEARR, OSLICE3, OSLICE3ARR, OSLICESTR,
  1188  		OIND, ODOTPTR, ODOTTYPE, ODIV, OMOD:
  1189  		// These ops might panic, make sure they are done
  1190  		// before we start marshaling args for a call. See issue 16760.
  1191  		ul = UINF
  1192  		goto out
  1193  	}
  1194  
  1195  	ul = 1
  1196  	if n.Left != nil {
  1197  		ul = int(n.Left.Ullman)
  1198  	}
  1199  	ur = 1
  1200  	if n.Right != nil {
  1201  		ur = int(n.Right.Ullman)
  1202  	}
  1203  	if ul == ur {
  1204  		ul += 1
  1205  	}
  1206  	if ur > ul {
  1207  		ul = ur
  1208  	}
  1209  
  1210  out:
  1211  	if ul > 200 {
  1212  		ul = 200 // clamp to uchar with room to grow
  1213  	}
  1214  	n.Ullman = uint8(ul)
  1215  }
  1216  
  1217  func badtype(op Op, tl *Type, tr *Type) {
  1218  	fmt_ := ""
  1219  	if tl != nil {
  1220  		fmt_ += fmt.Sprintf("\n\t%v", tl)
  1221  	}
  1222  	if tr != nil {
  1223  		fmt_ += fmt.Sprintf("\n\t%v", tr)
  1224  	}
  1225  
  1226  	// common mistake: *struct and *interface.
  1227  	if tl != nil && tr != nil && tl.IsPtr() && tr.IsPtr() {
  1228  		if tl.Elem().IsStruct() && tr.Elem().IsInterface() {
  1229  			fmt_ += "\n\t(*struct vs *interface)"
  1230  		} else if tl.Elem().IsInterface() && tr.Elem().IsStruct() {
  1231  			fmt_ += "\n\t(*interface vs *struct)"
  1232  		}
  1233  	}
  1234  
  1235  	s := fmt_
  1236  	yyerror("illegal types for operand: %v%s", op, s)
  1237  }
  1238  
  1239  // brcom returns !(op).
  1240  // For example, brcom(==) is !=.
  1241  func brcom(op Op) Op {
  1242  	switch op {
  1243  	case OEQ:
  1244  		return ONE
  1245  	case ONE:
  1246  		return OEQ
  1247  	case OLT:
  1248  		return OGE
  1249  	case OGT:
  1250  		return OLE
  1251  	case OLE:
  1252  		return OGT
  1253  	case OGE:
  1254  		return OLT
  1255  	}
  1256  	Fatalf("brcom: no com for %v\n", op)
  1257  	return op
  1258  }
  1259  
  1260  // brrev returns reverse(op).
  1261  // For example, Brrev(<) is >.
  1262  func brrev(op Op) Op {
  1263  	switch op {
  1264  	case OEQ:
  1265  		return OEQ
  1266  	case ONE:
  1267  		return ONE
  1268  	case OLT:
  1269  		return OGT
  1270  	case OGT:
  1271  		return OLT
  1272  	case OLE:
  1273  		return OGE
  1274  	case OGE:
  1275  		return OLE
  1276  	}
  1277  	Fatalf("brrev: no rev for %v\n", op)
  1278  	return op
  1279  }
  1280  
  1281  // return side effect-free n, appending side effects to init.
  1282  // result is assignable if n is.
  1283  func safeexpr(n *Node, init *Nodes) *Node {
  1284  	if n == nil {
  1285  		return nil
  1286  	}
  1287  
  1288  	if n.Ninit.Len() != 0 {
  1289  		walkstmtlist(n.Ninit.Slice())
  1290  		init.AppendNodes(&n.Ninit)
  1291  	}
  1292  
  1293  	switch n.Op {
  1294  	case ONAME, OLITERAL:
  1295  		return n
  1296  
  1297  	case ODOT, OLEN, OCAP:
  1298  		l := safeexpr(n.Left, init)
  1299  		if l == n.Left {
  1300  			return n
  1301  		}
  1302  		r := nod(OXXX, nil, nil)
  1303  		*r = *n
  1304  		r.Left = l
  1305  		r = typecheck(r, Erv)
  1306  		r = walkexpr(r, init)
  1307  		return r
  1308  
  1309  	case ODOTPTR, OIND:
  1310  		l := safeexpr(n.Left, init)
  1311  		if l == n.Left {
  1312  			return n
  1313  		}
  1314  		a := nod(OXXX, nil, nil)
  1315  		*a = *n
  1316  		a.Left = l
  1317  		a = walkexpr(a, init)
  1318  		return a
  1319  
  1320  	case OINDEX, OINDEXMAP:
  1321  		l := safeexpr(n.Left, init)
  1322  		r := safeexpr(n.Right, init)
  1323  		if l == n.Left && r == n.Right {
  1324  			return n
  1325  		}
  1326  		a := nod(OXXX, nil, nil)
  1327  		*a = *n
  1328  		a.Left = l
  1329  		a.Right = r
  1330  		a = walkexpr(a, init)
  1331  		return a
  1332  
  1333  	case OSTRUCTLIT, OARRAYLIT, OSLICELIT:
  1334  		if isStaticCompositeLiteral(n) {
  1335  			return n
  1336  		}
  1337  	}
  1338  
  1339  	// make a copy; must not be used as an lvalue
  1340  	if islvalue(n) {
  1341  		Fatalf("missing lvalue case in safeexpr: %v", n)
  1342  	}
  1343  	return cheapexpr(n, init)
  1344  }
  1345  
  1346  func copyexpr(n *Node, t *Type, init *Nodes) *Node {
  1347  	l := temp(t)
  1348  	a := nod(OAS, l, n)
  1349  	a = typecheck(a, Etop)
  1350  	a = walkexpr(a, init)
  1351  	init.Append(a)
  1352  	return l
  1353  }
  1354  
  1355  // return side-effect free and cheap n, appending side effects to init.
  1356  // result may not be assignable.
  1357  func cheapexpr(n *Node, init *Nodes) *Node {
  1358  	switch n.Op {
  1359  	case ONAME, OLITERAL:
  1360  		return n
  1361  	}
  1362  
  1363  	return copyexpr(n, n.Type, init)
  1364  }
  1365  
  1366  // Code to resolve elided DOTs in embedded types.
  1367  
  1368  // A Dlist stores a pointer to a TFIELD Type embedded within
  1369  // a TSTRUCT or TINTER Type.
  1370  type Dlist struct {
  1371  	field *Field
  1372  }
  1373  
  1374  // dotlist is used by adddot1 to record the path of embedded fields
  1375  // used to access a target field or method.
  1376  // Must be non-nil so that dotpath returns a non-nil slice even if d is zero.
  1377  var dotlist = make([]Dlist, 10)
  1378  
  1379  // lookdot0 returns the number of fields or methods named s associated
  1380  // with Type t. If exactly one exists, it will be returned in *save
  1381  // (if save is not nil).
  1382  func lookdot0(s *Sym, t *Type, save **Field, ignorecase bool) int {
  1383  	u := t
  1384  	if u.IsPtr() {
  1385  		u = u.Elem()
  1386  	}
  1387  
  1388  	c := 0
  1389  	if u.IsStruct() || u.IsInterface() {
  1390  		for _, f := range u.Fields().Slice() {
  1391  			if f.Sym == s || (ignorecase && f.Type.Etype == TFUNC && f.Type.Recv() != nil && strings.EqualFold(f.Sym.Name, s.Name)) {
  1392  				if save != nil {
  1393  					*save = f
  1394  				}
  1395  				c++
  1396  			}
  1397  		}
  1398  	}
  1399  
  1400  	u = methtype(t)
  1401  	if u != nil {
  1402  		for _, f := range u.Methods().Slice() {
  1403  			if f.Embedded == 0 && (f.Sym == s || (ignorecase && strings.EqualFold(f.Sym.Name, s.Name))) {
  1404  				if save != nil {
  1405  					*save = f
  1406  				}
  1407  				c++
  1408  			}
  1409  		}
  1410  	}
  1411  
  1412  	return c
  1413  }
  1414  
  1415  // adddot1 returns the number of fields or methods named s at depth d in Type t.
  1416  // If exactly one exists, it will be returned in *save (if save is not nil),
  1417  // and dotlist will contain the path of embedded fields traversed to find it,
  1418  // in reverse order. If none exist, more will indicate whether t contains any
  1419  // embedded fields at depth d, so callers can decide whether to retry at
  1420  // a greater depth.
  1421  func adddot1(s *Sym, t *Type, d int, save **Field, ignorecase bool) (c int, more bool) {
  1422  	if t.Trecur != 0 {
  1423  		return
  1424  	}
  1425  	t.Trecur = 1
  1426  
  1427  	var u *Type
  1428  	d--
  1429  	if d < 0 {
  1430  		// We've reached our target depth. If t has any fields/methods
  1431  		// named s, then we're done. Otherwise, we still need to check
  1432  		// below for embedded fields.
  1433  		c = lookdot0(s, t, save, ignorecase)
  1434  		if c != 0 {
  1435  			goto out
  1436  		}
  1437  	}
  1438  
  1439  	u = t
  1440  	if u.IsPtr() {
  1441  		u = u.Elem()
  1442  	}
  1443  	if !u.IsStruct() && !u.IsInterface() {
  1444  		goto out
  1445  	}
  1446  
  1447  	for _, f := range u.Fields().Slice() {
  1448  		if f.Embedded == 0 || f.Sym == nil {
  1449  			continue
  1450  		}
  1451  		if d < 0 {
  1452  			// Found an embedded field at target depth.
  1453  			more = true
  1454  			goto out
  1455  		}
  1456  		a, more1 := adddot1(s, f.Type, d, save, ignorecase)
  1457  		if a != 0 && c == 0 {
  1458  			dotlist[d].field = f
  1459  		}
  1460  		c += a
  1461  		if more1 {
  1462  			more = true
  1463  		}
  1464  	}
  1465  
  1466  out:
  1467  	t.Trecur = 0
  1468  	return c, more
  1469  }
  1470  
  1471  // dotpath computes the unique shortest explicit selector path to fully qualify
  1472  // a selection expression x.f, where x is of type t and f is the symbol s.
  1473  // If no such path exists, dotpath returns nil.
  1474  // If there are multiple shortest paths to the same depth, ambig is true.
  1475  func dotpath(s *Sym, t *Type, save **Field, ignorecase bool) (path []Dlist, ambig bool) {
  1476  	// The embedding of types within structs imposes a tree structure onto
  1477  	// types: structs parent the types they embed, and types parent their
  1478  	// fields or methods. Our goal here is to find the shortest path to
  1479  	// a field or method named s in the subtree rooted at t. To accomplish
  1480  	// that, we iteratively perform depth-first searches of increasing depth
  1481  	// until we either find the named field/method or exhaust the tree.
  1482  	for d := 0; ; d++ {
  1483  		if d > len(dotlist) {
  1484  			dotlist = append(dotlist, Dlist{})
  1485  		}
  1486  		if c, more := adddot1(s, t, d, save, ignorecase); c == 1 {
  1487  			return dotlist[:d], false
  1488  		} else if c > 1 {
  1489  			return nil, true
  1490  		} else if !more {
  1491  			return nil, false
  1492  		}
  1493  	}
  1494  }
  1495  
  1496  // in T.field
  1497  // find missing fields that
  1498  // will give shortest unique addressing.
  1499  // modify the tree with missing type names.
  1500  func adddot(n *Node) *Node {
  1501  	n.Left = typecheck(n.Left, Etype|Erv)
  1502  	if n.Left.Diag {
  1503  		n.Diag = true
  1504  	}
  1505  	t := n.Left.Type
  1506  	if t == nil {
  1507  		return n
  1508  	}
  1509  
  1510  	if n.Left.Op == OTYPE {
  1511  		return n
  1512  	}
  1513  
  1514  	s := n.Sym
  1515  	if s == nil {
  1516  		return n
  1517  	}
  1518  
  1519  	switch path, ambig := dotpath(s, t, nil, false); {
  1520  	case path != nil:
  1521  		// rebuild elided dots
  1522  		for c := len(path) - 1; c >= 0; c-- {
  1523  			n.Left = nodSym(ODOT, n.Left, path[c].field.Sym)
  1524  			n.Left.Implicit = true
  1525  		}
  1526  	case ambig:
  1527  		yyerror("ambiguous selector %v", n)
  1528  		n.Left = nil
  1529  	}
  1530  
  1531  	return n
  1532  }
  1533  
  1534  // code to help generate trampoline
  1535  // functions for methods on embedded
  1536  // subtypes.
  1537  // these are approx the same as
  1538  // the corresponding adddot routines
  1539  // except that they expect to be called
  1540  // with unique tasks and they return
  1541  // the actual methods.
  1542  type Symlink struct {
  1543  	field     *Field
  1544  	followptr bool
  1545  }
  1546  
  1547  var slist []Symlink
  1548  
  1549  func expand0(t *Type, followptr bool) {
  1550  	u := t
  1551  	if u.IsPtr() {
  1552  		followptr = true
  1553  		u = u.Elem()
  1554  	}
  1555  
  1556  	if u.IsInterface() {
  1557  		for _, f := range u.Fields().Slice() {
  1558  			if f.Sym.Flags&SymUniq != 0 {
  1559  				continue
  1560  			}
  1561  			f.Sym.Flags |= SymUniq
  1562  			slist = append(slist, Symlink{field: f, followptr: followptr})
  1563  		}
  1564  
  1565  		return
  1566  	}
  1567  
  1568  	u = methtype(t)
  1569  	if u != nil {
  1570  		for _, f := range u.Methods().Slice() {
  1571  			if f.Sym.Flags&SymUniq != 0 {
  1572  				continue
  1573  			}
  1574  			f.Sym.Flags |= SymUniq
  1575  			slist = append(slist, Symlink{field: f, followptr: followptr})
  1576  		}
  1577  	}
  1578  }
  1579  
  1580  func expand1(t *Type, top, followptr bool) {
  1581  	if t.Trecur != 0 {
  1582  		return
  1583  	}
  1584  	t.Trecur = 1
  1585  
  1586  	if !top {
  1587  		expand0(t, followptr)
  1588  	}
  1589  
  1590  	u := t
  1591  	if u.IsPtr() {
  1592  		followptr = true
  1593  		u = u.Elem()
  1594  	}
  1595  
  1596  	if !u.IsStruct() && !u.IsInterface() {
  1597  		goto out
  1598  	}
  1599  
  1600  	for _, f := range u.Fields().Slice() {
  1601  		if f.Embedded == 0 {
  1602  			continue
  1603  		}
  1604  		if f.Sym == nil {
  1605  			continue
  1606  		}
  1607  		expand1(f.Type, false, followptr)
  1608  	}
  1609  
  1610  out:
  1611  	t.Trecur = 0
  1612  }
  1613  
  1614  func expandmeth(t *Type) {
  1615  	if t == nil || t.AllMethods().Len() != 0 {
  1616  		return
  1617  	}
  1618  
  1619  	// mark top-level method symbols
  1620  	// so that expand1 doesn't consider them.
  1621  	for _, f := range t.Methods().Slice() {
  1622  		f.Sym.Flags |= SymUniq
  1623  	}
  1624  
  1625  	// generate all reachable methods
  1626  	slist = slist[:0]
  1627  	expand1(t, true, false)
  1628  
  1629  	// check each method to be uniquely reachable
  1630  	var ms []*Field
  1631  	for i, sl := range slist {
  1632  		slist[i].field = nil
  1633  		sl.field.Sym.Flags &^= SymUniq
  1634  
  1635  		var f *Field
  1636  		if path, _ := dotpath(sl.field.Sym, t, &f, false); path == nil {
  1637  			continue
  1638  		}
  1639  
  1640  		// dotpath may have dug out arbitrary fields, we only want methods.
  1641  		if f.Type.Etype != TFUNC || f.Type.Recv() == nil {
  1642  			continue
  1643  		}
  1644  
  1645  		// add it to the base type method list
  1646  		f = f.Copy()
  1647  		f.Embedded = 1 // needs a trampoline
  1648  		if sl.followptr {
  1649  			f.Embedded = 2
  1650  		}
  1651  		ms = append(ms, f)
  1652  	}
  1653  
  1654  	for _, f := range t.Methods().Slice() {
  1655  		f.Sym.Flags &^= SymUniq
  1656  	}
  1657  
  1658  	ms = append(ms, t.Methods().Slice()...)
  1659  	t.AllMethods().Set(ms)
  1660  }
  1661  
  1662  // Given funarg struct list, return list of ODCLFIELD Node fn args.
  1663  func structargs(tl *Type, mustname bool) []*Node {
  1664  	var args []*Node
  1665  	gen := 0
  1666  	for _, t := range tl.Fields().Slice() {
  1667  		var n *Node
  1668  		if mustname && (t.Sym == nil || t.Sym.Name == "_") {
  1669  			// invent a name so that we can refer to it in the trampoline
  1670  			buf := fmt.Sprintf(".anon%d", gen)
  1671  			gen++
  1672  			n = newname(lookup(buf))
  1673  		} else if t.Sym != nil {
  1674  			n = newname(t.Sym)
  1675  		}
  1676  		a := nod(ODCLFIELD, n, typenod(t.Type))
  1677  		a.Isddd = t.Isddd
  1678  		if n != nil {
  1679  			n.Isddd = t.Isddd
  1680  		}
  1681  		args = append(args, a)
  1682  	}
  1683  
  1684  	return args
  1685  }
  1686  
  1687  // Generate a wrapper function to convert from
  1688  // a receiver of type T to a receiver of type U.
  1689  // That is,
  1690  //
  1691  //	func (t T) M() {
  1692  //		...
  1693  //	}
  1694  //
  1695  // already exists; this function generates
  1696  //
  1697  //	func (u U) M() {
  1698  //		u.M()
  1699  //	}
  1700  //
  1701  // where the types T and U are such that u.M() is valid
  1702  // and calls the T.M method.
  1703  // The resulting function is for use in method tables.
  1704  //
  1705  //	rcvr - U
  1706  //	method - M func (t T)(), a TFIELD type struct
  1707  //	newnam - the eventual mangled name of this function
  1708  
  1709  func genwrapper(rcvr *Type, method *Field, newnam *Sym, iface int) {
  1710  	if false && Debug['r'] != 0 {
  1711  		fmt.Printf("genwrapper rcvrtype=%v method=%v newnam=%v\n", rcvr, method, newnam)
  1712  	}
  1713  
  1714  	lineno = makePos(src.NewFileBase("<autogenerated>", "<autogenerated>"), 1, 0)
  1715  
  1716  	dclcontext = PEXTERN
  1717  	markdcl()
  1718  
  1719  	this := nod(ODCLFIELD, newname(lookup(".this")), typenod(rcvr))
  1720  	this.Left.Name.Param.Ntype = this.Right
  1721  	in := structargs(method.Type.Params(), true)
  1722  	out := structargs(method.Type.Results(), false)
  1723  
  1724  	t := nod(OTFUNC, nil, nil)
  1725  	l := []*Node{this}
  1726  	if iface != 0 && rcvr.Width < Types[Tptr].Width {
  1727  		// Building method for interface table and receiver
  1728  		// is smaller than the single pointer-sized word
  1729  		// that the interface call will pass in.
  1730  		// Add a dummy padding argument after the
  1731  		// receiver to make up the difference.
  1732  		tpad := typArray(Types[TUINT8], Types[Tptr].Width-rcvr.Width)
  1733  		pad := nod(ODCLFIELD, newname(lookup(".pad")), typenod(tpad))
  1734  		l = append(l, pad)
  1735  	}
  1736  
  1737  	t.List.Set(append(l, in...))
  1738  	t.Rlist.Set(out)
  1739  
  1740  	fn := nod(ODCLFUNC, nil, nil)
  1741  	fn.Func.Nname = newname(newnam)
  1742  	fn.Func.Nname.Name.Defn = fn
  1743  	fn.Func.Nname.Name.Param.Ntype = t
  1744  	declare(fn.Func.Nname, PFUNC)
  1745  	funchdr(fn)
  1746  
  1747  	// arg list
  1748  	var args []*Node
  1749  
  1750  	isddd := false
  1751  	for _, n := range in {
  1752  		args = append(args, n.Left)
  1753  		isddd = n.Left.Isddd
  1754  	}
  1755  
  1756  	methodrcvr := method.Type.Recv().Type
  1757  
  1758  	// generate nil pointer check for better error
  1759  	if rcvr.IsPtr() && rcvr.Elem() == methodrcvr {
  1760  		// generating wrapper from *T to T.
  1761  		n := nod(OIF, nil, nil)
  1762  		n.Left = nod(OEQ, this.Left, nodnil())
  1763  		call := nod(OCALL, syslook("panicwrap"), nil)
  1764  		n.Nbody.Set1(call)
  1765  		fn.Nbody.Append(n)
  1766  	}
  1767  
  1768  	dot := adddot(nodSym(OXDOT, this.Left, method.Sym))
  1769  
  1770  	// generate call
  1771  	// It's not possible to use a tail call when dynamic linking on ppc64le. The
  1772  	// bad scenario is when a local call is made to the wrapper: the wrapper will
  1773  	// call the implementation, which might be in a different module and so set
  1774  	// the TOC to the appropriate value for that module. But if it returns
  1775  	// directly to the wrapper's caller, nothing will reset it to the correct
  1776  	// value for that function.
  1777  	if !instrumenting && rcvr.IsPtr() && methodrcvr.IsPtr() && method.Embedded != 0 && !isifacemethod(method.Type) && !(Thearch.LinkArch.Name == "ppc64le" && Ctxt.Flag_dynlink) {
  1778  		// generate tail call: adjust pointer receiver and jump to embedded method.
  1779  		dot = dot.Left // skip final .M
  1780  		// TODO(mdempsky): Remove dependency on dotlist.
  1781  		if !dotlist[0].field.Type.IsPtr() {
  1782  			dot = nod(OADDR, dot, nil)
  1783  		}
  1784  		as := nod(OAS, this.Left, nod(OCONVNOP, dot, nil))
  1785  		as.Right.Type = rcvr
  1786  		fn.Nbody.Append(as)
  1787  		n := nod(ORETJMP, nil, nil)
  1788  		n.Left = newname(methodsym(method.Sym, methodrcvr, 0))
  1789  		fn.Nbody.Append(n)
  1790  		// When tail-calling, we can't use a frame pointer.
  1791  		fn.Func.NoFramePointer = true
  1792  	} else {
  1793  		fn.Func.Wrapper = true // ignore frame for panic+recover matching
  1794  		call := nod(OCALL, dot, nil)
  1795  		call.List.Set(args)
  1796  		call.Isddd = isddd
  1797  		if method.Type.Results().NumFields() > 0 {
  1798  			n := nod(ORETURN, nil, nil)
  1799  			n.List.Set1(call)
  1800  			call = n
  1801  		}
  1802  
  1803  		fn.Nbody.Append(call)
  1804  	}
  1805  
  1806  	if false && Debug['r'] != 0 {
  1807  		dumplist("genwrapper body", fn.Nbody)
  1808  	}
  1809  
  1810  	funcbody(fn)
  1811  	Curfn = fn
  1812  	popdcl()
  1813  	if debug_dclstack != 0 {
  1814  		testdclstack()
  1815  	}
  1816  
  1817  	// wrappers where T is anonymous (struct or interface) can be duplicated.
  1818  	if rcvr.IsStruct() || rcvr.IsInterface() || rcvr.IsPtr() && rcvr.Elem().IsStruct() {
  1819  		fn.Func.Dupok = true
  1820  	}
  1821  	fn = typecheck(fn, Etop)
  1822  	typecheckslice(fn.Nbody.Slice(), Etop)
  1823  
  1824  	inlcalls(fn)
  1825  	escAnalyze([]*Node{fn}, false)
  1826  
  1827  	Curfn = nil
  1828  	funccompile(fn)
  1829  }
  1830  
  1831  func hashmem(t *Type) *Node {
  1832  	sym := Pkglookup("memhash", Runtimepkg)
  1833  
  1834  	n := newname(sym)
  1835  	n.Class = PFUNC
  1836  	tfn := nod(OTFUNC, nil, nil)
  1837  	tfn.List.Append(nod(ODCLFIELD, nil, typenod(ptrto(t))))
  1838  	tfn.List.Append(nod(ODCLFIELD, nil, typenod(Types[TUINTPTR])))
  1839  	tfn.List.Append(nod(ODCLFIELD, nil, typenod(Types[TUINTPTR])))
  1840  	tfn.Rlist.Append(nod(ODCLFIELD, nil, typenod(Types[TUINTPTR])))
  1841  	tfn = typecheck(tfn, Etype)
  1842  	n.Type = tfn.Type
  1843  	return n
  1844  }
  1845  
  1846  func ifacelookdot(s *Sym, t *Type, followptr *bool, ignorecase bool) *Field {
  1847  	*followptr = false
  1848  
  1849  	if t == nil {
  1850  		return nil
  1851  	}
  1852  
  1853  	var m *Field
  1854  	path, ambig := dotpath(s, t, &m, ignorecase)
  1855  	if path == nil {
  1856  		if ambig {
  1857  			yyerror("%v.%v is ambiguous", t, s)
  1858  		}
  1859  		return nil
  1860  	}
  1861  
  1862  	for _, d := range path {
  1863  		if d.field.Type.IsPtr() {
  1864  			*followptr = true
  1865  			break
  1866  		}
  1867  	}
  1868  
  1869  	if m.Type.Etype != TFUNC || m.Type.Recv() == nil {
  1870  		yyerror("%v.%v is a field, not a method", t, s)
  1871  		return nil
  1872  	}
  1873  
  1874  	return m
  1875  }
  1876  
  1877  func implements(t, iface *Type, m, samename **Field, ptr *int) bool {
  1878  	t0 := t
  1879  	if t == nil {
  1880  		return false
  1881  	}
  1882  
  1883  	// if this is too slow,
  1884  	// could sort these first
  1885  	// and then do one loop.
  1886  
  1887  	if t.IsInterface() {
  1888  		for _, im := range iface.Fields().Slice() {
  1889  			for _, tm := range t.Fields().Slice() {
  1890  				if tm.Sym == im.Sym {
  1891  					if eqtype(tm.Type, im.Type) {
  1892  						goto found
  1893  					}
  1894  					*m = im
  1895  					*samename = tm
  1896  					*ptr = 0
  1897  					return false
  1898  				}
  1899  			}
  1900  
  1901  			*m = im
  1902  			*samename = nil
  1903  			*ptr = 0
  1904  			return false
  1905  		found:
  1906  		}
  1907  
  1908  		return true
  1909  	}
  1910  
  1911  	t = methtype(t)
  1912  	if t != nil {
  1913  		expandmeth(t)
  1914  	}
  1915  	for _, im := range iface.Fields().Slice() {
  1916  		if im.Broke {
  1917  			continue
  1918  		}
  1919  		var followptr bool
  1920  		tm := ifacelookdot(im.Sym, t, &followptr, false)
  1921  		if tm == nil || tm.Nointerface || !eqtype(tm.Type, im.Type) {
  1922  			if tm == nil {
  1923  				tm = ifacelookdot(im.Sym, t, &followptr, true)
  1924  			}
  1925  			*m = im
  1926  			*samename = tm
  1927  			*ptr = 0
  1928  			return false
  1929  		}
  1930  
  1931  		// if pointer receiver in method,
  1932  		// the method does not exist for value types.
  1933  		rcvr := tm.Type.Recv().Type
  1934  
  1935  		if rcvr.IsPtr() && !t0.IsPtr() && !followptr && !isifacemethod(tm.Type) {
  1936  			if false && Debug['r'] != 0 {
  1937  				yyerror("interface pointer mismatch")
  1938  			}
  1939  
  1940  			*m = im
  1941  			*samename = nil
  1942  			*ptr = 1
  1943  			return false
  1944  		}
  1945  	}
  1946  
  1947  	return true
  1948  }
  1949  
  1950  func listtreecopy(l []*Node, pos src.XPos) []*Node {
  1951  	var out []*Node
  1952  	for _, n := range l {
  1953  		out = append(out, treecopy(n, pos))
  1954  	}
  1955  	return out
  1956  }
  1957  
  1958  func liststmt(l []*Node) *Node {
  1959  	n := nod(OBLOCK, nil, nil)
  1960  	n.List.Set(l)
  1961  	if len(l) != 0 {
  1962  		n.Pos = l[0].Pos
  1963  	}
  1964  	return n
  1965  }
  1966  
  1967  // return power of 2 of the constant
  1968  // operand. -1 if it is not a power of 2.
  1969  // 1000+ if it is a -(power of 2)
  1970  func powtwo(n *Node) int {
  1971  	if n == nil || n.Op != OLITERAL || n.Type == nil {
  1972  		return -1
  1973  	}
  1974  	if !n.Type.IsInteger() {
  1975  		return -1
  1976  	}
  1977  
  1978  	v := uint64(n.Int64())
  1979  	b := uint64(1)
  1980  	for i := 0; i < 64; i++ {
  1981  		if b == v {
  1982  			return i
  1983  		}
  1984  		b = b << 1
  1985  	}
  1986  
  1987  	if !n.Type.IsSigned() {
  1988  		return -1
  1989  	}
  1990  
  1991  	v = -v
  1992  	b = 1
  1993  	for i := 0; i < 64; i++ {
  1994  		if b == v {
  1995  			return i + 1000
  1996  		}
  1997  		b = b << 1
  1998  	}
  1999  
  2000  	return -1
  2001  }
  2002  
  2003  func ngotype(n *Node) *Sym {
  2004  	if n.Type != nil {
  2005  		return typenamesym(n.Type)
  2006  	}
  2007  	return nil
  2008  }
  2009  
  2010  // Convert raw string to the prefix that will be used in the symbol
  2011  // table. All control characters, space, '%' and '"', as well as
  2012  // non-7-bit clean bytes turn into %xx. The period needs escaping
  2013  // only in the last segment of the path, and it makes for happier
  2014  // users if we escape that as little as possible.
  2015  //
  2016  // If you edit this, edit ../../debug/goobj/read.go:/importPathToPrefix too.
  2017  func pathtoprefix(s string) string {
  2018  	slash := strings.LastIndex(s, "/")
  2019  	for i := 0; i < len(s); i++ {
  2020  		c := s[i]
  2021  		if c <= ' ' || i >= slash && c == '.' || c == '%' || c == '"' || c >= 0x7F {
  2022  			var buf bytes.Buffer
  2023  			for i := 0; i < len(s); i++ {
  2024  				c := s[i]
  2025  				if c <= ' ' || i >= slash && c == '.' || c == '%' || c == '"' || c >= 0x7F {
  2026  					fmt.Fprintf(&buf, "%%%02x", c)
  2027  					continue
  2028  				}
  2029  				buf.WriteByte(c)
  2030  			}
  2031  			return buf.String()
  2032  		}
  2033  	}
  2034  	return s
  2035  }
  2036  
  2037  var pkgMap = make(map[string]*Pkg)
  2038  var pkgs []*Pkg
  2039  
  2040  func mkpkg(path string) *Pkg {
  2041  	if p := pkgMap[path]; p != nil {
  2042  		return p
  2043  	}
  2044  
  2045  	p := new(Pkg)
  2046  	p.Path = path
  2047  	p.Prefix = pathtoprefix(path)
  2048  	p.Syms = make(map[string]*Sym)
  2049  	pkgMap[path] = p
  2050  	pkgs = append(pkgs, p)
  2051  	return p
  2052  }
  2053  
  2054  // The result of addinit MUST be assigned back to n, e.g.
  2055  // 	n.Left = addinit(n.Left, init)
  2056  func addinit(n *Node, init []*Node) *Node {
  2057  	if len(init) == 0 {
  2058  		return n
  2059  	}
  2060  
  2061  	switch n.Op {
  2062  	// There may be multiple refs to this node;
  2063  	// introduce OCONVNOP to hold init list.
  2064  	case ONAME, OLITERAL:
  2065  		n = nod(OCONVNOP, n, nil)
  2066  		n.Type = n.Left.Type
  2067  		n.Typecheck = 1
  2068  	}
  2069  
  2070  	n.Ninit.Prepend(init...)
  2071  	n.Ullman = UINF
  2072  	return n
  2073  }
  2074  
  2075  var reservedimports = []string{
  2076  	"go",
  2077  	"type",
  2078  }
  2079  
  2080  func isbadimport(path string) bool {
  2081  	if strings.Contains(path, "\x00") {
  2082  		yyerror("import path contains NUL")
  2083  		return true
  2084  	}
  2085  
  2086  	for _, ri := range reservedimports {
  2087  		if path == ri {
  2088  			yyerror("import path %q is reserved and cannot be used", path)
  2089  			return true
  2090  		}
  2091  	}
  2092  
  2093  	for _, r := range path {
  2094  		if r == utf8.RuneError {
  2095  			yyerror("import path contains invalid UTF-8 sequence: %q", path)
  2096  			return true
  2097  		}
  2098  
  2099  		if r < 0x20 || r == 0x7f {
  2100  			yyerror("import path contains control character: %q", path)
  2101  			return true
  2102  		}
  2103  
  2104  		if r == '\\' {
  2105  			yyerror("import path contains backslash; use slash: %q", path)
  2106  			return true
  2107  		}
  2108  
  2109  		if unicode.IsSpace(r) {
  2110  			yyerror("import path contains space character: %q", path)
  2111  			return true
  2112  		}
  2113  
  2114  		if strings.ContainsRune("!\"#$%&'()*,:;<=>?[]^`{|}", r) {
  2115  			yyerror("import path contains invalid character '%c': %q", r, path)
  2116  			return true
  2117  		}
  2118  	}
  2119  
  2120  	return false
  2121  }
  2122  
  2123  func checknil(x *Node, init *Nodes) {
  2124  	x = walkexpr(x, nil) // caller has not done this yet
  2125  	if x.Type.IsInterface() {
  2126  		x = nod(OITAB, x, nil)
  2127  		x = typecheck(x, Erv)
  2128  	}
  2129  
  2130  	n := nod(OCHECKNIL, x, nil)
  2131  	n.Typecheck = 1
  2132  	init.Append(n)
  2133  }
  2134  
  2135  // Can this type be stored directly in an interface word?
  2136  // Yes, if the representation is a single pointer.
  2137  func isdirectiface(t *Type) bool {
  2138  	switch t.Etype {
  2139  	case TPTR32,
  2140  		TPTR64,
  2141  		TCHAN,
  2142  		TMAP,
  2143  		TFUNC,
  2144  		TUNSAFEPTR:
  2145  		return true
  2146  
  2147  	case TARRAY:
  2148  		// Array of 1 direct iface type can be direct.
  2149  		return t.NumElem() == 1 && isdirectiface(t.Elem())
  2150  
  2151  	case TSTRUCT:
  2152  		// Struct with 1 field of direct iface type can be direct.
  2153  		return t.NumFields() == 1 && isdirectiface(t.Field(0).Type)
  2154  	}
  2155  
  2156  	return false
  2157  }
  2158  
  2159  // itabType loads the _type field from a runtime.itab struct.
  2160  func itabType(itab *Node) *Node {
  2161  	typ := nodSym(ODOTPTR, itab, nil)
  2162  	typ.Type = ptrto(Types[TUINT8])
  2163  	typ.Typecheck = 1
  2164  	typ.Xoffset = int64(Widthptr) // offset of _type in runtime.itab
  2165  	typ.Bounded = true            // guaranteed not to fault
  2166  	return typ
  2167  }
  2168  
  2169  // ifaceData loads the data field from an interface.
  2170  // The concrete type must be known to have type t.
  2171  // It follows the pointer if !isdirectiface(t).
  2172  func ifaceData(n *Node, t *Type) *Node {
  2173  	ptr := nodSym(OIDATA, n, nil)
  2174  	if isdirectiface(t) {
  2175  		ptr.Type = t
  2176  		ptr.Typecheck = 1
  2177  		return ptr
  2178  	}
  2179  	ptr.Type = ptrto(t)
  2180  	ptr.Bounded = true
  2181  	ptr.Typecheck = 1
  2182  	ind := nod(OIND, ptr, nil)
  2183  	ind.Type = t
  2184  	ind.Typecheck = 1
  2185  	return ind
  2186  }
  2187  
  2188  // iet returns 'T' if t is a concrete type,
  2189  // 'I' if t is an interface type, and 'E' if t is an empty interface type.
  2190  // It is used to build calls to the conv* and assert* runtime routines.
  2191  func (t *Type) iet() byte {
  2192  	if t.IsEmptyInterface() {
  2193  		return 'E'
  2194  	}
  2195  	if t.IsInterface() {
  2196  		return 'I'
  2197  	}
  2198  	return 'T'
  2199  }