سؤال

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?

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

I found the answer:

program : expression
        | expression NEWLINE expression
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top