Lex & Yacc

Dave Clark dclark at b11.ingr.com
Thu Mar 7 04:58:05 AEST 1991


rom at 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



More information about the Comp.unix.questions mailing list