Skip to content

Instantly share code, notes, and snippets.

/core.cljs Secret

Created December 20, 2015 20:14
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save anonymous/4e7a7c13167f86d3c67a to your computer and use it in GitHub Desktop.
(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)
(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