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

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

View as plain text