我认为这个运算符实际上是右结合的,而不是左结合的。如果我将您的代码更改为:
import pyparsing as pp
TERNARY_INFIX = pp.infixNotation(
pp.pyparsing_common.integer, [
(("?", ":"), 3, pp.opAssoc.RIGHT),
])
TERNARY_INFIX.runTests("""\
1?1:(0?1:0)
(1?1:0)?1:0
1?1:0?1:0
""", fullDump=False)
然后我得到合理的输出,没有括号的输入没有错误:
1?1:(0?1:0)
[[1, '?', 1, ':', [0, '?', 1, ':', 0]]]
(1?1:0)?1:0
[[[1, '?', 1, ':', 0], '?', 1, ':', 0]]
1?1:0?1:0
[[1, '?', 1, ':', [0, '?', 1, ':', 0]]]
这是一个更大的表达式,用于评估 3 个变量中的最大值(来自本 C 教程:http://cprogramming.language-tutorial.com/2012/01/biggest-of-3-numbers-using-ternary.html):
TERNARY = pp.infixNotation(
pp.Char("abc"), [
(pp.oneOf("> <"), 2, pp.opAssoc.LEFT),
(("?", ":"), 3, pp.opAssoc.RIGHT),
])
TERNARY.runTests("""\
(a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c)
a > b ? a > c ? a : c : b > c ? b : c
""", fullDump=False)
给予:
(a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c)
[[['a', '>', 'b'], '?', [['a', '>', 'c'], '?', 'a', ':', 'c'], ':', [['b', '>', 'c'], '?', 'b', ':', 'c']]]
a > b ? a > c ? a : c : b > c ? b : c
[[['a', '>', 'b'], '?', [['a', '>', 'c'], '?', 'a', ':', 'c'], ':', [['b', '>', 'c'], '?', 'b', ':', 'c']]]
编辑:我现在看到这种情况类似于重复的二元运算符,例如“1 + 2 + 3”。左关联,pyparsing 不会将它们解析为[['1' '+' '2'] '+' '3'],而只是['1' '+' '2' '+' '3'],并且由评估器进行重复的从左到右的评估。
当我添加三元运算符时,我没有想到像您正在解析的那样的链式形式。对infixNotation 的单行更改将使用左关联性成功解析您的表达式,但就像链接的二元运算符一样,会给出未分组的结果:
[1, '?', 1, ':', 0, '?', 1, ':', 0]
就像重复加法的例子一样,由评估者进行从左到右的连续评估,例如:
def eval_ternary(tokens):
operands = tokens[0]
ret = bool(operands[0])
i = 1
while i < len(operands):
ret = bool(operands[i+1]) if ret else bool(operands[i+3])
i += 4
return ret
如果您想手动修补您的 pyparsing 代码,请更改:
elif arity == 3:
matchExpr = _FB(
lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr
) + Group(lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr)
到:
elif arity == 3:
matchExpr = _FB(
lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr
) + Group(lastExpr + OneOrMore(opExpr1 + lastExpr + opExpr2 + lastExpr))
^^^^^^^^^^
在 pyparsing.py 中进行此更改,或将infxNotation 的定义复制到您自己的代码中并在那里进行更改。
我将在 pyparsing 的下一个版本中进行此更改。
EDIT - 在 pyparsing 2.4.6 中修复,刚刚发布。