Skip to content

Commit 85fb4cf

Browse files
committed
add Catch and Throw as builtins
1 parent bd6b9e7 commit 85fb4cf

2 files changed

Lines changed: 37 additions & 8 deletions

File tree

mathics/builtin/control.py

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@
1010
from mathics.builtin.base import Builtin, BinaryOperator
1111
from mathics.core.expression import Expression, Symbol, from_python
1212
from mathics.core.evaluation import (
13-
AbortInterrupt, BreakInterrupt, ContinueInterrupt, ReturnInterrupt)
13+
AbortInterrupt, BreakInterrupt, ContinueInterrupt, ReturnInterrupt,
14+
WLThrowInterrupt)
1415
from mathics.builtin.lists import _IterationFunction
1516
from mathics.builtin.patterns import match
1617

@@ -732,7 +733,7 @@ class Catch(Builtin):
732733
<dt>'Catch[`expr`, `form`]'
733734
<dd> returns value from the first Throw[`value`,`tag`] for which form matches `tag`.
734735
735-
<dt>'Catch[`expr`,`form`,`f`]'
736+
<dt>'Catch[`expr`,`form`, `f`]'
736737
<dd> returns the argument of the first `Throw` generated in the evaluation of `expr`.
737738
</dl>
738739
@@ -751,9 +752,25 @@ class Catch(Builtin):
751752
752753
"""
753754

754-
def apply(self, expr, form, f, evaluation):
755-
'Catch[expr_, form_:___, f__:Identity]'
756-
print("setting a Catch point")
755+
def apply1(self, expr, evaluation):
756+
'Catch[expr_]'
757+
try:
758+
ret = expr.evaluate(evaluation)
759+
except WLThrowInterrupt as e:
760+
return e.value
761+
return ret
762+
763+
764+
def apply3(self, expr, form, f, evaluation):
765+
'Catch[expr_, form_, f__:Identity]'
766+
try:
767+
ret = expr.evaluate(evaluation)
768+
except WLThrowInterrupt as e:
769+
# TODO: check that form match tag.
770+
# otherwise, re-raise the exception
771+
return Expression(f, e.value)
772+
return ret
773+
757774

758775

759776
class Throw(Builtin):
@@ -777,8 +794,13 @@ class Throw(Builtin):
777794
"""
778795
messages = {'nocatch': 'Uncaught `1` returned to top level.', }
779796

780-
def apply(self, value, tag, evaluation):
781-
'Throw[value_, tag__:Null]'
782-
print ("Throw")
797+
def apply1(self, value, evaluation):
798+
'Throw[value_]'
799+
raise WLThrowInterrupt(value)
800+
801+
def apply2(self, value, tag, evaluation):
802+
'Throw[value_, tag_]'
803+
raise WLThrowInterrupt(value, tag)
804+
783805

784806

mathics/core/evaluation.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,13 @@ class BreakInterrupt(EvaluationInterrupt):
5050
class ContinueInterrupt(EvaluationInterrupt):
5151
pass
5252

53+
class WLThrowInterrupt(EvaluationInterrupt):
54+
def __init__(self, value, tag=None):
55+
self.tag = tag
56+
self.value = value
57+
58+
59+
5360

5461
def _thread_target(request, queue) -> None:
5562
try:

0 commit comments

Comments
 (0)