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