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

View as plain text