github.com/zxy12/golang151_with_comment@v0.0.0-20190507085033-721809559d3c/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 // The lhs expression must be in the untyped map, mark 686 // the entry as lhs shift operand. 687 info, found := check.untyped[x.expr] 688 assert(found) 689 info.isLhs = true 690 check.untyped[x.expr] = info 691 // keep x's type 692 x.mode = value 693 return 694 } 695 } 696 697 // constant rhs must be >= 0 698 if y.mode == constant_ && constant.Sign(y.val) < 0 { 699 check.invalidOp(y.pos(), "shift count %s must not be negative", y) 700 } 701 702 // non-constant shift - lhs must be an integer 703 if !isInteger(x.typ) { 704 check.invalidOp(x.pos(), "shifted operand %s must be integer", x) 705 x.mode = invalid 706 return 707 } 708 709 x.mode = value 710 } 711 712 var binaryOpPredicates = opPredicates{ 713 token.ADD: func(typ Type) bool { return isNumeric(typ) || isString(typ) }, 714 token.SUB: isNumeric, 715 token.MUL: isNumeric, 716 token.QUO: isNumeric, 717 token.REM: isInteger, 718 719 token.AND: isInteger, 720 token.OR: isInteger, 721 token.XOR: isInteger, 722 token.AND_NOT: isInteger, 723 724 token.LAND: isBoolean, 725 token.LOR: isBoolean, 726 } 727 728 // The binary expression e may be nil. It's passed in for better error messages only. 729 func (check *Checker) binary(x *operand, e *ast.BinaryExpr, lhs, rhs ast.Expr, op token.Token) { 730 var y operand 731 732 check.expr(x, lhs) 733 check.expr(&y, rhs) 734 735 if x.mode == invalid { 736 return 737 } 738 if y.mode == invalid { 739 x.mode = invalid 740 x.expr = y.expr 741 return 742 } 743 744 if isShift(op) { 745 check.shift(x, &y, op) 746 return 747 } 748 749 check.convertUntyped(x, y.typ) 750 if x.mode == invalid { 751 return 752 } 753 check.convertUntyped(&y, x.typ) 754 if y.mode == invalid { 755 x.mode = invalid 756 return 757 } 758 759 if isComparison(op) { 760 check.comparison(x, &y, op) 761 return 762 } 763 764 if !Identical(x.typ, y.typ) { 765 // only report an error if we have valid types 766 // (otherwise we had an error reported elsewhere already) 767 if x.typ != Typ[Invalid] && y.typ != Typ[Invalid] { 768 check.invalidOp(x.pos(), "mismatched types %s and %s", x.typ, y.typ) 769 } 770 x.mode = invalid 771 return 772 } 773 774 if !check.op(binaryOpPredicates, x, op) { 775 x.mode = invalid 776 return 777 } 778 779 if (op == token.QUO || op == token.REM) && (x.mode == constant_ || isInteger(x.typ)) && y.mode == constant_ && constant.Sign(y.val) == 0 { 780 check.invalidOp(y.pos(), "division by zero") 781 x.mode = invalid 782 return 783 } 784 785 if x.mode == constant_ && y.mode == constant_ { 786 typ := x.typ.Underlying().(*Basic) 787 // force integer division of integer operands 788 if op == token.QUO && isInteger(typ) { 789 op = token.QUO_ASSIGN 790 } 791 x.val = constant.BinaryOp(x.val, op, y.val) 792 // Typed constants must be representable in 793 // their type after each constant operation. 794 if isTyped(typ) { 795 if e != nil { 796 x.expr = e // for better error message 797 } 798 check.representable(x, typ) 799 } 800 return 801 } 802 803 x.mode = value 804 // x.typ is unchanged 805 } 806 807 // index checks an index expression for validity. 808 // If max >= 0, it is the upper bound for index. 809 // If index is valid and the result i >= 0, then i is the constant value of index. 810 func (check *Checker) index(index ast.Expr, max int64) (i int64, valid bool) { 811 var x operand 812 check.expr(&x, index) 813 if x.mode == invalid { 814 return 815 } 816 817 // an untyped constant must be representable as Int 818 check.convertUntyped(&x, Typ[Int]) 819 if x.mode == invalid { 820 return 821 } 822 823 // the index must be of integer type 824 if !isInteger(x.typ) { 825 check.invalidArg(x.pos(), "index %s must be integer", &x) 826 return 827 } 828 829 // a constant index i must be in bounds 830 if x.mode == constant_ { 831 if constant.Sign(x.val) < 0 { 832 check.invalidArg(x.pos(), "index %s must not be negative", &x) 833 return 834 } 835 i, valid = constant.Int64Val(x.val) 836 if !valid || max >= 0 && i >= max { 837 check.errorf(x.pos(), "index %s is out of bounds", &x) 838 return i, false 839 } 840 // 0 <= i [ && i < max ] 841 return i, true 842 } 843 844 return -1, true 845 } 846 847 // indexElts checks the elements (elts) of an array or slice composite literal 848 // against the literal's element type (typ), and the element indices against 849 // the literal length if known (length >= 0). It returns the length of the 850 // literal (maximum index value + 1). 851 // 852 func (check *Checker) indexedElts(elts []ast.Expr, typ Type, length int64) int64 { 853 visited := make(map[int64]bool, len(elts)) 854 var index, max int64 855 for _, e := range elts { 856 // determine and check index 857 validIndex := false 858 eval := e 859 if kv, _ := e.(*ast.KeyValueExpr); kv != nil { 860 if i, ok := check.index(kv.Key, length); ok { 861 if i >= 0 { 862 index = i 863 validIndex = true 864 } else { 865 check.errorf(e.Pos(), "index %s must be integer constant", kv.Key) 866 } 867 } 868 eval = kv.Value 869 } else if length >= 0 && index >= length { 870 check.errorf(e.Pos(), "index %d is out of bounds (>= %d)", index, length) 871 } else { 872 validIndex = true 873 } 874 875 // if we have a valid index, check for duplicate entries 876 if validIndex { 877 if visited[index] { 878 check.errorf(e.Pos(), "duplicate index %d in array or slice literal", index) 879 } 880 visited[index] = true 881 } 882 index++ 883 if index > max { 884 max = index 885 } 886 887 // check element against composite literal element type 888 var x operand 889 check.exprWithHint(&x, eval, typ) 890 if !check.assignment(&x, typ) && x.mode != invalid { 891 check.errorf(x.pos(), "cannot use %s as %s value in array or slice literal", &x, typ) 892 } 893 } 894 return max 895 } 896 897 // exprKind describes the kind of an expression; the kind 898 // determines if an expression is valid in 'statement context'. 899 type exprKind int 900 901 const ( 902 conversion exprKind = iota 903 expression 904 statement 905 ) 906 907 // rawExpr typechecks expression e and initializes x with the expression 908 // value or type. If an error occurred, x.mode is set to invalid. 909 // If hint != nil, it is the type of a composite literal element. 910 // 911 func (check *Checker) rawExpr(x *operand, e ast.Expr, hint Type) exprKind { 912 if trace { 913 check.trace(e.Pos(), "%s", e) 914 check.indent++ 915 defer func() { 916 check.indent-- 917 check.trace(e.Pos(), "=> %s", x) 918 }() 919 } 920 921 kind := check.exprInternal(x, e, hint) 922 923 // convert x into a user-friendly set of values 924 // TODO(gri) this code can be simplified 925 var typ Type 926 var val constant.Value 927 switch x.mode { 928 case invalid: 929 typ = Typ[Invalid] 930 case novalue: 931 typ = (*Tuple)(nil) 932 case constant_: 933 typ = x.typ 934 val = x.val 935 default: 936 typ = x.typ 937 } 938 assert(x.expr != nil && typ != nil) 939 940 if isUntyped(typ) { 941 // delay type and value recording until we know the type 942 // or until the end of type checking 943 check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val) 944 } else { 945 check.recordTypeAndValue(e, x.mode, typ, val) 946 } 947 948 return kind 949 } 950 951 // exprInternal contains the core of type checking of expressions. 952 // Must only be called by rawExpr. 953 // 954 func (check *Checker) exprInternal(x *operand, e ast.Expr, hint Type) exprKind { 955 // make sure x has a valid state in case of bailout 956 // (was issue 5770) 957 x.mode = invalid 958 x.typ = Typ[Invalid] 959 960 switch e := e.(type) { 961 case *ast.BadExpr: 962 goto Error // error was reported before 963 964 case *ast.Ident: 965 check.ident(x, e, nil, nil) 966 967 case *ast.Ellipsis: 968 // ellipses are handled explicitly where they are legal 969 // (array composite literals and parameter lists) 970 check.error(e.Pos(), "invalid use of '...'") 971 goto Error 972 973 case *ast.BasicLit: 974 x.setConst(e.Kind, e.Value) 975 if x.mode == invalid { 976 check.invalidAST(e.Pos(), "invalid literal %v", e.Value) 977 goto Error 978 } 979 980 case *ast.FuncLit: 981 if sig, ok := check.typ(e.Type).(*Signature); ok { 982 // Anonymous functions are considered part of the 983 // init expression/func declaration which contains 984 // them: use existing package-level declaration info. 985 check.funcBody(check.decl, "", sig, e.Body) 986 x.mode = value 987 x.typ = sig 988 } else { 989 check.invalidAST(e.Pos(), "invalid function literal %s", e) 990 goto Error 991 } 992 993 case *ast.CompositeLit: 994 typ := hint 995 openArray := false 996 if e.Type != nil { 997 // [...]T array types may only appear with composite literals. 998 // Check for them here so we don't have to handle ... in general. 999 typ = nil 1000 if atyp, _ := e.Type.(*ast.ArrayType); atyp != nil && atyp.Len != nil { 1001 if ellip, _ := atyp.Len.(*ast.Ellipsis); ellip != nil && ellip.Elt == nil { 1002 // We have an "open" [...]T array type. 1003 // Create a new ArrayType with unknown length (-1) 1004 // and finish setting it up after analyzing the literal. 1005 typ = &Array{len: -1, elem: check.typ(atyp.Elt)} 1006 openArray = true 1007 } 1008 } 1009 if typ == nil { 1010 typ = check.typ(e.Type) 1011 } 1012 } 1013 if typ == nil { 1014 // TODO(gri) provide better error messages depending on context 1015 check.error(e.Pos(), "missing type in composite literal") 1016 goto Error 1017 } 1018 1019 switch typ, _ := deref(typ); utyp := typ.Underlying().(type) { 1020 case *Struct: 1021 if len(e.Elts) == 0 { 1022 break 1023 } 1024 fields := utyp.fields 1025 if _, ok := e.Elts[0].(*ast.KeyValueExpr); ok { 1026 // all elements must have keys 1027 visited := make([]bool, len(fields)) 1028 for _, e := range e.Elts { 1029 kv, _ := e.(*ast.KeyValueExpr) 1030 if kv == nil { 1031 check.error(e.Pos(), "mixture of field:value and value elements in struct literal") 1032 continue 1033 } 1034 key, _ := kv.Key.(*ast.Ident) 1035 if key == nil { 1036 check.errorf(kv.Pos(), "invalid field name %s in struct literal", kv.Key) 1037 continue 1038 } 1039 i := fieldIndex(utyp.fields, check.pkg, key.Name) 1040 if i < 0 { 1041 check.errorf(kv.Pos(), "unknown field %s in struct literal", key.Name) 1042 continue 1043 } 1044 fld := fields[i] 1045 check.recordUse(key, fld) 1046 // 0 <= i < len(fields) 1047 if visited[i] { 1048 check.errorf(kv.Pos(), "duplicate field name %s in struct literal", key.Name) 1049 continue 1050 } 1051 visited[i] = true 1052 check.expr(x, kv.Value) 1053 etyp := fld.typ 1054 if !check.assignment(x, etyp) { 1055 if x.mode != invalid { 1056 check.errorf(x.pos(), "cannot use %s as %s value in struct literal", x, etyp) 1057 } 1058 continue 1059 } 1060 } 1061 } else { 1062 // no element must have a key 1063 for i, e := range e.Elts { 1064 if kv, _ := e.(*ast.KeyValueExpr); kv != nil { 1065 check.error(kv.Pos(), "mixture of field:value and value elements in struct literal") 1066 continue 1067 } 1068 check.expr(x, e) 1069 if i >= len(fields) { 1070 check.error(x.pos(), "too many values in struct literal") 1071 break // cannot continue 1072 } 1073 // i < len(fields) 1074 fld := fields[i] 1075 if !fld.Exported() && fld.pkg != check.pkg { 1076 check.errorf(x.pos(), "implicit assignment to unexported field %s in %s literal", fld.name, typ) 1077 continue 1078 } 1079 etyp := fld.typ 1080 if !check.assignment(x, etyp) { 1081 if x.mode != invalid { 1082 check.errorf(x.pos(), "cannot use %s as %s value in struct literal", x, etyp) 1083 } 1084 continue 1085 } 1086 } 1087 if len(e.Elts) < len(fields) { 1088 check.error(e.Rbrace, "too few values in struct literal") 1089 // ok to continue 1090 } 1091 } 1092 1093 case *Array: 1094 n := check.indexedElts(e.Elts, utyp.elem, utyp.len) 1095 // if we have an "open" [...]T array, set the length now that we know it 1096 if openArray { 1097 utyp.len = n 1098 } 1099 1100 case *Slice: 1101 check.indexedElts(e.Elts, utyp.elem, -1) 1102 1103 case *Map: 1104 visited := make(map[interface{}][]Type, len(e.Elts)) 1105 for _, e := range e.Elts { 1106 kv, _ := e.(*ast.KeyValueExpr) 1107 if kv == nil { 1108 check.error(e.Pos(), "missing key in map literal") 1109 continue 1110 } 1111 check.exprWithHint(x, kv.Key, utyp.key) 1112 if !check.assignment(x, utyp.key) { 1113 if x.mode != invalid { 1114 check.errorf(x.pos(), "cannot use %s as %s key in map literal", x, utyp.key) 1115 } 1116 continue 1117 } 1118 if x.mode == constant_ { 1119 duplicate := false 1120 // if the key is of interface type, the type is also significant when checking for duplicates 1121 if _, ok := utyp.key.Underlying().(*Interface); ok { 1122 for _, vtyp := range visited[x.val] { 1123 if Identical(vtyp, x.typ) { 1124 duplicate = true 1125 break 1126 } 1127 } 1128 visited[x.val] = append(visited[x.val], x.typ) 1129 } else { 1130 _, duplicate = visited[x.val] 1131 visited[x.val] = nil 1132 } 1133 if duplicate { 1134 check.errorf(x.pos(), "duplicate key %s in map literal", x.val) 1135 continue 1136 } 1137 } 1138 check.exprWithHint(x, kv.Value, utyp.elem) 1139 if !check.assignment(x, utyp.elem) { 1140 if x.mode != invalid { 1141 check.errorf(x.pos(), "cannot use %s as %s value in map literal", x, utyp.elem) 1142 } 1143 continue 1144 } 1145 } 1146 1147 default: 1148 // if utyp is invalid, an error was reported before 1149 if utyp != Typ[Invalid] { 1150 check.errorf(e.Pos(), "invalid composite literal type %s", typ) 1151 goto Error 1152 } 1153 } 1154 1155 x.mode = value 1156 x.typ = typ 1157 1158 case *ast.ParenExpr: 1159 kind := check.rawExpr(x, e.X, nil) 1160 x.expr = e 1161 return kind 1162 1163 case *ast.SelectorExpr: 1164 check.selector(x, e) 1165 1166 case *ast.IndexExpr: 1167 check.expr(x, e.X) 1168 if x.mode == invalid { 1169 goto Error 1170 } 1171 1172 valid := false 1173 length := int64(-1) // valid if >= 0 1174 switch typ := x.typ.Underlying().(type) { 1175 case *Basic: 1176 if isString(typ) { 1177 valid = true 1178 if x.mode == constant_ { 1179 length = int64(len(constant.StringVal(x.val))) 1180 } 1181 // an indexed string always yields a byte value 1182 // (not a constant) even if the string and the 1183 // index are constant 1184 x.mode = value 1185 x.typ = universeByte // use 'byte' name 1186 } 1187 1188 case *Array: 1189 valid = true 1190 length = typ.len 1191 if x.mode != variable { 1192 x.mode = value 1193 } 1194 x.typ = typ.elem 1195 1196 case *Pointer: 1197 if typ, _ := typ.base.Underlying().(*Array); typ != nil { 1198 valid = true 1199 length = typ.len 1200 x.mode = variable 1201 x.typ = typ.elem 1202 } 1203 1204 case *Slice: 1205 valid = true 1206 x.mode = variable 1207 x.typ = typ.elem 1208 1209 case *Map: 1210 var key operand 1211 check.expr(&key, e.Index) 1212 if !check.assignment(&key, typ.key) { 1213 if key.mode != invalid { 1214 check.invalidOp(key.pos(), "cannot use %s as map index of type %s", &key, typ.key) 1215 } 1216 goto Error 1217 } 1218 x.mode = mapindex 1219 x.typ = typ.elem 1220 x.expr = e 1221 return expression 1222 } 1223 1224 if !valid { 1225 check.invalidOp(x.pos(), "cannot index %s", x) 1226 goto Error 1227 } 1228 1229 if e.Index == nil { 1230 check.invalidAST(e.Pos(), "missing index for %s", x) 1231 goto Error 1232 } 1233 1234 check.index(e.Index, length) 1235 // ok to continue 1236 1237 case *ast.SliceExpr: 1238 check.expr(x, e.X) 1239 if x.mode == invalid { 1240 goto Error 1241 } 1242 1243 valid := false 1244 length := int64(-1) // valid if >= 0 1245 switch typ := x.typ.Underlying().(type) { 1246 case *Basic: 1247 if isString(typ) { 1248 if slice3(e) { 1249 check.invalidOp(x.pos(), "3-index slice of string") 1250 goto Error 1251 } 1252 valid = true 1253 if x.mode == constant_ { 1254 length = int64(len(constant.StringVal(x.val))) 1255 } 1256 // spec: "For untyped string operands the result 1257 // is a non-constant value of type string." 1258 if typ.kind == UntypedString { 1259 x.typ = Typ[String] 1260 } 1261 } 1262 1263 case *Array: 1264 valid = true 1265 length = typ.len 1266 if x.mode != variable { 1267 check.invalidOp(x.pos(), "cannot slice %s (value not addressable)", x) 1268 goto Error 1269 } 1270 x.typ = &Slice{elem: typ.elem} 1271 1272 case *Pointer: 1273 if typ, _ := typ.base.Underlying().(*Array); typ != nil { 1274 valid = true 1275 length = typ.len 1276 x.typ = &Slice{elem: typ.elem} 1277 } 1278 1279 case *Slice: 1280 valid = true 1281 // x.typ doesn't change 1282 } 1283 1284 if !valid { 1285 check.invalidOp(x.pos(), "cannot slice %s", x) 1286 goto Error 1287 } 1288 1289 x.mode = value 1290 1291 // spec: "Only the first index may be omitted; it defaults to 0." 1292 if slice3(e) && (e.High == nil || sliceMax(e) == nil) { 1293 check.error(e.Rbrack, "2nd and 3rd index required in 3-index slice") 1294 goto Error 1295 } 1296 1297 // check indices 1298 var ind [3]int64 1299 for i, expr := range []ast.Expr{e.Low, e.High, sliceMax(e)} { 1300 x := int64(-1) 1301 switch { 1302 case expr != nil: 1303 // The "capacity" is only known statically for strings, arrays, 1304 // and pointers to arrays, and it is the same as the length for 1305 // those types. 1306 max := int64(-1) 1307 if length >= 0 { 1308 max = length + 1 1309 } 1310 if t, ok := check.index(expr, max); ok && t >= 0 { 1311 x = t 1312 } 1313 case i == 0: 1314 // default is 0 for the first index 1315 x = 0 1316 case length >= 0: 1317 // default is length (== capacity) otherwise 1318 x = length 1319 } 1320 ind[i] = x 1321 } 1322 1323 // constant indices must be in range 1324 // (check.index already checks that existing indices >= 0) 1325 L: 1326 for i, x := range ind[:len(ind)-1] { 1327 if x > 0 { 1328 for _, y := range ind[i+1:] { 1329 if y >= 0 && x > y { 1330 check.errorf(e.Rbrack, "invalid slice indices: %d > %d", x, y) 1331 break L // only report one error, ok to continue 1332 } 1333 } 1334 } 1335 } 1336 1337 case *ast.TypeAssertExpr: 1338 check.expr(x, e.X) 1339 if x.mode == invalid { 1340 goto Error 1341 } 1342 xtyp, _ := x.typ.Underlying().(*Interface) 1343 if xtyp == nil { 1344 check.invalidOp(x.pos(), "%s is not an interface", x) 1345 goto Error 1346 } 1347 // x.(type) expressions are handled explicitly in type switches 1348 if e.Type == nil { 1349 check.invalidAST(e.Pos(), "use of .(type) outside type switch") 1350 goto Error 1351 } 1352 T := check.typ(e.Type) 1353 if T == Typ[Invalid] { 1354 goto Error 1355 } 1356 check.typeAssertion(x.pos(), x, xtyp, T) 1357 x.mode = commaok 1358 x.typ = T 1359 1360 case *ast.CallExpr: 1361 return check.call(x, e) 1362 1363 case *ast.StarExpr: 1364 check.exprOrType(x, e.X) 1365 switch x.mode { 1366 case invalid: 1367 goto Error 1368 case typexpr: 1369 x.typ = &Pointer{base: x.typ} 1370 default: 1371 if typ, ok := x.typ.Underlying().(*Pointer); ok { 1372 x.mode = variable 1373 x.typ = typ.base 1374 } else { 1375 check.invalidOp(x.pos(), "cannot indirect %s", x) 1376 goto Error 1377 } 1378 } 1379 1380 case *ast.UnaryExpr: 1381 check.expr(x, e.X) 1382 if x.mode == invalid { 1383 goto Error 1384 } 1385 check.unary(x, e, e.Op) 1386 if x.mode == invalid { 1387 goto Error 1388 } 1389 if e.Op == token.ARROW { 1390 x.expr = e 1391 return statement // receive operations may appear in statement context 1392 } 1393 1394 case *ast.BinaryExpr: 1395 check.binary(x, e, e.X, e.Y, e.Op) 1396 if x.mode == invalid { 1397 goto Error 1398 } 1399 1400 case *ast.KeyValueExpr: 1401 // key:value expressions are handled in composite literals 1402 check.invalidAST(e.Pos(), "no key:value expected") 1403 goto Error 1404 1405 case *ast.ArrayType, *ast.StructType, *ast.FuncType, 1406 *ast.InterfaceType, *ast.MapType, *ast.ChanType: 1407 x.mode = typexpr 1408 x.typ = check.typ(e) 1409 // Note: rawExpr (caller of exprInternal) will call check.recordTypeAndValue 1410 // even though check.typ has already called it. This is fine as both 1411 // times the same expression and type are recorded. It is also not a 1412 // performance issue because we only reach here for composite literal 1413 // types, which are comparatively rare. 1414 1415 default: 1416 panic(fmt.Sprintf("%s: unknown expression type %T", check.fset.Position(e.Pos()), e)) 1417 } 1418 1419 // everything went well 1420 x.expr = e 1421 return expression 1422 1423 Error: 1424 x.mode = invalid 1425 x.expr = e 1426 return statement // avoid follow-up errors 1427 } 1428 1429 // typeAssertion checks that x.(T) is legal; xtyp must be the type of x. 1430 func (check *Checker) typeAssertion(pos token.Pos, x *operand, xtyp *Interface, T Type) { 1431 method, wrongType := assertableTo(xtyp, T) 1432 if method == nil { 1433 return 1434 } 1435 1436 var msg string 1437 if wrongType { 1438 msg = "wrong type for method" 1439 } else { 1440 msg = "missing method" 1441 } 1442 check.errorf(pos, "%s cannot have dynamic type %s (%s %s)", x, T, msg, method.name) 1443 } 1444 1445 // expr typechecks expression e and initializes x with the expression value. 1446 // If an error occurred, x.mode is set to invalid. 1447 // 1448 func (check *Checker) expr(x *operand, e ast.Expr) { 1449 check.rawExpr(x, e, nil) 1450 var msg string 1451 switch x.mode { 1452 default: 1453 return 1454 case novalue: 1455 msg = "used as value" 1456 case builtin: 1457 msg = "must be called" 1458 case typexpr: 1459 msg = "is not an expression" 1460 } 1461 check.errorf(x.pos(), "%s %s", x, msg) 1462 x.mode = invalid 1463 } 1464 1465 // exprWithHint typechecks expression e and initializes x with the expression value. 1466 // If an error occurred, x.mode is set to invalid. 1467 // If hint != nil, it is the type of a composite literal element. 1468 // 1469 func (check *Checker) exprWithHint(x *operand, e ast.Expr, hint Type) { 1470 assert(hint != nil) 1471 check.rawExpr(x, e, hint) 1472 var msg string 1473 switch x.mode { 1474 default: 1475 return 1476 case novalue: 1477 msg = "used as value" 1478 case builtin: 1479 msg = "must be called" 1480 case typexpr: 1481 msg = "is not an expression" 1482 } 1483 check.errorf(x.pos(), "%s %s", x, msg) 1484 x.mode = invalid 1485 } 1486 1487 // exprOrType typechecks expression or type e and initializes x with the expression value or type. 1488 // If an error occurred, x.mode is set to invalid. 1489 // 1490 func (check *Checker) exprOrType(x *operand, e ast.Expr) { 1491 check.rawExpr(x, e, nil) 1492 if x.mode == novalue { 1493 check.errorf(x.pos(), "%s used as value or type", x) 1494 x.mode = invalid 1495 } 1496 }