Cond
Description
Resolve errors without unwinding the stack.
Synopsis
require 'cond'
include Cond
def divide(x, y)
restartable do
restart :return_this_instead do |value|
return value
end
raise ZeroDivisionError if y == 0
x/y
end
end
handling do
handle ZeroDivisionError do
invoke_restart :return_this_instead, 42
end
puts divide(10, 2) # => 5
puts divide(18, 3) # => 6
puts divide(4, 0) # => 42
puts divide(7, 0) # => 42
end
Install
% gem install cond
or
% ruby install.rb [--uninstall]
Overview
Cond allows errors to be handled near the place where they occur, before the stack unwinds. It offers several advantages over exceptions while peacefully coexisting with the standard exception behavior.
The system is divided into two parts: restarts and handlers. When raise
is called and there is a matching handler for the error, the normal mechanism of unwinding the stack is suspended while the handler is called instead. At this time, the handler may invoke one of the available restarts.
(1) program start (stack begin) --> +
|
|
|
|<-- handler_a
|
(2) handlers are set up -------> |<-- handler_b
|
|<-- handler_c -----+
| . |
| /|\ |
| | |
| | | (5) handler
| | | calls
| | | restart
| | |
+--------->------------- | ------+ |
| | (4) exception |
| | sent to |
| | handler |
| | |
| | |
| |<-- restart_x |
^ | |
|<-- restart_y <----+
(3) raise called here here ------> |
+<-- restart_z
A handler may find a way to negate the problem and, by invoking a restart, allow execution to continue from a place proximal to where raise
was called. Or a handler may choose to allow the exception to propagate in the usual unwinding fashion, as if the handler was never called.
Cond is 100% compatible with the built-in exception-handling system. We may imagine that Ruby had this handler/restart functionality from the very beginning, but everyone had forgotten to write restarts. And since no restarts were available, no handlers were written.
Background
Cond is stolen from the Common Lisp condition system.
Peter Seibel discusses the advantages of handlers and restarts in the following video. I have fast-forwarded to the most relevant part, though the whole talk is worthwhile.
video.google.com/videoplay?docid=448441135356213813#46m07s
The example he shows is taken from his book on Lisp,
www.gigamonkeys.com/book/beyond-exception-handling-conditions-and-restarts.html
See readmes/seibel_pcl.rb for a Ruby translation.
Synopsis 2.0
x, y = 7, 0
handling do
handle ZeroDivisionError do |exception|
invoke_restart :return_this_instead, 42
end
result = restartable do
restart :return_this_instead do |value|
leave value
end
raise ZeroDivisionError if y == 0
x/y
end
puts result # => 42
end
leave
acts like return
for the current handling
or restartable
block. Its counterpart is again
, which acts like redo
for the current handling
or restartable
block. These blocks may be nested arbitrarily.
leave
and again
are for convenience only. They remove the need for repetitive catch blocks and prevent symbol collisions for nested catch labels.
A default handler is provided which runs a simple choose-a-restart input loop when raise
is called, as the next example demonstrates.
Restart Example
require 'pp'
require 'cond'
include Cond
class RestartableFetchError < RuntimeError
end
def read_new_value(what)
print("Enter a new #{what}: ")
eval($stdin.readline.chomp)
end
def restartable_fetch(hash, key, default = nil)
restartable do
restart :continue, "Return not having found the value." do
return default
end
restart :try_again, "Try getting the key from the hash again." do
again
end
restart :use_new_key, "Use a new key." do
key = read_new_value("key")
again
end
restart :use_new_hash, "Use a new hash." do
hash = read_new_value("hash")
again
end
hash.fetch(key) {
raise RestartableFetchError,
"Error getting #{key.inspect} from:\n#{hash.pretty_inspect}"
}
end
end
fruits_and_vegetables = Hash[*%w[
apple fruit
orange fruit
lettuce vegetable
tomato depends_on_who_you_ask
]]
Cond.with_default_handlers {
puts("value: " + restartable_fetch(fruits_and_vegetables, "mango").inspect)
}
Run:
% ruby readmes/restarts.rb
readmes/restarts.rb:49:in `<main>'
Error getting "mango" from:
{"apple"=>"fruit",
"orange"=>"fruit",
"lettuce"=>"vegetable",
"tomato"=>"depends_on_who_you_ask"}
0: Return not having found the value. (:continue)
1: Try getting the key from the hash again. (:try_again)
2: Use a new hash. (:use_new_hash)
3: Use a new key. (:use_new_key)
Choose number: 3
Enter a new key: "apple"
value: "fruit"
% ruby readmes/restarts.rb
readmes/restarts.rb:49:in `<main>'
Error getting "mango" from:
{"apple"=>"fruit",
"orange"=>"fruit",
"lettuce"=>"vegetable",
"tomato"=>"depends_on_who_you_ask"}
0: Return not having found the value. (:continue)
1: Try getting the key from the hash again. (:try_again)
2: Use a new hash. (:use_new_hash)
3: Use a new key. (:use_new_key)
Choose number: 2
Enter a new hash: { "mango" => "mangoish fruit" }
value: "mangoish fruit"
Translated to Ruby from c2.com/cgi/wiki?LispRestartExample
Technical Notes
Cond has been tested on MRI 1.8.6, 1.8.7, 1.9, and the latest jruby.
Each thread keeps its own list of handlers, restarts, and other data. All operations are fully thread-safe.
It is not required to include Cond
. The includable methods of Cond
are module_function
s and are thus callable via e.g. Cond.handling
.
Cond
nests private modules and classes inside Cond::CondPrivate in order to improve the hygiene of include Cond
and encourage its use.
Except for the redefinition raise
, Cond does not silently modify any of the standard classes
The essential implementation is small and simple: it consists of two per-thread stacks of hashes (handlers and restarts) with merge-push and pop operations. The syntax shown in the above examples is a thin layer concealing the underlying hashes. It is equivalent to the following raw form. You are free to use either form according to preference or circumstance.
Raw Form
require 'cond'
def divide(x, y)
restarts = {
:return_this_instead => lambda { |value|
throw :leave, value
}
}
catch :leave do
Cond.with_restarts restarts do
raise ZeroDivisionError if y == 0
x/y
end
end
end
handlers = {
ZeroDivisionError => lambda { |exception|
Cond.invoke_restart :return_this_instead, 42
}
}
Cond.with_handlers handlers do
puts divide(10, 2) # => 5
puts divide(18, 3) # => 6
puts divide(4, 0) # => 42
puts divide(7, 0) # => 42
end
Limitations
There must be a call to raise
inside Ruby code (as opposed to C code) for a handler to be invoked.
The above synopsis gives an example: Why is there a check for division by zero when ZeroDivisionError
would be raised anyway? Because Fixnum#/
is written in C.
It is still possible for handlers to intercept these raises, but it requires redefining a wrapped version of the method in question:
Cond.wrap_instance_method(Fixnum, :/)
Once this has been called, the line
raise ZeroDivisionError if y == 0
is unnecessary.
It is possible remove this limitation by modifying the Ruby interpreter to call Kernel#raise dynamically.
Links
-
Documentation: cond.rubyforge.org
-
Rubyforge home: rubyforge.org/projects/cond/
-
Download: rubyforge.org/frs/?group_id=7916
-
Repository: github.com/quix/cond/tree/master
Author
-
James M. Lawrence < [email protected] >
License
Copyright © 2009 James M. Lawrence. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ‘Software’), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.