github.com/mattn/go@v0.0.0-20171011075504-07f7db3ea99f/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  		// The operands don't need to be updated since they
   406  		// never get "materialized" into a typed value. If
   407  		// left in the untyped map, they will be processed
   408  		// at the end of the type check.
   409  		if old.val != nil {
   410  			break
   411  		}
   412  		check.updateExprType(x.X, typ, final)
   413  
   414  	case *ast.BinaryExpr:
   415  		if old.val != nil {
   416  			break // see comment for unary expressions
   417  		}
   418  		if isComparison(x.Op) {
   419  			// The result type is independent of operand types
   420  			// and the operand types must have final types.
   421  		} else if isShift(x.Op) {
   422  			// The result type depends only on lhs operand.
   423  			// The rhs type was updated when checking the shift.
   424  			check.updateExprType(x.X, typ, final)
   425  		} else {
   426  			// The operand types match the result type.
   427  			check.updateExprType(x.X, typ, final)
   428  			check.updateExprType(x.Y, typ, final)
   429  		}
   430  
   431  	default:
   432  		unreachable()
   433  	}
   434  
   435  	// If the new type is not final and still untyped, just
   436  	// update the recorded type.
   437  	if !final && isUntyped(typ) {
   438  		old.typ = typ.Underlying().(*Basic)
   439  		check.untyped[x] = old
   440  		return
   441  	}
   442  
   443  	// Otherwise we have the final (typed or untyped type).
   444  	// Remove it from the map of yet untyped expressions.
   445  	delete(check.untyped, x)
   446  
   447  	if old.isLhs {
   448  		// If x is the lhs of a shift, its final type must be integer.
   449  		// We already know from the shift check that it is representable
   450  		// as an integer if it is a constant.
   451  		if !isInteger(typ) {
   452  			check.invalidOp(x.Pos(), "shifted operand %s (type %s) must be integer", x, typ)
   453  			return
   454  		}
   455  	} else if old.val != nil {
   456  		// If x is a constant, it must be representable as a value of typ.
   457  		c := operand{old.mode, x, old.typ, old.val, 0}
   458  		check.convertUntyped(&c, typ)
   459  		if c.mode == invalid {
   460  			return
   461  		}
   462  	}
   463  
   464  	// Everything's fine, record final type and value for x.
   465  	check.recordTypeAndValue(x, old.mode, typ, old.val)
   466  }
   467  
   468  // updateExprVal updates the value of x to val.
   469  func (check *Checker) updateExprVal(x ast.Expr, val constant.Value) {
   470  	if info, ok := check.untyped[x]; ok {
   471  		info.val = val
   472  		check.untyped[x] = info
   473  	}
   474  }
   475  
   476  // convertUntyped attempts to set the type of an untyped value to the target type.
   477  func (check *Checker) convertUntyped(x *operand, target Type) {
   478  	if x.mode == invalid || isTyped(x.typ) || target == Typ[Invalid] {
   479  		return
   480  	}
   481  
   482  	// TODO(gri) Sloppy code - clean up. This function is central
   483  	//           to assignment and expression checking.
   484  
   485  	if isUntyped(target) {
   486  		// both x and target are untyped
   487  		xkind := x.typ.(*Basic).kind
   488  		tkind := target.(*Basic).kind
   489  		if isNumeric(x.typ) && isNumeric(target) {
   490  			if xkind < tkind {
   491  				x.typ = target
   492  				check.updateExprType(x.expr, target, false)
   493  			}
   494  		} else if xkind != tkind {
   495  			goto Error
   496  		}
   497  		return
   498  	}
   499  
   500  	// typed target
   501  	switch t := target.Underlying().(type) {
   502  	case *Basic:
   503  		if x.mode == constant_ {
   504  			check.representable(x, t)
   505  			if x.mode == invalid {
   506  				return
   507  			}
   508  			// expression value may have been rounded - update if needed
   509  			check.updateExprVal(x.expr, x.val)
   510  		} else {
   511  			// Non-constant untyped values may appear as the
   512  			// result of comparisons (untyped bool), intermediate
   513  			// (delayed-checked) rhs operands of shifts, and as
   514  			// the value nil.
   515  			switch x.typ.(*Basic).kind {
   516  			case UntypedBool:
   517  				if !isBoolean(target) {
   518  					goto Error
   519  				}
   520  			case UntypedInt, UntypedRune, UntypedFloat, UntypedComplex:
   521  				if !isNumeric(target) {
   522  					goto Error
   523  				}
   524  			case UntypedString:
   525  				// Non-constant untyped string values are not
   526  				// permitted by the spec and should not occur.
   527  				unreachable()
   528  			case UntypedNil:
   529  				// Unsafe.Pointer is a basic type that includes nil.
   530  				if !hasNil(target) {
   531  					goto Error
   532  				}
   533  			default:
   534  				goto Error
   535  			}
   536  		}
   537  	case *Interface:
   538  		if !x.isNil() && !t.Empty() /* empty interfaces are ok */ {
   539  			goto Error
   540  		}
   541  		// Update operand types to the default type rather then
   542  		// the target (interface) type: values must have concrete
   543  		// dynamic types. If the value is nil, keep it untyped
   544  		// (this is important for tools such as go vet which need
   545  		// the dynamic type for argument checking of say, print
   546  		// functions)
   547  		if x.isNil() {
   548  			target = Typ[UntypedNil]
   549  		} else {
   550  			// cannot assign untyped values to non-empty interfaces
   551  			if !t.Empty() {
   552  				goto Error
   553  			}
   554  			target = Default(x.typ)
   555  		}
   556  	case *Pointer, *Signature, *Slice, *Map, *Chan:
   557  		if !x.isNil() {
   558  			goto Error
   559  		}
   560  		// keep nil untyped - see comment for interfaces, above
   561  		target = Typ[UntypedNil]
   562  	default:
   563  		goto Error
   564  	}
   565  
   566  	x.typ = target
   567  	check.updateExprType(x.expr, target, true) // UntypedNils are final
   568  	return
   569  
   570  Error:
   571  	check.errorf(x.pos(), "cannot convert %s to %s", x, target)
   572  	x.mode = invalid
   573  }
   574  
   575  func (check *Checker) comparison(x, y *operand, op token.Token) {
   576  	// spec: "In any comparison, the first operand must be assignable
   577  	// to the type of the second operand, or vice versa."
   578  	err := ""
   579  	if x.assignableTo(check.conf, y.typ, nil) || y.assignableTo(check.conf, x.typ, nil) {
   580  		defined := false
   581  		switch op {
   582  		case token.EQL, token.NEQ:
   583  			// spec: "The equality operators == and != apply to operands that are comparable."
   584  			defined = Comparable(x.typ) || x.isNil() && hasNil(y.typ) || y.isNil() && hasNil(x.typ)
   585  		case token.LSS, token.LEQ, token.GTR, token.GEQ:
   586  			// spec: The ordering operators <, <=, >, and >= apply to operands that are ordered."
   587  			defined = isOrdered(x.typ)
   588  		default:
   589  			unreachable()
   590  		}
   591  		if !defined {
   592  			typ := x.typ
   593  			if x.isNil() {
   594  				typ = y.typ
   595  			}
   596  			err = check.sprintf("operator %s not defined for %s", op, typ)
   597  		}
   598  	} else {
   599  		err = check.sprintf("mismatched types %s and %s", x.typ, y.typ)
   600  	}
   601  
   602  	if err != "" {
   603  		check.errorf(x.pos(), "cannot compare %s %s %s (%s)", x.expr, op, y.expr, err)
   604  		x.mode = invalid
   605  		return
   606  	}
   607  
   608  	if x.mode == constant_ && y.mode == constant_ {
   609  		x.val = constant.MakeBool(constant.Compare(x.val, op, y.val))
   610  		// The operands are never materialized; no need to update
   611  		// their types.
   612  	} else {
   613  		x.mode = value
   614  		// The operands have now their final types, which at run-
   615  		// time will be materialized. Update the expression trees.
   616  		// If the current types are untyped, the materialized type
   617  		// is the respective default type.
   618  		check.updateExprType(x.expr, Default(x.typ), true)
   619  		check.updateExprType(y.expr, Default(y.typ), true)
   620  	}
   621  
   622  	// spec: "Comparison operators compare two operands and yield
   623  	//        an untyped boolean value."
   624  	x.typ = Typ[UntypedBool]
   625  }
   626  
   627  func (check *Checker) shift(x, y *operand, e *ast.BinaryExpr, op token.Token) {
   628  	untypedx := isUntyped(x.typ)
   629  
   630  	var xval constant.Value
   631  	if x.mode == constant_ {
   632  		xval = constant.ToInt(x.val)
   633  	}
   634  
   635  	if isInteger(x.typ) || untypedx && xval != nil && xval.Kind() == constant.Int {
   636  		// The lhs is of integer type or an untyped constant representable
   637  		// as an integer. Nothing to do.
   638  	} else {
   639  		// shift has no chance
   640  		check.invalidOp(x.pos(), "shifted operand %s must be integer", x)
   641  		x.mode = invalid
   642  		return
   643  	}
   644  
   645  	// spec: "The right operand in a shift expression must have unsigned
   646  	// integer type or be an untyped constant representable by a value of
   647  	// type uint."
   648  	switch {
   649  	case isUnsigned(y.typ):
   650  		// nothing to do
   651  	case isUntyped(y.typ):
   652  		check.convertUntyped(y, Typ[Uint])
   653  		if y.mode == invalid {
   654  			x.mode = invalid
   655  			return
   656  		}
   657  	default:
   658  		check.invalidOp(y.pos(), "shift count %s must be unsigned integer", y)
   659  		x.mode = invalid
   660  		return
   661  	}
   662  
   663  	if x.mode == constant_ {
   664  		if y.mode == constant_ {
   665  			// rhs must be an integer value
   666  			yval := constant.ToInt(y.val)
   667  			if yval.Kind() != constant.Int {
   668  				check.invalidOp(y.pos(), "shift count %s must be unsigned integer", y)
   669  				x.mode = invalid
   670  				return
   671  			}
   672  			// rhs must be within reasonable bounds
   673  			const shiftBound = 1023 - 1 + 52 // so we can express smallestFloat64
   674  			s, ok := constant.Uint64Val(yval)
   675  			if !ok || s > shiftBound {
   676  				check.invalidOp(y.pos(), "invalid shift count %s", y)
   677  				x.mode = invalid
   678  				return
   679  			}
   680  			// The lhs is representable as an integer but may not be an integer
   681  			// (e.g., 2.0, an untyped float) - this can only happen for untyped
   682  			// non-integer numeric constants. Correct the type so that the shift
   683  			// result is of integer type.
   684  			if !isInteger(x.typ) {
   685  				x.typ = Typ[UntypedInt]
   686  			}
   687  			// x is a constant so xval != nil and it must be of Int kind.
   688  			x.val = constant.Shift(xval, op, uint(s))
   689  			// Typed constants must be representable in
   690  			// their type after each constant operation.
   691  			if isTyped(x.typ) {
   692  				if e != nil {
   693  					x.expr = e // for better error message
   694  				}
   695  				check.representable(x, x.typ.Underlying().(*Basic))
   696  			}
   697  			return
   698  		}
   699  
   700  		// non-constant shift with constant lhs
   701  		if untypedx {
   702  			// spec: "If the left operand of a non-constant shift
   703  			// expression is an untyped constant, the type of the
   704  			// constant is what it would be if the shift expression
   705  			// were replaced by its left operand alone.".
   706  			//
   707  			// Delay operand checking until we know the final type
   708  			// by marking the lhs expression as lhs shift operand.
   709  			//
   710  			// Usually (in correct programs), the lhs expression
   711  			// is in the untyped map. However, it is possible to
   712  			// create incorrect programs where the same expression
   713  			// is evaluated twice (via a declaration cycle) such
   714  			// that the lhs expression type is determined in the
   715  			// first round and thus deleted from the map, and then
   716  			// not found in the second round (double insertion of
   717  			// the same expr node still just leads to one entry for
   718  			// that node, and it can only be deleted once).
   719  			// Be cautious and check for presence of entry.
   720  			// Example: var e, f = int(1<<""[f]) // issue 11347
   721  			if info, found := check.untyped[x.expr]; found {
   722  				info.isLhs = true
   723  				check.untyped[x.expr] = info
   724  			}
   725  			// keep x's type
   726  			x.mode = value
   727  			return
   728  		}
   729  	}
   730  
   731  	// constant rhs must be >= 0
   732  	if y.mode == constant_ && constant.Sign(y.val) < 0 {
   733  		check.invalidOp(y.pos(), "shift count %s must not be negative", y)
   734  	}
   735  
   736  	// non-constant shift - lhs must be an integer
   737  	if !isInteger(x.typ) {
   738  		check.invalidOp(x.pos(), "shifted operand %s must be integer", x)
   739  		x.mode = invalid
   740  		return
   741  	}
   742  
   743  	x.mode = value
   744  }
   745  
   746  var binaryOpPredicates = opPredicates{
   747  	token.ADD: func(typ Type) bool { return isNumeric(typ) || isString(typ) },
   748  	token.SUB: isNumeric,
   749  	token.MUL: isNumeric,
   750  	token.QUO: isNumeric,
   751  	token.REM: isInteger,
   752  
   753  	token.AND:     isInteger,
   754  	token.OR:      isInteger,
   755  	token.XOR:     isInteger,
   756  	token.AND_NOT: isInteger,
   757  
   758  	token.LAND: isBoolean,
   759  	token.LOR:  isBoolean,
   760  }
   761  
   762  // The binary expression e may be nil. It's passed in for better error messages only.
   763  func (check *Checker) binary(x *operand, e *ast.BinaryExpr, lhs, rhs ast.Expr, op token.Token) {
   764  	var y operand
   765  
   766  	check.expr(x, lhs)
   767  	check.expr(&y, rhs)
   768  
   769  	if x.mode == invalid {
   770  		return
   771  	}
   772  	if y.mode == invalid {
   773  		x.mode = invalid
   774  		x.expr = y.expr
   775  		return
   776  	}
   777  
   778  	if isShift(op) {
   779  		check.shift(x, &y, e, op)
   780  		return
   781  	}
   782  
   783  	check.convertUntyped(x, y.typ)
   784  	if x.mode == invalid {
   785  		return
   786  	}
   787  	check.convertUntyped(&y, x.typ)
   788  	if y.mode == invalid {
   789  		x.mode = invalid
   790  		return
   791  	}
   792  
   793  	if isComparison(op) {
   794  		check.comparison(x, &y, op)
   795  		return
   796  	}
   797  
   798  	if !Identical(x.typ, y.typ) {
   799  		// only report an error if we have valid types
   800  		// (otherwise we had an error reported elsewhere already)
   801  		if x.typ != Typ[Invalid] && y.typ != Typ[Invalid] {
   802  			check.invalidOp(x.pos(), "mismatched types %s and %s", x.typ, y.typ)
   803  		}
   804  		x.mode = invalid
   805  		return
   806  	}
   807  
   808  	if !check.op(binaryOpPredicates, x, op) {
   809  		x.mode = invalid
   810  		return
   811  	}
   812  
   813  	if op == token.QUO || op == token.REM {
   814  		// check for zero divisor
   815  		if (x.mode == constant_ || isInteger(x.typ)) && y.mode == constant_ && constant.Sign(y.val) == 0 {
   816  			check.invalidOp(y.pos(), "division by zero")
   817  			x.mode = invalid
   818  			return
   819  		}
   820  
   821  		// check for divisor underflow in complex division (see issue 20227)
   822  		if x.mode == constant_ && y.mode == constant_ && isComplex(x.typ) {
   823  			re, im := constant.Real(y.val), constant.Imag(y.val)
   824  			re2, im2 := constant.BinaryOp(re, token.MUL, re), constant.BinaryOp(im, token.MUL, im)
   825  			if constant.Sign(re2) == 0 && constant.Sign(im2) == 0 {
   826  				check.invalidOp(y.pos(), "division by zero")
   827  				x.mode = invalid
   828  				return
   829  			}
   830  		}
   831  	}
   832  
   833  	if x.mode == constant_ && y.mode == constant_ {
   834  		xval := x.val
   835  		yval := y.val
   836  		typ := x.typ.Underlying().(*Basic)
   837  		// force integer division of integer operands
   838  		if op == token.QUO && isInteger(typ) {
   839  			op = token.QUO_ASSIGN
   840  		}
   841  		x.val = constant.BinaryOp(xval, op, yval)
   842  		// Typed constants must be representable in
   843  		// their type after each constant operation.
   844  		if isTyped(typ) {
   845  			if e != nil {
   846  				x.expr = e // for better error message
   847  			}
   848  			check.representable(x, typ)
   849  		}
   850  		return
   851  	}
   852  
   853  	x.mode = value
   854  	// x.typ is unchanged
   855  }
   856  
   857  // index checks an index expression for validity.
   858  // If max >= 0, it is the upper bound for index.
   859  // If index is valid and the result i >= 0, then i is the constant value of index.
   860  func (check *Checker) index(index ast.Expr, max int64) (i int64, valid bool) {
   861  	var x operand
   862  	check.expr(&x, index)
   863  	if x.mode == invalid {
   864  		return
   865  	}
   866  
   867  	// an untyped constant must be representable as Int
   868  	check.convertUntyped(&x, Typ[Int])
   869  	if x.mode == invalid {
   870  		return
   871  	}
   872  
   873  	// the index must be of integer type
   874  	if !isInteger(x.typ) {
   875  		check.invalidArg(x.pos(), "index %s must be integer", &x)
   876  		return
   877  	}
   878  
   879  	// a constant index i must be in bounds
   880  	if x.mode == constant_ {
   881  		if constant.Sign(x.val) < 0 {
   882  			check.invalidArg(x.pos(), "index %s must not be negative", &x)
   883  			return
   884  		}
   885  		i, valid = constant.Int64Val(constant.ToInt(x.val))
   886  		if !valid || max >= 0 && i >= max {
   887  			check.errorf(x.pos(), "index %s is out of bounds", &x)
   888  			return i, false
   889  		}
   890  		// 0 <= i [ && i < max ]
   891  		return i, true
   892  	}
   893  
   894  	return -1, true
   895  }
   896  
   897  // indexElts checks the elements (elts) of an array or slice composite literal
   898  // against the literal's element type (typ), and the element indices against
   899  // the literal length if known (length >= 0). It returns the length of the
   900  // literal (maximum index value + 1).
   901  //
   902  func (check *Checker) indexedElts(elts []ast.Expr, typ Type, length int64) int64 {
   903  	visited := make(map[int64]bool, len(elts))
   904  	var index, max int64
   905  	for _, e := range elts {
   906  		// determine and check index
   907  		validIndex := false
   908  		eval := e
   909  		if kv, _ := e.(*ast.KeyValueExpr); kv != nil {
   910  			if i, ok := check.index(kv.Key, length); ok {
   911  				if i >= 0 {
   912  					index = i
   913  					validIndex = true
   914  				} else {
   915  					check.errorf(e.Pos(), "index %s must be integer constant", kv.Key)
   916  				}
   917  			}
   918  			eval = kv.Value
   919  		} else if length >= 0 && index >= length {
   920  			check.errorf(e.Pos(), "index %d is out of bounds (>= %d)", index, length)
   921  		} else {
   922  			validIndex = true
   923  		}
   924  
   925  		// if we have a valid index, check for duplicate entries
   926  		if validIndex {
   927  			if visited[index] {
   928  				check.errorf(e.Pos(), "duplicate index %d in array or slice literal", index)
   929  			}
   930  			visited[index] = true
   931  		}
   932  		index++
   933  		if index > max {
   934  			max = index
   935  		}
   936  
   937  		// check element against composite literal element type
   938  		var x operand
   939  		check.exprWithHint(&x, eval, typ)
   940  		check.assignment(&x, typ, "array or slice literal")
   941  	}
   942  	return max
   943  }
   944  
   945  // exprKind describes the kind of an expression; the kind
   946  // determines if an expression is valid in 'statement context'.
   947  type exprKind int
   948  
   949  const (
   950  	conversion exprKind = iota
   951  	expression
   952  	statement
   953  )
   954  
   955  // rawExpr typechecks expression e and initializes x with the expression
   956  // value or type. If an error occurred, x.mode is set to invalid.
   957  // If hint != nil, it is the type of a composite literal element.
   958  //
   959  func (check *Checker) rawExpr(x *operand, e ast.Expr, hint Type) exprKind {
   960  	if trace {
   961  		check.trace(e.Pos(), "%s", e)
   962  		check.indent++
   963  		defer func() {
   964  			check.indent--
   965  			check.trace(e.Pos(), "=> %s", x)
   966  		}()
   967  	}
   968  
   969  	kind := check.exprInternal(x, e, hint)
   970  
   971  	// convert x into a user-friendly set of values
   972  	// TODO(gri) this code can be simplified
   973  	var typ Type
   974  	var val constant.Value
   975  	switch x.mode {
   976  	case invalid:
   977  		typ = Typ[Invalid]
   978  	case novalue:
   979  		typ = (*Tuple)(nil)
   980  	case constant_:
   981  		typ = x.typ
   982  		val = x.val
   983  	default:
   984  		typ = x.typ
   985  	}
   986  	assert(x.expr != nil && typ != nil)
   987  
   988  	if isUntyped(typ) {
   989  		// delay type and value recording until we know the type
   990  		// or until the end of type checking
   991  		check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val)
   992  	} else {
   993  		check.recordTypeAndValue(e, x.mode, typ, val)
   994  	}
   995  
   996  	return kind
   997  }
   998  
   999  // exprInternal contains the core of type checking of expressions.
  1000  // Must only be called by rawExpr.
  1001  //
  1002  func (check *Checker) exprInternal(x *operand, e ast.Expr, hint Type) exprKind {
  1003  	// make sure x has a valid state in case of bailout
  1004  	// (was issue 5770)
  1005  	x.mode = invalid
  1006  	x.typ = Typ[Invalid]
  1007  
  1008  	switch e := e.(type) {
  1009  	case *ast.BadExpr:
  1010  		goto Error // error was reported before
  1011  
  1012  	case *ast.Ident:
  1013  		check.ident(x, e, nil, nil)
  1014  
  1015  	case *ast.Ellipsis:
  1016  		// ellipses are handled explicitly where they are legal
  1017  		// (array composite literals and parameter lists)
  1018  		check.error(e.Pos(), "invalid use of '...'")
  1019  		goto Error
  1020  
  1021  	case *ast.BasicLit:
  1022  		x.setConst(e.Kind, e.Value)
  1023  		if x.mode == invalid {
  1024  			check.invalidAST(e.Pos(), "invalid literal %v", e.Value)
  1025  			goto Error
  1026  		}
  1027  
  1028  	case *ast.FuncLit:
  1029  		if sig, ok := check.typ(e.Type).(*Signature); ok {
  1030  			// Anonymous functions are considered part of the
  1031  			// init expression/func declaration which contains
  1032  			// them: use existing package-level declaration info.
  1033  			check.funcBody(check.decl, "", sig, e.Body)
  1034  			x.mode = value
  1035  			x.typ = sig
  1036  		} else {
  1037  			check.invalidAST(e.Pos(), "invalid function literal %s", e)
  1038  			goto Error
  1039  		}
  1040  
  1041  	case *ast.CompositeLit:
  1042  		var typ, base Type
  1043  
  1044  		switch {
  1045  		case e.Type != nil:
  1046  			// composite literal type present - use it
  1047  			// [...]T array types may only appear with composite literals.
  1048  			// Check for them here so we don't have to handle ... in general.
  1049  			if atyp, _ := e.Type.(*ast.ArrayType); atyp != nil && atyp.Len != nil {
  1050  				if ellip, _ := atyp.Len.(*ast.Ellipsis); ellip != nil && ellip.Elt == nil {
  1051  					// We have an "open" [...]T array type.
  1052  					// Create a new ArrayType with unknown length (-1)
  1053  					// and finish setting it up after analyzing the literal.
  1054  					typ = &Array{len: -1, elem: check.typ(atyp.Elt)}
  1055  					base = typ
  1056  					break
  1057  				}
  1058  			}
  1059  			typ = check.typ(e.Type)
  1060  			base = typ
  1061  
  1062  		case hint != nil:
  1063  			// no composite literal type present - use hint (element type of enclosing type)
  1064  			typ = hint
  1065  			base, _ = deref(typ.Underlying()) // *T implies &T{}
  1066  
  1067  		default:
  1068  			// TODO(gri) provide better error messages depending on context
  1069  			check.error(e.Pos(), "missing type in composite literal")
  1070  			goto Error
  1071  		}
  1072  
  1073  		switch utyp := base.Underlying().(type) {
  1074  		case *Struct:
  1075  			if len(e.Elts) == 0 {
  1076  				break
  1077  			}
  1078  			fields := utyp.fields
  1079  			if _, ok := e.Elts[0].(*ast.KeyValueExpr); ok {
  1080  				// all elements must have keys
  1081  				visited := make([]bool, len(fields))
  1082  				for _, e := range e.Elts {
  1083  					kv, _ := e.(*ast.KeyValueExpr)
  1084  					if kv == nil {
  1085  						check.error(e.Pos(), "mixture of field:value and value elements in struct literal")
  1086  						continue
  1087  					}
  1088  					key, _ := kv.Key.(*ast.Ident)
  1089  					if key == nil {
  1090  						check.errorf(kv.Pos(), "invalid field name %s in struct literal", kv.Key)
  1091  						continue
  1092  					}
  1093  					i := fieldIndex(utyp.fields, check.pkg, key.Name)
  1094  					if i < 0 {
  1095  						check.errorf(kv.Pos(), "unknown field %s in struct literal", key.Name)
  1096  						continue
  1097  					}
  1098  					fld := fields[i]
  1099  					check.recordUse(key, fld)
  1100  					// 0 <= i < len(fields)
  1101  					if visited[i] {
  1102  						check.errorf(kv.Pos(), "duplicate field name %s in struct literal", key.Name)
  1103  						continue
  1104  					}
  1105  					visited[i] = true
  1106  					check.expr(x, kv.Value)
  1107  					etyp := fld.typ
  1108  					check.assignment(x, etyp, "struct literal")
  1109  				}
  1110  			} else {
  1111  				// no element must have a key
  1112  				for i, e := range e.Elts {
  1113  					if kv, _ := e.(*ast.KeyValueExpr); kv != nil {
  1114  						check.error(kv.Pos(), "mixture of field:value and value elements in struct literal")
  1115  						continue
  1116  					}
  1117  					check.expr(x, e)
  1118  					if i >= len(fields) {
  1119  						check.error(x.pos(), "too many values in struct literal")
  1120  						break // cannot continue
  1121  					}
  1122  					// i < len(fields)
  1123  					fld := fields[i]
  1124  					if !fld.Exported() && fld.pkg != check.pkg {
  1125  						check.errorf(x.pos(), "implicit assignment to unexported field %s in %s literal", fld.name, typ)
  1126  						continue
  1127  					}
  1128  					etyp := fld.typ
  1129  					check.assignment(x, etyp, "struct literal")
  1130  				}
  1131  				if len(e.Elts) < len(fields) {
  1132  					check.error(e.Rbrace, "too few values in struct literal")
  1133  					// ok to continue
  1134  				}
  1135  			}
  1136  
  1137  		case *Array:
  1138  			// Prevent crash if the array referred to is not yet set up.
  1139  			// This is a stop-gap solution; a better approach would use the mechanism of
  1140  			// Checker.ident (typexpr.go) using a path of types. But that would require
  1141  			// passing the path everywhere (all expression-checking methods, not just
  1142  			// type expression checking), and we're not set up for that (quite possibly
  1143  			// an indication that cycle detection needs to be rethought). Was issue #18643.
  1144  			if utyp.elem == nil {
  1145  				check.error(e.Pos(), "illegal cycle in type declaration")
  1146  				goto Error
  1147  			}
  1148  			n := check.indexedElts(e.Elts, utyp.elem, utyp.len)
  1149  			// If we have an "open" [...]T array, set the length now that we know it
  1150  			// and record the type for [...] (usually done by check.typExpr which is
  1151  			// not called for [...]).
  1152  			if utyp.len < 0 {
  1153  				utyp.len = n
  1154  				check.recordTypeAndValue(e.Type, typexpr, utyp, nil)
  1155  			}
  1156  
  1157  		case *Slice:
  1158  			// Prevent crash if the slice referred to is not yet set up.
  1159  			// See analogous comment for *Array.
  1160  			if utyp.elem == nil {
  1161  				check.error(e.Pos(), "illegal cycle in type declaration")
  1162  				goto Error
  1163  			}
  1164  			check.indexedElts(e.Elts, utyp.elem, -1)
  1165  
  1166  		case *Map:
  1167  			// Prevent crash if the map referred to is not yet set up.
  1168  			// See analogous comment for *Array.
  1169  			if utyp.key == nil || utyp.elem == nil {
  1170  				check.error(e.Pos(), "illegal cycle in type declaration")
  1171  				goto Error
  1172  			}
  1173  			visited := make(map[interface{}][]Type, len(e.Elts))
  1174  			for _, e := range e.Elts {
  1175  				kv, _ := e.(*ast.KeyValueExpr)
  1176  				if kv == nil {
  1177  					check.error(e.Pos(), "missing key in map literal")
  1178  					continue
  1179  				}
  1180  				check.exprWithHint(x, kv.Key, utyp.key)
  1181  				check.assignment(x, utyp.key, "map literal")
  1182  				if x.mode == invalid {
  1183  					continue
  1184  				}
  1185  				if x.mode == constant_ {
  1186  					duplicate := false
  1187  					// if the key is of interface type, the type is also significant when checking for duplicates
  1188  					if _, ok := utyp.key.Underlying().(*Interface); ok {
  1189  						for _, vtyp := range visited[x.val] {
  1190  							if Identical(vtyp, x.typ) {
  1191  								duplicate = true
  1192  								break
  1193  							}
  1194  						}
  1195  						visited[x.val] = append(visited[x.val], x.typ)
  1196  					} else {
  1197  						_, duplicate = visited[x.val]
  1198  						visited[x.val] = nil
  1199  					}
  1200  					if duplicate {
  1201  						check.errorf(x.pos(), "duplicate key %s in map literal", x.val)
  1202  						continue
  1203  					}
  1204  				}
  1205  				check.exprWithHint(x, kv.Value, utyp.elem)
  1206  				check.assignment(x, utyp.elem, "map literal")
  1207  			}
  1208  
  1209  		default:
  1210  			// when "using" all elements unpack KeyValueExpr
  1211  			// explicitly because check.use doesn't accept them
  1212  			for _, e := range e.Elts {
  1213  				if kv, _ := e.(*ast.KeyValueExpr); kv != nil {
  1214  					// Ideally, we should also "use" kv.Key but we can't know
  1215  					// if it's an externally defined struct key or not. Going
  1216  					// forward anyway can lead to other errors. Give up instead.
  1217  					e = kv.Value
  1218  				}
  1219  				check.use(e)
  1220  			}
  1221  			// if utyp is invalid, an error was reported before
  1222  			if utyp != Typ[Invalid] {
  1223  				check.errorf(e.Pos(), "invalid composite literal type %s", typ)
  1224  				goto Error
  1225  			}
  1226  		}
  1227  
  1228  		x.mode = value
  1229  		x.typ = typ
  1230  
  1231  	case *ast.ParenExpr:
  1232  		kind := check.rawExpr(x, e.X, nil)
  1233  		x.expr = e
  1234  		return kind
  1235  
  1236  	case *ast.SelectorExpr:
  1237  		check.selector(x, e)
  1238  
  1239  	case *ast.IndexExpr:
  1240  		check.expr(x, e.X)
  1241  		if x.mode == invalid {
  1242  			check.use(e.Index)
  1243  			goto Error
  1244  		}
  1245  
  1246  		valid := false
  1247  		length := int64(-1) // valid if >= 0
  1248  		switch typ := x.typ.Underlying().(type) {
  1249  		case *Basic:
  1250  			if isString(typ) {
  1251  				valid = true
  1252  				if x.mode == constant_ {
  1253  					length = int64(len(constant.StringVal(x.val)))
  1254  				}
  1255  				// an indexed string always yields a byte value
  1256  				// (not a constant) even if the string and the
  1257  				// index are constant
  1258  				x.mode = value
  1259  				x.typ = universeByte // use 'byte' name
  1260  			}
  1261  
  1262  		case *Array:
  1263  			valid = true
  1264  			length = typ.len
  1265  			if x.mode != variable {
  1266  				x.mode = value
  1267  			}
  1268  			x.typ = typ.elem
  1269  
  1270  		case *Pointer:
  1271  			if typ, _ := typ.base.Underlying().(*Array); typ != nil {
  1272  				valid = true
  1273  				length = typ.len
  1274  				x.mode = variable
  1275  				x.typ = typ.elem
  1276  			}
  1277  
  1278  		case *Slice:
  1279  			valid = true
  1280  			x.mode = variable
  1281  			x.typ = typ.elem
  1282  
  1283  		case *Map:
  1284  			var key operand
  1285  			check.expr(&key, e.Index)
  1286  			check.assignment(&key, typ.key, "map index")
  1287  			if x.mode == invalid {
  1288  				goto Error
  1289  			}
  1290  			x.mode = mapindex
  1291  			x.typ = typ.elem
  1292  			x.expr = e
  1293  			return expression
  1294  		}
  1295  
  1296  		if !valid {
  1297  			check.invalidOp(x.pos(), "cannot index %s", x)
  1298  			goto Error
  1299  		}
  1300  
  1301  		if e.Index == nil {
  1302  			check.invalidAST(e.Pos(), "missing index for %s", x)
  1303  			goto Error
  1304  		}
  1305  
  1306  		check.index(e.Index, length)
  1307  		// ok to continue
  1308  
  1309  	case *ast.SliceExpr:
  1310  		check.expr(x, e.X)
  1311  		if x.mode == invalid {
  1312  			check.use(e.Low, e.High, e.Max)
  1313  			goto Error
  1314  		}
  1315  
  1316  		valid := false
  1317  		length := int64(-1) // valid if >= 0
  1318  		switch typ := x.typ.Underlying().(type) {
  1319  		case *Basic:
  1320  			if isString(typ) {
  1321  				if e.Slice3 {
  1322  					check.invalidOp(x.pos(), "3-index slice of string")
  1323  					goto Error
  1324  				}
  1325  				valid = true
  1326  				if x.mode == constant_ {
  1327  					length = int64(len(constant.StringVal(x.val)))
  1328  				}
  1329  				// spec: "For untyped string operands the result
  1330  				// is a non-constant value of type string."
  1331  				if typ.kind == UntypedString {
  1332  					x.typ = Typ[String]
  1333  				}
  1334  			}
  1335  
  1336  		case *Array:
  1337  			valid = true
  1338  			length = typ.len
  1339  			if x.mode != variable {
  1340  				check.invalidOp(x.pos(), "cannot slice %s (value not addressable)", x)
  1341  				goto Error
  1342  			}
  1343  			x.typ = &Slice{elem: typ.elem}
  1344  
  1345  		case *Pointer:
  1346  			if typ, _ := typ.base.Underlying().(*Array); typ != nil {
  1347  				valid = true
  1348  				length = typ.len
  1349  				x.typ = &Slice{elem: typ.elem}
  1350  			}
  1351  
  1352  		case *Slice:
  1353  			valid = true
  1354  			// x.typ doesn't change
  1355  		}
  1356  
  1357  		if !valid {
  1358  			check.invalidOp(x.pos(), "cannot slice %s", x)
  1359  			goto Error
  1360  		}
  1361  
  1362  		x.mode = value
  1363  
  1364  		// spec: "Only the first index may be omitted; it defaults to 0."
  1365  		if e.Slice3 && (e.High == nil || e.Max == nil) {
  1366  			check.error(e.Rbrack, "2nd and 3rd index required in 3-index slice")
  1367  			goto Error
  1368  		}
  1369  
  1370  		// check indices
  1371  		var ind [3]int64
  1372  		for i, expr := range []ast.Expr{e.Low, e.High, e.Max} {
  1373  			x := int64(-1)
  1374  			switch {
  1375  			case expr != nil:
  1376  				// The "capacity" is only known statically for strings, arrays,
  1377  				// and pointers to arrays, and it is the same as the length for
  1378  				// those types.
  1379  				max := int64(-1)
  1380  				if length >= 0 {
  1381  					max = length + 1
  1382  				}
  1383  				if t, ok := check.index(expr, max); ok && t >= 0 {
  1384  					x = t
  1385  				}
  1386  			case i == 0:
  1387  				// default is 0 for the first index
  1388  				x = 0
  1389  			case length >= 0:
  1390  				// default is length (== capacity) otherwise
  1391  				x = length
  1392  			}
  1393  			ind[i] = x
  1394  		}
  1395  
  1396  		// constant indices must be in range
  1397  		// (check.index already checks that existing indices >= 0)
  1398  	L:
  1399  		for i, x := range ind[:len(ind)-1] {
  1400  			if x > 0 {
  1401  				for _, y := range ind[i+1:] {
  1402  					if y >= 0 && x > y {
  1403  						check.errorf(e.Rbrack, "invalid slice indices: %d > %d", x, y)
  1404  						break L // only report one error, ok to continue
  1405  					}
  1406  				}
  1407  			}
  1408  		}
  1409  
  1410  	case *ast.TypeAssertExpr:
  1411  		check.expr(x, e.X)
  1412  		if x.mode == invalid {
  1413  			goto Error
  1414  		}
  1415  		xtyp, _ := x.typ.Underlying().(*Interface)
  1416  		if xtyp == nil {
  1417  			check.invalidOp(x.pos(), "%s is not an interface", x)
  1418  			goto Error
  1419  		}
  1420  		// x.(type) expressions are handled explicitly in type switches
  1421  		if e.Type == nil {
  1422  			check.invalidAST(e.Pos(), "use of .(type) outside type switch")
  1423  			goto Error
  1424  		}
  1425  		T := check.typ(e.Type)
  1426  		if T == Typ[Invalid] {
  1427  			goto Error
  1428  		}
  1429  		check.typeAssertion(x.pos(), x, xtyp, T)
  1430  		x.mode = commaok
  1431  		x.typ = T
  1432  
  1433  	case *ast.CallExpr:
  1434  		return check.call(x, e)
  1435  
  1436  	case *ast.StarExpr:
  1437  		check.exprOrType(x, e.X)
  1438  		switch x.mode {
  1439  		case invalid:
  1440  			goto Error
  1441  		case typexpr:
  1442  			x.typ = &Pointer{base: x.typ}
  1443  		default:
  1444  			if typ, ok := x.typ.Underlying().(*Pointer); ok {
  1445  				x.mode = variable
  1446  				x.typ = typ.base
  1447  			} else {
  1448  				check.invalidOp(x.pos(), "cannot indirect %s", x)
  1449  				goto Error
  1450  			}
  1451  		}
  1452  
  1453  	case *ast.UnaryExpr:
  1454  		check.expr(x, e.X)
  1455  		if x.mode == invalid {
  1456  			goto Error
  1457  		}
  1458  		check.unary(x, e, e.Op)
  1459  		if x.mode == invalid {
  1460  			goto Error
  1461  		}
  1462  		if e.Op == token.ARROW {
  1463  			x.expr = e
  1464  			return statement // receive operations may appear in statement context
  1465  		}
  1466  
  1467  	case *ast.BinaryExpr:
  1468  		check.binary(x, e, e.X, e.Y, e.Op)
  1469  		if x.mode == invalid {
  1470  			goto Error
  1471  		}
  1472  
  1473  	case *ast.KeyValueExpr:
  1474  		// key:value expressions are handled in composite literals
  1475  		check.invalidAST(e.Pos(), "no key:value expected")
  1476  		goto Error
  1477  
  1478  	case *ast.ArrayType, *ast.StructType, *ast.FuncType,
  1479  		*ast.InterfaceType, *ast.MapType, *ast.ChanType:
  1480  		x.mode = typexpr
  1481  		x.typ = check.typ(e)
  1482  		// Note: rawExpr (caller of exprInternal) will call check.recordTypeAndValue
  1483  		// even though check.typ has already called it. This is fine as both
  1484  		// times the same expression and type are recorded. It is also not a
  1485  		// performance issue because we only reach here for composite literal
  1486  		// types, which are comparatively rare.
  1487  
  1488  	default:
  1489  		panic(fmt.Sprintf("%s: unknown expression type %T", check.fset.Position(e.Pos()), e))
  1490  	}
  1491  
  1492  	// everything went well
  1493  	x.expr = e
  1494  	return expression
  1495  
  1496  Error:
  1497  	x.mode = invalid
  1498  	x.expr = e
  1499  	return statement // avoid follow-up errors
  1500  }
  1501  
  1502  // typeAssertion checks that x.(T) is legal; xtyp must be the type of x.
  1503  func (check *Checker) typeAssertion(pos token.Pos, x *operand, xtyp *Interface, T Type) {
  1504  	method, wrongType := assertableTo(xtyp, T)
  1505  	if method == nil {
  1506  		return
  1507  	}
  1508  
  1509  	var msg string
  1510  	if wrongType {
  1511  		msg = "wrong type for method"
  1512  	} else {
  1513  		msg = "missing method"
  1514  	}
  1515  	check.errorf(pos, "%s cannot have dynamic type %s (%s %s)", x, T, msg, method.name)
  1516  }
  1517  
  1518  func (check *Checker) singleValue(x *operand) {
  1519  	if x.mode == value {
  1520  		// tuple types are never named - no need for underlying type below
  1521  		if t, ok := x.typ.(*Tuple); ok {
  1522  			assert(t.Len() != 1)
  1523  			check.errorf(x.pos(), "%d-valued %s where single value is expected", t.Len(), x)
  1524  			x.mode = invalid
  1525  		}
  1526  	}
  1527  }
  1528  
  1529  // expr typechecks expression e and initializes x with the expression value.
  1530  // The result must be a single value.
  1531  // If an error occurred, x.mode is set to invalid.
  1532  //
  1533  func (check *Checker) expr(x *operand, e ast.Expr) {
  1534  	check.multiExpr(x, e)
  1535  	check.singleValue(x)
  1536  }
  1537  
  1538  // multiExpr is like expr but the result may be a multi-value.
  1539  func (check *Checker) multiExpr(x *operand, e ast.Expr) {
  1540  	check.rawExpr(x, e, nil)
  1541  	var msg string
  1542  	switch x.mode {
  1543  	default:
  1544  		return
  1545  	case novalue:
  1546  		msg = "%s used as value"
  1547  	case builtin:
  1548  		msg = "%s must be called"
  1549  	case typexpr:
  1550  		msg = "%s is not an expression"
  1551  	}
  1552  	check.errorf(x.pos(), msg, x)
  1553  	x.mode = invalid
  1554  }
  1555  
  1556  // exprWithHint typechecks expression e and initializes x with the expression value;
  1557  // hint is the type of a composite literal element.
  1558  // If an error occurred, x.mode is set to invalid.
  1559  //
  1560  func (check *Checker) exprWithHint(x *operand, e ast.Expr, hint Type) {
  1561  	assert(hint != nil)
  1562  	check.rawExpr(x, e, hint)
  1563  	check.singleValue(x)
  1564  	var msg string
  1565  	switch x.mode {
  1566  	default:
  1567  		return
  1568  	case novalue:
  1569  		msg = "%s used as value"
  1570  	case builtin:
  1571  		msg = "%s must be called"
  1572  	case typexpr:
  1573  		msg = "%s is not an expression"
  1574  	}
  1575  	check.errorf(x.pos(), msg, x)
  1576  	x.mode = invalid
  1577  }
  1578  
  1579  // exprOrType typechecks expression or type e and initializes x with the expression value or type.
  1580  // If an error occurred, x.mode is set to invalid.
  1581  //
  1582  func (check *Checker) exprOrType(x *operand, e ast.Expr) {
  1583  	check.rawExpr(x, e, nil)
  1584  	check.singleValue(x)
  1585  	if x.mode == novalue {
  1586  		check.errorf(x.pos(), "%s used as value or type", x)
  1587  		x.mode = invalid
  1588  	}
  1589  }