// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// This file implements typechecking of expressions.

package types

import (
	
	
	
	
	
)

/*
Basic algorithm:

Expressions are checked recursively, top down. Expression checker functions
are generally of the form:

  func f(x *operand, e *ast.Expr, ...)

where e is the expression to be checked, and x is the result of the check.
The check performed by f may fail in which case x.mode == invalid, and
related error messages will have been issued by f.

If a hint argument is present, it is the composite literal element type
of an outer composite literal; it is used to type-check composite literal
elements that have no explicit type specification in the source
(e.g.: []T{{...}, {...}}, the hint is the type T in this case).

All expressions are checked via rawExpr, which dispatches according
to expression kind. Upon returning, rawExpr is recording the types and
constant values for all expressions that have an untyped type (those types
may change on the way up in the expression tree). Usually these are constants,
but the results of comparisons or non-constant shifts of untyped constants
may also be untyped, but not constant.

Untyped expressions may eventually become fully typed (i.e., not untyped),
typically when the value is assigned to a variable, or is used otherwise.
The updateExprType method is used to record this final type and update
the recorded types: the type-checked expression tree is again traversed down,
and the new type is propagated as needed. Untyped constant expression values
that become fully typed must now be representable by the full type (constant
sub-expression trees are left alone except for their roots). This mechanism
ensures that a client sees the actual (run-time) type an untyped value would
have. It also permits type-checking of lhs shift operands "as if the shift
were not present": when updateExprType visits an untyped lhs shift operand
and assigns it it's final type, that type must be an integer type, and a
constant lhs must be representable as an integer.

When an expression gets its final type, either on the way out from rawExpr,
on the way down in updateExprType, or at the end of the type checker run,
the type (and constant value, if any) is recorded via Info.Types, if present.
*/

type opPredicates map[token.Token]func(Type) bool

var unaryOpPredicates = opPredicates{
	token.ADD: isNumeric,
	token.SUB: isNumeric,
	token.XOR: isInteger,
	token.NOT: isBoolean,
}

func ( *Checker) ( opPredicates,  *operand,  token.Token) bool {
	if  := [];  != nil {
		if !(.typ) {
			.invalidOp(, _UndefinedOp, "operator %s not defined for %s", , )
			return false
		}
	} else {
		.invalidAST(, "unknown operator %s", )
		return false
	}
	return true
}

// The unary expression e may be nil. It's passed in for better error messages only.
func ( *Checker) ( *operand,  *ast.UnaryExpr,  token.Token) {
	switch  {
	case token.AND:
		// spec: "As an exception to the addressability
		// requirement x may also be a composite literal."
		if ,  := unparen(.expr).(*ast.CompositeLit); ! && .mode != variable {
			.invalidOp(, _UnaddressableOperand, "cannot take address of %s", )
			.mode = invalid
			return
		}
		.mode = value
		.typ = &Pointer{base: .typ}
		return

	case token.ARROW:
		,  := .typ.Underlying().(*Chan)
		if ! {
			.invalidOp(, _InvalidReceive, "cannot receive from non-channel %s", )
			.mode = invalid
			return
		}
		if .dir == SendOnly {
			.invalidOp(, _InvalidReceive, "cannot receive from send-only channel %s", )
			.mode = invalid
			return
		}
		.mode = commaok
		.typ = .elem
		.hasCallOrRecv = true
		return
	}

	if !.op(unaryOpPredicates, , ) {
		.mode = invalid
		return
	}

	if .mode == constant_ {
		 := .typ.Underlying().(*Basic)
		var  uint
		if isUnsigned() {
			 = uint(.conf.sizeof() * 8)
		}
		.val = constant.UnaryOp(, .val, )
		// Typed constants must be representable in
		// their type after each constant operation.
		if isTyped() {
			if  != nil {
				.expr =  // for better error message
			}
			.representable(, )
		}
		return
	}

	.mode = value
	// x.typ remains unchanged
}

func isShift( token.Token) bool {
	return  == token.SHL ||  == token.SHR
}

func isComparison( token.Token) bool {
	// Note: tokens are not ordered well to make this much easier
	switch  {
	case token.EQL, token.NEQ, token.LSS, token.LEQ, token.GTR, token.GEQ:
		return true
	}
	return false
}

func fitsFloat32( constant.Value) bool {
	,  := constant.Float32Val()
	 := float64()
	return !math.IsInf(, 0)
}

func roundFloat32( constant.Value) constant.Value {
	,  := constant.Float32Val()
	 := float64()
	if !math.IsInf(, 0) {
		return constant.MakeFloat64()
	}
	return nil
}

func fitsFloat64( constant.Value) bool {
	,  := constant.Float64Val()
	return !math.IsInf(, 0)
}

func roundFloat64( constant.Value) constant.Value {
	,  := constant.Float64Val()
	if !math.IsInf(, 0) {
		return constant.MakeFloat64()
	}
	return nil
}

