B
betterking
I want to write a tiny sql parser with lex and yacc. At first I just
write sql.l sql.y with simple CREATE TABLE funciton.
sql.l
%{
#include "y.tab.h" //<>
#include <stdlib.h>
#include <string.h>
void yyerror(char *);
%}
%%
CREATE { return CREATE;}
TABLE { return TABLE;}
[0-9]+ {
yylval.intval =
atoi(yytext);
return INTEGER;
}
[a-z][a-z0-9]* {
strcpy(yylval.nameval,
yytext);
// fprintf(stderr,
"-----%s\n", *yytext);
return NAME;
}
[<>=] {
yylval.compval =
yytext[0];
return COMPARE;
}
[\n] { return *yytext;
}
[ \t] ;
.. {
yyerror("Unknown
Character!");
}
%%
int yywrap(void)
{
return 1;
}
sql.y:
%{
#include <stdio.h>
void yyerror(char *s);
int yylex(void);
%}
%union {
int intval;
char nameval[50];
char compval;
};
%token <intval> INTEGER
%token <nameval> NAME
%token <compval> COMPARE
%token CREATE TABLE
%%
createtablestatement:
| createtablestatement '\n'
| CREATE TABLE NAME '\n' {printf("%s\n", $3);}
;
%%
void yyerror(char *s)
{
fprintf(stderr," %s\n", s);
}
int main(void)
{
yyparse();
}
I compile and run it as follows:
lex sql.l
yacc -d sql.y
gcc -o create lex.yy.c y.tab.c -ll
$./create
CREATE TABLE aaaa
aaaa
CREATE TABLE bbbb
parse error
$
I want to know why it could run at the first time, but it could not
run at the second time.
Please help me. Thanks a lot!
write sql.l sql.y with simple CREATE TABLE funciton.
sql.l
%{
#include "y.tab.h" //<>
#include <stdlib.h>
#include <string.h>
void yyerror(char *);
%}
%%
CREATE { return CREATE;}
TABLE { return TABLE;}
[0-9]+ {
yylval.intval =
atoi(yytext);
return INTEGER;
}
[a-z][a-z0-9]* {
strcpy(yylval.nameval,
yytext);
// fprintf(stderr,
"-----%s\n", *yytext);
return NAME;
}
[<>=] {
yylval.compval =
yytext[0];
return COMPARE;
}
[\n] { return *yytext;
}
[ \t] ;
.. {
yyerror("Unknown
Character!");
}
%%
int yywrap(void)
{
return 1;
}
sql.y:
%{
#include <stdio.h>
void yyerror(char *s);
int yylex(void);
%}
%union {
int intval;
char nameval[50];
char compval;
};
%token <intval> INTEGER
%token <nameval> NAME
%token <compval> COMPARE
%token CREATE TABLE
%%
createtablestatement:
| createtablestatement '\n'
| CREATE TABLE NAME '\n' {printf("%s\n", $3);}
;
%%
void yyerror(char *s)
{
fprintf(stderr," %s\n", s);
}
int main(void)
{
yyparse();
}
I compile and run it as follows:
lex sql.l
yacc -d sql.y
gcc -o create lex.yy.c y.tab.c -ll
$./create
CREATE TABLE aaaa
aaaa
CREATE TABLE bbbb
parse error
$
I want to know why it could run at the first time, but it could not
run at the second time.
Please help me. Thanks a lot!