N元运算符解析 [英] N-ary operator parsing

查看:33
本文介绍了N元运算符解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在数学表达式中匹配变量 arity 的运算符(例如,1 <3

I'm trying to match an operator of variable arity (e.g. "1 < 3 < x < 10" yields true, given that 3 < x < 10) within a mathematical expression. Note that this is unlike most languages would parse the expression) The (simplified) production rule is:

expression: '(' expression ')'                  # parenthesisExpression
      | expression ('*' | '/' | '%') expression # multiplicationExpression
      | expression ('+' | '-') expression       # additionExpression
      | expression (SMALLER_THAN expression)+   # smallerThanExpression
      | IDENTIFIER                              # variableExpression
      ;

我们如何保持优先级,但仍然尽可能贪婪地解析smallerThanExpression?

How do we keep the precedence, but still parse the smallerThanExpression as greedy as possible?

例如;1 < 1+1 < 3"应该被解析为具有三个子节点的单个解析节点smallerThanExpression",每个子节点都是一个表达式.此时,smallerThanExpression 被分解为两个smallerThanExpression (1 <(1+1 <3)).

For example; "1 < 1+1 < 3" should be parsed as a single parse node "smallerThanExpression" with three child nodes, each of which is an expression. At this moment, the smallerThanExpression is broken up in two smallerThanExpressions (1 < (1+1 < 3)).

推荐答案

为了给后代"一个答案:我们通过将算术表达式与其他表达式分开来修复它.我们知道只有算术表达式可以用作我们的可变参数运算符的操作数('true < false' 不是一个有效的表达式).

To give an answer for "future generations": we fixed it by separating arithmetic expressions from the other expressions. We know that only arithmetic expressions can be used as operands for our variable-arity operators ('true < false' is not a valid expression).

expression: 
        '!' expression
      | arithmetic (SMALLER_THAN arithmetic)+
      | arithmetic (GREATER_THAN arithmetic)+
      | ....
      ;

arithmetic:
        '(' expression ')'                 
      | expression ('*' | '/' | '%') expression 
      | expression ('+' | '-') expression 
      | IDENTIFIER
      | ...
      ;

这会强制将诸如x < y < z"之类的表达式解析为单个表达式"节点,其中三个算术"节点作为子节点.

This enforces an expression such as "x < y < z" to be parsed as a single 'expression' node with three 'arithmetic' nodes as children.

(请注意,标识符可能指的是非整数对象;这是在上下文检查器中检查的)

(Note that an identifier might refer to a non-integer object; this is checked in the context checker)

这篇关于N元运算符解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