1
0
mirror of https://github.com/janet-lang/janet synced 2024-11-17 06:04:49 +00:00
janet/lib/pp.dst
2018-03-13 16:40:56 -04:00

53 lines
1.3 KiB
Plaintext

# Implements a simple pretty printer. Offers similar functionality
# as the describe function.
(defn- pp-seq [pp seen buf a start end]
(if (get seen a)
(buffer-push-string buf "<cycle>")
(do
(put seen a true)
(def len (length a))
(buffer-push-string buf start)
(for [i 0 len]
(when (not= i 0) (buffer-push-string buf " "))
(pp seen buf (get a i)))
(buffer-push-string buf end)))
buf)
(defn- pp-dict [pp seen buf a start end]
(if (get seen a)
(buffer-push-string buf "<cycle>")
(do
(put seen a true)
(var k (next a nil))
(buffer-push-string buf start)
(while k
(def v (get a k))
(pp seen buf k)
(buffer-push-string buf " ")
(pp seen buf v)
(varset! k (next a k))
(when k (buffer-push-string buf " ")))
(buffer-push-string buf end)))
buf)
(def printers :private {
:array (fn [pp seen buf x] (pp-seq pp seen buf x "[" "]"))
:tuple (fn [pp seen buf x] (pp-seq pp seen buf x "(" ")"))
:table (fn [pp seen buf x] (pp-dict pp seen buf x "@{" "}"))
:struct (fn [pp seen buf x] (pp-dict pp seen buf x "{" "}"))
})
(defn- default_printer [pp seen buf x]
(buffer-push-string buf (string x))
buf)
(defn- pp1 [seen buf x]
(def pmaybe (get printers (type x)))
(def p (if pmaybe pmaybe default_printer))
(p pp1 seen buf x))
(defn pp
"Pretty print a value x."
[x] (print (pp1 @{} @"" x)))