From daaf7b060df85ead61167349fa3548b4ff03cc48 Mon Sep 17 00:00:00 2001 From: vizitor Date: Sat, 2 Mar 2024 22:03:41 +0300 Subject: [PATCH] initial draft --- .gitignore | 34 +++ dependency-reduced-pom.xml | 159 ++++++++++++++ pom.xml | 207 ++++++++++++++++++ .../ru/darktale/calc/CalcApplication.kt | 48 ++++ .../kotlin/ru/darktale/calc/CalcController.kt | 50 +++++ .../kotlin/ru/darktale/calc/Calculator.kt | 37 ++++ src/main/kotlin/ru/darktale/calc/Converter.kt | 53 +++++ src/main/kotlin/ru/darktale/calc/Model.kt | 139 ++++++++++++ .../kotlin/ru/darktale/calc/Operations.kt | 53 +++++ src/main/kotlin/ru/darktale/calc/Parser.kt | 160 ++++++++++++++ .../kotlin/ru/darktale/calc/infra/Modules.kt | 80 +++++++ .../calc/service/CalculatorService.kt | 24 ++ .../darktale/calc/service/KeyEventHandler.kt | 21 ++ .../ru/darktale/calc/hello-view.fxml | 37 ++++ .../ru/darktale/calc/CalculatorImplTest.kt | 58 +++++ .../calc/ExpressionToRplConverterImplTest.kt | 51 +++++ .../calc/NestedExpressionsParserTest.kt | 39 ++++ .../kotlin/ru/darktale/calc/ParserImplTest.kt | 30 +++ 18 files changed, 1280 insertions(+) create mode 100644 .gitignore create mode 100644 dependency-reduced-pom.xml create mode 100644 pom.xml create mode 100644 src/main/kotlin/ru/darktale/calc/CalcApplication.kt create mode 100644 src/main/kotlin/ru/darktale/calc/CalcController.kt create mode 100644 src/main/kotlin/ru/darktale/calc/Calculator.kt create mode 100644 src/main/kotlin/ru/darktale/calc/Converter.kt create mode 100644 src/main/kotlin/ru/darktale/calc/Model.kt create mode 100644 src/main/kotlin/ru/darktale/calc/Operations.kt create mode 100644 src/main/kotlin/ru/darktale/calc/Parser.kt create mode 100644 src/main/kotlin/ru/darktale/calc/infra/Modules.kt create mode 100644 src/main/kotlin/ru/darktale/calc/service/CalculatorService.kt create mode 100644 src/main/kotlin/ru/darktale/calc/service/KeyEventHandler.kt create mode 100644 src/main/resources/ru/darktale/calc/hello-view.fxml create mode 100644 src/test/kotlin/ru/darktale/calc/CalculatorImplTest.kt create mode 100644 src/test/kotlin/ru/darktale/calc/ExpressionToRplConverterImplTest.kt create mode 100644 src/test/kotlin/ru/darktale/calc/NestedExpressionsParserTest.kt create mode 100644 src/test/kotlin/ru/darktale/calc/ParserImplTest.kt diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..39efbe8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,34 @@ +target/ +.mvn/ +mvnw* + +### IntelliJ IDEA ### +.idea/ +*.iws +*.iml +*.ipr + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/dependency-reduced-pom.xml b/dependency-reduced-pom.xml new file mode 100644 index 0000000..c9405b4 --- /dev/null +++ b/dependency-reduced-pom.xml @@ -0,0 +1,159 @@ + + + 4.0.0 + ru.darktale + calc + calc + 1.0 + + ${project.basedir}/src/main/kotlin + ${project.basedir}/src/test/kotlin + + + maven-compiler-plugin + 3.11.0 + + 21 + 21 + + + + 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 + ${kotlin.version} + + + compile + process-sources + + compile + + + + test-compile + test-compile + + test-compile + + + + + 21 + + + + maven-shade-plugin + + + package + + shade + + + + + + + + + native + + + + org.graalvm.nativeimage + native-image-maven-plugin + 19.3.6 + + + package + + native-image + + + + + calc-1.0 + --no-fallback + ru.darktale.calc.CalcApplicationKt + + + + + + + + + org.junit.jupiter + junit-jupiter-api + 5.9.2 + test + + + opentest4j + org.opentest4j + + + junit-platform-commons + org.junit.platform + + + apiguardian-api + org.apiguardian + + + + + org.junit.jupiter + junit-jupiter-engine + 5.9.2 + test + + + junit-platform-engine + org.junit.platform + + + apiguardian-api + org.apiguardian + + + + + + + + com.google.guava + guava + 33.0.0-jre + + + + + 1.9.20 + UTF-8 + 3.2.2 + 5.9.2 + 21-ea+24 + + diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..c9088a5 --- /dev/null +++ b/pom.xml @@ -0,0 +1,207 @@ + + + 4.0.0 + + ru.darktale + calc + 1.0 + jar + calc + + + UTF-8 + 5.9.2 + 1.9.20 + 3.2.2 + 21-ea+24 + + + + + com.google.guava + guava + 33.0.0-jre + + + + + + + com.google.inject + guice + 7.0.0 + + + + org.openjfx + javafx-controls + ${java.fx.version} + + + org.openjfx + javafx-fxml + ${java.fx.version} + + + + org.jetbrains.kotlin + kotlin-stdlib + ${kotlin.version} + + + + org.junit.jupiter + junit-jupiter-api + ${junit.version} + test + + + org.junit.jupiter + junit-jupiter-engine + ${junit.version} + test + + + org.junit.jupiter + junit-jupiter-params + ${junit.version} + test + + + io.mockk + mockk-jvm + 1.13.10 + test + + + org.jetbrains.kotlin + kotlin-test-junit5 + 1.8.22 + test + + + + + + ${project.basedir}/src/main/kotlin + ${project.basedir}/src/test/kotlin + + + org.apache.maven.plugins + maven-compiler-plugin + 3.11.0 + + 21 + 21 + + + + 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 + ${kotlin.version} + + + compile + process-sources + + compile + + + + test-compile + test-compile + + test-compile + + + + + 21 + + + + org.apache.maven.plugins + maven-shade-plugin + + + package + + shade + + + + + + + + + native + + false + + + + + org.graalvm.nativeimage + native-image-maven-plugin + 19.3.6 + + + + native-image + + package + + + + calc-1.0 + + + + ru.darktale.calc.CalcApplicationKt + + + + + + + \ No newline at end of file diff --git a/src/main/kotlin/ru/darktale/calc/CalcApplication.kt b/src/main/kotlin/ru/darktale/calc/CalcApplication.kt new file mode 100644 index 0000000..98fbf77 --- /dev/null +++ b/src/main/kotlin/ru/darktale/calc/CalcApplication.kt @@ -0,0 +1,48 @@ +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 kotlin.system.measureNanoTime +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 = "9^2" + val time = measureTimeMillis { + println("$expression = ${calculator.calculate(parser.parse(expression))}") + } + 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 new file mode 100644 index 0000000..036456b --- /dev/null +++ b/src/main/kotlin/ru/darktale/calc/CalcController.kt @@ -0,0 +1,50 @@ +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 new file mode 100644 index 0000000..ee74a71 --- /dev/null +++ b/src/main/kotlin/ru/darktale/calc/Calculator.kt @@ -0,0 +1,37 @@ +package ru.darktale.calc + +import jakarta.inject.Inject +import java.math.BigDecimal +import kotlin.collections.ArrayDeque + +interface Calculator { + fun calculate(expression: Expression): BigDecimal +} + +class CalculatorImpl @Inject constructor( + private val converter: ExpressionToRplConverter, + private val unaryFunctions: Map>, + private val binaryFunctions: Map>, +) : Calculator { + + override fun calculate(expression: Expression): BigDecimal { + val operands = ArrayDeque() + converter.convert(expression).process(operands) + return if (operands.size == 1) + operands.removeFirst().toBigDecimal() + else throw CalculationException() + } + + private fun List.process(operands: ArrayDeque) = forEach { + when (it) { + is Operand -> operands.addFirst(it) + is BinaryOperation -> { + val second = operands.removeFirst() + operands.addFirst(binaryFunctions[it]!!.apply(operands.removeFirst(), second)) + } + is UnaryOperation -> operands.addFirst(unaryFunctions[it]!!.apply(operands.removeFirst())) + } + } +} + +class CalculationException : Exception() \ 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 new file mode 100644 index 0000000..a5ac41e --- /dev/null +++ b/src/main/kotlin/ru/darktale/calc/Converter.kt @@ -0,0 +1,53 @@ +package ru.darktale.calc + +interface ExpressionToRplConverter { + fun convert(expression: Expression): List +} + +class ExpressionToRplConverterImpl : ExpressionToRplConverter { + override fun convert(expression: Expression) = expression.toRpl() + + /** RPL - reverse polish notation */ + private fun Expression.toRpl() = mutableListOf().apply { + 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 += element.elements.toTypedArray() + OpenBracket -> operationStack.addFirst(element) + is UnaryOperation -> { + if (element.isPrefix) operationStack.addFirst(element) + else this += element + } + + CloseBracket -> { + // pass elements to RPL + while (operationStack.first() != OpenBracket) this += operationStack.removeFirst() as CalculationToken + //remove OpenBracket itself + operationStack.removeFirst() + } + + is BinaryOperation -> { + while ( + operationStack.firstOrNull()?.let { + it is BinaryOperation && + it.priority <= element.priority + } == true + ) { + this += operationStack.removeFirst() as CalculationToken + } + operationStack.addFirst(element) + } + } + } + while (operationStack.isNotEmpty()) { + this += operationStack.removeFirst() as CalculationToken + } + } as List +} \ No newline at end of file diff --git a/src/main/kotlin/ru/darktale/calc/Model.kt b/src/main/kotlin/ru/darktale/calc/Model.kt new file mode 100644 index 0000000..c85fbb8 --- /dev/null +++ b/src/main/kotlin/ru/darktale/calc/Model.kt @@ -0,0 +1,139 @@ +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) + +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, +} + +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, +) { + 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 new file mode 100644 index 0000000..663a1a4 --- /dev/null +++ b/src/main/kotlin/ru/darktale/calc/Operations.kt @@ -0,0 +1,53 @@ +package ru.darktale.calc + +import java.math.BigDecimal +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().toNumber() +} + +object UnaryPlusFunction : UnaryOperationFunction { + override fun apply(operand: Operand) = operand +} + +object SinusFunction : UnaryOperationFunction { + override fun apply(operand: Operand) = sin(operand.toBigDecimal().toDouble()).toNumber() +} + +object SqrtFunction : UnaryOperationFunction { + override fun apply(operand: Operand) = operand.toBigDecimal().sqrt(DECIMAL128).toNumber() +} + +object BinaryMinusFunction : BinaryOperationFunction { + override fun apply(first: Operand, second: Operand) = + (first.toBigDecimal() - second.toBigDecimal()).toNumber() +} + +object BinaryPlusFunction : BinaryOperationFunction { + override fun apply(first: Operand, second: Operand) = + (first.toBigDecimal() + second.toBigDecimal()).toNumber() +} +object MultiplicationFunction : BinaryOperationFunction { + override fun apply(first: Operand, second: Operand) = + (first.toBigDecimal() * second.toBigDecimal()).toNumber() +} + +object DivisionFunction : BinaryOperationFunction { + override fun apply(first: Operand, second: Operand) = + (first.toBigDecimal() / second.toBigDecimal()).toNumber() +} + +object PowerFunction : BinaryOperationFunction { + override fun apply(first: Operand, second: Operand) = + (first.toBigDecimal().pow(second.toBigDecimal().toInt())).toNumber() +} + +fun BigDecimal.toNumber() = Operand(toString()) +fun Double.toNumber() = Operand(toString()) diff --git a/src/main/kotlin/ru/darktale/calc/Parser.kt b/src/main/kotlin/ru/darktale/calc/Parser.kt new file mode 100644 index 0000000..aa04aed --- /dev/null +++ b/src/main/kotlin/ru/darktale/calc/Parser.kt @@ -0,0 +1,160 @@ +package ru.darktale.calc + +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 { + + 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 operations = + if (elements.getOperationType(position) == ElementType.UNARY_OPERATION) UnaryOperations + else BinaryOperations + val key = getOperationKey(operations.typeMap.keys, expression, position) + position += (key.length) + operations[key]!! + } + } + } + if (stack.isNotEmpty()) throw ParseException("Unexpected end of expression, unclosed bracket") + 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.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.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 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 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()) + diff --git a/src/main/kotlin/ru/darktale/calc/infra/Modules.kt b/src/main/kotlin/ru/darktale/calc/infra/Modules.kt new file mode 100644 index 0000000..9673519 --- /dev/null +++ b/src/main/kotlin/ru/darktale/calc/infra/Modules.kt @@ -0,0 +1,80 @@ +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 +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, + ) + 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) + } + } + + 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) + } +} \ 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 new file mode 100644 index 0000000..d1e1cc2 --- /dev/null +++ b/src/main/kotlin/ru/darktale/calc/service/CalculatorService.kt @@ -0,0 +1,24 @@ +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 new file mode 100644 index 0000000..7316db1 --- /dev/null +++ b/src/main/kotlin/ru/darktale/calc/service/KeyEventHandler.kt @@ -0,0 +1,21 @@ +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 +import java.awt.Event.BACK_SPACE + +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 new file mode 100644 index 0000000..ec53d28 --- /dev/null +++ b/src/main/resources/ru/darktale/calc/hello-view.fxml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + +