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