...

Source file src/go/types/expr.go

Documentation: go/types

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

View as plain text