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 "logo.h"
#include "logo.tab.h"
%}
%%
[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 ("OPEN!!!\n"
;}
| NUMBER
{ printf ("%d", yylval.val); }
;
%%
yyerror(s)
char *s;
{
fprintf(stderr, "%s\n", 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 "open" and print out a message. When I run the above, and when I enter (in stdin) "open", it prints a blank line. But when I write "blah" it will print back "blah".
Can anybody please help me on this?
I'd greatly appreciate any help.
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 "logo.h"
#include "logo.tab.h"
%}
%%
[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 ("OPEN!!!\n"
| NUMBER
{ printf ("%d", yylval.val); }
;
%%
yyerror(s)
char *s;
{
fprintf(stderr, "%s\n", 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 "open" and print out a message. When I run the above, and when I enter (in stdin) "open", it prints a blank line. But when I write "blah" it will print back "blah".
Can anybody please help me on this?
I'd greatly appreciate any help.
