Source file src/cmd/compile/internal/types2/expr.go

     1  // Copyright 2012 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // This file implements typechecking of expressions.
     6  
     7  package types2
     8  
     9  import (
    10  	"cmd/compile/internal/syntax"
    11  	"fmt"
    12  	"go/constant"
    13  	"go/token"
    14  	. "internal/types/errors"
    15  	"strings"
    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  			panic("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  		panic("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  		panic("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  // langCompat reports an error if the representation of a numeric
  1036  // literal is not compatible with the current language version.
  1037  func (check *Checker) langCompat(lit *syntax.BasicLit) {
  1038  	s := lit.Value
  1039  	if len(s) <= 2 || check.allowVersion(lit, go1_13) {
  1040  		return
  1041  	}
  1042  	// len(s) > 2
  1043  	if strings.Contains(s, "_") {
  1044  		check.versionErrorf(lit, go1_13, "underscore in numeric literal")
  1045  		return
  1046  	}
  1047  	if s[0] != '0' {
  1048  		return
  1049  	}
  1050  	radix := s[1]
  1051  	if radix == 'b' || radix == 'B' {
  1052  		check.versionErrorf(lit, go1_13, "binary literal")
  1053  		return
  1054  	}
  1055  	if radix == 'o' || radix == 'O' {
  1056  		check.versionErrorf(lit, go1_13, "0o/0O-style octal literal")
  1057  		return
  1058  	}
  1059  	if lit.Kind != syntax.IntLit && (radix == 'x' || radix == 'X') {
  1060  		check.versionErrorf(lit, go1_13, "hexadecimal floating-point literal")
  1061  	}
  1062  }
  1063  
  1064  // exprInternal contains the core of type checking of expressions.
  1065  // Must only be called by rawExpr.
  1066  // (See rawExpr for an explanation of the parameters.)
  1067  func (check *Checker) exprInternal(T *target, x *operand, e syntax.Expr, hint Type) exprKind {
  1068  	// make sure x has a valid state in case of bailout
  1069  	// (was go.dev/issue/5770)
  1070  	x.mode = invalid
  1071  	x.typ = Typ[Invalid]
  1072  
  1073  	switch e := e.(type) {
  1074  	case nil:
  1075  		panic("unreachable")
  1076  
  1077  	case *syntax.BadExpr:
  1078  		goto Error // error was reported before
  1079  
  1080  	case *syntax.Name:
  1081  		check.ident(x, e, nil, false)
  1082  
  1083  	case *syntax.DotsType:
  1084  		// dots are handled explicitly where they are legal
  1085  		// (array composite literals and parameter lists)
  1086  		check.error(e, BadDotDotDotSyntax, "invalid use of '...'")
  1087  		goto Error
  1088  
  1089  	case *syntax.BasicLit:
  1090  		if e.Bad {
  1091  			goto Error // error reported during parsing
  1092  		}
  1093  		switch e.Kind {
  1094  		case syntax.IntLit, syntax.FloatLit, syntax.ImagLit:
  1095  			check.langCompat(e)
  1096  			// The max. mantissa precision for untyped numeric values
  1097  			// is 512 bits, or 4048 bits for each of the two integer
  1098  			// parts of a fraction for floating-point numbers that are
  1099  			// represented accurately in the go/constant package.
  1100  			// Constant literals that are longer than this many bits
  1101  			// are not meaningful; and excessively long constants may
  1102  			// consume a lot of space and time for a useless conversion.
  1103  			// Cap constant length with a generous upper limit that also
  1104  			// allows for separators between all digits.
  1105  			const limit = 10000
  1106  			if len(e.Value) > limit {
  1107  				check.errorf(e, InvalidConstVal, "excessively long constant: %s... (%d chars)", e.Value[:10], len(e.Value))
  1108  				goto Error
  1109  			}
  1110  		}
  1111  		x.setConst(e.Kind, e.Value)
  1112  		if x.mode == invalid {
  1113  			// The parser already establishes syntactic correctness.
  1114  			// If we reach here it's because of number under-/overflow.
  1115  			// TODO(gri) setConst (and in turn the go/constant package)
  1116  			// should return an error describing the issue.
  1117  			check.errorf(e, InvalidConstVal, "malformed constant: %s", e.Value)
  1118  			goto Error
  1119  		}
  1120  		// Ensure that integer values don't overflow (go.dev/issue/54280).
  1121  		x.expr = e // make sure that check.overflow below has an error position
  1122  		check.overflow(x, opPos(x.expr))
  1123  
  1124  	case *syntax.FuncLit:
  1125  		if sig, ok := check.typ(e.Type).(*Signature); ok {
  1126  			// Set the Scope's extent to the complete "func (...) {...}"
  1127  			// so that Scope.Innermost works correctly.
  1128  			sig.scope.pos = e.Pos()
  1129  			sig.scope.end = syntax.EndPos(e)
  1130  			if !check.conf.IgnoreFuncBodies && e.Body != nil {
  1131  				// Anonymous functions are considered part of the
  1132  				// init expression/func declaration which contains
  1133  				// them: use existing package-level declaration info.
  1134  				decl := check.decl // capture for use in closure below
  1135  				iota := check.iota // capture for use in closure below (go.dev/issue/22345)
  1136  				// Don't type-check right away because the function may
  1137  				// be part of a type definition to which the function
  1138  				// body refers. Instead, type-check as soon as possible,
  1139  				// but before the enclosing scope contents changes (go.dev/issue/22992).
  1140  				check.later(func() {
  1141  					check.funcBody(decl, "<function literal>", sig, e.Body, iota)
  1142  				}).describef(e, "func literal")
  1143  			}
  1144  			x.mode = value
  1145  			x.typ = sig
  1146  		} else {
  1147  			check.errorf(e, InvalidSyntaxTree, "invalid function literal %v", e)
  1148  			goto Error
  1149  		}
  1150  
  1151  	case *syntax.CompositeLit:
  1152  		var typ, base Type
  1153  
  1154  		switch {
  1155  		case e.Type != nil:
  1156  			// composite literal type present - use it
  1157  			// [...]T array types may only appear with composite literals.
  1158  			// Check for them here so we don't have to handle ... in general.
  1159  			if atyp, _ := e.Type.(*syntax.ArrayType); atyp != nil && atyp.Len == nil {
  1160  				// We have an "open" [...]T array type.
  1161  				// Create a new ArrayType with unknown length (-1)
  1162  				// and finish setting it up after analyzing the literal.
  1163  				typ = &Array{len: -1, elem: check.varType(atyp.Elem)}
  1164  				base = typ
  1165  				break
  1166  			}
  1167  			typ = check.typ(e.Type)
  1168  			base = typ
  1169  
  1170  		case hint != nil:
  1171  			// no composite literal type present - use hint (element type of enclosing type)
  1172  			typ = hint
  1173  			base, _ = deref(coreType(typ)) // *T implies &T{}
  1174  			if base == nil {
  1175  				check.errorf(e, InvalidLit, "invalid composite literal element type %s (no core type)", typ)
  1176  				goto Error
  1177  			}
  1178  
  1179  		default:
  1180  			// TODO(gri) provide better error messages depending on context
  1181  			check.error(e, UntypedLit, "missing type in composite literal")
  1182  			goto Error
  1183  		}
  1184  
  1185  		switch utyp := coreType(base).(type) {
  1186  		case *Struct:
  1187  			// Prevent crash if the struct referred to is not yet set up.
  1188  			// See analogous comment for *Array.
  1189  			if utyp.fields == nil {
  1190  				check.error(e, InvalidTypeCycle, "invalid recursive type")
  1191  				goto Error
  1192  			}
  1193  			if len(e.ElemList) == 0 {
  1194  				break
  1195  			}
  1196  			// Convention for error messages on invalid struct literals:
  1197  			// we mention the struct type only if it clarifies the error
  1198  			// (e.g., a duplicate field error doesn't need the struct type).
  1199  			fields := utyp.fields
  1200  			if _, ok := e.ElemList[0].(*syntax.KeyValueExpr); ok {
  1201  				// all elements must have keys
  1202  				visited := make([]bool, len(fields))
  1203  				for _, e := range e.ElemList {
  1204  					kv, _ := e.(*syntax.KeyValueExpr)
  1205  					if kv == nil {
  1206  						check.error(e, MixedStructLit, "mixture of field:value and value elements in struct literal")
  1207  						continue
  1208  					}
  1209  					key, _ := kv.Key.(*syntax.Name)
  1210  					// do all possible checks early (before exiting due to errors)
  1211  					// so we don't drop information on the floor
  1212  					check.expr(nil, x, kv.Value)
  1213  					if key == nil {
  1214  						check.errorf(kv, InvalidLitField, "invalid field name %s in struct literal", kv.Key)
  1215  						continue
  1216  					}
  1217  					i := fieldIndex(fields, check.pkg, key.Value, false)
  1218  					if i < 0 {
  1219  						var alt Object
  1220  						if j := fieldIndex(fields, check.pkg, key.Value, true); j >= 0 {
  1221  							alt = fields[j]
  1222  						}
  1223  						msg := check.lookupError(base, key.Value, alt, true)
  1224  						check.error(kv.Key, MissingLitField, msg)
  1225  						continue
  1226  					}
  1227  					fld := fields[i]
  1228  					check.recordUse(key, fld)
  1229  					etyp := fld.typ
  1230  					check.assignment(x, etyp, "struct literal")
  1231  					// 0 <= i < len(fields)
  1232  					if visited[i] {
  1233  						check.errorf(kv, DuplicateLitField, "duplicate field name %s in struct literal", key.Value)
  1234  						continue
  1235  					}
  1236  					visited[i] = true
  1237  				}
  1238  			} else {
  1239  				// no element must have a key
  1240  				for i, e := range e.ElemList {
  1241  					if kv, _ := e.(*syntax.KeyValueExpr); kv != nil {
  1242  						check.error(kv, MixedStructLit, "mixture of field:value and value elements in struct literal")
  1243  						continue
  1244  					}
  1245  					check.expr(nil, x, e)
  1246  					if i >= len(fields) {
  1247  						check.errorf(x, InvalidStructLit, "too many values in struct literal of type %s", base)
  1248  						break // cannot continue
  1249  					}
  1250  					// i < len(fields)
  1251  					fld := fields[i]
  1252  					if !fld.Exported() && fld.pkg != check.pkg {
  1253  						check.errorf(x, UnexportedLitField, "implicit assignment to unexported field %s in struct literal of type %s", fld.name, base)
  1254  						continue
  1255  					}
  1256  					etyp := fld.typ
  1257  					check.assignment(x, etyp, "struct literal")
  1258  				}
  1259  				if len(e.ElemList) < len(fields) {
  1260  					check.errorf(e.Rbrace, InvalidStructLit, "too few values in struct literal of type %s", base)
  1261  					// ok to continue
  1262  				}
  1263  			}
  1264  
  1265  		case *Array:
  1266  			// Prevent crash if the array referred to is not yet set up. Was go.dev/issue/18643.
  1267  			// This is a stop-gap solution. Should use Checker.objPath to report entire
  1268  			// path starting with earliest declaration in the source. TODO(gri) fix this.
  1269  			if utyp.elem == nil {
  1270  				check.error(e, InvalidTypeCycle, "invalid recursive type")
  1271  				goto Error
  1272  			}
  1273  			n := check.indexedElts(e.ElemList, utyp.elem, utyp.len)
  1274  			// If we have an array of unknown length (usually [...]T arrays, but also
  1275  			// arrays [n]T where n is invalid) set the length now that we know it and
  1276  			// record the type for the array (usually done by check.typ which is not
  1277  			// called for [...]T). We handle [...]T arrays and arrays with invalid
  1278  			// length the same here because it makes sense to "guess" the length for
  1279  			// the latter if we have a composite literal; e.g. for [n]int{1, 2, 3}
  1280  			// where n is invalid for some reason, it seems fair to assume it should
  1281  			// be 3 (see also Checked.arrayLength and go.dev/issue/27346).
  1282  			if utyp.len < 0 {
  1283  				utyp.len = n
  1284  				// e.Type is missing if we have a composite literal element
  1285  				// that is itself a composite literal with omitted type. In
  1286  				// that case there is nothing to record (there is no type in
  1287  				// the source at that point).
  1288  				if e.Type != nil {
  1289  					check.recordTypeAndValue(e.Type, typexpr, utyp, nil)
  1290  				}
  1291  			}
  1292  
  1293  		case *Slice:
  1294  			// Prevent crash if the slice referred to is not yet set up.
  1295  			// See analogous comment for *Array.
  1296  			if utyp.elem == nil {
  1297  				check.error(e, InvalidTypeCycle, "invalid recursive type")
  1298  				goto Error
  1299  			}
  1300  			check.indexedElts(e.ElemList, utyp.elem, -1)
  1301  
  1302  		case *Map:
  1303  			// Prevent crash if the map referred to is not yet set up.
  1304  			// See analogous comment for *Array.
  1305  			if utyp.key == nil || utyp.elem == nil {
  1306  				check.error(e, InvalidTypeCycle, "invalid recursive type")
  1307  				goto Error
  1308  			}
  1309  			// If the map key type is an interface (but not a type parameter),
  1310  			// the type of a constant key must be considered when checking for
  1311  			// duplicates.
  1312  			keyIsInterface := isNonTypeParamInterface(utyp.key)
  1313  			visited := make(map[interface{}][]Type, len(e.ElemList))
  1314  			for _, e := range e.ElemList {
  1315  				kv, _ := e.(*syntax.KeyValueExpr)
  1316  				if kv == nil {
  1317  					check.error(e, MissingLitKey, "missing key in map literal")
  1318  					continue
  1319  				}
  1320  				check.exprWithHint(x, kv.Key, utyp.key)
  1321  				check.assignment(x, utyp.key, "map literal")
  1322  				if x.mode == invalid {
  1323  					continue
  1324  				}
  1325  				if x.mode == constant_ {
  1326  					duplicate := false
  1327  					xkey := keyVal(x.val)
  1328  					if keyIsInterface {
  1329  						for _, vtyp := range visited[xkey] {
  1330  							if Identical(vtyp, x.typ) {
  1331  								duplicate = true
  1332  								break
  1333  							}
  1334  						}
  1335  						visited[xkey] = append(visited[xkey], x.typ)
  1336  					} else {
  1337  						_, duplicate = visited[xkey]
  1338  						visited[xkey] = nil
  1339  					}
  1340  					if duplicate {
  1341  						check.errorf(x, DuplicateLitKey, "duplicate key %s in map literal", x.val)
  1342  						continue
  1343  					}
  1344  				}
  1345  				check.exprWithHint(x, kv.Value, utyp.elem)
  1346  				check.assignment(x, utyp.elem, "map literal")
  1347  			}
  1348  
  1349  		default:
  1350  			// when "using" all elements unpack KeyValueExpr
  1351  			// explicitly because check.use doesn't accept them
  1352  			for _, e := range e.ElemList {
  1353  				if kv, _ := e.(*syntax.KeyValueExpr); kv != nil {
  1354  					// Ideally, we should also "use" kv.Key but we can't know
  1355  					// if it's an externally defined struct key or not. Going
  1356  					// forward anyway can lead to other errors. Give up instead.
  1357  					e = kv.Value
  1358  				}
  1359  				check.use(e)
  1360  			}
  1361  			// if utyp is invalid, an error was reported before
  1362  			if isValid(utyp) {
  1363  				check.errorf(e, InvalidLit, "invalid composite literal type %s", typ)
  1364  				goto Error
  1365  			}
  1366  		}
  1367  
  1368  		x.mode = value
  1369  		x.typ = typ
  1370  
  1371  	case *syntax.ParenExpr:
  1372  		// type inference doesn't go past parentheses (targe type T = nil)
  1373  		kind := check.rawExpr(nil, x, e.X, nil, false)
  1374  		x.expr = e
  1375  		return kind
  1376  
  1377  	case *syntax.SelectorExpr:
  1378  		check.selector(x, e, nil, false)
  1379  
  1380  	case *syntax.IndexExpr:
  1381  		if check.indexExpr(x, e) {
  1382  			if !enableReverseTypeInference {
  1383  				T = nil
  1384  			}
  1385  			check.funcInst(T, e.Pos(), x, e, true)
  1386  		}
  1387  		if x.mode == invalid {
  1388  			goto Error
  1389  		}
  1390  
  1391  	case *syntax.SliceExpr:
  1392  		check.sliceExpr(x, e)
  1393  		if x.mode == invalid {
  1394  			goto Error
  1395  		}
  1396  
  1397  	case *syntax.AssertExpr:
  1398  		check.expr(nil, x, e.X)
  1399  		if x.mode == invalid {
  1400  			goto Error
  1401  		}
  1402  		// x.(type) expressions are encoded via TypeSwitchGuards
  1403  		if e.Type == nil {
  1404  			check.error(e, InvalidSyntaxTree, "invalid use of AssertExpr")
  1405  			goto Error
  1406  		}
  1407  		if isTypeParam(x.typ) {
  1408  			check.errorf(x, InvalidAssert, invalidOp+"cannot use type assertion on type parameter value %s", x)
  1409  			goto Error
  1410  		}
  1411  		if _, ok := under(x.typ).(*Interface); !ok {
  1412  			check.errorf(x, InvalidAssert, invalidOp+"%s is not an interface", x)
  1413  			goto Error
  1414  		}
  1415  		T := check.varType(e.Type)
  1416  		if !isValid(T) {
  1417  			goto Error
  1418  		}
  1419  		check.typeAssertion(e, x, T, false)
  1420  		x.mode = commaok
  1421  		x.typ = T
  1422  
  1423  	case *syntax.TypeSwitchGuard:
  1424  		// x.(type) expressions are handled explicitly in type switches
  1425  		check.error(e, InvalidSyntaxTree, "use of .(type) outside type switch")
  1426  		check.use(e.X)
  1427  		goto Error
  1428  
  1429  	case *syntax.CallExpr:
  1430  		return check.callExpr(x, e)
  1431  
  1432  	case *syntax.ListExpr:
  1433  		// catch-all for unexpected expression lists
  1434  		check.error(e, InvalidSyntaxTree, "unexpected list of expressions")
  1435  		goto Error
  1436  
  1437  	// case *syntax.UnaryExpr:
  1438  	// 	check.expr(x, e.X)
  1439  	// 	if x.mode == invalid {
  1440  	// 		goto Error
  1441  	// 	}
  1442  	// 	check.unary(x, e, e.Op)
  1443  	// 	if x.mode == invalid {
  1444  	// 		goto Error
  1445  	// 	}
  1446  	// 	if e.Op == token.ARROW {
  1447  	// 		x.expr = e
  1448  	// 		return statement // receive operations may appear in statement context
  1449  	// 	}
  1450  
  1451  	// case *syntax.BinaryExpr:
  1452  	// 	check.binary(x, e, e.X, e.Y, e.Op)
  1453  	// 	if x.mode == invalid {
  1454  	// 		goto Error
  1455  	// 	}
  1456  
  1457  	case *syntax.Operation:
  1458  		if e.Y == nil {
  1459  			// unary expression
  1460  			if e.Op == syntax.Mul {
  1461  				// pointer indirection
  1462  				check.exprOrType(x, e.X, false)
  1463  				switch x.mode {
  1464  				case invalid:
  1465  					goto Error
  1466  				case typexpr:
  1467  					check.validVarType(e.X, x.typ)
  1468  					x.typ = &Pointer{base: x.typ}
  1469  				default:
  1470  					var base Type
  1471  					if !underIs(x.typ, func(u Type) bool {
  1472  						p, _ := u.(*Pointer)
  1473  						if p == nil {
  1474  							check.errorf(x, InvalidIndirection, invalidOp+"cannot indirect %s", x)
  1475  							return false
  1476  						}
  1477  						if base != nil && !Identical(p.base, base) {
  1478  							check.errorf(x, InvalidIndirection, invalidOp+"pointers of %s must have identical base types", x)
  1479  							return false
  1480  						}
  1481  						base = p.base
  1482  						return true
  1483  					}) {
  1484  						goto Error
  1485  					}
  1486  					x.mode = variable
  1487  					x.typ = base
  1488  				}
  1489  				break
  1490  			}
  1491  
  1492  			check.unary(x, e)
  1493  			if x.mode == invalid {
  1494  				goto Error
  1495  			}
  1496  			if e.Op == syntax.Recv {
  1497  				x.expr = e
  1498  				return statement // receive operations may appear in statement context
  1499  			}
  1500  			break
  1501  		}
  1502  
  1503  		// binary expression
  1504  		check.binary(x, e, e.X, e.Y, e.Op)
  1505  		if x.mode == invalid {
  1506  			goto Error
  1507  		}
  1508  
  1509  	case *syntax.KeyValueExpr:
  1510  		// key:value expressions are handled in composite literals
  1511  		check.error(e, InvalidSyntaxTree, "no key:value expected")
  1512  		goto Error
  1513  
  1514  	case *syntax.ArrayType, *syntax.SliceType, *syntax.StructType, *syntax.FuncType,
  1515  		*syntax.InterfaceType, *syntax.MapType, *syntax.ChanType:
  1516  		x.mode = typexpr
  1517  		x.typ = check.typ(e)
  1518  		// Note: rawExpr (caller of exprInternal) will call check.recordTypeAndValue
  1519  		// even though check.typ has already called it. This is fine as both
  1520  		// times the same expression and type are recorded. It is also not a
  1521  		// performance issue because we only reach here for composite literal
  1522  		// types, which are comparatively rare.
  1523  
  1524  	default:
  1525  		panic(fmt.Sprintf("%s: unknown expression type %T", atPos(e), e))
  1526  	}
  1527  
  1528  	// everything went well
  1529  	x.expr = e
  1530  	return expression
  1531  
  1532  Error:
  1533  	x.mode = invalid
  1534  	x.expr = e
  1535  	return statement // avoid follow-up errors
  1536  }
  1537  
  1538  // keyVal maps a complex, float, integer, string or boolean constant value
  1539  // to the corresponding complex128, float64, int64, uint64, string, or bool
  1540  // Go value if possible; otherwise it returns x.
  1541  // A complex constant that can be represented as a float (such as 1.2 + 0i)
  1542  // is returned as a floating point value; if a floating point value can be
  1543  // represented as an integer (such as 1.0) it is returned as an integer value.
  1544  // This ensures that constants of different kind but equal value (such as
  1545  // 1.0 + 0i, 1.0, 1) result in the same value.
  1546  func keyVal(x constant.Value) interface{} {
  1547  	switch x.Kind() {
  1548  	case constant.Complex:
  1549  		f := constant.ToFloat(x)
  1550  		if f.Kind() != constant.Float {
  1551  			r, _ := constant.Float64Val(constant.Real(x))
  1552  			i, _ := constant.Float64Val(constant.Imag(x))
  1553  			return complex(r, i)
  1554  		}
  1555  		x = f
  1556  		fallthrough
  1557  	case constant.Float:
  1558  		i := constant.ToInt(x)
  1559  		if i.Kind() != constant.Int {
  1560  			v, _ := constant.Float64Val(x)
  1561  			return v
  1562  		}
  1563  		x = i
  1564  		fallthrough
  1565  	case constant.Int:
  1566  		if v, ok := constant.Int64Val(x); ok {
  1567  			return v
  1568  		}
  1569  		if v, ok := constant.Uint64Val(x); ok {
  1570  			return v
  1571  		}
  1572  	case constant.String:
  1573  		return constant.StringVal(x)
  1574  	case constant.Bool:
  1575  		return constant.BoolVal(x)
  1576  	}
  1577  	return x
  1578  }
  1579  
  1580  // typeAssertion checks x.(T). The type of x must be an interface.
  1581  func (check *Checker) typeAssertion(e syntax.Expr, x *operand, T Type, typeSwitch bool) {
  1582  	var cause string
  1583  	if check.assertableTo(x.typ, T, &cause) {
  1584  		return // success
  1585  	}
  1586  
  1587  	if typeSwitch {
  1588  		check.errorf(e, ImpossibleAssert, "impossible type switch case: %s\n\t%s cannot have dynamic type %s %s", e, x, T, cause)
  1589  		return
  1590  	}
  1591  
  1592  	check.errorf(e, ImpossibleAssert, "impossible type assertion: %s\n\t%s does not implement %s %s", e, T, x.typ, cause)
  1593  }
  1594  
  1595  // expr typechecks expression e and initializes x with the expression value.
  1596  // If a non-nil target T is given and e is a generic function or
  1597  // a function call, T is used to infer the type arguments for e.
  1598  // The result must be a single value.
  1599  // If an error occurred, x.mode is set to invalid.
  1600  func (check *Checker) expr(T *target, x *operand, e syntax.Expr) {
  1601  	check.rawExpr(T, x, e, nil, false)
  1602  	check.exclude(x, 1<<novalue|1<<builtin|1<<typexpr)
  1603  	check.singleValue(x)
  1604  }
  1605  
  1606  // genericExpr is like expr but the result may also be generic.
  1607  func (check *Checker) genericExpr(x *operand, e syntax.Expr) {
  1608  	check.rawExpr(nil, x, e, nil, true)
  1609  	check.exclude(x, 1<<novalue|1<<builtin|1<<typexpr)
  1610  	check.singleValue(x)
  1611  }
  1612  
  1613  // multiExpr typechecks e and returns its value (or values) in list.
  1614  // If allowCommaOk is set and e is a map index, comma-ok, or comma-err
  1615  // expression, the result is a two-element list containing the value
  1616  // of e, and an untyped bool value or an error value, respectively.
  1617  // If an error occurred, list[0] is not valid.
  1618  func (check *Checker) multiExpr(e syntax.Expr, allowCommaOk bool) (list []*operand, commaOk bool) {
  1619  	var x operand
  1620  	check.rawExpr(nil, &x, e, nil, false)
  1621  	check.exclude(&x, 1<<novalue|1<<builtin|1<<typexpr)
  1622  
  1623  	if t, ok := x.typ.(*Tuple); ok && x.mode != invalid {
  1624  		// multiple values
  1625  		list = make([]*operand, t.Len())
  1626  		for i, v := range t.vars {
  1627  			list[i] = &operand{mode: value, expr: e, typ: v.typ}
  1628  		}
  1629  		return
  1630  	}
  1631  
  1632  	// exactly one (possibly invalid or comma-ok) value
  1633  	list = []*operand{&x}
  1634  	if allowCommaOk && (x.mode == mapindex || x.mode == commaok || x.mode == commaerr) {
  1635  		x2 := &operand{mode: value, expr: e, typ: Typ[UntypedBool]}
  1636  		if x.mode == commaerr {
  1637  			x2.typ = universeError
  1638  		}
  1639  		list = append(list, x2)
  1640  		commaOk = true
  1641  	}
  1642  
  1643  	return
  1644  }
  1645  
  1646  // exprWithHint typechecks expression e and initializes x with the expression value;
  1647  // hint is the type of a composite literal element.
  1648  // If an error occurred, x.mode is set to invalid.
  1649  func (check *Checker) exprWithHint(x *operand, e syntax.Expr, hint Type) {
  1650  	assert(hint != nil)
  1651  	check.rawExpr(nil, x, e, hint, false)
  1652  	check.exclude(x, 1<<novalue|1<<builtin|1<<typexpr)
  1653  	check.singleValue(x)
  1654  }
  1655  
  1656  // exprOrType typechecks expression or type e and initializes x with the expression value or type.
  1657  // If allowGeneric is set, the operand type may be an uninstantiated parameterized type or function
  1658  // value.
  1659  // If an error occurred, x.mode is set to invalid.
  1660  func (check *Checker) exprOrType(x *operand, e syntax.Expr, allowGeneric bool) {
  1661  	check.rawExpr(nil, x, e, nil, allowGeneric)
  1662  	check.exclude(x, 1<<novalue)
  1663  	check.singleValue(x)
  1664  }
  1665  
  1666  // exclude reports an error if x.mode is in modeset and sets x.mode to invalid.
  1667  // The modeset may contain any of 1<<novalue, 1<<builtin, 1<<typexpr.
  1668  func (check *Checker) exclude(x *operand, modeset uint) {
  1669  	if modeset&(1<<x.mode) != 0 {
  1670  		var msg string
  1671  		var code Code
  1672  		switch x.mode {
  1673  		case novalue:
  1674  			if modeset&(1<<typexpr) != 0 {
  1675  				msg = "%s used as value"
  1676  			} else {
  1677  				msg = "%s used as value or type"
  1678  			}
  1679  			code = TooManyValues
  1680  		case builtin:
  1681  			msg = "%s must be called"
  1682  			code = UncalledBuiltin
  1683  		case typexpr:
  1684  			msg = "%s is not an expression"
  1685  			code = NotAnExpr
  1686  		default:
  1687  			panic("unreachable")
  1688  		}
  1689  		check.errorf(x, code, msg, x)
  1690  		x.mode = invalid
  1691  	}
  1692  }
  1693  
  1694  // singleValue reports an error if x describes a tuple and sets x.mode to invalid.
  1695  func (check *Checker) singleValue(x *operand) {
  1696  	if x.mode == value {
  1697  		// tuple types are never named - no need for underlying type below
  1698  		if t, ok := x.typ.(*Tuple); ok {
  1699  			assert(t.Len() != 1)
  1700  			check.errorf(x, TooManyValues, "multiple-value %s in single-value context", x)
  1701  			x.mode = invalid
  1702  		}
  1703  	}
  1704  }
  1705  
  1706  // op2tok translates syntax.Operators into token.Tokens.
  1707  var op2tok = [...]token.Token{
  1708  	syntax.Def:  token.ILLEGAL,
  1709  	syntax.Not:  token.NOT,
  1710  	syntax.Recv: token.ILLEGAL,
  1711  
  1712  	syntax.OrOr:   token.LOR,
  1713  	syntax.AndAnd: token.LAND,
  1714  
  1715  	syntax.Eql: token.EQL,
  1716  	syntax.Neq: token.NEQ,
  1717  	syntax.Lss: token.LSS,
  1718  	syntax.Leq: token.LEQ,
  1719  	syntax.Gtr: token.GTR,
  1720  	syntax.Geq: token.GEQ,
  1721  
  1722  	syntax.Add: token.ADD,
  1723  	syntax.Sub: token.SUB,
  1724  	syntax.Or:  token.OR,
  1725  	syntax.Xor: token.XOR,
  1726  
  1727  	syntax.Mul:    token.MUL,
  1728  	syntax.Div:    token.QUO,
  1729  	syntax.Rem:    token.REM,
  1730  	syntax.And:    token.AND,
  1731  	syntax.AndNot: token.AND_NOT,
  1732  	syntax.Shl:    token.SHL,
  1733  	syntax.Shr:    token.SHR,
  1734  }
  1735  

View as plain text