~subsetpark/ec

ref: 208a50058aaaa7a7a93cc4bba216ce87bd2ca9cb ec/src/parser.janet -rw-r--r-- 1.2 KiB
208a5005 — Zach Smith float parsing and handle bools directly 8 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
(import /src/calc)

(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]
  (:new calc/Float (scan-number patt)
        :doc patt))

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

(defn handle-word
  [patt]
  (cond
    (index-of patt ["." "p" "s" "?" "??"]) [:special patt]
    (string/has-prefix? "'" patt) (:new calc/Symbol
                                        (string/slice patt 1)
                                        :quoted? true)
    (:new calc/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))