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
)
143 `(let* ((*context
* (clone-ctx *context
* ,name
))
144 (result (funcall ,parser offset
)))
147 (if (ctx-failed-p result
)
149 (succeed *context
* (value result
) (start-index result
) (end-index result
)))))
153 (defun match-string (string)
155 (let ((input (input *context
*))
156 (len (length string
)))
157 (if (and (>= (length input
) (+ offset len
))
158 (string= string input
:start2 offset
:end2
(+ offset len
)))
159 (succeed (clone-ctx *context
* 'opossum-string
) string offset
(+ offset
(length string
)))
162 (defun match-char (char-list)
164 (let ((input (input *context
*)))
166 (format *trace-output
* "match-char: looking for one of `~{~A~}'~%" char-list
))
167 (if (and (> (length input
) offset
)
168 (member (char input offset
)
169 char-list
:test
#'char
=))
170 (succeed (clone-ctx *context
* 'opossum-char
) (char input offset
) offset
(+ offset
1))
173 (defun match-octal-char-code (i1 i2 i3
)
174 "Compare the character given by i3 + 8*i2 + 64*i1 to the next input character."
175 (let ((c (+ i3
(* 8 i2
) (* 64 i1
))))
177 (let ((input (input *context
*)))
179 (format *trace-output
* "match-octal-char-code: looking for ~D~%" c
))
180 (if (and (> (length input
) offset
)
181 (= (char-int (char input offset
)) c
))
182 (succeed (clone-ctx *context
* 'opossum-char
) (char input offset
) offset
(+ offset
1))
185 (defun match-char-range (lower-char upper-char
)
186 "Match characters in the range between LOWER-CHAR and UPPER-CHAR (inclusive) as decided by CL:CHAR-CODE."
188 (let ((input (input *context
*)))
190 (format *trace-output
* "match-char-range: looking for ~A-~A~%" lower-char upper-char
))
191 (if (and (> (length input
) offset
)
192 (let ((x (char-code (char input offset
))))
193 (and (>= x
(char-code lower-char
))
194 (<= x
(char-code upper-char
)))))
195 (succeed (clone-ctx *context
* 'opossum-char-range
) (char input offset
) offset
(+ offset
1))
198 (defun match-any-char (&optional ignored
)
199 (declare (ignore ignored
))
201 "Match any character at OFFSET, fail only on EOF."
202 (let ((input (input *context
*)))
204 (format *trace-output
* "match-any-char~%"))
205 (if (< (1+ offset
) (length input
))
206 (succeed (clone-ctx *context
* 'opossum-anychar
) (char input offset
) offset
(+ offset
1))
209 (defun match-char-class (char-class)
210 "Regexp matching of next input character against [CHAR-CLASS] using cl-ppcre:scan."
211 (declare (type string char-class
))
212 ;; FIXME: could use a pre-computed scanner
213 (let ((cc (format nil
"[~A]" char-class
)))
215 "Match next character at OFFSET against the characters in CHAR-CLASS."
216 (let ((input (input *context
*)))
218 (format *trace-output
* "match-char-class on ~A~%"))
219 (if (and (< (1+ offset
) (length input
))
220 (let ((c (char input offset
)))
221 (cl-ppcre:scan cc
(make-string 1 :initial-element c
))))
222 (succeed (clone-ctx *context
* 'opossum-charclass
)
223 (char input offset
) offset
(+ offset
1))
226 (defun fix-escape-sequences (char-list)
227 "Iterate over the list CHAR-LIST, glueing adjacent #\\ #\n and #\\ #\t chars into
228 #\Newline and #\Tab."
230 ((null char-list
) char-list
)
231 ((null (cdr char-list
)) char-list
)
233 (loop :with drop
:= nil
234 :for
(c1 c2
) :on char-list
238 :collect
(if (char= c1
#\\)
240 ((#\n) (setf drop T
) #\Newline
)
241 ((#\t) (setf drop T
) #\Tab
)
242 ((#\r) (setf drop T
) #\Linefeed
)
248 ;; parsing combinator functions cribbed from libmetapeg
250 (defun either (&rest parsers
)
251 "Produce a function that tries each of the functions in PARSERS sequentially until one succeeds and
252 returns the result of that function, or a failure context if none succeeded."
254 (let ((*context
* (clone-ctx *context
* 'opossum-either
)))
256 (format *trace-output
* "either: ~A ~A~%" *context
* parsers
))
257 (loop :for p
:in parsers
258 :as result
= (funcall p offset
)
259 :when
(not (ctx-failed-p result
))
260 :return
(succeed *context
* (value result
) offset
(end-index result
))
261 :finally
(return (fail))))))
264 (defun optional (parser)
266 (let ((*context
* (clone-ctx *context
* 'opossum-optional
)))
268 (format *trace-output
* "optional: ~A ~A~%" *context
* parser
))
269 (let ((result (funcall parser offset
)))
270 (if (ctx-failed-p result
)
271 (succeed *context
* 'optional offset offset
)
272 (succeed *context
* (value result
) offset
(end-index result
)))))))
274 (defun follow (parser)
276 (let ((*context
* (clone-ctx *context
* 'opossum-follow
)))
278 (format *trace-output
* "follow: ~A ~A~%" *context
* parser
))
279 (let ((result (funcall parser offset
)))
280 (if (ctx-failed-p result
)
282 (succeed *context
* (value result
)
283 ;; don't consume input
288 (let ((*context
* (clone-ctx *context
* 'opossum-many
))
289 (start-offset offset
)
292 (format *trace-output
* "many: ~A ~A~%" *context
* parser
))
293 (loop :as result
:= (funcall parser offset
)
294 :while
(not (ctx-failed-p result
))
295 :do
(progn (push (value result
) children
)
296 (setf offset
(end-index result
)))
297 :finally
(return (succeed *context
* (nreverse children
) start-offset offset
))))))
300 (defun many1 (parser)
302 (let* ((*context
* (clone-ctx *context
* 'opossum-many1
))
303 (result (funcall parser offset
)))
305 (format *trace-output
* "many1: ~A ~A~%" *context
* parser
))
306 (if (not (ctx-failed-p result
))
307 (let ((result2 (funcall (many parser
) (end-index result
))))
308 (if (end-index result2
)
309 (succeed *context
* (cons (value result
) (value result2
)) offset
(end-index result2
))
310 (succeed *context
* (value result
) offset
(end-index result
))))
314 (defun seq (&rest parsers
)
316 (assert (> (length parsers
) 0))
317 (let ((*context
* (clone-ctx *context
* 'opossum-seq
))
318 (start-offset offset
)
322 (format *trace-output
* "seq: ~A ~A~%" *context
* parsers
))
324 (loop :for p
:in parsers
325 :do
(when *trace
* (format *trace-output
* " (seq ~A) trying ~A~%" *context
* p
))
328 (push (succeed (clone-ctx *context
* 'action
) nil offset offset
) child-nodes
)
329 (push p child-values
)
330 (setf (children *context
*) (reverse child-nodes
)))
332 (let ((result (funcall p offset
)))
333 (if (end-index result
)
335 (push result child-nodes
)
336 (push (value result
) child-values
)
337 (setf offset
(end-index result
))
338 (setf (children *context
*) (reverse child-nodes
)))
340 :finally
(return (succeed *context
* (reverse child-values
) start-offset offset
))))))
342 (defun negate (parser)
344 "Return a successful context at OFFSET if PARSER succeeds, without advancing input position."
345 (let ((*context
* (clone-ctx *context
* 'opossum-negate
)))
346 (let ((result (funcall parser offset
)))
347 (if (ctx-failed-p result
)
348 (succeed *context
* 'negate offset offset
)
353 (defun read-stream (stream)
354 "Read STREAM and return a string of all its contents."
356 (loop :as line
:= (read-line stream nil nil
)
358 :do
(setq s
(concatenate 'string s line
)))
361 (defun read-file (file)
362 "Read FILE and return a string of all its contents."
363 (with-open-file (f file
:direction
:input
)
364 (let ((len (file-length f
)))
366 (let ((s (make-string len
)))
371 (defun make-default-dst-package (grammarfile)
372 (make-package (gensym "opossum-parser")
373 :documentation
(format T
"Opossum parser for grammar ~A" grammarfile
)))
375 (defun generate-parser-package (grammarfile dst-package head
)
376 "Create functions to parse using GRAMMARFILE in DST-PACKAGE, starting ar rule named HEAD.
377 DST-PACKAGE will contain the 3 functions PARSE-STRING, PARSE-FILE and PARSE-STREAM as exported entrypoints."
378 (let ((*package
* dst-package
))
379 (multiple-value-bind (form actions
)
380 (opossum:parse-file grammarfile
)
381 (format *debug-io
* "Injecting parser functions into ~A~%" dst-package
)
382 (loop :for aform
:in form
384 (format *debug-io
* "Skipping aform ~A~%" aform
)))
385 (loop :for
(sym code
) :in actions
386 :do
(intern (compile sym
`(lambda (data) (declare (ignorable data
)) ,code
)))
387 :do
(format *debug-io
* "Compiled ~A~%" sym
))
388 (intern (compile 'parse-string
390 `,(format nil
"Parse S using grammar ~A starting at ~A" grammarfile head
)
391 (let ((*context
* (make-instance 'opossum
:context
:dstpkg
*package
* :input s
)))
392 (funcall (make-name head
) 0)))))
393 (intern (compile 'parse-file
394 #'(lambda (f) (parse-string (read-file f
)))))
395 (intern (compile 'parse-stream
396 #'(lambda (s) (parse-string (read-stream s
)))))
398 (setf (documentation '*trace
* 'cl
:variable
)
399 "When non-nil, the generated parser function log to cl:*trace-output*.")
400 (export '(parse-string parse-file parse-stream
*trace
*)))))
402 (defun get-iso-time ()
403 "Return a string in ISO format for the current time"
404 (multiple-value-bind (second minute hour date month year day daylight-p zone
)
406 (declare (ignore day
))
407 (format nil
"~4D-~2,'0D-~2,'0D-~2,'0D:~2,'0D:~2,'0D (UCT~@D)"
410 (if daylight-p
(1+ (- zone
)) (- zone
)))))
412 (defun cleanup-action-code (code)
413 "Remove trailing newlines so that the string CODE can be printed nicely."
415 (when (char= #\Newline
(char code
(1- (length code
))))
416 (1+ (position #\Newline code
:from-end T
:test
#'char
/=)))))
418 (defun generate-parser-file (grammarfile dst-package dst-file
&optional start-rule
)
419 "Create lisp code in DST-FILE that can be loaded to yield functions to parse using GRAMMARFILE in DST-PACKAGE.
420 DST-PACKAGE will contain the 3 functions PARSE-STRING, PARSE-FILE and PARSE-STREAM as exported entrypoints."
421 (let ((*package
* dst-package
))
422 (let ((result (opossum:parse-file grammarfile
)))
423 ;; FIXME: check for complete parse
424 (let ((*context
* result
)) ;; routines in pegutils.lisp expect *context* to be bound properly
425 (let ((forms (transform (value result
)))
426 (actions (actions result
)))
427 (with-open-file (s dst-file
:direction
:output
:if-exists
:supersede
)
428 (let ((*print-readably
* T
)
430 (*print-circle
* NIL
))
431 (format s
";; This is a Common Lisp peg parser automatically generated by OPOSSUM -*- mode:lisp -*-~%")
432 (format s
";; generated from ~A on ~A~%" grammarfile
(get-iso-time))
433 (format s
"(eval-when (:load-toplevel :compile-toplevel :execute) (declaim (optimize (speed 0) (safety 3) (debug 3))))~%~%")
434 (format s
"(defpackage #:~A~%" (package-name dst-package
))
435 (format s
" (:use #:cl #:opossum)~%")
436 (format s
" (:export #:parse-string #:parse-file #:parse-stream))~%")
437 (format s
"~%(in-package #:~A)~%" (package-name dst-package
))
438 ;; First form is taken to be the start rule
439 (let ((entryrule (or (and start-rule
(make-name start-rule
))
440 (and forms
(cadr (first forms
))))))
442 (format *error-output
* "Cannot find entry rule for parser")
445 (format *trace-output
* "Inserting definitions for parser entry points through ~A~%"
448 (prin1 `(defun parse-string (,(intern :s dst-package
))
449 ,(format nil
"Parse S using grammar ~A starting at ~A" grammarfile entryrule
)
450 (let ((*context
* (make-instance 'opossum
:context
451 :dstpkg
,(package-name dst-package
)
452 :input
,(intern :s dst-package
))))
453 (funcall (,entryrule
) 0)))
456 (loop :for aform
:in forms
457 :do
(when *trace
* (format *trace-output
* "Inserting form ~A~%" aform
))
463 `(defparameter ,(intern "*trace*" dst-package
) nil
464 "When non-nil, the generated parser function log to cl:*trace-output*.")
468 (loop :for
(sym code
) :in actions
469 :when sym
;; the final action is named NIL because we push a
470 ;; NIL ahead of us in store-actions
471 :do
(when *trace
* (format *trace-output
* "Inserting defun for ~A~%" sym
))
472 :and
:do
(format s
"~%(defun ~S (data)~% ~A)~%"
473 sym
(cleanup-action-code code
))))))))))
475 (defun transform (tree &optional
(depth 0))
478 (if (eq (first tree
) ':action
)
481 (format *trace-output
* "~AFound action ~A~%" (make-string depth
:initial-element
#\Space
) tree
))
483 (let ((data (mapcar #'(lambda (tr) (transform tr
(1+ depth
)))
485 (loop :for el
:in data
486 :when
(and (listp el
)
487 (eq (first el
) ':action
)
488 (symbolp (third el
)))
489 :do
(let ((*package
* (destpkg *context
*))
492 (format *trace-output
* "~&Applying action ~A to ~A~%" action data
))
494 (return-from transform
495 (funcall (symbol-function action
) data
))
496 (undefined-function (x)
498 (format *error-output
* "missing definition for ~A: ~A~%" action x
)
499 ; (break "~A in ~A" action *package*)