github.com/alash3al/go@v0.0.0-20150827002835-d497eeb00540/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) || y.assignableTo(check.conf, x.typ) { 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 if !check.assignment(&x, typ) && x.mode != invalid { 902 check.errorf(x.pos(), "cannot use %s as %s value in array or slice literal", &x, typ) 903 } 904 } 905 return max 906 } 907 908 // exprKind describes the kind of an expression; the kind 909 // determines if an expression is valid in 'statement context'. 910 type exprKind int 911 912 const ( 913 conversion exprKind = iota 914 expression 915 statement 916 ) 917 918 // rawExpr typechecks expression e and initializes x with the expression 919 // value or type. If an error occurred, x.mode is set to invalid. 920 // If hint != nil, it is the type of a composite literal element. 921 // 922 func (check *Checker) rawExpr(x *operand, e ast.Expr, hint Type) exprKind { 923 if trace { 924 check.trace(e.Pos(), "%s", e) 925 check.indent++ 926 defer func() { 927 check.indent-- 928 check.trace(e.Pos(), "=> %s", x) 929 }() 930 } 931 932 kind := check.exprInternal(x, e, hint) 933 934 // convert x into a user-friendly set of values 935 // TODO(gri) this code can be simplified 936 var typ Type 937 var val constant.Value 938 switch x.mode { 939 case invalid: 940 typ = Typ[Invalid] 941 case novalue: 942 typ = (*Tuple)(nil) 943 case constant_: 944 typ = x.typ 945 val = x.val 946 default: 947 typ = x.typ 948 } 949 assert(x.expr != nil && typ != nil) 950 951 if isUntyped(typ) { 952 // delay type and value recording until we know the type 953 // or until the end of type checking 954 check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val) 955 } else { 956 check.recordTypeAndValue(e, x.mode, typ, val) 957 } 958 959 return kind 960 } 961 962 // exprInternal contains the core of type checking of expressions. 963 // Must only be called by rawExpr. 964 // 965 func (check *Checker) exprInternal(x *operand, e ast.Expr, hint Type) exprKind { 966 // make sure x has a valid state in case of bailout 967 // (was issue 5770) 968 x.mode = invalid 969 x.typ = Typ[Invalid] 970 971 switch e := e.(type) { 972 case *ast.BadExpr: 973 goto Error // error was reported before 974 975 case *ast.Ident: 976 check.ident(x, e, nil, nil) 977 978 case *ast.Ellipsis: 979 // ellipses are handled explicitly where they are legal 980 // (array composite literals and parameter lists) 981 check.error(e.Pos(), "invalid use of '...'") 982 goto Error 983 984 case *ast.BasicLit: 985 x.setConst(e.Kind, e.Value) 986 if x.mode == invalid { 987 check.invalidAST(e.Pos(), "invalid literal %v", e.Value) 988 goto Error 989 } 990 991 case *ast.FuncLit: 992 if sig, ok := check.typ(e.Type).(*Signature); ok { 993 // Anonymous functions are considered part of the 994 // init expression/func declaration which contains 995 // them: use existing package-level declaration info. 996 check.funcBody(check.decl, "", sig, e.Body) 997 x.mode = value 998 x.typ = sig 999 } else { 1000 check.invalidAST(e.Pos(), "invalid function literal %s", e) 1001 goto Error 1002 } 1003 1004 case *ast.CompositeLit: 1005 typ := hint 1006 openArray := false 1007 if e.Type != nil { 1008 // [...]T array types may only appear with composite literals. 1009 // Check for them here so we don't have to handle ... in general. 1010 typ = nil 1011 if atyp, _ := e.Type.(*ast.ArrayType); atyp != nil && atyp.Len != nil { 1012 if ellip, _ := atyp.Len.(*ast.Ellipsis); ellip != nil && ellip.Elt == nil { 1013 // We have an "open" [...]T array type. 1014 // Create a new ArrayType with unknown length (-1) 1015 // and finish setting it up after analyzing the literal. 1016 typ = &Array{len: -1, elem: check.typ(atyp.Elt)} 1017 openArray = true 1018 } 1019 } 1020 if typ == nil { 1021 typ = check.typ(e.Type) 1022 } 1023 } 1024 if typ == nil { 1025 // TODO(gri) provide better error messages depending on context 1026 check.error(e.Pos(), "missing type in composite literal") 1027 goto Error 1028 } 1029 1030 switch typ, _ := deref(typ); utyp := typ.Underlying().(type) { 1031 case *Struct: 1032 if len(e.Elts) == 0 { 1033 break 1034 } 1035 fields := utyp.fields 1036 if _, ok := e.Elts[0].(*ast.KeyValueExpr); ok { 1037 // all elements must have keys 1038 visited := make([]bool, len(fields)) 1039 for _, e := range e.Elts { 1040 kv, _ := e.(*ast.KeyValueExpr) 1041 if kv == nil { 1042 check.error(e.Pos(), "mixture of field:value and value elements in struct literal") 1043 continue 1044 } 1045 key, _ := kv.Key.(*ast.Ident) 1046 if key == nil { 1047 check.errorf(kv.Pos(), "invalid field name %s in struct literal", kv.Key) 1048 continue 1049 } 1050 i := fieldIndex(utyp.fields, check.pkg, key.Name) 1051 if i < 0 { 1052 check.errorf(kv.Pos(), "unknown field %s in struct literal", key.Name) 1053 continue 1054 } 1055 fld := fields[i] 1056 check.recordUse(key, fld) 1057 // 0 <= i < len(fields) 1058 if visited[i] { 1059 check.errorf(kv.Pos(), "duplicate field name %s in struct literal", key.Name) 1060 continue 1061 } 1062 visited[i] = true 1063 check.expr(x, kv.Value) 1064 etyp := fld.typ 1065 if !check.assignment(x, etyp) { 1066 if x.mode != invalid { 1067 check.errorf(x.pos(), "cannot use %s as %s value in struct literal", x, etyp) 1068 } 1069 continue 1070 } 1071 } 1072 } else { 1073 // no element must have a key 1074 for i, e := range e.Elts { 1075 if kv, _ := e.(*ast.KeyValueExpr); kv != nil { 1076 check.error(kv.Pos(), "mixture of field:value and value elements in struct literal") 1077 continue 1078 } 1079 check.expr(x, e) 1080 if i >= len(fields) { 1081 check.error(x.pos(), "too many values in struct literal") 1082 break // cannot continue 1083 } 1084 // i < len(fields) 1085 fld := fields[i] 1086 if !fld.Exported() && fld.pkg != check.pkg { 1087 check.errorf(x.pos(), "implicit assignment to unexported field %s in %s literal", fld.name, typ) 1088 continue 1089 } 1090 etyp := fld.typ 1091 if !check.assignment(x, etyp) { 1092 if x.mode != invalid { 1093 check.errorf(x.pos(), "cannot use %s as %s value in struct literal", x, etyp) 1094 } 1095 continue 1096 } 1097 } 1098 if len(e.Elts) < len(fields) { 1099 check.error(e.Rbrace, "too few values in struct literal") 1100 // ok to continue 1101 } 1102 } 1103 1104 case *Array: 1105 n := check.indexedElts(e.Elts, utyp.elem, utyp.len) 1106 // if we have an "open" [...]T array, set the length now that we know it 1107 if openArray { 1108 utyp.len = n 1109 } 1110 1111 case *Slice: 1112 check.indexedElts(e.Elts, utyp.elem, -1) 1113 1114 case *Map: 1115 visited := make(map[interface{}][]Type, len(e.Elts)) 1116 for _, e := range e.Elts { 1117 kv, _ := e.(*ast.KeyValueExpr) 1118 if kv == nil { 1119 check.error(e.Pos(), "missing key in map literal") 1120 continue 1121 } 1122 check.exprWithHint(x, kv.Key, utyp.key) 1123 if !check.assignment(x, utyp.key) { 1124 if x.mode != invalid { 1125 check.errorf(x.pos(), "cannot use %s as %s key in map literal", x, utyp.key) 1126 } 1127 continue 1128 } 1129 if x.mode == constant_ { 1130 duplicate := false 1131 // if the key is of interface type, the type is also significant when checking for duplicates 1132 if _, ok := utyp.key.Underlying().(*Interface); ok { 1133 for _, vtyp := range visited[x.val] { 1134 if Identical(vtyp, x.typ) { 1135 duplicate = true 1136 break 1137 } 1138 } 1139 visited[x.val] = append(visited[x.val], x.typ) 1140 } else { 1141 _, duplicate = visited[x.val] 1142 visited[x.val] = nil 1143 } 1144 if duplicate { 1145 check.errorf(x.pos(), "duplicate key %s in map literal", x.val) 1146 continue 1147 } 1148 } 1149 check.exprWithHint(x, kv.Value, utyp.elem) 1150 if !check.assignment(x, utyp.elem) { 1151 if x.mode != invalid { 1152 check.errorf(x.pos(), "cannot use %s as %s value in map literal", x, utyp.elem) 1153 } 1154 continue 1155 } 1156 } 1157 1158 default: 1159 // if utyp is invalid, an error was reported before 1160 if utyp != Typ[Invalid] { 1161 check.errorf(e.Pos(), "invalid composite literal type %s", typ) 1162 goto Error 1163 } 1164 } 1165 1166 x.mode = value 1167 x.typ = typ 1168 1169 case *ast.ParenExpr: 1170 kind := check.rawExpr(x, e.X, nil) 1171 x.expr = e 1172 return kind 1173 1174 case *ast.SelectorExpr: 1175 check.selector(x, e) 1176 1177 case *ast.IndexExpr: 1178 check.expr(x, e.X) 1179 if x.mode == invalid { 1180 goto Error 1181 } 1182 1183 valid := false 1184 length := int64(-1) // valid if >= 0 1185 switch typ := x.typ.Underlying().(type) { 1186 case *Basic: 1187 if isString(typ) { 1188 valid = true 1189 if x.mode == constant_ { 1190 length = int64(len(constant.StringVal(x.val))) 1191 } 1192 // an indexed string always yields a byte value 1193 // (not a constant) even if the string and the 1194 // index are constant 1195 x.mode = value 1196 x.typ = universeByte // use 'byte' name 1197 } 1198 1199 case *Array: 1200 valid = true 1201 length = typ.len 1202 if x.mode != variable { 1203 x.mode = value 1204 } 1205 x.typ = typ.elem 1206 1207 case *Pointer: 1208 if typ, _ := typ.base.Underlying().(*Array); typ != nil { 1209 valid = true 1210 length = typ.len 1211 x.mode = variable 1212 x.typ = typ.elem 1213 } 1214 1215 case *Slice: 1216 valid = true 1217 x.mode = variable 1218 x.typ = typ.elem 1219 1220 case *Map: 1221 var key operand 1222 check.expr(&key, e.Index) 1223 if !check.assignment(&key, typ.key) { 1224 if key.mode != invalid { 1225 check.invalidOp(key.pos(), "cannot use %s as map index of type %s", &key, typ.key) 1226 } 1227 goto Error 1228 } 1229 x.mode = mapindex 1230 x.typ = typ.elem 1231 x.expr = e 1232 return expression 1233 } 1234 1235 if !valid { 1236 check.invalidOp(x.pos(), "cannot index %s", x) 1237 goto Error 1238 } 1239 1240 if e.Index == nil { 1241 check.invalidAST(e.Pos(), "missing index for %s", x) 1242 goto Error 1243 } 1244 1245 check.index(e.Index, length) 1246 // ok to continue 1247 1248 case *ast.SliceExpr: 1249 check.expr(x, e.X) 1250 if x.mode == invalid { 1251 goto Error 1252 } 1253 1254 valid := false 1255 length := int64(-1) // valid if >= 0 1256 switch typ := x.typ.Underlying().(type) { 1257 case *Basic: 1258 if isString(typ) { 1259 if e.Slice3 { 1260 check.invalidOp(x.pos(), "3-index slice of string") 1261 goto Error 1262 } 1263 valid = true 1264 if x.mode == constant_ { 1265 length = int64(len(constant.StringVal(x.val))) 1266 } 1267 // spec: "For untyped string operands the result 1268 // is a non-constant value of type string." 1269 if typ.kind == UntypedString { 1270 x.typ = Typ[String] 1271 } 1272 } 1273 1274 case *Array: 1275 valid = true 1276 length = typ.len 1277 if x.mode != variable { 1278 check.invalidOp(x.pos(), "cannot slice %s (value not addressable)", x) 1279 goto Error 1280 } 1281 x.typ = &Slice{elem: typ.elem} 1282 1283 case *Pointer: 1284 if typ, _ := typ.base.Underlying().(*Array); typ != nil { 1285 valid = true 1286 length = typ.len 1287 x.typ = &Slice{elem: typ.elem} 1288 } 1289 1290 case *Slice: 1291 valid = true 1292 // x.typ doesn't change 1293 } 1294 1295 if !valid { 1296 check.invalidOp(x.pos(), "cannot slice %s", x) 1297 goto Error 1298 } 1299 1300 x.mode = value 1301 1302 // spec: "Only the first index may be omitted; it defaults to 0." 1303 if e.Slice3 && (e.High == nil || e.Max == nil) { 1304 check.error(e.Rbrack, "2nd and 3rd index required in 3-index slice") 1305 goto Error 1306 } 1307 1308 // check indices 1309 var ind [3]int64 1310 for i, expr := range []ast.Expr{e.Low, e.High, e.Max} { 1311 x := int64(-1) 1312 switch { 1313 case expr != nil: 1314 // The "capacity" is only known statically for strings, arrays, 1315 // and pointers to arrays, and it is the same as the length for 1316 // those types. 1317 max := int64(-1) 1318 if length >= 0 { 1319 max = length + 1 1320 } 1321 if t, ok := check.index(expr, max); ok && t >= 0 { 1322 x = t 1323 } 1324 case i == 0: 1325 // default is 0 for the first index 1326 x = 0 1327 case length >= 0: 1328 // default is length (== capacity) otherwise 1329 x = length 1330 } 1331 ind[i] = x 1332 } 1333 1334 // constant indices must be in range 1335 // (check.index already checks that existing indices >= 0) 1336 L: 1337 for i, x := range ind[:len(ind)-1] { 1338 if x > 0 { 1339 for _, y := range ind[i+1:] { 1340 if y >= 0 && x > y { 1341 check.errorf(e.Rbrack, "invalid slice indices: %d > %d", x, y) 1342 break L // only report one error, ok to continue 1343 } 1344 } 1345 } 1346 } 1347 1348 case *ast.TypeAssertExpr: 1349 check.expr(x, e.X) 1350 if x.mode == invalid { 1351 goto Error 1352 } 1353 xtyp, _ := x.typ.Underlying().(*Interface) 1354 if xtyp == nil { 1355 check.invalidOp(x.pos(), "%s is not an interface", x) 1356 goto Error 1357 } 1358 // x.(type) expressions are handled explicitly in type switches 1359 if e.Type == nil { 1360 check.invalidAST(e.Pos(), "use of .(type) outside type switch") 1361 goto Error 1362 } 1363 T := check.typ(e.Type) 1364 if T == Typ[Invalid] { 1365 goto Error 1366 } 1367 check.typeAssertion(x.pos(), x, xtyp, T) 1368 x.mode = commaok 1369 x.typ = T 1370 1371 case *ast.CallExpr: 1372 return check.call(x, e) 1373 1374 case *ast.StarExpr: 1375 check.exprOrType(x, e.X) 1376 switch x.mode { 1377 case invalid: 1378 goto Error 1379 case typexpr: 1380 x.typ = &Pointer{base: x.typ} 1381 default: 1382 if typ, ok := x.typ.Underlying().(*Pointer); ok { 1383 x.mode = variable 1384 x.typ = typ.base 1385 } else { 1386 check.invalidOp(x.pos(), "cannot indirect %s", x) 1387 goto Error 1388 } 1389 } 1390 1391 case *ast.UnaryExpr: 1392 check.expr(x, e.X) 1393 if x.mode == invalid { 1394 goto Error 1395 } 1396 check.unary(x, e, e.Op) 1397 if x.mode == invalid { 1398 goto Error 1399 } 1400 if e.Op == token.ARROW { 1401 x.expr = e 1402 return statement // receive operations may appear in statement context 1403 } 1404 1405 case *ast.BinaryExpr: 1406 check.binary(x, e, e.X, e.Y, e.Op) 1407 if x.mode == invalid { 1408 goto Error 1409 } 1410 1411 case *ast.KeyValueExpr: 1412 // key:value expressions are handled in composite literals 1413 check.invalidAST(e.Pos(), "no key:value expected") 1414 goto Error 1415 1416 case *ast.ArrayType, *ast.StructType, *ast.FuncType, 1417 *ast.InterfaceType, *ast.MapType, *ast.ChanType: 1418 x.mode = typexpr 1419 x.typ = check.typ(e) 1420 // Note: rawExpr (caller of exprInternal) will call check.recordTypeAndValue 1421 // even though check.typ has already called it. This is fine as both 1422 // times the same expression and type are recorded. It is also not a 1423 // performance issue because we only reach here for composite literal 1424 // types, which are comparatively rare. 1425 1426 default: 1427 panic(fmt.Sprintf("%s: unknown expression type %T", check.fset.Position(e.Pos()), e)) 1428 } 1429 1430 // everything went well 1431 x.expr = e 1432 return expression 1433 1434 Error: 1435 x.mode = invalid 1436 x.expr = e 1437 return statement // avoid follow-up errors 1438 } 1439 1440 // typeAssertion checks that x.(T) is legal; xtyp must be the type of x. 1441 func (check *Checker) typeAssertion(pos token.Pos, x *operand, xtyp *Interface, T Type) { 1442 method, wrongType := assertableTo(xtyp, T) 1443 if method == nil { 1444 return 1445 } 1446 1447 var msg string 1448 if wrongType { 1449 msg = "wrong type for method" 1450 } else { 1451 msg = "missing method" 1452 } 1453 check.errorf(pos, "%s cannot have dynamic type %s (%s %s)", x, T, msg, method.name) 1454 } 1455 1456 // expr typechecks expression e and initializes x with the expression value. 1457 // If an error occurred, x.mode is set to invalid. 1458 // 1459 func (check *Checker) expr(x *operand, e ast.Expr) { 1460 check.rawExpr(x, e, nil) 1461 var msg string 1462 switch x.mode { 1463 default: 1464 return 1465 case novalue: 1466 msg = "used as value" 1467 case builtin: 1468 msg = "must be called" 1469 case typexpr: 1470 msg = "is not an expression" 1471 } 1472 check.errorf(x.pos(), "%s %s", x, msg) 1473 x.mode = invalid 1474 } 1475 1476 // exprWithHint typechecks expression e and initializes x with the expression value; 1477 // hint is the type of a composite literal element. 1478 // If an error occurred, x.mode is set to invalid. 1479 // 1480 func (check *Checker) exprWithHint(x *operand, e ast.Expr, hint Type) { 1481 assert(hint != nil) 1482 check.rawExpr(x, e, hint) 1483 var msg string 1484 switch x.mode { 1485 default: 1486 return 1487 case novalue: 1488 msg = "used as value" 1489 case builtin: 1490 msg = "must be called" 1491 case typexpr: 1492 msg = "is not an expression" 1493 } 1494 check.errorf(x.pos(), "%s %s", x, msg) 1495 x.mode = invalid 1496 } 1497 1498 // exprOrType typechecks expression or type e and initializes x with the expression value or type. 1499 // If an error occurred, x.mode is set to invalid. 1500 // 1501 func (check *Checker) exprOrType(x *operand, e ast.Expr) { 1502 check.rawExpr(x, e, nil) 1503 if x.mode == novalue { 1504 check.errorf(x.pos(), "%s used as value or type", x) 1505 x.mode = invalid 1506 } 1507 }