github.com/activestate/go@v0.0.0-20170614201249-0b81c023a722/src/go/types/expr.go (about)

     1  // Copyright 2012 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  // This file implements typechecking of expressions.
     6  
     7  package types
     8  
     9  import (
    10  	"fmt"
    11  	"go/ast"
    12  	"go/constant"
    13  	"go/token"
    14  	"math"
    15  )
    16  
    17  /*
    18  Basic algorithm:
    19  
    20  Expressions are checked recursively, top down. Expression checker functions
    21  are generally of the form:
    22  
    23    func f(x *operand, e *ast.Expr, ...)
    24  
    25  where e is the expression to be checked, and x is the result of the check.
    26  The check performed by f may fail in which case x.mode == invalid, and
    27  related error messages will have been issued by f.
    28  
    29  If a hint argument is present, it is the composite literal element type
    30  of an outer composite literal; it is used to type-check composite literal
    31  elements that have no explicit type specification in the source
    32  (e.g.: []T{{...}, {...}}, the hint is the type T in this case).
    33  
    34  All expressions are checked via rawExpr, which dispatches according
    35  to expression kind. Upon returning, rawExpr is recording the types and
    36  constant values for all expressions that have an untyped type (those types
    37  may change on the way up in the expression tree). Usually these are constants,
    38  but the results of comparisons or non-constant shifts of untyped constants
    39  may also be untyped, but not constant.
    40  
    41  Untyped expressions may eventually become fully typed (i.e., not untyped),
    42  typically when the value is assigned to a variable, or is used otherwise.
    43  The updateExprType method is used to record this final type and update
    44  the recorded types: the type-checked expression tree is again traversed down,
    45  and the new type is propagated as needed. Untyped constant expression values
    46  that become fully typed must now be representable by the full type (constant
    47  sub-expression trees are left alone except for their roots). This mechanism
    48  ensures that a client sees the actual (run-time) type an untyped value would
    49  have. It also permits type-checking of lhs shift operands "as if the shift
    50  were not present": when updateExprType visits an untyped lhs shift operand
    51  and assigns it it's final type, that type must be an integer type, and a
    52  constant lhs must be representable as an integer.
    53  
    54  When an expression gets its final type, either on the way out from rawExpr,
    55  on the way down in updateExprType, or at the end of the type checker run,
    56  the type (and constant value, if any) is recorded via Info.Types, if present.
    57  */
    58  
    59  type opPredicates map[token.Token]func(Type) bool
    60  
    61  var unaryOpPredicates = opPredicates{
    62  	token.ADD: isNumeric,
    63  	token.SUB: isNumeric,
    64  	token.XOR: isInteger,
    65  	token.NOT: isBoolean,
    66  }
    67  
    68  func (check *Checker) op(m opPredicates, x *operand, op token.Token) bool {
    69  	if pred := m[op]; pred != nil {
    70  		if !pred(x.typ) {
    71  			check.invalidOp(x.pos(), "operator %s not defined for %s", op, x)
    72  			return false
    73  		}
    74  	} else {
    75  		check.invalidAST(x.pos(), "unknown operator %s", op)
    76  		return false
    77  	}
    78  	return true
    79  }
    80  
    81  // The unary expression e may be nil. It's passed in for better error messages only.
    82  func (check *Checker) unary(x *operand, e *ast.UnaryExpr, op token.Token) {
    83  	switch op {
    84  	case token.AND:
    85  		// spec: "As an exception to the addressability
    86  		// requirement x may also be a composite literal."
    87  		if _, ok := unparen(x.expr).(*ast.CompositeLit); !ok && x.mode != variable {
    88  			check.invalidOp(x.pos(), "cannot take address of %s", x)
    89  			x.mode = invalid
    90  			return
    91  		}
    92  		x.mode = value
    93  		x.typ = &Pointer{base: x.typ}
    94  		return
    95  
    96  	case token.ARROW:
    97  		typ, ok := x.typ.Underlying().(*Chan)
    98  		if !ok {
    99  			check.invalidOp(x.pos(), "cannot receive from non-channel %s", x)
   100  			x.mode = invalid
   101  			return
   102  		}
   103  		if typ.dir == SendOnly {
   104  			check.invalidOp(x.pos(), "cannot receive from send-only channel %s", x)
   105  			x.mode = invalid
   106  			return
   107  		}
   108  		x.mode = commaok
   109  		x.typ = typ.elem
   110  		check.hasCallOrRecv = true
   111  		return
   112  	}
   113  
   114  	if !check.op(unaryOpPredicates, x, op) {
   115  		x.mode = invalid
   116  		return
   117  	}
   118  
   119  	if x.mode == constant_ {
   120  		typ := x.typ.Underlying().(*Basic)
   121  		var prec uint
   122  		if isUnsigned(typ) {
   123  			prec = uint(check.conf.sizeof(typ) * 8)
   124  		}
   125  		x.val = constant.UnaryOp(op, x.val, prec)
   126  		// Typed constants must be representable in
   127  		// their type after each constant operation.
   128  		if isTyped(typ) {
   129  			if e != nil {
   130  				x.expr = e // for better error message
   131  			}
   132  			check.representable(x, typ)
   133  		}
   134  		return
   135  	}
   136  
   137  	x.mode = value
   138  	// x.typ remains unchanged
   139  }
   140  
   141  func isShift(op token.Token) bool {
   142  	return op == token.SHL || op == token.SHR
   143  }
   144  
   145  func isComparison(op token.Token) bool {
   146  	// Note: tokens are not ordered well to make this much easier
   147  	switch op {
   148  	case token.EQL, token.NEQ, token.LSS, token.LEQ, token.GTR, token.GEQ:
   149  		return true
   150  	}
   151  	return false
   152  }
   153  
   154  func fitsFloat32(x constant.Value) bool {
   155  	f32, _ := constant.Float32Val(x)
   156  	f := float64(f32)
   157  	return !math.IsInf(f, 0)
   158  }
   159  
   160  func roundFloat32(x constant.Value) constant.Value {
   161  	f32, _ := constant.Float32Val(x)
   162  	f := float64(f32)
   163  	if !math.IsInf(f, 0) {
   164  		return constant.MakeFloat64(f)
   165  	}
   166  	return nil
   167  }
   168  
   169  func fitsFloat64(x constant.Value) bool {
   170  	f, _ := constant.Float64Val(x)
   171  	return !math.IsInf(f, 0)
   172  }
   173  
   174  func roundFloat64(x constant.Value) constant.Value {
   175  	f, _ := constant.Float64Val(x)
   176  	if !math.IsInf(f, 0) {
   177  		return constant.MakeFloat64(f)
   178  	}
   179  	return nil
   180  }
   181  
   182  // representableConst reports whether x can be represented as
   183  // value of the given basic type and for the configuration
   184  // provided (only needed for int/uint sizes).
   185  //
   186  // If rounded != nil, *rounded is set to the rounded value of x for
   187  // representable floating-point and complex values, and to an Int
   188  // value for integer values; it is left alone otherwise.
   189  // It is ok to provide the addressof the first argument for rounded.
   190  func representableConst(x constant.Value, conf *Config, typ *Basic, rounded *constant.Value) bool {
   191  	if x.Kind() == constant.Unknown {
   192  		return true // avoid follow-up errors
   193  	}
   194  
   195  	switch {
   196  	case isInteger(typ):
   197  		x := constant.ToInt(x)
   198  		if x.Kind() != constant.Int {
   199  			return false
   200  		}
   201  		if rounded != nil {
   202  			*rounded = x
   203  		}
   204  		if x, ok := constant.Int64Val(x); ok {
   205  			switch typ.kind {
   206  			case Int:
   207  				var s = uint(conf.sizeof(typ)) * 8
   208  				return int64(-1)<<(s-1) <= x && x <= int64(1)<<(s-1)-1
   209  			case Int8:
   210  				const s = 8
   211  				return -1<<(s-1) <= x && x <= 1<<(s-1)-1
   212  			case Int16:
   213  				const s = 16
   214  				return -1<<(s-1) <= x && x <= 1<<(s-1)-1
   215  			case Int32:
   216  				const s = 32
   217  				return -1<<(s-1) <= x && x <= 1<<(s-1)-1
   218  			case Int64, UntypedInt:
   219  				return true
   220  			case Uint, Uintptr:
   221  				if s := uint(conf.sizeof(typ)) * 8; s < 64 {
   222  					return 0 <= x && x <= int64(1)<<s-1
   223  				}
   224  				return 0 <= x
   225  			case Uint8:
   226  				const s = 8
   227  				return 0 <= x && x <= 1<<s-1
   228  			case Uint16:
   229  				const s = 16
   230  				return 0 <= x && x <= 1<<s-1
   231  			case Uint32:
   232  				const s = 32
   233  				return 0 <= x && x <= 1<<s-1
   234  			case Uint64:
   235  				return 0 <= x
   236  			default:
   237  				unreachable()
   238  			}
   239  		}
   240  		// x does not fit into int64
   241  		switch n := constant.BitLen(x); typ.kind {
   242  		case Uint, Uintptr:
   243  			var s = uint(conf.sizeof(typ)) * 8
   244  			return constant.Sign(x) >= 0 && n <= int(s)
   245  		case Uint64:
   246  			return constant.Sign(x) >= 0 && n <= 64
   247  		case UntypedInt:
   248  			return true
   249  		}
   250  
   251  	case isFloat(typ):
   252  		x := constant.ToFloat(x)
   253  		if x.Kind() != constant.Float {
   254  			return false
   255  		}
   256  		switch typ.kind {
   257  		case Float32:
   258  			if rounded == nil {
   259  				return fitsFloat32(x)
   260  			}
   261  			r := roundFloat32(x)
   262  			if r != nil {
   263  				*rounded = r
   264  				return true
   265  			}
   266  		case Float64:
   267  			if rounded == nil {
   268  				return fitsFloat64(x)
   269  			}
   270  			r := roundFloat64(x)
   271  			if r != nil {
   272  				*rounded = r
   273  				return true
   274  			}
   275  		case UntypedFloat:
   276  			return true
   277  		default:
   278  			unreachable()
   279  		}
   280  
   281  	case isComplex(typ):
   282  		x := constant.ToComplex(x)
   283  		if x.Kind() != constant.Complex {
   284  			return false
   285  		}
   286  		switch typ.kind {
   287  		case Complex64:
   288  			if rounded == nil {
   289  				return fitsFloat32(constant.Real(x)) && fitsFloat32(constant.Imag(x))
   290  			}
   291  			re := roundFloat32(constant.Real(x))
   292  			im := roundFloat32(constant.Imag(x))
   293  			if re != nil && im != nil {
   294  				*rounded = constant.BinaryOp(re, token.ADD, constant.MakeImag(im))
   295  				return true
   296  			}
   297  		case Complex128:
   298  			if rounded == nil {
   299  				return fitsFloat64(constant.Real(x)) && fitsFloat64(constant.Imag(x))
   300  			}
   301  			re := roundFloat64(constant.Real(x))
   302  			im := roundFloat64(constant.Imag(x))
   303  			if re != nil && im != nil {
   304  				*rounded = constant.BinaryOp(re, token.ADD, constant.MakeImag(im))
   305  				return true
   306  			}
   307  		case UntypedComplex:
   308  			return true
   309  		default:
   310  			unreachable()
   311  		}
   312  
   313  	case isString(typ):
   314  		return x.Kind() == constant.String
   315  
   316  	case isBoolean(typ):
   317  		return x.Kind() == constant.Bool
   318  	}
   319  
   320  	return false
   321  }
   322  
   323  // representable checks that a constant operand is representable in the given basic type.
   324  func (check *Checker) representable(x *operand, typ *Basic) {
   325  	assert(x.mode == constant_)
   326  	if !representableConst(x.val, check.conf, typ, &x.val) {
   327  		var msg string
   328  		if isNumeric(x.typ) && isNumeric(typ) {
   329  			// numeric conversion : error msg
   330  			//
   331  			// integer -> integer : overflows
   332  			// integer -> float   : overflows (actually not possible)
   333  			// float   -> integer : truncated
   334  			// float   -> float   : overflows
   335  			//
   336  			if !isInteger(x.typ) && isInteger(typ) {
   337  				msg = "%s truncated to %s"
   338  			} else {
   339  				msg = "%s overflows %s"
   340  			}
   341  		} else {
   342  			msg = "cannot convert %s to %s"
   343  		}
   344  		check.errorf(x.pos(), msg, x, typ)
   345  		x.mode = invalid
   346  	}
   347  }
   348  
   349  // updateExprType updates the type of x to typ and invokes itself
   350  // recursively for the operands of x, depending on expression kind.
   351  // If typ is still an untyped and not the final type, updateExprType
   352  // only updates the recorded untyped type for x and possibly its
   353  // operands. Otherwise (i.e., typ is not an untyped type anymore,
   354  // or it is the final type for x), the type and value are recorded.
   355  // Also, if x is a constant, it must be representable as a value of typ,
   356  // and if x is the (formerly untyped) lhs operand of a non-constant
   357  // shift, it must be an integer value.
   358  //
   359  func (check *Checker) updateExprType(x ast.Expr, typ Type, final bool) {
   360  	old, found := check.untyped[x]
   361  	if !found {
   362  		return // nothing to do
   363  	}
   364  
   365  	// update operands of x if necessary
   366  	switch x := x.(type) {
   367  	case *ast.BadExpr,
   368  		*ast.FuncLit,
   369  		*ast.CompositeLit,
   370  		*ast.IndexExpr,
   371  		*ast.SliceExpr,
   372  		*ast.TypeAssertExpr,
   373  		*ast.StarExpr,
   374  		*ast.KeyValueExpr,
   375  		*ast.ArrayType,
   376  		*ast.StructType,
   377  		*ast.FuncType,
   378  		*ast.InterfaceType,
   379  		*ast.MapType,
   380  		*ast.ChanType:
   381  		// These expression are never untyped - nothing to do.
   382  		// The respective sub-expressions got their final types
   383  		// upon assignment or use.
   384  		if debug {
   385  			check.dump("%s: found old type(%s): %s (new: %s)", x.Pos(), x, old.typ, typ)
   386  			unreachable()
   387  		}
   388  		return
   389  
   390  	case *ast.CallExpr:
   391  		// Resulting in an untyped constant (e.g., built-in complex).
   392  		// The respective calls take care of calling updateExprType
   393  		// for the arguments if necessary.
   394  
   395  	case *ast.Ident, *ast.BasicLit, *ast.SelectorExpr:
   396  		// An identifier denoting a constant, a constant literal,
   397  		// or a qualified identifier (imported untyped constant).
   398  		// No operands to take care of.
   399  
   400  	case *ast.ParenExpr:
   401  		check.updateExprType(x.X, typ, final)
   402  
   403  	case *ast.UnaryExpr:
   404  		// If x is a constant, the operands were constants.
   405  		// They don't need to be updated since they never
   406  		// get "materialized" into a typed value; and they
   407  		// will be processed at the end of the type check.
   408  		if old.val != nil {
   409  			break
   410  		}
   411  		check.updateExprType(x.X, typ, final)
   412  
   413  	case *ast.BinaryExpr:
   414  		if old.val != nil {
   415  			break // see comment for unary expressions
   416  		}
   417  		if isComparison(x.Op) {
   418  			// The result type is independent of operand types
   419  			// and the operand types must have final types.
   420  		} else if isShift(x.Op) {
   421  			// The result type depends only on lhs operand.
   422  			// The rhs type was updated when checking the shift.
   423  			check.updateExprType(x.X, typ, final)
   424  		} else {
   425  			// The operand types match the result type.
   426  			check.updateExprType(x.X, typ, final)
   427  			check.updateExprType(x.Y, typ, final)
   428  		}
   429  
   430  	default:
   431  		unreachable()
   432  	}
   433  
   434  	// If the new type is not final and still untyped, just
   435  	// update the recorded type.
   436  	if !final && isUntyped(typ) {
   437  		old.typ = typ.Underlying().(*Basic)
   438  		check.untyped[x] = old
   439  		return
   440  	}
   441  
   442  	// Otherwise we have the final (typed or untyped type).
   443  	// Remove it from the map of yet untyped expressions.
   444  	delete(check.untyped, x)
   445  
   446  	// If x is the lhs of a shift, its final type must be integer.
   447  	// We already know from the shift check that it is representable
   448  	// as an integer if it is a constant.
   449  	if old.isLhs && !isInteger(typ) {
   450  		check.invalidOp(x.Pos(), "shifted operand %s (type %s) must be integer", x, typ)
   451  		return
   452  	}
   453  
   454  	// Everything's fine, record final type and value for x.
   455  	check.recordTypeAndValue(x, old.mode, typ, old.val)
   456  }
   457  
   458  // updateExprVal updates the value of x to val.
   459  func (check *Checker) updateExprVal(x ast.Expr, val constant.Value) {
   460  	if info, ok := check.untyped[x]; ok {
   461  		info.val = val
   462  		check.untyped[x] = info
   463  	}
   464  }
   465  
   466  // convertUntyped attempts to set the type of an untyped value to the target type.
   467  func (check *Checker) convertUntyped(x *operand, target Type) {
   468  	if x.mode == invalid || isTyped(x.typ) || target == Typ[Invalid] {
   469  		return
   470  	}
   471  
   472  	// TODO(gri) Sloppy code - clean up. This function is central
   473  	//           to assignment and expression checking.
   474  
   475  	if isUntyped(target) {
   476  		// both x and target are untyped
   477  		xkind := x.typ.(*Basic).kind
   478  		tkind := target.(*Basic).kind
   479  		if isNumeric(x.typ) && isNumeric(target) {
   480  			if xkind < tkind {
   481  				x.typ = target
   482  				check.updateExprType(x.expr, target, false)
   483  			}
   484  		} else if xkind != tkind {
   485  			goto Error
   486  		}
   487  		return
   488  	}
   489  
   490  	// typed target
   491  	switch t := target.Underlying().(type) {
   492  	case *Basic:
   493  		if x.mode == constant_ {
   494  			check.representable(x, t)
   495  			if x.mode == invalid {
   496  				return
   497  			}
   498  			// expression value may have been rounded - update if needed
   499  			check.updateExprVal(x.expr, x.val)
   500  		} else {
   501  			// Non-constant untyped values may appear as the
   502  			// result of comparisons (untyped bool), intermediate
   503  			// (delayed-checked) rhs operands of shifts, and as
   504  			// the value nil.
   505  			switch x.typ.(*Basic).kind {
   506  			case UntypedBool:
   507  				if !isBoolean(target) {
   508  					goto Error
   509  				}
   510  			case UntypedInt, UntypedRune, UntypedFloat, UntypedComplex:
   511  				if !isNumeric(target) {
   512  					goto Error
   513  				}
   514  			case UntypedString:
   515  				// Non-constant untyped string values are not
   516  				// permitted by the spec and should not occur.
   517  				unreachable()
   518  			case UntypedNil:
   519  				// Unsafe.Pointer is a basic type that includes nil.
   520  				if !hasNil(target) {
   521  					goto Error
   522  				}
   523  			default:
   524  				goto Error
   525  			}
   526  		}
   527  	case *Interface:
   528  		if !x.isNil() && !t.Empty() /* empty interfaces are ok */ {
   529  			goto Error
   530  		}
   531  		// Update operand types to the default type rather then
   532  		// the target (interface) type: values must have concrete
   533  		// dynamic types. If the value is nil, keep it untyped
   534  		// (this is important for tools such as go vet which need
   535  		// the dynamic type for argument checking of say, print
   536  		// functions)
   537  		if x.isNil() {
   538  			target = Typ[UntypedNil]
   539  		} else {
   540  			// cannot assign untyped values to non-empty interfaces
   541  			if !t.Empty() {
   542  				goto Error
   543  			}
   544  			target = Default(x.typ)
   545  		}
   546  	case *Pointer, *Signature, *Slice, *Map, *Chan:
   547  		if !x.isNil() {
   548  			goto Error
   549  		}
   550  		// keep nil untyped - see comment for interfaces, above
   551  		target = Typ[UntypedNil]
   552  	default:
   553  		goto Error
   554  	}
   555  
   556  	x.typ = target
   557  	check.updateExprType(x.expr, target, true) // UntypedNils are final
   558  	return
   559  
   560  Error:
   561  	check.errorf(x.pos(), "cannot convert %s to %s", x, target)
   562  	x.mode = invalid
   563  }
   564  
   565  func (check *Checker) comparison(x, y *operand, op token.Token) {
   566  	// spec: "In any comparison, the first operand must be assignable
   567  	// to the type of the second operand, or vice versa."
   568  	err := ""
   569  	if x.assignableTo(check.conf, y.typ, nil) || y.assignableTo(check.conf, x.typ, nil) {
   570  		defined := false
   571  		switch op {
   572  		case token.EQL, token.NEQ:
   573  			// spec: "The equality operators == and != apply to operands that are comparable."
   574  			defined = Comparable(x.typ) || x.isNil() && hasNil(y.typ) || y.isNil() && hasNil(x.typ)
   575  		case token.LSS, token.LEQ, token.GTR, token.GEQ:
   576  			// spec: The ordering operators <, <=, >, and >= apply to operands that are ordered."
   577  			defined = isOrdered(x.typ)
   578  		default:
   579  			unreachable()
   580  		}
   581  		if !defined {
   582  			typ := x.typ
   583  			if x.isNil() {
   584  				typ = y.typ
   585  			}
   586  			err = check.sprintf("operator %s not defined for %s", op, typ)
   587  		}
   588  	} else {
   589  		err = check.sprintf("mismatched types %s and %s", x.typ, y.typ)
   590  	}
   591  
   592  	if err != "" {
   593  		check.errorf(x.pos(), "cannot compare %s %s %s (%s)", x.expr, op, y.expr, err)
   594  		x.mode = invalid
   595  		return
   596  	}
   597  
   598  	if x.mode == constant_ && y.mode == constant_ {
   599  		x.val = constant.MakeBool(constant.Compare(x.val, op, y.val))
   600  		// The operands are never materialized; no need to update
   601  		// their types.
   602  	} else {
   603  		x.mode = value
   604  		// The operands have now their final types, which at run-
   605  		// time will be materialized. Update the expression trees.
   606  		// If the current types are untyped, the materialized type
   607  		// is the respective default type.
   608  		check.updateExprType(x.expr, Default(x.typ), true)
   609  		check.updateExprType(y.expr, Default(y.typ), true)
   610  	}
   611  
   612  	// spec: "Comparison operators compare two operands and yield
   613  	//        an untyped boolean value."
   614  	x.typ = Typ[UntypedBool]
   615  }
   616  
   617  func (check *Checker) shift(x, y *operand, e *ast.BinaryExpr, op token.Token) {
   618  	untypedx := isUntyped(x.typ)
   619  
   620  	var xval constant.Value
   621  	if x.mode == constant_ {
   622  		xval = constant.ToInt(x.val)
   623  	}
   624  
   625  	if isInteger(x.typ) || untypedx && xval != nil && xval.Kind() == constant.Int {
   626  		// The lhs is of integer type or an untyped constant representable
   627  		// as an integer. Nothing to do.
   628  	} else {
   629  		// shift has no chance
   630  		check.invalidOp(x.pos(), "shifted operand %s must be integer", x)
   631  		x.mode = invalid
   632  		return
   633  	}
   634  
   635  	// spec: "The right operand in a shift expression must have unsigned
   636  	// integer type or be an untyped constant representable by a value of
   637  	// type uint."
   638  	switch {
   639  	case isUnsigned(y.typ):
   640  		// nothing to do
   641  	case isUntyped(y.typ):
   642  		check.convertUntyped(y, Typ[Uint])
   643  		if y.mode == invalid {
   644  			x.mode = invalid
   645  			return
   646  		}
   647  	default:
   648  		check.invalidOp(y.pos(), "shift count %s must be unsigned integer", y)
   649  		x.mode = invalid
   650  		return
   651  	}
   652  
   653  	if x.mode == constant_ {
   654  		if y.mode == constant_ {
   655  			// rhs must be an integer value
   656  			yval := constant.ToInt(y.val)
   657  			if yval.Kind() != constant.Int {
   658  				check.invalidOp(y.pos(), "shift count %s must be unsigned integer", y)
   659  				x.mode = invalid
   660  				return
   661  			}
   662  			// rhs must be within reasonable bounds
   663  			const shiftBound = 1023 - 1 + 52 // so we can express smallestFloat64
   664  			s, ok := constant.Uint64Val(yval)
   665  			if !ok || s > shiftBound {
   666  				check.invalidOp(y.pos(), "invalid shift count %s", y)
   667  				x.mode = invalid
   668  				return
   669  			}
   670  			// The lhs is representable as an integer but may not be an integer
   671  			// (e.g., 2.0, an untyped float) - this can only happen for untyped
   672  			// non-integer numeric constants. Correct the type so that the shift
   673  			// result is of integer type.
   674  			if !isInteger(x.typ) {
   675  				x.typ = Typ[UntypedInt]
   676  			}
   677  			// x is a constant so xval != nil and it must be of Int kind.
   678  			x.val = constant.Shift(xval, op, uint(s))
   679  			// Typed constants must be representable in
   680  			// their type after each constant operation.
   681  			if isTyped(x.typ) {
   682  				if e != nil {
   683  					x.expr = e // for better error message
   684  				}
   685  				check.representable(x, x.typ.Underlying().(*Basic))
   686  			}
   687  			return
   688  		}
   689  
   690  		// non-constant shift with constant lhs
   691  		if untypedx {
   692  			// spec: "If the left operand of a non-constant shift
   693  			// expression is an untyped constant, the type of the
   694  			// constant is what it would be if the shift expression
   695  			// were replaced by its left operand alone.".
   696  			//
   697  			// Delay operand checking until we know the final type
   698  			// by marking the lhs expression as lhs shift operand.
   699  			//
   700  			// Usually (in correct programs), the lhs expression
   701  			// is in the untyped map. However, it is possible to
   702  			// create incorrect programs where the same expression
   703  			// is evaluated twice (via a declaration cycle) such
   704  			// that the lhs expression type is determined in the
   705  			// first round and thus deleted from the map, and then
   706  			// not found in the second round (double insertion of
   707  			// the same expr node still just leads to one entry for
   708  			// that node, and it can only be deleted once).
   709  			// Be cautious and check for presence of entry.
   710  			// Example: var e, f = int(1<<""[f]) // issue 11347
   711  			if info, found := check.untyped[x.expr]; found {
   712  				info.isLhs = true
   713  				check.untyped[x.expr] = info
   714  			}
   715  			// keep x's type
   716  			x.mode = value
   717  			return
   718  		}
   719  	}
   720  
   721  	// constant rhs must be >= 0
   722  	if y.mode == constant_ && constant.Sign(y.val) < 0 {
   723  		check.invalidOp(y.pos(), "shift count %s must not be negative", y)
   724  	}
   725  
   726  	// non-constant shift - lhs must be an integer
   727  	if !isInteger(x.typ) {
   728  		check.invalidOp(x.pos(), "shifted operand %s must be integer", x)
   729  		x.mode = invalid
   730  		return
   731  	}
   732  
   733  	x.mode = value
   734  }
   735  
   736  var binaryOpPredicates = opPredicates{
   737  	token.ADD: func(typ Type) bool { return isNumeric(typ) || isString(typ) },
   738  	token.SUB: isNumeric,
   739  	token.MUL: isNumeric,
   740  	token.QUO: isNumeric,
   741  	token.REM: isInteger,
   742  
   743  	token.AND:     isInteger,
   744  	token.OR:      isInteger,
   745  	token.XOR:     isInteger,
   746  	token.AND_NOT: isInteger,
   747  
   748  	token.LAND: isBoolean,
   749  	token.LOR:  isBoolean,
   750  }
   751  
   752  // The binary expression e may be nil. It's passed in for better error messages only.
   753  func (check *Checker) binary(x *operand, e *ast.BinaryExpr, lhs, rhs ast.Expr, op token.Token) {
   754  	var y operand
   755  
   756  	check.expr(x, lhs)
   757  	check.expr(&y, rhs)
   758  
   759  	if x.mode == invalid {
   760  		return
   761  	}
   762  	if y.mode == invalid {
   763  		x.mode = invalid
   764  		x.expr = y.expr
   765  		return
   766  	}
   767  
   768  	if isShift(op) {
   769  		check.shift(x, &y, e, op)
   770  		return
   771  	}
   772  
   773  	check.convertUntyped(x, y.typ)
   774  	if x.mode == invalid {
   775  		return
   776  	}
   777  	check.convertUntyped(&y, x.typ)
   778  	if y.mode == invalid {
   779  		x.mode = invalid
   780  		return
   781  	}
   782  
   783  	if isComparison(op) {
   784  		check.comparison(x, &y, op)
   785  		return
   786  	}
   787  
   788  	if !Identical(x.typ, y.typ) {
   789  		// only report an error if we have valid types
   790  		// (otherwise we had an error reported elsewhere already)
   791  		if x.typ != Typ[Invalid] && y.typ != Typ[Invalid] {
   792  			check.invalidOp(x.pos(), "mismatched types %s and %s", x.typ, y.typ)
   793  		}
   794  		x.mode = invalid
   795  		return
   796  	}
   797  
   798  	if !check.op(binaryOpPredicates, x, op) {
   799  		x.mode = invalid
   800  		return
   801  	}
   802  
   803  	if op == token.QUO || op == token.REM {
   804  		// check for zero divisor
   805  		if (x.mode == constant_ || isInteger(x.typ)) && y.mode == constant_ && constant.Sign(y.val) == 0 {
   806  			check.invalidOp(y.pos(), "division by zero")
   807  			x.mode = invalid
   808  			return
   809  		}
   810  
   811  		// check for divisor underflow in complex division (see issue 20227)
   812  		if x.mode == constant_ && y.mode == constant_ && isComplex(x.typ) {
   813  			re, im := constant.Real(y.val), constant.Imag(y.val)
   814  			re2, im2 := constant.BinaryOp(re, token.MUL, re), constant.BinaryOp(im, token.MUL, im)
   815  			if constant.Sign(re2) == 0 && constant.Sign(im2) == 0 {
   816  				check.invalidOp(y.pos(), "division by zero")
   817  				x.mode = invalid
   818  				return
   819  			}
   820  		}
   821  	}
   822  
   823  	if x.mode == constant_ && y.mode == constant_ {
   824  		xval := x.val
   825  		yval := y.val
   826  		typ := x.typ.Underlying().(*Basic)
   827  		// force integer division of integer operands
   828  		if op == token.QUO && isInteger(typ) {
   829  			op = token.QUO_ASSIGN
   830  		}
   831  		x.val = constant.BinaryOp(xval, op, yval)
   832  		// Typed constants must be representable in
   833  		// their type after each constant operation.
   834  		if isTyped(typ) {
   835  			if e != nil {
   836  				x.expr = e // for better error message
   837  			}
   838  			check.representable(x, typ)
   839  		}
   840  		return
   841  	}
   842  
   843  	x.mode = value
   844  	// x.typ is unchanged
   845  }
   846  
   847  // index checks an index expression for validity.
   848  // If max >= 0, it is the upper bound for index.
   849  // If index is valid and the result i >= 0, then i is the constant value of index.
   850  func (check *Checker) index(index ast.Expr, max int64) (i int64, valid bool) {
   851  	var x operand
   852  	check.expr(&x, index)
   853  	if x.mode == invalid {
   854  		return
   855  	}
   856  
   857  	// an untyped constant must be representable as Int
   858  	check.convertUntyped(&x, Typ[Int])
   859  	if x.mode == invalid {
   860  		return
   861  	}
   862  
   863  	// the index must be of integer type
   864  	if !isInteger(x.typ) {
   865  		check.invalidArg(x.pos(), "index %s must be integer", &x)
   866  		return
   867  	}
   868  
   869  	// a constant index i must be in bounds
   870  	if x.mode == constant_ {
   871  		if constant.Sign(x.val) < 0 {
   872  			check.invalidArg(x.pos(), "index %s must not be negative", &x)
   873  			return
   874  		}
   875  		i, valid = constant.Int64Val(constant.ToInt(x.val))
   876  		if !valid || max >= 0 && i >= max {
   877  			check.errorf(x.pos(), "index %s is out of bounds", &x)
   878  			return i, false
   879  		}
   880  		// 0 <= i [ && i < max ]
   881  		return i, true
   882  	}
   883  
   884  	return -1, true
   885  }
   886  
   887  // indexElts checks the elements (elts) of an array or slice composite literal
   888  // against the literal's element type (typ), and the element indices against
   889  // the literal length if known (length >= 0). It returns the length of the
   890  // literal (maximum index value + 1).
   891  //
   892  func (check *Checker) indexedElts(elts []ast.Expr, typ Type, length int64) int64 {
   893  	visited := make(map[int64]bool, len(elts))
   894  	var index, max int64
   895  	for _, e := range elts {
   896  		// determine and check index
   897  		validIndex := false
   898  		eval := e
   899  		if kv, _ := e.(*ast.KeyValueExpr); kv != nil {
   900  			if i, ok := check.index(kv.Key, length); ok {
   901  				if i >= 0 {
   902  					index = i
   903  					validIndex = true
   904  				} else {
   905  					check.errorf(e.Pos(), "index %s must be integer constant", kv.Key)
   906  				}
   907  			}
   908  			eval = kv.Value
   909  		} else if length >= 0 && index >= length {
   910  			check.errorf(e.Pos(), "index %d is out of bounds (>= %d)", index, length)
   911  		} else {
   912  			validIndex = true
   913  		}
   914  
   915  		// if we have a valid index, check for duplicate entries
   916  		if validIndex {
   917  			if visited[index] {
   918  				check.errorf(e.Pos(), "duplicate index %d in array or slice literal", index)
   919  			}
   920  			visited[index] = true
   921  		}
   922  		index++
   923  		if index > max {
   924  			max = index
   925  		}
   926  
   927  		// check element against composite literal element type
   928  		var x operand
   929  		check.exprWithHint(&x, eval, typ)
   930  		check.assignment(&x, typ, "array or slice literal")
   931  	}
   932  	return max
   933  }
   934  
   935  // exprKind describes the kind of an expression; the kind
   936  // determines if an expression is valid in 'statement context'.
   937  type exprKind int
   938  
   939  const (
   940  	conversion exprKind = iota
   941  	expression
   942  	statement
   943  )
   944  
   945  // rawExpr typechecks expression e and initializes x with the expression
   946  // value or type. If an error occurred, x.mode is set to invalid.
   947  // If hint != nil, it is the type of a composite literal element.
   948  //
   949  func (check *Checker) rawExpr(x *operand, e ast.Expr, hint Type) exprKind {
   950  	if trace {
   951  		check.trace(e.Pos(), "%s", e)
   952  		check.indent++
   953  		defer func() {
   954  			check.indent--
   955  			check.trace(e.Pos(), "=> %s", x)
   956  		}()
   957  	}
   958  
   959  	kind := check.exprInternal(x, e, hint)
   960  
   961  	// convert x into a user-friendly set of values
   962  	// TODO(gri) this code can be simplified
   963  	var typ Type
   964  	var val constant.Value
   965  	switch x.mode {
   966  	case invalid:
   967  		typ = Typ[Invalid]
   968  	case novalue:
   969  		typ = (*Tuple)(nil)
   970  	case constant_:
   971  		typ = x.typ
   972  		val = x.val
   973  	default:
   974  		typ = x.typ
   975  	}
   976  	assert(x.expr != nil && typ != nil)
   977  
   978  	if isUntyped(typ) {
   979  		// delay type and value recording until we know the type
   980  		// or until the end of type checking
   981  		check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
   982  	} else {
   983  		check.recordTypeAndValue(e, x.mode, typ, val)
   984  	}
   985  
   986  	return kind
   987  }
   988  
   989  // exprInternal contains the core of type checking of expressions.
   990  // Must only be called by rawExpr.
   991  //
   992  func (check *Checker) exprInternal(x *operand, e ast.Expr, hint Type) exprKind {
   993  	// make sure x has a valid state in case of bailout
   994  	// (was issue 5770)
   995  	x.mode = invalid
   996  	x.typ = Typ[Invalid]
   997  
   998  	switch e := e.(type) {
   999  	case *ast.BadExpr:
  1000  		goto Error // error was reported before
  1001  
  1002  	case *ast.Ident:
  1003  		check.ident(x, e, nil, nil)
  1004  
  1005  	case *ast.Ellipsis:
  1006  		// ellipses are handled explicitly where they are legal
  1007  		// (array composite literals and parameter lists)
  1008  		check.error(e.Pos(), "invalid use of '...'")
  1009  		goto Error
  1010  
  1011  	case *ast.BasicLit:
  1012  		x.setConst(e.Kind, e.Value)
  1013  		if x.mode == invalid {
  1014  			check.invalidAST(e.Pos(), "invalid literal %v", e.Value)
  1015  			goto Error
  1016  		}
  1017  
  1018  	case *ast.FuncLit:
  1019  		if sig, ok := check.typ(e.Type).(*Signature); ok {
  1020  			// Anonymous functions are considered part of the
  1021  			// init expression/func declaration which contains
  1022  			// them: use existing package-level declaration info.
  1023  			check.funcBody(check.decl, "", sig, e.Body)
  1024  			x.mode = value
  1025  			x.typ = sig
  1026  		} else {
  1027  			check.invalidAST(e.Pos(), "invalid function literal %s", e)
  1028  			goto Error
  1029  		}
  1030  
  1031  	case *ast.CompositeLit:
  1032  		var typ, base Type
  1033  
  1034  		switch {
  1035  		case e.Type != nil:
  1036  			// composite literal type present - use it
  1037  			// [...]T array types may only appear with composite literals.
  1038  			// Check for them here so we don't have to handle ... in general.
  1039  			if atyp, _ := e.Type.(*ast.ArrayType); atyp != nil && atyp.Len != nil {
  1040  				if ellip, _ := atyp.Len.(*ast.Ellipsis); ellip != nil && ellip.Elt == nil {
  1041  					// We have an "open" [...]T array type.
  1042  					// Create a new ArrayType with unknown length (-1)
  1043  					// and finish setting it up after analyzing the literal.
  1044  					typ = &Array{len: -1, elem: check.typ(atyp.Elt)}
  1045  					base = typ
  1046  					break
  1047  				}
  1048  			}
  1049  			typ = check.typ(e.Type)
  1050  			base = typ
  1051  
  1052  		case hint != nil:
  1053  			// no composite literal type present - use hint (element type of enclosing type)
  1054  			typ = hint
  1055  			base, _ = deref(typ.Underlying()) // *T implies &T{}
  1056  
  1057  		default:
  1058  			// TODO(gri) provide better error messages depending on context
  1059  			check.error(e.Pos(), "missing type in composite literal")
  1060  			goto Error
  1061  		}
  1062  
  1063  		switch utyp := base.Underlying().(type) {
  1064  		case *Struct:
  1065  			if len(e.Elts) == 0 {
  1066  				break
  1067  			}
  1068  			fields := utyp.fields
  1069  			if _, ok := e.Elts[0].(*ast.KeyValueExpr); ok {
  1070  				// all elements must have keys
  1071  				visited := make([]bool, len(fields))
  1072  				for _, e := range e.Elts {
  1073  					kv, _ := e.(*ast.KeyValueExpr)
  1074  					if kv == nil {
  1075  						check.error(e.Pos(), "mixture of field:value and value elements in struct literal")
  1076  						continue
  1077  					}
  1078  					key, _ := kv.Key.(*ast.Ident)
  1079  					if key == nil {
  1080  						check.errorf(kv.Pos(), "invalid field name %s in struct literal", kv.Key)
  1081  						continue
  1082  					}
  1083  					i := fieldIndex(utyp.fields, check.pkg, key.Name)
  1084  					if i < 0 {
  1085  						check.errorf(kv.Pos(), "unknown field %s in struct literal", key.Name)
  1086  						continue
  1087  					}
  1088  					fld := fields[i]
  1089  					check.recordUse(key, fld)
  1090  					// 0 <= i < len(fields)
  1091  					if visited[i] {
  1092  						check.errorf(kv.Pos(), "duplicate field name %s in struct literal", key.Name)
  1093  						continue
  1094  					}
  1095  					visited[i] = true
  1096  					check.expr(x, kv.Value)
  1097  					etyp := fld.typ
  1098  					check.assignment(x, etyp, "struct literal")
  1099  				}
  1100  			} else {
  1101  				// no element must have a key
  1102  				for i, e := range e.Elts {
  1103  					if kv, _ := e.(*ast.KeyValueExpr); kv != nil {
  1104  						check.error(kv.Pos(), "mixture of field:value and value elements in struct literal")
  1105  						continue
  1106  					}
  1107  					check.expr(x, e)
  1108  					if i >= len(fields) {
  1109  						check.error(x.pos(), "too many values in struct literal")
  1110  						break // cannot continue
  1111  					}
  1112  					// i < len(fields)
  1113  					fld := fields[i]
  1114  					if !fld.Exported() && fld.pkg != check.pkg {
  1115  						check.errorf(x.pos(), "implicit assignment to unexported field %s in %s literal", fld.name, typ)
  1116  						continue
  1117  					}
  1118  					etyp := fld.typ
  1119  					check.assignment(x, etyp, "struct literal")
  1120  				}
  1121  				if len(e.Elts) < len(fields) {
  1122  					check.error(e.Rbrace, "too few values in struct literal")
  1123  					// ok to continue
  1124  				}
  1125  			}
  1126  
  1127  		case *Array:
  1128  			n := check.indexedElts(e.Elts, utyp.elem, utyp.len)
  1129  			// If we have an "open" [...]T array, set the length now that we know it
  1130  			// and record the type for [...] (usually done by check.typExpr which is
  1131  			// not called for [...]).
  1132  			if utyp.len < 0 {
  1133  				utyp.len = n
  1134  				check.recordTypeAndValue(e.Type, typexpr, utyp, nil)
  1135  			}
  1136  
  1137  		case *Slice:
  1138  			check.indexedElts(e.Elts, utyp.elem, -1)
  1139  
  1140  		case *Map:
  1141  			visited := make(map[interface{}][]Type, len(e.Elts))
  1142  			for _, e := range e.Elts {
  1143  				kv, _ := e.(*ast.KeyValueExpr)
  1144  				if kv == nil {
  1145  					check.error(e.Pos(), "missing key in map literal")
  1146  					continue
  1147  				}
  1148  				check.exprWithHint(x, kv.Key, utyp.key)
  1149  				check.assignment(x, utyp.key, "map literal")
  1150  				if x.mode == invalid {
  1151  					continue
  1152  				}
  1153  				if x.mode == constant_ {
  1154  					duplicate := false
  1155  					// if the key is of interface type, the type is also significant when checking for duplicates
  1156  					if _, ok := utyp.key.Underlying().(*Interface); ok {
  1157  						for _, vtyp := range visited[x.val] {
  1158  							if Identical(vtyp, x.typ) {
  1159  								duplicate = true
  1160  								break
  1161  							}
  1162  						}
  1163  						visited[x.val] = append(visited[x.val], x.typ)
  1164  					} else {
  1165  						_, duplicate = visited[x.val]
  1166  						visited[x.val] = nil
  1167  					}
  1168  					if duplicate {
  1169  						check.errorf(x.pos(), "duplicate key %s in map literal", x.val)
  1170  						continue
  1171  					}
  1172  				}
  1173  				check.exprWithHint(x, kv.Value, utyp.elem)
  1174  				check.assignment(x, utyp.elem, "map literal")
  1175  			}
  1176  
  1177  		default:
  1178  			// when "using" all elements unpack KeyValueExpr
  1179  			// explicitly because check.use doesn't accept them
  1180  			for _, e := range e.Elts {
  1181  				if kv, _ := e.(*ast.KeyValueExpr); kv != nil {
  1182  					// Ideally, we should also "use" kv.Key but we can't know
  1183  					// if it's an externally defined struct key or not. Going
  1184  					// forward anyway can lead to other errors. Give up instead.
  1185  					e = kv.Value
  1186  				}
  1187  				check.use(e)
  1188  			}
  1189  			// if utyp is invalid, an error was reported before
  1190  			if utyp != Typ[Invalid] {
  1191  				check.errorf(e.Pos(), "invalid composite literal type %s", typ)
  1192  				goto Error
  1193  			}
  1194  		}
  1195  
  1196  		x.mode = value
  1197  		x.typ = typ
  1198  
  1199  	case *ast.ParenExpr:
  1200  		kind := check.rawExpr(x, e.X, nil)
  1201  		x.expr = e
  1202  		return kind
  1203  
  1204  	case *ast.SelectorExpr:
  1205  		check.selector(x, e)
  1206  
  1207  	case *ast.IndexExpr:
  1208  		check.expr(x, e.X)
  1209  		if x.mode == invalid {
  1210  			check.use(e.Index)
  1211  			goto Error
  1212  		}
  1213  
  1214  		valid := false
  1215  		length := int64(-1) // valid if >= 0
  1216  		switch typ := x.typ.Underlying().(type) {
  1217  		case *Basic:
  1218  			if isString(typ) {
  1219  				valid = true
  1220  				if x.mode == constant_ {
  1221  					length = int64(len(constant.StringVal(x.val)))
  1222  				}
  1223  				// an indexed string always yields a byte value
  1224  				// (not a constant) even if the string and the
  1225  				// index are constant
  1226  				x.mode = value
  1227  				x.typ = universeByte // use 'byte' name
  1228  			}
  1229  
  1230  		case *Array:
  1231  			valid = true
  1232  			length = typ.len
  1233  			if x.mode != variable {
  1234  				x.mode = value
  1235  			}
  1236  			x.typ = typ.elem
  1237  
  1238  		case *Pointer:
  1239  			if typ, _ := typ.base.Underlying().(*Array); typ != nil {
  1240  				valid = true
  1241  				length = typ.len
  1242  				x.mode = variable
  1243  				x.typ = typ.elem
  1244  			}
  1245  
  1246  		case *Slice:
  1247  			valid = true
  1248  			x.mode = variable
  1249  			x.typ = typ.elem
  1250  
  1251  		case *Map:
  1252  			var key operand
  1253  			check.expr(&key, e.Index)
  1254  			check.assignment(&key, typ.key, "map index")
  1255  			if x.mode == invalid {
  1256  				goto Error
  1257  			}
  1258  			x.mode = mapindex
  1259  			x.typ = typ.elem
  1260  			x.expr = e
  1261  			return expression
  1262  		}
  1263  
  1264  		if !valid {
  1265  			check.invalidOp(x.pos(), "cannot index %s", x)
  1266  			goto Error
  1267  		}
  1268  
  1269  		if e.Index == nil {
  1270  			check.invalidAST(e.Pos(), "missing index for %s", x)
  1271  			goto Error
  1272  		}
  1273  
  1274  		check.index(e.Index, length)
  1275  		// ok to continue
  1276  
  1277  	case *ast.SliceExpr:
  1278  		check.expr(x, e.X)
  1279  		if x.mode == invalid {
  1280  			check.use(e.Low, e.High, e.Max)
  1281  			goto Error
  1282  		}
  1283  
  1284  		valid := false
  1285  		length := int64(-1) // valid if >= 0
  1286  		switch typ := x.typ.Underlying().(type) {
  1287  		case *Basic:
  1288  			if isString(typ) {
  1289  				if e.Slice3 {
  1290  					check.invalidOp(x.pos(), "3-index slice of string")
  1291  					goto Error
  1292  				}
  1293  				valid = true
  1294  				if x.mode == constant_ {
  1295  					length = int64(len(constant.StringVal(x.val)))
  1296  				}
  1297  				// spec: "For untyped string operands the result
  1298  				// is a non-constant value of type string."
  1299  				if typ.kind == UntypedString {
  1300  					x.typ = Typ[String]
  1301  				}
  1302  			}
  1303  
  1304  		case *Array:
  1305  			valid = true
  1306  			length = typ.len
  1307  			if x.mode != variable {
  1308  				check.invalidOp(x.pos(), "cannot slice %s (value not addressable)", x)
  1309  				goto Error
  1310  			}
  1311  			x.typ = &Slice{elem: typ.elem}
  1312  
  1313  		case *Pointer:
  1314  			if typ, _ := typ.base.Underlying().(*Array); typ != nil {
  1315  				valid = true
  1316  				length = typ.len
  1317  				x.typ = &Slice{elem: typ.elem}
  1318  			}
  1319  
  1320  		case *Slice:
  1321  			valid = true
  1322  			// x.typ doesn't change
  1323  		}
  1324  
  1325  		if !valid {
  1326  			check.invalidOp(x.pos(), "cannot slice %s", x)
  1327  			goto Error
  1328  		}
  1329  
  1330  		x.mode = value
  1331  
  1332  		// spec: "Only the first index may be omitted; it defaults to 0."
  1333  		if e.Slice3 && (e.High == nil || e.Max == nil) {
  1334  			check.error(e.Rbrack, "2nd and 3rd index required in 3-index slice")
  1335  			goto Error
  1336  		}
  1337  
  1338  		// check indices
  1339  		var ind [3]int64
  1340  		for i, expr := range []ast.Expr{e.Low, e.High, e.Max} {
  1341  			x := int64(-1)
  1342  			switch {
  1343  			case expr != nil:
  1344  				// The "capacity" is only known statically for strings, arrays,
  1345  				// and pointers to arrays, and it is the same as the length for
  1346  				// those types.
  1347  				max := int64(-1)
  1348  				if length >= 0 {
  1349  					max = length + 1
  1350  				}
  1351  				if t, ok := check.index(expr, max); ok && t >= 0 {
  1352  					x = t
  1353  				}
  1354  			case i == 0:
  1355  				// default is 0 for the first index
  1356  				x = 0
  1357  			case length >= 0:
  1358  				// default is length (== capacity) otherwise
  1359  				x = length
  1360  			}
  1361  			ind[i] = x
  1362  		}
  1363  
  1364  		// constant indices must be in range
  1365  		// (check.index already checks that existing indices >= 0)
  1366  	L:
  1367  		for i, x := range ind[:len(ind)-1] {
  1368  			if x > 0 {
  1369  				for _, y := range ind[i+1:] {
  1370  					if y >= 0 && x > y {
  1371  						check.errorf(e.Rbrack, "invalid slice indices: %d > %d", x, y)
  1372  						break L // only report one error, ok to continue
  1373  					}
  1374  				}
  1375  			}
  1376  		}
  1377  
  1378  	case *ast.TypeAssertExpr:
  1379  		check.expr(x, e.X)
  1380  		if x.mode == invalid {
  1381  			goto Error
  1382  		}
  1383  		xtyp, _ := x.typ.Underlying().(*Interface)
  1384  		if xtyp == nil {
  1385  			check.invalidOp(x.pos(), "%s is not an interface", x)
  1386  			goto Error
  1387  		}
  1388  		// x.(type) expressions are handled explicitly in type switches
  1389  		if e.Type == nil {
  1390  			check.invalidAST(e.Pos(), "use of .(type) outside type switch")
  1391  			goto Error
  1392  		}
  1393  		T := check.typ(e.Type)
  1394  		if T == Typ[Invalid] {
  1395  			goto Error
  1396  		}
  1397  		check.typeAssertion(x.pos(), x, xtyp, T)
  1398  		x.mode = commaok
  1399  		x.typ = T
  1400  
  1401  	case *ast.CallExpr:
  1402  		return check.call(x, e)
  1403  
  1404  	case *ast.StarExpr:
  1405  		check.exprOrType(x, e.X)
  1406  		switch x.mode {
  1407  		case invalid:
  1408  			goto Error
  1409  		case typexpr:
  1410  			x.typ = &Pointer{base: x.typ}
  1411  		default:
  1412  			if typ, ok := x.typ.Underlying().(*Pointer); ok {
  1413  				x.mode = variable
  1414  				x.typ = typ.base
  1415  			} else {
  1416  				check.invalidOp(x.pos(), "cannot indirect %s", x)
  1417  				goto Error
  1418  			}
  1419  		}
  1420  
  1421  	case *ast.UnaryExpr:
  1422  		check.expr(x, e.X)
  1423  		if x.mode == invalid {
  1424  			goto Error
  1425  		}
  1426  		check.unary(x, e, e.Op)
  1427  		if x.mode == invalid {
  1428  			goto Error
  1429  		}
  1430  		if e.Op == token.ARROW {
  1431  			x.expr = e
  1432  			return statement // receive operations may appear in statement context
  1433  		}
  1434  
  1435  	case *ast.BinaryExpr:
  1436  		check.binary(x, e, e.X, e.Y, e.Op)
  1437  		if x.mode == invalid {
  1438  			goto Error
  1439  		}
  1440  
  1441  	case *ast.KeyValueExpr:
  1442  		// key:value expressions are handled in composite literals
  1443  		check.invalidAST(e.Pos(), "no key:value expected")
  1444  		goto Error
  1445  
  1446  	case *ast.ArrayType, *ast.StructType, *ast.FuncType,
  1447  		*ast.InterfaceType, *ast.MapType, *ast.ChanType:
  1448  		x.mode = typexpr
  1449  		x.typ = check.typ(e)
  1450  		// Note: rawExpr (caller of exprInternal) will call check.recordTypeAndValue
  1451  		// even though check.typ has already called it. This is fine as both
  1452  		// times the same expression and type are recorded. It is also not a
  1453  		// performance issue because we only reach here for composite literal
  1454  		// types, which are comparatively rare.
  1455  
  1456  	default:
  1457  		panic(fmt.Sprintf("%s: unknown expression type %T", check.fset.Position(e.Pos()), e))
  1458  	}
  1459  
  1460  	// everything went well
  1461  	x.expr = e
  1462  	return expression
  1463  
  1464  Error:
  1465  	x.mode = invalid
  1466  	x.expr = e
  1467  	return statement // avoid follow-up errors
  1468  }
  1469  
  1470  // typeAssertion checks that x.(T) is legal; xtyp must be the type of x.
  1471  func (check *Checker) typeAssertion(pos token.Pos, x *operand, xtyp *Interface, T Type) {
  1472  	method, wrongType := assertableTo(xtyp, T)
  1473  	if method == nil {
  1474  		return
  1475  	}
  1476  
  1477  	var msg string
  1478  	if wrongType {
  1479  		msg = "wrong type for method"
  1480  	} else {
  1481  		msg = "missing method"
  1482  	}
  1483  	check.errorf(pos, "%s cannot have dynamic type %s (%s %s)", x, T, msg, method.name)
  1484  }
  1485  
  1486  func (check *Checker) singleValue(x *operand) {
  1487  	if x.mode == value {
  1488  		// tuple types are never named - no need for underlying type below
  1489  		if t, ok := x.typ.(*Tuple); ok {
  1490  			assert(t.Len() != 1)
  1491  			check.errorf(x.pos(), "%d-valued %s where single value is expected", t.Len(), x)
  1492  			x.mode = invalid
  1493  		}
  1494  	}
  1495  }
  1496  
  1497  // expr typechecks expression e and initializes x with the expression value.
  1498  // The result must be a single value.
  1499  // If an error occurred, x.mode is set to invalid.
  1500  //
  1501  func (check *Checker) expr(x *operand, e ast.Expr) {
  1502  	check.multiExpr(x, e)
  1503  	check.singleValue(x)
  1504  }
  1505  
  1506  // multiExpr is like expr but the result may be a multi-value.
  1507  func (check *Checker) multiExpr(x *operand, e ast.Expr) {
  1508  	check.rawExpr(x, e, nil)
  1509  	var msg string
  1510  	switch x.mode {
  1511  	default:
  1512  		return
  1513  	case novalue:
  1514  		msg = "%s used as value"
  1515  	case builtin:
  1516  		msg = "%s must be called"
  1517  	case typexpr:
  1518  		msg = "%s is not an expression"
  1519  	}
  1520  	check.errorf(x.pos(), msg, x)
  1521  	x.mode = invalid
  1522  }
  1523  
  1524  // exprWithHint typechecks expression e and initializes x with the expression value;
  1525  // hint is the type of a composite literal element.
  1526  // If an error occurred, x.mode is set to invalid.
  1527  //
  1528  func (check *Checker) exprWithHint(x *operand, e ast.Expr, hint Type) {
  1529  	assert(hint != nil)
  1530  	check.rawExpr(x, e, hint)
  1531  	check.singleValue(x)
  1532  	var msg string
  1533  	switch x.mode {
  1534  	default:
  1535  		return
  1536  	case novalue:
  1537  		msg = "%s used as value"
  1538  	case builtin:
  1539  		msg = "%s must be called"
  1540  	case typexpr:
  1541  		msg = "%s is not an expression"
  1542  	}
  1543  	check.errorf(x.pos(), msg, x)
  1544  	x.mode = invalid
  1545  }
  1546  
  1547  // exprOrType typechecks expression or type e and initializes x with the expression value or type.
  1548  // If an error occurred, x.mode is set to invalid.
  1549  //
  1550  func (check *Checker) exprOrType(x *operand, e ast.Expr) {
  1551  	check.rawExpr(x, e, nil)
  1552  	check.singleValue(x)
  1553  	if x.mode == novalue {
  1554  		check.errorf(x.pos(), "%s used as value or type", x)
  1555  		x.mode = invalid
  1556  	}
  1557  }