// representableConst reports whether x can be represented as
// value of the given basic type and for the configuration
// provided (only needed for int/uint sizes).
//
// If rounded != nil, *rounded is set to the rounded value of x for
// representable floating-point and complex values, and to an Int
// value for integer values; it is left alone otherwise.
// It is ok to provide the addressof the first argument for rounded.
//
// The check parameter may be nil if representableConst is invoked
// (indirectly) through an exported API call (AssignableTo, ConvertibleTo)
// because we don't need the Checker's config for those calls.
func representableConst( constant.Value,  *Checker,  *Basic,  *constant.Value) bool {
	if .Kind() == constant.Unknown {
		return true // avoid follow-up errors
	}

	var  *Config
	if  != nil {
		 = .conf
	}

	switch {
	case isInteger():
		 := constant.ToInt()
		if .Kind() != constant.Int {
			return false
		}
		if  != nil {
			* = 
		}
		if ,  := constant.Int64Val();  {
			switch .kind {
			case Int:
				var  = uint(.sizeof()) * 8
				return int64(-1)<<(-1) <=  &&  <= int64(1)<<(-1)-1
			case Int8:
				const  = 8
				return -1<<(-1) <=  &&  <= 1<<(-1)-1
			case Int16:
				const  = 16
				return -1<<(-1) <=  &&  <= 1<<(-1)-1
			case Int32:
				const  = 32
				return -1<<(-1) <=  &&  <= 1<<(-1)-1
			case Int64, UntypedInt:
				return true
			case Uint, Uintptr:
				if  := uint(.sizeof()) * 8;  < 64 {
					return 0 <=  &&  <= int64(1)<<-1
				}
				return 0 <= 
			case Uint8:
				const  = 8
				return 0 <=  &&  <= 1<<-1
			case Uint16:
				const  = 16
				return 0 <=  &&  <= 1<<-1
			case Uint32:
				const  = 32
				return 0 <=  &&  <= 1<<-1
			case Uint64:
				return 0 <= 
			default:
				unreachable()
			}
		}
		// x does not fit into int64
		switch  := constant.BitLen(); .kind {
		case Uint, Uintptr:
			var  = uint(.sizeof()) * 8
			return constant.Sign() >= 0 &&  <= int()
		case Uint64:
			return constant.Sign() >= 0 &&  <= 64
		case UntypedInt:
			return true
		}

	case isFloat():
		 := constant.ToFloat()
		if .Kind() != constant.Float {
			return false
		}
		switch .kind {
		case Float32:
			if  == nil {
				return fitsFloat32()
			}
			 := roundFloat32()
			if  != nil {
				* = 
				return true
			}
		case Float64:
			if  == nil {
				return fitsFloat64()
			}
			 := roundFloat64()
			if  != nil {
				* = 
				return true
			}
		case UntypedFloat:
			return true
		default:
			unreachable()
		}

	case isComplex():
		 := constant.ToComplex()
		if .Kind() != constant.Complex {
			return false
		}
		switch .kind {
		case Complex64:
			if  == nil {
				return fitsFloat32(constant.Real()) && fitsFloat32(constant.Imag())
			}
			 := roundFloat32(constant.Real())
			 := roundFloat32(constant.Imag())
			if  != nil &&  != nil {
				* = constant.BinaryOp(, token.ADD, constant.MakeImag())
				return true
			}
		case Complex128:
			if  == nil {
				return fitsFloat64(constant.Real()) && fitsFloat64(constant.Imag())
			}
			 := roundFloat64(constant.Real())
			 := roundFloat64(constant.Imag())
			if  != nil &&  != nil {
				* = constant.BinaryOp(, token.ADD, constant.MakeImag())
				return true
			}
		case UntypedComplex:
			return true
		default:
			unreachable()
		}

	case isString():
		return .Kind() == constant.String

	case isBoolean():
		return .Kind() == constant.Bool
	}

	return false
}

// representable checks that a constant operand is representable in the given
// basic type.
func ( *Checker) ( *operand,  *Basic) {
	if  := .isRepresentable(, );  != nil {
		.mode = invalid
		.err()
	}
}

func ( *Checker) ( *operand,  *Basic) error {
	assert(.mode == constant_)
	if !representableConst(.val, , , &.val) {
		var  string
		var  errorCode
		if isNumeric(.typ) && isNumeric() {
			// numeric conversion : error msg
			//
			// integer -> integer : overflows
			// integer -> float   : overflows (actually not possible)
			// float   -> integer : truncated
			// float   -> float   : overflows
			//
			if !isInteger(.typ) && isInteger() {
				 = "%s truncated to %s"
				 = _TruncatedFloat
			} else {
				 = "%s overflows %s"
				 = _NumericOverflow
			}
		} else {
			 = "cannot convert %s to %s"
			 = _InvalidConstVal
		}
		return .newErrorf(, , false, , , )
	}
	return nil
}

// updateExprType updates the type of x to typ and invokes itself
// recursively for the operands of x, depending on expression kind.
// If typ is still an untyped and not the final type, updateExprType
// only updates the recorded untyped type for x and possibly its
// operands. Otherwise (i.e., typ is not an untyped type anymore,
// or it is the final type for x), the type and value are recorded.
// Also, if x is a constant, it must be representable as a value of typ,
// and if x is the (formerly untyped) lhs operand of a non-constant
// shift, it must be an integer value.
//
func ( *Checker) ( ast.Expr,  Type,  bool) {
	,  := .untyped[]
	if ! {
		return // nothing to do
	}

	// update operands of x if necessary
	switch x := .(type) {
	case *ast.BadExpr,
		*ast.FuncLit,
		*ast.CompositeLit,
		*ast.IndexExpr,
		*ast.SliceExpr,
		*ast.TypeAssertExpr,
		*ast.StarExpr,
		*ast.KeyValueExpr,
		*ast.ArrayType,
		*ast.StructType,
		*ast.FuncType,
		*ast.InterfaceType,
		*ast.MapType,
		*ast.ChanType:
		// These expression are never untyped - nothing to do.
		// The respective sub-expressions got their final types
		// upon assignment or use.
		if debug {
			.dump("%v: found old type(%s): %s (new: %s)", .Pos(), , .typ, )
			unreachable()
		}
		return

	case *ast.CallExpr:
		// Resulting in an untyped constant (e.g., built-in complex).
		// The respective calls take care of calling updateExprType
		// for the arguments if necessary.

	case *ast.Ident, *ast.BasicLit, *ast.SelectorExpr:
		// An identifier denoting a constant, a constant literal,
		// or a qualified identifier (imported untyped constant).
		// No operands to take care of.

	case *ast.ParenExpr:
		.(.X, , )

	case *ast.UnaryExpr:
		// If x is a constant, the operands were constants.
		// The operands don't need to be updated since they
		// never get "materialized" into a typed value. If
		// left in the untyped map, they will be processed
		// at the end of the type check.
		if .val != nil {
			break
		}
		.(.X, , )

	case *ast.BinaryExpr:
		if .val != nil {
			break // see comment for unary expressions
		}
		if isComparison(.Op) {
			// The result type is independent of operand types
			// and the operand types must have final types.
		} else if isShift(.Op) {
			// The result type depends only on lhs operand.
			// The rhs type was updated when checking the shift.
			.(.X, , )
		} else {
			// The operand types match the result type.
			.(.X, , )
			.(.Y, , )
		}

	default:
		unreachable()
	}

	// If the new type is not final and still untyped, just
	// update the recorded type.
	if ! && isUntyped() {
		.typ = .Underlying().(*Basic)
		.untyped[] = 
		return
	}

	// Otherwise we have the final (typed or untyped type).
	// Remove it from the map of yet untyped expressions.
	delete(.untyped, )

	if .isLhs {
		// If x is the lhs of a shift, its final type must be integer.
		// We already know from the shift check that it is representable
		// as an integer if it is a constant.
		if !isInteger() {
			.invalidOp(, _InvalidShiftOperand, "shifted operand %s (type %s) must be integer", , )
			return
		}
		// Even if we have an integer, if the value is a constant we
		// still must check that it is representable as the specific
		// int type requested (was issue #22969). Fall through here.
	}
	if .val != nil {
		// If x is a constant, it must be representable as a value of typ.
		 := operand{.mode, , .typ, .val, 0}
		.convertUntyped(&, )
		if .mode == invalid {
			return
		}
	}

	// Everything's fine, record final type and value for x.
	.recordTypeAndValue(, .mode, , .val)
}

// updateExprVal updates the value of x to val.
func ( *Checker) ( ast.Expr,  constant.Value) {
	if ,  := .untyped[];  {
		.val = 
		.untyped[] = 
	}
}

// convertUntyped attempts to set the type of an untyped value to the target type.
func ( *Checker) ( *operand,  Type) {
	if  := .canConvertUntyped(, );  != nil {
		.mode = invalid
		.err()
	}
}

func ( *Checker) ( *operand,  Type) error {
	if .mode == invalid || isTyped(.typ) ||  == Typ[Invalid] {
		return nil
	}

	if isUntyped() {
		// both x and target are untyped
		 := .typ.(*Basic).kind
		 := .(*Basic).kind
		if isNumeric(.typ) && isNumeric() {
			if  <  {
				.typ = 
				.updateExprType(.expr, , false)
			}
		} else if  !=  {
			return .newErrorf(, _InvalidUntypedConversion, false, "cannot convert %s to %s", , )
		}
		return nil
	}

	if ,  := .Underlying().(*Basic);  && .mode == constant_ {
		if  := .isRepresentable(, );  != nil {
			return 
		}
		// Expression value may have been rounded - update if needed.
		.updateExprVal(.expr, .val)
	} else {
		 := .implicitType(, )
		if  == nil {
			return .newErrorf(, _InvalidUntypedConversion, false, "cannot convert %s to %s", , )
		}
		 = 
	}
	.typ = 
	// Even though implicitType can return UntypedNil, this value is final: the
	// predeclared identifier nil has no type.
	.updateExprType(.expr, , true)
	return nil
}

// implicitType returns the implicit type of x when used in a context where the
// target type is expected. If no such implicit conversion is possible, it
// returns nil.
func ( *Checker) ( *operand,  Type) Type {
	assert(isUntyped(.typ))
	switch t := .Underlying().(type) {
	case *Basic:
		assert(.mode != constant_)
		// Non-constant untyped values may appear as the
		// result of comparisons (untyped bool), intermediate
		// (delayed-checked) rhs operands of shifts, and as
		// the value nil.
		switch .typ.(*Basic).kind {
		case UntypedBool:
			if !isBoolean() {
				return nil
			}
		case UntypedInt, UntypedRune, UntypedFloat, UntypedComplex:
			if !isNumeric() {
				return nil
			}
		case UntypedString:
			// Non-constant untyped string values are not permitted by the spec and
			// should not occur during normal typechecking passes, but this path is
			// reachable via the AssignableTo API.
			if !isString() {
				return nil
			}
		case UntypedNil:
			// Unsafe.Pointer is a basic type that includes nil.
			if !hasNil() {
				return nil
			}
		default:
			return nil
		}
	case *Interface:
		// Values must have concrete dynamic types. If the value is nil,
		// keep it untyped (this is important for tools such as go vet which
		// need the dynamic type for argument checking of say, print
		// functions)
		if .isNil() {
			return Typ[UntypedNil]
		}
		// cannot assign untyped values to non-empty interfaces
		.completeInterface()
		if !.Empty() {
			return nil
		}
		return Default(.typ)
	case *Pointer, *Signature, *Slice, *Map, *Chan:
		if !.isNil() {
			return nil
		}
		// Keep nil untyped - see comment for interfaces, above.
		return Typ[UntypedNil]
	default:
		return nil
	}
	return 
}

func ( *Checker) (,  *operand,  token.Token) {
	// spec: "In any comparison, the first operand must be assignable
	// to the type of the second operand, or vice versa."
	 := ""
	var  errorCode
	,  := .assignableTo(, .typ, nil)
	,  := .assignableTo(, .typ, nil)
	if  ||  {
		 := false
		switch  {
		case token.EQL, token.NEQ:
			// spec: "The equality operators == and != apply to operands that are comparable."
			 = Comparable(.typ) && Comparable(.typ) || .isNil() && hasNil(.typ) || .isNil() && hasNil(.typ)
		case token.LSS, token.LEQ, token.GTR, token.GEQ:
			// spec: The ordering operators <, <=, >, and >= apply to operands that are ordered."
			 = isOrdered(.typ) && isOrdered(.typ)
		default:
			unreachable()
		}
		if ! {
			 := .typ
			if .isNil() {
				 = .typ
			}
			 = .sprintf("operator %s not defined for %s", , )
			 = _UndefinedOp
		}
	} else {
		 = .sprintf("mismatched types %s and %s", .typ, .typ)
		 = _MismatchedTypes
	}

	if  != "" {
		.errorf(, , "cannot compare %s %s %s (%s)", .expr, , .expr, )
		.mode = invalid
		return
	}

	if .mode == constant_ && .mode == constant_ {
		.val = constant.MakeBool(constant.Compare(.val, , .val))
		// The operands are never materialized; no need to update
		// their types.
	} else {
		.mode = value
		// The operands have now their final types, which at run-
		// time will be materialized. Update the expression trees.
		// If the current types are untyped, the materialized type
		// is the respective default type.
		.updateExprType(.expr, Default(.typ), true)
		.updateExprType(.expr, Default(.typ), true)
	}

	// spec: "Comparison operators compare two operands and yield
	//        an untyped boolean value."
	.typ = Typ[UntypedBool]
}

func ( *Checker) (,  *operand,  *ast.BinaryExpr,  token.Token) {
	 := isUntyped(.typ)

	var  constant.Value
	if .mode == constant_ {
		 = constant.ToInt(.val)
	}

	if isInteger(.typ) ||  &&  != nil && .Kind() == constant.Int {
		// The lhs is of integer type or an untyped constant representable
		// as an integer. Nothing to do.
	} else {
		// shift has no chance
		.invalidOp(, _InvalidShiftOperand, "shifted operand %s must be integer", )
		.mode = invalid
		return
	}

	// spec: "The right operand in a shift expression must have integer type
	// or be an untyped constant representable by a value of type uint."
	switch {
	case isInteger(.typ):
		// nothing to do
	case isUntyped(.typ):
		.convertUntyped(, Typ[Uint])
		if .mode == invalid {
			.mode = invalid
			return
		}
	default:
		.invalidOp(, _InvalidShiftCount, "shift count %s must be integer", )
		.mode = invalid
		return
	}

	var  constant.Value
	if .mode == constant_ {
		// rhs must be an integer value
		// (Either it was of an integer type already, or it was
		// untyped and successfully converted to a uint above.)
		 = constant.ToInt(.val)
		assert(.Kind() == constant.Int)
		if constant.Sign() < 0 {
			.invalidOp(, _InvalidShiftCount, "negative shift count %s", )
			.mode = invalid
			return
		}
	}

	if .mode == constant_ {
		if .mode == constant_ {
			// rhs must be within reasonable bounds in constant shifts
			const  = 1023 - 1 + 52 // so we can express smallestFloat64
			,  := constant.Uint64Val()
			if ! ||  >  {
				.invalidOp(, _InvalidShiftCount, "invalid shift count %s", )
				.mode = invalid
				return
			}
			// The lhs is representable as an integer but may not be an integer
			// (e.g., 2.0, an untyped float) - this can only happen for untyped
			// non-integer numeric constants. Correct the type so that the shift
			// result is of integer type.
			if !isInteger(.typ) {
				.typ = Typ[UntypedInt]
			}
			// x is a constant so xval != nil and it must be of Int kind.
			.val = constant.Shift(, , uint())
			// Typed constants must be representable in
			// their type after each constant operation.
			if isTyped(.typ) {
				if  != nil {
					.expr =  // for better error message
				}
				.representable(, .typ.Underlying().(*Basic))
			}
			return
		}

		// non-constant shift with constant lhs
		if  {
			// spec: "If the left operand of a non-constant shift
			// expression is an untyped constant, the type of the
			// constant is what it would be if the shift expression
			// were replaced by its left operand alone.".
			//
			// Delay operand checking until we know the final type
			// by marking the lhs expression as lhs shift operand.
			//
			// Usually (in correct programs), the lhs expression
			// is in the untyped map. However, it is possible to
			// create incorrect programs where the same expression
			// is evaluated twice (via a declaration cycle) such
			// that the lhs expression type is determined in the
			// first round and thus deleted from the map, and then
			// not found in the second round (double insertion of
			// the same expr node still just leads to one entry for
			// that node, and it can only be deleted once).
			// Be cautious and check for presence of entry.
			// Example: var e, f = int(1<<""[f]) // issue 11347
			if ,  := .untyped[.expr];  {
				.isLhs = true
				.untyped[.expr] = 
			}
			// keep x's type
			.mode = value
			return
		}
	}

	// non-constant shift - lhs must be an integer
	if !isInteger(.typ) {
		.invalidOp(, _InvalidShiftOperand, "shifted operand %s must be integer", )
		.mode = invalid
		return
	}

	.mode = value
}

var binaryOpPredicates = opPredicates{
	token.ADD: func( Type) bool { return isNumeric() || isString() },
	token.SUB: isNumeric,
	token.MUL: isNumeric,
	token.QUO: isNumeric,
	token.REM: isInteger,

	token.AND:     isInteger,
	token.OR:      isInteger,
	token.XOR:     isInteger,
	token.AND_NOT: isInteger,

	token.LAND: isBoolean,
	token.LOR:  isBoolean,
}

