System Programming

Using Lex and YACC, a simple parser for SQL statement

Author: Manav Sanghavi

"yacc.y" file

%{
#include <stdio.h>

void yyerror (const char *str) {
	fprintf(stderr, "error: %s\n", str);
}

int yywrap() {
	return 1;
}

main() {
	yyparse();
}

%}

%%

%token SELECT FROM IDENTIFIER WHERE AND;

line: select items using condition '\n' { printf("Syntax Correct\n"); };

select: SELECT;

items: '*' | identifiers;

identifiers: IDENTIFIER | IDENTIFIER ',' identifiers;

using: FROM IDENTIFIER WHERE;

condition: IDENTIFIER '=' IDENTIFIER | IDENTIFIER '=' IDENTIFIER AND condition;

%%

"lex.l" file

%{
#include <stdio.h>
#include "y.tab.h"
extern int yylval;
%}

%%
select					return SELECT;
from					return FROM;
where					return WHERE;
and						return AND;
[*]						return *yytext;
[,]						return *yytext;
[=]						return *yytext;
[a-zA-Z][a-zA-Z0-9]+	return IDENTIFIER;
\n						return *yytext;
[ \t]+					/* ignore whitespace */;
%%

Sample Output

mnvsngv@M17xR4:~/lexyacc$ lex lex.l

mnvsngv@M17xR4:~/lexyacc$ yacc -d yacc.y

mnvsngv@M17xR4:~/lexyacc$ gcc lex.yy.c y.tab.c -o lexyacc

mnvsngv@M17xR4:~/lexyacc$ ./lexyacc
select * from table1 where name=manav
Syntax Correct
select name from table2 where name=manav and surname=sanghavi
Syntax Correct
select * where name=manav
error: syntax error
Program List