Black Lives Matter. Support the Equal Justice Initiative.

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

View as plain text