// The binary expression e may be nil. It's passed in for better error messages only.
func ( *Checker) ( *operand,  *ast.BinaryExpr, ,  ast.Expr,  token.Token,  token.Pos) {
	var  operand

	.expr(, )
	.expr(&, )

	if .mode == invalid {
		return
	}
	if .mode == invalid {
		.mode = invalid
		.expr = .expr
		return
	}

	if isShift() {
		.shift(, &, , )
		return
	}

	.convertUntyped(, .typ)
	if .mode == invalid {
		return
	}
	.convertUntyped(&, .typ)
	if .mode == invalid {
		.mode = invalid
		return
	}

	if isComparison() {
		.comparison(, &, )
		return
	}

	if !.identical(.typ, .typ) {
		// only report an error if we have valid types
		// (otherwise we had an error reported elsewhere already)
		if .typ != Typ[Invalid] && .typ != Typ[Invalid] {
			var  positioner = 
			if  != nil {
				 = 
			}
			.invalidOp(, _MismatchedTypes, "mismatched types %s and %s", .typ, .typ)
		}
		.mode = invalid
		return
	}

	if !.op(binaryOpPredicates, , ) {
		.mode = invalid
		return
	}

	if  == token.QUO ||  == token.REM {
		// check for zero divisor
		if (.mode == constant_ || isInteger(.typ)) && .mode == constant_ && constant.Sign(.val) == 0 {
			.invalidOp(&, _DivByZero, "division by zero")
			.mode = invalid
			return
		}

		// check for divisor underflow in complex division (see issue 20227)
		if .mode == constant_ && .mode == constant_ && isComplex(.typ) {
			,  := constant.Real(.val), constant.Imag(.val)
			,  := constant.BinaryOp(, token.MUL, ), constant.BinaryOp(, token.MUL, )
			if constant.Sign() == 0 && constant.Sign() == 0 {
				.invalidOp(&, _DivByZero, "division by zero")
				.mode = invalid
				return
			}
		}
	}

	if .mode == constant_ && .mode == constant_ {
		 := .val
		 := .val
		 := .typ.Underlying().(*Basic)
		// force integer division of integer operands
		if  == token.QUO && isInteger() {
			 = token.QUO_ASSIGN
		}
		.val = constant.BinaryOp(, , )
		// report error if valid operands lead to an invalid result
		if .Kind() != constant.Unknown && .Kind() != constant.Unknown && .val.Kind() == constant.Unknown {
			// TODO(gri) We should report exactly what went wrong. At the
			//           moment we don't have the (go/constant) API for that.
			//           See also TODO in go/constant/value.go.
			.errorf(atPos(), _InvalidConstVal, "constant result is not representable")
			// TODO(gri) Should we mark operands with unknown values as invalid?
		}
		// Typed constants must be representable in
		// their type after each constant operation.
		if isTyped() {
			if  != nil {
				.expr =  // for better error message
			}
			.representable(, )
		}
		return
	}

	.mode = value
	// x.typ is unchanged
}

// index checks an index expression for validity.
// If max >= 0, it is the upper bound for index.
// If the result typ is != Typ[Invalid], index is valid and typ is its (possibly named) integer type.
// If the result val >= 0, index is valid and val is its constant int value.
func ( *Checker) ( ast.Expr,  int64) ( Type,  int64) {
	 = Typ[Invalid]
	 = -1

	var  operand
	.expr(&, )
	if .mode == invalid {
		return
	}

	// an untyped constant must be representable as Int
	.convertUntyped(&, Typ[Int])
	if .mode == invalid {
		return
	}

	// the index must be of integer type
	if !isInteger(.typ) {
		.invalidArg(&, _InvalidIndex, "index %s must be integer", &)
		return
	}

	if .mode != constant_ {
		return .typ, -1
	}

	// a constant index i must be in bounds
	if constant.Sign(.val) < 0 {
		.invalidArg(&, _InvalidIndex, "index %s must not be negative", &)
		return
	}

	,  := constant.Int64Val(constant.ToInt(.val))
	if ! ||  >= 0 &&  >=  {
		.errorf(&, _InvalidIndex, "index %s is out of bounds", &)
		return
	}

	// 0 <= v [ && v < max ]
	return Typ[Int], 
}

// indexElts checks the elements (elts) of an array or slice composite literal
// against the literal's element type (typ), and the element indices against
// the literal length if known (length >= 0). It returns the length of the
// literal (maximum index value + 1).
//
func ( *Checker) ( []ast.Expr,  Type,  int64) int64 {
	 := make(map[int64]bool, len())
	var ,  int64
	for ,  := range  {
		// determine and check index
		 := false
		 := 
		if ,  := .(*ast.KeyValueExpr);  != nil {
			if ,  := .index(.Key, );  != Typ[Invalid] {
				if  >= 0 {
					 = 
					 = true
				} else {
					.errorf(, _InvalidLitIndex, "index %s must be integer constant", .Key)
				}
			}
			 = .Value
		} else if  >= 0 &&  >=  {
			.errorf(, _OversizeArrayLit, "index %d is out of bounds (>= %d)", , )
		} else {
			 = true
		}

		// if we have a valid index, check for duplicate entries
		if  {
			if [] {
				.errorf(, _DuplicateLitKey, "duplicate index %d in array or slice literal", )
			}
			[] = true
		}
		++
		if  >  {
			 = 
		}

		// check element against composite literal element type
		var  operand
		.exprWithHint(&, , )
		.assignment(&, , "array or slice literal")
	}
	return 
}

// exprKind describes the kind of an expression; the kind
// determines if an expression is valid in 'statement context'.
type exprKind int

const (
	conversion exprKind = iota
	expression
	statement
)

// rawExpr typechecks expression e and initializes x with the expression
// value or type. If an error occurred, x.mode is set to invalid.
// If hint != nil, it is the type of a composite literal element.
//
func ( *Checker) ( *operand,  ast.Expr,  Type) exprKind {
	if trace {
		.trace(.Pos(), "%s", )
		.indent++
		defer func() {
			.indent--
			.trace(.Pos(), "=> %s", )
		}()
	}

	 := .exprInternal(, , )

	// convert x into a user-friendly set of values
	// TODO(gri) this code can be simplified
	var  Type
	var  constant.Value
	switch .mode {
	case invalid:
		 = Typ[Invalid]
	case novalue:
		 = (*Tuple)(nil)
	case constant_:
		 = .typ
		 = .val
	default:
		 = .typ
	}
	assert(.expr != nil &&  != nil)

	if isUntyped() {
		// delay type and value recording until we know the type
		// or until the end of type checking
		.rememberUntyped(.expr, false, .mode, .(*Basic), )
	} else {
		.recordTypeAndValue(, .mode, , )
	}

	return 
}

