Question

I would like to write a grammar rule of the nature:

program = { expression }

where {} indicates 1 or more.

For example, Lua's grammar uses the same syntax:

chunk ::= {stat [`;´]} [laststat [`;´]]

Is this possible? Does this conform with context free grammar?

Was it helpful?

Solution

I believe the best simple solution is:

program : expression
        | program NEWLINE expression

This only works since PLY generates LR grammars, a nonterminal can't begin with itself (left-recursion) in LL grammars (if you were using a tool such as ANTLR)

You could also do:

program : expression
        | expression NEWLINE program

This second version is nice because it's compatible with both LL and LR grammars, but I believe the first rule is more efficient for an LR parser.

OTHER TIPS

I found the answer:

program : expression
        | expression NEWLINE expression
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top