-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.clj
More file actions
103 lines (70 loc) · 2.1 KB
/
parser.clj
File metadata and controls
103 lines (70 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
;; constants
;; regexes
(def number-regex #"^(\d+)((.|\n)*)$")
(def string-regex #"^(\"[^\\']*(?:\\.[^\\']*)*\")((.|\n)*)$")
(def bool-regex #"^(true|false)((.|\n)*)$")
(def null-regex #"^(null)((.|\n)*)$")
(def space-regex #"^([ \t]+)((.|\n)*)$")
(def open-sqr-regex #"^(\[)((.|\n)*)$")
(def close-sqr-regex #"^(\])((.|\n)*)$")
(def open-curly-regex #"^(\{)((.|\n)*)$")
(def close-curly-regex #"^(\{)((.|\n)*)$")
(def comma-regex #"^(,)((.|\n)*)")
;; parser vector for the value parser
(def parsers [number-parser string-parser bool-parser]) ;; add array parser and value parser
;; utility functions
(defn get-match [regex]
(fn [input]
(let [match (re-matches regex input)]
[(get match 1)(get match 2)])))
(defn maybe [value func]
(if (= nil value)
nil
(func value)))
(defn get-first-match [input]
(filter #(not (= nil)) (map #(% input) parsers)))
;; value extractors
(defn get-number [value]
(update value 0 #(Integer/parseInt %)))
(defn get-string [value]
(update value 0 #(str %)))
(defn get-bool [value]
(not (= "false" value)))
(defn get-null [value]
(update value 0 #(symbol %)))
(defn get-comma [value]
(update value 0 #(symbol %)))
;; matcher functions
(def match-number
(get-match number-regex))
(def match-string
(get-match string-regex))
(def match-bool
(get-match bool-regex))
(def match-null
(get-match null-regex))
;; basic parsers
(def space-parser
(get-match space-regex))
(def open-sqr-bkt
(get-match open-sqr-regex))
(def close-sqr-bkt
(get-match close-sqr-regex))
(def open-curly-bkt
(get-match open-curly-regex))
(def close-curly-bkt
(get-match close-curly-regex))
(def comma-parser
(get-match comma-regex))
;; value parsers
(defn number-parser [input]
(maybe (match-number input) get-number))
(defn string-parser [input]
(maybe (match-string input) get-string))
(defn bool-parser [input]
(maybe (match-bool input) get-bool))
(defn null-parser [input]
(maybe (match-null input) get-null))
;; parser-array for the value-parser
(defn value-parser [input]
(get-first-match input))