diff --git a/pom.xml b/pom.xml index c9088a5..5ff5e52 100644 --- a/pom.xml +++ b/pom.xml @@ -34,17 +34,6 @@ 7.0.0 - - org.openjfx - javafx-controls - ${java.fx.version} - - - org.openjfx - javafx-fxml - ${java.fx.version} - - org.jetbrains.kotlin kotlin-stdlib @@ -110,30 +99,6 @@ --> - - org.openjfx - javafx-maven-plugin - 0.0.8 - - - - default-cli - - ru.darktale.calc.CalcApplication - app - app - app - true - true - true - - --add-modules=javafx.controls,javafx.fxml - --module-path "C:\Users\mi\.m2\repository\org\openjfx\javafx-fxml\21-ea+24";"C:\Users\mi\.m2\repository\org\openjfx\javafx-controls\21-ea+24";"C:\Users\mi\.m2\repository\org\openjfx\javafx-graphics\21-ea+24";"C:\Users\mi\.m2\repository\org\openjfx\javafx-base\21-ea+24" - - - - - org.jetbrains.kotlin kotlin-maven-plugin diff --git a/src/main/kotlin/ru/darktale/calc/CalcApplication.kt b/src/main/kotlin/ru/darktale/calc/CalcApplication.kt index 4d928b8..3f20783 100644 --- a/src/main/kotlin/ru/darktale/calc/CalcApplication.kt +++ b/src/main/kotlin/ru/darktale/calc/CalcApplication.kt @@ -1,47 +1,33 @@ package ru.darktale.calc import com.google.inject.Guice -import javafx.application.Application -import javafx.fxml.FXMLLoader -import javafx.scene.Scene -import javafx.stage.Stage -import ru.darktale.calc.infra.BasicModule -import ru.darktale.calc.infra.CalculationsModule -import ru.darktale.calc.service.KeyEventHandler +import ru.darktale.calc.guice.CalculationsModule +import ru.darktale.calc.parse.ParseException +import ru.darktale.calc.parse.Parser +import java.io.BufferedReader +import java.io.InputStreamReader import kotlin.system.measureTimeMillis -class CalcApplication : Application() { - override fun start(stage: Stage) { - initScene(stage) - stage.title = "Calc!" - stage.show() - } - - private fun initScene(stage: Stage) { - val injector = Guice.createInjector(BasicModule()) - val fxmlLoader = FXMLLoader(CalcApplication::class.java.getResource("hello-view.fxml")) - fxmlLoader.setControllerFactory { injector.getInstance(it) } - val scene = Scene(fxmlLoader.load(), 320.0, 240.0) - scene.onKeyPressed = injector.getInstance(KeyEventHandler::class.java) - stage.scene = scene - } -} -/* -fun main() { - Application.launch(CalcApplication::class.java) -} - - */ - fun main() { val injector = Guice.createInjector(CalculationsModule()) val parser = injector.getInstance(Parser::class.java) val calculator = injector.getInstance(Calculator::class.java) - val expression = "(3+1)!" - val time = measureTimeMillis { - println("$expression = ${calculator.calculate(parser.parse(expression))}") + val reader = BufferedReader(InputStreamReader(System.`in`)) + while (true) { + val expression = reader.readLine() + if (expression == "exit") break + val time = measureTimeMillis { + try { + println("$expression = ${calculator.calculate(parser.parse(expression))}") + } catch (ex: CalculationException) { + println("Calculation exception ${ex.message}") + } catch (ex: ParseException) { + println("""${ex.position?.let { " ".repeat(it) + "^" } ?: "parse exception: "} + |${ex.message}""".trimMargin()) + } + } + println("$time ms elapsed") } - println("$time ms elapsed") } \ No newline at end of file diff --git a/src/main/kotlin/ru/darktale/calc/CalcController.kt b/src/main/kotlin/ru/darktale/calc/CalcController.kt deleted file mode 100644 index 036456b..0000000 --- a/src/main/kotlin/ru/darktale/calc/CalcController.kt +++ /dev/null @@ -1,50 +0,0 @@ -package ru.darktale.calc - -import jakarta.inject.Inject -import jakarta.inject.Singleton -import javafx.fxml.FXML -import javafx.scene.control.TextField -import ru.darktale.calc.service.CalculatorService - -@Singleton -class CalcController { - - @Inject - private lateinit var calculatorService: CalculatorService - - @FXML - private lateinit var calcField: TextField - - @FXML - private fun on1Click() = addSymbol('1') - @FXML - private fun on2Click() = addSymbol('2') - @FXML - private fun on3Click() = addSymbol('3') - @FXML - private fun on4Click() = addSymbol('4') - @FXML - private fun on5Click() = addSymbol('5') - @FXML - private fun on6Click() = addSymbol('6') - @FXML - private fun on7Click() = addSymbol('7') - @FXML - private fun on8Click() = addSymbol('8') - @FXML - private fun on9Click() = addSymbol('9') - @FXML - private fun on0Click() = addSymbol('0') - @FXML - private fun onDotClick() = addSymbol('.') - - fun addSymbol(symbol: Char) { - println(this) - calcField.text = calculatorService.addSymbol(symbol) - } - - fun removeLast() { - println(this) - calcField.text = calculatorService.removeLast() - } -} \ No newline at end of file diff --git a/src/main/kotlin/ru/darktale/calc/Calculator.kt b/src/main/kotlin/ru/darktale/calc/Calculator.kt index e267c58..50a2129 100644 --- a/src/main/kotlin/ru/darktale/calc/Calculator.kt +++ b/src/main/kotlin/ru/darktale/calc/Calculator.kt @@ -1,6 +1,9 @@ package ru.darktale.calc import jakarta.inject.Inject +import ru.darktale.calc.model.* +import ru.darktale.calc.operation.BinaryOperationCalculation +import ru.darktale.calc.operation.UnaryOperationCalculation import java.math.BigDecimal import kotlin.collections.ArrayDeque @@ -10,8 +13,8 @@ interface Calculator { class CalculatorImpl @Inject constructor( private val converter: ExpressionToRplConverter, - private val unaryFunctions: Map>, - private val binaryFunctions: Map>, + private val unaryFunctions: Map>, + private val binaryFunctions: Map>, ) : Calculator { override fun calculate(expression: Expression): BigDecimal { @@ -25,6 +28,8 @@ class CalculatorImpl @Inject constructor( private fun List.process(operands: ArrayDeque) = forEach { when (it) { is Operand -> operands.addFirst(it) +// else -> with(calculations[it]!!) { operands.calc() } + is BinaryOperation -> { val second = operands.removeFirst() operands.addFirst(binaryFunctions[it]!!.apply(operands.removeFirst(), second)) diff --git a/src/main/kotlin/ru/darktale/calc/Converter.kt b/src/main/kotlin/ru/darktale/calc/Converter.kt index 083ecd9..998d80d 100644 --- a/src/main/kotlin/ru/darktale/calc/Converter.kt +++ b/src/main/kotlin/ru/darktale/calc/Converter.kt @@ -1,5 +1,8 @@ package ru.darktale.calc +import ru.darktale.calc.model.* +import ru.darktale.calc.model.TokenType.* + interface ExpressionToRplConverter { fun convert(expression: Expression): List } @@ -9,41 +12,40 @@ class ExpressionToRplConverterImpl : ExpressionToRplConverter { /** RPL - reverse polish notation */ private fun Expression.toRpl() = mutableListOf().apply { - val operationStack = ArrayDeque() + val operationStack = ArrayDeque() val queue = ArrayDeque(elements) while (queue.isNotEmpty()) { - when (val element = queue.removeFirst()) { - is Operand -> { - this += element - if (operationStack.firstOrNull() is UnaryOperation) this += operationStack.removeFirst() as UnaryOperation - } - - is Expression -> queue.addAll(0, element.elements) - OpenBracket -> operationStack.addFirst(element) - is UnaryOperation -> { - if (element.isPrefix) operationStack.addFirst(element) - else this += element - } - - CloseBracket -> { + val element = queue.removeFirst() + when (element.tokenType) { + EXPRESSION -> queue.addAll(0, (element as Expression).elements) + PREFIX_UNARY_OPERATION, PREFIX_FUNCTION -> operationStack.addFirst(element) + POSTFIX_UNARY_OPERATION -> this += (element as UnaryOperation) + OPEN_BRACKET -> operationStack.addFirst(element) + CLOSE_BRACKET -> { // pass elements to RPL while (operationStack.first() != OpenBracket) this += operationStack.removeFirst() as CalculationToken //remove OpenBracket itself operationStack.removeFirst() + if (operationStack.firstOrNull() is UnaryOperation) this += operationStack.removeFirst() as UnaryOperation } - is BinaryOperation -> { + BINARY_OPERATION -> { while ( operationStack.firstOrNull()?.let { it is BinaryOperation && - it.priority <= element.priority + it.priority <= (element as BinaryOperation).priority } == true ) { this += operationStack.removeFirst() as CalculationToken } operationStack.addFirst(element) } + + NUMBER -> { + this += (element as Operand) + if (operationStack.firstOrNull() is UnaryOperation) this += operationStack.removeFirst() as UnaryOperation + } } } while (operationStack.isNotEmpty()) { diff --git a/src/main/kotlin/ru/darktale/calc/Model.kt b/src/main/kotlin/ru/darktale/calc/Model.kt deleted file mode 100644 index ceb67a1..0000000 --- a/src/main/kotlin/ru/darktale/calc/Model.kt +++ /dev/null @@ -1,106 +0,0 @@ -package ru.darktale.calc - -import java.math.BigDecimal - -sealed class ExpressionElement { - abstract val elementType: ElementType -} - -interface CalculationToken - -class Operand( - private val value: String -) : ExpressionElement(), CalculationToken { - override var elementType: ElementType = ElementType.NUMBER - - private lateinit var bigDecimalValue: BigDecimal - - override fun toString() = value - fun toBigDecimal(): BigDecimal { - if (!::bigDecimalValue.isInitialized) bigDecimalValue = value.toBigDecimal() - return bigDecimalValue - } - - override fun equals(other: Any?): Boolean { - if (other !is Operand) return false - return value == other.value || - toBigDecimal() == other.toBigDecimal() - } - - override fun hashCode(): Int { - return toBigDecimal().hashCode() - } -} - -open class Expression( - val elements: List, -) : ExpressionElement() { - constructor(vararg elements: ExpressionElement) : this(elements.toList()) - - override val elementType = ElementType.EXPRESSION - override fun toString() = elements.joinToString("") -} - -class BracketExpression(elements: List) : Expression(listOf(OpenBracket) + elements + CloseBracket) - -sealed class Bracket(private val value: String) : ExpressionElement() { - override val elementType = ElementType.BRACKET - override fun toString() = value -} - -object OpenBracket : Bracket("(") -object CloseBracket : Bracket(")") - -sealed class OperationElement : ExpressionElement() { - abstract val value: String - abstract val isUnary: Boolean -} - -sealed class UnaryOperation( - override val value: String, - val isPrefix: Boolean -) : OperationElement(), CalculationToken { - override val elementType = ElementType.UNARY_OPERATION - override val isUnary = true - override fun toString() = value -} - -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, - val priority: Int, -) : OperationElement(), CalculationToken { - override val elementType = ElementType.BINARY_OPERATION - override val isUnary = false - override fun toString() = value -} - -object BinaryMinus : BinaryOperation("-", 3) -object BinaryPlus : BinaryOperation("+", 3) -object Multiplication : BinaryOperation("*", 2) -object Division : BinaryOperation("/", 2) -object Power : BinaryOperation("^", 1) - -enum class ElementType { - NUMBER, - BRACKET, - UNARY_OPERATION, - BINARY_OPERATION, - EXPRESSION, -} - -enum class Brackets( - val bracket: Bracket, -) { - OPEN_BRACKET(OpenBracket), - CLOSE_BRACKET(CloseBracket); - - companion object { - val typeMap = entries.associateBy { it.bracket.toString() } - } -} \ No newline at end of file diff --git a/src/main/kotlin/ru/darktale/calc/Operations.kt b/src/main/kotlin/ru/darktale/calc/Operations.kt deleted file mode 100644 index 4af3d07..0000000 --- a/src/main/kotlin/ru/darktale/calc/Operations.kt +++ /dev/null @@ -1,57 +0,0 @@ -package ru.darktale.calc - -import com.google.common.math.BigIntegerMath.factorial -import java.math.MathContext.DECIMAL128 -import java.util.function.BiFunction -import java.util.function.Function -import kotlin.math.sin - -interface UnaryOperationFunction : Function -interface BinaryOperationFunction : BiFunction - -object UnaryMinusFunction : UnaryOperationFunction { - override fun apply(operand: Operand) = operand.toBigDecimal().unaryMinus().toOperand() -} - -object UnaryPlusFunction : UnaryOperationFunction { - override fun apply(operand: Operand) = operand -} - -object SinusFunction : UnaryOperationFunction { - 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).toOperand() -} - -object BinaryMinusFunction : BinaryOperationFunction { - override fun apply(first: Operand, second: Operand) = - (first.toBigDecimal() - second.toBigDecimal()).toOperand() -} - -object BinaryPlusFunction : BinaryOperationFunction { - override fun apply(first: Operand, second: Operand) = - (first.toBigDecimal() + second.toBigDecimal()).toOperand() -} -object MultiplicationFunction : BinaryOperationFunction { - override fun apply(first: Operand, second: Operand) = - (first.toBigDecimal() * second.toBigDecimal()).toOperand() -} - -object DivisionFunction : BinaryOperationFunction { - override fun apply(first: Operand, second: Operand) = - (first.toBigDecimal() / second.toBigDecimal()).toOperand() -} - -object PowerFunction : BinaryOperationFunction { - override fun apply(first: Operand, second: Operand) = - (first.toBigDecimal().pow(second.toBigDecimal().toInt())).toOperand() -} - -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 deleted file mode 100644 index c4b5219..0000000 --- a/src/main/kotlin/ru/darktale/calc/Parser.kt +++ /dev/null @@ -1,128 +0,0 @@ -package ru.darktale.calc - -import jakarta.inject.Inject - -interface Parser { - fun parse(expression: String): Expression -} - -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>() - var elements = mutableListOf() - var position = 0 - while (position < expression.length) { - Brackets.typeMap[expression.substring(position..position)]?.let { bracket -> - if (bracket == Brackets.OPEN_BRACKET) { - elements.validateOpenBracket(position) - stack.addFirst(elements) - elements = mutableListOf() - } else { - elements.validateCloseBracket(position) - val nestedExpression = BracketExpression(elements) - elements = stack.removeFirstOrNull() ?: throw ParseException("Unexpected close bracket", position) - elements += nestedExpression - } - position++ - } ?: run { - elements += if (expression[position] in NUMBERS) { - elements.validateNumber(position) - getNumberLength(expression, position).let { - position += it - Operand(expression.substring(position - it until position)) - } - } else { - 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 - else -> Expression(elements) - } - } - - private fun List.validateNumber(position: Int) { - when (this.lastOrNull()) { - is Operand -> throw ParseException("Unexpected number after number", position) - is Expression -> throw ParseException("Unexpected number after expression", position) - else -> Unit - } - } - - private fun List.validateOpenBracket(position: Int) { - when (this.lastOrNull()) { - is OperationElement, null -> Unit - else -> throw ParseException("Unexpected open bracket", position) - } - } - - 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 - else -> throw ParseException("Unexpected close bracket", position) - } - } - - 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 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 { - var end = start - while (end < expression.length && - (expression.substring(start..end).toBigDecimalOrNull() != null || - "${expression.substring(start..end)}0".toBigDecimalOrNull() != null) - ) end++ - return end - start - } - - companion object { - private val NUMBERS = setOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.') - } -} - -class ParseException(message: String, position: Int? = null) : - Throwable("""$message${position?.let { " at $it" } ?: ""}""") - -private val EMPTY_EXPRESSION = Expression(emptyList()) \ No newline at end of file diff --git a/src/main/kotlin/ru/darktale/calc/guice/Modules.kt b/src/main/kotlin/ru/darktale/calc/guice/Modules.kt new file mode 100644 index 0000000..6da58a6 --- /dev/null +++ b/src/main/kotlin/ru/darktale/calc/guice/Modules.kt @@ -0,0 +1,64 @@ +package ru.darktale.calc.guice + +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.model.* +import ru.darktale.calc.operation.* +import ru.darktale.calc.parse.NestedExpressionsParser +import ru.darktale.calc.parse.Parser + +class CalculationsModule : AbstractModule() { + private val unaryOperationMap = mapOf( + UnaryMinus to UnaryMinusCalculation, + UnaryPlus to UnaryPlusCalculation, + Abs to AbsCalculation, + Sinus to SinusCalculation, + Cosine to CosineCalculation, + Sqrt to SqrtCalculation, + Factorial to FactorialCalculation, + ) + private val binaryOperationMap = mapOf( + BinaryMinus to BinaryMinusCalculation, + BinaryPlus to BinaryPlusCalculation, + Multiplication to MultiplicationCalculation, + Division to DivisionCalculation, + Power to PowerCalculation, + ) + + override fun configure() { + val binder = binder() + + MapBinder.newMapBinder( + binder, + TypeLiteral.get(UnaryOperation::class.java), + object : TypeLiteral>() {}, + ).apply { + unaryOperationMap.entries.forEach { + addBinding(it.key).toInstance(it.value) + } + } + + MapBinder.newMapBinder( + binder, + TypeLiteral.get(BinaryOperation::class.java), + object : TypeLiteral>() {}, + ).apply { + binaryOperationMap.entries.forEach { + addBinding(it.key).toInstance(it.value) + } + } + + Multibinder.newSetBinder(binder, OperationToken::class.java).apply { + (unaryOperationMap.keys + binaryOperationMap.keys + OpenBracket + CloseBracket).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) + } +} \ 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 deleted file mode 100644 index b17cf2c..0000000 --- a/src/main/kotlin/ru/darktale/calc/infra/Modules.kt +++ /dev/null @@ -1,74 +0,0 @@ -package ru.darktale.calc.infra - -import com.google.inject.AbstractModule -import com.google.inject.TypeLiteral -import com.google.inject.multibindings.MapBinder -import ru.darktale.calc.* -import ru.darktale.calc.service.CalculatorService -import ru.darktale.calc.service.CalculatorServiceImpl -import ru.darktale.calc.service.KeyEventHandler -import ru.darktale.calc.service.KeyEventHandlerImpl - -class BasicModule : AbstractModule() { - override fun configure() { - bind(CalculatorService::class.java).to(CalculatorServiceImpl::class.java) - bind(KeyEventHandler::class.java).to(KeyEventHandlerImpl::class.java) - } -} - -class CalculationsModule : AbstractModule() { - private val unaryOperationMap = mapOf( - UnaryMinus to UnaryMinusFunction, - UnaryPlus to UnaryPlusFunction, - Sinus to SinusFunction, - Sqrt to SqrtFunction, - Factorial to FactorialFunction, - ) - private val binaryOperationMap = mapOf( - BinaryMinus to BinaryMinusFunction, - BinaryPlus to BinaryPlusFunction, - Multiplication to MultiplicationFunction, - Division to DivisionFunction, - Power to PowerFunction, - ) - - override fun configure() { - val binder = binder() - - MapBinder.newMapBinder( - binder, - TypeLiteral.get(UnaryOperation::class.java), - object : TypeLiteral>() {}, - ).apply { - unaryOperationMap.entries.forEach { - addBinding(it.key).toInstance(it.value) - } - } - - MapBinder.newMapBinder(binder, String::class.java, UnaryOperation::class.java).apply { - unaryOperationMap.keys.forEach { - addBinding(it.value).toInstance(it) - } - } - - MapBinder.newMapBinder( - binder, - TypeLiteral.get(BinaryOperation::class.java), - object : TypeLiteral>() {}, - ).apply { - binaryOperationMap.entries.forEach { - addBinding(it.key).toInstance(it.value) - } - } - - MapBinder.newMapBinder(binder, String::class.java, BinaryOperation::class.java).apply { - binaryOperationMap.keys.forEach { - addBinding(it.value).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) - } -} \ No newline at end of file diff --git a/src/main/kotlin/ru/darktale/calc/model/Model.kt b/src/main/kotlin/ru/darktale/calc/model/Model.kt new file mode 100644 index 0000000..ab67e3b --- /dev/null +++ b/src/main/kotlin/ru/darktale/calc/model/Model.kt @@ -0,0 +1,134 @@ +package ru.darktale.calc.model + +import java.math.BigDecimal + +sealed class ExpressionToken { + abstract val tokenType: TokenType + abstract val value: String +} + +sealed interface CalculationToken + +class Operand( + override val value: String +) : ExpressionToken(), CalculationToken { + override var tokenType: TokenType = TokenType.NUMBER + + private lateinit var bigDecimalValue: BigDecimal + + override fun toString() = value + + fun toBigDecimal(): BigDecimal { + if (!::bigDecimalValue.isInitialized) bigDecimalValue = value.toBigDecimal() + return bigDecimalValue + } + + override fun equals(other: Any?): Boolean { + if (other !is Operand) return false + return value == other.value || + toBigDecimal() == other.toBigDecimal() + } + + override fun hashCode(): Int { + return toBigDecimal().hashCode() + } +} + +sealed class Expression( + val elements: List +) : ExpressionToken() { + override val value = elements.joinToString("") + override val tokenType = TokenType.EXPRESSION + override fun toString() = value +} + +class SimpleExpression(elements: List) : Expression(elements) { + constructor(vararg elements: ExpressionToken) : this(elements.toList()) +} + +class BracketExpression(elements: List) : + Expression(listOf(OpenBracket) + elements + CloseBracket) + +object EmptyExpression : Expression(emptyList()) + +sealed class OperationToken : ExpressionToken() { + abstract val hasLeftOperand: Boolean + abstract val hasRightOperand: Boolean + abstract val priority: Int +} + +sealed class Bracket( + override val value: String, + override val tokenType: TokenType, +) : OperationToken() { + override val hasLeftOperand = false + override val hasRightOperand = false + override val priority = 0 + override fun toString() = value +} + +object OpenBracket : Bracket("(", TokenType.OPEN_BRACKET) +object CloseBracket : Bracket(")", TokenType.CLOSE_BRACKET) + + +sealed class UnaryOperation: OperationToken(), CalculationToken { + override val priority = 0 + override fun toString() = value +} + +sealed class PrefixUnaryOperation( + override val value: String, +) : UnaryOperation() { + override val tokenType = TokenType.PREFIX_UNARY_OPERATION + override val hasLeftOperand = false + override val hasRightOperand = true +} + +sealed class PrefixFunction( + override val value: String +) : PrefixUnaryOperation(value) { + override val tokenType = TokenType.PREFIX_FUNCTION +} + +sealed class PostfixUnaryOperation( + override val value: String, +) : UnaryOperation() { + override val tokenType = TokenType.POSTFIX_UNARY_OPERATION + override val hasLeftOperand = true + override val hasRightOperand = false +} + +object UnaryMinus : PrefixUnaryOperation("-") +object UnaryPlus : PrefixUnaryOperation("+") +object Abs : PrefixFunction("abs") +object Sinus : PrefixFunction("sin") +object Cosine : PrefixFunction("cos") +object Sqrt : PrefixFunction("sqrt") +object Factorial : PostfixUnaryOperation("!") + +sealed class BinaryOperation( + override val value: String, + override val priority: Int +) : OperationToken(), CalculationToken { + override val tokenType = TokenType.BINARY_OPERATION + override val hasLeftOperand = true + override val hasRightOperand = true + override fun toString() = value +} + +object BinaryMinus : BinaryOperation("-", 3) +object BinaryPlus : BinaryOperation("+", 3) +object Multiplication : BinaryOperation("*", 2) +object Division : BinaryOperation("/", 2) +object Power : BinaryOperation("^", 1) + +enum class TokenType { + NUMBER, + OPEN_BRACKET, + CLOSE_BRACKET, + PREFIX_UNARY_OPERATION, + PREFIX_FUNCTION, + POSTFIX_UNARY_OPERATION, + BINARY_OPERATION, + EXPRESSION, +} \ No newline at end of file diff --git a/src/main/kotlin/ru/darktale/calc/operation/Operations.kt b/src/main/kotlin/ru/darktale/calc/operation/Operations.kt new file mode 100644 index 0000000..8eaa62d --- /dev/null +++ b/src/main/kotlin/ru/darktale/calc/operation/Operations.kt @@ -0,0 +1,71 @@ +package ru.darktale.calc.operation + +import com.google.common.math.BigIntegerMath.factorial +import ru.darktale.calc.model.* +import java.math.MathContext.DECIMAL128 +import java.util.function.BiFunction +import java.util.function.Function +import kotlin.math.cos +import kotlin.math.sin + +interface UnaryOperationCalculation : Function +interface BinaryOperationCalculation : BiFunction + +object UnaryMinusCalculation : UnaryOperationCalculation { + override fun apply(operand: Operand) = operand.toBigDecimal().unaryMinus().toOperand() +} + +object UnaryPlusCalculation : UnaryOperationCalculation { + override fun apply(operand: Operand) = operand +} + +object SinusCalculation : UnaryOperationCalculation { + override fun apply(operand: Operand) = sin(operand.toDouble()).toOperand() +} + + +object AbsCalculation : UnaryOperationCalculation { + override fun apply(operand: Operand) = + if (operand.value.startsWith("-")) Operand(operand.value.substring(1)) + else operand +} + +object CosineCalculation : UnaryOperationCalculation { + override fun apply(operand: Operand) = cos(operand.toDouble()).toOperand() +} + +object FactorialCalculation : UnaryOperationCalculation { + override fun apply(operand: Operand) = + factorial(operand.toBigDecimal().toInt()).toOperand() +} + +object SqrtCalculation : UnaryOperationCalculation { + override fun apply(operand: Operand) = operand.toBigDecimal().sqrt(DECIMAL128).toOperand() +} + +object BinaryMinusCalculation : BinaryOperationCalculation { + override fun apply(first: Operand, second: Operand) = + (first.toBigDecimal() - second.toBigDecimal()).toOperand() +} + +object BinaryPlusCalculation : BinaryOperationCalculation { + override fun apply(first: Operand, second: Operand) = + (first.toBigDecimal() + second.toBigDecimal()).toOperand() +} +object MultiplicationCalculation : BinaryOperationCalculation { + override fun apply(first: Operand, second: Operand) = + (first.toBigDecimal() * second.toBigDecimal()).toOperand() +} + +object DivisionCalculation : BinaryOperationCalculation { + override fun apply(first: Operand, second: Operand) = + (first.toBigDecimal().divide(second.toBigDecimal(), DECIMAL128)).toOperand() +} + +object PowerCalculation : BinaryOperationCalculation { + override fun apply(first: Operand, second: Operand) = + (first.toBigDecimal().pow(second.toBigDecimal().toInt())).toOperand() +} + +fun Number.toOperand() = Operand(toString()) +fun Operand.toDouble() = this.value.toDouble() \ No newline at end of file diff --git a/src/main/kotlin/ru/darktale/calc/parse/Parser.kt b/src/main/kotlin/ru/darktale/calc/parse/Parser.kt new file mode 100644 index 0000000..f9c6d42 --- /dev/null +++ b/src/main/kotlin/ru/darktale/calc/parse/Parser.kt @@ -0,0 +1,94 @@ +package ru.darktale.calc.parse + +import jakarta.inject.Inject +import ru.darktale.calc.model.* +import ru.darktale.calc.model.TokenType.* + +interface Parser { + fun parse(expression: String): Expression +} + +class NestedExpressionsParser @Inject constructor( + operationTokens: Set, +) : Parser { + private val tokensByType = operationTokens.groupBy { it.tokenType } + + override fun parse(expression: String): Expression { + val stack = ArrayDeque>() + var elements = mutableListOf() + var position = 0 + while (position < expression.length) { + val possibleTokenTypes = elements.getPossibleTokenTypes() + val token = expression.getNextToken(position, possibleTokenTypes) + when (token.tokenType) { + OPEN_BRACKET -> { + stack.addFirst(elements) + elements = mutableListOf() + } + CLOSE_BRACKET -> { + val nestedExpression = BracketExpression(elements) + elements = stack.removeFirstOrNull() ?: throw ParseException("Unexpected close bracket", position) + elements += nestedExpression + } + else -> elements += token + } + position += token.value.length + } + if (stack.isNotEmpty()) throw ParseException("Unexpected end of expression, unclosed bracket") + elements.validate() + + return when { + elements.isEmpty() -> EmptyExpression + elements.size == 1 && elements[0] is Expression -> elements[0] as Expression + else -> SimpleExpression(elements) + } + } + + private fun String.getNextToken(position: Int, possibleTokenTypes: Set): ExpressionToken { + if (NUMBER in possibleTokenTypes && this[position] in NUMBER_FIRST_CHARS) { + var end = position + while (end < this.length && + (this.substring(position..end).toBigDecimalOrNull() != null || + "${this.substring(position..end)}0".toBigDecimalOrNull() != null) + ) end++ + return Operand(this.substring(position until end)) + } + + val expectedTokens = tokensByType.filter { it.key in possibleTokenTypes } + .flatMap { it.value } + .associateBy { it.value } + val maxLength = expectedTokens.keys.maxBy { it.length }.length + for (length in position until minOf(position + maxLength, this.length)) { + expectedTokens[this.substring(position..length)]?.let { return it } + } + throw ParseException("Unexpected symbol", position) + } + + private fun List.validate() { + when (this.lastOrNull()?.tokenType) { + BINARY_OPERATION -> throw ParseException("Expression ends with binary operation") + PREFIX_UNARY_OPERATION -> throw ParseException("Expression ends with prefix unary operation") + OPEN_BRACKET -> throw ParseException("Expression ends with open bracket") + else -> Unit + } + } + + private fun List.getPossibleTokenTypes(): Set = + when (this.lastOrNull()?.tokenType) { + null, OPEN_BRACKET, BINARY_OPERATION -> OPERANDS + PREFIX_UNARY_OPERATION -> PREFIXED_OPERANDS + NUMBER, POSTFIX_UNARY_OPERATION, CLOSE_BRACKET, EXPRESSION -> AFTER_OPERANDS + PREFIX_FUNCTION -> FUNCTION_BODY + } + + companion object Sets { + private val OPERANDS = setOf(PREFIX_UNARY_OPERATION, PREFIX_FUNCTION, OPEN_BRACKET, NUMBER) + private val PREFIXED_OPERANDS = setOf(OPEN_BRACKET, NUMBER, PREFIX_FUNCTION) + private val AFTER_OPERANDS = setOf(POSTFIX_UNARY_OPERATION, BINARY_OPERATION, CLOSE_BRACKET) + private val FUNCTION_BODY = setOf(OPEN_BRACKET) + private val NUMBER_FIRST_CHARS = setOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.') + } +} + +class ParseException(message: String, val position: Int? = null) : + Throwable("""$message${position?.let { " at $it" } ?: ""}""") \ No newline at end of file diff --git a/src/main/kotlin/ru/darktale/calc/service/CalculatorService.kt b/src/main/kotlin/ru/darktale/calc/service/CalculatorService.kt deleted file mode 100644 index d1e1cc2..0000000 --- a/src/main/kotlin/ru/darktale/calc/service/CalculatorService.kt +++ /dev/null @@ -1,24 +0,0 @@ -package ru.darktale.calc.service - -import jakarta.inject.Singleton -import kotlin.text.StringBuilder - -interface CalculatorService { - fun addSymbol(symbol: Char): String - fun removeLast(): String -} - -@Singleton -class CalculatorServiceImpl: CalculatorService { - private val builder = StringBuilder() - - override fun addSymbol(symbol: Char): String { - builder.append(symbol) - return builder.toString() - } - - override fun removeLast(): String { - val len = builder.length - return if (len > 0) builder.deleteAt(len - 1).toString() else "" - } -} diff --git a/src/main/kotlin/ru/darktale/calc/service/KeyEventHandler.kt b/src/main/kotlin/ru/darktale/calc/service/KeyEventHandler.kt deleted file mode 100644 index 79292fd..0000000 --- a/src/main/kotlin/ru/darktale/calc/service/KeyEventHandler.kt +++ /dev/null @@ -1,20 +0,0 @@ -package ru.darktale.calc.service - -import jakarta.inject.Inject -import javafx.event.EventHandler -import javafx.scene.input.KeyCode -import javafx.scene.input.KeyEvent -import ru.darktale.calc.CalcController - -interface KeyEventHandler : EventHandler - -class KeyEventHandlerImpl : KeyEventHandler { - @Inject - private lateinit var calcController: CalcController - - override fun handle(keyEvent: KeyEvent) { - println(keyEvent) - if (keyEvent.code == KeyCode.BACK_SPACE) calcController.removeLast() - else calcController.addSymbol(keyEvent.character.toCharArray()[0]) - } -} \ No newline at end of file diff --git a/src/main/resources/ru/darktale/calc/hello-view.fxml b/src/main/resources/ru/darktale/calc/hello-view.fxml deleted file mode 100644 index ec53d28..0000000 --- a/src/main/resources/ru/darktale/calc/hello-view.fxml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - -