Clojure Instaparse Parser Tutorial: Partial Parse

By Xah Lee. Date:

The parses functions accepts optional argument:

:partial true → returns a lazy sequence of parse trees that are results of parsing increasingly more the input.

The function parse also accept the argument, but isn't useful. parse function basically just return the first element of parses.

Simple Example of Partial Parse

;; example of partial parse

(ns example.core (:require [instaparse.core :as insta]))

(def r3
  (insta/parser
    "S = 'a'+"))

(insta/parses r3 "aaa")
;; output
;; ([:S "a" "a" "a"])

(insta/parses r3 "aaa" :partial true)
;; output
;; ([:S "a"] [:S "a" "a"] [:S "a" "a" "a"] )

(insta/parse r3 "aaa")
;; output
;; [:S "a" "a" "a"]

(insta/parse r3 "aaa" :partial true)
;; output
;; [:S "a"]

More Examples

Here's a more complex example.

(ns example.core (:require [instaparse.core :as insta]))

(def pp
     (insta/parser
      "S = DIGIT (SPACES '+' SPACES DIGIT)*;
       SPACES = ' '*;
       DIGIT = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';"
      ))

(insta/parses pp "3 +4+ 5")
;; output
;; ([:S [:DIGIT "3"] [:SPACES " "] "+" [:SPACES] [:DIGIT "4"] [:SPACES] "+" [:SPACES " "] [:DIGIT "5"]])

(insta/parses pp "3 +4+ 5" :partial true)
;; output
;; ([:S [:DIGIT "3"]]
;;  [:S [:DIGIT "3"] [:SPACES " "] "+" [:SPACES] [:DIGIT "4"]]
;;  [:S [:DIGIT "3"] [:SPACES " "] "+" [:SPACES] [:DIGIT "4"] [:SPACES] "+" [:SPACES " "] [:DIGIT "5"]]
;; )

(insta/parse pp "3 +4+ 5")
;; output
;; [:S [:DIGIT "3"] [:SPACES " "] "+" [:SPACES] [:DIGIT "4"] [:SPACES] "+" [:SPACES " "] [:DIGIT "5"]]

(insta/parse pp "3 +4+ 5" :partial true)
;; output
;; [:S [:DIGIT "3"]]

back to Clojure Instaparse Parser Tutorial

If you have a question, put $5 at patreon and message me.

Clojure Instaparse