Debian Codegraph @

test/quoting.fnl

raw
1 (local t (require :test.faith))
2 (local fennel (require :fennel))
3 (local view (require :fennel.view))
4
5 (macro v [expr] (view expr))
6 (macro peval [expr ?opts]
7 `(pcall fennel.eval (v ,expr) ,?opts))
8
9 (fn c [code]
10 (fennel.compileString code {:allowedGlobals false :compiler-env _G}))
11
12 (fn cv [code]
13 (view ((fennel.loadCode (c code) (let [env {:sequence fennel.sequence}]
14 (set env._G env)
15 (setmetatable env {:__index _G}))))
16 {:one-line? true}))
17
18 (fn test-quote []
19 (t.= (c "`:abcde") "return \"abcde\"" "simple string quoting")
20 (t.= (cv "`[1 2 ,(+ 1 2) 4]") "[1 2 3 4]"
21 "unquote inside quote leads to evaluation")
22 (t.= (cv "(let [a (+ 2 3)] `[:hey ,(+ a a)])") "[\"hey\" 10]"
23 "unquote inside other forms")
24 (t.= (cv "`[:a :b :c]") "[\"a\" \"b\" \"c\"]"
25 "quoted sequential table")
26 (local viewed (cv "`{:a 5 :b 9}"))
27 (t.is (or (= viewed "{:a 5 :b 9}") (= viewed "{:b 9 :a 5}"))
28 (.. "quoted keyed table: " viewed))
29
30
31 ;; make sure shadowing the macro env in a macro body doesn't break anything
32 (let [shadow-scope (fennel.scope)
33 _ (fennel.compile-string
34 (v (macro shadow-macro [name args ...]
35 (let [g (. (getmetatable _G) :__index)
36 shadow-bind []]
37 (each [k (pairs _G)]
38 (when (and (= :string (type k)) (not= k :_G) (= nil (. g k))
39 ;; `comment` shadows a special form
40 (not= :comment k))
41 (table.insert shadow-bind (sym k))
42 (table.insert shadow-bind true)))
43 `(macro ,name ,args (let ,shadow-bind ,...)))))
44 {:scope shadow-scope})
45 (ok res) (peval (do (shadow-macro m [v] `(do ,v))
46 (shadow-macro n [v] `[,v])
47 (shadow-macro o [v] `(let [x# ,v] x#))
48 [(m :a) (n :b) (o :c)])
49 {:scope (fennel.scope shadow-scope)})]
50 (t.is ok (: "shadowing the compiler env in a macro doesn't break quoting\n%s"
51 :format (tostring res)))
52 (t.= [:a [:b] :c] res
53 "shadowing the compiler env in a macro doesn't break quoting")))
54
55 (fn test-quoted-source []
56 (t.= "return 3" (c "\n\n(eval-compiler (. `abc :line))")
57 "syms have source data")
58 (t.= "return 2" (c "\n(eval-compiler (. `abc# :line))")
59 "autogensyms have source data")
60 (t.= "return 4" (c "\n\n\n(eval-compiler (. `(abc) :line))")
61 "lists have source data")
62 (let [(_ msg) (pcall c "\n\n\n\n(macro abc [] `(fn [... a#] 1)) (abc)")]
63 (t.match "unknown:5" msg "quoted tables have source data"))
64 ;; runtime quoting
65 (t.= "return {\"foo\", \"x\", table.unpack({1, 2, 3}), \"y\"}"
66 (c "`[:foo :x ,(table.unpack [1 2 3]) :y]")))
67
68 (macro not-equal-gensym []
69 (let [s (gensym :sym)]
70 `(let [,s 10 sym# 20] (and sym# (not= ,s sym#)))))
71
72 (fn test-autogensym []
73 (t.is (not-equal-gensym)))
74
75 {: test-quote
76 : test-quoted-source
77 : test-autogensym}