// exprInternal contains the core of type checking of expressions.
// Must only be called by rawExpr.
//
func ( *Checker) ( *operand,  ast.Expr,  Type) exprKind {
	// make sure x has a valid state in case of bailout
	// (was issue 5770)
	.mode = invalid
	.typ = Typ[Invalid]

	switch e := .(type) {
	case *ast.BadExpr:
		goto  // error was reported before

	case *ast.Ident:
		.ident(, , nil, false)

	case *ast.Ellipsis:
		// ellipses are handled explicitly where they are legal
		// (array composite literals and parameter lists)
		.error(, _BadDotDotDotSyntax, "invalid use of '...'")
		goto 

	case *ast.BasicLit:
		.setConst(.Kind, .Value)
		if .mode == invalid {
			// The parser already establishes syntactic correctness.
			// If we reach here it's because of number under-/overflow.
			// TODO(gri) setConst (and in turn the go/constant package)
			// should return an error describing the issue.
			.errorf(, _InvalidConstVal, "malformed constant: %s", .Value)
			goto 
		}

	case *ast.FuncLit:
		if ,  := .typ(.Type).(*Signature);  {
			// Anonymous functions are considered part of the
			// init expression/func declaration which contains
			// them: use existing package-level declaration info.
			 := .decl // capture for use in closure below
			 := .iota // capture for use in closure below (#22345)
			// Don't type-check right away because the function may
			// be part of a type definition to which the function
			// body refers. Instead, type-check as soon as possible,
			// but before the enclosing scope contents changes (#22992).
			.later(func() {
				.funcBody(, "<function literal>", , .Body, )
			})
			.mode = value
			.typ = 
		} else {
			.invalidAST(, "invalid function literal %s", )
			goto 
		}

	case *ast.CompositeLit:
		var ,  Type

		switch {
		case .Type != nil:
			// composite literal type present - use it
			// [...]T array types may only appear with composite literals.
			// Check for them here so we don't have to handle ... in general.
			if ,  := .Type.(*ast.ArrayType);  != nil && .Len != nil {
				if ,  := .Len.(*ast.Ellipsis);  != nil && .Elt == nil {
					// We have an "open" [...]T array type.
					// Create a new ArrayType with unknown length (-1)
					// and finish setting it up after analyzing the literal.
					 = &Array{len: -1, elem: .typ(.Elt)}
					 = 
					break
				}
			}
			 = .typ(.Type)
			 = 

		case  != nil:
			// no composite literal type present - use hint (element type of enclosing type)
			 = 
			, _ = deref(.Underlying()) // *T implies &T{}

		default:
			// TODO(gri) provide better error messages depending on context
			.error(, _UntypedLit, "missing type in composite literal")
			goto 
		}

		switch utyp := .Underlying().(type) {
		case *Struct:
			if len(.Elts) == 0 {
				break
			}
			 := .fields
			if ,  := .Elts[0].(*ast.KeyValueExpr);  {
				// all elements must have keys
				 := make([]bool, len())
				for ,  := range .Elts {
					,  := .(*ast.KeyValueExpr)
					if  == nil {
						.error(, _MixedStructLit, "mixture of field:value and value elements in struct literal")
						continue
					}
					,  := .Key.(*ast.Ident)
					// do all possible checks early (before exiting due to errors)
					// so we don't drop information on the floor
					.expr(, .Value)
					if  == nil {
						.errorf(, _InvalidLitField, "invalid field name %s in struct literal", .Key)
						continue
					}
					 := fieldIndex(.fields, .pkg, .Name)
					if  < 0 {
						.errorf(, _MissingLitField, "unknown field %s in struct literal", .Name)
						continue
					}
					 := []
					.recordUse(, )
					 := .typ
					.assignment(, , "struct literal")
					// 0 <= i < len(fields)
					if [] {
						.errorf(, _DuplicateLitField, "duplicate field name %s in struct literal", .Name)
						continue
					}
					[] = true
				}
			} else {
				// no element must have a key
				for ,  := range .Elts {
					if ,  := .(*ast.KeyValueExpr);  != nil {
						.error(, _MixedStructLit, "mixture of field:value and value elements in struct literal")
						continue
					}
					.expr(, )
					if  >= len() {
						.error(, _InvalidStructLit, "too many values in struct literal")
						break // cannot continue
					}
					// i < len(fields)
					 := []
					if !.Exported() && .pkg != .pkg {
						.errorf(,
							_UnexportedLitField,
							"implicit assignment to unexported field %s in %s literal", .name, )
						continue
					}
					 := .typ
					.assignment(, , "struct literal")
				}
				if len(.Elts) < len() {
					.error(inNode(, .Rbrace), _InvalidStructLit, "too few values in struct literal")
					// ok to continue
				}
			}

		case *Array:
			// Prevent crash if the array referred to is not yet set up. Was issue #18643.
			// This is a stop-gap solution. Should use Checker.objPath to report entire
			// path starting with earliest declaration in the source. TODO(gri) fix this.
			if .elem == nil {
				.error(, _InvalidTypeCycle, "illegal cycle in type declaration")
				goto 
			}
			 := .indexedElts(.Elts, .elem, .len)
			// If we have an array of unknown length (usually [...]T arrays, but also
			// arrays [n]T where n is invalid) set the length now that we know it and
			// record the type for the array (usually done by check.typ which is not
			// called for [...]T). We handle [...]T arrays and arrays with invalid
			// length the same here because it makes sense to "guess" the length for
			// the latter if we have a composite literal; e.g. for [n]int{1, 2, 3}
			// where n is invalid for some reason, it seems fair to assume it should
			// be 3 (see also Checked.arrayLength and issue #27346).
			if .len < 0 {
				.len = 
				// e.Type is missing if we have a composite literal element
				// that is itself a composite literal with omitted type. In
				// that case there is nothing to record (there is no type in
				// the source at that point).
				if .Type != nil {
					.recordTypeAndValue(.Type, typexpr, , nil)
				}
			}

		case *Slice:
			// Prevent crash if the slice referred to is not yet set up.
			// See analogous comment for *Array.
			if .elem == nil {
				.error(, _InvalidTypeCycle, "illegal cycle in type declaration")
				goto 
			}
			.indexedElts(.Elts, .elem, -1)

		case *Map:
			// Prevent crash if the map referred to is not yet set up.
			// See analogous comment for *Array.
			if .key == nil || .elem == nil {
				.error(, _InvalidTypeCycle, "illegal cycle in type declaration")
				goto 
			}
			 := make(map[interface{}][]Type, len(.Elts))
			for ,  := range .Elts {
				,  := .(*ast.KeyValueExpr)
				if  == nil {
					.error(, _MissingLitKey, "missing key in map literal")
					continue
				}
				.exprWithHint(, .Key, .key)
				.assignment(, .key, "map literal")
				if .mode == invalid {
					continue
				}
				if .mode == constant_ {
					 := false
					// if the key is of interface type, the type is also significant when checking for duplicates
					 := keyVal(.val)
					if ,  := .key.Underlying().(*Interface);  {
						for ,  := range [] {
							if .identical(, .typ) {
								 = true
								break
							}
						}
						[] = append([], .typ)
					} else {
						_,  = []
						[] = nil
					}
					if  {
						.errorf(, _DuplicateLitKey, "duplicate key %s in map literal", .val)
						continue
					}
				}
				.exprWithHint(, .Value, .elem)
				.assignment(, .elem, "map literal")
			}

		default:
			// when "using" all elements unpack KeyValueExpr
			// explicitly because check.use doesn't accept them
			for ,  := range .Elts {
				if ,  := .(*ast.KeyValueExpr);  != nil {
					// Ideally, we should also "use" kv.Key but we can't know
					// if it's an externally defined struct key or not. Going
					// forward anyway can lead to other errors. Give up instead.
					 = .Value
				}
				.use()
			}
			// if utyp is invalid, an error was reported before
			if  != Typ[Invalid] {
				.errorf(, _InvalidLit, "invalid composite literal type %s", )
				goto 
			}
		}

		.mode = value
		.typ = 

	case *ast.ParenExpr:
		 := .rawExpr(, .X, nil)
		.expr = 
		return 

	case *ast.SelectorExpr:
		.selector(, )

	case *ast.IndexExpr:
		.expr(, .X)
		if .mode == invalid {
			.use(.Index)
			goto 
		}

		 := false
		 := int64(-1) // valid if >= 0
		switch typ := .typ.Underlying().(type) {
		case *Basic:
			if isString() {
				 = true
				if .mode == constant_ {
					 = int64(len(constant.StringVal(.val)))
				}
				// an indexed string always yields a byte value
				// (not a constant) even if the string and the
				// index are constant
				.mode = value
				.typ = universeByte // use 'byte' name
			}

		case *Array:
			 = true
			 = .len
			if .mode != variable {
				.mode = value
			}
			.typ = .elem

		case *Pointer:
			if ,  := .base.Underlying().(*Array);  != nil {
				 = true
				 = .len
				.mode = variable
				.typ = .elem
			}

		case *Slice:
			 = true
			.mode = variable
			.typ = .elem

		case *Map:
			var  operand
			.expr(&, .Index)
			.assignment(&, .key, "map index")
			// ok to continue even if indexing failed - map element type is known
			.mode = mapindex
			.typ = .elem
			.expr = 
			return expression
		}

		if ! {
			.invalidOp(, _NonIndexableOperand, "cannot index %s", )
			goto 
		}

		if .Index == nil {
			.invalidAST(, "missing index for %s", )
			goto 
		}

		.index(.Index, )
		// ok to continue

	case *ast.SliceExpr:
		.expr(, .X)
		if .mode == invalid {
			.use(.Low, .High, .Max)
			goto 
		}

		 := false
		 := int64(-1) // valid if >= 0
		switch typ := .typ.Underlying().(type) {
		case *Basic:
			if isString() {
				if .Slice3 {
					.invalidOp(, _InvalidSliceExpr, "3-index slice of string")
					goto 
				}
				 = true
				if .mode == constant_ {
					 = int64(len(constant.StringVal(.val)))
				}
				// spec: "For untyped string operands the result
				// is a non-constant value of type string."
				if .kind == UntypedString {
					.typ = Typ[String]
				}
			}

		case *Array:
			 = true
			 = .len
			if .mode != variable {
				.invalidOp(, _NonSliceableOperand, "cannot slice %s (value not addressable)", )
				goto 
			}
			.typ = &Slice{elem: .elem}

		case *Pointer:
			if ,  := .base.Underlying().(*Array);  != nil {
				 = true
				 = .len
				.typ = &Slice{elem: .elem}
			}

		case *Slice:
			 = true
			// x.typ doesn't change
		}

		if ! {
			.invalidOp(, _NonSliceableOperand, "cannot slice %s", )
			goto 
		}

		.mode = value

		// spec: "Only the first index may be omitted; it defaults to 0."
		if .Slice3 && (.High == nil || .Max == nil) {
			.invalidAST(inNode(, .Rbrack), "2nd and 3rd index required in 3-index slice")
			goto 
		}

		// check indices
		var  [3]int64
		for ,  := range []ast.Expr{.Low, .High, .Max} {
			 := int64(-1)
			switch {
			case  != nil:
				// The "capacity" is only known statically for strings, arrays,
				// and pointers to arrays, and it is the same as the length for
				// those types.
				 := int64(-1)
				if  >= 0 {
					 =  + 1
				}
				if ,  := .index(, );  >= 0 {
					 = 
				}
			case  == 0:
				// default is 0 for the first index
				 = 0
			case  >= 0:
				// default is length (== capacity) otherwise
				 = 
			}
			[] = 
		}

		// constant indices must be in range
		// (check.index already checks that existing indices >= 0)
	:
		for ,  := range [:len()-1] {
			if  > 0 {
				for ,  := range [+1:] {
					if  >= 0 &&  >  {
						.errorf(inNode(, .Rbrack), _SwappedSliceIndices, "swapped slice indices: %d > %d", , )
						break  // only report one error, ok to continue
					}
				}
			}
		}

	case *ast.TypeAssertExpr:
		.expr(, .X)
		if .mode == invalid {
			goto 
		}
		,  := .typ.Underlying().(*Interface)
		if  == nil {
			.invalidOp(, _InvalidAssert, "%s is not an interface", )
			goto 
		}
		// x.(type) expressions are handled explicitly in type switches
		if .Type == nil {
			// Don't use invalidAST because this can occur in the AST produced by
			// go/parser.
			.error(, _BadTypeKeyword, "use of .(type) outside type switch")
			goto 
		}
		 := .typ(.Type)
		if  == Typ[Invalid] {
			goto 
		}
		.typeAssertion(, , , )
		.mode = commaok
		.typ = 

	case *ast.CallExpr:
		return .call(, )

	case *ast.StarExpr:
		.exprOrType(, .X)
		switch .mode {
		case invalid:
			goto 
		case typexpr:
			.typ = &Pointer{base: .typ}
		default:
			if ,  := .typ.Underlying().(*Pointer);  {
				.mode = variable
				.typ = .base
			} else {
				.invalidOp(, _InvalidIndirection, "cannot indirect %s", )
				goto 
			}
		}

	case *ast.UnaryExpr:
		.expr(, .X)
		if .mode == invalid {
			goto 
		}
		.unary(, , .Op)
		if .mode == invalid {
			goto 
		}
		if .Op == token.ARROW {
			.expr = 
			return statement // receive operations may appear in statement context
		}

	case *ast.BinaryExpr:
		.binary(, , .X, .Y, .Op, .OpPos)
		if .mode == invalid {
			goto 
		}

	case *ast.KeyValueExpr:
		// key:value expressions are handled in composite literals
		.invalidAST(, "no key:value expected")
		goto 

	case *ast.ArrayType, *ast.StructType, *ast.FuncType,
		*ast.InterfaceType, *ast.MapType, *ast.ChanType:
		.mode = typexpr
		.typ = .typ()
		// Note: rawExpr (caller of exprInternal) will call check.recordTypeAndValue
		// even though check.typ has already called it. This is fine as both
		// times the same expression and type are recorded. It is also not a
		// performance issue because we only reach here for composite literal
		// types, which are comparatively rare.

	default:
		panic(fmt.Sprintf("%s: unknown expression type %T", .fset.Position(.Pos()), ))
	}

	// everything went well
	.expr = 
	return expression

:
	.mode = invalid
	.expr = 
	return statement // avoid follow-up errors
}

