source: project/release/4/lexgen/trunk/lexgen.scm @ 14885

Last change on this file since 14885 was 14885, checked in by Ivan Raikov, 10 years ago

added cps-table in lexgen

File size: 7.6 KB
Line 
1;;
2;;  Lexer combinator library.
3;;
4;;  Based on the SML lexer generator by Thant Tessman.
5;;
6;;  Ported to Chicken Scheme by Ivan Raikov.
7;;  Copyright 2009 Ivan Raikov.
8;;
9;;
10;;  Redistribution and use in source and binary forms, with or without
11;;  modification, are permitted provided that the following conditions
12;;  are met:
13;;
14;;  - Redistributions of source code must retain the above copyright
15;;  notice, this list of conditions and the following disclaimer.
16;;
17;;  - Redistributions in binary form must reproduce the above
18;;  copyright notice, this list of conditions and the following
19;;  disclaimer in the documentation and/or other materials provided
20;;  with the distribution.
21;;
22;;  - Neither name of the copyright holders nor the names of its
23;;  contributors may be used to endorse or promote products derived
24;;  from this software without specific prior written permission.
25;;
26;;  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND THE
27;;  CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
28;;  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
29;;  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
30;;  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR THE
31;;  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
32;;  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
33;;  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
34;;  USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
35;;  AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36;;  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
37;;  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38;;  POSSIBILITY OF SUCH DAMAGE.
39;;
40
41(module lexgen
42
43  ( tok seq star bar 
44    try pass pos opt char 
45    set range lst lit 
46    cps-table longest lex )
47
48
49   (import scheme chicken data-structures
50           (only srfi-1 first second filter-map fold concatenate) 
51           srfi-14 srfi-69)
52   (require-extension matchable)
53
54;;
55;;   This is a lexer generator comprised in its core of four small
56;;   functions. The programmer assembles these functions into regular
57;;   expression pattern-matching functions.
58;;
59;;   The idea is that a pattern matcher function takes a list of
60;;   streams, and returns a new list of streams advanced by every
61;;   combination allowed by the pattern matcher function. In this
62;;   implementation, a stream is simply a tuple containing a list of
63;;   elements consumed by the pattern matcher, and a list of
64;;   characters not yet consumed.
65;;
66;;   Note that the number of streams returned by the function
67;;   typically won't match the number of streams passed in. If the
68;;   pattern doesn't match at all, the empty list is returned.
69;;
70
71;; 'tok' builds a pattern matcher function that applies procedure p to
72;; a given token and an input character. If the procedure returns a
73;; true value, that value is prepended to the list of consumed
74;; elements, and the input character is removed from the list of input
75;; elements.
76
77(define (tok t p)
78  (let ((f (lambda (s) 
79             (match s
80                    ((c (h . r)) 
81                     (let ((ans (p t h)))
82                       (and ans (list (cons ans c) r))))
83                    ((c ())  s)
84                    (else #f)))))
85    (lambda (cont streams)
86      (let ((streams1 (filter-map f streams)))
87        (cont streams1)))))
88   
89
90;; This matches a sequence of patterns.
91
92(define (seq p1 p2)
93  (lambda (cont streams)
94    (p1 (lambda (streams1) (p2 cont streams1)) streams)))
95
96
97;; This matches either one of two patterns. It's analogous to patterns
98;; separated by the '|' in regular expressions.
99
100(define (bar p1 p2)
101  (lambda (cont streams)
102    (let ((cont1 (lambda (streams1) 
103                   (if (null? streams1) (p2 cont streams) (cont streams1)))))
104      (p1 cont1 streams))))
105
106
107;; Kleene closure. Analogous to '*'
108
109(define (star p)
110  (lambda (cont streams)
111    (if (null? streams) (cont streams)
112        (let ((cont1 (lambda (streams1) (cont (concatenate (list streams streams1))))))
113          (p (lambda (streams1) 
114               (cond ((equal? streams streams1) (cont streams))
115                     (else  ((star p) cont1 streams1))))
116             streams)))))
117
118;; The rest of these are built from the previous four and are provided
119;; for convenience.
120
121;; this parser always succeeds
122(define (pass cont s) (cont s))
123 
124;; Positive closure. Analogous to '+'
125
126(define (pos pat) (seq pat (star pat)))
127
128;; Optional pattern. Analogous to '?'
129
130(define (opt pat) (bar pat pass))
131
132;; Converts a binary predicate procedure to a binary procedure that
133;; returns its right argument when the predicate is true, and false
134;; otherwise.
135
136(define (try p) (lambda (x y) (let ((res (p x y))) (and res y))))
137
138;; Matches a single character
139
140(define (char c) (tok c (try char=?)))
141 
142;; Matches any of a SRFI-14 set of characters.
143
144(define (set s)
145  (let ((cs (if (char-set? s) s (list->char-set (if (string? s) (string->list s) s)))))
146    (tok cs (try char-set-contains?))))
147
148;; Range of characters. Analogous to character class '[]'
149
150(define (range a b)
151  (if (char<? b a) (range b a)
152      (set (ucs-range->char-set 
153            (char->integer a) (char->integer b)))))
154
155;; Matches a consecutive list of patterns
156
157(define (lst ps)
158  (let ((ps (reverse ps)))
159    (let loop ((ps (cdr ps)) (p1 (car ps)))
160      (cond ((null? ps) p1)
161            ((null? (cdr ps))    (seq (car ps) p1))
162            (else (loop (cdr ps) (seq (car ps) p1)))))))
163 
164;; Matches a literal string s
165
166(define (lit s)
167  (let ((f (lambda (t) (tok t (try char=?)))))
168    (lst (map f (if (string? s) (string->list s) s)))))
169
170
171;; Takes the resulting streams produced by the application of a
172;; pattern on a stream (or streams) and selects the longest match if
173;; one exists.
174
175(define (longest streams)
176  (match-let (((count stream)
177               (fold (lambda (stream max)
178                       (match (list stream max)
179                              (((eaten food) (max-count max-stream)) 
180                               (if (< max-count (length eaten))
181                                   (list (length eaten) stream) max))
182                              (else (error 'longest "invalid stream" stream))))
183                     (list 0 `(() ()))
184                     streams)))
185             (and (positive? count) stream)))
186
187
188;; This takes a pattern and a string, turns the string into a list of
189;; streams (containing one stream), applies the pattern, and returns
190;; the longest match.
191
192(define (->char-list s)
193  (if (string? s) (string->list s) s))
194
195(define (lex pat error s)
196  (let* ((stream (->char-list s))
197         (res    (longest (pat (lambda (s1) (if (null? s1) (error s) s1)) `((() ,stream))))))
198    (and res (list (reverse (first res)) (second res)))))
199
200
201(define make-table      make-hash-table)
202(define table-ref       hash-table-ref/default)
203(define table-put!      hash-table-set!)
204(define table-for-each  hash-table-for-each)
205
206
207;; tabled execution wrapper
208;; from _Tabled Execution in Scheme_, by Willcock, et al.
209
210(define (cps-table f combine)
211  (let ((memo    (make-table equal?))
212        (k-list  (make-table equal?)))
213    (lambda (k arg)
214      (table-put! k-list arg (cons k (table-ref k-list arg (list))))
215      (if (not (table-ref memo arg  #f))
216          (let ((memo-table (make-table)))
217            (print "miss: arg = " arg)
218            (table-put! memo arg memo-table)
219            (f (lambda (result)
220                 (print "miss: result = " result)
221                 (if (null? result) (k result)
222                     (let* ((len     (length result))
223                            (old-len (table-ref memo-table result #f))
224                            (new-len (combine (or old-len 0) len)))
225                       (print "len = " len)
226                       (print "old-len = " old-len)
227                       (print "new-len = " new-len)
228                       (if (not (equal? old-len new-len))
229                           (begin
230                             (table-put! memo-table result new-len)
231                             (for-each (lambda (saved-k) (saved-k result))
232                                       (table-ref k-list arg (list))))))))
233               
234               arg))
235          (let ((memo-table (table-ref memo arg #f) ))
236            (print "hit: arg = " arg)
237            (table-for-each memo-table (lambda (result len) (k result)))
238            )))))
239
240)
Note: See TracBrowser for help on using the repository browser.