github.com/sbinet/go@v0.0.0-20160827155028-54d7de7dd62b/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 = defaultType(x.typ) 545 } 546 case *Pointer, *Signature, *Slice, *Map, *Chan: 547 if !x.isNil() { 548 goto Error 549 } 550 // keep nil untyped - see comment for interfaces, above 551 target = Typ[UntypedNil] 552 default: 553 goto Error 554 } 555 556 x.typ = target 557 check.updateExprType(x.expr, target, true) // UntypedNils are final 558 return 559 560 Error: 561 check.errorf(x.pos(), "cannot convert %s to %s", x, target) 562 x.mode = invalid 563 } 564 565 func (check *Checker) comparison(x, y *operand, op token.Token) { 566 // spec: "In any comparison, the first operand must be assignable 567 // to the type of the second operand, or vice versa." 568 err := "" 569 if x.assignableTo(check.conf, y.typ, 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, defaultType(x.typ), true) 609 check.updateExprType(y.expr, defaultType(y.typ), true) 610 } 611 612 // spec: "Comparison operators compare two operands and yield 613 // an untyped boolean value." 614 x.typ = Typ[UntypedBool] 615 } 616 617 func (check *Checker) shift(x, y *operand, 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 typ := hint 1019 openArray := false 1020 if e.Type != nil { 1021 // [...]T array types may only appear with composite literals. 1022 // Check for them here so we don't have to handle ... in general. 1023 typ = nil 1024 if atyp, _ := e.Type.(*ast.ArrayType); atyp != nil && atyp.Len != nil { 1025 if ellip, _ := atyp.Len.(*ast.Ellipsis); ellip != nil && ellip.Elt == nil { 1026 // We have an "open" [...]T array type. 1027 // Create a new ArrayType with unknown length (-1) 1028 // and finish setting it up after analyzing the literal. 1029 typ = &Array{len: -1, elem: check.typ(atyp.Elt)} 1030 openArray = true 1031 } 1032 } 1033 if typ == nil { 1034 typ = check.typ(e.Type) 1035 } 1036 } 1037 if typ == nil { 1038 // TODO(gri) provide better error messages depending on context 1039 check.error(e.Pos(), "missing type in composite literal") 1040 goto Error 1041 } 1042 1043 switch typ, _ := deref(typ); utyp := typ.Underlying().(type) { 1044 case *Struct: 1045 if len(e.Elts) == 0 { 1046 break 1047 } 1048 fields := utyp.fields 1049 if _, ok := e.Elts[0].(*ast.KeyValueExpr); ok { 1050 // all elements must have keys 1051 visited := make([]bool, len(fields)) 1052 for _, e := range e.Elts { 1053 kv, _ := e.(*ast.KeyValueExpr) 1054 if kv == nil { 1055 check.error(e.Pos(), "mixture of field:value and value elements in struct literal") 1056 continue 1057 } 1058 key, _ := kv.Key.(*ast.Ident) 1059 if key == nil { 1060 check.errorf(kv.Pos(), "invalid field name %s in struct literal", kv.Key) 1061 continue 1062 } 1063 i := fieldIndex(utyp.fields, check.pkg, key.Name) 1064 if i < 0 { 1065 check.errorf(kv.Pos(), "unknown field %s in struct literal", key.Name) 1066 continue 1067 } 1068 fld := fields[i] 1069 check.recordUse(key, fld) 1070 // 0 <= i < len(fields) 1071 if visited[i] { 1072 check.errorf(kv.Pos(), "duplicate field name %s in struct literal", key.Name) 1073 continue 1074 } 1075 visited[i] = true 1076 check.expr(x, kv.Value) 1077 etyp := fld.typ 1078 check.assignment(x, etyp, "struct literal") 1079 } 1080 } else { 1081 // no element must have a key 1082 for i, e := range e.Elts { 1083 if kv, _ := e.(*ast.KeyValueExpr); kv != nil { 1084 check.error(kv.Pos(), "mixture of field:value and value elements in struct literal") 1085 continue 1086 } 1087 check.expr(x, e) 1088 if i >= len(fields) { 1089 check.error(x.pos(), "too many values in struct literal") 1090 break // cannot continue 1091 } 1092 // i < len(fields) 1093 fld := fields[i] 1094 if !fld.Exported() && fld.pkg != check.pkg { 1095 check.errorf(x.pos(), "implicit assignment to unexported field %s in %s literal", fld.name, typ) 1096 continue 1097 } 1098 etyp := fld.typ 1099 check.assignment(x, etyp, "struct literal") 1100 } 1101 if len(e.Elts) < len(fields) { 1102 check.error(e.Rbrace, "too few values in struct literal") 1103 // ok to continue 1104 } 1105 } 1106 1107 case *Array: 1108 n := check.indexedElts(e.Elts, utyp.elem, utyp.len) 1109 // If we have an "open" [...]T array, set the length now that we know it 1110 // and record the type for [...] (usually done by check.typExpr which is 1111 // not called for [...]). 1112 if openArray { 1113 utyp.len = n 1114 check.recordTypeAndValue(e.Type, typexpr, utyp, nil) 1115 } 1116 1117 case *Slice: 1118 check.indexedElts(e.Elts, utyp.elem, -1) 1119 1120 case *Map: 1121 visited := make(map[interface{}][]Type, len(e.Elts)) 1122 for _, e := range e.Elts { 1123 kv, _ := e.(*ast.KeyValueExpr) 1124 if kv == nil { 1125 check.error(e.Pos(), "missing key in map literal") 1126 continue 1127 } 1128 check.exprWithHint(x, kv.Key, utyp.key) 1129 check.assignment(x, utyp.key, "map literal") 1130 if x.mode == invalid { 1131 continue 1132 } 1133 if x.mode == constant_ { 1134 duplicate := false 1135 // if the key is of interface type, the type is also significant when checking for duplicates 1136 if _, ok := utyp.key.Underlying().(*Interface); ok { 1137 for _, vtyp := range visited[x.val] { 1138 if Identical(vtyp, x.typ) { 1139 duplicate = true 1140 break 1141 } 1142 } 1143 visited[x.val] = append(visited[x.val], x.typ) 1144 } else { 1145 _, duplicate = visited[x.val] 1146 visited[x.val] = nil 1147 } 1148 if duplicate { 1149 check.errorf(x.pos(), "duplicate key %s in map literal", x.val) 1150 continue 1151 } 1152 } 1153 check.exprWithHint(x, kv.Value, utyp.elem) 1154 check.assignment(x, utyp.elem, "map literal") 1155 } 1156 1157 default: 1158 // if utyp is invalid, an error was reported before 1159 if utyp != Typ[Invalid] { 1160 check.errorf(e.Pos(), "invalid composite literal type %s", typ) 1161 goto Error 1162 } 1163 } 1164 1165 x.mode = value 1166 x.typ = typ 1167 1168 case *ast.ParenExpr: 1169 kind := check.rawExpr(x, e.X, nil) 1170 x.expr = e 1171 return kind 1172 1173 case *ast.SelectorExpr: 1174 check.selector(x, e) 1175 1176 case *ast.IndexExpr: 1177 check.expr(x, e.X) 1178 if x.mode == invalid { 1179 goto Error 1180 } 1181 1182 valid := false 1183 length := int64(-1) // valid if >= 0 1184 switch typ := x.typ.Underlying().(type) { 1185 case *Basic: 1186 if isString(typ) { 1187 valid = true 1188 if x.mode == constant_ { 1189 length = int64(len(constant.StringVal(x.val))) 1190 } 1191 // an indexed string always yields a byte value 1192 // (not a constant) even if the string and the 1193 // index are constant 1194 x.mode = value 1195 x.typ = universeByte // use 'byte' name 1196 } 1197 1198 case *Array: 1199 valid = true 1200 length = typ.len 1201 if x.mode != variable { 1202 x.mode = value 1203 } 1204 x.typ = typ.elem 1205 1206 case *Pointer: 1207 if typ, _ := typ.base.Underlying().(*Array); typ != nil { 1208 valid = true 1209 length = typ.len 1210 x.mode = variable 1211 x.typ = typ.elem 1212 } 1213 1214 case *Slice: 1215 valid = true 1216 x.mode = variable 1217 x.typ = typ.elem 1218 1219 case *Map: 1220 var key operand 1221 check.expr(&key, e.Index) 1222 check.assignment(&key, typ.key, "map index") 1223 if x.mode == invalid { 1224 goto Error 1225 } 1226 x.mode = mapindex 1227 x.typ = typ.elem 1228 x.expr = e 1229 return expression 1230 } 1231 1232 if !valid { 1233 check.invalidOp(x.pos(), "cannot index %s", x) 1234 goto Error 1235 } 1236 1237 if e.Index == nil { 1238 check.invalidAST(e.Pos(), "missing index for %s", x) 1239 goto Error 1240 } 1241 1242 check.index(e.Index, length) 1243 // ok to continue 1244 1245 case *ast.SliceExpr: 1246 check.expr(x, e.X) 1247 if x.mode == invalid { 1248 goto Error 1249 } 1250 1251 valid := false 1252 length := int64(-1) // valid if >= 0 1253 switch typ := x.typ.Underlying().(type) { 1254 case *Basic: 1255 if isString(typ) { 1256 if e.Slice3 { 1257 check.invalidOp(x.pos(), "3-index slice of string") 1258 goto Error 1259 } 1260 valid = true 1261 if x.mode == constant_ { 1262 length = int64(len(constant.StringVal(x.val))) 1263 } 1264 // spec: "For untyped string operands the result 1265 // is a non-constant value of type string." 1266 if typ.kind == UntypedString { 1267 x.typ = Typ[String] 1268 } 1269 } 1270 1271 case *Array: 1272 valid = true 1273 length = typ.len 1274 if x.mode != variable { 1275 check.invalidOp(x.pos(), "cannot slice %s (value not addressable)", x) 1276 goto Error 1277 } 1278 x.typ = &Slice{elem: typ.elem} 1279 1280 case *Pointer: 1281 if typ, _ := typ.base.Underlying().(*Array); typ != nil { 1282 valid = true 1283 length = typ.len 1284 x.typ = &Slice{elem: typ.elem} 1285 } 1286 1287 case *Slice: 1288 valid = true 1289 // x.typ doesn't change 1290 } 1291 1292 if !valid { 1293 check.invalidOp(x.pos(), "cannot slice %s", x) 1294 goto Error 1295 } 1296 1297 x.mode = value 1298 1299 // spec: "Only the first index may be omitted; it defaults to 0." 1300 if e.Slice3 && (e.High == nil || e.Max == nil) { 1301 check.error(e.Rbrack, "2nd and 3rd index required in 3-index slice") 1302 goto Error 1303 } 1304 1305 // check indices 1306 var ind [3]int64 1307 for i, expr := range []ast.Expr{e.Low, e.High, e.Max} { 1308 x := int64(-1) 1309 switch { 1310 case expr != nil: 1311 // The "capacity" is only known statically for strings, arrays, 1312 // and pointers to arrays, and it is the same as the length for 1313 // those types. 1314 max := int64(-1) 1315 if length >= 0 { 1316 max = length + 1 1317 } 1318 if t, ok := check.index(expr, max); ok && t >= 0 { 1319 x = t 1320 } 1321 case i == 0: 1322 // default is 0 for the first index 1323 x = 0 1324 case length >= 0: 1325 // default is length (== capacity) otherwise 1326 x = length 1327 } 1328 ind[i] = x 1329 } 1330 1331 // constant indices must be in range 1332 // (check.index already checks that existing indices >= 0) 1333 L: 1334 for i, x := range ind[:len(ind)-1] { 1335 if x > 0 { 1336 for _, y := range ind[i+1:] { 1337 if y >= 0 && x > y { 1338 check.errorf(e.Rbrack, "invalid slice indices: %d > %d", x, y) 1339 break L // only report one error, ok to continue 1340 } 1341 } 1342 } 1343 } 1344 1345 case *ast.TypeAssertExpr: 1346 check.expr(x, e.X) 1347 if x.mode == invalid { 1348 goto Error 1349 } 1350 xtyp, _ := x.typ.Underlying().(*Interface) 1351 if xtyp == nil { 1352 check.invalidOp(x.pos(), "%s is not an interface", x) 1353 goto Error 1354 } 1355 // x.(type) expressions are handled explicitly in type switches 1356 if e.Type == nil { 1357 check.invalidAST(e.Pos(), "use of .(type) outside type switch") 1358 goto Error 1359 } 1360 T := check.typ(e.Type) 1361 if T == Typ[Invalid] { 1362 goto Error 1363 } 1364 check.typeAssertion(x.pos(), x, xtyp, T) 1365 x.mode = commaok 1366 x.typ = T 1367 1368 case *ast.CallExpr: 1369 return check.call(x, e) 1370 1371 case *ast.StarExpr: 1372 check.exprOrType(x, e.X) 1373 switch x.mode { 1374 case invalid: 1375 goto Error 1376 case typexpr: 1377 x.typ = &Pointer{base: x.typ} 1378 default: 1379 if typ, ok := x.typ.Underlying().(*Pointer); ok { 1380 x.mode = variable 1381 x.typ = typ.base 1382 } else { 1383 check.invalidOp(x.pos(), "cannot indirect %s", x) 1384 goto Error 1385 } 1386 } 1387 1388 case *ast.UnaryExpr: 1389 check.expr(x, e.X) 1390 if x.mode == invalid { 1391 goto Error 1392 } 1393 check.unary(x, e, e.Op) 1394 if x.mode == invalid { 1395 goto Error 1396 } 1397 if e.Op == token.ARROW { 1398 x.expr = e 1399 return statement // receive operations may appear in statement context 1400 } 1401 1402 case *ast.BinaryExpr: 1403 check.binary(x, e, e.X, e.Y, e.Op) 1404 if x.mode == invalid { 1405 goto Error 1406 } 1407 1408 case *ast.KeyValueExpr: 1409 // key:value expressions are handled in composite literals 1410 check.invalidAST(e.Pos(), "no key:value expected") 1411 goto Error 1412 1413 case *ast.ArrayType, *ast.StructType, *ast.FuncType, 1414 *ast.InterfaceType, *ast.MapType, *ast.ChanType: 1415 x.mode = typexpr 1416 x.typ = check.typ(e) 1417 // Note: rawExpr (caller of exprInternal) will call check.recordTypeAndValue 1418 // even though check.typ has already called it. This is fine as both 1419 // times the same expression and type are recorded. It is also not a 1420 // performance issue because we only reach here for composite literal 1421 // types, which are comparatively rare. 1422 1423 default: 1424 panic(fmt.Sprintf("%s: unknown expression type %T", check.fset.Position(e.Pos()), e)) 1425 } 1426 1427 // everything went well 1428 x.expr = e 1429 return expression 1430 1431 Error: 1432 x.mode = invalid 1433 x.expr = e 1434 return statement // avoid follow-up errors 1435 } 1436 1437 // typeAssertion checks that x.(T) is legal; xtyp must be the type of x. 1438 func (check *Checker) typeAssertion(pos token.Pos, x *operand, xtyp *Interface, T Type) { 1439 method, wrongType := assertableTo(xtyp, T) 1440 if method == nil { 1441 return 1442 } 1443 1444 var msg string 1445 if wrongType { 1446 msg = "wrong type for method" 1447 } else { 1448 msg = "missing method" 1449 } 1450 check.errorf(pos, "%s cannot have dynamic type %s (%s %s)", x, T, msg, method.name) 1451 } 1452 1453 func (check *Checker) singleValue(x *operand) { 1454 if x.mode == value { 1455 // tuple types are never named - no need for underlying type below 1456 if t, ok := x.typ.(*Tuple); ok { 1457 assert(t.Len() != 1) 1458 check.errorf(x.pos(), "%d-valued %s where single value is expected", t.Len(), x) 1459 x.mode = invalid 1460 } 1461 } 1462 } 1463 1464 // expr typechecks expression e and initializes x with the expression value. 1465 // The result must be a single value. 1466 // If an error occurred, x.mode is set to invalid. 1467 // 1468 func (check *Checker) expr(x *operand, e ast.Expr) { 1469 check.multiExpr(x, e) 1470 check.singleValue(x) 1471 } 1472 1473 // multiExpr is like expr but the result may be a multi-value. 1474 func (check *Checker) multiExpr(x *operand, e ast.Expr) { 1475 check.rawExpr(x, e, nil) 1476 var msg string 1477 switch x.mode { 1478 default: 1479 return 1480 case novalue: 1481 msg = "%s used as value" 1482 case builtin: 1483 msg = "%s must be called" 1484 case typexpr: 1485 msg = "%s is not an expression" 1486 } 1487 check.errorf(x.pos(), msg, x) 1488 x.mode = invalid 1489 } 1490 1491 // exprWithHint typechecks expression e and initializes x with the expression value; 1492 // hint is the type of a composite literal element. 1493 // If an error occurred, x.mode is set to invalid. 1494 // 1495 func (check *Checker) exprWithHint(x *operand, e ast.Expr, hint Type) { 1496 assert(hint != nil) 1497 check.rawExpr(x, e, hint) 1498 check.singleValue(x) 1499 var msg string 1500 switch x.mode { 1501 default: 1502 return 1503 case novalue: 1504 msg = "%s used as value" 1505 case builtin: 1506 msg = "%s must be called" 1507 case typexpr: 1508 msg = "%s is not an expression" 1509 } 1510 check.errorf(x.pos(), msg, x) 1511 x.mode = invalid 1512 } 1513 1514 // exprOrType typechecks expression or type e and initializes x with the expression value or type. 1515 // If an error occurred, x.mode is set to invalid. 1516 // 1517 func (check *Checker) exprOrType(x *operand, e ast.Expr) { 1518 check.rawExpr(x, e, nil) 1519 check.singleValue(x) 1520 if x.mode == novalue { 1521 check.errorf(x.pos(), "%s used as value or type", x) 1522 x.mode = invalid 1523 } 1524 }