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

View as plain text