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