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

View as plain text