Skip to content

Commit 88f42e4

Browse files
committed
feat: add switchOp and caseOp #22
1 parent df144dc commit 88f42e4

2 files changed

Lines changed: 35 additions & 0 deletions

File tree

chapi-domain/src/main/kotlin/chapi/domain/expr/Expression.kt

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,22 @@ sealed class Expression {
6868
override fun toString() = "[${args.joinToString(", ")}]"
6969
}
7070

71+
class SwitchCases(val lhs: ExpressionNode, val cases: Array<CaseOp>, val defaultBlock: ExpressionNode?) : ExpressionNode {
72+
override fun toString(): String {
73+
val casesStr = cases.joinToString("\n") { "case ${it.condition}: ${it.thenBlock}" }
74+
val defaultStr = if (defaultBlock != null) {
75+
"default: $defaultBlock"
76+
} else {
77+
""
78+
}
79+
return "switch ($lhs) {\n$casesStr\n$defaultStr\n}"
80+
}
81+
}
82+
83+
class CaseOp(val condition: ExpressionNode, val thenBlock: ExpressionNode) : ExpressionNode {
84+
override fun toString() = "$condition -> $thenBlock"
85+
}
86+
7187
class Value(val value: Any) : ExpressionNode {
7288
override fun toString() = value.toString()
7389
}

chapi-domain/src/test/kotlin/chapi/domain/expr/ExpressionTest.kt

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,4 +135,23 @@ class ExpressionTest {
135135
).toString(), "a = 1"
136136
)
137137
}
138+
139+
@Test
140+
fun switchCase() {
141+
assertEquals(Expression.SwitchCases(
142+
lhs = Expression.Variable("a"),
143+
cases = arrayOf(
144+
Expression.CaseOp(
145+
condition = Expression.IntValue(1),
146+
thenBlock = Expression.IntValue(2)
147+
),
148+
Expression.CaseOp(
149+
condition = Expression.IntValue(2),
150+
thenBlock = Expression.IntValue(3)
151+
)
152+
),
153+
defaultBlock = Expression.IntValue(4)
154+
).toString(), "switch (a) { case 1: 2; case 2: 3; default: 4; }"
155+
)
156+
}
138157
}

0 commit comments

Comments
 (0)