实现一个sql语法解析器

项目流程规划

  1. sql语法设计
  2. 词法语法分析
  3. 语法制导翻译
  4. 文件操作
  5. 测试与优化

1. LEX介绍

另见: lex语法分析器的使用

2. sql语法设计并使用lex进行词法分析

从sql语言语法中提取出关键字,定义为token,使得lex能够识别他们,并进行下一步的语法分析.

%{
    #include <stdio.h>
    #include <vector>
    #include "dbCore.h"
    #include "sql.tab.h"
    #include <cstring>
    int cur_line = 1;
%}

CREATE create 
SHOW show
DROP drop
USE use
DATABASE database
DATABASES databases
TABLE table
TABLES tables
CHAR char
INT int
DOUBLE double  
FROM from
SELECT select
WHERE where
AND and
OR or
INSERT insert
INTO into
VALUES VALUES
DELETE delete
UPDATE update
SET set
ID [a-zA-Z][a-zA-Z_0-9]*
NUMBER [-+]?[0-9][0-9]*
STRING '.*'

%%
{CHAR} {yylval.typeval = CHAR; return CHAR; }
{INT} {yylval.typeval = INT; return INT;}
{DOUBLE} {yylval.typeval = DOUBLE; return DOUBLE;} //add double here
{CREATE} { return CREATE;}
{SHOW} {return SHOW; }
{DROP} {return DROP; }
{USE} {return USE;}
{TABLE} {return TABLE;}
{TABLES} { return TABLES;}
{DATABASE} { return DATABASE;}
{DATABASES} { return DATABASES;}
{SELECT} {return SELECT;}
{FROM} {return FROM;}
{WHERE} {return WHERE;}
{AND} {return AND;}
{OR} {return OR;}
{INSERT} {return INSERT;}
{INTO} {return INTO;}
{VALUES} {return VALUES;}
{DELETE} {return DELETE;}
{UPDATE} {return UPDATE;}
{SET} {return SET;}
{ID} { yylval.chval = strdup(yytext); return ID;}
{NUMBER} {yylval.intval = atoi(yytext); return NUMBER;}
"("  { return '('; }
")"  { return ')'; }
";"  { return ';'; }
","  { return ','; }
"*"  { return '*'; }
"."  { return '.'; }
"<"  { return '<'; }
">"  { return '>'; }
"="  { return '='; }
"!"  { return '!'; }
\n   { cur_line++; }
{STRING} 
 {
   *(yytext+strlen(yytext)-1) = '\0'; 
   yylval.chval = strdup(yytext+1);  
   return STRING;
 }

[ \t]+      /* ignore whitespace */;
"//".*     { /* DO NOTHING */ }
%%

int yywrap()//此函数必须由用户提供
{
    return 1;
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×