Migrate condition evaluator to Kotlin
This commit is contained in:
@@ -1,6 +1,10 @@
|
||||
package io.smnp.dsl.ast.model.node
|
||||
|
||||
class ConditionNode(trueBranchToken: Node, condition: Node, trueBranch: Node, falseBranchToken: Node, falseBranch: Node) : Node(3, trueBranchToken.position) {
|
||||
operator fun component1(): Node = children[0]
|
||||
operator fun component2(): Node = children[1]
|
||||
operator fun component3(): Node = children[2]
|
||||
|
||||
val condition: Node
|
||||
get() = children[0]
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package io.smnp.evaluation.evaluator
|
||||
|
||||
import io.smnp.data.enumeration.DataType
|
||||
import io.smnp.dsl.ast.model.node.ConditionNode
|
||||
import io.smnp.dsl.ast.model.node.Node
|
||||
import io.smnp.dsl.ast.model.node.NoneNode
|
||||
import io.smnp.error.EvaluationException
|
||||
import io.smnp.evaluation.environment.Environment
|
||||
import io.smnp.evaluation.model.entity.EvaluatorOutput
|
||||
|
||||
class ConditionEvaluator : Evaluator() {
|
||||
override fun supportedNodes() = listOf(ConditionNode::class)
|
||||
|
||||
override fun tryToEvaluate(node: Node, environment: Environment): EvaluatorOutput {
|
||||
val expressionEvaluator = ExpressionEvaluator()
|
||||
val defaultEvaluator = DefaultEvaluator()
|
||||
val (conditionNode, trueBranchNode, falseBranchNode) = (node as ConditionNode)
|
||||
val condition = expressionEvaluator.evaluate(conditionNode, environment).value!!
|
||||
|
||||
if(condition.type != DataType.BOOL) {
|
||||
throw EvaluationException("Condition should be of bool type, found '${condition.value}'", conditionNode.position)
|
||||
}
|
||||
|
||||
if(condition.value!! as Boolean) {
|
||||
return defaultEvaluator.evaluate(trueBranchNode, environment)
|
||||
} else if(falseBranchNode !is NoneNode) {
|
||||
return defaultEvaluator.evaluate(falseBranchNode, environment)
|
||||
}
|
||||
|
||||
return EvaluatorOutput.fail()
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ class DefaultEvaluator : Evaluator() {
|
||||
|
||||
override fun tryToEvaluate(node: Node, environment: Environment): EvaluatorOutput {
|
||||
return oneOf(
|
||||
ConditionEvaluator(),
|
||||
BlockEvaluator(),
|
||||
ThrowEvaluator(),
|
||||
ExpressionEvaluator()
|
||||
|
||||
Reference in New Issue
Block a user