關於上下文,請首先閱讀this question about Ternary Operators。使用調車場算法解析三元運算符
我正在構建自己的編程語言,允許您定義自定義運算符。因爲我希望它儘可能少的編譯器的內置插件越好,它應該允許自定義的三元運營商的定義,最好的形式
infix operator ? : { precedence 120 }
我(手寫)表達式解析器會變成嵌套三元運營商進入操作符分隔的操作數列表。
a ? b ? c : d : e
(a) ? (b) ? (c) : (d) : (d)
OperatorChain(operators: [?, ?, :, :], operands: [a, b, c, d, e])
的OperatorChain
類現在查找從操作者定義的運營商的範圍和使用調度場算法,這將在下面示出的修改後的版本將所述列表轉變成二進制AST節點:
// Note: OperatorElement is a class that merely stores an Identifier, an associated source code position and the resolved operator.
// IValue is the base interface for all Expression AST nodes
final Stack<OperatorElement> operatorStack = new LinkedList<>();
final Stack<IValue> operandStack = new LinkedList<>();
operandStack.push(this.operands[0]);
for (int i = 0; i < this.operatorCount; i++)
{
final OperatorElement element1 = this.operators[i];
OperatorElement element2;
while (!operatorStack.isEmpty())
{
element2 = operatorStack.peek();
final int comparePrecedence = element1.operator.comparePrecedence(element2.operator);
if (comparePrecedence < 0
|| element1.operator.getAssociativity() != IOperator.RIGHT && comparePrecedence == 0)
{
operatorStack.pop();
this.pushCall(operandStack, element2);
}
else
{
break;
}
}
operatorStack.push(element1);
operandStack.push(this.operands[i + 1]);
}
while (!operatorStack.isEmpty())
{
this.pushCall(operandStack, operatorStack.pop());
}
return operandStack.pop().resolve(markers, context);
我需要如何修改這個算法才能使用三元運算符(包括自定義運算符)?
非常感謝!我設法調整我的'OperatorChain'類以支持自定義三元運算符。唯一的區別是,它沒有前面的':'對待?「儘管這是有意的,但它是正確聯想的。 – Clashsoft