github.com/lovishpuri/go-40569/src@v0.0.0-20230519171745-f8623e7c56cf/go/types/expr.go (about)

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