Skip to content

Commit

Permalink
feat: add switchOp and caseOp #22
Browse files Browse the repository at this point in the history
  • Loading branch information
phodal committed Nov 9, 2022
1 parent df144dc commit 88f42e4
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
16 changes: 16 additions & 0 deletions chapi-domain/src/main/kotlin/chapi/domain/expr/Expression.kt
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,22 @@ sealed class Expression {
override fun toString() = "[${args.joinToString(", ")}]"
}

class SwitchCases(val lhs: ExpressionNode, val cases: Array<CaseOp>, val defaultBlock: ExpressionNode?) : ExpressionNode {
override fun toString(): String {
val casesStr = cases.joinToString("\n") { "case ${it.condition}: ${it.thenBlock}" }
val defaultStr = if (defaultBlock != null) {
"default: $defaultBlock"
} else {
""
}
return "switch ($lhs) {\n$casesStr\n$defaultStr\n}"
}
}

class CaseOp(val condition: ExpressionNode, val thenBlock: ExpressionNode) : ExpressionNode {
override fun toString() = "$condition -> $thenBlock"
}

class Value(val value: Any) : ExpressionNode {
override fun toString() = value.toString()
}
Expand Down
19 changes: 19 additions & 0 deletions chapi-domain/src/test/kotlin/chapi/domain/expr/ExpressionTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -135,4 +135,23 @@ class ExpressionTest {
).toString(), "a = 1"
)
}

@Test
fun switchCase() {
assertEquals(Expression.SwitchCases(
lhs = Expression.Variable("a"),
cases = arrayOf(
Expression.CaseOp(
condition = Expression.IntValue(1),
thenBlock = Expression.IntValue(2)
),
Expression.CaseOp(
condition = Expression.IntValue(2),
thenBlock = Expression.IntValue(3)
)
),
defaultBlock = Expression.IntValue(4)
).toString(), "switch (a) { case 1: 2; case 2: 3; default: 4; }"
)
}
}

0 comments on commit 88f42e4

Please sign in to comment.