-
-
Save anonymous/4e7a7c13167f86d3c67a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns foo.core | |
(:require-macros [foo.macros :refer [with-open]]) | |
(:require [cljs.nodejs :as nodejs])) | |
(nodejs/enable-util-print!) | |
(def foo | |
(reify | |
Object | |
(close [_] (println "closing!")))) | |
; (with-open [f foo] (+ 1 1)) ;=> #object[TypeError TypeError: Cannot read property 'macros' of undefined] | |
(defn -main [& args] nil) | |
(set! *main-cli-fn* -main) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns foo.macros | |
(:refer-clojure :exclude [with-open])) | |
(defmacro with-open | |
"bindings => [name init ...] | |
Evaluates body in a try expression with names bound to the values | |
of the inits, and a finally clause that calls (.close name) on each | |
name in reverse order." | |
[bindings & body] | |
(assert (vector? bindings) "a vector for its binding") | |
(assert (even? (count bindings)) "an even number of forms in binding vector") | |
(cond | |
(= (count bindings) 0) `(do ~@body) | |
(symbol? (bindings 0)) `(let ~(subvec bindings 0 2) | |
(try | |
(with-open ~(subvec bindings 2) ~@body) | |
(finally | |
(. ~(bindings 0) close)))) | |
:else (throw #?(:cljs (js/Error. "with-open only allows Symbols in bindings") | |
:clj (IllegalArgumentException. | |
"with-open only allows Symbols in bindings"))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment