Clojure Instaparse Parser Tutorial: Output Formats

By Xah Lee. Date: . Last updated: .

Parse Tree Output Formats

Instaparse supports 2 output formats: “hiccup” and “enlive”. “hiccup” is default.

The output format is specified as a optional argument to the “parser” function. Example:

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

(def my-parser
  (insta/parser
    "S = AB*
     AB = A B
     A = 'a'+
     B = 'b'+"
    :output-format :enlive))
(my-parser "aaaaabbbaaaabb")

Hiccup Format Parse Tree

;; parse tree, in hiccup format (Instaparse default)
[:S
 [:AB [:A "a" "a" "a" "a" "a"]
      [:B "b" "b" "b"]]
 [:AB [:A "a" "a" "a" "a"]
      [:B "b" "b"]]]

Enlive Format Parse Tree

;; parse tree, in enlive format
{:tag :S,
 :content
 ({:tag :AB,
   :content
   ({:tag :A, :content ("a" "a" "a" "a" "a")}
    {:tag :B, :content ("b" "b" "b")})}
  {:tag :AB,
   :content
   ({:tag :A, :content ("a" "a" "a" "a")}
    {:tag :B, :content ("b" "b")})})}

You can use the enlive lib to transform your parse tree. See: https://github.com/cgrand/enlive

set default output format

(insta/set-default-output-format! :enlive)

Note: this will set output format only for newly created parser.

back to Clojure Instaparse Parser Tutorial