|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
(define-module (ice-9 peg using-parsers) |
|
#:use-module (ice-9 peg simplify-tree) |
|
#:use-module (ice-9 peg codegen) |
|
#:use-module (ice-9 peg cache) |
|
#:use-module (srfi srfi-9) |
|
#:export (match-pattern define-peg-pattern search-for-pattern |
|
prec make-prec peg:start peg:end peg:string |
|
peg:tree peg:substring peg-record?)) |
|
|
|
(define-record-type prec |
|
(make-prec start end string tree) |
|
peg-record? |
|
(start prec-start) |
|
(end prec-end) |
|
(string prec-string) |
|
(tree prec-tree)) |
|
|
|
(define (peg:start pm) |
|
(and pm (prec-start pm))) |
|
(define (peg:end pm) |
|
(and pm (prec-end pm))) |
|
(define (peg:string pm) |
|
(and pm (prec-string pm))) |
|
(define (peg:tree pm) |
|
(and pm (prec-tree pm))) |
|
(define (peg:substring pm) |
|
(and pm (substring (prec-string pm) (prec-start pm) (prec-end pm)))) |
|
|
|
|
|
|
|
|
|
|
|
(define-syntax until |
|
(syntax-rules () |
|
"Evaluate TEST. If it is true, return its value. Otherwise, |
|
execute the STMTs and try again." |
|
((_ test stmt stmt* ...) |
|
(let lp () |
|
(or test |
|
(begin stmt stmt* ... (lp))))))) |
|
|
|
|
|
|
|
|
|
|
|
|
|
(define (match-pattern nonterm string) |
|
|
|
|
|
|
|
(let ((res (nonterm (string-copy string) (string-length string) 0))) |
|
(if (not res) |
|
#f |
|
(make-prec 0 (car res) string (string-collapse (cadr res)))))) |
|
|
|
|
|
(define-syntax define-peg-pattern |
|
(lambda (x) |
|
(syntax-case x () |
|
((_ sym accum pat) |
|
(let ((matchf (compile-peg-pattern #'pat (syntax->datum #'accum))) |
|
(accumsym (syntax->datum #'accum))) |
|
|
|
(let ((syn (wrap-parser-for-users x matchf accumsym #'sym))) |
|
#`(define sym #,(cg-cached-parser syn)))))))) |
|
|
|
(define (peg-like->peg pat) |
|
(syntax-case pat () |
|
(str (string? (syntax->datum #'str)) #'(peg str)) |
|
(else pat))) |
|
|
|
|
|
|
|
(define-syntax search-for-pattern |
|
(lambda (x) |
|
(syntax-case x () |
|
((_ pattern string-uncopied) |
|
(let ((pmsym (syntax->datum #'pattern))) |
|
(let ((matcher (compile-peg-pattern (peg-like->peg #'pattern) 'body))) |
|
|
|
|
|
|
|
|
|
#`(let ((string (string-copy string-uncopied)) |
|
(strlen (string-length string-uncopied)) |
|
(at 0)) |
|
(let ((ret (until (or (>= at strlen) |
|
(#,matcher string strlen at)) |
|
(set! at (+ at 1))))) |
|
(if (eq? ret #t) ;; (>= at strlen) succeeded |
|
#f |
|
(let ((end (car ret)) |
|
(match (cadr ret))) |
|
(make-prec |
|
at end string |
|
(string-collapse match)))))))))))) |
|
|