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