Skip to content

Commit

Permalink
fix: boolean operations must have boolean operands (gnolang#1451)
Browse files Browse the repository at this point in the history
<!-- please provide a detailed description of the changes made in this
pull request. -->
Addresses gnolang#1083

This fixes an issue where there was no enforcement of operand types when
doing boolean operations. The correct approach should be to verify
boolean operand type expressions also evaluate to boolean typed values
before proceeding. This prevents any of the behavior described in the
issue that this PR addresses.

<details><summary>Contributors' checklist...</summary>

- [x] Added new tests, or not needed, or not feasible
- [x] Provided an example (e.g. screenshot) to aid review or the PR is
self-explanatory
- [x] Updated the official documentation or not needed
- [x] No breaking changes were made, or a `BREAKING CHANGE: xxx` message
was included in the description
- [x] Added references to related issues and PRs
- [ ] Provided any useful hints for running manual tests
- [ ] Added new benchmarks to [generated
graphs](https://gnoland.github.io/benchmarks), if any. More info
[here](https://github.com/gnolang/gno/blob/master/.benchmarks/README.md).
</details>
  • Loading branch information
deelawn authored and gfanton committed Jan 18, 2024
1 parent bcc5c1c commit aa3a84e
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
7 changes: 7 additions & 0 deletions gnovm/pkg/gnolang/preprocess.go
Original file line number Diff line number Diff line change
Expand Up @@ -755,6 +755,13 @@ func Preprocess(store Store, ctx BlockNode, n Node) Node {
resn := Preprocess(store, last, n2)
return resn, TRANS_CONTINUE
}

// Left and right hand expressions must evaluate to a boolean typed value if
// the operation is a logical AND or OR.
if (n.Op == LAND || n.Op == LOR) && (lt.Kind() != BoolKind || rt.Kind() != BoolKind) {
panic("operands of boolean operators must evaluate to boolean typed values")
}

// General case.
lcx, lic := n.Left.(*ConstExpr)
rcx, ric := n.Right.(*ConstExpr)
Expand Down
12 changes: 12 additions & 0 deletions gnovm/tests/files/bool6.gno
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package main

func main() {
println(X())
}

func X() string {
return "hello" || "world"
}

// Error:
// main/files/bool6.gno:8: operands of boolean operators must evaluate to boolean typed values
16 changes: 16 additions & 0 deletions gnovm/tests/files/bool7.gno
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package main

// Ensure, when comparing evaluated boolean operand types, that the kinds produced
// are the same when one operand is typed and the other is untyped.
func main() {
println(boolAndTrue(true))
println(boolAndTrue(false))
}

func boolAndTrue(b bool) bool {
return b && true
}

// Output:
// true
// false

0 comments on commit aa3a84e

Please sign in to comment.