Skip to content

Commit 30b809b

Browse files
rymndhngswannodette
authored andcommitted
CLJS-1299: Add support for more literals in reader
Adds support for rich character literals like `\space`, `\return` and unicode literals like `\u1234`. The implementation is a port of the JVM's `CharacterReader`. See http://dev.clojure.org/jira/browse/CLJS-1299
1 parent 637e247 commit 30b809b

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/main/cljs/cljs/reader.cljs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,21 @@ nil if the end of stream has been reached")
334334
(.-length token)))
335335
(special-symbols token (symbol token)))))
336336

337+
(defn read-literal
338+
[rdr ch]
339+
(let [token (read-token rdr ch)
340+
chars (subs token 1)]
341+
(cond (identical? (.-length chars) 1) chars
342+
(identical? chars "tab") "\t"
343+
(identical? chars "return") "\r"
344+
(identical? chars "newline") "\n"
345+
(identical? chars "space") " "
346+
(identical? chars "backspace") "\b"
347+
(identical? chars "formfeed") "\f"
348+
(identical? (.charAt chars 0) "u") (make-unicode-char (subs chars 1))
349+
(identical? (.charAt chars 0) "o") (not-implemented rdr token)
350+
:else (reader-error rdr "Unknown character literal: " token))))
351+
337352
(defn read-keyword
338353
[reader initch]
339354
(let [token (read-token reader (read-char reader))
@@ -407,7 +422,7 @@ nil if the end of stream has been reached")
407422
(identical? c \]) read-unmatched-delimiter
408423
(identical? c \{) read-map
409424
(identical? c \}) read-unmatched-delimiter
410-
(identical? c \\) read-char
425+
(identical? c \\) read-literal
411426
(identical? c \#) read-dispatch
412427
:else nil))
413428

src/test/cljs/cljs/reader_test.cljs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,10 @@
9494
(reader/register-default-tag-parser! (fn [tag val] val))
9595
(is (= [1 2] (reader/read-string "#a.b/c [1 2]"))))
9696

97+
(testing "Character Literals"
98+
(is (= [\tab \return \newline \space \backspace \formfeed \u1234]
99+
(reader/read-string "[\\tab \\return \\newline \\space \\backspace \\formfeed \\u1234]"))))
100+
97101
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
98102
;; Unicode Tests
99103

0 commit comments

Comments
 (0)