aboutsummaryrefslogtreecommitdiff
path: root/argot.lisp
blob: c4347787aa8d1b79203acc4938acac12b6d2cc32 (plain)
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
;;;; argot.lisp

(in-package #:argot)

(defstruct rule lhs pattern action)

(define-condition invalid-rule-def (error)
  ((rule :reader rule :initarg :rule)))

(defun include-rule (grammar rule)
  (setf (gethash (rule-lhs rule) grammar) rule))

(defun nonterminal? (lhs)
  (and (symbolp lhs)
       (let* ((name (symbol-name lhs))
              (length (length name)))
         (and (<= 3 length)
              (eql #\< (elt name 0))
              (eql #\> (elt name (1- length)))))))

(defun var? (var)
  (and var (symbolp var) (not (keywordp var))))

(defun pattern? (pat)
  "Every pattern PAT is either a nonterminal symbol, or a pattern
expression. Such expressions look like (OP . ARGS) where OP is one of
:SEQ :? :* :+ :OR :OR= := :*= :?= :SEQ= :@ :EOF"
  (or (nonterminal? pat)
      (and (consp pat)
           (destructuring-bind (op . more) pat
             (case op
               ((:seq :? :* :+ :or)
                (every #'pattern? more))
               ((:or= := :*= :+= :?= :seq=)
                (not (null more)))
               (:@ (and (var? (first more))
                        (not (third more))
                        (pattern? (second more))))
               (:eof (endp more)))))))

(defun var-pattern? (pat)
  "VAR-PATTERN? checks that a pattern is a var pattern (:@ VAR PATTERN)
and it returns VAR in that case."
  (and (consp pat)
       (third pat)
       (destructuring-bind (at var . _) pat
         (declare (ignore _))
         (and (eq at :@) (var? var) var))))

(defun collect-vars (pat)
  "Collects all of the variables from the var patterns in PAT and returns them."
  (if-let (var (var-pattern? pat))
    (list var)
    (when (consp pat)
      (append (collect-vars (car pat))
              (collect-vars (cdr pat))))))

(defun parse-rule-def (ruledef)
  (handler-case 
      (ematch ruledef
        ((guard (list lhs :-> pattern)
                       (and (nonterminal? lhs) (pattern? pattern)))
         (list lhs pattern (collect-vars pattern) nil))
        
        ((guard (list lhs :-> pattern :=> action)
                       (and (nonterminal? lhs) (pattern? pattern)))
         (list lhs pattern (collect-vars pattern) action)))
    (trivia::match-error ()
      (error 'invalid-rule-def :rule ruledef))))

(defmacro defgrammar (name (&key (documentation "")) &body ruledefs)
  (let ((bindings-var (gensym "BINDINGS")))
    `(progn
       (defvar ,name nil ,documentation)
       (setf ,name (make-hash-table :test #'eq))
       ,@(loop :for ruledef :in ruledefs
               :for (lhs pattern vars action) := (parse-rule-def ruledef)
               :for bindings
                 := (loop :for var :in vars
                          :collect `(,var (cdr (assoc ',var ,bindings-var))))
               :collect `(include-rule
                          ,name
                          (make-rule
                           :lhs ',lhs
                           :pattern ',pattern
                           ,@(when action
                               (list 
                                :action `(lambda (,bindings-var) (let ,bindings ,action)))))))
       ,name)))

(defvar *position*)
(defvar *grammar*)
(defvar *tokens*)
(defvar *bindings*)

(defun succeed (result)
  (values result t))

(defun fail ()
  (values nil nil))

(defparameter +eof+ #())

(defun next-token ()
  (if (< *position* (length *tokens*))
      (prog1 (elt *tokens* *position*)
        (incf *position*))
      +eof+))

(defun update-bindings (var value)
  (setf *bindings* (acons var value *bindings*)))

(defmacro try-parse
    ((&optional (result (gensym)))
     parse-expression
     &optional
       (success-clause `(succeed ,result))
       (fail-clause '(fail)))
  (alexandria:with-gensyms (successp pos)
    `(let ((,pos *position*))
       (multiple-value-bind (,result ,successp) ,parse-expression
         (if ,successp ,success-clause
             (progn
               (setf *position* ,pos)
               ,fail-clause))))))

(defun parse-sequence (patterns)
  "Parse each member of PATTERNS and succeed with a list of results. If
any pattern fails the whole parse fails."
  (try-parse
      () (loop :for pattern :in patterns
               :for (result successp)
                 := (multiple-value-list (parse-pattern pattern))
               :if successp
                 :collect result :into results
               :else :return (fail)
               :finally (return (succeed results)))))

(defun parse-optional (pattern)
  (try-parse
      (res) (parse-pattern pattern)
      (succeed res)
      (succeed nil)))

(defun parse-kleene (pattern)
  (loop :for (res successp) := (multiple-value-list (try-parse () (parse-pattern pattern)))
        :while successp :collect res :into results
        :finally (return-from parse-kleene (succeed results))))

(defun parse-one-or-more (pattern)
  (try-parse (first) (parse-pattern pattern)
      (try-parse (rest) (parse-kleene pattern)
          (succeed (cons first rest)))))

(defun parse-alernatives (patterns)
  (if (endp patterns) (fail)
      (try-parse (result) (parse-pattern (first patterns))
          (succeed result)
          (parse-alernatives (rest patterns)))))

(defun literals->patterns (literals)
  (loop :for l :in literals :collect (list := l)))

(defun literals-equal? (a b) (eq a b))

(defun parse-literal (literal)
  (if (literals-equal? (next-token) literal)
      (succeed literal)
      (fail)))

(defun parse-literal-alternatives (literals)
  (parse-alernatives (literals->patterns literals)))

(defun parse-kleene-literal (literal)
  (parse-kleene (list := literal)))

(defun parse-one-or-more-literal (literal)
  (parse-one-or-more (list := literal)))

(defun parse-optional-literal (literal)
  (parse-optional (list := literal)))

(defun parse-literal-sequence (literals)
  (parse-sequence (literals->patterns literals)))

(defun parse-binding-pattern (var pattern)
  (try-parse
      (result) (parse-pattern pattern)
      (progn
        (update-bindings var result)
        (succeed result))))

(defun parse-eof ()
  (if (eq +eof+ (next-token))
      (succeed nil)
      (fail)))

(defun parse-pattern (pattern)
  (try-parse ()
             (if (nonterminal? pattern)
                 (parse-rule pattern)
                 (destructuring-bind (op . args) pattern
                   (case op
                     (:seq (parse-sequence args))
                     (:? (parse-optional (first args)))
                     (:* (parse-kleene (first args)))
                     (:+ (parse-one-or-more (first args)))
                     (:or (parse-alernatives args))
                     (:or= (parse-literal-alternatives args))
                     (:= (parse-literal (first args)))
                     (:*= (parse-kleene-literal (first args)))
                     (:+= (parse-one-or-more-literal (first args)))
                     (:?= (parse-optional-literal (first args)))
                     (:seq= (parse-literal-sequence args))
                     (:@ (parse-binding-pattern (first args) (second args)))
                     (:eof (parse-eof)))))))

(defun parse-rule (nonterminal)
  (if-let (rule (gethash nonterminal *grammar*))
    (let ((*bindings* nil))
      (try-parse (result) (parse-pattern (rule-pattern rule))
          (if (rule-action rule)
              (succeed (funcall (rule-action rule) *bindings*))
              (succeed result))))
    (fail)))


(defun parse (grammar rule tokens)
  (let ((*position* 0)
        (*grammar* grammar)
        (*tokens* tokens))
    (parse-rule rule)))