View difference between Paste ID: Tq0x0QXV and 2N51sRLP
SHOW: | | - or go back to the newest paste.
1
;=============================================================================
2
;  Pratt's Top Down Operator Precedence Parser
3
;=============================================================================
4
(def make-assoc (f)
5
  (fn (bind pre inf)
6
    (list bind (and pre (fn ()    (pre     (f bind))))
7
               (and inf (fn (val) (inf val (f bind)))))))
8
9
(= left  (make-assoc (fn (bind) (expression bind))))
10
(= right (make-assoc (fn (bind) (expression (- bind 1)))))
11
12
(def literal (x)
13
  (list 0 (fn () x) nil))
14
15
(def expression (bind)
16
  (withs (x    (car tokens)
17
          nud  (aand x (x 1) (it)))
18
    (zap cdr tokens)
19
    (while (and x (< bind (x 0)))
20
      (when (= x car.tokens)
21
        (zap cdr tokens)
22
        (zap (x 2) nud)))
23
    nud))
24
25
(mac infix (n parms . body)
26
  `(left ,n nil (fn ,parms ,@body)))
27
28
(mac prefix (n parms . body)
29
  `(left ,n (fn ,parms ,@body) nil))
30
31
32
;=============================================================================
33
;  ssexpand
34
;=============================================================================
35
(= ssyntax-rules* (obj #\~ (prefix 10 (r)  `(complement ,r))
36
                       #\: (infix 10 (l r) `(compose ,l ,r))
37
                       #\& (infix 10 (l r) `(andf ,l ,r))
38
                       #\. (infix 10 (l r) `(,l ,r))
39
                       #\! (infix 10 (l r) `(,l ',r))))
40
41
(def chars->value (x)
42
  (literal:read:string:rev x))
43
44
(def tokenize (x)
45
  ((afn (x l r)
46
     (aif (no x)
47
            (rev:cons chars->value.l r)
48
          (ssyntax-rules* car.x)
49
            (self cdr.x nil (cons it (cons chars->value.l r)))
50
          (self cdr.x (cons car.x l) r)))
51
   (coerce string.x 'cons) nil nil))
52
53
(def ssexpand (x)
54
  (= tokens tokenize.x)
55
  (expression -1))