github.com/goproxy0/go@v0.0.0-20171111080102-49cc0c489d2c/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  			//
  1034  			// TODO(gri) We delay type-checking of regular (top-level)
  1035  			//           function bodies until later. Why don't we do
  1036  			//           it for closures of top-level expressions?
  1037  			//           (We can't easily do it for local closures
  1038  			//           because the surrounding scopes must reflect
  1039  			//           the exact position where the closure appears
  1040  			//           in the source; e.g., variables declared below
  1041  			//           must not be visible).
  1042  			check.funcBody(check.decl, "", sig, e.Body)
  1043  			x.mode = value
  1044  			x.typ = sig
  1045  		} else {
  1046  			check.invalidAST(e.Pos(), "invalid function literal %s", e)
  1047  			goto Error
  1048  		}
  1049  
  1050  	case *ast.CompositeLit:
  1051  		var typ, base Type
  1052  
  1053  		switch {
  1054  		case e.Type != nil:
  1055  			// composite literal type present - use it
  1056  			// [...]T array types may only appear with composite literals.
  1057  			// Check for them here so we don't have to handle ... in general.
  1058  			if atyp, _ := e.Type.(*ast.ArrayType); atyp != nil && atyp.Len != nil {
  1059  				if ellip, _ := atyp.Len.(*ast.Ellipsis); ellip != nil && ellip.Elt == nil {
  1060  					// We have an "open" [...]T array type.
  1061  					// Create a new ArrayType with unknown length (-1)
  1062  					// and finish setting it up after analyzing the literal.
  1063  					typ = &Array{len: -1, elem: check.typ(atyp.Elt)}
  1064  					base = typ
  1065  					break
  1066  				}
  1067  			}
  1068  			typ = check.typ(e.Type)
  1069  			base = typ
  1070  
  1071  		case hint != nil:
  1072  			// no composite literal type present - use hint (element type of enclosing type)
  1073  			typ = hint
  1074  			base, _ = deref(typ.Underlying()) // *T implies &T{}
  1075  
  1076  		default:
  1077  			// TODO(gri) provide better error messages depending on context
  1078  			check.error(e.Pos(), "missing type in composite literal")
  1079  			goto Error
  1080  		}
  1081  
  1082  		switch utyp := base.Underlying().(type) {
  1083  		case *Struct:
  1084  			if len(e.Elts) == 0 {
  1085  				break
  1086  			}
  1087  			fields := utyp.fields
  1088  			if _, ok := e.Elts[0].(*ast.KeyValueExpr); ok {
  1089  				// all elements must have keys
  1090  				visited := make([]bool, len(fields))
  1091  				for _, e := range e.Elts {
  1092  					kv, _ := e.(*ast.KeyValueExpr)
  1093  					if kv == nil {
  1094  						check.error(e.Pos(), "mixture of field:value and value elements in struct literal")
  1095  						continue
  1096  					}
  1097  					key, _ := kv.Key.(*ast.Ident)
  1098  					if key == nil {
  1099  						check.errorf(kv.Pos(), "invalid field name %s in struct literal", kv.Key)
  1100  						continue
  1101  					}
  1102  					i := fieldIndex(utyp.fields, check.pkg, key.Name)
  1103  					if i < 0 {
  1104  						check.errorf(kv.Pos(), "unknown field %s in struct literal", key.Name)
  1105  						continue
  1106  					}
  1107  					fld := fields[i]
  1108  					check.recordUse(key, fld)
  1109  					// 0 <= i < len(fields)
  1110  					if visited[i] {
  1111  						check.errorf(kv.Pos(), "duplicate field name %s in struct literal", key.Name)
  1112  						continue
  1113  					}
  1114  					visited[i] = true
  1115  					check.expr(x, kv.Value)
  1116  					etyp := fld.typ
  1117  					check.assignment(x, etyp, "struct literal")
  1118  				}
  1119  			} else {
  1120  				// no element must have a key
  1121  				for i, e := range e.Elts {
  1122  					if kv, _ := e.(*ast.KeyValueExpr); kv != nil {
  1123  						check.error(kv.Pos(), "mixture of field:value and value elements in struct literal")
  1124  						continue
  1125  					}
  1126  					check.expr(x, e)
  1127  					if i >= len(fields) {
  1128  						check.error(x.pos(), "too many values in struct literal")
  1129  						break // cannot continue
  1130  					}
  1131  					// i < len(fields)
  1132  					fld := fields[i]
  1133  					if !fld.Exported() && fld.pkg != check.pkg {
  1134  						check.errorf(x.pos(), "implicit assignment to unexported field %s in %s literal", fld.name, typ)
  1135  						continue
  1136  					}
  1137  					etyp := fld.typ
  1138  					check.assignment(x, etyp, "struct literal")
  1139  				}
  1140  				if len(e.Elts) < len(fields) {
  1141  					check.error(e.Rbrace, "too few values in struct literal")
  1142  					// ok to continue
  1143  				}
  1144  			}
  1145  
  1146  		case *Array:
  1147  			// Prevent crash if the array referred to is not yet set up.
  1148  			// This is a stop-gap solution; a better approach would use the mechanism of
  1149  			// Checker.ident (typexpr.go) using a path of types. But that would require
  1150  			// passing the path everywhere (all expression-checking methods, not just
  1151  			// type expression checking), and we're not set up for that (quite possibly
  1152  			// an indication that cycle detection needs to be rethought). Was issue #18643.
  1153  			if utyp.elem == nil {
  1154  				check.error(e.Pos(), "illegal cycle in type declaration")
  1155  				goto Error
  1156  			}
  1157  			n := check.indexedElts(e.Elts, utyp.elem, utyp.len)
  1158  			// If we have an "open" [...]T array, set the length now that we know it
  1159  			// and record the type for [...] (usually done by check.typExpr which is
  1160  			// not called for [...]).
  1161  			if utyp.len < 0 {
  1162  				utyp.len = n
  1163  				check.recordTypeAndValue(e.Type, typexpr, utyp, nil)
  1164  			}
  1165  
  1166  		case *Slice:
  1167  			// Prevent crash if the slice referred to is not yet set up.
  1168  			// See analogous comment for *Array.
  1169  			if utyp.elem == nil {
  1170  				check.error(e.Pos(), "illegal cycle in type declaration")
  1171  				goto Error
  1172  			}
  1173  			check.indexedElts(e.Elts, utyp.elem, -1)
  1174  
  1175  		case *Map:
  1176  			// Prevent crash if the map referred to is not yet set up.
  1177  			// See analogous comment for *Array.
  1178  			if utyp.key == nil || utyp.elem == nil {
  1179  				check.error(e.Pos(), "illegal cycle in type declaration")
  1180  				goto Error
  1181  			}
  1182  			visited := make(map[interface{}][]Type, len(e.Elts))
  1183  			for _, e := range e.Elts {
  1184  				kv, _ := e.(*ast.KeyValueExpr)
  1185  				if kv == nil {
  1186  					check.error(e.Pos(), "missing key in map literal")
  1187  					continue
  1188  				}
  1189  				check.exprWithHint(x, kv.Key, utyp.key)
  1190  				check.assignment(x, utyp.key, "map literal")
  1191  				if x.mode == invalid {
  1192  					continue
  1193  				}
  1194  				if x.mode == constant_ {
  1195  					duplicate := false
  1196  					// if the key is of interface type, the type is also significant when checking for duplicates
  1197  					if _, ok := utyp.key.Underlying().(*Interface); ok {
  1198  						for _, vtyp := range visited[x.val] {
  1199  							if Identical(vtyp, x.typ) {
  1200  								duplicate = true
  1201  								break
  1202  							}
  1203  						}
  1204  						visited[x.val] = append(visited[x.val], x.typ)
  1205  					} else {
  1206  						_, duplicate = visited[x.val]
  1207  						visited[x.val] = nil
  1208  					}
  1209  					if duplicate {
  1210  						check.errorf(x.pos(), "duplicate key %s in map literal", x.val)
  1211  						continue
  1212  					}
  1213  				}
  1214  				check.exprWithHint(x, kv.Value, utyp.elem)
  1215  				check.assignment(x, utyp.elem, "map literal")
  1216  			}
  1217  
  1218  		default:
  1219  			// when "using" all elements unpack KeyValueExpr
  1220  			// explicitly because check.use doesn't accept them
  1221  			for _, e := range e.Elts {
  1222  				if kv, _ := e.(*ast.KeyValueExpr); kv != nil {
  1223  					// Ideally, we should also "use" kv.Key but we can't know
  1224  					// if it's an externally defined struct key or not. Going
  1225  					// forward anyway can lead to other errors. Give up instead.
  1226  					e = kv.Value
  1227  				}
  1228  				check.use(e)
  1229  			}
  1230  			// if utyp is invalid, an error was reported before
  1231  			if utyp != Typ[Invalid] {
  1232  				check.errorf(e.Pos(), "invalid composite literal type %s", typ)
  1233  				goto Error
  1234  			}
  1235  		}
  1236  
  1237  		x.mode = value
  1238  		x.typ = typ
  1239  
  1240  	case *ast.ParenExpr:
  1241  		kind := check.rawExpr(x, e.X, nil)
  1242  		x.expr = e
  1243  		return kind
  1244  
  1245  	case *ast.SelectorExpr:
  1246  		check.selector(x, e)
  1247  
  1248  	case *ast.IndexExpr:
  1249  		check.expr(x, e.X)
  1250  		if x.mode == invalid {
  1251  			check.use(e.Index)
  1252  			goto Error
  1253  		}
  1254  
  1255  		valid := false
  1256  		length := int64(-1) // valid if >= 0
  1257  		switch typ := x.typ.Underlying().(type) {
  1258  		case *Basic:
  1259  			if isString(typ) {
  1260  				valid = true
  1261  				if x.mode == constant_ {
  1262  					length = int64(len(constant.StringVal(x.val)))
  1263  				}
  1264  				// an indexed string always yields a byte value
  1265  				// (not a constant) even if the string and the
  1266  				// index are constant
  1267  				x.mode = value
  1268  				x.typ = universeByte // use 'byte' name
  1269  			}
  1270  
  1271  		case *Array:
  1272  			valid = true
  1273  			length = typ.len
  1274  			if x.mode != variable {
  1275  				x.mode = value
  1276  			}
  1277  			x.typ = typ.elem
  1278  
  1279  		case *Pointer:
  1280  			if typ, _ := typ.base.Underlying().(*Array); typ != nil {
  1281  				valid = true
  1282  				length = typ.len
  1283  				x.mode = variable
  1284  				x.typ = typ.elem
  1285  			}
  1286  
  1287  		case *Slice:
  1288  			valid = true
  1289  			x.mode = variable
  1290  			x.typ = typ.elem
  1291  
  1292  		case *Map:
  1293  			var key operand
  1294  			check.expr(&key, e.Index)
  1295  			check.assignment(&key, typ.key, "map index")
  1296  			if x.mode == invalid {
  1297  				goto Error
  1298  			}
  1299  			x.mode = mapindex
  1300  			x.typ = typ.elem
  1301  			x.expr = e
  1302  			return expression
  1303  		}
  1304  
  1305  		if !valid {
  1306  			check.invalidOp(x.pos(), "cannot index %s", x)
  1307  			goto Error
  1308  		}
  1309  
  1310  		if e.Index == nil {
  1311  			check.invalidAST(e.Pos(), "missing index for %s", x)
  1312  			goto Error
  1313  		}
  1314  
  1315  		check.index(e.Index, length)
  1316  		// ok to continue
  1317  
  1318  	case *ast.SliceExpr:
  1319  		check.expr(x, e.X)
  1320  		if x.mode == invalid {
  1321  			check.use(e.Low, e.High, e.Max)
  1322  			goto Error
  1323  		}
  1324  
  1325  		valid := false
  1326  		length := int64(-1) // valid if >= 0
  1327  		switch typ := x.typ.Underlying().(type) {
  1328  		case *Basic:
  1329  			if isString(typ) {
  1330  				if e.Slice3 {
  1331  					check.invalidOp(x.pos(), "3-index slice of string")
  1332  					goto Error
  1333  				}
  1334  				valid = true
  1335  				if x.mode == constant_ {
  1336  					length = int64(len(constant.StringVal(x.val)))
  1337  				}
  1338  				// spec: "For untyped string operands the result
  1339  				// is a non-constant value of type string."
  1340  				if typ.kind == UntypedString {
  1341  					x.typ = Typ[String]
  1342  				}
  1343  			}
  1344  
  1345  		case *Array:
  1346  			valid = true
  1347  			length = typ.len
  1348  			if x.mode != variable {
  1349  				check.invalidOp(x.pos(), "cannot slice %s (value not addressable)", x)
  1350  				goto Error
  1351  			}
  1352  			x.typ = &Slice{elem: typ.elem}
  1353  
  1354  		case *Pointer:
  1355  			if typ, _ := typ.base.Underlying().(*Array); typ != nil {
  1356  				valid = true
  1357  				length = typ.len
  1358  				x.typ = &Slice{elem: typ.elem}
  1359  			}
  1360  
  1361  		case *Slice:
  1362  			valid = true
  1363  			// x.typ doesn't change
  1364  		}
  1365  
  1366  		if !valid {
  1367  			check.invalidOp(x.pos(), "cannot slice %s", x)
  1368  			goto Error
  1369  		}
  1370  
  1371  		x.mode = value
  1372  
  1373  		// spec: "Only the first index may be omitted; it defaults to 0."
  1374  		if e.Slice3 && (e.High == nil || e.Max == nil) {
  1375  			check.error(e.Rbrack, "2nd and 3rd index required in 3-index slice")
  1376  			goto Error
  1377  		}
  1378  
  1379  		// check indices
  1380  		var ind [3]int64
  1381  		for i, expr := range []ast.Expr{e.Low, e.High, e.Max} {
  1382  			x := int64(-1)
  1383  			switch {
  1384  			case expr != nil:
  1385  				// The "capacity" is only known statically for strings, arrays,
  1386  				// and pointers to arrays, and it is the same as the length for
  1387  				// those types.
  1388  				max := int64(-1)
  1389  				if length >= 0 {
  1390  					max = length + 1
  1391  				}
  1392  				if t, ok := check.index(expr, max); ok && t >= 0 {
  1393  					x = t
  1394  				}
  1395  			case i == 0:
  1396  				// default is 0 for the first index
  1397  				x = 0
  1398  			case length >= 0:
  1399  				// default is length (== capacity) otherwise
  1400  				x = length
  1401  			}
  1402  			ind[i] = x
  1403  		}
  1404  
  1405  		// constant indices must be in range
  1406  		// (check.index already checks that existing indices >= 0)
  1407  	L:
  1408  		for i, x := range ind[:len(ind)-1] {
  1409  			if x > 0 {
  1410  				for _, y := range ind[i+1:] {
  1411  					if y >= 0 && x > y {
  1412  						check.errorf(e.Rbrack, "invalid slice indices: %d > %d", x, y)
  1413  						break L // only report one error, ok to continue
  1414  					}
  1415  				}
  1416  			}
  1417  		}
  1418  
  1419  	case *ast.TypeAssertExpr:
  1420  		check.expr(x, e.X)
  1421  		if x.mode == invalid {
  1422  			goto Error
  1423  		}
  1424  		xtyp, _ := x.typ.Underlying().(*Interface)
  1425  		if xtyp == nil {
  1426  			check.invalidOp(x.pos(), "%s is not an interface", x)
  1427  			goto Error
  1428  		}
  1429  		// x.(type) expressions are handled explicitly in type switches
  1430  		if e.Type == nil {
  1431  			check.invalidAST(e.Pos(), "use of .(type) outside type switch")
  1432  			goto Error
  1433  		}
  1434  		T := check.typ(e.Type)
  1435  		if T == Typ[Invalid] {
  1436  			goto Error
  1437  		}
  1438  		check.typeAssertion(x.pos(), x, xtyp, T)
  1439  		x.mode = commaok
  1440  		x.typ = T
  1441  
  1442  	case *ast.CallExpr:
  1443  		return check.call(x, e)
  1444  
  1445  	case *ast.StarExpr:
  1446  		check.exprOrType(x, e.X)
  1447  		switch x.mode {
  1448  		case invalid:
  1449  			goto Error
  1450  		case typexpr:
  1451  			x.typ = &Pointer{base: x.typ}
  1452  		default:
  1453  			if typ, ok := x.typ.Underlying().(*Pointer); ok {
  1454  				x.mode = variable
  1455  				x.typ = typ.base
  1456  			} else {
  1457  				check.invalidOp(x.pos(), "cannot indirect %s", x)
  1458  				goto Error
  1459  			}
  1460  		}
  1461  
  1462  	case *ast.UnaryExpr:
  1463  		check.expr(x, e.X)
  1464  		if x.mode == invalid {
  1465  			goto Error
  1466  		}
  1467  		check.unary(x, e, e.Op)
  1468  		if x.mode == invalid {
  1469  			goto Error
  1470  		}
  1471  		if e.Op == token.ARROW {
  1472  			x.expr = e
  1473  			return statement // receive operations may appear in statement context
  1474  		}
  1475  
  1476  	case *ast.BinaryExpr:
  1477  		check.binary(x, e, e.X, e.Y, e.Op)
  1478  		if x.mode == invalid {
  1479  			goto Error
  1480  		}
  1481  
  1482  	case *ast.KeyValueExpr:
  1483  		// key:value expressions are handled in composite literals
  1484  		check.invalidAST(e.Pos(), "no key:value expected")
  1485  		goto Error
  1486  
  1487  	case *ast.ArrayType, *ast.StructType, *ast.FuncType,
  1488  		*ast.InterfaceType, *ast.MapType, *ast.ChanType:
  1489  		x.mode = typexpr
  1490  		x.typ = check.typ(e)
  1491  		// Note: rawExpr (caller of exprInternal) will call check.recordTypeAndValue
  1492  		// even though check.typ has already called it. This is fine as both
  1493  		// times the same expression and type are recorded. It is also not a
  1494  		// performance issue because we only reach here for composite literal
  1495  		// types, which are comparatively rare.
  1496  
  1497  	default:
  1498  		panic(fmt.Sprintf("%s: unknown expression type %T", check.fset.Position(e.Pos()), e))
  1499  	}
  1500  
  1501  	// everything went well
  1502  	x.expr = e
  1503  	return expression
  1504  
  1505  Error:
  1506  	x.mode = invalid
  1507  	x.expr = e
  1508  	return statement // avoid follow-up errors
  1509  }
  1510  
  1511  // typeAssertion checks that x.(T) is legal; xtyp must be the type of x.
  1512  func (check *Checker) typeAssertion(pos token.Pos, x *operand, xtyp *Interface, T Type) {
  1513  	method, wrongType := assertableTo(xtyp, T)
  1514  	if method == nil {
  1515  		return
  1516  	}
  1517  
  1518  	var msg string
  1519  	if wrongType {
  1520  		msg = "wrong type for method"
  1521  	} else {
  1522  		msg = "missing method"
  1523  	}
  1524  	check.errorf(pos, "%s cannot have dynamic type %s (%s %s)", x, T, msg, method.name)
  1525  }
  1526  
  1527  func (check *Checker) singleValue(x *operand) {
  1528  	if x.mode == value {
  1529  		// tuple types are never named - no need for underlying type below
  1530  		if t, ok := x.typ.(*Tuple); ok {
  1531  			assert(t.Len() != 1)
  1532  			check.errorf(x.pos(), "%d-valued %s where single value is expected", t.Len(), x)
  1533  			x.mode = invalid
  1534  		}
  1535  	}
  1536  }
  1537  
  1538  // expr typechecks expression e and initializes x with the expression value.
  1539  // The result must be a single value.
  1540  // If an error occurred, x.mode is set to invalid.
  1541  //
  1542  func (check *Checker) expr(x *operand, e ast.Expr) {
  1543  	check.multiExpr(x, e)
  1544  	check.singleValue(x)
  1545  }
  1546  
  1547  // multiExpr is like expr but the result may be a multi-value.
  1548  func (check *Checker) multiExpr(x *operand, e ast.Expr) {
  1549  	check.rawExpr(x, e, nil)
  1550  	var msg string
  1551  	switch x.mode {
  1552  	default:
  1553  		return
  1554  	case novalue:
  1555  		msg = "%s used as value"
  1556  	case builtin:
  1557  		msg = "%s must be called"
  1558  	case typexpr:
  1559  		msg = "%s is not an expression"
  1560  	}
  1561  	check.errorf(x.pos(), msg, x)
  1562  	x.mode = invalid
  1563  }
  1564  
  1565  // exprWithHint typechecks expression e and initializes x with the expression value;
  1566  // hint is the type of a composite literal element.
  1567  // If an error occurred, x.mode is set to invalid.
  1568  //
  1569  func (check *Checker) exprWithHint(x *operand, e ast.Expr, hint Type) {
  1570  	assert(hint != nil)
  1571  	check.rawExpr(x, e, hint)
  1572  	check.singleValue(x)
  1573  	var msg string
  1574  	switch x.mode {
  1575  	default:
  1576  		return
  1577  	case novalue:
  1578  		msg = "%s used as value"
  1579  	case builtin:
  1580  		msg = "%s must be called"
  1581  	case typexpr:
  1582  		msg = "%s is not an expression"
  1583  	}
  1584  	check.errorf(x.pos(), msg, x)
  1585  	x.mode = invalid
  1586  }
  1587  
  1588  // exprOrType typechecks expression or type e and initializes x with the expression value or type.
  1589  // If an error occurred, x.mode is set to invalid.
  1590  //
  1591  func (check *Checker) exprOrType(x *operand, e ast.Expr) {
  1592  	check.rawExpr(x, e, nil)
  1593  	check.singleValue(x)
  1594  	if x.mode == novalue {
  1595  		check.errorf(x.pos(), "%s used as value or type", x)
  1596  		x.mode = invalid
  1597  	}
  1598  }