ANTLR 3.x - 如何格式化重写规则

发布于 2024-08-23 03:29:14 字数 690 浏览 3 评论 0原文

我发现自己面临着当原始规则中出现某些条件时如何正确格式化重写规则的挑战。

重写此内容的适当方法是什么:

unaryExpression: op=('!' | '-') t=term
  -> ^(UNARY_EXPR $op $t)

Antlr 似乎不喜欢我在括号中用标签标记任何内容,并且“op =”失败。另外,我尝试过:

unaryExpression: ('!' | '-') t=term
  -> ^(UNARY_EXPR ('!' | '-') $t)

Antlr 不喜欢或“|”并抛出语法错误。

用标记名称替换字符类确实解决了这个问题,但是它给我的语法带来了其他问题的泥潭。

--- 编辑 ----

添加了第二个问题。请帮我用树语法格式化此规则:

multExpression : 一元表达式 (MULT_OP 一元表达式)* ;

非常简单:我的期望是将每个匹配的标记包含在父(虚构)标记 MULT 中,这样我最终会得到类似的结果:

 MULT
  o
  |
  o---o---o---o---o
  |   |   |   |   |
 '3' '*' '6' '%'  2

I'm finding myself challenged on how to properly format rewrite rules when certain conditions occur in the original rule.

What is the appropriate way to rewrite this:

unaryExpression: op=('!' | '-') t=term
  -> ^(UNARY_EXPR $op $t)

Antlr doesn't seem to like me branding anything in parenthesis with a label and "op=" fails. Also, I've tried:

unaryExpression: ('!' | '-') t=term
  -> ^(UNARY_EXPR ('!' | '-') $t)

Antlr doesn't like the or '|' and throws a grammar error.

Replacing the character class with a token name does solve this problem, however it creates a quagmire of other issues with my grammar.

--- edit ----

A second problem has been added. Please help me format this rule with tree grammar:

multExpression
: unaryExpression (MULT_OP unaryExpression)*
;

Pretty simple: My expectation is to enclose every matched token in a parent (imaginary) token MULT so that I end up with something like:

 MULT
  o
  |
  o---o---o---o---o
  |   |   |   |   |
 '3' '*' '6' '%'  2

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

海风掠过北极光 2024-08-30 03:29:14
unaryExpression
    :    (op='!' | op='-') term
         -> ^(UNARY_EXPR[$op] $op term)
    ;

我使用了 UNARY_EXPR[$op],因此根节点获得一些有用的行/列信息,而不是默认为 -1。

unaryExpression
    :    (op='!' | op='-') term
         -> ^(UNARY_EXPR[$op] $op term)
    ;

I used the UNARY_EXPR[$op] so the root node gets some useful line/column information instead of defaulting to -1.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文