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

View as plain text