Fix evaluating function's optional arguments
This commit is contained in:
@@ -10,17 +10,35 @@ import io.smnp.evaluation.evaluator.ExpressionEvaluator
|
|||||||
import io.smnp.type.model.Value
|
import io.smnp.type.model.Value
|
||||||
|
|
||||||
object FunctionEnvironmentProvider {
|
object FunctionEnvironmentProvider {
|
||||||
fun provideEnvironment(signature: FunctionDefinitionArgumentsNode, actualArgs: List<Value>, environment: Environment): Map<String, Value> {
|
private val evaluator = ExpressionEvaluator()
|
||||||
val evaluator = ExpressionEvaluator()
|
|
||||||
|
fun provideEnvironment(
|
||||||
|
signature: FunctionDefinitionArgumentsNode,
|
||||||
|
actualArgs: List<Value>,
|
||||||
|
environment: Environment
|
||||||
|
): Map<String, Value> {
|
||||||
return signature.items.mapIndexed { index, node ->
|
return signature.items.mapIndexed { index, node ->
|
||||||
when (node) {
|
when (node) {
|
||||||
is RegularFunctionDefinitionArgumentNode -> (node.identifier as IdentifierNode).token.rawValue to actualArgs[index]
|
is RegularFunctionDefinitionArgumentNode -> regularArgument(node, actualArgs, index)
|
||||||
is OptionalFunctionDefinitionArgumentNode -> (node.identifier as IdentifierNode).token.rawValue to evaluator.evaluate(
|
is OptionalFunctionDefinitionArgumentNode -> optionalArgument(node, environment, actualArgs, index)
|
||||||
node.defaultValue,
|
|
||||||
environment
|
|
||||||
).value!!
|
|
||||||
else -> throw ShouldNeverReachThisLineException()
|
else -> throw ShouldNeverReachThisLineException()
|
||||||
}
|
}
|
||||||
}.toMap()
|
}.toMap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun regularArgument(
|
||||||
|
node: RegularFunctionDefinitionArgumentNode,
|
||||||
|
actualArgs: List<Value>,
|
||||||
|
index: Int
|
||||||
|
) = (node.identifier as IdentifierNode).token.rawValue to actualArgs[index]
|
||||||
|
|
||||||
|
private fun optionalArgument(
|
||||||
|
node: OptionalFunctionDefinitionArgumentNode,
|
||||||
|
environment: Environment,
|
||||||
|
actualArgs: List<Value>,
|
||||||
|
index: Int
|
||||||
|
) = (node.identifier as IdentifierNode).token.rawValue to
|
||||||
|
if (index < actualArgs.size) actualArgs[index]
|
||||||
|
else evaluator.evaluate(node.defaultValue, environment).value!!
|
||||||
|
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user