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

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

View as plain text