简体   繁体   English

Antlr树重写规则

[英]Antlr tree rewrite rules

I'm trying to parse an expression like a IN [3 .. 5[ , where the direction of the angle brackets determine whether the interval is inclusive or exclusive. 我试图解析一个像a IN [3 .. 5[的表达式,其中尖括号的方向确定间隔是包含的还是排除的。 I want this to be rewritten to an AST like 我希望将其重写为AST之类的

             NODE-TYPE
                 |
    +------------+-----------+
    |            |           |
 variable  lower-bound  upper-bound

where NODE-TYPE is one of BTW_INCLUSIVE, BTW_EXCL_LOWER, BTW_EXCL_UPPER or BTW_EXCL_BOTH, depending on the direction of the angle brackets. 其中,NODE-TYPE是BTW_INCLUSIVE,BTW_EXCL_LOWER,BTW_EXCL_UPPER或BTW_EXCL_BOTH之一,具体取决于尖括号的方向。

I have the following parse rule: 我有以下解析规则:

interval_expr : expr1=variable IN
                (LBRACKET|RBRACKET)
                expr2=expression DOTDOT expr3=expression
                (LBRACKET|RBRACKET)
                -> ^(BETWEEN $expr1 $expr2 $expr3)

This works, except that it does not create the correct tree node type. 除不能创建正确的树节点类型外,此方法均有效。 How can I choose which node type to create based on what was matched? 如何根据匹配的内容选择要创建的节点类型?

I think you have to solve this by writing one rule for each of the bracket combinations, adding the node type manually. 我认为您必须通过为每个括号组合编写一个规则来解决此问题,并手动添加节点类型。 As far as I know, it's not possible to rewrite two (non-adjacent) matching tokens into one other. 据我所知,不可能将两个(不相邻的)匹配令牌相互重写。

So you'd get this: 所以你会得到这个:

interval_expr:
  inclusive_expr |
  excl_lower_expr |
  excl_upper_expr |
  excl_both_expr;

inclusive_expr:
  expr1=variable IN LBRACKET expr2=expression DOTDOT expr3=expression RBRACKET
    -> ^(BTW_INCLUSIVE $expr1 $expr2 $expr3);

excl_lower_expr:
  expr1=variable IN RBRACKET expr2=expression DOTDOT expr3=expression RBRACKET
    -> ^(BTW_EXCL_LOWER $expr1 $expr2 $expr3);

excl_upper_expr:
  expr1=variable IN LBRACKET expr2=expression DOTDOT expr3=expression LBRACKET
    -> ^(BTW_EXCL_UPPER $expr1 $expr2 $expr3);

excl_both_expr:
  expr1=variable IN RBRACKET expr2=expression DOTDOT expr3=expression LBRACKET
    -> ^(BTW_EXCL_BOTH $expr1 $expr2 $expr3);

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

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