yacc sorrows

andre andre at targon.UUCP
Wed Feb 14 20:47:04 AEST 1990


In article <7179 at arcturus> evil at arcturus.UUCP (Wade Guthrie) writes:

  >My problem is this: I am trying to get access to the strings that
  >got matched by lex to make the tokens which are passed to yacc.
  >Given this, I can do the job (I think).  This is on a sun 3/60 under
  >the 3.4 version of the operating system.  After RTFMing (and
  >gratuitous consultation of my local guru), I got to the part that
  >says "the programmer includes in the declaration section [of the
  >yacc grammar] %union { body }  This declares the yacc value stack
  >[...] the value is referenced through a $$ or $n construction, yacc
  >automatically inserts the appropriate union name", or some such.
  >I tried this approach (and another that I will get to soon).

If you declare a union for the yacc stack, you must do two
things to use the union.

1       tell yacc with (non) terminals have which type
2       let the lex code fill the members of the
	global union yylval.
3       (easier) put an include lex.yy.c in the last part
	of the yacc file then you need not fiddle with the include
	file.

Example (not tested)

lex:
%%
[a-zA-Z][a-zA-Z0-9_]*   { yylval.str = strncpy(malloc(yyleng+1), yytext, yyleng);
			  return NAME; }
[0-9]+                  { yylval.nr  = atoi(yytext);
			  return INT; }
%%

yacc:

%union VALTYPE {
    int  nr;
    char *str;
};


%token <str> NAME string
%token <nr>  INT  number

%%

file    : string {printf("NAME %s\n", $1};
	| number {printf("INT  %d\n", $1};
	;

string  : NAME
	;

number  : INT
	;

%%

#include "lex.yy.c"

This should get you back on the road :-).


-- 
The mail|    AAA         DDDD  It's not the kill, but the thrill of the chase.
demon...|   AA AAvv   vvDD  DD        Ketchup is a vegetable.
hits!.@&|  AAAAAAAvv vvDD  DD                    {nixbur|nixtor}!adalen.via
--more--| AAA   AAAvvvDDDDDD    Andre van Dalen, uunet!hp4nl!targon!andre



More information about the Comp.lang.c mailing list