...

Source file src/go/types/expr.go

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

View as plain text