Engelberg / instaparse

Eclipse Public License 1.0
2.74k stars 148 forks source link

Compose parsers? #205

Closed theronic closed 5 months ago

theronic commented 3 years ago

I would love to be able to compose parsers, e.g.

(defparser thing
  {:S (c/cat (regexp "abc"))}
  :start :S)

(defparser container
  {:S (c/cat thing (regexp "def")}
  :start :S)

(As an aside, I find the combinator syntax much more flexible and readable than dealing with the string-based EBNF and ABNF syntaxes.)

Engelberg commented 3 years ago

The notion of what is the :start rule in one parser doesn't really make sense as a thing to compose within another parser. What you really want to compose is the individual rules from another grammar map, which you can do as long as you've given them non-conflicting names. You can retrieve the grammar map from inside a parser with :grammar.

(defparser thing
  {:ABC (c/cat (regexp "abc"))}
  :start :ABC)

(defparser container
  {:S (c/cat (:grammar thing) (regexp "def")}
  :start :S)