forked from Ramarren/cl-parser-combinators
-
Notifications
You must be signed in to change notification settings - Fork 1
/
combinators.lisp
85 lines (77 loc) · 3.4 KB
/
combinators.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
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
(in-package :parser-combinators)
;;; emulating monads... did I even understand those?
;;; bind :: Parser a -> (a -> Parser b) -> Parser b
;;; (parser-tree1 function-from-tree1-to-parser-tree2)=>parser-tree2
;;; p ‘bind‘ f = \inp -> concat [f v inp’ | (v,inp’) <- p inp]
;;; (bind p f inp)=(concat list-comprehension)
(defun execute-bind (inp parser parser-generator) ;return continuation function
(with-parsers (parser)
(let ((p-parse-continuation (funcall parser inp))
(q-parse-continuation nil))
#'(lambda ()
(let ((result nil))
(iter (when q-parse-continuation (setf result (funcall q-parse-continuation)))
(until (or result
(and (null p-parse-continuation)
(null q-parse-continuation))))
(unless result
(setf q-parse-continuation
(let ((p-next-result
(funcall p-parse-continuation)))
(if p-next-result
(let ((v (tree-of p-next-result))
(inp-prime (suffix-of p-next-result)))
(funcall (ensure-parser (funcall parser-generator v)) inp-prime))
(setf p-parse-continuation nil))))))
result)))))
(defmacro bind (parser parser-generator) ; results in parser-promise
`(let ((parser ,parser)
(parser-generator ,parser-generator))
#'(lambda (inp)
(execute-bind inp
parser
parser-generator))))
(defun execute-choice (inp parser1 parser2)
(let ((continuation-1 (funcall parser1 inp))
(continuation-2 nil))
#'(lambda ()
(cond (continuation-1
(let ((result (funcall continuation-1)))
(unless result
(setf continuation-1 nil)
(setf continuation-2 (funcall parser2 inp))
(setf result (funcall continuation-2)))
result))
(continuation-2
(let ((result (funcall continuation-2)))
(unless result
(setf continuation-2 nil))
result))
(t nil)))))
(defmacro choice (parser1 parser2)
"Combinator: all alternatives from two parsers"
`(let ((parser1 (ensure-parser ,parser1))
(parser2 (ensure-parser ,parser2)))
#'(lambda (inp)
(execute-choice inp parser1 parser2))))
(defmacro choice1 (parser1 parser2)
"Combinator: one alternative from two parsers"
`(let ((parser1 (ensure-parser ,parser1))
(parser2 (ensure-parser ,parser2)))
(define-oneshot-result inp is-unread
(funcall (execute-choice inp
parser1
parser2)))))
(defmacro choices (&rest parser-list)
"Combinator: all alternatives from multiple parsers"
(if (cdr parser-list)
`(choice ,(car parser-list)
(choices ,@(cdr parser-list)))
(car parser-list)))
(defmacro choices1 (&rest parser-list)
"Combinator: one alternative from multiple parsers"
`(let ((parser-list (list ,@parser-list)))
(define-oneshot-result inp is-unread
(iter (for p in parser-list)
(for result = (funcall (funcall (ensure-parser p) inp)))
(thereis result)))))