[comp.unix.questions] Lex & Yacc

rom@mvsun.ericsson.se (Robert Malmgren TK/DG) (03/05/91)

I'm trying to learn yacc and lex, but I'm having a tough time. I've written
a simple testprogram that does an arithmetic operation on two args. The 
problem is that it works the first time I enter the digits and prints the
correct result, but fails with a 'syntax error'-message the second time. Why? 
Could someone please enlighten me.

--------------------------------------- c.l -----------------------------------
%%
[ \t]+	;

[0-9]+	{
	sscanf(yytext, "%d", &yylval);
	return INTEGER;
	}

[-+\*]	return yytext[0];

\n	return '\n';
%%
--------------------------------------- c.y -----------------------------------
%token INTEGER

%%
line:		'\n'
	|	expr '\n'
			{printf("%d\n", $1);}
	;

expr:  		expr '+' expr 
			{$$ = $1 + $3;}
	|	expr '-' expr
			{$$ = $1 - $3;}
	|	expr '*' expr
			{$$ = $1 * $3;}
	|	int
	;

int:		INTEGER  {
			$$ = $1;
		}
	;
%%
#include "lex.yy.c"


-------------------------------------------------------------------------------
Robert Malmgren    ! Phone: +46 8 7197937 ! Internet: rom@miranda.ericsson.se
MV/ETX/TK/DG       ! Fax  : +46 8 7196443 ! UUCP: ..uunet!mvsun.ericsson.se!rom
Ericsson Telecom   ! Home : +46 8 933733  ! SUNET   : MINDA::ROBERT

dclark@b11.ingr.com (Dave Clark) (03/07/91)

rom@mvsun.ericsson.se (Robert Malmgren TK/DG) writes:

>I'm trying to learn yacc and lex, but I'm having a tough time. I've written
>a simple testprogram that does an arithmetic operation on two args. The 
>problem is that it works the first time I enter the digits and prints the
>correct result, but fails with a 'syntax error'-message the second time. Why? 
>Could someone please enlighten me.

{Lex stuff deleted}

>--------------------------------------- c.y -----------------------------------
>%token INTEGER

>%%
>line:		'\n'
>	|	expr '\n'
>			{printf("%d\n", $1);}
>	;

{Yacc stuff deleted}

Yacc begins parsing with the first production ("line" in your example).  To
change this, use the %start directive.

The first production is successfully parsed -- fine.  But your grammar defines
that there should be only one "line" per file.  To fix this, you can add the
following production (before "line" in your file).

file:	/* empty */
	| line file
	;

This allows a "file" to consist of zero or more lines.


-- 
----------------------------------------------------------------------------
   Dave Clark                     |
   System Development             |  I among men bear the same wounded hand,
   Intergraph Corp., CR1102       |  suffer the same reddened cup