func keyVal( constant.Value) interface{} {
	switch .Kind() {
	case constant.Bool:
		return constant.BoolVal()
	case constant.String:
		return constant.StringVal()
	case constant.Int:
		if ,  := constant.Int64Val();  {
			return 
		}
		if ,  := constant.Uint64Val();  {
			return 
		}
	case constant.Float:
		,  := constant.Float64Val()
		return 
	case constant.Complex:
		,  := constant.Float64Val(constant.Real())
		,  := constant.Float64Val(constant.Imag())
		return complex(, )
	}
	return 
}

// typeAssertion checks that x.(T) is legal; xtyp must be the type of x.
func ( *Checker) ( positioner,  *operand,  *Interface,  Type) {
	,  := .assertableTo(, )
	if  == nil {
		return
	}
	var  string
	if  != nil {
		if .identical(.typ, .typ) {
			 = fmt.Sprintf("missing method %s (%s has pointer receiver)", .name, .name)
		} else {
			 = fmt.Sprintf("wrong type for method %s (have %s, want %s)", .name, .typ, .typ)
		}
	} else {
		 = "missing method " + .name
	}
	.errorf(, _ImpossibleAssert, "%s cannot have dynamic type %s (%s)", , , )
}

func ( *Checker) ( *operand) {
	if .mode == value {
		// tuple types are never named - no need for underlying type below
		if ,  := .typ.(*Tuple);  {
			assert(.Len() != 1)
			.errorf(, _TooManyValues, "%d-valued %s where single value is expected", .Len(), )
			.mode = invalid
		}
	}
}

