...

Source file src/go/types/expr.go

Documentation: go/types

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

View as plain text