Created
January 20, 2023 19:08
-
-
Save yvern/5c0aa5a47eee8e23f413da418c8b79d7 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 hooks.defrule) | |
(def clara-inserts | |
"The forms we care about, capable of inserting facts." | |
#{'insert! 'insert-all!}) | |
(def descend* | |
"Transducer to descend into inner forms, looling for those we care about, the ones that insert facts. | |
Unfortunately we can't really figure out if someone defines another function that calls `insert!`." | |
(comp (map macroexpand) | |
(drop 1) | |
(filter (some-fn #(some clara-inserts (flatten %)) | |
clara-inserts)) | |
cat)) | |
(defn- check-fact-type | |
[inserts] | |
(some #{:fact-type} (tree-seq coll? seq inserts))) | |
(defn- descend | |
"Recursively checks forms that contain `insert!`s based on whether the verb/head is: | |
`insert!`s (exiting), | |
`let` forms where the body needs to be checked, | |
or any other symbol, meaning a macro/function call around an `insert!`, which could change control flow." | |
[[verb & args]] | |
(case verb | |
(insert! insert-all!) | |
(when-not (every? check-fact-type args) | |
(ex-info "Facts must have the `:fact-type` key" {})) | |
(let clojure.core/let let* clojure.core/let* do clojure.core/do) ; we can add further forms here, but to use as a param we need to use `cond` or write a macro | |
(recur (sequence descend* args)) | |
(-> "`%s` or anything that expands to it is not allowed around `insert!` or `insert-all!` inside a `defrule`" | |
(format verb) | |
(ex-info {})))) | |
(defn defrule | |
[form] | |
(some->> form | |
:node | |
clj-kondo.hooks-api/sexpr | |
(sequence (comp (drop-while (complement #{'=>})) descend*)) | |
descend | |
throw)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment