简体   繁体   English

如何为 select sql 语句编写语法?

[英]How do I write a grammar for a select sql statement?

I am writing a grammar for an SQL parser and I've been stuck on this for a while now-我正在为 SQL 解析器编写语法,但我已经坚持了一段时间了-

F:      FETCH  fields  FROM  tables  Conditions
;

fields:     ALL
|           ids
;

ids:        ID ids_
;

ids_:       ',' ID ids_
|            { /*empty*/ }
;

tables:     ID
;

Conditions:     WHERE  ConditionList 
|               { /*empty*/ }
;

ConditionList:      Condition ConditionList_
;

ConditionList_:     BoolOp Condition ConditionList_
|                   { /*empty*/ }
;

Condition:      Operand RELOP Operand
|               NOT Operand RELOP Operand
;

Operand:    ID
|           NUM
;

BoolOp:     AND
|           OR
;

For some reason when the lexer reads a FROM token, the parser terminates with an error.由于某种原因,当词法分析器读取 FROM 令牌时,解析器会因错误而终止。 Here's the lex code-这是 lex 代码-

FETCH{ printf("fetch ");            return FETCH;}
FROM        { printf("from ");  return UNIQUE;                                      }

ALL     { printf("all ");   return ALL;     }
WHERE       { printf("where ");     return WHERE;   }
AND         { printf("and ");   return AND;     }
OR      { printf("or ");    return OR;  }
NOT             { printf("not ");   return NOT; }
RelOp           { printf("%s", yytext);     yylval.string = strdup(yytext); return RELOP;   }
[0-9]*          {printf("num ");    return NUM; }
[_a-zA-Z][_a-zA-Z0-9]*      { printf("id ");        return ID;      }
{symbol}    { printf("%c ", yytext[0]); return yytext[0];       }
.                           {   }

RelOp is a pattern- RelOp ("<"|"<="|">"|">="|"=") and symbol is a pattern- symbol ("("|")"|",") RelOp 是一个模式RelOp ("<"|"<="|">"|">="|"=")和 symbol 是一个模式- symbol ("("|")"|",")

Your grammar starts with你的语法从

F:      FETCH  fields  FROM  tables  Conditions

However, your lexer rules includes但是,您的词法分析器规则包括

FROM        { printf("from ");  return UNIQUE; }

Since UNIQUE is different from FROM , the grammar rule won't apply.由于UNIQUEFROM不同,语法规则将不适用。

If those printf calls in your lexer are some kind of debugging attempt, they are not very useful since they won't tell you whether you are actually returning the correct token type (and value, in the cases where that is necessary).如果您的词法分析器中的那些printf调用是某种调试尝试,那么它们并不是很有用,因为它们不会告诉您是否实际上返回了正确的令牌类型(和值,在必要的情况下)。 I strongly recommend using bison's trace feature to get an accurate view of what is going on.我强烈建议使用bison 的跟踪功能来准确了解正在发生的事情。 (Bison's trace will tell you which token type is being received by the parser, for example.) (例如,Bison 的跟踪将告诉您解析器正在接收哪种令牌类型。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM