LEX & YACC Help!

wizzz

Senior member
Jul 20, 2000
267
0
0
I'm trying to do this really simple thing by using lex and yacc but I have been sitting in front of my computer for hours! Can someone help me on this?

I'm trying to use lex to recognize tokens and parse the tokens using Yacc.
For example, I want my program to recognize a line with specific commands such as "open" or numbers. So right now, I want to recognize "open" and printf out a line saying I recognized "open".


so in my lex file, I have

%{
#include <stdio.h>
#include &quot;logo.h&quot;
#include &quot;logo.tab.h&quot;
%}

%%
[0-9]+ { yylval.val = atoi(yytext);
return NUMBER; }

[ \t] ;

open {struct symtab *sp;
yylval.symp = sp;
return OPEN; }
%%



In my Yacc file I have,

%{
#include <stdio.h>
%}

%union {
int val;
struct symtab *symp;
}

%token <val> NUMBER
%token <symp> OPEN

%type <symp> Command

%%

expr:
| expr Command '\n'
;

Command : OPEN
{ printf (&quot;OPEN!!!\n&quot;);}
| NUMBER
{ printf (&quot;%d&quot;, yylval.val); }
;


%%

yyerror(s)
char *s;
{
fprintf(stderr, &quot;%s\n&quot;, s);
}


My logo.h looks like:

#define OPEN 258
#define NUMBER 257

struct symtab {
char *name;
}symtab;



I have to use both lex and yacc to do this.
I think I'm doing the lexing correctly but I don't know how to tell yacc that I got &quot;open&quot; and print out a message. When I run the above, and when I enter (in stdin) &quot;open&quot;, it prints a blank line. But when I write &quot;blah&quot; it will print back &quot;blah&quot;.

Can anybody please help me on this?
I'd greatly appreciate any help.
 

br0wn

Senior member
Jun 22, 2000
572
0
0
Change your code to something like the following :

IN THE LEX FILE :

%{
#include <stdio.h>
#include &quot;logo.tab.h&quot;
%}

%%
[0-9]+ { yylval.val = atoi(yytext);
return NUMBER; }

[ \t] ;

open {struct symtab *sp;
yylval.symp = sp;
return OPEN; }
%%



IN THE YACC FILE :

%{
#include <stdio.h>
extern int yylex(); /* YOU FORGOT TO ADD THIS */
extern char *yytext; /* YOU FORGOT TO ADD THIS */
%}

%union {
int val;
struct symtab *symp;
}

%token <val> NUMBER
%token <symp> OPEN

%type <symp> Command

%%

expr:
| expr Command '\n' /* I THINK YOU DON'T WANT THE '\n' HERE */
;

Command : OPEN
{ printf (&quot;OPEN!!!\n&quot;);}
| NUMBER
{ printf (&quot;%d&quot;, yylval.val); }
;


%%

yyerror(s)
char *s;
{
fprintf(stderr, &quot;%s\n&quot;, s);
}

Have fun.