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