~subsetpark/ec

ref: c036dd32fafa9d1671676e1e52d4ebdfa236c1bd ec/src/parser.janet -rw-r--r-- 1.4 KiB
c036dd32 — Zach Smith unwrap single tuple 4 months ago
                                                                                
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
(use fugue)
(import /src/calc)

(defproto Symbol calc/Element
  value {:init? true}
  quoted? {:default false})

(extend-multi calc/make-element [:symbol] [s] (new-Symbol s))
(extend-multi calc/make-element [_] [v] v)

(defn handle-parens
  [& patt]
  [:parens (string ;patt)])

(defn handle-quotes
  [& patt]
  (calc/quote-wrap ;patt))

(defn handle-vectors
  [& patt]
  (calc/wrap ;patt))

(defn handle-float
  [patt]
  (calc/new-Float (scan-number patt)
                  :doc patt))

(defn handle-int
  [patt]
  (calc/new-Int (scan-number patt)
                :doc patt))

(defn handle-word
  [patt]
  (cond
    (index-of patt ["." "p" "s" "?" "??"]) [:special patt]
    (string/has-prefix? "'" patt) (new-Symbol
                                    (string/slice patt 1)
                                    :quoted? true)
    (new-Symbol patt
                :quoted? false)))

(def- peg (peg/compile
            ~{:main (any (+ :s+ :quotes :vectors :token))
              :quotes (cmt (* (set "({") :main (set ")}")) ,handle-quotes)
              :vectors (cmt (* "[" :main "]") ,handle-vectors)
              :number-part (some (+ :d "_"))
              :float (cmt (<- (* (? "-") (? :number-part) "." :number-part)) ,handle-float)
              :int (cmt (<- (* (? "-") :number-part)) ,handle-int)
              :word (cmt (<- (some (if-not (+ :s (set "()[]{}")) 1))) ,handle-word)
              :token (+ :float :int :word)}))

(defn parse
  [str]
  (peg/match peg str))