Skip to content

Commit

Permalink
Added metadata support for defne and friends, with some tests
Browse files Browse the repository at this point in the history
  • Loading branch information
frenchy64 authored and swannodette committed Nov 20, 2011
1 parent 2c8413c commit b47c860
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 9 deletions.
42 changes: 34 additions & 8 deletions src/main/clojure/clojure/core/logic.clj
Original file line number Diff line number Diff line change
Expand Up @@ -1282,13 +1282,39 @@
`(~t
~@(map (handle-clause as) cs)))

(defn- defnm [t n as & cs]
(if-let [tabled? (-> n meta :tabled)]
`(def ~n
(clojure.core.logic.tabled/tabled [~@as]
~(handle-clauses t as cs)))
`(defn ~n [~@as]
~(handle-clauses t as cs))))
;; name-with-attributes by Konrad Hinsen, from clojure.contrib.def
(defn- name-with-attributes
"To be used in macro definitions.
Handles optional docstrings and attribute maps for a name to be defined
in a list of macro arguments. If the first macro argument is a string
it is added as a docstring to name and removed from the macro argument
list. If afterwards the first macro argument is a map, its entries are
added to the name's metadata map and the map is removed from the
macro argument list. The return value is a vector containing the name
with its extended metadata map and the list of unprocessed macro
arguments."
[name macro-args]
(let [[docstring macro-args] (if (string? (first macro-args))
[(first macro-args) (next macro-args)]
[nil macro-args])
[attr macro-args] (if (map? (first macro-args))
[(first macro-args) (next macro-args)]
[{} macro-args])
attr (if docstring
(assoc attr :doc docstring)
attr)
attr (if (meta name)
(conj (meta name) attr)
attr)]
[(with-meta name attr) macro-args]))

(declare tabled)

(defn- defnm [t n & rest]
(let [[n [as & cs]] (name-with-attributes n rest)]
(if-let [tabled? (-> n meta :tabled)]
`(def ~n (tabled [~@as] ~(handle-clauses t as cs)))
`(defn ~n [~@as] ~(handle-clauses t as cs)))))

;; =============================================================================
;; Useful goals
Expand Down Expand Up @@ -1960,4 +1986,4 @@
failure."
[u v]
`(fn [a#]
(!=-verify a# (unify a# ~u ~v))))
(!=-verify a# (unify a# ~u ~v))))
18 changes: 17 additions & 1 deletion src/test/clojure/clojure/core/logic/tests.clj
Original file line number Diff line number Diff line change
Expand Up @@ -1163,4 +1163,20 @@

(deftest test-unify-fail-3
(is (= (run* [p] (fresh [a b c d] (== () b) (== '(1) d) (== (lcons a b) (lcons c d)) (== p [a b c d])))
())))
())))

;; -----------------------------------------------------------------------------
;; Pattern matching functions preserve metadata

(defne ^:tabled dummy
"Docstring"
[x l]
([_ [x . ?tail]])
([_ [?head . ?tail]]
(membero x ?tail)))

(deftest test-metadata-defne
(is (= (-> #'dummy meta :tabled)
true))
(is (= (-> #'dummy meta :doc)
"Docstring")))

0 comments on commit b47c860

Please sign in to comment.