~subsetpark/ec

ref: 5f2065e7cc6bb4fd362d3861bfd2a5cdc32f128f ec/src/parser.janet -rw-r--r-- 2.3 KiB
5f2065e7 — Zach Smith Add if 9 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
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
(import /src/calc)
(import /src/operations)
(import /src/adverbs)
(import /src/compose)

(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
                 "pow" operations/pow

                 "distribute" adverbs/distribute
                 "/" adverbs/distribute
                 "apply" adverbs/apply-quotation
                 "!" adverbs/apply-quotation
                 "@" adverbs/wrap-stack
                 "swap" adverbs/swap
                 "slurp" adverbs/slurp
                 "slurpl" adverbs/slurp-left
                 "slurpr" adverbs/slurp
                 "c" adverbs/clear-stack
                 "fill" adverbs/fill
                 "dup" adverbs/dup
                 "arity" adverbs/arity
                 "shape" adverbs/shape
                 "if" adverbs/if

                 "sqr" compose/square})

(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]
    true
    (or (dictionary patt)
        (errorf "syntax error: unknown word %s" patt))))

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