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