Skip to content

Commit a6045ab

Browse files
authored
Add throw-unless-truthy-to-or rule (#462)
Closes #450.
1 parent 2697e4d commit a6045ab

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

default-recommendations/conditional-shortcuts-test.rkt

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,20 @@ test: "refactoring always-throwing cond expressions to when doesn't reformat ent
413413
------------------------------
414414

415415

416+
test: "always-throwing unless before returning condition variable refactorable to or"
417+
--------------------
418+
(define (f s)
419+
(define x (string->number s))
420+
(unless x
421+
(error "string that is not a num"))
422+
x)
423+
--------------------
424+
--------------------
425+
(define (f s)
426+
(or (string->number s) (error "string that is not a num")))
427+
--------------------
428+
429+
416430
test: "cond with nested else-cond can be flattened"
417431
------------------------------
418432
(define (f a b)

default-recommendations/conditional-shortcuts.rkt

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,21 @@
148148
#:original throwing-cond)))))
149149

150150

151+
(define-definition-context-refactoring-rule throw-unless-truthy-to-or
152+
#:description
153+
"Instead of using `unless` to throw an exception if a truthy value is false, consider using `or`."
154+
#:literals (define unless)
155+
(~seq body-before ...
156+
(~and def (define truthy-var:id truthy-expr))
157+
(~and check (unless truthy-var2:id fail:always-throwing-expression))
158+
truthy-var3:id)
159+
#:when (free-identifier=? #'truthy-var #'truthy-var2)
160+
#:when (free-identifier=? #'truthy-var #'truthy-var3)
161+
(body-before ...
162+
(~focus-replacement-on
163+
(~replacement (or truthy-expr fail) #:original-splice (def check truthy-var3)))))
164+
165+
151166
(define-refactoring-rule cond-else-cond-to-cond
152167
#:description
153168
"The `else` clause of this `cond` expression is another `cond` expression and can be flattened."
@@ -230,4 +245,5 @@
230245
if-let-to-cond
231246
if-void-to-when-or-unless
232247
if-x-else-x-to-and
233-
nested-if-to-cond))
248+
nested-if-to-cond
249+
throw-unless-truthy-to-or))

0 commit comments

Comments
 (0)