]> Cypherpunks repositories - gostls13.git/commitdiff
go/types: add test case for incorrect map index expression
authorRobert Griesemer <gri@golang.org>
Tue, 17 Nov 2020 06:23:48 +0000 (22:23 -0800)
committerRobert Griesemer <gri@golang.org>
Tue, 17 Nov 2020 22:57:34 +0000 (22:57 +0000)
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>
src/go/types/expr.go
src/go/types/testdata/expr3.src

index 1f8b94640743984326ad85abfd04f5e8cb2785b8..11f94112846602d5652edb4f9c3738562a7aaa7e 100644 (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
index 6f2201c3656c1d18bfbc249204f2c5b6742cedb3..e6777aad2bbb4fc5bf4a895a406d9c62756287b9 100644 (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]