Source file src/go/types/expr.go

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

View as plain text