~subsetpark/ec

ref: a37c903188ba035322c030f56c766089eab36556 ec/src/parser.janet -rw-r--r-- 1.5 KiB
a37c9031 — Zach Smith Bugfix: make-element in vector math as well 10 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
(import /src/calc)
(import /src/operations)
(import /src/adverbs)

(def dictionary {"+" operations/add
                 "-" operations/sub
                 "*" operations/mul
                 "x" operations/mul
                 "%" operations/div
                 "sqrt" operations/sqrt
                 ">" operations/gt
                 "<" operations/lt
                 ">=" operations/gte
                 "<=" operations/lte
                 "=" operations/eq
                 "cmp" operations/cmp
                 "/" adverbs/distribute-dyad
                 "!" adverbs/apply-vector
                 "@" adverbs/wrap-stack})

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

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

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

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

(defn handle-word
  [patt]
  (or (dictionary patt)
      (errorf "syntax error: unknown word %s" patt)))

(def- peg (peg/compile
            ~{:main (any (+ :s+ :brackets :token))
              :brackets (cmt (* "[" :main "]") ,handle-brackets)
              :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))