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