github.com/panjjo/go@v0.0.0-20161104043856-d62b31386338/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 case OINDEX, OSLICE, OSLICEARR, OSLICE3, OSLICE3ARR, OSLICESTR, 1186 OIND, ODOTPTR, ODOTTYPE, ODIV, OMOD: 1187 // These ops might panic, make sure they are done 1188 // before we start marshaling args for a call. See issue 16760. 1189 ul = UINF 1190 goto out 1191 } 1192 1193 ul = 1 1194 if n.Left != nil { 1195 ul = int(n.Left.Ullman) 1196 } 1197 ur = 1 1198 if n.Right != nil { 1199 ur = int(n.Right.Ullman) 1200 } 1201 if ul == ur { 1202 ul += 1 1203 } 1204 if ur > ul { 1205 ul = ur 1206 } 1207 1208 out: 1209 if ul > 200 { 1210 ul = 200 // clamp to uchar with room to grow 1211 } 1212 n.Ullman = uint8(ul) 1213 } 1214 1215 func badtype(op Op, tl *Type, tr *Type) { 1216 fmt_ := "" 1217 if tl != nil { 1218 fmt_ += fmt.Sprintf("\n\t%v", tl) 1219 } 1220 if tr != nil { 1221 fmt_ += fmt.Sprintf("\n\t%v", tr) 1222 } 1223 1224 // common mistake: *struct and *interface. 1225 if tl != nil && tr != nil && tl.IsPtr() && tr.IsPtr() { 1226 if tl.Elem().IsStruct() && tr.Elem().IsInterface() { 1227 fmt_ += "\n\t(*struct vs *interface)" 1228 } else if tl.Elem().IsInterface() && tr.Elem().IsStruct() { 1229 fmt_ += "\n\t(*interface vs *struct)" 1230 } 1231 } 1232 1233 s := fmt_ 1234 yyerror("illegal types for operand: %v%s", op, s) 1235 } 1236 1237 // brcom returns !(op). 1238 // For example, brcom(==) is !=. 1239 func brcom(op Op) Op { 1240 switch op { 1241 case OEQ: 1242 return ONE 1243 case ONE: 1244 return OEQ 1245 case OLT: 1246 return OGE 1247 case OGT: 1248 return OLE 1249 case OLE: 1250 return OGT 1251 case OGE: 1252 return OLT 1253 } 1254 Fatalf("brcom: no com for %v\n", op) 1255 return op 1256 } 1257 1258 // brrev returns reverse(op). 1259 // For example, Brrev(<) is >. 1260 func brrev(op Op) Op { 1261 switch op { 1262 case OEQ: 1263 return OEQ 1264 case ONE: 1265 return ONE 1266 case OLT: 1267 return OGT 1268 case OGT: 1269 return OLT 1270 case OLE: 1271 return OGE 1272 case OGE: 1273 return OLE 1274 } 1275 Fatalf("brrev: no rev for %v\n", op) 1276 return op 1277 } 1278 1279 // return side effect-free n, appending side effects to init. 1280 // result is assignable if n is. 1281 func safeexpr(n *Node, init *Nodes) *Node { 1282 if n == nil { 1283 return nil 1284 } 1285 1286 if n.Ninit.Len() != 0 { 1287 walkstmtlist(n.Ninit.Slice()) 1288 init.AppendNodes(&n.Ninit) 1289 } 1290 1291 switch n.Op { 1292 case ONAME, OLITERAL: 1293 return n 1294 1295 case ODOT, OLEN, OCAP: 1296 l := safeexpr(n.Left, init) 1297 if l == n.Left { 1298 return n 1299 } 1300 r := nod(OXXX, nil, nil) 1301 *r = *n 1302 r.Left = l 1303 r = typecheck(r, Erv) 1304 r = walkexpr(r, init) 1305 return r 1306 1307 case ODOTPTR, OIND: 1308 l := safeexpr(n.Left, init) 1309 if l == n.Left { 1310 return n 1311 } 1312 a := nod(OXXX, nil, nil) 1313 *a = *n 1314 a.Left = l 1315 a = walkexpr(a, init) 1316 return a 1317 1318 case OINDEX, OINDEXMAP: 1319 l := safeexpr(n.Left, init) 1320 r := safeexpr(n.Right, init) 1321 if l == n.Left && r == n.Right { 1322 return n 1323 } 1324 a := nod(OXXX, nil, nil) 1325 *a = *n 1326 a.Left = l 1327 a.Right = r 1328 a = walkexpr(a, init) 1329 return a 1330 1331 case OSTRUCTLIT, OARRAYLIT, OSLICELIT: 1332 if isStaticCompositeLiteral(n) { 1333 return n 1334 } 1335 } 1336 1337 // make a copy; must not be used as an lvalue 1338 if islvalue(n) { 1339 Fatalf("missing lvalue case in safeexpr: %v", n) 1340 } 1341 return cheapexpr(n, init) 1342 } 1343 1344 func copyexpr(n *Node, t *Type, init *Nodes) *Node { 1345 l := temp(t) 1346 a := nod(OAS, l, n) 1347 a = typecheck(a, Etop) 1348 a = walkexpr(a, init) 1349 init.Append(a) 1350 return l 1351 } 1352 1353 // return side-effect free and cheap n, appending side effects to init. 1354 // result may not be assignable. 1355 func cheapexpr(n *Node, init *Nodes) *Node { 1356 switch n.Op { 1357 case ONAME, OLITERAL: 1358 return n 1359 } 1360 1361 return copyexpr(n, n.Type, init) 1362 } 1363 1364 // Code to resolve elided DOTs in embedded types. 1365 1366 // A Dlist stores a pointer to a TFIELD Type embedded within 1367 // a TSTRUCT or TINTER Type. 1368 type Dlist struct { 1369 field *Field 1370 } 1371 1372 // dotlist is used by adddot1 to record the path of embedded fields 1373 // used to access a target field or method. 1374 // Must be non-nil so that dotpath returns a non-nil slice even if d is zero. 1375 var dotlist = make([]Dlist, 10) 1376 1377 // lookdot0 returns the number of fields or methods named s associated 1378 // with Type t. If exactly one exists, it will be returned in *save 1379 // (if save is not nil). 1380 func lookdot0(s *Sym, t *Type, save **Field, ignorecase bool) int { 1381 u := t 1382 if u.IsPtr() { 1383 u = u.Elem() 1384 } 1385 1386 c := 0 1387 if u.IsStruct() || u.IsInterface() { 1388 for _, f := range u.Fields().Slice() { 1389 if f.Sym == s || (ignorecase && f.Type.Etype == TFUNC && f.Type.Recv() != nil && strings.EqualFold(f.Sym.Name, s.Name)) { 1390 if save != nil { 1391 *save = f 1392 } 1393 c++ 1394 } 1395 } 1396 } 1397 1398 u = methtype(t) 1399 if u != nil { 1400 for _, f := range u.Methods().Slice() { 1401 if f.Embedded == 0 && (f.Sym == s || (ignorecase && strings.EqualFold(f.Sym.Name, s.Name))) { 1402 if save != nil { 1403 *save = f 1404 } 1405 c++ 1406 } 1407 } 1408 } 1409 1410 return c 1411 } 1412 1413 // adddot1 returns the number of fields or methods named s at depth d in Type t. 1414 // If exactly one exists, it will be returned in *save (if save is not nil), 1415 // and dotlist will contain the path of embedded fields traversed to find it, 1416 // in reverse order. If none exist, more will indicate whether t contains any 1417 // embedded fields at depth d, so callers can decide whether to retry at 1418 // a greater depth. 1419 func adddot1(s *Sym, t *Type, d int, save **Field, ignorecase bool) (c int, more bool) { 1420 if t.Trecur != 0 { 1421 return 1422 } 1423 t.Trecur = 1 1424 1425 var u *Type 1426 d-- 1427 if d < 0 { 1428 // We've reached our target depth. If t has any fields/methods 1429 // named s, then we're done. Otherwise, we still need to check 1430 // below for embedded fields. 1431 c = lookdot0(s, t, save, ignorecase) 1432 if c != 0 { 1433 goto out 1434 } 1435 } 1436 1437 u = t 1438 if u.IsPtr() { 1439 u = u.Elem() 1440 } 1441 if !u.IsStruct() && !u.IsInterface() { 1442 goto out 1443 } 1444 1445 for _, f := range u.Fields().Slice() { 1446 if f.Embedded == 0 || f.Sym == nil { 1447 continue 1448 } 1449 if d < 0 { 1450 // Found an embedded field at target depth. 1451 more = true 1452 goto out 1453 } 1454 a, more1 := adddot1(s, f.Type, d, save, ignorecase) 1455 if a != 0 && c == 0 { 1456 dotlist[d].field = f 1457 } 1458 c += a 1459 if more1 { 1460 more = true 1461 } 1462 } 1463 1464 out: 1465 t.Trecur = 0 1466 return c, more 1467 } 1468 1469 // dotpath computes the unique shortest explicit selector path to fully qualify 1470 // a selection expression x.f, where x is of type t and f is the symbol s. 1471 // If no such path exists, dotpath returns nil. 1472 // If there are multiple shortest paths to the same depth, ambig is true. 1473 func dotpath(s *Sym, t *Type, save **Field, ignorecase bool) (path []Dlist, ambig bool) { 1474 // The embedding of types within structs imposes a tree structure onto 1475 // types: structs parent the types they embed, and types parent their 1476 // fields or methods. Our goal here is to find the shortest path to 1477 // a field or method named s in the subtree rooted at t. To accomplish 1478 // that, we iteratively perform depth-first searches of increasing depth 1479 // until we either find the named field/method or exhaust the tree. 1480 for d := 0; ; d++ { 1481 if d > len(dotlist) { 1482 dotlist = append(dotlist, Dlist{}) 1483 } 1484 if c, more := adddot1(s, t, d, save, ignorecase); c == 1 { 1485 return dotlist[:d], false 1486 } else if c > 1 { 1487 return nil, true 1488 } else if !more { 1489 return nil, false 1490 } 1491 } 1492 } 1493 1494 // in T.field 1495 // find missing fields that 1496 // will give shortest unique addressing. 1497 // modify the tree with missing type names. 1498 func adddot(n *Node) *Node { 1499 n.Left = typecheck(n.Left, Etype|Erv) 1500 if n.Left.Diag { 1501 n.Diag = true 1502 } 1503 t := n.Left.Type 1504 if t == nil { 1505 return n 1506 } 1507 1508 if n.Left.Op == OTYPE { 1509 return n 1510 } 1511 1512 s := n.Sym 1513 if s == nil { 1514 return n 1515 } 1516 1517 switch path, ambig := dotpath(s, t, nil, false); { 1518 case path != nil: 1519 // rebuild elided dots 1520 for c := len(path) - 1; c >= 0; c-- { 1521 n.Left = nodSym(ODOT, n.Left, path[c].field.Sym) 1522 n.Left.Implicit = true 1523 } 1524 case ambig: 1525 yyerror("ambiguous selector %v", n) 1526 n.Left = nil 1527 } 1528 1529 return n 1530 } 1531 1532 // code to help generate trampoline 1533 // functions for methods on embedded 1534 // subtypes. 1535 // these are approx the same as 1536 // the corresponding adddot routines 1537 // except that they expect to be called 1538 // with unique tasks and they return 1539 // the actual methods. 1540 type Symlink struct { 1541 field *Field 1542 followptr bool 1543 } 1544 1545 var slist []Symlink 1546 1547 func expand0(t *Type, followptr bool) { 1548 u := t 1549 if u.IsPtr() { 1550 followptr = true 1551 u = u.Elem() 1552 } 1553 1554 if u.IsInterface() { 1555 for _, f := range u.Fields().Slice() { 1556 if f.Sym.Flags&SymUniq != 0 { 1557 continue 1558 } 1559 f.Sym.Flags |= SymUniq 1560 slist = append(slist, Symlink{field: f, followptr: followptr}) 1561 } 1562 1563 return 1564 } 1565 1566 u = methtype(t) 1567 if u != nil { 1568 for _, f := range u.Methods().Slice() { 1569 if f.Sym.Flags&SymUniq != 0 { 1570 continue 1571 } 1572 f.Sym.Flags |= SymUniq 1573 slist = append(slist, Symlink{field: f, followptr: followptr}) 1574 } 1575 } 1576 } 1577 1578 func expand1(t *Type, top, followptr bool) { 1579 if t.Trecur != 0 { 1580 return 1581 } 1582 t.Trecur = 1 1583 1584 if !top { 1585 expand0(t, followptr) 1586 } 1587 1588 u := t 1589 if u.IsPtr() { 1590 followptr = true 1591 u = u.Elem() 1592 } 1593 1594 if !u.IsStruct() && !u.IsInterface() { 1595 goto out 1596 } 1597 1598 for _, f := range u.Fields().Slice() { 1599 if f.Embedded == 0 { 1600 continue 1601 } 1602 if f.Sym == nil { 1603 continue 1604 } 1605 expand1(f.Type, false, followptr) 1606 } 1607 1608 out: 1609 t.Trecur = 0 1610 } 1611 1612 func expandmeth(t *Type) { 1613 if t == nil || t.AllMethods().Len() != 0 { 1614 return 1615 } 1616 1617 // mark top-level method symbols 1618 // so that expand1 doesn't consider them. 1619 for _, f := range t.Methods().Slice() { 1620 f.Sym.Flags |= SymUniq 1621 } 1622 1623 // generate all reachable methods 1624 slist = slist[:0] 1625 expand1(t, true, false) 1626 1627 // check each method to be uniquely reachable 1628 var ms []*Field 1629 for i, sl := range slist { 1630 slist[i].field = nil 1631 sl.field.Sym.Flags &^= SymUniq 1632 1633 var f *Field 1634 if path, _ := dotpath(sl.field.Sym, t, &f, false); path == nil { 1635 continue 1636 } 1637 1638 // dotpath may have dug out arbitrary fields, we only want methods. 1639 if f.Type.Etype != TFUNC || f.Type.Recv() == nil { 1640 continue 1641 } 1642 1643 // add it to the base type method list 1644 f = f.Copy() 1645 f.Embedded = 1 // needs a trampoline 1646 if sl.followptr { 1647 f.Embedded = 2 1648 } 1649 ms = append(ms, f) 1650 } 1651 1652 for _, f := range t.Methods().Slice() { 1653 f.Sym.Flags &^= SymUniq 1654 } 1655 1656 ms = append(ms, t.Methods().Slice()...) 1657 t.AllMethods().Set(ms) 1658 } 1659 1660 // Given funarg struct list, return list of ODCLFIELD Node fn args. 1661 func structargs(tl *Type, mustname bool) []*Node { 1662 var args []*Node 1663 gen := 0 1664 for _, t := range tl.Fields().Slice() { 1665 var n *Node 1666 if mustname && (t.Sym == nil || t.Sym.Name == "_") { 1667 // invent a name so that we can refer to it in the trampoline 1668 buf := fmt.Sprintf(".anon%d", gen) 1669 gen++ 1670 n = newname(lookup(buf)) 1671 } else if t.Sym != nil { 1672 n = newname(t.Sym) 1673 } 1674 a := nod(ODCLFIELD, n, typenod(t.Type)) 1675 a.Isddd = t.Isddd 1676 if n != nil { 1677 n.Isddd = t.Isddd 1678 } 1679 args = append(args, a) 1680 } 1681 1682 return args 1683 } 1684 1685 // Generate a wrapper function to convert from 1686 // a receiver of type T to a receiver of type U. 1687 // That is, 1688 // 1689 // func (t T) M() { 1690 // ... 1691 // } 1692 // 1693 // already exists; this function generates 1694 // 1695 // func (u U) M() { 1696 // u.M() 1697 // } 1698 // 1699 // where the types T and U are such that u.M() is valid 1700 // and calls the T.M method. 1701 // The resulting function is for use in method tables. 1702 // 1703 // rcvr - U 1704 // method - M func (t T)(), a TFIELD type struct 1705 // newnam - the eventual mangled name of this function 1706 1707 var genwrapper_linehistdone int = 0 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 lexlineno++ 1715 lineno = lexlineno 1716 if genwrapper_linehistdone == 0 { 1717 // All the wrappers can share the same linehist entry. 1718 linehistpush("<autogenerated>") 1719 1720 genwrapper_linehistdone = 1 1721 } 1722 1723 dclcontext = PEXTERN 1724 markdcl() 1725 1726 this := nod(ODCLFIELD, newname(lookup(".this")), typenod(rcvr)) 1727 this.Left.Name.Param.Ntype = this.Right 1728 in := structargs(method.Type.Params(), true) 1729 out := structargs(method.Type.Results(), false) 1730 1731 t := nod(OTFUNC, nil, nil) 1732 l := []*Node{this} 1733 if iface != 0 && rcvr.Width < Types[Tptr].Width { 1734 // Building method for interface table and receiver 1735 // is smaller than the single pointer-sized word 1736 // that the interface call will pass in. 1737 // Add a dummy padding argument after the 1738 // receiver to make up the difference. 1739 tpad := typArray(Types[TUINT8], Types[Tptr].Width-rcvr.Width) 1740 pad := nod(ODCLFIELD, newname(lookup(".pad")), typenod(tpad)) 1741 l = append(l, pad) 1742 } 1743 1744 t.List.Set(append(l, in...)) 1745 t.Rlist.Set(out) 1746 1747 fn := nod(ODCLFUNC, nil, nil) 1748 fn.Func.Nname = newname(newnam) 1749 fn.Func.Nname.Name.Defn = fn 1750 fn.Func.Nname.Name.Param.Ntype = t 1751 declare(fn.Func.Nname, PFUNC) 1752 funchdr(fn) 1753 1754 // arg list 1755 var args []*Node 1756 1757 isddd := false 1758 for _, n := range in { 1759 args = append(args, n.Left) 1760 isddd = n.Left.Isddd 1761 } 1762 1763 methodrcvr := method.Type.Recv().Type 1764 1765 // generate nil pointer check for better error 1766 if rcvr.IsPtr() && rcvr.Elem() == methodrcvr { 1767 // generating wrapper from *T to T. 1768 n := nod(OIF, nil, nil) 1769 1770 n.Left = nod(OEQ, this.Left, nodnil()) 1771 1772 // these strings are already in the reflect tables, 1773 // so no space cost to use them here. 1774 var l []*Node 1775 1776 var v Val 1777 v.U = rcvr.Elem().Sym.Pkg.Name // package name 1778 l = append(l, nodlit(v)) 1779 v.U = rcvr.Elem().Sym.Name // type name 1780 l = append(l, nodlit(v)) 1781 v.U = method.Sym.Name 1782 l = append(l, nodlit(v)) // method name 1783 call := nod(OCALL, syslook("panicwrap"), nil) 1784 call.List.Set(l) 1785 n.Nbody.Set1(call) 1786 fn.Nbody.Append(n) 1787 } 1788 1789 dot := adddot(nodSym(OXDOT, this.Left, method.Sym)) 1790 1791 // generate call 1792 // It's not possible to use a tail call when dynamic linking on ppc64le. The 1793 // bad scenario is when a local call is made to the wrapper: the wrapper will 1794 // call the implementation, which might be in a different module and so set 1795 // the TOC to the appropriate value for that module. But if it returns 1796 // directly to the wrapper's caller, nothing will reset it to the correct 1797 // value for that function. 1798 if !instrumenting && rcvr.IsPtr() && methodrcvr.IsPtr() && method.Embedded != 0 && !isifacemethod(method.Type) && !(Thearch.LinkArch.Name == "ppc64le" && Ctxt.Flag_dynlink) { 1799 // generate tail call: adjust pointer receiver and jump to embedded method. 1800 dot = dot.Left // skip final .M 1801 // TODO(mdempsky): Remove dependency on dotlist. 1802 if !dotlist[0].field.Type.IsPtr() { 1803 dot = nod(OADDR, dot, nil) 1804 } 1805 as := nod(OAS, this.Left, nod(OCONVNOP, dot, nil)) 1806 as.Right.Type = rcvr 1807 fn.Nbody.Append(as) 1808 n := nod(ORETJMP, nil, nil) 1809 n.Left = newname(methodsym(method.Sym, methodrcvr, 0)) 1810 fn.Nbody.Append(n) 1811 } else { 1812 fn.Func.Wrapper = true // ignore frame for panic+recover matching 1813 call := nod(OCALL, dot, nil) 1814 call.List.Set(args) 1815 call.Isddd = isddd 1816 if method.Type.Results().NumFields() > 0 { 1817 n := nod(ORETURN, nil, nil) 1818 n.List.Set1(call) 1819 call = n 1820 } 1821 1822 fn.Nbody.Append(call) 1823 } 1824 1825 if false && Debug['r'] != 0 { 1826 dumplist("genwrapper body", fn.Nbody) 1827 } 1828 1829 funcbody(fn) 1830 Curfn = fn 1831 popdcl() 1832 testdclstack() 1833 1834 // wrappers where T is anonymous (struct or interface) can be duplicated. 1835 if rcvr.IsStruct() || rcvr.IsInterface() || rcvr.IsPtr() && rcvr.Elem().IsStruct() { 1836 fn.Func.Dupok = true 1837 } 1838 fn = typecheck(fn, Etop) 1839 typecheckslice(fn.Nbody.Slice(), Etop) 1840 1841 inlcalls(fn) 1842 escAnalyze([]*Node{fn}, false) 1843 1844 Curfn = nil 1845 funccompile(fn) 1846 } 1847 1848 func hashmem(t *Type) *Node { 1849 sym := Pkglookup("memhash", Runtimepkg) 1850 1851 n := newname(sym) 1852 n.Class = PFUNC 1853 tfn := nod(OTFUNC, nil, nil) 1854 tfn.List.Append(nod(ODCLFIELD, nil, typenod(ptrto(t)))) 1855 tfn.List.Append(nod(ODCLFIELD, nil, typenod(Types[TUINTPTR]))) 1856 tfn.List.Append(nod(ODCLFIELD, nil, typenod(Types[TUINTPTR]))) 1857 tfn.Rlist.Append(nod(ODCLFIELD, nil, typenod(Types[TUINTPTR]))) 1858 tfn = typecheck(tfn, Etype) 1859 n.Type = tfn.Type 1860 return n 1861 } 1862 1863 func ifacelookdot(s *Sym, t *Type, followptr *bool, ignorecase bool) *Field { 1864 *followptr = false 1865 1866 if t == nil { 1867 return nil 1868 } 1869 1870 var m *Field 1871 path, ambig := dotpath(s, t, &m, ignorecase) 1872 if path == nil { 1873 if ambig { 1874 yyerror("%v.%v is ambiguous", t, s) 1875 } 1876 return nil 1877 } 1878 1879 for _, d := range path { 1880 if d.field.Type.IsPtr() { 1881 *followptr = true 1882 break 1883 } 1884 } 1885 1886 if m.Type.Etype != TFUNC || m.Type.Recv() == nil { 1887 yyerror("%v.%v is a field, not a method", t, s) 1888 return nil 1889 } 1890 1891 return m 1892 } 1893 1894 func implements(t, iface *Type, m, samename **Field, ptr *int) bool { 1895 t0 := t 1896 if t == nil { 1897 return false 1898 } 1899 1900 // if this is too slow, 1901 // could sort these first 1902 // and then do one loop. 1903 1904 if t.IsInterface() { 1905 for _, im := range iface.Fields().Slice() { 1906 for _, tm := range t.Fields().Slice() { 1907 if tm.Sym == im.Sym { 1908 if eqtype(tm.Type, im.Type) { 1909 goto found 1910 } 1911 *m = im 1912 *samename = tm 1913 *ptr = 0 1914 return false 1915 } 1916 } 1917 1918 *m = im 1919 *samename = nil 1920 *ptr = 0 1921 return false 1922 found: 1923 } 1924 1925 return true 1926 } 1927 1928 t = methtype(t) 1929 if t != nil { 1930 expandmeth(t) 1931 } 1932 for _, im := range iface.Fields().Slice() { 1933 if im.Broke { 1934 continue 1935 } 1936 var followptr bool 1937 tm := ifacelookdot(im.Sym, t, &followptr, false) 1938 if tm == nil || tm.Nointerface || !eqtype(tm.Type, im.Type) { 1939 if tm == nil { 1940 tm = ifacelookdot(im.Sym, t, &followptr, true) 1941 } 1942 *m = im 1943 *samename = tm 1944 *ptr = 0 1945 return false 1946 } 1947 1948 // if pointer receiver in method, 1949 // the method does not exist for value types. 1950 rcvr := tm.Type.Recv().Type 1951 1952 if rcvr.IsPtr() && !t0.IsPtr() && !followptr && !isifacemethod(tm.Type) { 1953 if false && Debug['r'] != 0 { 1954 yyerror("interface pointer mismatch") 1955 } 1956 1957 *m = im 1958 *samename = nil 1959 *ptr = 1 1960 return false 1961 } 1962 } 1963 1964 return true 1965 } 1966 1967 // even simpler simtype; get rid of ptr, bool. 1968 // assuming that the front end has rejected 1969 // all the invalid conversions (like ptr -> bool) 1970 func Simsimtype(t *Type) EType { 1971 if t == nil { 1972 return 0 1973 } 1974 1975 et := simtype[t.Etype] 1976 switch et { 1977 case TPTR32: 1978 et = TUINT32 1979 1980 case TPTR64: 1981 et = TUINT64 1982 1983 case TBOOL: 1984 et = TUINT8 1985 } 1986 1987 return et 1988 } 1989 1990 func listtreecopy(l []*Node, lineno int32) []*Node { 1991 var out []*Node 1992 for _, n := range l { 1993 out = append(out, treecopy(n, lineno)) 1994 } 1995 return out 1996 } 1997 1998 func liststmt(l []*Node) *Node { 1999 n := nod(OBLOCK, nil, nil) 2000 n.List.Set(l) 2001 if len(l) != 0 { 2002 n.Lineno = l[0].Lineno 2003 } 2004 return n 2005 } 2006 2007 // return power of 2 of the constant 2008 // operand. -1 if it is not a power of 2. 2009 // 1000+ if it is a -(power of 2) 2010 func powtwo(n *Node) int { 2011 if n == nil || n.Op != OLITERAL || n.Type == nil { 2012 return -1 2013 } 2014 if !n.Type.IsInteger() { 2015 return -1 2016 } 2017 2018 v := uint64(n.Int64()) 2019 b := uint64(1) 2020 for i := 0; i < 64; i++ { 2021 if b == v { 2022 return i 2023 } 2024 b = b << 1 2025 } 2026 2027 if !n.Type.IsSigned() { 2028 return -1 2029 } 2030 2031 v = -v 2032 b = 1 2033 for i := 0; i < 64; i++ { 2034 if b == v { 2035 return i + 1000 2036 } 2037 b = b << 1 2038 } 2039 2040 return -1 2041 } 2042 2043 func ngotype(n *Node) *Sym { 2044 if n.Type != nil { 2045 return typenamesym(n.Type) 2046 } 2047 return nil 2048 } 2049 2050 // Convert raw string to the prefix that will be used in the symbol 2051 // table. All control characters, space, '%' and '"', as well as 2052 // non-7-bit clean bytes turn into %xx. The period needs escaping 2053 // only in the last segment of the path, and it makes for happier 2054 // users if we escape that as little as possible. 2055 // 2056 // If you edit this, edit ../../debug/goobj/read.go:/importPathToPrefix too. 2057 func pathtoprefix(s string) string { 2058 slash := strings.LastIndex(s, "/") 2059 for i := 0; i < len(s); i++ { 2060 c := s[i] 2061 if c <= ' ' || i >= slash && c == '.' || c == '%' || c == '"' || c >= 0x7F { 2062 var buf bytes.Buffer 2063 for i := 0; i < len(s); i++ { 2064 c := s[i] 2065 if c <= ' ' || i >= slash && c == '.' || c == '%' || c == '"' || c >= 0x7F { 2066 fmt.Fprintf(&buf, "%%%02x", c) 2067 continue 2068 } 2069 buf.WriteByte(c) 2070 } 2071 return buf.String() 2072 } 2073 } 2074 return s 2075 } 2076 2077 var pkgMap = make(map[string]*Pkg) 2078 var pkgs []*Pkg 2079 2080 func mkpkg(path string) *Pkg { 2081 if p := pkgMap[path]; p != nil { 2082 return p 2083 } 2084 2085 p := new(Pkg) 2086 p.Path = path 2087 p.Prefix = pathtoprefix(path) 2088 p.Syms = make(map[string]*Sym) 2089 pkgMap[path] = p 2090 pkgs = append(pkgs, p) 2091 return p 2092 } 2093 2094 // The result of addinit MUST be assigned back to n, e.g. 2095 // n.Left = addinit(n.Left, init) 2096 func addinit(n *Node, init []*Node) *Node { 2097 if len(init) == 0 { 2098 return n 2099 } 2100 2101 switch n.Op { 2102 // There may be multiple refs to this node; 2103 // introduce OCONVNOP to hold init list. 2104 case ONAME, OLITERAL: 2105 n = nod(OCONVNOP, n, nil) 2106 n.Type = n.Left.Type 2107 n.Typecheck = 1 2108 } 2109 2110 n.Ninit.Prepend(init...) 2111 n.Ullman = UINF 2112 return n 2113 } 2114 2115 var reservedimports = []string{ 2116 "go", 2117 "type", 2118 } 2119 2120 func isbadimport(path string) bool { 2121 if strings.Contains(path, "\x00") { 2122 yyerror("import path contains NUL") 2123 return true 2124 } 2125 2126 for _, ri := range reservedimports { 2127 if path == ri { 2128 yyerror("import path %q is reserved and cannot be used", path) 2129 return true 2130 } 2131 } 2132 2133 for _, r := range path { 2134 if r == utf8.RuneError { 2135 yyerror("import path contains invalid UTF-8 sequence: %q", path) 2136 return true 2137 } 2138 2139 if r < 0x20 || r == 0x7f { 2140 yyerror("import path contains control character: %q", path) 2141 return true 2142 } 2143 2144 if r == '\\' { 2145 yyerror("import path contains backslash; use slash: %q", path) 2146 return true 2147 } 2148 2149 if unicode.IsSpace(r) { 2150 yyerror("import path contains space character: %q", path) 2151 return true 2152 } 2153 2154 if strings.ContainsRune("!\"#$%&'()*,:;<=>?[]^`{|}", r) { 2155 yyerror("import path contains invalid character '%c': %q", r, path) 2156 return true 2157 } 2158 } 2159 2160 return false 2161 } 2162 2163 func checknil(x *Node, init *Nodes) { 2164 x = walkexpr(x, nil) // caller has not done this yet 2165 if x.Type.IsInterface() { 2166 x = nod(OITAB, x, nil) 2167 x = typecheck(x, Erv) 2168 } 2169 2170 n := nod(OCHECKNIL, x, nil) 2171 n.Typecheck = 1 2172 init.Append(n) 2173 } 2174 2175 // Can this type be stored directly in an interface word? 2176 // Yes, if the representation is a single pointer. 2177 func isdirectiface(t *Type) bool { 2178 switch t.Etype { 2179 case TPTR32, 2180 TPTR64, 2181 TCHAN, 2182 TMAP, 2183 TFUNC, 2184 TUNSAFEPTR: 2185 return true 2186 2187 case TARRAY: 2188 // Array of 1 direct iface type can be direct. 2189 return t.NumElem() == 1 && isdirectiface(t.Elem()) 2190 2191 case TSTRUCT: 2192 // Struct with 1 field of direct iface type can be direct. 2193 return t.NumFields() == 1 && isdirectiface(t.Field(0).Type) 2194 } 2195 2196 return false 2197 } 2198 2199 // itabType loads the _type field from a runtime.itab struct. 2200 func itabType(itab *Node) *Node { 2201 typ := nodSym(ODOTPTR, itab, nil) 2202 typ.Type = ptrto(Types[TUINT8]) 2203 typ.Typecheck = 1 2204 typ.Xoffset = int64(Widthptr) // offset of _type in runtime.itab 2205 typ.Bounded = true // guaranteed not to fault 2206 return typ 2207 } 2208 2209 // ifaceData loads the data field from an interface. 2210 // The concrete type must be known to have type t. 2211 // It follows the pointer if !isdirectiface(t). 2212 func ifaceData(n *Node, t *Type) *Node { 2213 ptr := nodSym(OIDATA, n, nil) 2214 if isdirectiface(t) { 2215 ptr.Type = t 2216 ptr.Typecheck = 1 2217 return ptr 2218 } 2219 ptr.Type = ptrto(t) 2220 ptr.Bounded = true 2221 ptr.Typecheck = 1 2222 ind := nod(OIND, ptr, nil) 2223 ind.Type = t 2224 ind.Typecheck = 1 2225 return ind 2226 } 2227 2228 // iet returns 'T' if t is a concrete type, 2229 // 'I' if t is an interface type, and 'E' if t is an empty interface type. 2230 // It is used to build calls to the conv* and assert* runtime routines. 2231 func (t *Type) iet() byte { 2232 if t.IsEmptyInterface() { 2233 return 'E' 2234 } 2235 if t.IsInterface() { 2236 return 'I' 2237 } 2238 return 'T' 2239 }