Migrate power operator evaluator to Kotlin

This commit is contained in:
2020-03-07 17:31:57 +01:00
parent 5f92cab2bf
commit 1406a3fa6f
4 changed files with 36 additions and 1 deletions

View File

@@ -22,6 +22,10 @@ enum class DataType(val kotlinType: KClass<out Any>?) {
return kotlinType.isInstance(value)
}
fun isNumeric(): Boolean {
return this == INT || this == FLOAT
}
override fun toString(): String {
return super.toString().toLowerCase()
}

View File

@@ -1,6 +1,10 @@
package io.smnp.dsl.ast.model.node
abstract class BinaryOperatorAbstractNode(lhs: Node, operator: Node, rhs: Node) : Node(3, operator.position) {
operator fun component1() = children[0]
operator fun component2() = children[1]
operator fun component3() = children[2]
val lhs: Node
get() = children[0]

View File

@@ -18,7 +18,8 @@ class DefaultEvaluator : Evaluator() {
MapEvaluator(),
MinusOperatorEvaluator(),
NotOperatorEvaluator()
NotOperatorEvaluator(),
PowerOperatorEvaluator()
).evaluate(node, environment)
}
}

View File

@@ -0,0 +1,26 @@
package io.smnp.evaluation.evaluator
import io.smnp.data.model.Value
import io.smnp.dsl.ast.model.node.Node
import io.smnp.dsl.ast.model.node.PowerOperatorNode
import io.smnp.error.EvaluationException
import io.smnp.evaluation.environment.Environment
import io.smnp.evaluation.model.entity.EvaluatorOutput
import kotlin.math.pow
class PowerOperatorEvaluator : Evaluator() {
override fun supportedNodes() = listOf(PowerOperatorNode::class)
override fun tryToEvaluate(node: Node, environment: Environment): EvaluatorOutput {
val (lhsNode, _, rhsNode) = (node as PowerOperatorNode)
val evaluator = DefaultEvaluator()
val lhs = evaluator.evaluate(lhsNode, environment).value!!
val rhs = evaluator.evaluate(rhsNode, environment).value!!
if(!lhs.type.isNumeric() || !rhs.type.isNumeric()) {
throw EvaluationException("Operator ** supports only numeric types", node.position)
}
return EvaluatorOutput.value(Value.float((lhs.value as Number).toFloat().pow((rhs.value as Number).toFloat())))
}
}