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