-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathexample-sexp.lisp
60 lines (45 loc) · 1.61 KB
/
example-sexp.lisp
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
;;;; S-Expression parser from “esrap/example-sexp.lisp” ported to MaxPC.
(defpackage maxpc.example-sexp
(:use :cl :maxpc :maxpc.char :maxpc.digit)
(:export :=sexp))
(in-package :maxpc.example-sexp)
;;; A semantic predicate for filtering out double quotes.
(defun not-doublequote (char)
(not (eql #\" char)))
(defun not-integer (string)
(when (find-if-not #'digit-char-p string)
t))
;;; Utility rules.
(defun ?alphanumeric ()
(?satisfies 'alphanumericp))
(defun ?string-char ()
(%or (?seq (?eq #\\) (?eq #\"))
(?satisfies 'not-doublequote)))
;;; Here we go: an S-expression is either a list or an atom, with possibly
;;; leading whitespace.
(defun =atom ()
(%or (=string) (=integer-number) (=symbol)))
(defun =string ()
(=destructure (_ s _)
(=list (?eq #\")
(=subseq (%any (?string-char)))
(?eq #\"))))
(defun =symbol ()
;; NOT-INTEGER is not strictly needed because ATOM considers INTEGER before a
;; STRING, we know can accept all sequences of alphanumerics -- we already
;; know it isn't an integer.
(=transform (=subseq (?satisfies 'not-integer
(=subseq (%some (?alphanumeric)))))
'intern))
(defun =sexp ()
(%or '=slist/parser (=atom)))
(defun =slist ()
(=destructure (_ expressions _ _)
(=list (?eq #\()
(%any (=destructure (_ expression)
(=list (%any (?whitespace)) '=sexp/parser)))
(%any (?whitespace))
(?eq #\)))))
;; Recursive parsers hack.
(setf (fdefinition '=sexp/parser) (=sexp)
(fdefinition '=slist/parser) (=slist))