Skip to content

Commit

Permalink
cmd/compile: clearer error when non-bool used as "||" and "&&" operand
Browse files Browse the repository at this point in the history
Fixes #41500

Change-Id: I658d8921b7769b6e4288ca781cbdca5ff14a84ee
Reviewed-on: https://go-review.googlesource.com/c/go/+/255899
Trust: Cuong Manh Le <[email protected]>
Run-TryBot: Cuong Manh Le <[email protected]>
TryBot-Result: Go Bot <[email protected]>
Reviewed-by: Matthew Dempsky <[email protected]>
  • Loading branch information
cuonglm committed Sep 22, 2020
1 parent 8860251 commit 23573d0
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/cmd/compile/internal/gc/typecheck.go
Original file line number Diff line number Diff line change
Expand Up @@ -630,6 +630,22 @@ func typecheck1(n *Node, top int) (res *Node) {
break
}

// For "x == x && len(s)", it's better to report that "len(s)" (type int)
// can't be used with "&&" than to report that "x == x" (type untyped bool)
// can't be converted to int (see issue #41500).
if n.Op == OANDAND || n.Op == OOROR {
if !n.Left.Type.IsBoolean() {
yyerror("invalid operation: %v (operator %v not defined on %s)", n, n.Op, typekind(n.Left.Type))
n.Type = nil
return n
}
if !n.Right.Type.IsBoolean() {
yyerror("invalid operation: %v (operator %v not defined on %s)", n, n.Op, typekind(n.Right.Type))
n.Type = nil
return n
}
}

// ideal mixed with non-ideal
l, r = defaultlit2(l, r, false)

Expand Down
20 changes: 20 additions & 0 deletions test/fixedbugs/issue41500.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// errorcheck

// Copyright 2020 The Go Authors. All rights reserved. Use of this
// source code is governed by a BSD-style license that can be found in
// the LICENSE file.

package p

type s struct {
slice []int
}

func f() {
var x *s

_ = x == nil || len(x.slice) // ERROR "invalid operation: .+ \(operator \|\| not defined on int\)"
_ = len(x.slice) || x == nil // ERROR "invalid operation: .+ \(operator \|\| not defined on int\)"
_ = x == nil && len(x.slice) // ERROR "invalid operation: .+ \(operator && not defined on int\)"
_ = len(x.slice) && x == nil // ERROR "invalid operation: .+ \(operator && not defined on int\)"
}

0 comments on commit 23573d0

Please sign in to comment.