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

View as plain text