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