├── LICENSE ├── README.md ├── project.clj ├── src └── restarts │ └── core.clj └── test └── restarts └── core_test.clj /LICENSE: -------------------------------------------------------------------------------- 1 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC 2 | LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM 3 | CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 4 | 5 | 1. DEFINITIONS 6 | 7 | "Contribution" means: 8 | 9 | a) in the case of the initial Contributor, the initial code and 10 | documentation distributed under this Agreement, and 11 | 12 | b) in the case of each subsequent Contributor: 13 | 14 | i) changes to the Program, and 15 | 16 | ii) additions to the Program; 17 | 18 | where such changes and/or additions to the Program originate from and are 19 | distributed by that particular Contributor. A Contribution 'originates' from 20 | a Contributor if it was added to the Program by such Contributor itself or 21 | anyone acting on such Contributor's behalf. Contributions do not include 22 | additions to the Program which: (i) are separate modules of software 23 | distributed in conjunction with the Program under their own license 24 | agreement, and (ii) are not derivative works of the Program. 25 | 26 | "Contributor" means any person or entity that distributes the Program. 27 | 28 | "Licensed Patents" mean patent claims licensable by a Contributor which are 29 | necessarily infringed by the use or sale of its Contribution alone or when 30 | combined with the Program. 31 | 32 | "Program" means the Contributions distributed in accordance with this 33 | Agreement. 34 | 35 | "Recipient" means anyone who receives the Program under this Agreement, 36 | including all Contributors. 37 | 38 | 2. GRANT OF RIGHTS 39 | 40 | a) Subject to the terms of this Agreement, each Contributor hereby grants 41 | Recipient a non-exclusive, worldwide, royalty-free copyright license to 42 | reproduce, prepare derivative works of, publicly display, publicly perform, 43 | distribute and sublicense the Contribution of such Contributor, if any, and 44 | such derivative works, in source code and object code form. 45 | 46 | b) Subject to the terms of this Agreement, each Contributor hereby grants 47 | Recipient a non-exclusive, worldwide, royalty-free patent license under 48 | Licensed Patents to make, use, sell, offer to sell, import and otherwise 49 | transfer the Contribution of such Contributor, if any, in source code and 50 | object code form. This patent license shall apply to the combination of the 51 | Contribution and the Program if, at the time the Contribution is added by the 52 | Contributor, such addition of the Contribution causes such combination to be 53 | covered by the Licensed Patents. The patent license shall not apply to any 54 | other combinations which include the Contribution. No hardware per se is 55 | licensed hereunder. 56 | 57 | c) Recipient understands that although each Contributor grants the licenses 58 | to its Contributions set forth herein, no assurances are provided by any 59 | Contributor that the Program does not infringe the patent or other 60 | intellectual property rights of any other entity. Each Contributor disclaims 61 | any liability to Recipient for claims brought by any other entity based on 62 | infringement of intellectual property rights or otherwise. As a condition to 63 | exercising the rights and licenses granted hereunder, each Recipient hereby 64 | assumes sole responsibility to secure any other intellectual property rights 65 | needed, if any. For example, if a third party patent license is required to 66 | allow Recipient to distribute the Program, it is Recipient's responsibility 67 | to acquire that license before distributing the Program. 68 | 69 | d) Each Contributor represents that to its knowledge it has sufficient 70 | copyright rights in its Contribution, if any, to grant the copyright license 71 | set forth in this Agreement. 72 | 73 | 3. REQUIREMENTS 74 | 75 | A Contributor may choose to distribute the Program in object code form under 76 | its own license agreement, provided that: 77 | 78 | a) it complies with the terms and conditions of this Agreement; and 79 | 80 | b) its license agreement: 81 | 82 | i) effectively disclaims on behalf of all Contributors all warranties and 83 | conditions, express and implied, including warranties or conditions of title 84 | and non-infringement, and implied warranties or conditions of merchantability 85 | and fitness for a particular purpose; 86 | 87 | ii) effectively excludes on behalf of all Contributors all liability for 88 | damages, including direct, indirect, special, incidental and consequential 89 | damages, such as lost profits; 90 | 91 | iii) states that any provisions which differ from this Agreement are offered 92 | by that Contributor alone and not by any other party; and 93 | 94 | iv) states that source code for the Program is available from such 95 | Contributor, and informs licensees how to obtain it in a reasonable manner on 96 | or through a medium customarily used for software exchange. 97 | 98 | When the Program is made available in source code form: 99 | 100 | a) it must be made available under this Agreement; and 101 | 102 | b) a copy of this Agreement must be included with each copy of the Program. 103 | 104 | Contributors may not remove or alter any copyright notices contained within 105 | the Program. 106 | 107 | Each Contributor must identify itself as the originator of its Contribution, 108 | if any, in a manner that reasonably allows subsequent Recipients to identify 109 | the originator of the Contribution. 110 | 111 | 4. COMMERCIAL DISTRIBUTION 112 | 113 | Commercial distributors of software may accept certain responsibilities with 114 | respect to end users, business partners and the like. While this license is 115 | intended to facilitate the commercial use of the Program, the Contributor who 116 | includes the Program in a commercial product offering should do so in a 117 | manner which does not create potential liability for other Contributors. 118 | Therefore, if a Contributor includes the Program in a commercial product 119 | offering, such Contributor ("Commercial Contributor") hereby agrees to defend 120 | and indemnify every other Contributor ("Indemnified Contributor") against any 121 | losses, damages and costs (collectively "Losses") arising from claims, 122 | lawsuits and other legal actions brought by a third party against the 123 | Indemnified Contributor to the extent caused by the acts or omissions of such 124 | Commercial Contributor in connection with its distribution of the Program in 125 | a commercial product offering. The obligations in this section do not apply 126 | to any claims or Losses relating to any actual or alleged intellectual 127 | property infringement. In order to qualify, an Indemnified Contributor must: 128 | a) promptly notify the Commercial Contributor in writing of such claim, and 129 | b) allow the Commercial Contributor tocontrol, and cooperate with the 130 | Commercial Contributor in, the defense and any related settlement 131 | negotiations. The Indemnified Contributor may participate in any such claim 132 | at its own expense. 133 | 134 | For example, a Contributor might include the Program in a commercial product 135 | offering, Product X. That Contributor is then a Commercial Contributor. If 136 | that Commercial Contributor then makes performance claims, or offers 137 | warranties related to Product X, those performance claims and warranties are 138 | such Commercial Contributor's responsibility alone. Under this section, the 139 | Commercial Contributor would have to defend claims against the other 140 | Contributors related to those performance claims and warranties, and if a 141 | court requires any other Contributor to pay any damages as a result, the 142 | Commercial Contributor must pay those damages. 143 | 144 | 5. NO WARRANTY 145 | 146 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON 147 | AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER 148 | EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR 149 | CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A 150 | PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the 151 | appropriateness of using and distributing the Program and assumes all risks 152 | associated with its exercise of rights under this Agreement , including but 153 | not limited to the risks and costs of program errors, compliance with 154 | applicable laws, damage to or loss of data, programs or equipment, and 155 | unavailability or interruption of operations. 156 | 157 | 6. DISCLAIMER OF LIABILITY 158 | 159 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY 160 | CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, 161 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION 162 | LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 163 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 164 | ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE 165 | EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY 166 | OF SUCH DAMAGES. 167 | 168 | 7. GENERAL 169 | 170 | If any provision of this Agreement is invalid or unenforceable under 171 | applicable law, it shall not affect the validity or enforceability of the 172 | remainder of the terms of this Agreement, and without further action by the 173 | parties hereto, such provision shall be reformed to the minimum extent 174 | necessary to make such provision valid and enforceable. 175 | 176 | If Recipient institutes patent litigation against any entity (including a 177 | cross-claim or counterclaim in a lawsuit) alleging that the Program itself 178 | (excluding combinations of the Program with other software or hardware) 179 | infringes such Recipient's patent(s), then such Recipient's rights granted 180 | under Section 2(b) shall terminate as of the date such litigation is filed. 181 | 182 | All Recipient's rights under this Agreement shall terminate if it fails to 183 | comply with any of the material terms or conditions of this Agreement and 184 | does not cure such failure in a reasonable period of time after becoming 185 | aware of such noncompliance. If all Recipient's rights under this Agreement 186 | terminate, Recipient agrees to cease use and distribution of the Program as 187 | soon as reasonably practicable. However, Recipient's obligations under this 188 | Agreement and any licenses granted by Recipient relating to the Program shall 189 | continue and survive. 190 | 191 | Everyone is permitted to copy and distribute copies of this Agreement, but in 192 | order to avoid inconsistency the Agreement is copyrighted and may only be 193 | modified in the following manner. The Agreement Steward reserves the right to 194 | publish new versions (including revisions) of this Agreement from time to 195 | time. No one other than the Agreement Steward has the right to modify this 196 | Agreement. The Eclipse Foundation is the initial Agreement Steward. The 197 | Eclipse Foundation may assign the responsibility to serve as the Agreement 198 | Steward to a suitable separate entity. Each new version of the Agreement will 199 | be given a distinguishing version number. The Program (including 200 | Contributions) may always be distributed subject to the version of the 201 | Agreement under which it was received. In addition, after a new version of 202 | the Agreement is published, Contributor may elect to distribute the Program 203 | (including its Contributions) under the new version. Except as expressly 204 | stated in Sections 2(a) and 2(b) above, Recipient receives no rights or 205 | licenses to the intellectual property of any Contributor under this 206 | Agreement, whether expressly, by implication, estoppel or otherwise. All 207 | rights in the Program not expressly granted under this Agreement are 208 | reserved. 209 | 210 | This Agreement is governed by the laws of the State of New York and the 211 | intellectual property laws of the United States of America. No party to this 212 | Agreement will bring a legal action under this Agreement more than one year 213 | after the cause of action arose. Each party waives its rights to a jury trial 214 | in any resulting litigation. 215 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # restarts 2 | 3 | A Clojure library providing basic Common Lisp style restarts for Clojure. 4 | 5 | [![Clojars Project](http://clojars.org/restarts/latest-version.svg)](http://clojars.org/restarts) 6 | 7 | ## Usage 8 | 9 | ```clojure 10 | (with-restart-handlers {Exception (fn [e] (invoke-restart :continue)) 11 | :foobar (fn [val] (println "Got Value: " val))} 12 | (with-restart-handlers {RuntimeException (fn [e] (throw-restart (Exception. e)))} 13 | (let [x (throw-restart (RuntimeException. "Failure") 14 | (continue [] {:success true}))] 15 | (signal :foobar "Cool Value") 16 | x))) 17 | 18 | Got Value: Cool Value 19 | => {:success true} 20 | ``` 21 | 22 | ### Throwing Errors 23 | 24 | The basic idea is that when throwing an exception, you are able to provide 'restarts.' Restarts are just functions that allow code higher-up on the stack to specify a recovery mechanism if it wants. 25 | 26 | When writing code in any language, the easiest place to recover from an error is where the error happens, but it can be difficult to decide how to best handle errors when different strategies might be desired depending on the situation. 27 | 28 | For example: 29 | A function `(defn parse-config [file] ...)` might have the job of parsing and validating various config files. Depending on the particular config, maybe a missing config value or an extra config value is ok, or maybe it means the config is bad and we have to deal with it. It's hard to decide how to handle that in parse-config. On the one hand, I can throw an exception when I get a config value that doesn't validate. On the other, I can just include the bad config and hope the code above me will take care of it. Neither of these seems particularly desirable, since if you're not careful to know how the underlying function works, you can end up with bad configs or unwanted exceptions. 30 | 31 | Common Lisp style restarts provide a solution to this problem. When you encounter a potential error in a function, you can throw an error, but provide 'restarts' that code higher on the stack can choose to continue with. The value of `(throw-restart ...)` is the return value of the restart that is called. 32 | 33 | In our previous example, `parse-config` might look like: 34 | ```clojure 35 | (defn parse-config [file] 36 | (into {} 37 | (for [[k v] (read-conf file)] 38 | (if (valid? k v) 39 | [k v] 40 | (throw-restart :bad-config 41 | (include [] [k v]) 42 | (reject [] nil) 43 | (replace [x] x)))))) 44 | ``` 45 | or, if you want to use Java Throwables: 46 | ```clojure 47 | (defn parse-config [file] 48 | (into {} 49 | (for [[k v] (read-conf file)] 50 | (if (valid? k v) 51 | [k v] 52 | (throw-restart (Exception. "Bad Config.") 53 | (include [] [k v]) 54 | (reject [] nil) 55 | (replace [x] x)))))) 56 | ``` 57 | 58 | `throw-restart` can also be given a special restart, called `default` which will run if no handlers are set up to handle the error. If we want to include the bad config by default in case no handlers are installed, `parse-config` might look like this: 59 | ```clojure 60 | (defn parse-config [file] 61 | (into {} 62 | (for [[k v] (read-conf file)] 63 | (if (valid? k v) 64 | [k v] 65 | (throw-restart (Exception. "Bad Config.") 66 | (include [] [k v]) 67 | (reject [] nil) 68 | (replace [x] x) 69 | (default [] [k v])))))) 70 | ``` 71 | 72 | Code higher on the stack can wait for a `:bad-config` error and choose to continue by including the bad pair, continue by rejecting it, continue by replacing it, or choose to bail on reading the config altogether. Then the calling function might look like one of these: 73 | ```clojure 74 | (defn do-something-important [] 75 | (let [important-config (with-restart-handlers 76 | ; This is the exception -> handler map. 77 | ; This config is important. It has to be valid. 78 | ; We should throw a Java exception if the config isn't valid. 79 | {:bad-config (fn [e] 80 | (throw RuntimeException. (str "Invalid Config: " file)))} 81 | (parse-config file))] 82 | ...)) 83 | ``` 84 | 85 | Or for throwing a Java Throwable: 86 | ```clojure 87 | (defn do-something-important [] 88 | (let [important-config (with-restart-handlers 89 | ; This is the exception -> handler map. 90 | ; This config is important. It has to be valid. 91 | ; We should throw a Java exception if the config isn't valid. 92 | {Exception (fn [e] 93 | (throw (RuntimeException. 94 | (str "Invalid Config: " file) e)))} 95 | (parse-config file))] 96 | ...)) 97 | ``` 98 | 99 | It could be helpful in this case if the handler could take a look at the value that caused the exception. `throw-restart` lets you throw some data up along with the exception if you want to: 100 | 101 | ```clojure 102 | (defn parse-config [file] 103 | (into {} 104 | (for [[k v] (read-conf file)] 105 | (if (valid? k v) 106 | [k v] 107 | (throw-restart [:bad-config [k v]] 108 | (include [] [k v]) 109 | (reject [] nil) 110 | (replace [x] x) 111 | (default [] [k v])))))) 112 | 113 | (defn parse-config [file] 114 | (into {} 115 | (for [[k v] (read-conf file)] 116 | (if (valid? k v) 117 | [k v] 118 | (throw-restart [(Exception. "Bad Config.") [k v]] 119 | (include [] [k v]) 120 | (reject [] nil) 121 | (replace [x] x) 122 | (default [] [k v])))))) 123 | ``` 124 | 125 | In which case, the handlers might look like this: 126 | 127 | ```clojure 128 | (defn do-something-important [] 129 | (let [important-config (with-restart-handlers 130 | ; This is the exception -> handler map. 131 | ; This config is important. It has to be valid. 132 | ; We should throw a Java exception if the config isn't valid. 133 | {:bad-config (fn [e kv-pair] 134 | (throw RuntimeException. 135 | (str "Invalid Config: " file 136 | " " kv-pair)))} 137 | (parse-config file))] 138 | ...)) 139 | 140 | (defn do-something-important [] 141 | (let [important-config (with-restart-handlers 142 | ; This is the exception -> handler map. 143 | ; This config is important. It has to be valid. 144 | ; We should throw a Java exception if the config isn't valid. 145 | {Exception (fn [e kv-pair] 146 | (throw (RuntimeException. 147 | (str "Invalid Config: " file 148 | " " kv-pair) e)))} 149 | (parse-config file))] 150 | ...)) 151 | ``` 152 | 153 | Handlers can determine what kind of strategy to use for recovery by calling `(invoke-restart ...)`. (replace :bad-config with Exception or any other Throwable if you like): 154 | ```clojure 155 | (defn do-something-not-too-important [] 156 | (let [less-important-config (with-restart-handlers 157 | ; We can check if we want to include this key/value 158 | ; pair and either include or reject it. 159 | {:bad-config (fn [e [k v]] 160 | (if (should-include? k v) 161 | (invoke-restart :include) 162 | (invoke-restart :reject)))} 163 | (parse-config file))] 164 | ...)) 165 | 166 | (defn do-something-else [] 167 | ; Or just call parse-config without catching the errors. 168 | ; Code higher on the stack might have restart handlers. 169 | ; If nobody on the stack has a handler for the error, 170 | ; it'll be handled by the default handler if there is one. 171 | ; If not, it is treated as a regular Java exception. 172 | ; (will be caught by try/catch blocks or kill the program) 173 | (let [config (parse-config file)] 174 | ...)) 175 | ``` 176 | 177 | The last example, where no restart-handlers are defined, one of four things happens: 178 | 179 | 1. A function somewhere on the stack has defined handlers, and it decides which restart to call. 180 | 2. No function on the stack has defined handlers, but `throw-restart` has a `default` handler defined. In this case, the default handler is run. 181 | 3. No function on the stack has defined handlers for the error, no `default` is defined, and the error was a keyword. (i.e. `:bad-config`) In this case, the error is converted into a `RuntimeException` with a string of the keyword as the message and thrown. 182 | 4. No function on the stack has defined handlers for the error, no `default` is defined, and the error was a Java `Throwable`. In this case, the `Throwable` is thrown. 183 | 184 | There. Now we have a way to determine how functions further down the callstack should behave when they encounter issues. Higher-up functions don't have to know how lower functions work, but can still specify how they behave when something goes wrong if they choose. If not, we have a way to describe how a function should continue by default if calling functions don't tell it how to handle the error. 185 | 186 | Furthermore, it's relatively fast. The stack doesn't get unwound unless it needs to be. The function `parse-config` can encounter an error mid-processing and continue without throwing an exception if a caller determines which restart it should use to finish the job. 187 | 188 | ### Signaling events 189 | 190 | There is also a concept of signals in the library. Signals provide another way for code high on the stack to communicate with code lower on the stack. They're less intrusive than errors in that if there's no handler, they go unnoticed rather than being thrown as an exception. Say you have an application where it's not ever important to really validate the config. Someone still might want to be notified when a bad config is read. Signals will allow you to do this without having to write handlers if you don't care to. 191 | 192 | Signals allow you to pass stuff to the handler. Here we're passing the key/value pair that wasn't valid. 193 | 194 | ```clojure 195 | (defn parse-config [file] 196 | (into {} 197 | (for [[k v] (read-conf file)] 198 | (do 199 | (when (not (valid? k v)) 200 | (signal :bad-config [k v])) 201 | [k v])))) 202 | ``` 203 | 204 | When `parse-config` encounters a bad config, it signals with `:bad-config`. (Again, you can use Throwables if you like) Calling functions can listen for this signal if they're interested: 205 | 206 | ```clojure 207 | (defn do-something [] 208 | (let [config (with-restart-handlers 209 | ; This is the exception -> handler map. 210 | ; We're watching for bad-config signals so we can log them. 211 | {:bad-config (fn [[k v]] (log/info (str "Bad config item: " k " -> " v)))} 212 | (parse-config file))] 213 | ...)) 214 | ``` 215 | 216 | Notice the `:bad-config` handler accepts a key/value pair, just what the signal provides as arguments to the handler. 217 | 218 | It can just as easily ignore the signal, never having to know the underlying function was using signals at all: 219 | 220 | ```clojure 221 | (defn do-something [] 222 | ; Just a config. All signals go unnoticed. 223 | (let [config (parse-config file)] 224 | ...)) 225 | ``` 226 | 227 | Of course, a function calling do-something can still listen for the signal if it wants to. 228 | 229 | ```clojure 230 | (defn do-something-else 231 | (with-restart-handlers {:bad-config (fn [[k v]] (log/info "Bad config: " k " -> " v))} 232 | (do-something))) 233 | ``` 234 | 235 | ### More Info 236 | 237 | When writing handlers for keyword exceptions, the keywords must match exactly. Java exceptions, however, work much like they do with the traditional try/catch. If you write a handler for `Exception`, the handler will handle any exceptions of type `Exception` or any subclass of `Exception`. You can provide many handlers with both keyword-exceptions and Java exceptions intermixed. For Java exceptions, where multiple handlers match (For example, a `RuntimeException` is thrown, and both a `RuntimeException` handler and an `Exception` handler are defined), the most specific handler is called. 238 | 239 | ```clojure 240 | (with-restart-handlers {Exception (fn [e] 241 | (println "Caught Exception.") 242 | (invoke-restart :continue)) 243 | RuntimeException (fn [e] 244 | (println "Caught RuntimeException.") 245 | (invoke-restart :continue))} 246 | (throw-restart (RuntimeException. "Runtime!") 247 | (continue [] :success))) 248 | Caught RuntimeException. 249 | => :success 250 | ``` 251 | 252 | Without defining a `RuntimeException` handler, the `Exception` handler is called, since `RuntimeException` inherits from `Exception`. 253 | 254 | ```clojure 255 | (with-restart-handlers {Exception (fn [e] 256 | (println "Caught Exception.") 257 | (invoke-restart :continue))} 258 | (throw-restart (RuntimeException. "Runtime!") 259 | (continue [] :success))) 260 | Caught Exception. 261 | => :success 262 | ``` 263 | 264 | You may have noticed the syntax for handlers includes a name, a vector, and a body. The name is obvious. The vector is an argument list. You may provide additional arguments to `invoke-restart` which will be passed to the restart: 265 | 266 | ```clojure 267 | (with-restart-handlers {Exception (fn [e] 268 | (println "Caught Exception.") 269 | (invoke-restart :continue :foo))} 270 | (throw-restart (RuntimeException. "Runtime!") 271 | (continue [x] x))) 272 | Caught Exception. 273 | => :foo 274 | ``` 275 | 276 | Be careful. You must match the arity of the restart when calling `invoke-restart`. 277 | 278 | ### Safety 279 | 280 | The restart library is thread-safe. Handlers and restarts are provided on a per-thread basis, so they can be used safely virtually anywhere. 281 | 282 | The library is also unintrusive. Code that doesn't interact with it incurs no performance hit at all, even if code somewhere else is using it. Restarts and handlers are only kept around for the lifetime of the dynamic scope they're involved in. 283 | 284 | ### More Reading 285 | 286 | For more on restarts, check out this page: [Practical Common Lisp](http://www.gigamonkeys.com/book/beyond-exception-handling-conditions-and-restarts.html) 287 | 288 | ## License 289 | 290 | Copyright © 2015 Kyle Nusbaum 291 | 292 | Distributed under the Eclipse Public License version 1.0 293 | -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject restarts "0.0.2" 2 | :description "A simple Common Lisp style restart library for Clojure." 3 | :url "http://www.github.com/knusbaum/cl-restart" 4 | :license {:name "Eclipse Public License" 5 | :url "http://www.eclipse.org/legal/epl-v10.html"} 6 | :dependencies [[org.clojure/clojure "1.6.0"]] 7 | :scm {:name "git" 8 | :url "https://github.com/knusbaum/cl-restart.git"}) 9 | -------------------------------------------------------------------------------- /src/restarts/core.clj: -------------------------------------------------------------------------------- 1 | (ns restarts.core) 2 | 3 | (def ^:dynamic handlers {}) 4 | (def ^:dynamic restarts {}) 5 | 6 | (defmacro with-restart-handlers [new-handlers & body] 7 | `(binding [handlers (merge handlers ~new-handlers)] 8 | ~@body)) 9 | 10 | (defmacro invoke-restart [restart & args] 11 | `(let [restart-fn# (restarts ~restart)] 12 | (if restart-fn# 13 | (restart-fn# ~@args) 14 | (throw (RuntimeException. (str "No such restart: " ~restart)))))) 15 | 16 | (defn get-handler-for-instance [handlers instance] 17 | (let [candidates (filter #(isa? (class instance) %) (keys handlers))] 18 | (reduce (fn [acc cls] 19 | (if (isa? cls acc) 20 | cls 21 | acc)) 22 | candidates))) 23 | 24 | (defn handlers-to-map [forms] 25 | (apply 26 | hash-map 27 | (apply concat 28 | (for [restart forms] 29 | (let [restart-name (keyword (first restart)) 30 | arglist (second restart) 31 | body (drop 2 restart)] 32 | [restart-name `(fn ~arglist ~@body)]))))) 33 | 34 | (defmacro throw-restart [e & forms] 35 | (let [[ex & the-rest] 36 | (if (vector? e) 37 | e 38 | [e]) 39 | e-sym (gensym)] 40 | `(let [~e-sym ~ex] 41 | (if (or 42 | (and (keyword? ~e-sym) (contains? handlers ~e-sym)) 43 | (some #(isa? (class ~e-sym) %) (keys handlers))) 44 | (binding [restarts 45 | (merge 46 | restarts 47 | ~(handlers-to-map forms))] 48 | (let [handler-function# 49 | (cond 50 | (keyword? ~e-sym) (handlers ~e-sym) 51 | (isa? (class ~e-sym) 52 | Throwable) (handlers 53 | (get-handler-for-instance 54 | handlers ~e-sym)))] 55 | (handler-function# ~e-sym ~@the-rest))) 56 | (binding [restarts (merge restarts ~(handlers-to-map forms))] 57 | (if (restarts :default) 58 | ((restarts :default)) 59 | (if (isa? (class ~e-sym) Throwable) 60 | (throw ~e-sym) 61 | (throw (RuntimeException. ~e-sym))))))))) 62 | 63 | (defmacro signal [e & args] 64 | (let [e-sym (gensym)] 65 | `(let [~e-sym ~e] 66 | (if (or 67 | (and (keyword? ~e-sym) (contains? handlers ~e-sym)) 68 | (some #(isa? (class ~e-sym) %) (keys handlers))) 69 | (let [handler-function# (if (keyword? ~e-sym) 70 | (handlers ~e-sym) 71 | (handlers (get-handler-for-instance handlers ~e-sym)))] 72 | (handler-function# ~@args)))))) 73 | -------------------------------------------------------------------------------- /test/restarts/core_test.clj: -------------------------------------------------------------------------------- 1 | (ns restarts.core-test 2 | (:require [clojure.test :refer :all] 3 | [restarts.core :refer :all])) 4 | 5 | (defn throw-a-signal [sig] 6 | (signal sig)) 7 | 8 | (deftest signal-test 9 | (testing "Signal works" 10 | (let [v (atom nil)] 11 | (with-restart-handlers 12 | {:some-signal #(reset! v :got-signal)} 13 | (throw-a-signal :some-signal)) 14 | (is @v :got-signal))) 15 | (testing "Nested signal test" 16 | (let [v (atom nil)] 17 | (with-restart-handlers 18 | {:some-signal #(reset! v :got-signal)} 19 | (with-restart-handlers 20 | {:some-other-signal #(reset! v :not-signal)} 21 | (throw-a-signal :some-signal))) 22 | (is @v :got-signal))) 23 | (testing "Nested signal test 2" 24 | (let [v (atom nil)] 25 | (with-restart-handlers 26 | {:some-signal #(reset! v :got-signal)} 27 | (with-restart-handlers 28 | {:some-other-signal #(signal :some-signal)} 29 | (throw-a-signal :some-other-signal))) 30 | (is @v :got-signal)))) 31 | 32 | (deftest throw-test 33 | (testing "Throwing Exception and invoking restart." 34 | (is (= {:success true} 35 | (with-restart-handlers {Exception (fn [^Exception e] (invoke-restart :continue))} 36 | (throw-restart (RuntimeException. "Simulated Failure") 37 | (continue [] {:success true}) 38 | (fail [] {:success false}))))) 39 | (is (= {:success false} 40 | (with-restart-handlers {Exception (fn [^Exception e] (invoke-restart :fail))} 41 | (throw-restart (RuntimeException. "Simulated Failure") 42 | (continue [] {:success true}) 43 | (fail [] {:success false})))))) 44 | (testing "Throwing Exception with no matching handler." 45 | (is (thrown? Exception 46 | (with-restart-handlers {RuntimeException (fn [^Exception e] (invoke-restart :continue))} 47 | (throw-restart (Exception. "Simulated Failure") 48 | (continue [] {:success true}) 49 | (fail [] {:success false})))))) 50 | (testing "Throwing Exception and invoking a bad restart." 51 | (is (thrown? RuntimeException 52 | (with-restart-handlers {Exception (fn [^Exception e] (invoke-restart :not-a-real-restart))} 53 | (throw-restart (Exception. "Simulated Failure") 54 | (continue [] {:success true}) 55 | (fail [] {:success false})))))) 56 | (testing "Throwing keyword errors and invoking restarts." 57 | (is (= {:success true} 58 | (with-restart-handlers {:some-error (fn [e] (invoke-restart :continue))} 59 | (throw-restart :some-error 60 | (continue [] {:success true}) 61 | (fail [] {:success false}))))) 62 | (is (= {:success false} 63 | (with-restart-handlers {:some-error (fn [e] (invoke-restart :fail))} 64 | (throw-restart :some-error 65 | (continue [] {:success true}) 66 | (fail [] {:success false})))))) 67 | (testing "Throwing keyword with no matching handler." 68 | (is (thrown? RuntimeException 69 | (with-restart-handlers {:some-other-error (fn [e] (invoke-restart :continue))} 70 | (throw-restart :some-error 71 | (continue [] {:success true}) 72 | (fail [] {:success false})))))) 73 | (testing "Throwing keyword and invoking a bad restart." 74 | (is (thrown? RuntimeException 75 | (with-restart-handlers {:some-error (fn [e] (invoke-restart :not-a-real-restart))} 76 | (throw-restart :some-error 77 | (continue [] {:success true}) 78 | (fail [] {:success false})))))) 79 | (testing "Default Handlers" 80 | (is (= {:default true} 81 | (with-restart-handlers {:some-other-error (fn [e] (invoke-restart :not-a-real-restart))} 82 | (throw-restart :some-error 83 | (continue [] {:success true}) 84 | (fail [] {:success false}) 85 | (default [] {:default true})))))) 86 | (testing "Default Handlers don't interfere" 87 | (is (= {:success true} 88 | (with-restart-handlers {:some-error (fn [e] (invoke-restart :continue))} 89 | (throw-restart :some-error 90 | (continue [] {:success true}) 91 | (fail [] {:success false}) 92 | (default [] {:default true})))))) 93 | (testing "Vector throws" 94 | (is (= {:success true} 95 | (with-restart-handlers {:some-error (fn [e x] 96 | (invoke-restart :continue x))} 97 | (throw-restart [:some-error true] 98 | (continue [x] {:success x}) 99 | (fail [] {:success false}) 100 | (default [] {:default true}))))) 101 | (is (= {:success true} 102 | (with-restart-handlers {Exception (fn [e x] 103 | (invoke-restart :continue x))} 104 | (throw-restart [(RuntimeException. "foo") true] 105 | (continue [x] {:success x}) 106 | (fail [] {:success false}) 107 | (default [] {:default true}))))))) 108 | 109 | ;; I almost fell for this before. We can't necessarily 110 | ;; determine the type of exception at compile-time, 111 | ;; since the type of exception can be the result of 112 | ;; a function call. 113 | ;; All of the macros have to work on S-expressions of any 114 | ;; resulting type, which can't necessarily be evaluated at 115 | ;; compile-time. 116 | (deftest can-throw-with-vars 117 | (testing "Exceptions can be results of evaluating things within a context." 118 | (is (= {:success true} 119 | (let [v :foo 120 | id-function #(do %)] 121 | (with-restart-handlers {:some-error (fn [e x] 122 | (invoke-restart :continue x))} 123 | (throw-restart [(id-function :some-error) true] 124 | (continue [x] {:success x}) 125 | (fail [] {:success false}) 126 | (default [] {:default true})))))) 127 | (is (= {:success true} 128 | (let [exception-fn (fn [] (Exception.))] 129 | (with-restart-handlers {Exception (fn [e x] 130 | (invoke-restart :continue x))} 131 | (throw-restart [(exception-fn) true] 132 | (continue [x] {:success x}) 133 | (fail [] {:success false}) 134 | (default [] {:default true})))))))) 135 | 136 | --------------------------------------------------------------------------------