diff --git a/src/main/kotlin/ru/darktale/calc/CalcApplication.kt b/src/main/kotlin/ru/darktale/calc/CalcApplication.kt index 98fbf77..4d928b8 100644 --- a/src/main/kotlin/ru/darktale/calc/CalcApplication.kt +++ b/src/main/kotlin/ru/darktale/calc/CalcApplication.kt @@ -8,7 +8,6 @@ import javafx.stage.Stage import ru.darktale.calc.infra.BasicModule import ru.darktale.calc.infra.CalculationsModule import ru.darktale.calc.service.KeyEventHandler -import kotlin.system.measureNanoTime import kotlin.system.measureTimeMillis @@ -40,7 +39,7 @@ fun main() { val parser = injector.getInstance(Parser::class.java) val calculator = injector.getInstance(Calculator::class.java) - val expression = "9^2" + val expression = "(3+1)!" val time = measureTimeMillis { println("$expression = ${calculator.calculate(parser.parse(expression))}") } diff --git a/src/main/kotlin/ru/darktale/calc/Calculator.kt b/src/main/kotlin/ru/darktale/calc/Calculator.kt index ee74a71..e267c58 100644 --- a/src/main/kotlin/ru/darktale/calc/Calculator.kt +++ b/src/main/kotlin/ru/darktale/calc/Calculator.kt @@ -19,7 +19,7 @@ class CalculatorImpl @Inject constructor( converter.convert(expression).process(operands) return if (operands.size == 1) operands.removeFirst().toBigDecimal() - else throw CalculationException() + else throw CalculationException("unexpected stack size: ${operands.size}") } private fun List.process(operands: ArrayDeque) = forEach { @@ -34,4 +34,4 @@ class CalculatorImpl @Inject constructor( } } -class CalculationException : Exception() \ No newline at end of file +class CalculationException(message: String) : Exception(message) \ No newline at end of file diff --git a/src/main/kotlin/ru/darktale/calc/Converter.kt b/src/main/kotlin/ru/darktale/calc/Converter.kt index a5ac41e..083ecd9 100644 --- a/src/main/kotlin/ru/darktale/calc/Converter.kt +++ b/src/main/kotlin/ru/darktale/calc/Converter.kt @@ -19,7 +19,7 @@ class ExpressionToRplConverterImpl : ExpressionToRplConverter { if (operationStack.firstOrNull() is UnaryOperation) this += operationStack.removeFirst() as UnaryOperation } - is Expression -> queue += element.elements.toTypedArray() + is Expression -> queue.addAll(0, element.elements) OpenBracket -> operationStack.addFirst(element) is UnaryOperation -> { if (element.isPrefix) operationStack.addFirst(element) diff --git a/src/main/kotlin/ru/darktale/calc/Model.kt b/src/main/kotlin/ru/darktale/calc/Model.kt index c85fbb8..ceb67a1 100644 --- a/src/main/kotlin/ru/darktale/calc/Model.kt +++ b/src/main/kotlin/ru/darktale/calc/Model.kt @@ -69,6 +69,7 @@ object UnaryMinus : UnaryOperation("-", true) object UnaryPlus : UnaryOperation("+", true) object Sinus : UnaryOperation("sin", true) object Sqrt : UnaryOperation("sqrt", true) +object Factorial : UnaryOperation("!", false) sealed class BinaryOperation( override val value: String, @@ -93,40 +94,6 @@ enum class ElementType { EXPRESSION, } -interface OperationMapper { - val typeMap: Map - operator fun get(key: String): OperationElement? -} - -enum class UnaryOperations( - var operationElement: UnaryOperation? -) { - UNARY_MINUS(UnaryMinus), - UNARY_PLUS(UnaryPlus), - SQRT(Sqrt), - SINUS(Sinus); - - companion object : OperationMapper { - override val typeMap = entries.associateBy { it.operationElement.toString() } - override fun get(key: String) = typeMap[key]?.operationElement - } -} - -enum class BinaryOperations( - val operationElement: BinaryOperation, -) { - BINARY_MINUS(BinaryMinus), - BINARY_PLUS(BinaryPlus), - MULTIPLICATION(Multiplication), - POWER(Power), - DIVISION(Division); - - companion object : OperationMapper { - override val typeMap = entries.associateBy { it.operationElement.toString() } - override fun get(key: String) = typeMap[key]?.operationElement - } -} - enum class Brackets( val bracket: Bracket, ) { diff --git a/src/main/kotlin/ru/darktale/calc/Operations.kt b/src/main/kotlin/ru/darktale/calc/Operations.kt index 663a1a4..4af3d07 100644 --- a/src/main/kotlin/ru/darktale/calc/Operations.kt +++ b/src/main/kotlin/ru/darktale/calc/Operations.kt @@ -1,6 +1,6 @@ package ru.darktale.calc -import java.math.BigDecimal +import com.google.common.math.BigIntegerMath.factorial import java.math.MathContext.DECIMAL128 import java.util.function.BiFunction import java.util.function.Function @@ -10,7 +10,7 @@ interface UnaryOperationFunction : Function interface BinaryOperationFunction : BiFunction object UnaryMinusFunction : UnaryOperationFunction { - override fun apply(operand: Operand) = operand.toBigDecimal().unaryMinus().toNumber() + override fun apply(operand: Operand) = operand.toBigDecimal().unaryMinus().toOperand() } object UnaryPlusFunction : UnaryOperationFunction { @@ -18,36 +18,40 @@ object UnaryPlusFunction : UnaryOperationFunction { } object SinusFunction : UnaryOperationFunction { - override fun apply(operand: Operand) = sin(operand.toBigDecimal().toDouble()).toNumber() + override fun apply(operand: Operand) = sin(operand.toBigDecimal().toDouble()).toOperand() +} + +object FactorialFunction : UnaryOperationFunction { + override fun apply(operand: Operand) = + factorial(operand.toBigDecimal().toInt()).toOperand() } object SqrtFunction : UnaryOperationFunction { - override fun apply(operand: Operand) = operand.toBigDecimal().sqrt(DECIMAL128).toNumber() + override fun apply(operand: Operand) = operand.toBigDecimal().sqrt(DECIMAL128).toOperand() } object BinaryMinusFunction : BinaryOperationFunction { override fun apply(first: Operand, second: Operand) = - (first.toBigDecimal() - second.toBigDecimal()).toNumber() + (first.toBigDecimal() - second.toBigDecimal()).toOperand() } object BinaryPlusFunction : BinaryOperationFunction { override fun apply(first: Operand, second: Operand) = - (first.toBigDecimal() + second.toBigDecimal()).toNumber() + (first.toBigDecimal() + second.toBigDecimal()).toOperand() } object MultiplicationFunction : BinaryOperationFunction { override fun apply(first: Operand, second: Operand) = - (first.toBigDecimal() * second.toBigDecimal()).toNumber() + (first.toBigDecimal() * second.toBigDecimal()).toOperand() } object DivisionFunction : BinaryOperationFunction { override fun apply(first: Operand, second: Operand) = - (first.toBigDecimal() / second.toBigDecimal()).toNumber() + (first.toBigDecimal() / second.toBigDecimal()).toOperand() } object PowerFunction : BinaryOperationFunction { override fun apply(first: Operand, second: Operand) = - (first.toBigDecimal().pow(second.toBigDecimal().toInt())).toNumber() + (first.toBigDecimal().pow(second.toBigDecimal().toInt())).toOperand() } -fun BigDecimal.toNumber() = Operand(toString()) -fun Double.toNumber() = Operand(toString()) +fun Number.toOperand() = Operand(toString()) \ No newline at end of file diff --git a/src/main/kotlin/ru/darktale/calc/Parser.kt b/src/main/kotlin/ru/darktale/calc/Parser.kt index aa04aed..c4b5219 100644 --- a/src/main/kotlin/ru/darktale/calc/Parser.kt +++ b/src/main/kotlin/ru/darktale/calc/Parser.kt @@ -5,55 +5,13 @@ import jakarta.inject.Inject interface Parser { fun parse(expression: String): Expression } -/* -class ParserImpl : Parser { - private val operations = UnaryOperations.typeMap.keys + BinaryOperations.typeMap.keys - override fun parse(expression: String): Expression { - val result = mutableListOf() - var (tokenStart, tokenEnd) = 0 to 0 - var prevNumber: String? = null - - fun parseTokenOrNull(token: String): ExpressionElement? = - Brackets.typeMap[token]?.bracket - ?: if (token in operations) getOperation(result.lastOrNull(), token) - else (token.toBigDecimalOrNull() ?: "${token}0".toBigDecimalOrNull())?.let { - prevNumber = token - return null - } ?: prevNumber?.let { - Number(it) - } - - while (tokenEnd < expression.length) { - parseTokenOrNull(expression.substring(tokenStart..tokenEnd))?.let { - result += it - tokenStart = tokenEnd - if (it.elementType == ElementType.NUMBER) - tokenEnd-- - else - tokenStart++ - } - tokenEnd++ - } - if (tokenStart < expression.length) { - result += Number(expression.substring(tokenStart)) - } - return Expression(result) - } - - private fun getOperation(previousElement: ExpressionElement?, token: String) = when { - previousElement?.elementType == ElementType.NUMBER || - previousElement?.elementType == ElementType.BRACKET -> - BinaryOperations.typeMap[token]!!.operationElement - - else -> UnaryOperations.typeMap[token]!!.operationElement - } -} -*/ class NestedExpressionsParser @Inject constructor( private val unaryOperations: Map, private val binaryOperations: Map, ) : Parser { + private val operations: Set = unaryOperations.keys + binaryOperations.keys + private val maxOperLength = operations.maxBy { it.length }.length override fun parse(expression: String): Expression { val stack = ArrayDeque>() @@ -80,16 +38,15 @@ class NestedExpressionsParser @Inject constructor( Operand(expression.substring(position - it until position)) } } else { - val operations = - if (elements.getOperationType(position) == ElementType.UNARY_OPERATION) UnaryOperations - else BinaryOperations - val key = getOperationKey(operations.typeMap.keys, expression, position) - position += (key.length) - operations[key]!! + val operation = getOperation(expression, position, elements.isUnaryPrefixOperation(position)) + position += operation.value.length + operation } } } if (stack.isNotEmpty()) throw ParseException("Unexpected end of expression, unclosed bracket") + elements.validate() + return when { elements.isEmpty() -> EMPTY_EXPRESSION elements.size == 1 && elements[0] is Expression -> elements[0] as Expression @@ -112,6 +69,14 @@ class NestedExpressionsParser @Inject constructor( } } + private fun List.validate() { + when (val operation = this.lastOrNull()) { + is BinaryOperation -> throw ParseException("expression ends with binary operation") + is UnaryOperation -> if (operation.isPrefix) throw ParseException("expression ends with prefix unary operation") + else -> Unit + } + } + private fun List.validateCloseBracket(position: Int) { when (this.lastOrNull()) { is Operand, is Expression, Brackets.CLOSE_BRACKET.bracket -> Unit @@ -119,24 +84,28 @@ class NestedExpressionsParser @Inject constructor( } } - private fun List.getOperationType(position: Int) = - when (this.lastOrNull()) { - is Operand, is Expression -> ElementType.BINARY_OPERATION - is UnaryOperation -> throw ParseException("Not a number after unary operation", position) - else -> ElementType.UNARY_OPERATION + private fun List.isUnaryPrefixOperation(position: Int) = + when (val operation = this.lastOrNull()) { + is Operand, is Expression -> false + is UnaryOperation -> { + if (operation.isPrefix) throw ParseException( + "Not a number or expression after prefix unary operation", + position + ) + else false + } + else -> true } - private fun getOperationKey(keys: Set, expression: String, position: Int): String { - val maxLength = keys.maxBy { it.length }.length - var length = 0 - while (length < maxLength && position + length <= expression.length && - expression.substring(position until position + length) !in keys - ) length++ - if (position + length >= expression.length - || expression.substring(position until position + length) !in keys - ) - throw ParseException("Unknown operation", position) - return expression.substring(position until position + length) + private fun getOperation(expression: String, position: Int, isUnaryPrefixOper: Boolean): OperationElement { + val acceptableOperations = + if (isUnaryPrefixOper) unaryOperations.filter { it.value.isPrefix } + else unaryOperations.filter { !it.value.isPrefix } + binaryOperations + + for (length in position until minOf(position + maxOperLength, expression.length)) { + acceptableOperations[expression.substring(position..length)]?.let { return it } + } + throw ParseException("Unknown operation", position) } private fun getNumberLength(expression: String, start: Int): Int { @@ -156,5 +125,4 @@ class NestedExpressionsParser @Inject constructor( class ParseException(message: String, position: Int? = null) : Throwable("""$message${position?.let { " at $it" } ?: ""}""") -private val EMPTY_EXPRESSION = Expression(emptyList()) - +private val EMPTY_EXPRESSION = Expression(emptyList()) \ No newline at end of file diff --git a/src/main/kotlin/ru/darktale/calc/infra/Modules.kt b/src/main/kotlin/ru/darktale/calc/infra/Modules.kt index 9673519..b17cf2c 100644 --- a/src/main/kotlin/ru/darktale/calc/infra/Modules.kt +++ b/src/main/kotlin/ru/darktale/calc/infra/Modules.kt @@ -3,7 +3,6 @@ package ru.darktale.calc.infra import com.google.inject.AbstractModule import com.google.inject.TypeLiteral import com.google.inject.multibindings.MapBinder -import com.google.inject.multibindings.Multibinder import ru.darktale.calc.* import ru.darktale.calc.service.CalculatorService import ru.darktale.calc.service.CalculatorServiceImpl @@ -23,6 +22,7 @@ class CalculationsModule : AbstractModule() { UnaryPlus to UnaryPlusFunction, Sinus to SinusFunction, Sqrt to SqrtFunction, + Factorial to FactorialFunction, ) private val binaryOperationMap = mapOf( BinaryMinus to BinaryMinusFunction, @@ -67,12 +67,6 @@ class CalculationsModule : AbstractModule() { } } - Multibinder.newSetBinder(binder, BinaryOperation::class.java).apply { - binaryOperationMap.keys.forEach { - addBinding().toInstance(it) - } - } - bind(ExpressionToRplConverter::class.java).to(ExpressionToRplConverterImpl::class.java) bind(Calculator::class.java).to(CalculatorImpl::class.java) bind(Parser::class.java).to(NestedExpressionsParser::class.java) diff --git a/src/main/kotlin/ru/darktale/calc/service/KeyEventHandler.kt b/src/main/kotlin/ru/darktale/calc/service/KeyEventHandler.kt index 7316db1..79292fd 100644 --- a/src/main/kotlin/ru/darktale/calc/service/KeyEventHandler.kt +++ b/src/main/kotlin/ru/darktale/calc/service/KeyEventHandler.kt @@ -5,7 +5,6 @@ import javafx.event.EventHandler import javafx.scene.input.KeyCode import javafx.scene.input.KeyEvent import ru.darktale.calc.CalcController -import java.awt.Event.BACK_SPACE interface KeyEventHandler : EventHandler diff --git a/src/test/kotlin/ru/darktale/calc/ExpressionToRplConverterImplTest.kt b/src/test/kotlin/ru/darktale/calc/ExpressionToRplConverterImplTest.kt index fbea9d8..0ca0e36 100644 --- a/src/test/kotlin/ru/darktale/calc/ExpressionToRplConverterImplTest.kt +++ b/src/test/kotlin/ru/darktale/calc/ExpressionToRplConverterImplTest.kt @@ -47,5 +47,9 @@ class ExpressionProvider : ArgumentsProvider { Expression(UnaryMinus, Operand("3"), Multiplication, OpenBracket, UnaryMinus, Operand("2"), BinaryPlus, Operand("1"), CloseBracket), listOf(Operand("3"), UnaryMinus, Operand("2"), UnaryMinus, Operand("1"), BinaryPlus, Multiplication) ), + Arguments.of( + Expression(OpenBracket, Operand("5"), BinaryPlus, Operand("1"), CloseBracket, Factorial), + listOf(Operand("5"), Operand("1"), BinaryPlus, Factorial) + ), ) } diff --git a/src/test/kotlin/ru/darktale/calc/NestedExpressionsParserTest.kt b/src/test/kotlin/ru/darktale/calc/NestedExpressionsParserTest.kt index 59c885d..93d24cf 100644 --- a/src/test/kotlin/ru/darktale/calc/NestedExpressionsParserTest.kt +++ b/src/test/kotlin/ru/darktale/calc/NestedExpressionsParserTest.kt @@ -1,5 +1,6 @@ package ru.darktale.calc +import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.assertDoesNotThrow import org.junit.jupiter.params.ParameterizedTest @@ -8,7 +9,28 @@ import kotlin.test.assertEquals import kotlin.test.assertFailsWith class NestedExpressionsParserTest { - private val parser = NestedExpressionsParser() + private lateinit var unaryOperations: Map + private lateinit var binaryOperations: Map + + private lateinit var parser: NestedExpressionsParser + + @BeforeEach + fun setup() { + // todo add mocks + unaryOperations = mapOf( + "sin" to Sinus, + "-" to UnaryMinus, + "+" to UnaryPlus, + "!" to Factorial, + ) + binaryOperations = mapOf( + "+" to BinaryPlus, + "-" to BinaryMinus, + "*" to Multiplication, + "/" to Division, + ) + parser = NestedExpressionsParser(unaryOperations, binaryOperations) + } @ParameterizedTest @CsvSource( @@ -18,7 +40,8 @@ class NestedExpressionsParserTest { "(1+2)", "(1+2)/(3+4)", "((1+2)*(3+4))", "(0)", "-1", "+0", "-.5", "-1*(-1)", "-1*-1", - "sin45", "sin(45)","sin(45*2)", + "sin45", "sin(45)", "sin(45*2)", + "(5+1)!", ) @DisplayName(("Parse correct expressions")) fun parseSuccess(expression: String) { @@ -31,6 +54,7 @@ class NestedExpressionsParserTest { "-", "+", "(", ")", "(()", ")(", "()", "1++", "++1", "+1+", + "!", "+!", "!5", ) @DisplayName("Fail incorrect expressions") fun parseException(expression: String) { diff --git a/src/test/kotlin/ru/darktale/calc/ParserImplTest.kt b/src/test/kotlin/ru/darktale/calc/ParserImplTest.kt deleted file mode 100644 index b4a42c4..0000000 --- a/src/test/kotlin/ru/darktale/calc/ParserImplTest.kt +++ /dev/null @@ -1,30 +0,0 @@ -package ru.darktale.calc - -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.params.ParameterizedTest -import org.junit.jupiter.params.provider.CsvSource -/* -class ParserImplTest { - private val parser = ParserImpl() - - @ParameterizedTest(name = "input {0} expects {1}") - @CsvSource( - "123; [123]", - "12+13; [12, +, 13]", - "120*9; [120, *, 9]", - "-11; [-, 11]", - "(3+2)*8; [(, 3, +, 2, ), *, 8]", - "1e3; [1e3]", - "1e+3; [1e+3]", - "1e-3; [1e-3]", - "1e0; [1e0]", - "1e0-3; [1e0, -, 3]", - delimiter = ';' - ) - fun parseSimpleExpression(expression: String, expectedResult: String) { - val result = parser.parse(expression) - assertEquals(expression, result.toString()) - } -} - - */ \ No newline at end of file