...

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

Documentation: cmd/compile/internal/types2

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

View as plain text