4

我对 jison 非常陌生,并设法拼凑出一个有用的查询解析器。我现在正在尝试创建一个解析器,它可以将像“a == 1 and b == 1 and c == 1”这样的字符串解析为像这样的对象

{and: [
  {a: {eq: 1}},
  {b: {eq: 1}},
  {c: {eq: 2}}
]}

而像“a == 1 or b == 1 and c == 1”这样的字符串应该解析成一个像这样的对象

{or: [
  {a: {eq: 1}},
  {and: [
    {b: {eq: 1}},
    {c: {eq: 1}}
  ]}
]}

到目前为止,我的语法看起来像这样:

%lex

%%
\s+       /*skip whitespace*/
\"(\\.|[^"])*\"          yytext = yytext.substr(1, yyleng-2); return 'STRING';
"=="                     return '==';
and[^\w]                 return 'and';
or[^\w]                  return 'or';
[0-9]+(?:\.[0-9]+)?\b    return 'NUMBER';
[a-zA-Z][\.a-zA-Z0-9_]*  return 'SYMBOL';
<<EOF>>                  return 'EOF';

/lex

%left 'or'
%left 'and'
%left '=='

%start expressions

%%

expressions
  : e EOF
    {$$ = $1;}
  ;

e
  : property '==' value
    { $$ = {}; $[$1] = {eq: $3}; }
  | boolAnd 
    { $$ = {and: $1}}
  | boolOr 
    { $$ = {or: $1}}
  ;

boolAnd
  : boolAnd 'and' e
    {$$ = $1; $1.push($3);}
  | e 'and' e
    {$$ = [$1, $3];}
  ;

boolOr
  : boolOr 'or' e
    {$$ = $1; $1.push($3);}
  | e 'or' e
    {$$ = [$1, $3];}
  ;

property
  : SYMBOL
    {$$ = $1;}
  ;

value
  : NUMBER
    {$$ = Number(yytext);}
  | STRING
    {$$ = yytext; }
  ;

它给了我以下冲突错误:

Conflict in grammar: multiple actions possible when lookahead token is and in state 4
- reduce by rule: e -> boolAnd
- shift token (then go to state 11)
Conflict in grammar: multiple actions possible when lookahead token is or in state 5
- reduce by rule: e -> boolOr
- shift token (then go to state 12)

States with conflicts:
State 4
  e -> boolAnd . #lookaheads= EOF and or
  boolAnd -> boolAnd .and e #lookaheads= EOF and or
State 5
  e -> boolOr . #lookaheads= EOF and or
  boolOr -> boolOr .or e #lookaheads= EOF or and

有人可以就我做错了什么提出建议吗?非常感谢

4

1 回答 1

1

自从

e : boolAnd

不可能在以下之间做出决定:

boolAnd: e 'and' e
       | boolAnd 'and' e

这就是jison所抱怨的。(值得注意的是,减少boolAndtoe似乎并不是你想要的。这确实是一个类型错误,或者如果 JS 有类型。)

就个人而言,我只会使用二叉树;根据我的经验,事实证明它们更容易使用。您可以使用单个非终端和优先声明轻松地做到这一点。

%left 'or'
%left 'and'
%%
e
  : property '==' value
    { $$ = {eq: [$1, $3]}; /* This seems better to me. YMMV. }
  | e 'and' e
    { $$ = {and: [$1, $3]}}
  | e 'or' e
    { $$ = {or: [$1, $3]}}
  | '(' e ')'
    { $$ = $2  /* You didn't have this one, but it seems useful */ }
  ;

可以创建一个处理可变参数运算符(即 reduce x OP y OP zto {OP: [x, y, z]})的语法,但实际上要做到这一点需要相当多的工作,而且它不容易产生基于优先级声明的解决方案。除非您真的想区分x OP y OP zand x OP (y OP z),这在布尔运算符的情况下是不必要的,否则在解析树的第二遍或直接在创建二元节点时折叠多个相似的二元运算符通常更容易和更通用,通过检查子表达式的运算符类型。

于 2016-05-07T02:31:40.217 回答