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