out of options handler
[scpubgit/DKit.git] / lib / DX / State.pm
index 0ee431c..4815ab2 100644 (file)
@@ -1,5 +1,7 @@
 package DX::State;
 
+use Return::MultiLevel qw(with_return);
+use DX::Op::FromCode;
 use Moo;
 
 has next_op => (is => 'ro', required => 1);
@@ -41,6 +43,9 @@ sub backtrack {
     $var->bound_value; $var->clear_bound_value;
     return $state->mark_choice($var) unless $var->bound_stream->is_exhausted;
   }
+  if (our $No_Options_Handler) {
+    $No_Options_Handler->(undef);
+  }
   die "Out of options";
 }
 
@@ -51,10 +56,18 @@ sub then {
 
 sub run {
   my ($state) = @_;
-  while (my $op = $state->next_op) {
-    $state = $op->run($state);
+  with_return {
+    my ($return) = @_;
+    local our $No_Options_Handler = $return;
+    while (my $op = $state->next_op) {
+      $state = $op->run($state);
+    }
+    return $state;
   }
-  return $state;
+}
+
+sub push_backtrack {
+  $_[0]->then(DX::Op::FromCode->new(code => sub { $_[1]->backtrack }));
 }
 
 1;