1 ;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10; -*-
3 ;;; pegutils.lisp --- Utility functions for implementing PEG parsers
5 ;; Copyright (C) 2008 Utz-Uwe Haus <lisp@uuhaus.de>
8 ;; This code is free software; you can redistribute it and/or modify
9 ;; it under the terms of the version 2.1 of the GNU Lesser General
10 ;; Public License as published by the Free Software Foundation, as
11 ;; clarified by the lisp prequel found in LICENSE.
13 ;; This code is distributed in the hope that it will be useful, but
14 ;; without any warranty; without even the implied warranty of
15 ;; merchantability or fitness for a particular purpose. See the GNU
16 ;; Lesser General Public License for more details.
18 ;; Version 2.1 of the GNU Lesser General Public License is in the file
19 ;; LICENSE that was distributed with this file. If it is not
20 ;; present, you can access it from
21 ;; http://www.gnu.org/copyleft/lgpl.txt (until superseded by a
22 ;; newer version) or write to the Free Software Foundation, Inc., 59
23 ;; Temple Place, Suite 330, Boston, MA 02111-1307 USA
27 ;; Some code here is inspired by the metapeg library of John Leuner
32 (eval-when (:load-toplevel
:compile-toplevel
:execute
)
33 (declaim (optimize (speed 0) (safety 3) (debug 3))))
35 (in-package #:opossum
)
37 (defparameter *trace
* nil
"If non-nil, do extensive tracing of the parser functions.")
41 (;; these slots are copied when cloning a context for recursion
42 (input :accessor input
:initarg
:input
:initform nil
44 :documentation
"The input string being parsed.")
45 (destpkg :accessor destpkg
:initarg
:destpkg
:initform nil
47 :documentation
"The package into which symbols generated during the parse are interned.")
48 ;; these slots are shared by all cloned copies of a context -- use only STORE-ACTION to guarantee consistency
49 (actions :accessor actions
:initarg
:actions
:initform
'(NIL)
51 :documentation
"The list of actions accumulated during the parse.")
52 (action-counter :accessor action-counter
:initarg
:action-counter
:initform
'(0)
53 :type
'(cons (integer 0) null
)
54 :documentation
"The counter of actions.")
55 ;; these slots are what make a context unique
56 (parent :accessor parent
:initarg
:parent
:initform nil
)
57 (rule :accessor rule
:initarg
:rule
:initform nil
)
58 (children :accessor children
:initform nil
)
59 (value :accessor value
:initarg
:value
:initform nil
)
60 (start-index :accessor start-index
:initarg
:start-index
:initform nil
)
61 (end-index :accessor end-index
:initarg
:end-index
:initform nil
))
62 (:documentation
"The parser context."))
64 (defmethod print-object ((obj context
) stream
)
65 (print-unreadable-object (obj stream
:type T
:identity NIL
)
66 (format stream
"rule ~A (~S) value ~S (~D:~D)"
67 (rule obj
) (children obj
) (value obj
) (start-index obj
) (end-index obj
))))
69 (defmethod store-action ((ctx context
) action
)
70 (let ((a (actions ctx
)))
71 (rplacd a
(cons (car a
) (cdr a
)))
74 (defvar *context
* nil
"The current parser context.")
76 (defun clone-ctx (ctx rule
)
77 "Create clone context of CTX for rule RULE."
78 (make-instance 'context
80 :destpkg
(destpkg ctx
)
81 :actions
(actions ctx
)
82 :action-counter
(action-counter ctx
)
85 :start-index
(end-index ctx
)))
87 (defun ctx-failed-p (ctx)
89 (break "Botched context"))
90 (null (end-index ctx
)))
92 (defun succeed (ctx value start-index end-index
)
93 "Mark CTX as successful: set VALUE and matched region."
94 (setf (value ctx
) value
)
95 (setf (start-index ctx
) start-index
)
96 (setf (end-index ctx
) end-index
)
97 ; (break "generated success context ~A" ctx)
99 (format *trace-output
* "Matched: ~A (~D:~D)~%"
100 (rule ctx
) (start-index ctx
) (end-index ctx
)))
104 "Return a failure context."
105 (let ((ctx (make-instance 'context
106 :input
(input *context
*)
108 :value
(rule *context
*)
109 :start-index
(start-index *context
*)
110 :end-index
(end-index *context
*)
111 ;; probably some of these copies can be saved
112 :destpkg
(destpkg *context
*)
113 :actions
(actions *context
*)
114 :action-counter
(action-counter *context
*))))
115 ; (break "generated failure context ~A" ctx )
117 (format *trace-output
* "(failed: ~A ~A ~A)~%"
118 (value ctx
) (start-index ctx
) (end-index ctx
)))
123 (defun make-name (string)
124 (intern (concatenate 'string
"parse-" string
)
125 (destpkg *context
*)))
127 (defun make-action-name (&key ctx
)
128 "Return a symbol suitable to name the next action."
129 (incf (car (action-counter *context
*)))
131 (format nil
"opossum-action-~D-srcpos-~D-~D"
132 (car (action-counter *context
*))
135 (format nil
"opossum-action-~D-~D~D"
136 (car (action-counter *context
*)))) ))
137 (intern aname
(destpkg *context
*))))
139 (defun char-list-to-string (char-list)
140 (coerce char-list
'string
))
142 (defmacro build-parser-function
(name parser
)
144 (let* ((*context
* (clone-ctx *context
* ,name
))
145 (result (funcall ,parser offset
)))
148 (if (ctx-failed-p result
)
150 (succeed *context
* (value result
) (start-index result
) (end-index result
))))))
154 (defun match-string (string)
156 (let ((input (input *context
*))
157 (len (length string
)))
158 (if (and (>= (length input
) (+ offset len
))
159 (string= string input
:start2 offset
:end2
(+ offset len
)))
160 (succeed (clone-ctx *context
* 'opossum-string
) string offset
(+ offset
(length string
)))
163 (defun match-char (char-list)
165 (let ((input (input *context
*)))
167 (format *trace-output
* "match-char: looking for one of `~{~A~}'~%" char-list
))
168 (if (and (> (length input
) offset
)
169 (member (char input offset
)
170 char-list
:test
#'char
=))
171 (succeed (clone-ctx *context
* 'opossum-char
) (char input offset
) offset
(+ offset
1))
174 (defun match-octal-char-code (i1 i2 i3
)
175 "Compare the character given by i3 + 8*i2 + 64*i1 to the next input character."
176 (let ((c (+ i3
(* 8 i2
) (* 64 i1
))))
178 (let ((input (input *context
*)))
180 (format *trace-output
* "match-octal-char-code: looking for ~D~%" c
))
181 (if (and (> (length input
) offset
)
182 (= (char-int (char input offset
)) c
))
183 (succeed (clone-ctx *context
* 'opossum-char
) (char input offset
) offset
(+ offset
1))
186 (defun match-char-range (lower-char upper-char
)
187 "Match characters in the range between LOWER-CHAR and UPPER-CHAR (inclusive) as decided by CL:CHAR-CODE."
189 (let ((input (input *context
*)))
191 (format *trace-output
* "match-char-range: looking for ~A-~A~%" lower-char upper-char
))
192 (if (and (> (length input
) offset
)
193 (let ((x (char-code (char input offset
))))
194 (and (>= x
(char-code lower-char
))
195 (<= x
(char-code upper-char
)))))
196 (succeed (clone-ctx *context
* 'opossum-char-range
) (char input offset
) offset
(+ offset
1))
199 (defun match-any-char (&optional ignored
)
200 (declare (ignore ignored
))
202 "Match any character at OFFSET, fail only on EOF."
203 (let ((input (input *context
*)))
205 (format *trace-output
* "match-any-char~%"))
206 (if (< (1+ offset
) (length input
))
207 (succeed (clone-ctx *context
* 'opossum-anychar
) (char input offset
) offset
(+ offset
1))
210 (defun match-char-class (char-class)
211 "Regexp matching of next input character against [CHAR-CLASS] using cl-ppcre:scan."
212 (declare (type string char-class
))
213 ;; FIXME: could use a pre-computed scanner
214 (let ((cc (format nil
"[~A]" char-class
)))
216 "Match next character at OFFSET against the characters in CHAR-CLASS."
217 (let ((input (input *context
*)))
219 (format *trace-output
* "match-char-class on ~A~%"))
220 (if (and (< (1+ offset
) (length input
))
221 (let ((c (char input offset
)))
222 (cl-ppcre:scan cc
(make-string 1 :initial-element c
))))
223 (succeed (clone-ctx *context
* 'opossum-charclass
)
224 (char input offset
) offset
(+ offset
1))
227 (defun fix-escape-sequences (char-list)
228 "Iterate over the list CHAR-LIST, glueing adjacent #\\ #\n and #\\ #\t chars into
229 #\Newline and #\Tab."
231 ((null char-list
) char-list
)
232 ((null (cdr char-list
)) char-list
)
234 (loop :with drop
:= nil
235 :for
(c1 c2
) :on char-list
239 :collect
(if (char= c1
#\\)
241 ((#\n) (setf drop T
) #\Newline
)
242 ((#\t) (setf drop T
) #\Tab
)
243 ((#\r) (setf drop T
) #\Linefeed
)
249 ;; parsing combinator functions cribbed from libmetapeg
251 (defun either (&rest parsers
)
252 "Produce a function that tries each of the functions in PARSERS sequentially until one succeeds and
253 returns the result of that function, or a failure context if none succeeded."
255 (let ((*context
* (clone-ctx *context
* 'opossum-either
)))
257 (format *trace-output
* "either: ~A ~A~%" *context
* parsers
))
258 (loop :for p
:in parsers
259 :as result
= (funcall p offset
)
260 :when
(not (ctx-failed-p result
))
261 :return
(succeed *context
* (value result
) offset
(end-index result
))
262 :finally
(return (fail))))))
265 (defun optional (parser)
267 (let ((*context
* (clone-ctx *context
* 'opossum-optional
)))
269 (format *trace-output
* "optional: ~A ~A~%" *context
* parser
))
270 (let ((result (funcall parser offset
)))
271 (if (ctx-failed-p result
)
272 (succeed *context
* 'optional offset offset
)
273 (succeed *context
* (value result
) offset
(end-index result
)))))))
275 (defun follow (parser)
277 (let ((*context
* (clone-ctx *context
* 'opossum-follow
)))
279 (format *trace-output
* "follow: ~A ~A~%" *context
* parser
))
280 (let ((result (funcall parser offset
)))
281 (if (ctx-failed-p result
)
283 (succeed *context
* (value result
)
284 ;; don't consume input
289 (let ((*context
* (clone-ctx *context
* 'opossum-many
))
290 (start-offset offset
)
293 (format *trace-output
* "many: ~A ~A~%" *context
* parser
))
294 (loop :as result
:= (funcall parser offset
)
295 :while
(not (ctx-failed-p result
))
296 :do
(progn (push (value result
) children
)
297 (setf offset
(end-index result
)))
298 :finally
(return (succeed *context
* (nreverse children
) start-offset offset
))))))
301 (defun many1 (parser)
303 (let* ((*context
* (clone-ctx *context
* 'opossum-many1
))
304 (result (funcall parser offset
)))
306 (format *trace-output
* "many1: ~A ~A~%" *context
* parser
))
307 (if (not (ctx-failed-p result
))
308 (let ((result2 (funcall (many parser
) (end-index result
))))
309 (if (end-index result2
)
310 (succeed *context
* (cons (value result
) (value result2
)) offset
(end-index result2
))
311 (succeed *context
* (value result
) offset
(end-index result
))))
315 (defun seq (&rest parsers
)
317 (assert (> (length parsers
) 0))
318 (let ((*context
* (clone-ctx *context
* 'opossum-seq
))
319 (start-offset offset
)
323 (format *trace-output
* "seq: ~A ~A~%" *context
* parsers
))
325 (loop :for p
:in parsers
326 :do
(when *trace
* (format *trace-output
* " (seq ~A) trying ~A~%" *context
* p
))
329 (push (succeed (clone-ctx *context
* 'action
) nil offset offset
) child-nodes
)
330 (push p child-values
)
331 (setf (children *context
*) (reverse child-nodes
)))
333 (let ((result (funcall p offset
)))
334 (if (end-index result
)
336 (push result child-nodes
)
337 (push (value result
) child-values
)
338 (setf offset
(end-index result
))
339 (setf (children *context
*) (reverse child-nodes
)))
341 :finally
(return (succeed *context
* (reverse child-values
) start-offset offset
))))))
343 (defun negate (parser)
345 "Return a successful context at OFFSET if PARSER succeeds, without advancing input position."
346 (let ((*context
* (clone-ctx *context
* 'opossum-negate
)))
347 (let ((result (funcall parser offset
)))
348 (if (ctx-failed-p result
)
349 (succeed *context
* 'negate offset offset
)
354 (defun read-stream (stream)
355 "Read STREAM and return a string of all its contents."
357 (loop :as line
:= (read-line stream nil nil
)
359 :do
(setq s
(concatenate 'string s line
)))
362 (defun read-file (file)
363 "Read FILE and return a string of all its contents."
364 (with-open-file (f file
:direction
:input
)
365 (let ((len (file-length f
)))
367 (let ((s (make-string len
)))
372 (defun make-default-dst-package (grammarfile)
373 (make-package (gensym "opossum-parser")
374 :documentation
(format T
"Opossum parser for grammar ~A" grammarfile
)))
376 (defun generate-parser-package (grammarfile &key
(dst-package (make-package (gensym "opossum-parser-")))
377 start-rule
(parse-file-fun #'opossum
:parse-file
))
378 "Create functions to parse using GRAMMARFILE in DST-PACKAGE, starting ar rule named HEAD.
379 DST-PACKAGE will contain the 3 functions PARSE-STRING, PARSE-FILE and PARSE-STREAM as exported entrypoints."
380 (error "This is broken and needs to be merged with g-p-f.")
381 (let ((*package
* dst-package
))
382 (multiple-value-bind (form actions
)
383 (funcall parse-file-fun grammarfile
)
384 (format *debug-io
* "Injecting parser functions into ~A~%" dst-package
)
385 (loop :for aform
:in form
387 (format *debug-io
* "Skipping aform ~A~%" aform
)))
388 (loop :for
(sym code
) :in actions
389 :do
(intern (compile sym
`(lambda (data) (declare (ignorable data
)) ,code
)))
390 :do
(format *debug-io
* "Compiled ~A~%" sym
))
391 (intern (compile 'parse-string
393 `,(format nil
"Parse S using grammar ~A starting at ~A" grammarfile start-rule
)
394 (let ((*context
* (make-instance 'opossum
:context
:dstpkg
*package
* :input s
)))
395 (funcall (make-name start-rule
) 0)))))
396 (intern (compile 'parse-file
397 #'(lambda (f) (parse-string (read-file f
)))))
398 (intern (compile 'parse-stream
399 #'(lambda (s) (parse-string (read-stream s
)))))
401 (setf (documentation '*trace
* 'cl
:variable
)
402 "When non-nil, the generated parser function log to cl:*trace-output*.")
403 (export '(parse-string parse-file parse-stream
*trace
*)))))
405 (defun get-iso-time ()
406 "Return a string in ISO format for the current time"
407 (multiple-value-bind (second minute hour date month year day daylight-p zone
)
409 (declare (ignore day
))
410 (format nil
"~4D-~2,'0D-~2,'0D-~2,'0D:~2,'0D:~2,'0D (UCT~@D)"
413 (if daylight-p
(1+ (- zone
)) (- zone
)))))
415 (defun cleanup-action-code (code)
416 "Remove trailing newlines so that the string CODE can be printed nicely."
418 (when (char= #\Newline
(char code
(1- (length code
))))
419 (1+ (position #\Newline code
:from-end T
:test
#'char
/=)))))
421 (defun generate-parser-file (grammarfile dst-package dst-file
&key start-rule
(parse-file-fun #'opossum
:parse-file
))
422 "Create lisp code in DST-FILE that can be loaded to yield functions to parse using GRAMMARFILE in DST-PACKAGE.
423 DST-PACKAGE will contain the 3 functions PARSE-STRING, PARSE-FILE and PARSE-STREAM as exported entrypoints."
424 (let ((*package
* dst-package
))
425 (let ((result (funcall parse-file-fun grammarfile
)))
426 ;; FIXME: check for complete parse
427 (let ((*context
* result
)) ;; routines in pegutils.lisp expect *context* to be bound properly
428 (let ((forms (transform (value result
)))
429 (actions (actions result
)))
430 (with-open-file (s dst-file
:direction
:output
:if-exists
:supersede
)
431 (let ((*print-readably
* T
)
434 (dpkg (intern (package-name dst-package
) :keyword
)))
435 (format s
";; This is a Common Lisp peg parser automatically generated by OPOSSUM -*- mode:lisp -*-~%")
436 (format s
";; generated from ~A on ~A~%" grammarfile
(get-iso-time))
438 `(eval-when (:load-toplevel
:compile-toplevel
:execute
)
439 (declaim (optimize (speed 0) (safety 3) (debug 3))))
444 (:export
:parse-string
:parse-file
:parse-stream
))
446 (prin1 `(in-package ,dpkg
) s
) (terpri s
)
447 ;; First form is taken to be the start rule
448 (let ((entryrule (or (and start-rule
(make-name start-rule
))
449 (and forms
(cadr (first forms
))))))
451 (format *error-output
* "Cannot find entry rule for parser")
454 (format *trace-output
* "Inserting definitions for parser entry points through ~A~%"
457 (prin1 `(defun parse-string (,(intern :s dst-package
))
458 ,(format nil
"Parse S using grammar ~A starting at ~A" grammarfile entryrule
)
459 (let ((*context
* (make-instance 'opossum
:context
461 :input
,(intern :s dst-package
))))
462 (funcall (,entryrule
) 0)))
465 (loop :for aform
:in forms
466 :do
(when *trace
* (format *trace-output
* "Inserting form ~A~%" aform
))
472 `(defparameter ,(intern "*trace*" dst-package
) nil
473 "When non-nil, the generated parser function log to cl:*trace-output*.")
477 (loop :for
(sym code
) :in actions
478 :when sym
;; the final action is named NIL because we push a
479 ;; NIL ahead of us in store-actions
480 :do
(when *trace
* (format *trace-output
* "Inserting defun for ~A~%" sym
))
481 :and
:do
(format s
"~%(defun ~S (data)~% ~A)~%"
482 sym
(cleanup-action-code code
))))))))))
484 (defun transform (tree &optional
(depth 0))
487 (if (eq (first tree
) ':action
)
490 (format *trace-output
* "~AFound action ~A~%" (make-string depth
:initial-element
#\Space
) tree
))
492 (let ((data (mapcar #'(lambda (tr) (transform tr
(1+ depth
)))
494 (loop :for el
:in data
495 :when
(and (listp el
)
496 (eq (first el
) ':action
)
497 (symbolp (third el
)))
498 :do
(let ((*package
* (destpkg *context
*))
501 (format *trace-output
* "~&Applying action ~A to ~A~%" action data
))
503 (return-from transform
504 (funcall (symbol-function action
) data
))
505 (undefined-function (x)
507 (format *error-output
* "missing definition for ~A: ~A~%" action x
)
508 ; (break "~A in ~A" action *package*)