0
votes

I would like to write an LR(1) grammar in BNF form for the language described by these two rules from The Complete Syntax of Lua:

parlist ::= namelist [`,´ `...´] | `...´
namelist ::= Name {`,´ Name}

I have tried the following grammars, but according to the tool I am using, both are "not LR(1) due to shift-reduce conflict":

parlist ::= namelist
parlist ::= namelist , ...
parlist ::= ...

namelist ::= Name namelist1
namelist1 ::= , Name namelist1
namelist1 ::= <epsilon>

parlist ::= namelist
parlist ::= namelist , ...
parlist ::= ...

namelist ::= namelist1 Name
namelist1 ::= namelist1 Name ,
namelist1 ::= <epsilon>

Is there an LR(1) grammar, in BNF form, for this language?

2
Why aren't you using namelist ::= Name and namelist ::= namelist , Name rules?Jonathan Leffler

2 Answers

0
votes

Here's a simple one:

parlist ::= Name
parlist ::= ...
parlist ::= Name , parlist

Here's a slightly less simple one which has the advantage of being left-recursive:

parlist ::= namelist
parlist ::= namelist , ...
parlist ::= ...
namelist ::= Name
namelist ::= namelist , Name

The rather artificial distortion of the grammar using an artificial namelist1 non-terminal, which looks like it is taken out of an LL grammar, is just causing problems. (It's not making the grammar LL(1) either, although that could easily be done by left factoring the first alternative above.)

0
votes

Here's a bison grammar with no conflicts. It's LALR(1), which makes it also LR(1):

%token ELIPSES COMMA NAME
%%
parlist : namelist parlistsuffix
        | ELIPSES
        ;
parlistsuffix: COMMA ELIPSES
        | /* epsilon */
        ;
namelist: namelist COMMA NAME
        | NAME
        ;