github.com/aloncn/graphics-go@v0.0.1/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 stupidShift = 1023 - 1 + 52 // so we can express smallestFloat64 664 s, ok := constant.Uint64Val(yval) 665 if !ok || s > stupidShift { 666 check.invalidOp(y.pos(), "stupid 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 if openArray { 1111 utyp.len = n 1112 } 1113 1114 case *Slice: 1115 check.indexedElts(e.Elts, utyp.elem, -1) 1116 1117 case *Map: 1118 visited := make(map[interface{}][]Type, len(e.Elts)) 1119 for _, e := range e.Elts { 1120 kv, _ := e.(*ast.KeyValueExpr) 1121 if kv == nil { 1122 check.error(e.Pos(), "missing key in map literal") 1123 continue 1124 } 1125 check.exprWithHint(x, kv.Key, utyp.key) 1126 check.assignment(x, utyp.key, "map literal") 1127 if x.mode == invalid { 1128 continue 1129 } 1130 if x.mode == constant_ { 1131 duplicate := false 1132 // if the key is of interface type, the type is also significant when checking for duplicates 1133 if _, ok := utyp.key.Underlying().(*Interface); ok { 1134 for _, vtyp := range visited[x.val] { 1135 if Identical(vtyp, x.typ) { 1136 duplicate = true 1137 break 1138 } 1139 } 1140 visited[x.val] = append(visited[x.val], x.typ) 1141 } else { 1142 _, duplicate = visited[x.val] 1143 visited[x.val] = nil 1144 } 1145 if duplicate { 1146 check.errorf(x.pos(), "duplicate key %s in map literal", x.val) 1147 continue 1148 } 1149 } 1150 check.exprWithHint(x, kv.Value, utyp.elem) 1151 check.assignment(x, utyp.elem, "map literal") 1152 } 1153 1154 default: 1155 // if utyp is invalid, an error was reported before 1156 if utyp != Typ[Invalid] { 1157 check.errorf(e.Pos(), "invalid composite literal type %s", typ) 1158 goto Error 1159 } 1160 } 1161 1162 x.mode = value 1163 x.typ = typ 1164 1165 case *ast.ParenExpr: 1166 kind := check.rawExpr(x, e.X, nil) 1167 x.expr = e 1168 return kind 1169 1170 case *ast.SelectorExpr: 1171 check.selector(x, e) 1172 1173 case *ast.IndexExpr: 1174 check.expr(x, e.X) 1175 if x.mode == invalid { 1176 goto Error 1177 } 1178 1179 valid := false 1180 length := int64(-1) // valid if >= 0 1181 switch typ := x.typ.Underlying().(type) { 1182 case *Basic: 1183 if isString(typ) { 1184 valid = true 1185 if x.mode == constant_ { 1186 length = int64(len(constant.StringVal(x.val))) 1187 } 1188 // an indexed string always yields a byte value 1189 // (not a constant) even if the string and the 1190 // index are constant 1191 x.mode = value 1192 x.typ = universeByte // use 'byte' name 1193 } 1194 1195 case *Array: 1196 valid = true 1197 length = typ.len 1198 if x.mode != variable { 1199 x.mode = value 1200 } 1201 x.typ = typ.elem 1202 1203 case *Pointer: 1204 if typ, _ := typ.base.Underlying().(*Array); typ != nil { 1205 valid = true 1206 length = typ.len 1207 x.mode = variable 1208 x.typ = typ.elem 1209 } 1210 1211 case *Slice: 1212 valid = true 1213 x.mode = variable 1214 x.typ = typ.elem 1215 1216 case *Map: 1217 var key operand 1218 check.expr(&key, e.Index) 1219 check.assignment(&key, typ.key, "map index") 1220 if x.mode == invalid { 1221 goto Error 1222 } 1223 x.mode = mapindex 1224 x.typ = typ.elem 1225 x.expr = e 1226 return expression 1227 } 1228 1229 if !valid { 1230 check.invalidOp(x.pos(), "cannot index %s", x) 1231 goto Error 1232 } 1233 1234 if e.Index == nil { 1235 check.invalidAST(e.Pos(), "missing index for %s", x) 1236 goto Error 1237 } 1238 1239 check.index(e.Index, length) 1240 // ok to continue 1241 1242 case *ast.SliceExpr: 1243 check.expr(x, e.X) 1244 if x.mode == invalid { 1245 goto Error 1246 } 1247 1248 valid := false 1249 length := int64(-1) // valid if >= 0 1250 switch typ := x.typ.Underlying().(type) { 1251 case *Basic: 1252 if isString(typ) { 1253 if e.Slice3 { 1254 check.invalidOp(x.pos(), "3-index slice of string") 1255 goto Error 1256 } 1257 valid = true 1258 if x.mode == constant_ { 1259 length = int64(len(constant.StringVal(x.val))) 1260 } 1261 // spec: "For untyped string operands the result 1262 // is a non-constant value of type string." 1263 if typ.kind == UntypedString { 1264 x.typ = Typ[String] 1265 } 1266 } 1267 1268 case *Array: 1269 valid = true 1270 length = typ.len 1271 if x.mode != variable { 1272 check.invalidOp(x.pos(), "cannot slice %s (value not addressable)", x) 1273 goto Error 1274 } 1275 x.typ = &Slice{elem: typ.elem} 1276 1277 case *Pointer: 1278 if typ, _ := typ.base.Underlying().(*Array); typ != nil { 1279 valid = true 1280 length = typ.len 1281 x.typ = &Slice{elem: typ.elem} 1282 } 1283 1284 case *Slice: 1285 valid = true 1286 // x.typ doesn't change 1287 } 1288 1289 if !valid { 1290 check.invalidOp(x.pos(), "cannot slice %s", x) 1291 goto Error 1292 } 1293 1294 x.mode = value 1295 1296 // spec: "Only the first index may be omitted; it defaults to 0." 1297 if e.Slice3 && (e.High == nil || e.Max == nil) { 1298 check.error(e.Rbrack, "2nd and 3rd index required in 3-index slice") 1299 goto Error 1300 } 1301 1302 // check indices 1303 var ind [3]int64 1304 for i, expr := range []ast.Expr{e.Low, e.High, e.Max} { 1305 x := int64(-1) 1306 switch { 1307 case expr != nil: 1308 // The "capacity" is only known statically for strings, arrays, 1309 // and pointers to arrays, and it is the same as the length for 1310 // those types. 1311 max := int64(-1) 1312 if length >= 0 { 1313 max = length + 1 1314 } 1315 if t, ok := check.index(expr, max); ok && t >= 0 { 1316 x = t 1317 } 1318 case i == 0: 1319 // default is 0 for the first index 1320 x = 0 1321 case length >= 0: 1322 // default is length (== capacity) otherwise 1323 x = length 1324 } 1325 ind[i] = x 1326 } 1327 1328 // constant indices must be in range 1329 // (check.index already checks that existing indices >= 0) 1330 L: 1331 for i, x := range ind[:len(ind)-1] { 1332 if x > 0 { 1333 for _, y := range ind[i+1:] { 1334 if y >= 0 && x > y { 1335 check.errorf(e.Rbrack, "invalid slice indices: %d > %d", x, y) 1336 break L // only report one error, ok to continue 1337 } 1338 } 1339 } 1340 } 1341 1342 case *ast.TypeAssertExpr: 1343 check.expr(x, e.X) 1344 if x.mode == invalid { 1345 goto Error 1346 } 1347 xtyp, _ := x.typ.Underlying().(*Interface) 1348 if xtyp == nil { 1349 check.invalidOp(x.pos(), "%s is not an interface", x) 1350 goto Error 1351 } 1352 // x.(type) expressions are handled explicitly in type switches 1353 if e.Type == nil { 1354 check.invalidAST(e.Pos(), "use of .(type) outside type switch") 1355 goto Error 1356 } 1357 T := check.typ(e.Type) 1358 if T == Typ[Invalid] { 1359 goto Error 1360 } 1361 check.typeAssertion(x.pos(), x, xtyp, T) 1362 x.mode = commaok 1363 x.typ = T 1364 1365 case *ast.CallExpr: 1366 return check.call(x, e) 1367 1368 case *ast.StarExpr: 1369 check.exprOrType(x, e.X) 1370 switch x.mode { 1371 case invalid: 1372 goto Error 1373 case typexpr: 1374 x.typ = &Pointer{base: x.typ} 1375 default: 1376 if typ, ok := x.typ.Underlying().(*Pointer); ok { 1377 x.mode = variable 1378 x.typ = typ.base 1379 } else { 1380 check.invalidOp(x.pos(), "cannot indirect %s", x) 1381 goto Error 1382 } 1383 } 1384 1385 case *ast.UnaryExpr: 1386 check.expr(x, e.X) 1387 if x.mode == invalid { 1388 goto Error 1389 } 1390 check.unary(x, e, e.Op) 1391 if x.mode == invalid { 1392 goto Error 1393 } 1394 if e.Op == token.ARROW { 1395 x.expr = e 1396 return statement // receive operations may appear in statement context 1397 } 1398 1399 case *ast.BinaryExpr: 1400 check.binary(x, e, e.X, e.Y, e.Op) 1401 if x.mode == invalid { 1402 goto Error 1403 } 1404 1405 case *ast.KeyValueExpr: 1406 // key:value expressions are handled in composite literals 1407 check.invalidAST(e.Pos(), "no key:value expected") 1408 goto Error 1409 1410 case *ast.ArrayType, *ast.StructType, *ast.FuncType, 1411 *ast.InterfaceType, *ast.MapType, *ast.ChanType: 1412 x.mode = typexpr 1413 x.typ = check.typ(e) 1414 // Note: rawExpr (caller of exprInternal) will call check.recordTypeAndValue 1415 // even though check.typ has already called it. This is fine as both 1416 // times the same expression and type are recorded. It is also not a 1417 // performance issue because we only reach here for composite literal 1418 // types, which are comparatively rare. 1419 1420 default: 1421 panic(fmt.Sprintf("%s: unknown expression type %T", check.fset.Position(e.Pos()), e)) 1422 } 1423 1424 // everything went well 1425 x.expr = e 1426 return expression 1427 1428 Error: 1429 x.mode = invalid 1430 x.expr = e 1431 return statement // avoid follow-up errors 1432 } 1433 1434 // typeAssertion checks that x.(T) is legal; xtyp must be the type of x. 1435 func (check *Checker) typeAssertion(pos token.Pos, x *operand, xtyp *Interface, T Type) { 1436 method, wrongType := assertableTo(xtyp, T) 1437 if method == nil { 1438 return 1439 } 1440 1441 var msg string 1442 if wrongType { 1443 msg = "wrong type for method" 1444 } else { 1445 msg = "missing method" 1446 } 1447 check.errorf(pos, "%s cannot have dynamic type %s (%s %s)", x, T, msg, method.name) 1448 } 1449 1450 func (check *Checker) singleValue(x *operand) { 1451 if x.mode == value { 1452 // tuple types are never named - no need for underlying type below 1453 if t, ok := x.typ.(*Tuple); ok { 1454 assert(t.Len() != 1) 1455 check.errorf(x.pos(), "%d-valued %s where single value is expected", t.Len(), x) 1456 x.mode = invalid 1457 } 1458 } 1459 } 1460 1461 // expr typechecks expression e and initializes x with the expression value. 1462 // The result must be a single value. 1463 // If an error occurred, x.mode is set to invalid. 1464 // 1465 func (check *Checker) expr(x *operand, e ast.Expr) { 1466 check.multiExpr(x, e) 1467 check.singleValue(x) 1468 } 1469 1470 // multiExpr is like expr but the result may be a multi-value. 1471 func (check *Checker) multiExpr(x *operand, e ast.Expr) { 1472 check.rawExpr(x, e, nil) 1473 var msg string 1474 switch x.mode { 1475 default: 1476 return 1477 case novalue: 1478 msg = "%s used as value" 1479 case builtin: 1480 msg = "%s must be called" 1481 case typexpr: 1482 msg = "%s is not an expression" 1483 } 1484 check.errorf(x.pos(), msg, x) 1485 x.mode = invalid 1486 } 1487 1488 // exprWithHint typechecks expression e and initializes x with the expression value; 1489 // hint is the type of a composite literal element. 1490 // If an error occurred, x.mode is set to invalid. 1491 // 1492 func (check *Checker) exprWithHint(x *operand, e ast.Expr, hint Type) { 1493 assert(hint != nil) 1494 check.rawExpr(x, e, hint) 1495 check.singleValue(x) 1496 var msg string 1497 switch x.mode { 1498 default: 1499 return 1500 case novalue: 1501 msg = "%s used as value" 1502 case builtin: 1503 msg = "%s must be called" 1504 case typexpr: 1505 msg = "%s is not an expression" 1506 } 1507 check.errorf(x.pos(), msg, x) 1508 x.mode = invalid 1509 } 1510 1511 // exprOrType typechecks expression or type e and initializes x with the expression value or type. 1512 // If an error occurred, x.mode is set to invalid. 1513 // 1514 func (check *Checker) exprOrType(x *operand, e ast.Expr) { 1515 check.rawExpr(x, e, nil) 1516 check.singleValue(x) 1517 if x.mode == novalue { 1518 check.errorf(x.pos(), "%s used as value or type", x) 1519 x.mode = invalid 1520 } 1521 }