Skip to content

Commit

Permalink
Add rule for rand(Bool) instead of rand() < 0.5
Browse files Browse the repository at this point in the history
  • Loading branch information
iuliadmtru committed Sep 1, 2024
1 parent 9322f67 commit b692572
Show file tree
Hide file tree
Showing 3 changed files with 103 additions and 0 deletions.
40 changes: 40 additions & 0 deletions rules/lang/best-practice/rand_bool.fixed.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#ruleid: rand-bool
rand(Bool)

function some_rand_function(x)
#ruleid: rand-bool
if rand(Bool)
println("Random")
end
end

#ok: rand-bool
rand() < 0.7 # this is fine

x = rand()
#ruleid: rand-bool
if rand(Bool)
do_something()
else
do_something_else()
end

#ok: rand-bool
y = ok()
if y < 0.5
do_something()
else
do_something_else()
end

#ruleid: rand-bool
rand(Bool) && action()

#ok: rand-bool
flag = rand(Bool)

#ruleid: rand-bool
if some_flag && rand(Bool) || other_flag
println("Random")
end

40 changes: 40 additions & 0 deletions rules/lang/best-practice/rand_bool.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#ruleid: rand-bool
rand() < 0.5

function some_rand_function(x)
#ruleid: rand-bool
if rand() < 0.5
println("Random")
end
end

#ok: rand-bool
rand() < 0.7 # this is fine

x = rand()
#ruleid: rand-bool
if x < 0.5
do_something()
else
do_something_else()
end

#ok: rand-bool
y = ok()
if y < 0.5
do_something()
else
do_something_else()
end

#ruleid: rand-bool
x < 0.5 && action()

#ok: rand-bool
flag = rand(Bool)

#ruleid: rand-bool
if some_flag && rand() < 0.5 || other_flag
println("Random")
end

23 changes: 23 additions & 0 deletions rules/lang/best-practice/rand_bool.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
rules:
- id: rand-bool
patterns:
- pattern-either:
- pattern: $RAND() < 0.5
- patterns:
- pattern-inside: |
$X = $RAND()
...
<... $X < 0.5 ...>
- pattern: $X < 0.5
- metavariable-regex:
metavariable: $RAND
regex: '(Base.)?rand'
fix: rand(Bool)
message: To get a random Boolean, use `rand(Bool)`.
languages:
- julia
severity: WARNING
metadata:
category: best-practice
license: LGPL

0 comments on commit b692572

Please sign in to comment.