|
| 1 | +package chapi.domain.expr |
| 2 | + |
| 3 | +import java.util.function.BinaryOperator |
| 4 | +import java.util.function.IntBinaryOperator |
| 5 | + |
| 6 | +// todo: mapping to pratt parser ? |
| 7 | +// mini sample <https://github.com/segeljakt/pratt> |
| 8 | +// |
| 9 | +// enum class TokenTree { |
| 10 | +// Primary, |
| 11 | +// Prefix, |
| 12 | +// Infix, |
| 13 | +// Postfix; |
| 14 | +// } |
| 15 | +sealed class Expression { |
| 16 | + class BinOp(lhs: Expression, op: BinOpKind, rhs: Expression) : ExpressionNode |
| 17 | + class UnOp(lhs: Expression, op: UnOpKind) : ExpressionNode |
| 18 | + class Int(val value: Int?) : ExpressionNode |
| 19 | +} |
| 20 | + |
| 21 | +sealed class BinOpKind { |
| 22 | + object Add : BinOpKind() // + |
| 23 | + object Sub : BinOpKind() // - |
| 24 | + object Mul : BinOpKind() // * |
| 25 | + object Div : BinOpKind() // / |
| 26 | + object Pow : BinOpKind() // ^ |
| 27 | + object Eq : BinOpKind() // = |
| 28 | +} |
| 29 | + |
| 30 | +sealed class UnOpKind { |
| 31 | + object Not : UnOpKind() // ! |
| 32 | + object Neg : UnOpKind() // - |
| 33 | + object Try : UnOpKind() // ? |
| 34 | +} |
| 35 | + |
| 36 | +interface ExpressionType { |
| 37 | + val name: String |
| 38 | +} |
| 39 | + |
| 40 | +interface ExpressionNode { |
| 41 | + val childrens: Array<ExpressionNode> get() = emptyArray() |
| 42 | + val expressionTypes: Array<ExpressionType> get() = emptyArray() |
| 43 | + |
| 44 | + fun getPriority(): Int = 0 |
| 45 | + |
| 46 | + fun addChildren(child: Operator) { |
| 47 | + childrens.plus(child) |
| 48 | + } |
| 49 | + |
| 50 | + fun addExpressionType(type: ExpressionType) { |
| 51 | + expressionTypes.plus(type) |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | + |
| 56 | +interface Operator : ExpressionNode |
| 57 | + |
| 58 | +enum class Arithmetics : BinaryOperator<Int>, IntBinaryOperator { |
| 59 | + PLUS { |
| 60 | + override fun apply(t: Int, u: Int): Int { |
| 61 | + return t + u |
| 62 | + } |
| 63 | + } |
| 64 | + ; |
| 65 | + |
| 66 | + override fun applyAsInt(t: Int, u: Int) = apply(t, u) |
| 67 | +} |
0 commit comments