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

View as plain text