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

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

问题描述

我正在尝试在数学表达式中匹配变量Arity的运算符(例如,"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
      ;

我们如何保留优先级,但仍然尽可能将小ThanExpression解析为贪婪的呢?

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

例如;应该将"1< 1 + 1< 3"解析为具有三个子节点的单个分析节点"smallerThanExpression",每个子节点都是一个表达式.此时,将smallThanExpression分解为两个较小的hanhanThanExpressions(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天全站免登陆