go/types: add test case for incorrect map index expression

The existing code for map index expressions checked the
wrong variable (x rather than key) to see if the index
assignment was correct. Since x.mode was always valid in
that case, type-checking didn't follow the error exit in
case of an incorrect map index expression.

However, since we know the correct map element type
irrespective of the validity of the map key, the existing
code path is preferrable over exiting early via an error
because the map index expression returns a valid type which
then can be used for further type-checking.

Removed the unneeded 'if' statement and added a test case
producing the expected two errors (rather than only one if
we would "correct" the 'if' statement instead).

In summary, this commit adds a test but doesn't change the
behavior of type-checking of map index expressions.

Change-Id: I67845bfaa03600c9400f9a1462d7a68a66921ad4
Reviewed-on: https://go-review.googlesource.com/c/go/+/270658
Trust: Robert Griesemer <gri@golang.org>
Run-TryBot: Robert Griesemer <gri@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Robert Findley <rfindley@google.com>
This commit is contained in:
Robert Griesemer 2020-11-16 22:23:48 -08:00
parent 05082c90d5
commit 041a4e4c34
2 changed files with 2 additions and 3 deletions

View file

@ -1357,9 +1357,7 @@ func (check *Checker) exprInternal(x *operand, e ast.Expr, hint Type) exprKind {
var key operand
check.expr(&key, e.Index)
check.assignment(&key, typ.key, "map index")
if x.mode == invalid {
goto Error
}
// ok to continue even if indexing failed - map element type is known
x.mode = mapindex
x.typ = typ.elem
x.expr = e

View file

@ -102,6 +102,7 @@ func indexes() {
var ok mybool
_, ok = m["bar"]
_ = ok
_ = m[0 /* ERROR "cannot use 0" */ ] + "foo" // ERROR "cannot convert"
var t string
_ = t[- /* ERROR "negative" */ 1]