github.com/rakyll/go@v0.0.0-20170216000551-64c02460d703/src/cmd/compile/internal/gc/swt.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 "sort"
     8  
     9  const (
    10  	// expression switch
    11  	switchKindExpr  = iota // switch a {...} or switch 5 {...}
    12  	switchKindTrue         // switch true {...} or switch {...}
    13  	switchKindFalse        // switch false {...}
    14  )
    15  
    16  const (
    17  	binarySearchMin = 4 // minimum number of cases for binary search
    18  	integerRangeMin = 2 // minimum size of integer ranges
    19  )
    20  
    21  // An exprSwitch walks an expression switch.
    22  type exprSwitch struct {
    23  	exprname *Node // node for the expression being switched on
    24  	kind     int   // kind of switch statement (switchKind*)
    25  }
    26  
    27  // A typeSwitch walks a type switch.
    28  type typeSwitch struct {
    29  	hashname *Node // node for the hash of the type of the variable being switched on
    30  	facename *Node // node for the concrete type of the variable being switched on
    31  	okname   *Node // boolean node used for comma-ok type assertions
    32  }
    33  
    34  // A caseClause is a single case clause in a switch statement.
    35  type caseClause struct {
    36  	node    *Node  // points at case statement
    37  	ordinal int    // position in switch
    38  	hash    uint32 // hash of a type switch
    39  	// isconst indicates whether this case clause is a constant,
    40  	// for the purposes of the switch code generation.
    41  	// For expression switches, that's generally literals (case 5:, not case x:).
    42  	// For type switches, that's concrete types (case time.Time:), not interfaces (case io.Reader:).
    43  	isconst bool
    44  }
    45  
    46  // caseClauses are all the case clauses in a switch statement.
    47  type caseClauses struct {
    48  	list   []caseClause // general cases
    49  	defjmp *Node        // OGOTO for default case or OBREAK if no default case present
    50  	niljmp *Node        // OGOTO for nil type case in a type switch
    51  }
    52  
    53  // typecheckswitch typechecks a switch statement.
    54  func typecheckswitch(n *Node) {
    55  	lno := lineno
    56  	typecheckslice(n.Ninit.Slice(), Etop)
    57  
    58  	var nilonly string
    59  	var top int
    60  	var t *Type
    61  
    62  	if n.Left != nil && n.Left.Op == OTYPESW {
    63  		// type switch
    64  		top = Etype
    65  		n.Left.Right = typecheck(n.Left.Right, Erv)
    66  		t = n.Left.Right.Type
    67  		if t != nil && !t.IsInterface() {
    68  			yyerror("cannot type switch on non-interface value %L", n.Left.Right)
    69  		}
    70  	} else {
    71  		// expression switch
    72  		top = Erv
    73  		if n.Left != nil {
    74  			n.Left = typecheck(n.Left, Erv)
    75  			n.Left = defaultlit(n.Left, nil)
    76  			t = n.Left.Type
    77  		} else {
    78  			t = Types[TBOOL]
    79  		}
    80  		if t != nil {
    81  			switch {
    82  			case !okforeq[t.Etype]:
    83  				yyerror("cannot switch on %L", n.Left)
    84  			case t.IsSlice():
    85  				nilonly = "slice"
    86  			case t.IsArray() && !t.IsComparable():
    87  				yyerror("cannot switch on %L", n.Left)
    88  			case t.IsStruct():
    89  				if f := t.IncomparableField(); f != nil {
    90  					yyerror("cannot switch on %L (struct containing %v cannot be compared)", n.Left, f.Type)
    91  				}
    92  			case t.Etype == TFUNC:
    93  				nilonly = "func"
    94  			case t.IsMap():
    95  				nilonly = "map"
    96  			}
    97  		}
    98  	}
    99  
   100  	n.Type = t
   101  
   102  	var def, niltype *Node
   103  	for _, ncase := range n.List.Slice() {
   104  		setlineno(n)
   105  		if ncase.List.Len() == 0 {
   106  			// default
   107  			if def != nil {
   108  				setlineno(ncase)
   109  				yyerror("multiple defaults in switch (first at %v)", def.Line())
   110  			} else {
   111  				def = ncase
   112  			}
   113  		} else {
   114  			ls := ncase.List.Slice()
   115  			for i1, n1 := range ls {
   116  				setlineno(n1)
   117  				ls[i1] = typecheck(ls[i1], Erv|Etype)
   118  				n1 = ls[i1]
   119  				if n1.Type == nil || t == nil {
   120  					continue
   121  				}
   122  				setlineno(ncase)
   123  				switch top {
   124  				// expression switch
   125  				case Erv:
   126  					ls[i1] = defaultlit(ls[i1], t)
   127  					n1 = ls[i1]
   128  					switch {
   129  					case n1.Op == OTYPE:
   130  						yyerror("type %v is not an expression", n1.Type)
   131  					case n1.Type != nil && assignop(n1.Type, t, nil) == 0 && assignop(t, n1.Type, nil) == 0:
   132  						if n.Left != nil {
   133  							yyerror("invalid case %v in switch on %v (mismatched types %v and %v)", n1, n.Left, n1.Type, t)
   134  						} else {
   135  							yyerror("invalid case %v in switch (mismatched types %v and bool)", n1, n1.Type)
   136  						}
   137  					case nilonly != "" && !isnil(n1):
   138  						yyerror("invalid case %v in switch (can only compare %s %v to nil)", n1, nilonly, n.Left)
   139  					case t.IsInterface() && !n1.Type.IsInterface() && !n1.Type.IsComparable():
   140  						yyerror("invalid case %L in switch (incomparable type)", n1)
   141  					}
   142  
   143  				// type switch
   144  				case Etype:
   145  					var missing, have *Field
   146  					var ptr int
   147  					switch {
   148  					case n1.Op == OLITERAL && n1.Type.IsKind(TNIL):
   149  						// case nil:
   150  						if niltype != nil {
   151  							yyerror("multiple nil cases in type switch (first at %v)", niltype.Line())
   152  						} else {
   153  							niltype = ncase
   154  						}
   155  					case n1.Op != OTYPE && n1.Type != nil: // should this be ||?
   156  						yyerror("%L is not a type", n1)
   157  						// reset to original type
   158  						n1 = n.Left.Right
   159  						ls[i1] = n1
   160  					case !n1.Type.IsInterface() && t.IsInterface() && !implements(n1.Type, t, &missing, &have, &ptr):
   161  						if have != nil && !missing.Broke && !have.Broke {
   162  							yyerror("impossible type switch case: %L cannot have dynamic type %v"+
   163  								" (wrong type for %v method)\n\thave %v%S\n\twant %v%S", n.Left.Right, n1.Type, missing.Sym, have.Sym, have.Type, missing.Sym, missing.Type)
   164  						} else if !missing.Broke {
   165  							if ptr != 0 {
   166  								yyerror("impossible type switch case: %L cannot have dynamic type %v"+
   167  									" (%v method has pointer receiver)", n.Left.Right, n1.Type, missing.Sym)
   168  							} else {
   169  								yyerror("impossible type switch case: %L cannot have dynamic type %v"+
   170  									" (missing %v method)", n.Left.Right, n1.Type, missing.Sym)
   171  							}
   172  						}
   173  					}
   174  				}
   175  			}
   176  		}
   177  
   178  		if top == Etype && n.Type != nil {
   179  			ll := ncase.List
   180  			if ncase.Rlist.Len() != 0 {
   181  				nvar := ncase.Rlist.First()
   182  				if ll.Len() == 1 && ll.First().Type != nil && !ll.First().Type.IsKind(TNIL) {
   183  					// single entry type switch
   184  					nvar.Name.Param.Ntype = typenod(ll.First().Type)
   185  				} else {
   186  					// multiple entry type switch or default
   187  					nvar.Name.Param.Ntype = typenod(n.Type)
   188  				}
   189  
   190  				nvar = typecheck(nvar, Erv|Easgn)
   191  				ncase.Rlist.SetIndex(0, nvar)
   192  			}
   193  		}
   194  
   195  		typecheckslice(ncase.Nbody.Slice(), Etop)
   196  	}
   197  
   198  	lineno = lno
   199  }
   200  
   201  // walkswitch walks a switch statement.
   202  func walkswitch(sw *Node) {
   203  	// convert switch {...} to switch true {...}
   204  	if sw.Left == nil {
   205  		sw.Left = nodbool(true)
   206  		sw.Left = typecheck(sw.Left, Erv)
   207  	}
   208  
   209  	if sw.Left.Op == OTYPESW {
   210  		var s typeSwitch
   211  		s.walk(sw)
   212  	} else {
   213  		var s exprSwitch
   214  		s.walk(sw)
   215  	}
   216  }
   217  
   218  // walk generates an AST implementing sw.
   219  // sw is an expression switch.
   220  // The AST is generally of the form of a linear
   221  // search using if..goto, although binary search
   222  // is used with long runs of constants.
   223  func (s *exprSwitch) walk(sw *Node) {
   224  	casebody(sw, nil)
   225  
   226  	cond := sw.Left
   227  	sw.Left = nil
   228  
   229  	s.kind = switchKindExpr
   230  	if Isconst(cond, CTBOOL) {
   231  		s.kind = switchKindTrue
   232  		if !cond.Val().U.(bool) {
   233  			s.kind = switchKindFalse
   234  		}
   235  	}
   236  
   237  	cond = walkexpr(cond, &sw.Ninit)
   238  	t := sw.Type
   239  	if t == nil {
   240  		return
   241  	}
   242  
   243  	// convert the switch into OIF statements
   244  	var cas []*Node
   245  	if s.kind == switchKindTrue || s.kind == switchKindFalse {
   246  		s.exprname = nodbool(s.kind == switchKindTrue)
   247  	} else if consttype(cond) >= 0 {
   248  		// leave constants to enable dead code elimination (issue 9608)
   249  		s.exprname = cond
   250  	} else {
   251  		s.exprname = temp(cond.Type)
   252  		cas = []*Node{nod(OAS, s.exprname, cond)}
   253  		typecheckslice(cas, Etop)
   254  	}
   255  
   256  	// Enumerate the cases and prepare the default case.
   257  	clauses := s.genCaseClauses(sw.List.Slice())
   258  	sw.List.Set(nil)
   259  	cc := clauses.list
   260  
   261  	// handle the cases in order
   262  	for len(cc) > 0 {
   263  		// deal with expressions one at a time
   264  		if !okforcmp[t.Etype] || !cc[0].isconst {
   265  			a := s.walkCases(cc[:1])
   266  			cas = append(cas, a)
   267  			cc = cc[1:]
   268  			continue
   269  		}
   270  
   271  		// do binary search on runs of constants
   272  		var run int
   273  		for run = 1; run < len(cc) && cc[run].isconst; run++ {
   274  		}
   275  
   276  		// sort and compile constants
   277  		sort.Sort(caseClauseByConstVal(cc[:run]))
   278  		a := s.walkCases(cc[:run])
   279  		cas = append(cas, a)
   280  		cc = cc[run:]
   281  	}
   282  
   283  	// handle default case
   284  	if nerrors == 0 {
   285  		cas = append(cas, clauses.defjmp)
   286  		sw.Nbody.Prepend(cas...)
   287  		walkstmtlist(sw.Nbody.Slice())
   288  	}
   289  }
   290  
   291  // walkCases generates an AST implementing the cases in cc.
   292  func (s *exprSwitch) walkCases(cc []caseClause) *Node {
   293  	if len(cc) < binarySearchMin {
   294  		// linear search
   295  		var cas []*Node
   296  		for _, c := range cc {
   297  			n := c.node
   298  			lno := setlineno(n)
   299  
   300  			a := nod(OIF, nil, nil)
   301  			if rng := n.List.Slice(); rng != nil {
   302  				// Integer range.
   303  				// exprname is a temp or a constant,
   304  				// so it is safe to evaluate twice.
   305  				// In most cases, this conjunction will be
   306  				// rewritten by walkinrange into a single comparison.
   307  				low := nod(OGE, s.exprname, rng[0])
   308  				high := nod(OLE, s.exprname, rng[1])
   309  				a.Left = nod(OANDAND, low, high)
   310  				a.Left = typecheck(a.Left, Erv)
   311  				a.Left = walkexpr(a.Left, nil) // give walk the opportunity to optimize the range check
   312  			} else if (s.kind != switchKindTrue && s.kind != switchKindFalse) || assignop(n.Left.Type, s.exprname.Type, nil) == OCONVIFACE || assignop(s.exprname.Type, n.Left.Type, nil) == OCONVIFACE {
   313  				a.Left = nod(OEQ, s.exprname, n.Left) // if name == val
   314  				a.Left = typecheck(a.Left, Erv)
   315  			} else if s.kind == switchKindTrue {
   316  				a.Left = n.Left // if val
   317  			} else {
   318  				// s.kind == switchKindFalse
   319  				a.Left = nod(ONOT, n.Left, nil) // if !val
   320  				a.Left = typecheck(a.Left, Erv)
   321  			}
   322  			a.Nbody.Set1(n.Right) // goto l
   323  
   324  			cas = append(cas, a)
   325  			lineno = lno
   326  		}
   327  		return liststmt(cas)
   328  	}
   329  
   330  	// find the middle and recur
   331  	half := len(cc) / 2
   332  	a := nod(OIF, nil, nil)
   333  	n := cc[half-1].node
   334  	var mid *Node
   335  	if rng := n.List.Slice(); rng != nil {
   336  		mid = rng[1] // high end of range
   337  	} else {
   338  		mid = n.Left
   339  	}
   340  	le := nod(OLE, s.exprname, mid)
   341  	if Isconst(mid, CTSTR) {
   342  		// Search by length and then by value; see caseClauseByConstVal.
   343  		lenlt := nod(OLT, nod(OLEN, s.exprname, nil), nod(OLEN, mid, nil))
   344  		leneq := nod(OEQ, nod(OLEN, s.exprname, nil), nod(OLEN, mid, nil))
   345  		a.Left = nod(OOROR, lenlt, nod(OANDAND, leneq, le))
   346  	} else {
   347  		a.Left = le
   348  	}
   349  	a.Left = typecheck(a.Left, Erv)
   350  	a.Nbody.Set1(s.walkCases(cc[:half]))
   351  	a.Rlist.Set1(s.walkCases(cc[half:]))
   352  	return a
   353  }
   354  
   355  // casebody builds separate lists of statements and cases.
   356  // It makes labels between cases and statements
   357  // and deals with fallthrough, break, and unreachable statements.
   358  func casebody(sw *Node, typeswvar *Node) {
   359  	if sw.List.Len() == 0 {
   360  		return
   361  	}
   362  
   363  	lno := setlineno(sw)
   364  
   365  	var cas []*Node  // cases
   366  	var stat []*Node // statements
   367  	var def *Node    // defaults
   368  	br := nod(OBREAK, nil, nil)
   369  
   370  	for i, n := range sw.List.Slice() {
   371  		setlineno(n)
   372  		if n.Op != OXCASE {
   373  			Fatalf("casebody %v", n.Op)
   374  		}
   375  		n.Op = OCASE
   376  		needvar := n.List.Len() != 1 || n.List.First().Op == OLITERAL
   377  
   378  		jmp := nod(OGOTO, autolabel(".s"), nil)
   379  		switch n.List.Len() {
   380  		case 0:
   381  			// default
   382  			if def != nil {
   383  				yyerror("more than one default case")
   384  			}
   385  			// reuse original default case
   386  			n.Right = jmp
   387  			def = n
   388  		case 1:
   389  			// one case -- reuse OCASE node
   390  			n.Left = n.List.First()
   391  			n.Right = jmp
   392  			n.List.Set(nil)
   393  			cas = append(cas, n)
   394  		default:
   395  			// Expand multi-valued cases and detect ranges of integer cases.
   396  			if typeswvar != nil || sw.Left.Type.IsInterface() || !n.List.First().Type.IsInteger() || n.List.Len() < integerRangeMin {
   397  				// Can't use integer ranges. Expand each case into a separate node.
   398  				for _, n1 := range n.List.Slice() {
   399  					cas = append(cas, nod(OCASE, n1, jmp))
   400  				}
   401  				break
   402  			}
   403  			// Find integer ranges within runs of constants.
   404  			s := n.List.Slice()
   405  			j := 0
   406  			for j < len(s) {
   407  				// Find a run of constants.
   408  				var run int
   409  				for run = j; run < len(s) && Isconst(s[run], CTINT); run++ {
   410  				}
   411  				if run-j >= integerRangeMin {
   412  					// Search for integer ranges in s[j:run].
   413  					// Typechecking is done, so all values are already in an appropriate range.
   414  					search := s[j:run]
   415  					sort.Sort(constIntNodesByVal(search))
   416  					for beg, end := 0, 1; end <= len(search); end++ {
   417  						if end < len(search) && search[end].Int64() == search[end-1].Int64()+1 {
   418  							continue
   419  						}
   420  						if end-beg >= integerRangeMin {
   421  							// Record range in List.
   422  							c := nod(OCASE, nil, jmp)
   423  							c.List.Set2(search[beg], search[end-1])
   424  							cas = append(cas, c)
   425  						} else {
   426  							// Not large enough for range; record separately.
   427  							for _, n := range search[beg:end] {
   428  								cas = append(cas, nod(OCASE, n, jmp))
   429  							}
   430  						}
   431  						beg = end
   432  					}
   433  					j = run
   434  				}
   435  				// Advance to next constant, adding individual non-constant
   436  				// or as-yet-unhandled constant cases as we go.
   437  				for ; j < len(s) && (j < run || !Isconst(s[j], CTINT)); j++ {
   438  					cas = append(cas, nod(OCASE, s[j], jmp))
   439  				}
   440  			}
   441  		}
   442  
   443  		stat = append(stat, nod(OLABEL, jmp.Left, nil))
   444  		if typeswvar != nil && needvar && n.Rlist.Len() != 0 {
   445  			l := []*Node{
   446  				nod(ODCL, n.Rlist.First(), nil),
   447  				nod(OAS, n.Rlist.First(), typeswvar),
   448  			}
   449  			typecheckslice(l, Etop)
   450  			stat = append(stat, l...)
   451  		}
   452  		stat = append(stat, n.Nbody.Slice()...)
   453  
   454  		// Search backwards for the index of the fallthrough
   455  		// statement. Do not assume it'll be in the last
   456  		// position, since in some cases (e.g. when the statement
   457  		// list contains autotmp_ variables), one or more OVARKILL
   458  		// nodes will be at the end of the list.
   459  		fallIndex := len(stat) - 1
   460  		for stat[fallIndex].Op == OVARKILL {
   461  			fallIndex--
   462  		}
   463  		last := stat[fallIndex]
   464  
   465  		// botch - shouldn't fall through declaration
   466  		if last.Xoffset == n.Xoffset && last.Op == OXFALL {
   467  			if typeswvar != nil {
   468  				setlineno(last)
   469  				yyerror("cannot fallthrough in type switch")
   470  			}
   471  
   472  			if i+1 >= sw.List.Len() {
   473  				setlineno(last)
   474  				yyerror("cannot fallthrough final case in switch")
   475  			}
   476  
   477  			last.Op = OFALL
   478  		} else {
   479  			stat = append(stat, br)
   480  		}
   481  	}
   482  
   483  	stat = append(stat, br)
   484  	if def != nil {
   485  		cas = append(cas, def)
   486  	}
   487  
   488  	sw.List.Set(cas)
   489  	sw.Nbody.Set(stat)
   490  	lineno = lno
   491  }
   492  
   493  // genCaseClauses generates the caseClauses value for clauses.
   494  func (s *exprSwitch) genCaseClauses(clauses []*Node) caseClauses {
   495  	var cc caseClauses
   496  	for _, n := range clauses {
   497  		if n.Left == nil && n.List.Len() == 0 {
   498  			// default case
   499  			if cc.defjmp != nil {
   500  				Fatalf("duplicate default case not detected during typechecking")
   501  			}
   502  			cc.defjmp = n.Right
   503  			continue
   504  		}
   505  		c := caseClause{node: n, ordinal: len(cc.list)}
   506  		if n.List.Len() > 0 {
   507  			c.isconst = true
   508  		}
   509  		switch consttype(n.Left) {
   510  		case CTFLT, CTINT, CTRUNE, CTSTR:
   511  			c.isconst = true
   512  		}
   513  		cc.list = append(cc.list, c)
   514  	}
   515  
   516  	if cc.defjmp == nil {
   517  		cc.defjmp = nod(OBREAK, nil, nil)
   518  	}
   519  
   520  	// diagnose duplicate cases
   521  	s.checkDupCases(cc.list)
   522  	return cc
   523  }
   524  
   525  // genCaseClauses generates the caseClauses value for clauses.
   526  func (s *typeSwitch) genCaseClauses(clauses []*Node) caseClauses {
   527  	var cc caseClauses
   528  	for _, n := range clauses {
   529  		switch {
   530  		case n.Left == nil:
   531  			// default case
   532  			if cc.defjmp != nil {
   533  				Fatalf("duplicate default case not detected during typechecking")
   534  			}
   535  			cc.defjmp = n.Right
   536  			continue
   537  		case n.Left.Op == OLITERAL:
   538  			// nil case in type switch
   539  			if cc.niljmp != nil {
   540  				Fatalf("duplicate nil case not detected during typechecking")
   541  			}
   542  			cc.niljmp = n.Right
   543  			continue
   544  		}
   545  
   546  		// general case
   547  		c := caseClause{
   548  			node:    n,
   549  			ordinal: len(cc.list),
   550  			isconst: !n.Left.Type.IsInterface(),
   551  			hash:    typehash(n.Left.Type),
   552  		}
   553  		cc.list = append(cc.list, c)
   554  	}
   555  
   556  	if cc.defjmp == nil {
   557  		cc.defjmp = nod(OBREAK, nil, nil)
   558  	}
   559  
   560  	// diagnose duplicate cases
   561  	s.checkDupCases(cc.list)
   562  	return cc
   563  }
   564  
   565  func (s *typeSwitch) checkDupCases(cc []caseClause) {
   566  	if len(cc) < 2 {
   567  		return
   568  	}
   569  	// We store seen types in a map keyed by type hash.
   570  	// It is possible, but very unlikely, for multiple distinct types to have the same hash.
   571  	seen := make(map[uint32][]*Node)
   572  	// To avoid many small allocations of length 1 slices,
   573  	// also set up a single large slice to slice into.
   574  	nn := make([]*Node, 0, len(cc))
   575  Outer:
   576  	for _, c := range cc {
   577  		prev, ok := seen[c.hash]
   578  		if !ok {
   579  			// First entry for this hash.
   580  			nn = append(nn, c.node)
   581  			seen[c.hash] = nn[len(nn)-1 : len(nn):len(nn)]
   582  			continue
   583  		}
   584  		for _, n := range prev {
   585  			if eqtype(n.Left.Type, c.node.Left.Type) {
   586  				yyerrorl(c.node.Pos, "duplicate case %v in type switch\n\tprevious case at %v", c.node.Left.Type, n.Line())
   587  				// avoid double-reporting errors
   588  				continue Outer
   589  			}
   590  		}
   591  		seen[c.hash] = append(seen[c.hash], c.node)
   592  	}
   593  }
   594  
   595  func (s *exprSwitch) checkDupCases(cc []caseClause) {
   596  	if len(cc) < 2 {
   597  		return
   598  	}
   599  	// The common case is that s's expression is not an interface.
   600  	// In that case, all constant clauses have the same type,
   601  	// so checking for duplicates can be done solely by value.
   602  	if !s.exprname.Type.IsInterface() {
   603  		seen := make(map[interface{}]*Node)
   604  		for _, c := range cc {
   605  			switch {
   606  			case c.node.Left != nil:
   607  				// Single constant.
   608  
   609  				// Can't check for duplicates that aren't constants, per the spec. Issue 15896.
   610  				// Don't check for duplicate bools. Although the spec allows it,
   611  				// (1) the compiler hasn't checked it in the past, so compatibility mandates it, and
   612  				// (2) it would disallow useful things like
   613  				//       case GOARCH == "arm" && GOARM == "5":
   614  				//       case GOARCH == "arm":
   615  				//     which would both evaluate to false for non-ARM compiles.
   616  				if ct := consttype(c.node.Left); ct < 0 || ct == CTBOOL {
   617  					continue
   618  				}
   619  
   620  				val := c.node.Left.Val().Interface()
   621  				prev, dup := seen[val]
   622  				if !dup {
   623  					seen[val] = c.node
   624  					continue
   625  				}
   626  				setlineno(c.node)
   627  				yyerror("duplicate case %#v in switch\n\tprevious case at %v", val, prev.Line())
   628  
   629  			case c.node.List.Len() == 2:
   630  				// Range of integers.
   631  				low := c.node.List.Index(0).Int64()
   632  				high := c.node.List.Index(1).Int64()
   633  				for i := low; i <= high; i++ {
   634  					prev, dup := seen[i]
   635  					if !dup {
   636  						seen[i] = c.node
   637  						continue
   638  					}
   639  					setlineno(c.node)
   640  					yyerror("duplicate case %d in switch\n\tprevious case at %v", i, prev.Line())
   641  				}
   642  
   643  			default:
   644  				Fatalf("bad caseClause node in checkDupCases: %v", c.node)
   645  			}
   646  		}
   647  		return
   648  	}
   649  	// s's expression is an interface. This is fairly rare, so keep this simple.
   650  	// Duplicates are only duplicates if they have the same type and the same value.
   651  	type typeVal struct {
   652  		typ string
   653  		val interface{}
   654  	}
   655  	seen := make(map[typeVal]*Node)
   656  	for _, c := range cc {
   657  		if ct := consttype(c.node.Left); ct < 0 || ct == CTBOOL {
   658  			continue
   659  		}
   660  		n := c.node.Left
   661  		tv := typeVal{
   662  			// n.Type.tconv(FmtLeft | FmtUnsigned) here serves to completely describe the type.
   663  			// See the comments in func typehash.
   664  			typ: n.Type.tconv(FmtLeft | FmtUnsigned),
   665  			val: n.Val().Interface(),
   666  		}
   667  		prev, dup := seen[tv]
   668  		if !dup {
   669  			seen[tv] = c.node
   670  			continue
   671  		}
   672  		setlineno(c.node)
   673  		yyerror("duplicate case %v in switch\n\tprevious case at %v", prev.Left, prev.Line())
   674  	}
   675  }
   676  
   677  // walk generates an AST that implements sw,
   678  // where sw is a type switch.
   679  // The AST is generally of the form of a linear
   680  // search using if..goto, although binary search
   681  // is used with long runs of concrete types.
   682  func (s *typeSwitch) walk(sw *Node) {
   683  	cond := sw.Left
   684  	sw.Left = nil
   685  
   686  	if cond == nil {
   687  		sw.List.Set(nil)
   688  		return
   689  	}
   690  	if cond.Right == nil {
   691  		setlineno(sw)
   692  		yyerror("type switch must have an assignment")
   693  		return
   694  	}
   695  
   696  	cond.Right = walkexpr(cond.Right, &sw.Ninit)
   697  	if !cond.Right.Type.IsInterface() {
   698  		yyerror("type switch must be on an interface")
   699  		return
   700  	}
   701  
   702  	var cas []*Node
   703  
   704  	// predeclare temporary variables and the boolean var
   705  	s.facename = temp(cond.Right.Type)
   706  
   707  	a := nod(OAS, s.facename, cond.Right)
   708  	a = typecheck(a, Etop)
   709  	cas = append(cas, a)
   710  
   711  	s.okname = temp(Types[TBOOL])
   712  	s.okname = typecheck(s.okname, Erv)
   713  
   714  	s.hashname = temp(Types[TUINT32])
   715  	s.hashname = typecheck(s.hashname, Erv)
   716  
   717  	// set up labels and jumps
   718  	casebody(sw, s.facename)
   719  
   720  	clauses := s.genCaseClauses(sw.List.Slice())
   721  	sw.List.Set(nil)
   722  	def := clauses.defjmp
   723  
   724  	// For empty interfaces, do:
   725  	//     if e._type == nil {
   726  	//         do nil case if it exists, otherwise default
   727  	//     }
   728  	//     h := e._type.hash
   729  	// Use a similar strategy for non-empty interfaces.
   730  
   731  	// Get interface descriptor word.
   732  	// For empty interfaces this will be the type.
   733  	// For non-empty interfaces this will be the itab.
   734  	itab := nod(OITAB, s.facename, nil)
   735  
   736  	// Check for nil first.
   737  	i := nod(OIF, nil, nil)
   738  	i.Left = nod(OEQ, itab, nodnil())
   739  	if clauses.niljmp != nil {
   740  		// Do explicit nil case right here.
   741  		i.Nbody.Set1(clauses.niljmp)
   742  	} else {
   743  		// Jump to default case.
   744  		lbl := autolabel(".s")
   745  		i.Nbody.Set1(nod(OGOTO, lbl, nil))
   746  		// Wrap default case with label.
   747  		blk := nod(OBLOCK, nil, nil)
   748  		blk.List.Set([]*Node{nod(OLABEL, lbl, nil), def})
   749  		def = blk
   750  	}
   751  	i.Left = typecheck(i.Left, Erv)
   752  	cas = append(cas, i)
   753  
   754  	// Load hash from type or itab.
   755  	h := nodSym(ODOTPTR, itab, nil)
   756  	h.Type = Types[TUINT32]
   757  	h.Typecheck = 1
   758  	if cond.Right.Type.IsEmptyInterface() {
   759  		h.Xoffset = int64(2 * Widthptr) // offset of hash in runtime._type
   760  	} else {
   761  		h.Xoffset = int64(3 * Widthptr) // offset of hash in runtime.itab
   762  	}
   763  	h.Bounded = true // guaranteed not to fault
   764  	a = nod(OAS, s.hashname, h)
   765  	a = typecheck(a, Etop)
   766  	cas = append(cas, a)
   767  
   768  	cc := clauses.list
   769  
   770  	// insert type equality check into each case block
   771  	for _, c := range cc {
   772  		c.node.Right = s.typeone(c.node)
   773  	}
   774  
   775  	// generate list of if statements, binary search for constant sequences
   776  	for len(cc) > 0 {
   777  		if !cc[0].isconst {
   778  			n := cc[0].node
   779  			cas = append(cas, n.Right)
   780  			cc = cc[1:]
   781  			continue
   782  		}
   783  
   784  		// identify run of constants
   785  		var run int
   786  		for run = 1; run < len(cc) && cc[run].isconst; run++ {
   787  		}
   788  
   789  		// sort by hash
   790  		sort.Sort(caseClauseByType(cc[:run]))
   791  
   792  		// for debugging: linear search
   793  		if false {
   794  			for i := 0; i < run; i++ {
   795  				n := cc[i].node
   796  				cas = append(cas, n.Right)
   797  			}
   798  			continue
   799  		}
   800  
   801  		// combine adjacent cases with the same hash
   802  		ncase := 0
   803  		for i := 0; i < run; i++ {
   804  			ncase++
   805  			hash := []*Node{cc[i].node.Right}
   806  			for j := i + 1; j < run && cc[i].hash == cc[j].hash; j++ {
   807  				hash = append(hash, cc[j].node.Right)
   808  			}
   809  			cc[i].node.Right = liststmt(hash)
   810  		}
   811  
   812  		// binary search among cases to narrow by hash
   813  		cas = append(cas, s.walkCases(cc[:ncase]))
   814  		cc = cc[ncase:]
   815  	}
   816  
   817  	// handle default case
   818  	if nerrors == 0 {
   819  		cas = append(cas, def)
   820  		sw.Nbody.Prepend(cas...)
   821  		sw.List.Set(nil)
   822  		walkstmtlist(sw.Nbody.Slice())
   823  	}
   824  }
   825  
   826  // typeone generates an AST that jumps to the
   827  // case body if the variable is of type t.
   828  func (s *typeSwitch) typeone(t *Node) *Node {
   829  	var name *Node
   830  	var init []*Node
   831  	if t.Rlist.Len() == 0 {
   832  		name = nblank
   833  		nblank = typecheck(nblank, Erv|Easgn)
   834  	} else {
   835  		name = t.Rlist.First()
   836  		init = []*Node{nod(ODCL, name, nil)}
   837  		a := nod(OAS, name, nil)
   838  		a = typecheck(a, Etop)
   839  		init = append(init, a)
   840  	}
   841  
   842  	a := nod(OAS2, nil, nil)
   843  	a.List.Set([]*Node{name, s.okname}) // name, ok =
   844  	b := nod(ODOTTYPE, s.facename, nil)
   845  	b.Type = t.Left.Type // interface.(type)
   846  	a.Rlist.Set1(b)
   847  	a = typecheck(a, Etop)
   848  	init = append(init, a)
   849  
   850  	c := nod(OIF, nil, nil)
   851  	c.Left = s.okname
   852  	c.Nbody.Set1(t.Right) // if ok { goto l }
   853  
   854  	return liststmt(append(init, c))
   855  }
   856  
   857  // walkCases generates an AST implementing the cases in cc.
   858  func (s *typeSwitch) walkCases(cc []caseClause) *Node {
   859  	if len(cc) < binarySearchMin {
   860  		var cas []*Node
   861  		for _, c := range cc {
   862  			n := c.node
   863  			if !c.isconst {
   864  				Fatalf("typeSwitch walkCases")
   865  			}
   866  			a := nod(OIF, nil, nil)
   867  			a.Left = nod(OEQ, s.hashname, nodintconst(int64(c.hash)))
   868  			a.Left = typecheck(a.Left, Erv)
   869  			a.Nbody.Set1(n.Right)
   870  			cas = append(cas, a)
   871  		}
   872  		return liststmt(cas)
   873  	}
   874  
   875  	// find the middle and recur
   876  	half := len(cc) / 2
   877  	a := nod(OIF, nil, nil)
   878  	a.Left = nod(OLE, s.hashname, nodintconst(int64(cc[half-1].hash)))
   879  	a.Left = typecheck(a.Left, Erv)
   880  	a.Nbody.Set1(s.walkCases(cc[:half]))
   881  	a.Rlist.Set1(s.walkCases(cc[half:]))
   882  	return a
   883  }
   884  
   885  // caseClauseByConstVal sorts clauses by constant value to enable binary search.
   886  type caseClauseByConstVal []caseClause
   887  
   888  func (x caseClauseByConstVal) Len() int      { return len(x) }
   889  func (x caseClauseByConstVal) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
   890  func (x caseClauseByConstVal) Less(i, j int) bool {
   891  	// n1 and n2 might be individual constants or integer ranges.
   892  	// We have checked for duplicates already,
   893  	// so ranges can be safely represented by any value in the range.
   894  	n1 := x[i].node
   895  	var v1 interface{}
   896  	if s := n1.List.Slice(); s != nil {
   897  		v1 = s[0].Val().U
   898  	} else {
   899  		v1 = n1.Left.Val().U
   900  	}
   901  
   902  	n2 := x[j].node
   903  	var v2 interface{}
   904  	if s := n2.List.Slice(); s != nil {
   905  		v2 = s[0].Val().U
   906  	} else {
   907  		v2 = n2.Left.Val().U
   908  	}
   909  
   910  	switch v1 := v1.(type) {
   911  	case *Mpflt:
   912  		return v1.Cmp(v2.(*Mpflt)) < 0
   913  	case *Mpint:
   914  		return v1.Cmp(v2.(*Mpint)) < 0
   915  	case string:
   916  		// Sort strings by length and then by value.
   917  		// It is much cheaper to compare lengths than values,
   918  		// and all we need here is consistency.
   919  		// We respect this sorting in exprSwitch.walkCases.
   920  		a := v1
   921  		b := v2.(string)
   922  		if len(a) != len(b) {
   923  			return len(a) < len(b)
   924  		}
   925  		return a < b
   926  	}
   927  
   928  	Fatalf("caseClauseByConstVal passed bad clauses %v < %v", x[i].node.Left, x[j].node.Left)
   929  	return false
   930  }
   931  
   932  type caseClauseByType []caseClause
   933  
   934  func (x caseClauseByType) Len() int      { return len(x) }
   935  func (x caseClauseByType) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
   936  func (x caseClauseByType) Less(i, j int) bool {
   937  	c1, c2 := x[i], x[j]
   938  	// sort by hash code, then ordinal (for the rare case of hash collisions)
   939  	if c1.hash != c2.hash {
   940  		return c1.hash < c2.hash
   941  	}
   942  	return c1.ordinal < c2.ordinal
   943  }
   944  
   945  type constIntNodesByVal []*Node
   946  
   947  func (x constIntNodesByVal) Len() int      { return len(x) }
   948  func (x constIntNodesByVal) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
   949  func (x constIntNodesByVal) Less(i, j int) bool {
   950  	return x[i].Val().U.(*Mpint).Cmp(x[j].Val().U.(*Mpint)) < 0
   951  }