Search code examples
clojuredslcontext-free-grammarinstaparse

Grammar that allows arbitrary rules order


I'm (trying) to design a domain-specific language (I called it "Fahrenheit") for designing citation styles.

A program written in Fahrenheit:

  • MUST have exactly one citation block
  • MAY have zero or more macro blocks.

Here's a simplified yet valid example:

macro m1
  "Hello World!"
end

macro m2
  "Hello World!"
end

citation
  "Hello World!"
end

This grammar will recognise the above code as syntactically correct:

style = macro* citation

(*  example of macro definition

    macro hw
        "Hello World!"
    end

    *)

macro = <'macro'> #'[a-z0-9]+' statement+ end

citation = <'citation'> statement+ end

statement = #'".*?"'

<end> = <'end'>

However the ordering of "blocks" (e.g macro or citation) shouldn't matter.

Question: How should I change my grammar so that it recognises the following program as syntactically correct?

macro m1
  "Hello World!"
end

citation
  "Hello World!"
end

macro m2
  "Hello World!"
end

PS: I'm intending to add other optional blocks which order is also irrelevant.


Solution

  • For the 0..n rules you can put them before or after the citation. E.g.

    style = tools* citation tools*
    tools = macro | foo | bar
    ...