Migrate power operator evaluator to Kotlin
This commit is contained in:
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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]
|
||||
|
||||
|
||||
@@ -18,7 +18,8 @@ class DefaultEvaluator : Evaluator() {
|
||||
MapEvaluator(),
|
||||
|
||||
MinusOperatorEvaluator(),
|
||||
NotOperatorEvaluator()
|
||||
NotOperatorEvaluator(),
|
||||
PowerOperatorEvaluator()
|
||||
).evaluate(node, environment)
|
||||
}
|
||||
}
|
||||
@@ -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())))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user