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