Skip to content

Commit

Permalink
feat: try if else packages
Browse files Browse the repository at this point in the history
  • Loading branch information
phodal committed Nov 9, 2022
1 parent 8382a41 commit 33ee8b9
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 7 deletions.
27 changes: 20 additions & 7 deletions chapi-domain/src/main/kotlin/chapi/domain/expr/Expression.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,6 @@ package chapi.domain.expr

// todo: mapping to pratt parser ?
// mini sample <https://github.com/segeljakt/pratt>
//
// enum class TokenTree {
// Primary,
// Prefix,
// Infix,
// Postfix;
// }
sealed class Expression {
class BinOp(val lhs: ExpressionNode, val op: BinOpKind, val rhs: ExpressionNode) : ExpressionNode {
override fun toString() = "$lhs $op $rhs"
Expand All @@ -22,10 +15,26 @@ sealed class Expression {
override fun toString() = value.toString()
}

class FloatValue(val value: Float) : ExpressionNode {
override fun toString() = value.toString()
}

class StringValue(val value: String) : ExpressionNode {
override fun toString() = value
}

class Variable(val name: String) : ExpressionNode {
override fun toString() = name
}

class TryCatch(val tryBlock: ExpressionNode, val catchBlock: ExpressionNode) : ExpressionNode {
override fun toString() = "try { $tryBlock } catch { $catchBlock }"
}

class IfElse(val condition: ExpressionNode, val thenBlock: ExpressionNode, val elseBlock: ExpressionNode) : ExpressionNode {
override fun toString() = "if ($condition) { $thenBlock } else { $elseBlock }"
}

class Identifier(val name: String) : ExpressionNode {
override fun toString() = name
}
Expand All @@ -45,6 +54,10 @@ sealed class Expression {
override fun toString() = args.joinToString(", ")
}

class ArrayLiteral(val args: kotlin.Array<ExpressionNode>) : ExpressionNode {
override fun toString() = "[${args.joinToString(", ")}]"
}

class CustomValueType(val value: ValueType) : ExpressionNode

}
Expand Down
30 changes: 30 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 @@ -70,4 +70,34 @@ class ExpressionTest {
).toString(), "add(1, 2)"
)
}

@Test
fun arrayLiteral() {
assertEquals(Expression.ArrayLiteral(
args = arrayOf(
Expression.IntValue(1),
Expression.IntValue(2)
)
).toString(), "[1, 2]"
)
}

@Test
fun tryCatch() {
assertEquals(Expression.TryCatch(
tryBlock = Expression.IntValue(1),
catchBlock = Expression.IntValue(2)
).toString(), "try { 1 } catch { 2 }"
)
}

@Test
fun ifElse() {
assertEquals(Expression.IfElse(
condition = Expression.IntValue(1),
thenBlock = Expression.IntValue(2),
elseBlock = Expression.IntValue(3)
).toString(), "if (1) { 2 } else { 3 }"
)
}
}

0 comments on commit 33ee8b9

Please sign in to comment.