Skip to content

Commit

Permalink
Avoid runtime reflection
Browse files Browse the repository at this point in the history
  • Loading branch information
borkdude committed Sep 24, 2024
1 parent 16b97a8 commit 6a94cbd
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 9 deletions.
22 changes: 18 additions & 4 deletions src/nextjournal/markdown/impl.clj
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,18 @@
z/up (z/edit assoc :type :todo-list)
z/down z/rightmost))

(def clazzes (atom #{}))

(comment
@clazzes
)

(def ^:private visitChildren-meth
;; cached reflection only happens once
(delay (let [meth (.getDeclaredMethod AbstractVisitor "visitChildren" (into-array [Node]))]
(.setAccessible meth true)
meth)))

(defn node->data [{:as ctx-in :keys [footnotes]} ^Node node]
(assert (:type ctx-in) ":type must be set on initial doc")
(assert (:content ctx-in) ":content must be set on initial doc")
Expand Down Expand Up @@ -249,10 +261,12 @@

;; else branch nodes
(if (get-method open-node (class node))
(with-tight-list node
(swap! !ctx open-node node)
(proxy-super visitChildren node)
(swap! !ctx close-node node))
(do
(swap! clazzes conj (class node))
(with-tight-list node
(swap! !ctx open-node node)
(.invoke ^java.lang.reflect.Method @visitChildren-meth this (into-array Object [node]))
(swap! !ctx close-node node)))
(prn ::not-implemented node))))))

(let [{:as ctx-out :keys [doc title toc footnotes] ::keys [label->footnote-ref]} (deref !ctx)]
Expand Down
14 changes: 9 additions & 5 deletions src/nextjournal/markdown/impl/types.clj
Original file line number Diff line number Diff line change
@@ -1,29 +1,33 @@
(ns nextjournal.markdown.impl.types
(:import [nextjournal.markdown.impl.types CustomNode]))
(ns nextjournal.markdown.impl.types)

;; See also
;; https://github.com/noties/Markwon/blob/master/markwon-ext-latex/src/main/java/io/noties/markwon/ext/latex/JLatexMathBlockParser.java

(set! *warn-on-reflection* true)

(definterface CustomNode
(getLiteral [])
(setLiteral [v])
(nodeType []))

(defn ->InlineFormula [lit]
(let [state (atom lit)]
(proxy [org.commonmark.node.CustomNode CustomNode] []
(proxy [org.commonmark.node.CustomNode nextjournal.markdown.impl.types.CustomNode] []
(getLiteral [] @state)
(nodeType [] :inline-formula))))

(defn ->BlockFormula
([] (->BlockFormula nil))
([lit]
(let [state (atom lit)]
(proxy [org.commonmark.node.CustomBlock CustomNode] []
(proxy [org.commonmark.node.CustomBlock nextjournal.markdown.impl.types.CustomNode] []
(getLiteral [] @state)
(setLiteral [v] (do (reset! state v)
this))
(nodeType [] :block-formula)))))

(defn ->ToC []
(proxy [org.commonmark.node.CustomBlock CustomNode] []
(proxy [org.commonmark.node.CustomBlock nextjournal.markdown.impl.types.CustomNode] []
(nodeType [] :toc)))

(defn setLiteral [^CustomNode n lit]
Expand Down

0 comments on commit 6a94cbd

Please sign in to comment.