简体   繁体   中英

LR(1) BNF grammar for function parameters with trailing elipsis

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?

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.)

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
        ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM