Skip to content

Commit 58b1491

Browse files
authored
Merge pull request #1605 from iacore/patch-2
Patch try to accept (try body ([] catch-body))
2 parents 21a6ed3 + e815c91 commit 58b1491

File tree

1 file changed

+17
-16
lines changed

1 file changed

+17
-16
lines changed

src/boot/boot.janet

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -290,22 +290,6 @@
290290
(array/concat accum body)
291291
(tuple/slice accum 0))
292292

293-
(defmacro try
294-
``Try something and catch errors. `body` is any expression,
295-
and `catch` should be a form, the first element of which is a tuple. This tuple
296-
should contain a binding for errors and an optional binding for
297-
the fiber wrapping the body. Returns the result of `body` if no error,
298-
or the result of `catch` if an error.``
299-
[body catch]
300-
(let [[[err fib]] catch
301-
f (gensym)
302-
r (gensym)]
303-
~(let [,f (,fiber/new (fn :try [] ,body) :ie)
304-
,r (,resume ,f)]
305-
(if (,= (,fiber/status ,f) :error)
306-
(do (def ,err ,r) ,(if fib ~(def ,fib ,f)) ,;(tuple/slice catch 1))
307-
,r))))
308-
309293
(defmacro protect
310294
`Evaluate expressions, while capturing any errors. Evaluates to a tuple
311295
of two elements. The first element is true if successful, false if an
@@ -352,6 +336,23 @@
352336
(tuple 'if $fi $fi ret))))))
353337
ret)
354338

339+
(defmacro try
340+
``Try something and catch errors. `body` is any expression,
341+
and `catch` should be a form, the first element of which is a tuple. This tuple
342+
should contain a binding for errors and an optional binding for
343+
the fiber wrapping the body. Returns the result of `body` if no error,
344+
or the result of `catch` if an error.``
345+
[body catch]
346+
(assert (and (not (empty? catch)) (indexed? (catch 0))) "the first element of `catch` must be a tuple or array")
347+
(let [[err fib] (catch 0)
348+
r (or err (gensym))
349+
f (or fib (gensym))]
350+
~(let [,f (,fiber/new (fn :try [] ,body) :ie)
351+
,r (,resume ,f)]
352+
(if (,= (,fiber/status ,f) :error)
353+
(do ,;(tuple/slice catch 1))
354+
,r))))
355+
355356
(defmacro with-syms
356357
"Evaluates `body` with each symbol in `syms` bound to a generated, unique symbol."
357358
[syms & body]

0 commit comments

Comments
 (0)