...
Run Format

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

View as plain text