github.com/bir3/gocompiler@v0.3.205/src/go/types/expr.go (about)

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