|
Home > Archive > Unix Programming > April 2006 > how to write a grammar rule with yacc/bison
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
how to write a grammar rule with yacc/bison
|
|
| justincui@gmail.com 2006-04-27, 7:55 am |
| Hi,
How to write such a grammar rule that it looks like "Y --> X1; X2;
X3; ..; X100;" but X1, X2,..., X100 can appear once and only once and
having no limitation on the order?
Best Regards,
Justin Cui
| |
| Pascal Bourguignon 2006-04-27, 7:55 am |
| justincui@gmail.com writes:
> How to write such a grammar rule that it looks like "Y --> X1; X2;
> X3; ..; X100;" but X1, X2,..., X100 can appear once and only once and
> having no limitation on the order?
If you want to enforce that at the syntax level, you'll have to write
a rule for each combination.
I would just write:
Y : X-sequence ;
X_sequence : | X ';' X_sequence ;
X : X1 | X2 | X3 | ... | X100 ;
and check at the semantic level that each X occured only once:
Y : X-sequence { if(duplicate_X($1){error("Duplicate X");} return $1; } ;
--
__Pascal Bourguignon__ http://www.informatimago.com/
Un chat errant
se soulage
dans le jardin d'hiver
Shiki
| |
|
| Pascal Bourguignon wrote:
> justincui@gmail.com writes:
>
> If you want to enforce that at the syntax level, you'll have to write
> a rule for each combination.
>
> I would just write:
>
> Y : X-sequence ;
> X_sequence : | X ';' X_sequence ;
> X : X1 | X2 | X3 | ... | X100 ;
>
> and check at the semantic level that each X occured only once:
>
> Y : X-sequence { if(duplicate_X($1){error("Duplicate X");} return $1; } ;
You can also check earlier,
%{
int seen[100];
%}
%%
Y : XSEQ '\n' ;
XSEQ : X | XSEQ ';' X ;
X : XTOK
{ printf("saw: %c\n",$1);
if(seen[$1-'0']) { yyerror("duplicate"); YYERROR; }
else seen[$1-'0'] = 1;
};
XTOK : '1'|'2'|'3';
%%
int yylex(){
return yylval = getchar();
}
>
>
> --
> __Pascal Bourguignon__ http://www.informatimago.com/
> Un chat errant
> se soulage
> dans le jardin d'hiver
> Shiki
|
|
|
|
|