Skip to content

Commit

Permalink
fix #684: support print-method on records (#685)
Browse files Browse the repository at this point in the history
  • Loading branch information
borkdude authored Mar 5, 2022
1 parent 84bad66 commit b782d43
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
15 changes: 14 additions & 1 deletion src/sci/impl/io.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,25 @@
{:no-doc true}
(:refer-clojure :exclude [pr prn pr-str prn-str print print-str println
newline flush with-out-str with-in-str read-line
printf #?@(:cljs [string-print])])
printf #?@(:cljs [string-print])
print-method])
(:require #?(:cljs [goog.string])
[sci.impl.records]
[sci.impl.unrestrict :refer [*unrestricted*]]
#?(:cljs [sci.impl.utils :as utils])
[sci.impl.vars :as vars]))

#?(:clj
(defmulti print-method (fn [x _writer]
(if (instance? sci.impl.records.SciRecord x)
(-> x meta :type)
:default))))

#?(:clj
(defmethod print-method :default
[x writer]
(clojure.core/print-method x writer)))

#?(:clj (set! *warn-on-reflection* true))

(defn core-dynamic-var
Expand Down
2 changes: 1 addition & 1 deletion src/sci/impl/namespaces.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -834,7 +834,7 @@
'pr-str (copy-core-var io/pr-str)
'prn-str (copy-core-var io/prn-str)
'print-str (copy-core-var #?(:cljs io/print-str :clj print-str))
#?@(:clj ['print-method (copy-core-var print-method)])
#?@(:clj ['print-method (copy-core-var io/print-method)])
#?@(:clj ['print-dup (copy-core-var print-dup)])
#?@(:clj ['printf (copy-core-var io/printf)])
'with-out-str (macrofy 'with-out-str io/with-out-str)
Expand Down
5 changes: 5 additions & 0 deletions test/sci/records_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -164,3 +164,8 @@
(deftest roundtrip-test
(let [prog "(ns foo) (defrecord A [x y z]) (str [#foo.A{:x 1 :y 2 :z 3} (read-string \"#foo.A{:x 1 :y 2 :z 3}\")])"]
(is (= "[#foo.A{:x 1, :y 2, :z 3} #foo.A{:x 1, :y 2, :z 3}]" (tu/eval* prog {})))))

#?(:clj
(deftest print-method-test
(let [prog "(ns foo) (defrecord A [x y z]) (defmethod print-method A [x writer] (.write writer \"<A>\")) (pr-str (->A 1))"]
(is (= "<A>" (tu/eval* prog {}))))))

0 comments on commit b782d43

Please sign in to comment.