Function: peg-run

peg-run is a byte-compiled function defined in peg.el.gz.

Signature

(peg-run PEG-MATCHER &optional FAILURE-FUNCTION SUCCESS-FUNCTION)

Documentation

Parse with PEG-MATCHER at point and run the success/failure function.

If a match was found, move to the end of the match and call SUCCESS-FUNCTION with one argument: a function which will perform all the actions collected during the parse and then return the resulting stack (or t if empty). If no match was found, move to the (rightmost) point of parse failure and call FAILURE-FUNCTION with one argument, which is a list of PEG expressions that failed at this point. SUCCESS-FUNCTION defaults to funcall and FAILURE-FUNCTION defaults to ignore.

View in manual

Source Code

;; Defined in /usr/src/emacs/lisp/progmodes/peg.el.gz
;; There are several "infos we want to return" when parsing a given PEX:
;; 1- We want to return the success/failure of the parse.
;; 2- We want to return the data of the successful parse (the stack).
;; 3- We want to return the diagnostic of the failures.
;; 4- We want to perform the actions (upon parse success)!
;; `peg-parse' used an error signal to encode the (1) boolean, which
;; lets it return all the info conveniently but the error signal was sometimes
;; inconvenient.  Other times one wants to just know (1) maybe without even
;; performing (4).
;; `peg-run' lets you choose all that, and by default gives you
;; (1) as a simple boolean, while also doing (2), and (4).

(defun peg-run (peg-matcher &optional failure-function success-function)
  "Parse with PEG-MATCHER at point and run the success/failure function.
If a match was found, move to the end of the match and call SUCCESS-FUNCTION
with one argument: a function which will perform all the actions collected
during the parse and then return the resulting stack (or t if empty).
If no match was found, move to the (rightmost) point of parse failure and call
FAILURE-FUNCTION with one argument, which is a list of PEG expressions that
failed at this point.
SUCCESS-FUNCTION defaults to `funcall' and FAILURE-FUNCTION
defaults to `ignore'."
  (let ((peg--actions '()) (peg--errors '(-1)))
    (if (funcall peg-matcher)
        ;; Found a parse: run the actions collected along the way.
        (funcall (or success-function #'funcall)
                 (lambda ()
                   (save-excursion (peg-postprocess peg--actions))))
      (goto-char (car peg--errors))
      (when failure-function
        (funcall failure-function (peg-merge-errors (cdr peg--errors)))))))