diff options
author | Robert Griesemer <gri@golang.org> | 2020-02-06 15:32:40 -0800 |
---|---|---|
committer | Robert Griesemer <gri@golang.org> | 2020-02-21 22:57:52 +0000 |
commit | ffc0573b854ca2fc58ad85ad7599ec66f0a82b36 (patch) | |
tree | c9e863a427f9008fd6caf57e90268ec3648ff495 /src/cmd/compile/internal/syntax | |
parent | d532d5f0fade2630612a5bdb0ac3f95824266ad5 (diff) | |
download | go-ffc0573b854ca2fc58ad85ad7599ec66f0a82b36.tar.gz go-ffc0573b854ca2fc58ad85ad7599ec66f0a82b36.zip |
cmd/compile/internal/syntax: better error when an assignment is used in value context
The error message is now positioned at the statement position (which is
an identifing token, such as the '=' for assignments); and in case of
assignments it emphasizes the assignment by putting the Lhs and Rhs
in parentheses. Finally, the wording is changed from "use of * as value"
to the stronger "cannot use * as value" (for which there is precedent
elsewhere in the parser).
Fixes #36858.
Change-Id: Ic3f101bba50f58e3a1d9b29645066634631f2d61
Reviewed-on: https://go-review.googlesource.com/c/go/+/218337
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
Diffstat (limited to 'src/cmd/compile/internal/syntax')
-rw-r--r-- | src/cmd/compile/internal/syntax/parser.go | 11 | ||||
-rw-r--r-- | src/cmd/compile/internal/syntax/testdata/issue23385.src | 9 |
2 files changed, 15 insertions, 5 deletions
diff --git a/src/cmd/compile/internal/syntax/parser.go b/src/cmd/compile/internal/syntax/parser.go index f3c2c60ec8..469d9ad69b 100644 --- a/src/cmd/compile/internal/syntax/parser.go +++ b/src/cmd/compile/internal/syntax/parser.go @@ -1886,11 +1886,16 @@ done: // which turns an expression into an assignment. Provide // a more explicit error message in that case to prevent // further confusion. - str := String(s) + var str string if as, ok := s.(*AssignStmt); ok && as.Op == 0 { - str = "assignment " + str + // Emphasize Lhs and Rhs of assignment with parentheses to highlight '='. + // Do it always - it's not worth going through the trouble of doing it + // only for "complex" left and right sides. + str = "assignment (" + String(as.Lhs) + ") = (" + String(as.Rhs) + ")" + } else { + str = String(s) } - p.syntaxError(fmt.Sprintf("%s used as value", str)) + p.syntaxErrorAt(s.Pos(), fmt.Sprintf("cannot use %s as value", str)) } p.xnest = outer diff --git a/src/cmd/compile/internal/syntax/testdata/issue23385.src b/src/cmd/compile/internal/syntax/testdata/issue23385.src index 44abcd7e23..2459a7369b 100644 --- a/src/cmd/compile/internal/syntax/testdata/issue23385.src +++ b/src/cmd/compile/internal/syntax/testdata/issue23385.src @@ -6,7 +6,12 @@ package p -func f() { - if true || 0 = 1 /* ERROR assignment .* used as value */ { +func _() { + if true || 0 /* ERROR cannot use assignment .* as value */ = 1 { + } +} + +func _(a, b string) { + if a == "a" && b /* ERROR cannot use assignment .* as value */ = "b" { } } |