Source file src/go/types/expr.go

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

View as plain text