// expr typechecks expression e and initializes x with the expression value.
// The result must be a single value.
// If an error occurred, x.mode is set to invalid.
//
func ( *Checker) ( *operand,  ast.Expr) {
	.multiExpr(, )
	.singleValue()
}

// multiExpr is like expr but the result may be a multi-value.
func ( *Checker) ( *operand,  ast.Expr) {
	.rawExpr(, , nil)
	var  string
	var  errorCode
	switch .mode {
	default:
		return
	case novalue:
		 = "%s used as value"
		 = _TooManyValues
	case builtin:
		 = "%s must be called"
		 = _UncalledBuiltin
	case typexpr:
		 = "%s is not an expression"
		 = _NotAnExpr
	}
	.errorf(, , , )
	.mode = invalid
}

// exprWithHint typechecks expression e and initializes x with the expression value;
// hint is the type of a composite literal element.
// If an error occurred, x.mode is set to invalid.
//
func ( *Checker) ( *operand,  ast.Expr,  Type) {
	assert( != nil)
	.rawExpr(, , )
	.singleValue()
	var  string
	var  errorCode
	switch .mode {
	default:
		return
	case novalue:
		 = "%s used as value"
		 = _TooManyValues
	case builtin:
		 = "%s must be called"
		 = _UncalledBuiltin
	case typexpr:
		 = "%s is not an expression"
		 = _NotAnExpr
	}
	.errorf(, , , )
	.mode = invalid
}

// exprOrType typechecks expression or type e and initializes x with the expression value or type.
// If an error occurred, x.mode is set to invalid.
//
func ( *Checker) ( *operand,  ast.Expr) {
	.rawExpr(, , nil)
	.singleValue()
	if .mode == novalue {
		.errorf(, _NotAnExpr, "%s used as value or type", )
		.mode = invalid
	}
}