github.com/q45/go@v0.0.0-20151101211701-a4fb8c13db3f/src/go/types/expr.go (about) 1 // Copyright 2012 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // This file implements typechecking of expressions. 6 7 package types 8 9 import ( 10 "fmt" 11 "go/ast" 12 "go/constant" 13 "go/token" 14 "math" 15 ) 16 17 /* 18 Basic algorithm: 19 20 Expressions are checked recursively, top down. Expression checker functions 21 are generally of the form: 22 23 func f(x *operand, e *ast.Expr, ...) 24 25 where e is the expression to be checked, and x is the result of the check. 26 The check performed by f may fail in which case x.mode == invalid, and 27 related error messages will have been issued by f. 28 29 If a hint argument is present, it is the composite literal element type 30 of an outer composite literal; it is used to type-check composite literal 31 elements that have no explicit type specification in the source 32 (e.g.: []T{{...}, {...}}, the hint is the type T in this case). 33 34 All expressions are checked via rawExpr, which dispatches according 35 to expression kind. Upon returning, rawExpr is recording the types and 36 constant values for all expressions that have an untyped type (those types 37 may change on the way up in the expression tree). Usually these are constants, 38 but the results of comparisons or non-constant shifts of untyped constants 39 may also be untyped, but not constant. 40 41 Untyped expressions may eventually become fully typed (i.e., not untyped), 42 typically when the value is assigned to a variable, or is used otherwise. 43 The updateExprType method is used to record this final type and update 44 the recorded types: the type-checked expression tree is again traversed down, 45 and the new type is propagated as needed. Untyped constant expression values 46 that become fully typed must now be representable by the full type (constant 47 sub-expression trees are left alone except for their roots). This mechanism 48 ensures that a client sees the actual (run-time) type an untyped value would 49 have. It also permits type-checking of lhs shift operands "as if the shift 50 were not present": when updateExprType visits an untyped lhs shift operand 51 and assigns it it's final type, that type must be an integer type, and a 52 constant lhs must be representable as an integer. 53 54 When an expression gets its final type, either on the way out from rawExpr, 55 on the way down in updateExprType, or at the end of the type checker run, 56 the type (and constant value, if any) is recorded via Info.Types, if present. 57 */ 58 59 type opPredicates map[token.Token]func(Type) bool 60 61 var unaryOpPredicates = opPredicates{ 62 token.ADD: isNumeric, 63 token.SUB: isNumeric, 64 token.XOR: isInteger, 65 token.NOT: isBoolean, 66 } 67 68 func (check *Checker) op(m opPredicates, x *operand, op token.Token) bool { 69 if pred := m[op]; pred != nil { 70 if !pred(x.typ) { 71 check.invalidOp(x.pos(), "operator %s not defined for %s", op, x) 72 return false 73 } 74 } else { 75 check.invalidAST(x.pos(), "unknown operator %s", op) 76 return false 77 } 78 return true 79 } 80 81 // The unary expression e may be nil. It's passed in for better error messages only. 82 func (check *Checker) unary(x *operand, e *ast.UnaryExpr, op token.Token) { 83 switch op { 84 case token.AND: 85 // spec: "As an exception to the addressability 86 // requirement x may also be a composite literal." 87 if _, ok := unparen(x.expr).(*ast.CompositeLit); !ok && x.mode != variable { 88 check.invalidOp(x.pos(), "cannot take address of %s", x) 89 x.mode = invalid 90 return 91 } 92 x.mode = value 93 x.typ = &Pointer{base: x.typ} 94 return 95 96 case token.ARROW: 97 typ, ok := x.typ.Underlying().(*Chan) 98 if !ok { 99 check.invalidOp(x.pos(), "cannot receive from non-channel %s", x) 100 x.mode = invalid 101 return 102 } 103 if typ.dir == SendOnly { 104 check.invalidOp(x.pos(), "cannot receive from send-only channel %s", x) 105 x.mode = invalid 106 return 107 } 108 x.mode = commaok 109 x.typ = typ.elem 110 check.hasCallOrRecv = true 111 return 112 } 113 114 if !check.op(unaryOpPredicates, x, op) { 115 x.mode = invalid 116 return 117 } 118 119 if x.mode == constant_ { 120 typ := x.typ.Underlying().(*Basic) 121 var prec uint 122 if isUnsigned(typ) { 123 prec = uint(check.conf.sizeof(typ) * 8) 124 } 125 x.val = constant.UnaryOp(op, x.val, prec) 126 // Typed constants must be representable in 127 // their type after each constant operation. 128 if isTyped(typ) { 129 if e != nil { 130 x.expr = e // for better error message 131 } 132 check.representable(x, typ) 133 } 134 return 135 } 136 137 x.mode = value 138 // x.typ remains unchanged 139 } 140 141 func isShift(op token.Token) bool { 142 return op == token.SHL || op == token.SHR 143 } 144 145 func isComparison(op token.Token) bool { 146 // Note: tokens are not ordered well to make this much easier 147 switch op { 148 case token.EQL, token.NEQ, token.LSS, token.LEQ, token.GTR, token.GEQ: 149 return true 150 } 151 return false 152 } 153 154 func fitsFloat32(x constant.Value) bool { 155 f32, _ := constant.Float32Val(x) 156 f := float64(f32) 157 return !math.IsInf(f, 0) 158 } 159 160 func roundFloat32(x constant.Value) constant.Value { 161 f32, _ := constant.Float32Val(x) 162 f := float64(f32) 163 if !math.IsInf(f, 0) { 164 return constant.MakeFloat64(f) 165 } 166 return nil 167 } 168 169 func fitsFloat64(x constant.Value) bool { 170 f, _ := constant.Float64Val(x) 171 return !math.IsInf(f, 0) 172 } 173 174 func roundFloat64(x constant.Value) constant.Value { 175 f, _ := constant.Float64Val(x) 176 if !math.IsInf(f, 0) { 177 return constant.MakeFloat64(f) 178 } 179 return nil 180 } 181 182 // representableConst reports whether x can be represented as 183 // value of the given basic type kind and for the configuration 184 // provided (only needed for int/uint sizes). 185 // 186 // If rounded != nil, *rounded is set to the rounded value of x for 187 // representable floating-point values; it is left alone otherwise. 188 // It is ok to provide the addressof the first argument for rounded. 189 func representableConst(x constant.Value, conf *Config, as BasicKind, rounded *constant.Value) bool { 190 switch x.Kind() { 191 case constant.Unknown: 192 return true 193 194 case constant.Bool: 195 return as == Bool || as == UntypedBool 196 197 case constant.Int: 198 if x, ok := constant.Int64Val(x); ok { 199 switch as { 200 case Int: 201 var s = uint(conf.sizeof(Typ[as])) * 8 202 return int64(-1)<<(s-1) <= x && x <= int64(1)<<(s-1)-1 203 case Int8: 204 const s = 8 205 return -1<<(s-1) <= x && x <= 1<<(s-1)-1 206 case Int16: 207 const s = 16 208 return -1<<(s-1) <= x && x <= 1<<(s-1)-1 209 case Int32: 210 const s = 32 211 return -1<<(s-1) <= x && x <= 1<<(s-1)-1 212 case Int64: 213 return true 214 case Uint, Uintptr: 215 if s := uint(conf.sizeof(Typ[as])) * 8; s < 64 { 216 return 0 <= x && x <= int64(1)<<s-1 217 } 218 return 0 <= x 219 case Uint8: 220 const s = 8 221 return 0 <= x && x <= 1<<s-1 222 case Uint16: 223 const s = 16 224 return 0 <= x && x <= 1<<s-1 225 case Uint32: 226 const s = 32 227 return 0 <= x && x <= 1<<s-1 228 case Uint64: 229 return 0 <= x 230 case Float32, Float64, Complex64, Complex128, 231 UntypedInt, UntypedFloat, UntypedComplex: 232 return true 233 } 234 } 235 236 n := constant.BitLen(x) 237 switch as { 238 case Uint, Uintptr: 239 var s = uint(conf.sizeof(Typ[as])) * 8 240 return constant.Sign(x) >= 0 && n <= int(s) 241 case Uint64: 242 return constant.Sign(x) >= 0 && n <= 64 243 case Float32, Complex64: 244 if rounded == nil { 245 return fitsFloat32(x) 246 } 247 r := roundFloat32(x) 248 if r != nil { 249 *rounded = r 250 return true 251 } 252 case Float64, Complex128: 253 if rounded == nil { 254 return fitsFloat64(x) 255 } 256 r := roundFloat64(x) 257 if r != nil { 258 *rounded = r 259 return true 260 } 261 case UntypedInt, UntypedFloat, UntypedComplex: 262 return true 263 } 264 265 case constant.Float: 266 switch as { 267 case Float32, Complex64: 268 if rounded == nil { 269 return fitsFloat32(x) 270 } 271 r := roundFloat32(x) 272 if r != nil { 273 *rounded = r 274 return true 275 } 276 case Float64, Complex128: 277 if rounded == nil { 278 return fitsFloat64(x) 279 } 280 r := roundFloat64(x) 281 if r != nil { 282 *rounded = r 283 return true 284 } 285 case UntypedFloat, UntypedComplex: 286 return true 287 } 288 289 case constant.Complex: 290 switch as { 291 case Complex64: 292 if rounded == nil { 293 return fitsFloat32(constant.Real(x)) && fitsFloat32(constant.Imag(x)) 294 } 295 re := roundFloat32(constant.Real(x)) 296 im := roundFloat32(constant.Imag(x)) 297 if re != nil && im != nil { 298 *rounded = constant.BinaryOp(re, token.ADD, constant.MakeImag(im)) 299 return true 300 } 301 case Complex128: 302 if rounded == nil { 303 return fitsFloat64(constant.Real(x)) && fitsFloat64(constant.Imag(x)) 304 } 305 re := roundFloat64(constant.Real(x)) 306 im := roundFloat64(constant.Imag(x)) 307 if re != nil && im != nil { 308 *rounded = constant.BinaryOp(re, token.ADD, constant.MakeImag(im)) 309 return true 310 } 311 case UntypedComplex: 312 return true 313 } 314 315 case constant.String: 316 return as == String || as == UntypedString 317 318 default: 319 unreachable() 320 } 321 322 return false 323 } 324 325 // representable checks that a constant operand is representable in the given basic type. 326 func (check *Checker) representable(x *operand, typ *Basic) { 327 assert(x.mode == constant_) 328 if !representableConst(x.val, check.conf, typ.kind, &x.val) { 329 var msg string 330 if isNumeric(x.typ) && isNumeric(typ) { 331 // numeric conversion : error msg 332 // 333 // integer -> integer : overflows 334 // integer -> float : overflows (actually not possible) 335 // float -> integer : truncated 336 // float -> float : overflows 337 // 338 if !isInteger(x.typ) && isInteger(typ) { 339 msg = "%s truncated to %s" 340 } else { 341 msg = "%s overflows %s" 342 } 343 } else { 344 msg = "cannot convert %s to %s" 345 } 346 check.errorf(x.pos(), msg, x, typ) 347 x.mode = invalid 348 } 349 } 350 351 // updateExprType updates the type of x to typ and invokes itself 352 // recursively for the operands of x, depending on expression kind. 353 // If typ is still an untyped and not the final type, updateExprType 354 // only updates the recorded untyped type for x and possibly its 355 // operands. Otherwise (i.e., typ is not an untyped type anymore, 356 // or it is the final type for x), the type and value are recorded. 357 // Also, if x is a constant, it must be representable as a value of typ, 358 // and if x is the (formerly untyped) lhs operand of a non-constant 359 // shift, it must be an integer value. 360 // 361 func (check *Checker) updateExprType(x ast.Expr, typ Type, final bool) { 362 old, found := check.untyped[x] 363 if !found { 364 return // nothing to do 365 } 366 367 // update operands of x if necessary 368 switch x := x.(type) { 369 case *ast.BadExpr, 370 *ast.FuncLit, 371 *ast.CompositeLit, 372 *ast.IndexExpr, 373 *ast.SliceExpr, 374 *ast.TypeAssertExpr, 375 *ast.StarExpr, 376 *ast.KeyValueExpr, 377 *ast.ArrayType, 378 *ast.StructType, 379 *ast.FuncType, 380 *ast.InterfaceType, 381 *ast.MapType, 382 *ast.ChanType: 383 // These expression are never untyped - nothing to do. 384 // The respective sub-expressions got their final types 385 // upon assignment or use. 386 if debug { 387 check.dump("%s: found old type(%s): %s (new: %s)", x.Pos(), x, old.typ, typ) 388 unreachable() 389 } 390 return 391 392 case *ast.CallExpr: 393 // Resulting in an untyped constant (e.g., built-in complex). 394 // The respective calls take care of calling updateExprType 395 // for the arguments if necessary. 396 397 case *ast.Ident, *ast.BasicLit, *ast.SelectorExpr: 398 // An identifier denoting a constant, a constant literal, 399 // or a qualified identifier (imported untyped constant). 400 // No operands to take care of. 401 402 case *ast.ParenExpr: 403 check.updateExprType(x.X, typ, final) 404 405 case *ast.UnaryExpr: 406 // If x is a constant, the operands were constants. 407 // They don't need to be updated since they never 408 // get "materialized" into a typed value; and they 409 // will be processed at the end of the type check. 410 if old.val != nil { 411 break 412 } 413 check.updateExprType(x.X, typ, final) 414 415 case *ast.BinaryExpr: 416 if old.val != nil { 417 break // see comment for unary expressions 418 } 419 if isComparison(x.Op) { 420 // The result type is independent of operand types 421 // and the operand types must have final types. 422 } else if isShift(x.Op) { 423 // The result type depends only on lhs operand. 424 // The rhs type was updated when checking the shift. 425 check.updateExprType(x.X, typ, final) 426 } else { 427 // The operand types match the result type. 428 check.updateExprType(x.X, typ, final) 429 check.updateExprType(x.Y, typ, final) 430 } 431 432 default: 433 unreachable() 434 } 435 436 // If the new type is not final and still untyped, just 437 // update the recorded type. 438 if !final && isUntyped(typ) { 439 old.typ = typ.Underlying().(*Basic) 440 check.untyped[x] = old 441 return 442 } 443 444 // Otherwise we have the final (typed or untyped type). 445 // Remove it from the map of yet untyped expressions. 446 delete(check.untyped, x) 447 448 // If x is the lhs of a shift, its final type must be integer. 449 // We already know from the shift check that it is representable 450 // as an integer if it is a constant. 451 if old.isLhs && !isInteger(typ) { 452 check.invalidOp(x.Pos(), "shifted operand %s (type %s) must be integer", x, typ) 453 return 454 } 455 456 // Everything's fine, record final type and value for x. 457 check.recordTypeAndValue(x, old.mode, typ, old.val) 458 } 459 460 // updateExprVal updates the value of x to val. 461 func (check *Checker) updateExprVal(x ast.Expr, val constant.Value) { 462 if info, ok := check.untyped[x]; ok { 463 info.val = val 464 check.untyped[x] = info 465 } 466 } 467 468 // convertUntyped attempts to set the type of an untyped value to the target type. 469 func (check *Checker) convertUntyped(x *operand, target Type) { 470 if x.mode == invalid || isTyped(x.typ) || target == Typ[Invalid] { 471 return 472 } 473 474 // TODO(gri) Sloppy code - clean up. This function is central 475 // to assignment and expression checking. 476 477 if isUntyped(target) { 478 // both x and target are untyped 479 xkind := x.typ.(*Basic).kind 480 tkind := target.(*Basic).kind 481 if isNumeric(x.typ) && isNumeric(target) { 482 if xkind < tkind { 483 x.typ = target 484 check.updateExprType(x.expr, target, false) 485 } 486 } else if xkind != tkind { 487 goto Error 488 } 489 return 490 } 491 492 // typed target 493 switch t := target.Underlying().(type) { 494 case *Basic: 495 if x.mode == constant_ { 496 check.representable(x, t) 497 if x.mode == invalid { 498 return 499 } 500 // expression value may have been rounded - update if needed 501 // TODO(gri) A floating-point value may silently underflow to 502 // zero. If it was negative, the sign is lost. See issue 6898. 503 check.updateExprVal(x.expr, x.val) 504 } else { 505 // Non-constant untyped values may appear as the 506 // result of comparisons (untyped bool), intermediate 507 // (delayed-checked) rhs operands of shifts, and as 508 // the value nil. 509 switch x.typ.(*Basic).kind { 510 case UntypedBool: 511 if !isBoolean(target) { 512 goto Error 513 } 514 case UntypedInt, UntypedRune, UntypedFloat, UntypedComplex: 515 if !isNumeric(target) { 516 goto Error 517 } 518 case UntypedString: 519 // Non-constant untyped string values are not 520 // permitted by the spec and should not occur. 521 unreachable() 522 case UntypedNil: 523 // Unsafe.Pointer is a basic type that includes nil. 524 if !hasNil(target) { 525 goto Error 526 } 527 default: 528 goto Error 529 } 530 } 531 case *Interface: 532 if !x.isNil() && !t.Empty() /* empty interfaces are ok */ { 533 goto Error 534 } 535 // Update operand types to the default type rather then 536 // the target (interface) type: values must have concrete 537 // dynamic types. If the value is nil, keep it untyped 538 // (this is important for tools such as go vet which need 539 // the dynamic type for argument checking of say, print 540 // functions) 541 if x.isNil() { 542 target = Typ[UntypedNil] 543 } else { 544 // cannot assign untyped values to non-empty interfaces 545 if !t.Empty() { 546 goto Error 547 } 548 target = defaultType(x.typ) 549 } 550 case *Pointer, *Signature, *Slice, *Map, *Chan: 551 if !x.isNil() { 552 goto Error 553 } 554 // keep nil untyped - see comment for interfaces, above 555 target = Typ[UntypedNil] 556 default: 557 goto Error 558 } 559 560 x.typ = target 561 check.updateExprType(x.expr, target, true) // UntypedNils are final 562 return 563 564 Error: 565 check.errorf(x.pos(), "cannot convert %s to %s", x, target) 566 x.mode = invalid 567 } 568 569 func (check *Checker) comparison(x, y *operand, op token.Token) { 570 // spec: "In any comparison, the first operand must be assignable 571 // to the type of the second operand, or vice versa." 572 err := "" 573 if x.assignableTo(check.conf, y.typ, nil) || y.assignableTo(check.conf, x.typ, nil) { 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, e *ast.BinaryExpr, 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 // Typed constants must be representable in 675 // their type after each constant operation. 676 if isTyped(x.typ) { 677 if e != nil { 678 x.expr = e // for better error message 679 } 680 check.representable(x, x.typ.Underlying().(*Basic)) 681 } 682 return 683 } 684 685 // non-constant shift with constant lhs 686 if untypedx { 687 // spec: "If the left operand of a non-constant shift 688 // expression is an untyped constant, the type of the 689 // constant is what it would be if the shift expression 690 // were replaced by its left operand alone.". 691 // 692 // Delay operand checking until we know the final type 693 // by marking the lhs expression as lhs shift operand. 694 // 695 // Usually (in correct programs), the lhs expression 696 // is in the untyped map. However, it is possible to 697 // create incorrect programs where the same expression 698 // is evaluated twice (via a declaration cycle) such 699 // that the lhs expression type is determined in the 700 // first round and thus deleted from the map, and then 701 // not found in the second round (double insertion of 702 // the same expr node still just leads to one entry for 703 // that node, and it can only be deleted once). 704 // Be cautious and check for presence of entry. 705 // Example: var e, f = int(1<<""[f]) // issue 11347 706 if info, found := check.untyped[x.expr]; found { 707 info.isLhs = true 708 check.untyped[x.expr] = info 709 } 710 // keep x's type 711 x.mode = value 712 return 713 } 714 } 715 716 // constant rhs must be >= 0 717 if y.mode == constant_ && constant.Sign(y.val) < 0 { 718 check.invalidOp(y.pos(), "shift count %s must not be negative", y) 719 } 720 721 // non-constant shift - lhs must be an integer 722 if !isInteger(x.typ) { 723 check.invalidOp(x.pos(), "shifted operand %s must be integer", x) 724 x.mode = invalid 725 return 726 } 727 728 x.mode = value 729 } 730 731 var binaryOpPredicates = opPredicates{ 732 token.ADD: func(typ Type) bool { return isNumeric(typ) || isString(typ) }, 733 token.SUB: isNumeric, 734 token.MUL: isNumeric, 735 token.QUO: isNumeric, 736 token.REM: isInteger, 737 738 token.AND: isInteger, 739 token.OR: isInteger, 740 token.XOR: isInteger, 741 token.AND_NOT: isInteger, 742 743 token.LAND: isBoolean, 744 token.LOR: isBoolean, 745 } 746 747 // The binary expression e may be nil. It's passed in for better error messages only. 748 func (check *Checker) binary(x *operand, e *ast.BinaryExpr, lhs, rhs ast.Expr, op token.Token) { 749 var y operand 750 751 check.expr(x, lhs) 752 check.expr(&y, rhs) 753 754 if x.mode == invalid { 755 return 756 } 757 if y.mode == invalid { 758 x.mode = invalid 759 x.expr = y.expr 760 return 761 } 762 763 if isShift(op) { 764 check.shift(x, &y, e, op) 765 return 766 } 767 768 check.convertUntyped(x, y.typ) 769 if x.mode == invalid { 770 return 771 } 772 check.convertUntyped(&y, x.typ) 773 if y.mode == invalid { 774 x.mode = invalid 775 return 776 } 777 778 if isComparison(op) { 779 check.comparison(x, &y, op) 780 return 781 } 782 783 if !Identical(x.typ, y.typ) { 784 // only report an error if we have valid types 785 // (otherwise we had an error reported elsewhere already) 786 if x.typ != Typ[Invalid] && y.typ != Typ[Invalid] { 787 check.invalidOp(x.pos(), "mismatched types %s and %s", x.typ, y.typ) 788 } 789 x.mode = invalid 790 return 791 } 792 793 if !check.op(binaryOpPredicates, x, op) { 794 x.mode = invalid 795 return 796 } 797 798 if (op == token.QUO || op == token.REM) && (x.mode == constant_ || isInteger(x.typ)) && y.mode == constant_ && constant.Sign(y.val) == 0 { 799 check.invalidOp(y.pos(), "division by zero") 800 x.mode = invalid 801 return 802 } 803 804 if x.mode == constant_ && y.mode == constant_ { 805 typ := x.typ.Underlying().(*Basic) 806 // force integer division of integer operands 807 if op == token.QUO && isInteger(typ) { 808 op = token.QUO_ASSIGN 809 } 810 x.val = constant.BinaryOp(x.val, op, y.val) 811 // Typed constants must be representable in 812 // their type after each constant operation. 813 if isTyped(typ) { 814 if e != nil { 815 x.expr = e // for better error message 816 } 817 check.representable(x, typ) 818 } 819 return 820 } 821 822 x.mode = value 823 // x.typ is unchanged 824 } 825 826 // index checks an index expression for validity. 827 // If max >= 0, it is the upper bound for index. 828 // If index is valid and the result i >= 0, then i is the constant value of index. 829 func (check *Checker) index(index ast.Expr, max int64) (i int64, valid bool) { 830 var x operand 831 check.expr(&x, index) 832 if x.mode == invalid { 833 return 834 } 835 836 // an untyped constant must be representable as Int 837 check.convertUntyped(&x, Typ[Int]) 838 if x.mode == invalid { 839 return 840 } 841 842 // the index must be of integer type 843 if !isInteger(x.typ) { 844 check.invalidArg(x.pos(), "index %s must be integer", &x) 845 return 846 } 847 848 // a constant index i must be in bounds 849 if x.mode == constant_ { 850 if constant.Sign(x.val) < 0 { 851 check.invalidArg(x.pos(), "index %s must not be negative", &x) 852 return 853 } 854 i, valid = constant.Int64Val(x.val) 855 if !valid || max >= 0 && i >= max { 856 check.errorf(x.pos(), "index %s is out of bounds", &x) 857 return i, false 858 } 859 // 0 <= i [ && i < max ] 860 return i, true 861 } 862 863 return -1, true 864 } 865 866 // indexElts checks the elements (elts) of an array or slice composite literal 867 // against the literal's element type (typ), and the element indices against 868 // the literal length if known (length >= 0). It returns the length of the 869 // literal (maximum index value + 1). 870 // 871 func (check *Checker) indexedElts(elts []ast.Expr, typ Type, length int64) int64 { 872 visited := make(map[int64]bool, len(elts)) 873 var index, max int64 874 for _, e := range elts { 875 // determine and check index 876 validIndex := false 877 eval := e 878 if kv, _ := e.(*ast.KeyValueExpr); kv != nil { 879 if i, ok := check.index(kv.Key, length); ok { 880 if i >= 0 { 881 index = i 882 validIndex = true 883 } else { 884 check.errorf(e.Pos(), "index %s must be integer constant", kv.Key) 885 } 886 } 887 eval = kv.Value 888 } else if length >= 0 && index >= length { 889 check.errorf(e.Pos(), "index %d is out of bounds (>= %d)", index, length) 890 } else { 891 validIndex = true 892 } 893 894 // if we have a valid index, check for duplicate entries 895 if validIndex { 896 if visited[index] { 897 check.errorf(e.Pos(), "duplicate index %d in array or slice literal", index) 898 } 899 visited[index] = true 900 } 901 index++ 902 if index > max { 903 max = index 904 } 905 906 // check element against composite literal element type 907 var x operand 908 check.exprWithHint(&x, eval, typ) 909 check.assignment(&x, typ, "array or slice literal") 910 } 911 return max 912 } 913 914 // exprKind describes the kind of an expression; the kind 915 // determines if an expression is valid in 'statement context'. 916 type exprKind int 917 918 const ( 919 conversion exprKind = iota 920 expression 921 statement 922 ) 923 924 // rawExpr typechecks expression e and initializes x with the expression 925 // value or type. If an error occurred, x.mode is set to invalid. 926 // If hint != nil, it is the type of a composite literal element. 927 // 928 func (check *Checker) rawExpr(x *operand, e ast.Expr, hint Type) exprKind { 929 if trace { 930 check.trace(e.Pos(), "%s", e) 931 check.indent++ 932 defer func() { 933 check.indent-- 934 check.trace(e.Pos(), "=> %s", x) 935 }() 936 } 937 938 kind := check.exprInternal(x, e, hint) 939 940 // convert x into a user-friendly set of values 941 // TODO(gri) this code can be simplified 942 var typ Type 943 var val constant.Value 944 switch x.mode { 945 case invalid: 946 typ = Typ[Invalid] 947 case novalue: 948 typ = (*Tuple)(nil) 949 case constant_: 950 typ = x.typ 951 val = x.val 952 default: 953 typ = x.typ 954 } 955 assert(x.expr != nil && typ != nil) 956 957 if isUntyped(typ) { 958 // delay type and value recording until we know the type 959 // or until the end of type checking 960 check.rememberUntyped(x.expr, false, x.mode, typ.(*Basic), val) 961 } else { 962 check.recordTypeAndValue(e, x.mode, typ, val) 963 } 964 965 return kind 966 } 967 968 // exprInternal contains the core of type checking of expressions. 969 // Must only be called by rawExpr. 970 // 971 func (check *Checker) exprInternal(x *operand, e ast.Expr, hint Type) exprKind { 972 // make sure x has a valid state in case of bailout 973 // (was issue 5770) 974 x.mode = invalid 975 x.typ = Typ[Invalid] 976 977 switch e := e.(type) { 978 case *ast.BadExpr: 979 goto Error // error was reported before 980 981 case *ast.Ident: 982 check.ident(x, e, nil, nil) 983 984 case *ast.Ellipsis: 985 // ellipses are handled explicitly where they are legal 986 // (array composite literals and parameter lists) 987 check.error(e.Pos(), "invalid use of '...'") 988 goto Error 989 990 case *ast.BasicLit: 991 x.setConst(e.Kind, e.Value) 992 if x.mode == invalid { 993 check.invalidAST(e.Pos(), "invalid literal %v", e.Value) 994 goto Error 995 } 996 997 case *ast.FuncLit: 998 if sig, ok := check.typ(e.Type).(*Signature); ok { 999 // Anonymous functions are considered part of the 1000 // init expression/func declaration which contains 1001 // them: use existing package-level declaration info. 1002 check.funcBody(check.decl, "", sig, e.Body) 1003 x.mode = value 1004 x.typ = sig 1005 } else { 1006 check.invalidAST(e.Pos(), "invalid function literal %s", e) 1007 goto Error 1008 } 1009 1010 case *ast.CompositeLit: 1011 typ := hint 1012 openArray := false 1013 if e.Type != nil { 1014 // [...]T array types may only appear with composite literals. 1015 // Check for them here so we don't have to handle ... in general. 1016 typ = nil 1017 if atyp, _ := e.Type.(*ast.ArrayType); atyp != nil && atyp.Len != nil { 1018 if ellip, _ := atyp.Len.(*ast.Ellipsis); ellip != nil && ellip.Elt == nil { 1019 // We have an "open" [...]T array type. 1020 // Create a new ArrayType with unknown length (-1) 1021 // and finish setting it up after analyzing the literal. 1022 typ = &Array{len: -1, elem: check.typ(atyp.Elt)} 1023 openArray = true 1024 } 1025 } 1026 if typ == nil { 1027 typ = check.typ(e.Type) 1028 } 1029 } 1030 if typ == nil { 1031 // TODO(gri) provide better error messages depending on context 1032 check.error(e.Pos(), "missing type in composite literal") 1033 goto Error 1034 } 1035 1036 switch typ, _ := deref(typ); utyp := typ.Underlying().(type) { 1037 case *Struct: 1038 if len(e.Elts) == 0 { 1039 break 1040 } 1041 fields := utyp.fields 1042 if _, ok := e.Elts[0].(*ast.KeyValueExpr); ok { 1043 // all elements must have keys 1044 visited := make([]bool, len(fields)) 1045 for _, e := range e.Elts { 1046 kv, _ := e.(*ast.KeyValueExpr) 1047 if kv == nil { 1048 check.error(e.Pos(), "mixture of field:value and value elements in struct literal") 1049 continue 1050 } 1051 key, _ := kv.Key.(*ast.Ident) 1052 if key == nil { 1053 check.errorf(kv.Pos(), "invalid field name %s in struct literal", kv.Key) 1054 continue 1055 } 1056 i := fieldIndex(utyp.fields, check.pkg, key.Name) 1057 if i < 0 { 1058 check.errorf(kv.Pos(), "unknown field %s in struct literal", key.Name) 1059 continue 1060 } 1061 fld := fields[i] 1062 check.recordUse(key, fld) 1063 // 0 <= i < len(fields) 1064 if visited[i] { 1065 check.errorf(kv.Pos(), "duplicate field name %s in struct literal", key.Name) 1066 continue 1067 } 1068 visited[i] = true 1069 check.expr(x, kv.Value) 1070 etyp := fld.typ 1071 check.assignment(x, etyp, "struct literal") 1072 } 1073 } else { 1074 // no element must have a key 1075 for i, e := range e.Elts { 1076 if kv, _ := e.(*ast.KeyValueExpr); kv != nil { 1077 check.error(kv.Pos(), "mixture of field:value and value elements in struct literal") 1078 continue 1079 } 1080 check.expr(x, e) 1081 if i >= len(fields) { 1082 check.error(x.pos(), "too many values in struct literal") 1083 break // cannot continue 1084 } 1085 // i < len(fields) 1086 fld := fields[i] 1087 if !fld.Exported() && fld.pkg != check.pkg { 1088 check.errorf(x.pos(), "implicit assignment to unexported field %s in %s literal", fld.name, typ) 1089 continue 1090 } 1091 etyp := fld.typ 1092 check.assignment(x, etyp, "struct literal") 1093 } 1094 if len(e.Elts) < len(fields) { 1095 check.error(e.Rbrace, "too few values in struct literal") 1096 // ok to continue 1097 } 1098 } 1099 1100 case *Array: 1101 n := check.indexedElts(e.Elts, utyp.elem, utyp.len) 1102 // if we have an "open" [...]T array, set the length now that we know it 1103 if openArray { 1104 utyp.len = n 1105 } 1106 1107 case *Slice: 1108 check.indexedElts(e.Elts, utyp.elem, -1) 1109 1110 case *Map: 1111 visited := make(map[interface{}][]Type, len(e.Elts)) 1112 for _, e := range e.Elts { 1113 kv, _ := e.(*ast.KeyValueExpr) 1114 if kv == nil { 1115 check.error(e.Pos(), "missing key in map literal") 1116 continue 1117 } 1118 check.exprWithHint(x, kv.Key, utyp.key) 1119 check.assignment(x, utyp.key, "map literal") 1120 if x.mode == invalid { 1121 continue 1122 } 1123 if x.mode == constant_ { 1124 duplicate := false 1125 // if the key is of interface type, the type is also significant when checking for duplicates 1126 if _, ok := utyp.key.Underlying().(*Interface); ok { 1127 for _, vtyp := range visited[x.val] { 1128 if Identical(vtyp, x.typ) { 1129 duplicate = true 1130 break 1131 } 1132 } 1133 visited[x.val] = append(visited[x.val], x.typ) 1134 } else { 1135 _, duplicate = visited[x.val] 1136 visited[x.val] = nil 1137 } 1138 if duplicate { 1139 check.errorf(x.pos(), "duplicate key %s in map literal", x.val) 1140 continue 1141 } 1142 } 1143 check.exprWithHint(x, kv.Value, utyp.elem) 1144 check.assignment(x, utyp.elem, "map literal") 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 check.assignment(&key, typ.key, "map index") 1213 if x.mode == invalid { 1214 goto Error 1215 } 1216 x.mode = mapindex 1217 x.typ = typ.elem 1218 x.expr = e 1219 return expression 1220 } 1221 1222 if !valid { 1223 check.invalidOp(x.pos(), "cannot index %s", x) 1224 goto Error 1225 } 1226 1227 if e.Index == nil { 1228 check.invalidAST(e.Pos(), "missing index for %s", x) 1229 goto Error 1230 } 1231 1232 check.index(e.Index, length) 1233 // ok to continue 1234 1235 case *ast.SliceExpr: 1236 check.expr(x, e.X) 1237 if x.mode == invalid { 1238 goto Error 1239 } 1240 1241 valid := false 1242 length := int64(-1) // valid if >= 0 1243 switch typ := x.typ.Underlying().(type) { 1244 case *Basic: 1245 if isString(typ) { 1246 if e.Slice3 { 1247 check.invalidOp(x.pos(), "3-index slice of string") 1248 goto Error 1249 } 1250 valid = true 1251 if x.mode == constant_ { 1252 length = int64(len(constant.StringVal(x.val))) 1253 } 1254 // spec: "For untyped string operands the result 1255 // is a non-constant value of type string." 1256 if typ.kind == UntypedString { 1257 x.typ = Typ[String] 1258 } 1259 } 1260 1261 case *Array: 1262 valid = true 1263 length = typ.len 1264 if x.mode != variable { 1265 check.invalidOp(x.pos(), "cannot slice %s (value not addressable)", x) 1266 goto Error 1267 } 1268 x.typ = &Slice{elem: typ.elem} 1269 1270 case *Pointer: 1271 if typ, _ := typ.base.Underlying().(*Array); typ != nil { 1272 valid = true 1273 length = typ.len 1274 x.typ = &Slice{elem: typ.elem} 1275 } 1276 1277 case *Slice: 1278 valid = true 1279 // x.typ doesn't change 1280 } 1281 1282 if !valid { 1283 check.invalidOp(x.pos(), "cannot slice %s", x) 1284 goto Error 1285 } 1286 1287 x.mode = value 1288 1289 // spec: "Only the first index may be omitted; it defaults to 0." 1290 if e.Slice3 && (e.High == nil || e.Max == nil) { 1291 check.error(e.Rbrack, "2nd and 3rd index required in 3-index slice") 1292 goto Error 1293 } 1294 1295 // check indices 1296 var ind [3]int64 1297 for i, expr := range []ast.Expr{e.Low, e.High, e.Max} { 1298 x := int64(-1) 1299 switch { 1300 case expr != nil: 1301 // The "capacity" is only known statically for strings, arrays, 1302 // and pointers to arrays, and it is the same as the length for 1303 // those types. 1304 max := int64(-1) 1305 if length >= 0 { 1306 max = length + 1 1307 } 1308 if t, ok := check.index(expr, max); ok && t >= 0 { 1309 x = t 1310 } 1311 case i == 0: 1312 // default is 0 for the first index 1313 x = 0 1314 case length >= 0: 1315 // default is length (== capacity) otherwise 1316 x = length 1317 } 1318 ind[i] = x 1319 } 1320 1321 // constant indices must be in range 1322 // (check.index already checks that existing indices >= 0) 1323 L: 1324 for i, x := range ind[:len(ind)-1] { 1325 if x > 0 { 1326 for _, y := range ind[i+1:] { 1327 if y >= 0 && x > y { 1328 check.errorf(e.Rbrack, "invalid slice indices: %d > %d", x, y) 1329 break L // only report one error, ok to continue 1330 } 1331 } 1332 } 1333 } 1334 1335 case *ast.TypeAssertExpr: 1336 check.expr(x, e.X) 1337 if x.mode == invalid { 1338 goto Error 1339 } 1340 xtyp, _ := x.typ.Underlying().(*Interface) 1341 if xtyp == nil { 1342 check.invalidOp(x.pos(), "%s is not an interface", x) 1343 goto Error 1344 } 1345 // x.(type) expressions are handled explicitly in type switches 1346 if e.Type == nil { 1347 check.invalidAST(e.Pos(), "use of .(type) outside type switch") 1348 goto Error 1349 } 1350 T := check.typ(e.Type) 1351 if T == Typ[Invalid] { 1352 goto Error 1353 } 1354 check.typeAssertion(x.pos(), x, xtyp, T) 1355 x.mode = commaok 1356 x.typ = T 1357 1358 case *ast.CallExpr: 1359 return check.call(x, e) 1360 1361 case *ast.StarExpr: 1362 check.exprOrType(x, e.X) 1363 switch x.mode { 1364 case invalid: 1365 goto Error 1366 case typexpr: 1367 x.typ = &Pointer{base: x.typ} 1368 default: 1369 if typ, ok := x.typ.Underlying().(*Pointer); ok { 1370 x.mode = variable 1371 x.typ = typ.base 1372 } else { 1373 check.invalidOp(x.pos(), "cannot indirect %s", x) 1374 goto Error 1375 } 1376 } 1377 1378 case *ast.UnaryExpr: 1379 check.expr(x, e.X) 1380 if x.mode == invalid { 1381 goto Error 1382 } 1383 check.unary(x, e, e.Op) 1384 if x.mode == invalid { 1385 goto Error 1386 } 1387 if e.Op == token.ARROW { 1388 x.expr = e 1389 return statement // receive operations may appear in statement context 1390 } 1391 1392 case *ast.BinaryExpr: 1393 check.binary(x, e, e.X, e.Y, e.Op) 1394 if x.mode == invalid { 1395 goto Error 1396 } 1397 1398 case *ast.KeyValueExpr: 1399 // key:value expressions are handled in composite literals 1400 check.invalidAST(e.Pos(), "no key:value expected") 1401 goto Error 1402 1403 case *ast.ArrayType, *ast.StructType, *ast.FuncType, 1404 *ast.InterfaceType, *ast.MapType, *ast.ChanType: 1405 x.mode = typexpr 1406 x.typ = check.typ(e) 1407 // Note: rawExpr (caller of exprInternal) will call check.recordTypeAndValue 1408 // even though check.typ has already called it. This is fine as both 1409 // times the same expression and type are recorded. It is also not a 1410 // performance issue because we only reach here for composite literal 1411 // types, which are comparatively rare. 1412 1413 default: 1414 panic(fmt.Sprintf("%s: unknown expression type %T", check.fset.Position(e.Pos()), e)) 1415 } 1416 1417 // everything went well 1418 x.expr = e 1419 return expression 1420 1421 Error: 1422 x.mode = invalid 1423 x.expr = e 1424 return statement // avoid follow-up errors 1425 } 1426 1427 // typeAssertion checks that x.(T) is legal; xtyp must be the type of x. 1428 func (check *Checker) typeAssertion(pos token.Pos, x *operand, xtyp *Interface, T Type) { 1429 method, wrongType := assertableTo(xtyp, T) 1430 if method == nil { 1431 return 1432 } 1433 1434 var msg string 1435 if wrongType { 1436 msg = "wrong type for method" 1437 } else { 1438 msg = "missing method" 1439 } 1440 check.errorf(pos, "%s cannot have dynamic type %s (%s %s)", x, T, msg, method.name) 1441 } 1442 1443 func (check *Checker) singleValue(x *operand) { 1444 if x.mode == value { 1445 // tuple types are never named - no need for underlying type below 1446 if t, ok := x.typ.(*Tuple); ok { 1447 assert(t.Len() != 1) 1448 check.errorf(x.pos(), "%d-valued %s where single value is expected", t.Len(), x) 1449 x.mode = invalid 1450 } 1451 } 1452 } 1453 1454 // expr typechecks expression e and initializes x with the expression value. 1455 // The result must be a single value. 1456 // If an error occurred, x.mode is set to invalid. 1457 // 1458 func (check *Checker) expr(x *operand, e ast.Expr) { 1459 check.multiExpr(x, e) 1460 check.singleValue(x) 1461 } 1462 1463 // multiExpr is like expr but the result may be a multi-value. 1464 func (check *Checker) multiExpr(x *operand, e ast.Expr) { 1465 check.rawExpr(x, e, nil) 1466 var msg string 1467 switch x.mode { 1468 default: 1469 return 1470 case novalue: 1471 msg = "%s used as value" 1472 case builtin: 1473 msg = "%s must be called" 1474 case typexpr: 1475 msg = "%s is not an expression" 1476 } 1477 check.errorf(x.pos(), msg, x) 1478 x.mode = invalid 1479 } 1480 1481 // exprWithHint typechecks expression e and initializes x with the expression value; 1482 // hint is the type of a composite literal element. 1483 // If an error occurred, x.mode is set to invalid. 1484 // 1485 func (check *Checker) exprWithHint(x *operand, e ast.Expr, hint Type) { 1486 assert(hint != nil) 1487 check.rawExpr(x, e, hint) 1488 check.singleValue(x) 1489 var msg string 1490 switch x.mode { 1491 default: 1492 return 1493 case novalue: 1494 msg = "%s used as value" 1495 case builtin: 1496 msg = "%s must be called" 1497 case typexpr: 1498 msg = "%s is not an expression" 1499 } 1500 check.errorf(x.pos(), msg, x) 1501 x.mode = invalid 1502 } 1503 1504 // exprOrType typechecks expression or type e and initializes x with the expression value or type. 1505 // If an error occurred, x.mode is set to invalid. 1506 // 1507 func (check *Checker) exprOrType(x *operand, e ast.Expr) { 1508 check.rawExpr(x, e, nil) 1509 check.singleValue(x) 1510 if x.mode == novalue { 1511 check.errorf(x.pos(), "%s used as value or type", x) 1512 x.mode = invalid 1513 } 1514 }