diff --git a/.detekt.yml b/.detekt.yml index 853ebdb11..8331c29b1 100644 --- a/.detekt.yml +++ b/.detekt.yml @@ -571,7 +571,7 @@ style: - reason: 'Kotlin does not support @Inherited annotation, see https://youtrack.jetbrains.com/issue/KT-22265' value: 'java.lang.annotation.Inherited' ForbiddenComment: - active: true + active: false comments: - reason: 'Forbidden FIXME todo marker in comment, please fix the problem.' value: 'FIXME:' @@ -662,8 +662,6 @@ style: active: true OptionalUnit: active: false - OptionalWhenBraces: - active: false PreferToOverPairSyntax: active: false ProtectedMemberInFinalClass: diff --git a/.editorconfig b/.editorconfig index 20de88770..2580bcf05 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,2 +1,3 @@ [*.{kt,kts}] -indent_size=4 +indent_size = 4 +max_line_length = 120 diff --git a/.github/workflows/test-extensively.yml b/.github/workflows/test-extensively.yml index a74674d9c..c62369b94 100644 --- a/.github/workflows/test-extensively.yml +++ b/.github/workflows/test-extensively.yml @@ -9,7 +9,7 @@ jobs: fail-fast: false matrix: os: [ windows-2022, macos-12, ubuntu-22.04 ] - java-version: [11, 17, 19] + java-version: [11, 17, 21] jdk-dist: - adopt-hotspot - temurin @@ -40,8 +40,8 @@ jobs: node-version: - 'latest-16' - 'latest-18' - - 'latest-19' - 'latest-20' + - 'latest-21' runs-on: ${{ matrix.os }} env: ORG_GRADLE_PROJECT_nodeVersion: ${{ matrix.node-version }} diff --git a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/BinaryDecisionDiagram.kt b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/BinaryDecisionDiagram.kt index c474f7412..72b86e01a 100644 --- a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/BinaryDecisionDiagram.kt +++ b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/BinaryDecisionDiagram.kt @@ -93,7 +93,7 @@ interface BinaryDecisionDiagram> { fun > variableOf( value: E, low: BinaryDecisionDiagram, - high: BinaryDecisionDiagram + high: BinaryDecisionDiagram, ): BinaryDecisionDiagram = BinaryDecisionDiagramBuilder.defaultOf().buildVariable(value, low, high) /** Creates a new [Terminal] node from diff --git a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/BinaryDecisionDiagramBuilder.kt b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/BinaryDecisionDiagramBuilder.kt index 05cd7d5f9..6fe7b795a 100644 --- a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/BinaryDecisionDiagramBuilder.kt +++ b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/BinaryDecisionDiagramBuilder.kt @@ -16,13 +16,16 @@ import kotlin.js.JsName * @author Jason Dellaluce */ interface BinaryDecisionDiagramBuilder> { - /** * Returns an instance of [BinaryDecisionDiagram.Variable] with * the provided input. * */ @JsName("buildVariable") - fun buildVariable(value: T, low: BinaryDecisionDiagram, high: BinaryDecisionDiagram): BinaryDecisionDiagram + fun buildVariable( + value: T, + low: BinaryDecisionDiagram, + high: BinaryDecisionDiagram, + ): BinaryDecisionDiagram /** * Returns an instance of [BinaryDecisionDiagram.Terminal] with @@ -68,7 +71,7 @@ interface BinaryDecisionDiagramBuilder> { * */ @JsName("reducedOf") fun > reducedOf( - delegate: BinaryDecisionDiagramBuilder = defaultOf() + delegate: BinaryDecisionDiagramBuilder = defaultOf(), ): BinaryDecisionDiagramBuilder { return ReducedBinaryDecisionDiagramBuilder(delegate) } diff --git a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/BinaryDecisionDiagramOperators.kt b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/BinaryDecisionDiagramOperators.kt index f5767f021..b5d755dac 100644 --- a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/BinaryDecisionDiagramOperators.kt +++ b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/BinaryDecisionDiagramOperators.kt @@ -17,14 +17,12 @@ import kotlin.jvm.JvmName * Decision Diagram (ROBDD). * */ @JsName("applyUnary") -fun > BinaryDecisionDiagram.apply( - unaryOp: (Boolean) -> Boolean -): BinaryDecisionDiagram { +fun > BinaryDecisionDiagram.apply(unaryOp: (Boolean) -> Boolean): BinaryDecisionDiagram { return runOperationAndCatchErrors { this.applyThenExpansion( unaryOp, 0, - 0 + 0, ) { _, _, _ -> 0 } }.first } @@ -37,14 +35,14 @@ fun > BinaryDecisionDiagram.apply( @JsName("applyBinary") fun > BinaryDecisionDiagram.apply( that: BinaryDecisionDiagram, - binaryOp: (Boolean, Boolean) -> Boolean + binaryOp: (Boolean, Boolean) -> Boolean, ): BinaryDecisionDiagram { return runOperationAndCatchErrors { this.applyThenExpansion( that, binaryOp, 0, - 0 + 0, ) { _, _, _ -> 0 } }.first } @@ -65,7 +63,7 @@ fun , E> BinaryDecisionDiagram.applyThenExpansion( unaryOp: (Boolean) -> Boolean, expansionFalseTerminal: E, expansionTrueTerminal: E, - expansionOperator: (node: T, low: E, high: E) -> E + expansionOperator: (node: T, low: E, high: E) -> E, ): Pair, E> { return runOperationAndCatchErrors { this.accept( @@ -74,8 +72,8 @@ fun , E> BinaryDecisionDiagram.applyThenExpansion( unaryOp, expansionFalseTerminal, expansionTrueTerminal, - expansionOperator - ) + expansionOperator, + ), ) } } @@ -97,7 +95,7 @@ fun , E> BinaryDecisionDiagram.applyThenExpansion( binaryOp: (Boolean, Boolean) -> Boolean, expansionFalseTerminal: E, expansionTrueTerminal: E, - expansionOperator: (node: T, low: E, high: E) -> E + expansionOperator: (node: T, low: E, high: E) -> E, ): Pair, E> { return runOperationAndCatchErrors { this.accept( @@ -107,8 +105,8 @@ fun , E> BinaryDecisionDiagram.applyThenExpansion( binaryOp, expansionFalseTerminal, expansionTrueTerminal, - expansionOperator - ) + expansionOperator, + ), ) } } @@ -139,14 +137,14 @@ fun > BinaryDecisionDiagram.not(): BinaryDecisionDiagram fun , E> BinaryDecisionDiagram.notThenExpansion( expansionFalseTerminal: E, expansionTrueTerminal: E, - expansionOperator: (node: T, low: E, high: E) -> E + expansionOperator: (node: T, low: E, high: E) -> E, ): Pair, E> { return runOperationAndCatchErrors { this.applyThenExpansion( { a -> !a }, expansionFalseTerminal, expansionTrueTerminal, - expansionOperator + expansionOperator, ) } } @@ -157,9 +155,7 @@ fun , E> BinaryDecisionDiagram.notThenExpansion( * Decision Diagram (ROBDD). */ @JsName("and") -infix fun > BinaryDecisionDiagram.and( - that: BinaryDecisionDiagram -): BinaryDecisionDiagram { +infix fun > BinaryDecisionDiagram.and(that: BinaryDecisionDiagram): BinaryDecisionDiagram { return runOperationAndCatchErrors { this.apply(that) { a, b -> a && b } } @@ -181,7 +177,7 @@ fun , E> BinaryDecisionDiagram.andThenExpansion( that: BinaryDecisionDiagram, expansionFalseTerminal: E, expansionTrueTerminal: E, - expansionOperator: (node: T, low: E, high: E) -> E + expansionOperator: (node: T, low: E, high: E) -> E, ): Pair, E> { return runOperationAndCatchErrors { this.applyThenExpansion( @@ -189,7 +185,7 @@ fun , E> BinaryDecisionDiagram.andThenExpansion( { a, b -> a && b }, expansionFalseTerminal, expansionTrueTerminal, - expansionOperator + expansionOperator, ) } } @@ -199,9 +195,7 @@ fun , E> BinaryDecisionDiagram.andThenExpansion( * The result is a Reduced Ordered Binary Decision Diagram (ROBDD). */ @JsName("or") -infix fun > BinaryDecisionDiagram.or( - that: BinaryDecisionDiagram -): BinaryDecisionDiagram { +infix fun > BinaryDecisionDiagram.or(that: BinaryDecisionDiagram): BinaryDecisionDiagram { return runOperationAndCatchErrors { this.apply(that) { a, b -> a || b } } @@ -223,7 +217,7 @@ fun , E> BinaryDecisionDiagram.orThenExpansion( that: BinaryDecisionDiagram, expansionFalseTerminal: E, expansionTrueTerminal: E, - expansionOperator: (node: T, low: E, high: E) -> E + expansionOperator: (node: T, low: E, high: E) -> E, ): Pair, E> { return runOperationAndCatchErrors { this.applyThenExpansion( @@ -231,7 +225,7 @@ fun , E> BinaryDecisionDiagram.orThenExpansion( { a, b -> a || b }, expansionFalseTerminal, expansionTrueTerminal, - expansionOperator + expansionOperator, ) } } diff --git a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/BinaryDecisionDiagramUtils.kt b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/BinaryDecisionDiagramUtils.kt index 34ee2c30a..6058d9c55 100644 --- a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/BinaryDecisionDiagramUtils.kt +++ b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/BinaryDecisionDiagramUtils.kt @@ -16,16 +16,14 @@ import kotlin.jvm.JvmName * Shortcut for the [BinaryDecisionDiagram.variableOf] method. */ @JsName("bddOf") -fun > bddOf(value: T): BinaryDecisionDiagram = - BinaryDecisionDiagram.variableOf(value) +fun > bddOf(value: T): BinaryDecisionDiagram = BinaryDecisionDiagram.variableOf(value) /** * Shortcut for the [BinaryDecisionDiagram.terminalOf] method. */ @JsName("bddTerminalOf") -fun > bddTerminalOf( - value: Boolean -): BinaryDecisionDiagram = BinaryDecisionDiagram.terminalOf(value) +fun > bddTerminalOf(value: Boolean): BinaryDecisionDiagram = + BinaryDecisionDiagram.terminalOf(value) /** Internal helper function to catch all exceptions and wrap them into * BBD-specific ones. */ @@ -35,7 +33,7 @@ internal fun runOperationAndCatchErrors(action: () -> T): T { } catch (e: Throwable) { throw BinaryDecisionDiagramOperationException( "BinaryDecisionDiagram operation failure", - e + e, ) } } @@ -50,15 +48,15 @@ internal fun runOperationAndCatchErrors(action: () -> T): T { fun , E> BinaryDecisionDiagram.expansion( falseTerminal: E, trueTerminal: E, - operator: (node: T, low: E, high: E) -> E + operator: (node: T, low: E, high: E) -> E, ): E { return runOperationAndCatchErrors { this.accept( ExpansionVisitor( operator, falseTerminal, - trueTerminal - ) + trueTerminal, + ), ) } } @@ -68,9 +66,7 @@ fun , E> BinaryDecisionDiagram.expansion( * element matching the given predicate. */ @JsName("anyWhere") -fun > BinaryDecisionDiagram.any( - predicate: (T) -> Boolean -): Boolean { +fun > BinaryDecisionDiagram.any(predicate: (T) -> Boolean): Boolean { return runOperationAndCatchErrors { this.accept(AnyVisitor(predicate)) } @@ -92,14 +88,12 @@ fun > BinaryDecisionDiagram.any(): Boolean { * The internal structure of the diagram is maintained. */ @JsName("map") -fun , E : Comparable> BinaryDecisionDiagram.map( - mapper: (T) -> E -): BinaryDecisionDiagram { +fun , E : Comparable> BinaryDecisionDiagram.map(mapper: (T) -> E): BinaryDecisionDiagram { val builder = BinaryDecisionDiagramBuilder.reducedOf() return runOperationAndCatchErrors { this.expansion( builder.buildTerminal(false), - builder.buildTerminal(true) + builder.buildTerminal(true), ) { node, low, high -> builder.buildVariable(mapper(node), low, high) } } } @@ -124,7 +118,7 @@ fun > BinaryDecisionDiagram.toDotString(): String { val nodeValue = Triple(node, low, high).hashCode() if (nodeValue !in checkSet) { labelBuilder.append( - "$nodeValue [shape=record, label=\"$node\"]\n" + "$nodeValue [shape=record, label=\"$node\"]\n", ) graphBuilder.append("$nodeValue -> $low [style=dashed]\n") graphBuilder.append("$nodeValue -> $high\n") diff --git a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/BinaryDecisionDiagramVisitor.kt b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/BinaryDecisionDiagramVisitor.kt index a04b00085..66bb3a5c6 100644 --- a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/BinaryDecisionDiagramVisitor.kt +++ b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/BinaryDecisionDiagramVisitor.kt @@ -11,7 +11,6 @@ import kotlin.js.JsName * @author Jason Dellaluce */ interface BinaryDecisionDiagramVisitor, E> { - companion object @JsName("visitTerminal") diff --git a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/exception/BinaryDecisionDiagramException.kt b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/exception/BinaryDecisionDiagramException.kt index d89535675..703d66c51 100644 --- a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/exception/BinaryDecisionDiagramException.kt +++ b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/exception/BinaryDecisionDiagramException.kt @@ -8,7 +8,9 @@ import kotlin.jvm.JvmOverloads * @param message the detail message string. * @param cause the cause of this exception. */ -open class BinaryDecisionDiagramException @JvmOverloads constructor( - override val message: String? = null, - override val cause: Throwable? = null -) : RuntimeException(message, cause) +open class BinaryDecisionDiagramException + @JvmOverloads + constructor( + override val message: String? = null, + override val cause: Throwable? = null, + ) : RuntimeException(message, cause) diff --git a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/exception/BinaryDecisionDiagramOperationException.kt b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/exception/BinaryDecisionDiagramOperationException.kt index 1d96c15a3..5352486c5 100644 --- a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/exception/BinaryDecisionDiagramOperationException.kt +++ b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/exception/BinaryDecisionDiagramOperationException.kt @@ -8,7 +8,9 @@ import kotlin.jvm.JvmOverloads * @param message the detail message string. * @param cause the cause of this exception. */ -class BinaryDecisionDiagramOperationException @JvmOverloads constructor( - message: String?, - cause: Throwable? = null -) : BinaryDecisionDiagramException(message, cause) +class BinaryDecisionDiagramOperationException + @JvmOverloads + constructor( + message: String?, + cause: Throwable? = null, + ) : BinaryDecisionDiagramException(message, cause) diff --git a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/AnyVisitor.kt b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/AnyVisitor.kt index a86c669d3..32abf613e 100644 --- a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/AnyVisitor.kt +++ b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/AnyVisitor.kt @@ -10,12 +10,9 @@ import it.unibo.tuprolog.bdd.BinaryDecisionDiagramVisitor * @author Jason Dellaluce */ internal class AnyVisitor>( - private val predicate: (T) -> Boolean + private val predicate: (T) -> Boolean, ) : BinaryDecisionDiagramVisitor { - - override fun visit( - node: BinaryDecisionDiagram.Terminal - ): Boolean = false + override fun visit(node: BinaryDecisionDiagram.Terminal): Boolean = false override fun visit(node: BinaryDecisionDiagram.Variable): Boolean { var result = predicate(node.value) diff --git a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/BinaryApplyExpansionVisitor.kt b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/BinaryApplyExpansionVisitor.kt index b724d14b7..5fe5df670 100644 --- a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/BinaryApplyExpansionVisitor.kt +++ b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/BinaryApplyExpansionVisitor.kt @@ -38,17 +38,15 @@ internal class BinaryApplyExpansionVisitor, E>( private val operator: (first: Boolean, second: Boolean) -> Boolean, private val expansionFalseTerminal: E, private val expansionTrueTerminal: E, - private val expansionOperator: (node: T, low: E, high: E) -> E + private val expansionOperator: (node: T, low: E, high: E) -> E, ) : BinaryDecisionDiagramVisitor> { private val dynamicTable: MutableMap>> = - mutableMapOf() + mutableMapOf() private val castVisitor = CastVisitor>() - override fun visit( - node: BinaryDecisionDiagram.Terminal - ): ApplyExpansionResult { + override fun visit(node: BinaryDecisionDiagram.Terminal): ApplyExpansionResult { return visitWithTable(node, thatNode) { castVisitor.onTerminal = { that -> this.apply(node, that) } castVisitor.onVariable = { that -> this.apply(node, that) } @@ -56,9 +54,7 @@ internal class BinaryApplyExpansionVisitor, E>( } } - override fun visit( - node: BinaryDecisionDiagram.Variable - ): ApplyExpansionResult { + override fun visit(node: BinaryDecisionDiagram.Variable): ApplyExpansionResult { return visitWithTable(node, thatNode) { castVisitor.onTerminal = { that -> this.apply(node, that) } castVisitor.onVariable = { that -> this.apply(node, that) } @@ -69,7 +65,7 @@ internal class BinaryApplyExpansionVisitor, E>( private fun visitWithTable( first: BinaryDecisionDiagram, second: BinaryDecisionDiagram, - computation: () -> ApplyExpansionResult + computation: () -> ApplyExpansionResult, ): ApplyExpansionResult { val firstKey = first.hashCode() val secondKey = second.hashCode() @@ -88,18 +84,18 @@ internal class BinaryApplyExpansionVisitor, E>( private fun apply( first: BinaryDecisionDiagram.Terminal, - second: BinaryDecisionDiagram.Terminal + second: BinaryDecisionDiagram.Terminal, ): ApplyExpansionResult { val truth = operator(first.truth, second.truth) return ApplyExpansionResult( builder.buildTerminal(truth), - if (truth) expansionTrueTerminal else expansionFalseTerminal + if (truth) expansionTrueTerminal else expansionFalseTerminal, ) } private fun apply( first: BinaryDecisionDiagram.Terminal, - second: BinaryDecisionDiagram.Variable + second: BinaryDecisionDiagram.Variable, ): ApplyExpansionResult { thatNode = second.low val lowNode = first.accept(this) @@ -107,13 +103,13 @@ internal class BinaryApplyExpansionVisitor, E>( val highNode = first.accept(this) return ApplyExpansionResult( builder.buildVariable(second.value, lowNode.first, highNode.first), - expansionOperator(second.value, lowNode.second, highNode.second) + expansionOperator(second.value, lowNode.second, highNode.second), ) } private fun apply( first: BinaryDecisionDiagram.Variable, - second: BinaryDecisionDiagram.Terminal + second: BinaryDecisionDiagram.Terminal, ): ApplyExpansionResult { thatNode = first return second.accept(this) @@ -121,7 +117,7 @@ internal class BinaryApplyExpansionVisitor, E>( private fun apply( first: BinaryDecisionDiagram.Variable, - second: BinaryDecisionDiagram.Variable + second: BinaryDecisionDiagram.Variable, ): ApplyExpansionResult { val newValue: T val firstLow: BinaryDecisionDiagram @@ -152,7 +148,7 @@ internal class BinaryApplyExpansionVisitor, E>( val highNode = firstHigh.accept(this) return ApplyExpansionResult( builder.buildVariable(newValue, lowNode.first, highNode.first), - expansionOperator(newValue, lowNode.second, highNode.second) + expansionOperator(newValue, lowNode.second, highNode.second), ) } } diff --git a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/ExpansionVisitor.kt b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/ExpansionVisitor.kt index 3bf57fe57..4cb2f956f 100644 --- a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/ExpansionVisitor.kt +++ b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/ExpansionVisitor.kt @@ -14,9 +14,8 @@ import it.unibo.tuprolog.bdd.BinaryDecisionDiagramVisitor internal class ExpansionVisitor, E>( private val varOp: (node: T, low: E, high: E) -> E, private val falseTerminal: E, - private val trueTerminal: E + private val trueTerminal: E, ) : BinaryDecisionDiagramVisitor { - override fun visit(node: BinaryDecisionDiagram.Terminal): E { return if (node.truth) trueTerminal else falseTerminal } diff --git a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/UnaryApplyExpansionVisitor.kt b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/UnaryApplyExpansionVisitor.kt index 5d5c464a0..d02fcbf75 100644 --- a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/UnaryApplyExpansionVisitor.kt +++ b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/UnaryApplyExpansionVisitor.kt @@ -29,34 +29,31 @@ internal class UnaryApplyExpansionVisitor, E>( private val operator: (first: Boolean) -> Boolean, private val expansionFalseTerminal: E, private val expansionTrueTerminal: E, - private val expansionOperator: (node: T, low: E, high: E) -> E + private val expansionOperator: (node: T, low: E, high: E) -> E, ) : BinaryDecisionDiagramVisitor> { private val dynamicTable: MutableMap> = mutableMapOf() - override fun visit( - node: BinaryDecisionDiagram.Terminal - ): ApplyExpansionResult { + override fun visit(node: BinaryDecisionDiagram.Terminal): ApplyExpansionResult { val resTruth = operator(node.truth) return ApplyExpansionResult( builder.buildTerminal(resTruth), - if (resTruth) expansionTrueTerminal else expansionFalseTerminal + if (resTruth) expansionTrueTerminal else expansionFalseTerminal, ) } - override fun visit( - node: BinaryDecisionDiagram.Variable - ): ApplyExpansionResult { + override fun visit(node: BinaryDecisionDiagram.Variable): ApplyExpansionResult { val key = node.hashCode() if (dynamicTable.containsKey(key)) { return dynamicTable[key]!! } val lowNode = node.low.accept(this) val highNode = node.high.accept(this) - val result = ApplyExpansionResult( - builder.buildVariable(node.value, lowNode.first, highNode.first), - expansionOperator(node.value, lowNode.second, highNode.second) - ) + val result = + ApplyExpansionResult( + builder.buildVariable(node.value, lowNode.first, highNode.first), + expansionOperator(node.value, lowNode.second, highNode.second), + ) dynamicTable[key] = result return result } diff --git a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/builder/ReducedBinaryDecisionDiagramBuilder.kt b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/builder/ReducedBinaryDecisionDiagramBuilder.kt index 5bfe2ba75..bc55a39d1 100644 --- a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/builder/ReducedBinaryDecisionDiagramBuilder.kt +++ b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/builder/ReducedBinaryDecisionDiagramBuilder.kt @@ -17,14 +17,14 @@ import it.unibo.tuprolog.bdd.BinaryDecisionDiagramBuilder.Companion.defaultOf * to the same node * */ internal class ReducedBinaryDecisionDiagramBuilder>( - private val delegate: BinaryDecisionDiagramBuilder + private val delegate: BinaryDecisionDiagramBuilder, ) : BinaryDecisionDiagramBuilder { private val table: MutableMap> = mutableMapOf() override fun buildVariable( value: T, low: BinaryDecisionDiagram, - high: BinaryDecisionDiagram + high: BinaryDecisionDiagram, ): BinaryDecisionDiagram { if (low == high) { return low diff --git a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/builder/SimpleBinaryDecisionDiagramBuilder.kt b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/builder/SimpleBinaryDecisionDiagramBuilder.kt index bc2abc029..6a655b674 100644 --- a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/builder/SimpleBinaryDecisionDiagramBuilder.kt +++ b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/builder/SimpleBinaryDecisionDiagramBuilder.kt @@ -16,18 +16,18 @@ internal class SimpleBinaryDecisionDiagramBuilder> : override fun buildVariable( value: T, low: BinaryDecisionDiagram, - high: BinaryDecisionDiagram + high: BinaryDecisionDiagram, ): BinaryDecisionDiagram { return SimpleBinaryDecisionDiagramVariable( value, low, - high + high, ) } override fun buildTerminal(truth: Boolean): BinaryDecisionDiagram { return SimpleBinaryDecisionDiagramTerminal( - truth + truth, ) } } diff --git a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/builder/SimpleBinaryDecisionDiagramTerminal.kt b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/builder/SimpleBinaryDecisionDiagramTerminal.kt index fde8d372f..52779e76a 100644 --- a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/builder/SimpleBinaryDecisionDiagramTerminal.kt +++ b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/builder/SimpleBinaryDecisionDiagramTerminal.kt @@ -6,9 +6,8 @@ import it.unibo.tuprolog.bdd.BinaryDecisionDiagram * @author Jason Dellaluce */ internal data class SimpleBinaryDecisionDiagramTerminal>( - override val truth: Boolean + override val truth: Boolean, ) : BinaryDecisionDiagram.Terminal { - override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || this::class != other::class) return false diff --git a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/builder/SimpleBinaryDecisionDiagramVariable.kt b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/builder/SimpleBinaryDecisionDiagramVariable.kt index 5ebd4ee37..a2ea99be3 100644 --- a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/builder/SimpleBinaryDecisionDiagramVariable.kt +++ b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/builder/SimpleBinaryDecisionDiagramVariable.kt @@ -8,9 +8,8 @@ import it.unibo.tuprolog.bdd.BinaryDecisionDiagram internal data class SimpleBinaryDecisionDiagramVariable>( override val value: T, override val low: BinaryDecisionDiagram, - override val high: BinaryDecisionDiagram + override val high: BinaryDecisionDiagram, ) : BinaryDecisionDiagram.Variable { - private val hashCodeCache: Int by lazy { var result = value.hashCode() result = 31 * result + low.hashCode() diff --git a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/utils/CastVisitor.kt b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/utils/CastVisitor.kt index 2957173e5..fa7fb1604 100644 --- a/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/utils/CastVisitor.kt +++ b/bdd/src/commonMain/kotlin/it/unibo/tuprolog/bdd/impl/utils/CastVisitor.kt @@ -23,11 +23,7 @@ internal class CastVisitor, E> : var onTerminal: ((o: BinaryDecisionDiagram.Terminal) -> E)? = null var onVariable: ((o: BinaryDecisionDiagram.Variable) -> E)? = null - override fun visit( - node: BinaryDecisionDiagram.Terminal - ): E = onTerminal!!(node) + override fun visit(node: BinaryDecisionDiagram.Terminal): E = onTerminal!!(node) - override fun visit( - node: BinaryDecisionDiagram.Variable - ): E = onVariable!!(node) + override fun visit(node: BinaryDecisionDiagram.Variable): E = onVariable!!(node) } diff --git a/bdd/src/commonTest/kotlin/it/unibo/tuprolog/bdd/TestBinaryDecisionDiagram.kt b/bdd/src/commonTest/kotlin/it/unibo/tuprolog/bdd/TestBinaryDecisionDiagram.kt index 72cc6e29b..5cfc63426 100644 --- a/bdd/src/commonTest/kotlin/it/unibo/tuprolog/bdd/TestBinaryDecisionDiagram.kt +++ b/bdd/src/commonTest/kotlin/it/unibo/tuprolog/bdd/TestBinaryDecisionDiagram.kt @@ -48,12 +48,13 @@ class TestBinaryDecisionDiagram { * Probabilities to base-level "someHeads" predicates have been added to simulate "Probabilistic Clauses". */ @Test fun testApplyWithProbSomeHeads() { - val solution = ( - bddOf(ComparablePair(0, "someHeads", 0.2)) and - bddOf(ComparablePair(1, "heads1", 0.5)) + val solution = + ( + bddOf(ComparablePair(0, "someHeads", 0.2)) and + bddOf(ComparablePair(1, "heads1", 0.5)) ) or ( - bddOf(ComparablePair(2, "someHeads", 0.5)) and - bddOf(ComparablePair(3, "heads2", 0.6)) + bddOf(ComparablePair(2, "someHeads", 0.5)) and + bddOf(ComparablePair(3, "heads2", 0.6)) ) val prob = solution.probability() assertTrue(prob >= 0.37 - doubleEpsilon) @@ -66,15 +67,16 @@ class TestBinaryDecisionDiagram { fun testApplyWithProbAlarmNegationsNoEvidence() { val burglary = bddOf(ComparablePair(0, "burglary", 0.7)) val earthquake = bddOf(ComparablePair(1, "earthquake", 0.2)) - val solution = ( - bddOf(ComparablePair(2, "alarm", 0.9)) - and burglary and earthquake + val solution = + ( + bddOf(ComparablePair(2, "alarm", 0.9)) + and burglary and earthquake ) or ( - bddOf(ComparablePair(3, "alarm", 0.8)) - and burglary and earthquake.not() + bddOf(ComparablePair(3, "alarm", 0.8)) + and burglary and earthquake.not() ) or ( - bddOf(ComparablePair(4, "alarm", 0.1)) - and burglary.not() and earthquake + bddOf(ComparablePair(4, "alarm", 0.1)) + and burglary.not() and earthquake ) val prob = solution.probability() assertTrue(prob >= 0.58 - doubleEpsilon) diff --git a/build.gradle.kts b/build.gradle.kts index 529cbac00..7a14761c8 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,7 +1,6 @@ import io.github.gciatto.kt.mpp.Plugins -import io.github.gciatto.kt.mpp.ProjectType -import io.github.gciatto.kt.mpp.log -import io.github.gciatto.kt.mpp.nodeVersion +import io.github.gciatto.kt.mpp.helpers.ProjectType +import io.github.gciatto.kt.mpp.utils.log @Suppress("DSL_SCOPE_VIOLATION") plugins { @@ -19,37 +18,42 @@ gitSemVer { log("version: $version", LogLevel.LIFECYCLE) multiProjectHelper { - defaultProjectType = ProjectType.KOTLIN // default project type for all projects which are not explicitly marked + defaultProjectType = ProjectType.KOTLIN - jvmProjects(":examples", ":ide", ":ide-plp", ":parser-jvm") // marks projects as JVM-only - jsProjects(":parser-js") // marks projects as JS-only - otherProjects(":documentation") // marks projects as non-Kotlin related + jvmProjects(":examples", ":ide", ":ide-plp", ":parser-jvm") + jsProjects(":parser-js") + otherProjects(":documentation") - val baseProjectTemplate = buildSet { - add(Plugins.documentation) - add(Plugins.linter) - add(Plugins.bugFinder) - add(Plugins.versions) - } + val baseProjectTemplate = + buildSet { + add(Plugins.documentation) + add(Plugins.linter) + add(Plugins.bugFinder) + add(Plugins.versions) + } - ktProjectTemplate = buildSet { - addAll(baseProjectTemplate) - add(Plugins.multiplatform) - } + ktProjectTemplate = + buildSet { + addAll(baseProjectTemplate) + add(Plugins.multiplatform) + } - jvmProjectTemplate = buildSet { - addAll(baseProjectTemplate) - add(Plugins.jvmOnly) - } + jvmProjectTemplate = + buildSet { + addAll(baseProjectTemplate) + add(Plugins.jvmOnly) + } - jsProjectTemplate = buildSet { - addAll(baseProjectTemplate) - add(Plugins.jsOnly) - } + jsProjectTemplate = + buildSet { + addAll(baseProjectTemplate) + add(Plugins.jsOnly) + } - otherProjectTemplate = buildSet { - add(Plugins.versions) - } + otherProjectTemplate = + buildSet { + add(Plugins.versions) + } applyProjectTemplates() } @@ -60,14 +64,3 @@ allprojects { mavenCentral() } } - -project.findProperty("nodeVersion")?.let { it.toString() }?.takeIf { it.isNotBlank() }?.let { - nodeVersion(it) - log("override NodeJS version: $it", LogLevel.LIFECYCLE) -} - -afterEvaluate { - subprojects { - version = rootProject.version - } -} diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts deleted file mode 100644 index 230f185fd..000000000 --- a/buildSrc/build.gradle.kts +++ /dev/null @@ -1,28 +0,0 @@ -plugins { - `kotlin-dsl` - alias(libs.plugins.kotlin.jvm) -} - -repositories { - mavenCentral() - gradlePluginPortal() -} - -dependencies { - implementation(libs.shadowJar) - implementation(libs.kotlin.gradlePlugin) -} - -val targetJvm = libs.versions.jvm.get() -val targetJava = JavaVersion.valueOf("VERSION_$targetJvm") - -tasks.withType { - kotlinOptions { - jvmTarget = targetJvm - } -} - -java { - sourceCompatibility = targetJava - targetCompatibility = targetJava -} diff --git a/buildSrc/gradle.properties b/buildSrc/gradle.properties deleted file mode 100644 index 2eeeab7d4..000000000 --- a/buildSrc/gradle.properties +++ /dev/null @@ -1,2 +0,0 @@ -kotlin.mpp.stability.nowarn=true -kotlin.options.suppressFreeCompilerArgsModificationWarning=true diff --git a/buildSrc/settings.gradle.kts b/buildSrc/settings.gradle.kts deleted file mode 100644 index b5a0fabf6..000000000 --- a/buildSrc/settings.gradle.kts +++ /dev/null @@ -1,7 +0,0 @@ -dependencyResolutionManagement { - versionCatalogs { - create("libs") { - from(files("../gradle/libs.versions.toml")) - } - } -} diff --git a/buildSrc/src/main/kotlin/ShadowUtils.kt b/buildSrc/src/main/kotlin/ShadowUtils.kt deleted file mode 100644 index 2ea2bc022..000000000 --- a/buildSrc/src/main/kotlin/ShadowUtils.kt +++ /dev/null @@ -1,99 +0,0 @@ -import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar -import org.gradle.api.Project -import org.gradle.api.file.FileCollection -import org.gradle.api.file.FileSystemLocation -import org.gradle.api.file.FileTree -import org.gradle.api.tasks.SourceSetContainer -import org.gradle.configurationcache.extensions.capitalized -import org.gradle.kotlin.dsl.attributes -import org.gradle.kotlin.dsl.extra -import org.gradle.kotlin.dsl.provideDelegate -import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension -import java.io.File - -fun String.toPascalCase(separators: Set = setOf('_', '-')) = - split(*separators.toCharArray()).joinToString("") { - it.capitalized() - } - -private val Project.supportedPlatforms: List - get() { - val supportedPlatforms: List? by extra - return supportedPlatforms ?: emptyList() - } - -fun Project.shadowJar( - entryPoint: String? = null, - platform: String? = null, - name: String = "shadowJar" + (platform?.let { "For${it.toPascalCase()}" } ?: ""), - classifier: String = "redist", - excludedPlatforms: List = platform?.let { supportedPlatforms - it } ?: emptyList() -): ShadowJar { - fun setOfFileSystemLocationsToFileTree(locations: Set): FileTree = - locations.map { it.asFile }.map { if (it.isDirectory) fileTree(it) else zipTree(it) }.reduce(FileTree::plus) - fun fileShouldBeIncluded(file: File): Boolean = excludedPlatforms.none { file.name.endsWith("$it.jar") } - return tasks.maybeCreate(name, ShadowJar::class.java).also { jarTask -> - entryPoint?.let { jarTask.manifest { attributes("Main-Class" to it) } } - jarTask.archiveBaseName.set(project.provider { "${rootProject.name}-${project.name}" }) - jarTask.archiveVersion.set(project.provider { project.version.toString() }) - if (platform !== null) { - jarTask.archiveClassifier.set("$classifier-$platform") - } else { - jarTask.archiveClassifier.set(classifier) - } - configureJarForProject(jarTask, ::fileShouldBeIncluded, ::setOfFileSystemLocationsToFileTree) - jarTask.from(files("${rootProject.projectDir}/LICENSE")) - tasks.maybeCreate("allShadowJars").also { - it.dependsOn(jarTask) - it.group = "shadow" - } - } -} - -private fun Project.configureJarFromFileCollection( - jarTask: ShadowJar, - fileCollection: FileCollection, - shouldBeIncluded: (File) -> Boolean, - toFileTree: (Set) -> FileTree, -) = fileCollection.filter { it.exists() }.filter(shouldBeIncluded).elements.map(toFileTree).let { jarTask.from(it) } - -private fun Project.configureJarForJvmProject( - jarTask: ShadowJar, - shouldBeIncluded: (File) -> Boolean, - toFileTree: (Set) -> FileTree -) { - plugins.withId("org.jetbrains.kotlin.jvm") { - project.extensions.configure("sourceSets") { - getByName("main") { - configureJarFromFileCollection(jarTask, runtimeClasspath, shouldBeIncluded, toFileTree) - } - } - jarTask.dependsOn("classes") - } -} - -private fun Project.configureJarForMpProject( - jarTask: ShadowJar, - shouldBeIncluded: (File) -> Boolean, - toFileTree: (Set) -> FileTree -) { - plugins.withId("org.jetbrains.kotlin.multiplatform") { - project.extensions.configure(KotlinMultiplatformExtension::class.java) { - jvm().compilations.getByName("main").run { - for (collection in listOf(output.allOutputs, runtimeDependencyFiles)) { - configureJarFromFileCollection(jarTask, collection, shouldBeIncluded, toFileTree) - } - } - } - jarTask.dependsOn("jvmMainClasses") - } -} - -private fun Project.configureJarForProject( - jarTask: ShadowJar, - shouldBeIncluded: (File) -> Boolean, - toFileTree: (Set) -> FileTree -) { - configureJarForMpProject(jarTask, shouldBeIncluded, toFileTree) - configureJarForJvmProject(jarTask, shouldBeIncluded, toFileTree) -} diff --git a/core/build.gradle.kts b/core/build.gradle.kts index 0a004ac6a..9f1b1d24a 100644 --- a/core/build.gradle.kts +++ b/core/build.gradle.kts @@ -15,7 +15,8 @@ val tuPrologPackageDir: String get() = tuPrologPackage.replace('.', File.separatorChar) val infoKtFileContent: String - get() = """|package $tuPrologPackage + get() = + """|package $tuPrologPackage | |object Info { | const val VERSION = "$version" @@ -23,7 +24,7 @@ val infoKtFileContent: String | val OS: Os by lazy { currentOs() } |} | - """.trimMargin() + """.trimMargin() kotlin { sourceSets { diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/Os.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/Os.kt index ed875b07d..76bbce433 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/Os.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/Os.kt @@ -5,17 +5,19 @@ enum class Os(val isPosix: Boolean) { LINUX(true), MAC(true), ANDROID(true), - UNKNOWN_POSIX(true); + UNKNOWN_POSIX(true), + ; companion object { - fun detect(description: String): Os? = when { - description.contains("android", ignoreCase = true) -> ANDROID - description.contains("dalvik", ignoreCase = true) -> ANDROID - description.contains("win", ignoreCase = true) -> WINDOWS - description.contains("mac", ignoreCase = true) -> MAC - description.contains("mac", ignoreCase = true) -> MAC - description.contains("linux", ignoreCase = true) -> LINUX - else -> null - } + fun detect(description: String): Os? = + when { + description.contains("android", ignoreCase = true) -> ANDROID + description.contains("dalvik", ignoreCase = true) -> ANDROID + description.contains("win", ignoreCase = true) -> WINDOWS + description.contains("mac", ignoreCase = true) -> MAC + description.contains("mac", ignoreCase = true) -> MAC + description.contains("linux", ignoreCase = true) -> LINUX + else -> null + } } } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/Platform.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/Platform.kt index f45f0e021..66f2012c6 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/Platform.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/Platform.kt @@ -4,5 +4,5 @@ enum class Platform(val isJava: Boolean, val isJavaScript: Boolean) { JVM(true, false), ANDROID(true, false), NODE(false, true), - BROWSER(false, true) + BROWSER(false, true), } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Applicable.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Applicable.kt index d65969748..386aedfd3 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Applicable.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Applicable.kt @@ -64,8 +64,10 @@ interface Applicable> { * @see Substitution.of */ @JsName("apply") - fun apply(substitution: Substitution, vararg substitutions: Substitution): T = - apply(Substitution.of(substitution, *substitutions)) + fun apply( + substitution: Substitution, + vararg substitutions: Substitution, + ): T = apply(Substitution.of(substitution, *substitutions)) /** * This is an alias for [apply] aimed at supporting a square-brackets syntax for substitutions applications in @@ -86,6 +88,8 @@ interface Applicable> { * @see Substitution.of */ @JsName("getSubstituted") - operator fun get(substitution: Substitution, vararg substitutions: Substitution): T = - apply(substitution, *substitutions) + operator fun get( + substitution: Substitution, + vararg substitutions: Substitution, + ): T = apply(substitution, *substitutions) } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Atom.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Atom.kt index be440723b..67844e7da 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Atom.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Atom.kt @@ -17,7 +17,6 @@ import kotlin.collections.List as KtList * to [value]. */ interface Atom : Struct, Constant { - override val arity: Int get() = 0 @@ -52,16 +51,13 @@ interface Atom : Struct, Constant { override fun asAtom(): Atom = this companion object { - @JvmStatic @JsName("escapeValue") - fun escapeValue(string: String): String = - Struct.enquoteFunctor(string) + fun escapeValue(string: String): String = Struct.enquoteFunctor(string) @JvmStatic @JsName("escapeValueIfNecessary") - fun escapeValueIfNecessary(string: String): String = - Struct.enquoteFunctorIfNecessary(string) + fun escapeValueIfNecessary(string: String): String = Struct.enquoteFunctorIfNecessary(string) @JvmField val ATOM_PATTERN = Terms.ATOM_PATTERN diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Block.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Block.kt index ef93da31f..f2d14000b 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Block.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Block.kt @@ -6,7 +6,6 @@ import kotlin.jvm.JvmStatic import kotlin.collections.List as KtList interface Block : Recursive { - override val isBlock: Boolean get() = true @@ -29,7 +28,6 @@ interface Block : Recursive { override fun asBlock(): Block = this companion object { - const val FUNCTOR = Terms.BLOCK_FUNCTOR const val EMPTY_FUNCTOR = Terms.EMPTY_BLOCK_FUNCTOR diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/BlockIterator.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/BlockIterator.kt index 9d1efa9e5..e0797f1ad 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/BlockIterator.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/BlockIterator.kt @@ -1,7 +1,6 @@ package it.unibo.tuprolog.core class BlockIterator(block: Block) : Iterator { - private open inner class BlockIteratorVisitor : TermVisitor { override fun visitTuple(term: Tuple): Term { current = term.right @@ -20,13 +19,12 @@ class BlockIterator(block: Block) : Iterator { private val innerBlockIteratorVisitor = BlockIteratorVisitor() - private val outerBlockIteratorVisitor = object : BlockIteratorVisitor() { - override fun visitBlock(term: Block): Term = - term[0].accept(innerBlockIteratorVisitor) + private val outerBlockIteratorVisitor = + object : BlockIteratorVisitor() { + override fun visitBlock(term: Block): Term = term[0].accept(innerBlockIteratorVisitor) - override fun visitEmptyBlock(term: EmptyBlock): Term = - throw throw NoSuchElementException() - } + override fun visitEmptyBlock(term: EmptyBlock): Term = throw throw NoSuchElementException() + } override fun next(): Term = current?.accept(outerBlockIteratorVisitor) ?: throw NoSuchElementException() } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Clause.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Clause.kt index e2ea64e36..832dcb656 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Clause.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Clause.kt @@ -5,7 +5,6 @@ import kotlin.js.JsName import kotlin.jvm.JvmStatic interface Clause : Struct { - override val functor: String get() = CLAUSE_FUNCTOR @@ -77,7 +76,10 @@ interface Clause : Struct { fun setHeadArgs(arguments: Sequence): Clause @JsName("insertHeadArg") - fun insertHeadArg(index: Int, argument: Term): Clause + fun insertHeadArg( + index: Int, + argument: Term, + ): Clause @JsName("addFirstHeadArg") fun addFirstHeadArg(argument: Term): Clause @@ -89,7 +91,10 @@ interface Clause : Struct { fun appendHeadArg(argument: Term): Clause @JsName("setBodyItems") - fun setBodyItems(argument: Term, vararg arguments: Term): Clause + fun setBodyItems( + argument: Term, + vararg arguments: Term, + ): Clause @JsName("setBodyItemsIterable") fun setBodyItems(arguments: Iterable): Clause @@ -98,7 +103,10 @@ interface Clause : Struct { fun setBodyItems(arguments: Sequence): Clause @JsName("insertBodyItem") - fun insertBodyItem(index: Int, argument: Term): Clause + fun insertBodyItem( + index: Int, + argument: Term, + ): Clause @JsName("addFirstBodyItem") fun addFirstBodyItem(argument: Term): Clause @@ -110,16 +118,21 @@ interface Clause : Struct { fun appendBodyItem(argument: Term): Clause companion object { - const val FUNCTOR = CLAUSE_FUNCTOR @JvmStatic @JsName("of") - fun of(head: Struct? = null, vararg body: Term): Clause = of(head, body.asIterable()) + fun of( + head: Struct? = null, + vararg body: Term, + ): Clause = of(head, body.asIterable()) @JvmStatic @JsName("ofIterable") - fun of(head: Struct? = null, body: Iterable): Clause = + fun of( + head: Struct? = null, + body: Iterable, + ): Clause = when (head) { null -> { require(body.any()) { "If Clause head is null, at least one body element, is required" } @@ -130,7 +143,10 @@ interface Clause : Struct { @JvmStatic @JsName("ofSequence") - fun of(head: Struct? = null, body: Sequence): Clause = of(head, body.asIterable()) + fun of( + head: Struct? = null, + body: Sequence, + ): Clause = of(head, body.asIterable()) /** Contains notable functor in determining if a Clause [isWellFormed] */ @JvmStatic @@ -140,38 +156,41 @@ interface Clause : Struct { /** A visitor that checks whether [isWellFormed] (body constraints part) is respected */ @JvmStatic @JsName("bodyWellFormedVisitor") - val bodyWellFormedVisitor: TermVisitor = object : TermVisitor { - - override fun defaultValue(term: Term): Boolean = true - - override fun visitNumeric(term: Numeric): Boolean = false - - override fun visitStruct(term: Struct): Boolean = when { - term.functor in notableFunctors && term.arity == 2 -> - term.argsSequence - .map { arg -> arg.accept(this) } - .reduce(Boolean::and) - else -> true + val bodyWellFormedVisitor: TermVisitor = + object : TermVisitor { + override fun defaultValue(term: Term): Boolean = true + + override fun visitNumeric(term: Numeric): Boolean = false + + override fun visitStruct(term: Struct): Boolean = + when { + term.functor in notableFunctors && term.arity == 2 -> + term.argsSequence + .map { arg -> arg.accept(this) } + .reduce(Boolean::and) + else -> true + } } - } // TODO: 16/01/2020 test this method internal fun preparationForExecutionVisitor(unifier: Substitution.Unifier = Substitution.empty()) = object : TermVisitor { override fun defaultValue(term: Term) = term - override fun visitStruct(term: Struct): Term = when { - term.functor in notableFunctors && term.arity == 2 -> - Struct.of(term.functor, term.argsSequence.map { arg -> arg.accept(this) }) - else -> term - } + override fun visitStruct(term: Struct): Term = + when { + term.functor in notableFunctors && term.arity == 2 -> + Struct.of(term.functor, term.argsSequence.map { arg -> arg.accept(this) }) + else -> term + } override fun visitClause(term: Clause): Term = of(term.head, term.body.accept(this)) - override fun visitVar(term: Var): Term = when (term) { - in unifier -> unifier[term]!!.accept(this) - else -> Struct.of("call", term) - } + override fun visitVar(term: Var): Term = + when (term) { + in unifier -> unifier[term]!!.accept(this) + else -> Struct.of("call", term) + } } /** diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/ClauseExtensions.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/ClauseExtensions.kt index fcf8bb7ab..70e99da65 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/ClauseExtensions.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/ClauseExtensions.kt @@ -12,8 +12,7 @@ import kotlin.jvm.JvmName * as the Term: `product(A) :- call(A), call(A)` */ @JsName("prepareForExecution") -fun Clause.prepareForExecution(): Clause = - accept(Clause.defaultPreparationForExecutionVisitor).castToClause() +fun Clause.prepareForExecution(): Clause = accept(Clause.defaultPreparationForExecutionVisitor).castToClause() @JsName("prepareForExecutionWithUnifier") fun Clause.prepareForExecution(unifier: Substitution.Unifier): Clause = diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/ComparisonUtils.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/ComparisonUtils.kt index 178697caf..3316f98cf 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/ComparisonUtils.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/ComparisonUtils.kt @@ -4,4 +4,7 @@ package it.unibo.tuprolog.core import kotlin.jvm.JvmName -expect fun compareStringsLocaleIndependently(string1: String, string2: String): Int +expect fun compareStringsLocaleIndependently( + string1: String, + string2: String, +): Int diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Cons.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Cons.kt index 55a001347..3e9c901a9 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Cons.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Cons.kt @@ -7,7 +7,6 @@ import kotlin.jvm.JvmStatic import it.unibo.tuprolog.core.List as LogicList interface Cons : LogicList { - override val isCons: Boolean get() = true @@ -33,12 +32,14 @@ interface Cons : LogicList { override fun asCons(): Cons = this companion object { - const val FUNCTOR = CONS_FUNCTOR @JvmStatic @JsName("of") - fun of(head: Term, tail: Term): Cons = ConsImpl(head, tail) + fun of( + head: Term, + tail: Term, + ): Cons = ConsImpl(head, tail) @JvmStatic @JsName("singleton") diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Constant.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Constant.kt index 4f7a42336..dc3b2ebda 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Constant.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Constant.kt @@ -3,7 +3,6 @@ package it.unibo.tuprolog.core import kotlin.js.JsName interface Constant : Term { - override val isConstant: Boolean get() = true @JsName("value") diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Conversions.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Conversions.kt index e9be01fff..810f39225 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Conversions.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Conversions.kt @@ -62,5 +62,4 @@ fun Array.toTerm(): List = List.of(*this) /** Conversion from a raw `Map` to the [Substitution.Unifier] type */ @JsName("asUnifier") -fun Map.asUnifier(): Substitution.Unifier = - this as? Substitution.Unifier ?: Substitution.of(this) +fun Map.asUnifier(): Substitution.Unifier = this as? Substitution.Unifier ?: Substitution.of(this) diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Directive.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Directive.kt index c196da7a4..b4bb89c5a 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Directive.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Directive.kt @@ -5,7 +5,6 @@ import kotlin.js.JsName import kotlin.jvm.JvmStatic interface Directive : Clause { - override val head: Struct? get() = null @@ -38,8 +37,10 @@ interface Directive : Clause { @JvmStatic @JsName("of") - fun of(body1: Term, vararg body: Term): Directive = - of(listOf(body1, *body)) + fun of( + body1: Term, + vararg body: Term, + ): Directive = of(listOf(body1, *body)) @JvmStatic @JsName("template") diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Empty.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Empty.kt index c41a7c47e..13629f1d1 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Empty.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Empty.kt @@ -4,13 +4,11 @@ import kotlin.js.JsName import kotlin.jvm.JvmStatic interface Empty : Atom { - override fun freshCopy(): Empty override fun freshCopy(scope: Scope): Empty companion object { - const val EMPTY_LIST_FUNCTOR = Terms.EMPTY_LIST_FUNCTOR const val EMPTY_BLOCK_FUNCTOR = Terms.EMPTY_BLOCK_FUNCTOR diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/EmptyBlock.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/EmptyBlock.kt index bd7d1c19a..6425b0049 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/EmptyBlock.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/EmptyBlock.kt @@ -5,7 +5,6 @@ import kotlin.js.JsName import kotlin.jvm.JvmStatic interface EmptyBlock : Empty, Block { - override val isEmptyBlock: Boolean get() = true diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/EmptyList.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/EmptyList.kt index ce001d0c3..c8c608bdb 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/EmptyList.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/EmptyList.kt @@ -6,7 +6,6 @@ import kotlin.jvm.JvmStatic import it.unibo.tuprolog.core.List as LogicList interface EmptyList : Empty, LogicList { - override val isCons: Boolean get() = false @@ -32,7 +31,6 @@ interface EmptyList : Empty, LogicList { override fun asEmptyList(): EmptyList = this companion object { - const val FUNCTOR: String = Terms.EMPTY_LIST_FUNCTOR @JvmStatic diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Fact.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Fact.kt index be4d30b0a..f05c9b982 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Fact.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Fact.kt @@ -5,7 +5,6 @@ import kotlin.js.JsName import kotlin.jvm.JvmStatic interface Fact : Rule { - override val body: Term get() = Truth.TRUE @@ -26,7 +25,10 @@ interface Fact : Rule { override fun setHeadArgs(arguments: Sequence): Fact - override fun insertHeadArg(index: Int, argument: Term): Fact + override fun insertHeadArg( + index: Int, + argument: Term, + ): Fact override fun addFirstHeadArg(argument: Term): Fact @@ -35,7 +37,6 @@ interface Fact : Rule { override fun appendHeadArg(argument: Term): Fact companion object { - const val FUNCTOR = Terms.CLAUSE_FUNCTOR @JvmStatic @@ -44,7 +45,10 @@ interface Fact : Rule { @JvmStatic @JsName("template") - fun template(functor: String, arity: Int): Fact { + fun template( + functor: String, + arity: Int, + ): Fact { return of(Struct.template(functor, arity)) } } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Indicator.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Indicator.kt index 3cf99d311..6e00b0a12 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Indicator.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Indicator.kt @@ -16,7 +16,6 @@ import kotlin.jvm.JvmStatic * @author Enrico */ interface Indicator : Struct { - override val isIndicator: Boolean get() = true @@ -66,18 +65,23 @@ interface Indicator : Struct { operator fun component2(): Term = arityTerm companion object { - /** The canonical indicator functor: `/` */ const val FUNCTOR = INDICATOR_FUNCTOR /** Creates an indicator denoting functor named [name] with [arity] */ @JvmStatic @JsName("of") - fun of(name: Term, arity: Term): Indicator = IndicatorImpl(name, arity) + fun of( + name: Term, + arity: Term, + ): Indicator = IndicatorImpl(name, arity) /** Creates an indicator denoting functor named [name] with [arity] */ @JvmStatic @JsName("ofString") - fun of(name: String, arity: Int): Indicator = of(Atom.of(name), Integer.of(arity)) + fun of( + name: String, + arity: Int, + ): Indicator = of(Atom.of(name), Integer.of(arity)) } } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Integer.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Integer.kt index 6d29b0e27..61236e4e1 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Integer.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Integer.kt @@ -8,7 +8,6 @@ import kotlin.jvm.JvmField import kotlin.jvm.JvmStatic interface Integer : Numeric { - override val isInteger: Boolean get() = true @@ -27,7 +26,6 @@ interface Integer : Numeric { override fun asInteger(): Integer = this companion object { - @JvmField val PATTERN = Terms.INTEGER_PATTERN @@ -57,7 +55,10 @@ interface Integer : Numeric { @JvmStatic @JsName("parseRadix") - fun of(integer: String, radix: Int): Integer = of(BigInteger.of(integer, radix)) + fun of( + integer: String, + radix: Int, + ): Integer = of(BigInteger.of(integer, radix)) @JvmField val ZERO = Integer.of(BigInteger.ZERO) diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/List.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/List.kt index 169f45ded..a7bcd9abe 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/List.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/List.kt @@ -9,7 +9,6 @@ import kotlin.jvm.JvmStatic import kotlin.collections.List as KtList interface List : Recursive { - override val isList: Boolean get() = true @@ -36,13 +35,14 @@ interface List : Recursive { override val unfoldedArray: Array override val size: Int - get() = unfoldedSequence.count().let { - if (isWellFormed) { - it - 1 - } else { - it + get() = + unfoldedSequence.count().let { + if (isWellFormed) { + it - 1 + } else { + it + } } - } override fun freshCopy(): List @@ -51,7 +51,6 @@ interface List : Recursive { override fun asList(): List = this companion object { - const val CONS_FUNCTOR = Terms.CONS_FUNCTOR const val EMPTY_LIST_FUNCTOR = Terms.EMPTY_LIST_FUNCTOR @@ -82,17 +81,21 @@ interface List : Recursive { @JvmStatic @JsName("from") - fun from(vararg items: Term, last: Term?): List = - from(items.toList(), last) + fun from( + vararg items: Term, + last: Term?, + ): List = from(items.toList(), last) @JvmStatic @JsName("fromNullTerminated") - fun from(vararg items: Term): List = - from(items.cursor(), null) + fun from(vararg items: Term): List = from(items.cursor(), null) @JvmStatic @JsName("fromIterable") - fun from(items: Iterable, last: Term?): List = + fun from( + items: Iterable, + last: Term?, + ): List = when (items) { is KtList -> from(items, last) else -> from(items.cursor(), last) @@ -100,33 +103,39 @@ interface List : Recursive { @JvmStatic @JsName("fromIterableNullTerminated") - fun from(items: Iterable): List = - from(items, null) + fun from(items: Iterable): List = from(items, null) @JvmStatic @JsName("fromSequence") - fun from(items: Sequence, last: Term?): List = - from(items.cursor(), last) + fun from( + items: Sequence, + last: Term?, + ): List = from(items.cursor(), last) @JvmStatic @JsName("fromSequenceNullTerminated") - fun from(items: Sequence): List = - from(items.cursor(), null) + fun from(items: Sequence): List = from(items.cursor(), null) @JvmStatic @JsName("fromList") - fun from(items: KtList, last: Term?): List { + fun from( + items: KtList, + last: Term?, + ): List { if (items.isEmpty()) { return (last ?: empty()).asList() - ?: throw IllegalArgumentException("Cannot create a list out of the provided arguments: $items, $last") + ?: throw IllegalArgumentException( + "Cannot create a list out of the provided arguments: $items, $last", + ) } val i = items.asReversed().iterator() - var right = if (last == null) { - i.next() - items.last() - } else { - last - } + var right = + if (last == null) { + i.next() + items.last() + } else { + last + } while (i.hasNext()) { right = Cons.of(i.next(), right) } @@ -135,16 +144,20 @@ interface List : Recursive { @JvmStatic @JsName("fromListNullTerminated") - fun from(items: KtList): List = - from(items, null) + fun from(items: KtList): List = from(items, null) @JvmStatic @JsName("fromCursor") - fun from(items: Cursor, last: Term?): List { + fun from( + items: Cursor, + last: Term?, + ): List { return when { items.isOver -> (last ?: empty()).asList() - ?: throw IllegalArgumentException("Cannot create a list out of the provided arguments: $items, $last") + ?: throw IllegalArgumentException( + "Cannot create a list out of the provided arguments: $items, $last", + ) last == null -> LazyConsWithImplicitLast(items) else -> LazyConsWithExplicitLast(items, last) } @@ -152,7 +165,6 @@ interface List : Recursive { @JvmStatic @JsName("fromCursorNullTerminated") - fun from(items: Cursor): List = - from(items, null) + fun from(items: Cursor): List = from(items, null) } } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/ListIterator.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/ListIterator.kt index 114a889dc..dd8d1cdd4 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/ListIterator.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/ListIterator.kt @@ -1,26 +1,26 @@ package it.unibo.tuprolog.core sealed class ListIterator(list: List) : Iterator { - protected open var current: Term? = list override fun hasNext(): Boolean = current != null - private val listIteratorVisitor = object : TermVisitor { - override fun visitCons(term: Cons): Term { - current = term.tail - return term.head - } + private val listIteratorVisitor = + object : TermVisitor { + override fun visitCons(term: Cons): Term { + current = term.tail + return term.head + } - override fun visitEmptyList(term: EmptyList): Term { - return onEmptyList(term) - } + override fun visitEmptyList(term: EmptyList): Term { + return onEmptyList(term) + } - override fun defaultValue(term: Term): Term { - current = null - return term + override fun defaultValue(term: Term): Term { + current = null + return term + } } - } override fun next(): Term = current?.accept(listIteratorVisitor) ?: throw NoSuchElementException() @@ -40,12 +40,14 @@ sealed class ListIterator(list: List) : Iterator { class SkippingLast(list: List, unifier: Substitution.Unifier) : Substituting(list, unifier) { override fun hasNext(): Boolean = hasNextSkippingLast() + override fun onEmptyList(item: EmptyList): Term = onEmptyListSkippingLast(item) } } class SkippingLast(list: List) : ListIterator(list) { override fun hasNext(): Boolean = hasNextSkippingLast() + override fun onEmptyList(item: EmptyList): Term = onEmptyListSkippingLast(item) } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Numeric.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Numeric.kt index daecca09d..98843aed1 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Numeric.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Numeric.kt @@ -7,7 +7,6 @@ import kotlin.jvm.JvmField import kotlin.jvm.JvmStatic interface Numeric : Constant { - override val isNumber: Boolean get() = true @@ -30,7 +29,6 @@ interface Numeric : Constant { override fun asNumeric(): Numeric = this companion object { - @JvmField val INTEGER_PATTERN = Terms.INTEGER_PATTERN @@ -71,16 +69,17 @@ interface Numeric : Constant { @JvmStatic @JsName("of") - fun of(value: Number): Numeric = when (value) { - // avoiding string format is necessary for "floats", to maintain full precision during conversions - is Double -> of(value) - is Int -> of(value) - is Float -> of(value) - is Long -> of(value) - is Short -> of(value) - is Byte -> of(value) - else -> of(value.toString()) - } + fun of(value: Number): Numeric = + when (value) { + // avoiding string format is necessary for "floats", to maintain full precision during conversions + is Double -> of(value) + is Int -> of(value) + is Float -> of(value) + is Long -> of(value) + is Short -> of(value) + is Byte -> of(value) + else -> of(value.toString()) + } @JvmStatic @JsName("parse") diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Real.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Real.kt index 99769c419..e9111922d 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Real.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Real.kt @@ -8,7 +8,6 @@ import kotlin.jvm.JvmField import kotlin.jvm.JvmStatic interface Real : Numeric { - override val isReal: Boolean get() = true @@ -27,7 +26,6 @@ interface Real : Numeric { override fun asReal(): Real = this companion object { - @JvmField val PATTERN = Terms.REAL_PATTERN diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Recursive.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Recursive.kt index bc3e06a22..22742e0bf 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Recursive.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Recursive.kt @@ -4,7 +4,6 @@ import kotlin.collections.List import kotlin.js.JsName interface Recursive : Struct { - override val isRecursive: Boolean get() = true diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Rule.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Rule.kt index 3b4cf1e24..51c515a92 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Rule.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Rule.kt @@ -5,7 +5,6 @@ import kotlin.js.JsName import kotlin.jvm.JvmStatic interface Rule : Clause { - override val head: Struct override val isRule: Boolean @@ -42,7 +41,10 @@ interface Rule : Clause { override fun setHeadArgs(arguments: Sequence): Rule - override fun insertHeadArg(index: Int, argument: Term): Rule + override fun insertHeadArg( + index: Int, + argument: Term, + ): Rule override fun addFirstHeadArg(argument: Term): Rule @@ -50,13 +52,19 @@ interface Rule : Clause { override fun appendHeadArg(argument: Term): Rule - override fun setBodyItems(argument: Term, vararg arguments: Term): Rule + override fun setBodyItems( + argument: Term, + vararg arguments: Term, + ): Rule override fun setBodyItems(arguments: Iterable): Rule override fun setBodyItems(arguments: Sequence): Rule - override fun insertBodyItem(index: Int, argument: Term): Rule + override fun insertBodyItem( + index: Int, + argument: Term, + ): Rule override fun addFirstBodyItem(argument: Term): Rule @@ -65,16 +73,21 @@ interface Rule : Clause { override fun appendBodyItem(argument: Term): Rule companion object { - const val FUNCTOR = Terms.CLAUSE_FUNCTOR @JvmStatic @JsName("of") - fun of(head: Struct, vararg body: Term): Rule = of(head, body.asIterable()) + fun of( + head: Struct, + vararg body: Term, + ): Rule = of(head, body.asIterable()) @JvmStatic @JsName("ofIterable") - fun of(head: Struct, body: Iterable): Rule { + fun of( + head: Struct, + body: Iterable, + ): Rule { val i = body.iterator() if (!i.hasNext()) return Fact.of(head) val first = i.next() @@ -84,11 +97,17 @@ interface Rule : Clause { @JvmStatic @JsName("ofSequence") - fun of(head: Struct, body: Sequence): Rule = of(head, body.asIterable()) + fun of( + head: Struct, + body: Sequence, + ): Rule = of(head, body.asIterable()) @JvmStatic @JsName("template") - fun template(functor: String, arity: Int): Rule { + fun template( + functor: String, + arity: Int, + ): Rule { return of(Struct.template(functor, arity), Var.anonymous()) } } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Scope.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Scope.kt index a6dce776b..be57580ed 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Scope.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Scope.kt @@ -8,7 +8,6 @@ import kotlin.jvm.JvmStatic import it.unibo.tuprolog.core.List as LogicList interface Scope { - @JsName("variables") val variables: Map @@ -48,16 +47,28 @@ interface Scope { fun atomOf(value: String): Atom @JsName("structOf") - fun structOf(functor: String, vararg args: Term): Struct + fun structOf( + functor: String, + vararg args: Term, + ): Struct @JsName("structOfSequence") - fun structOf(functor: String, args: Sequence): Struct + fun structOf( + functor: String, + args: Sequence, + ): Struct @JsName("structOfIterable") - fun structOf(functor: String, args: Iterable): Struct + fun structOf( + functor: String, + args: Iterable, + ): Struct @JsName("structOfList") - fun structOf(functor: String, args: List): Struct + fun structOf( + functor: String, + args: List, + ): Struct @JsName("tupleOf") fun tupleOf(vararg terms: Term): Tuple @@ -75,7 +86,10 @@ interface Scope { fun ktListOf(vararg items: T): List @JsName("append") - fun List.append(item: T, vararg items: T): List + fun List.append( + item: T, + vararg items: T, + ): List @JsName("concat") fun List.concat(other: Iterable): List @@ -90,13 +104,22 @@ interface Scope { fun listOf(terms: Sequence): LogicList @JsName("listFrom") - fun listFrom(vararg terms: Term, last: Term? = null): LogicList + fun listFrom( + vararg terms: Term, + last: Term? = null, + ): LogicList @JsName("listFromIterable") - fun listFrom(terms: Iterable, last: Term? = null): LogicList + fun listFrom( + terms: Iterable, + last: Term? = null, + ): LogicList @JsName("listFromSequence") - fun listFrom(terms: Sequence, last: Term? = null): LogicList + fun listFrom( + terms: Sequence, + last: Term? = null, + ): LogicList @JsName("setOf") fun blockOf(vararg terms: Term): Block @@ -117,22 +140,41 @@ interface Scope { fun factOf(head: Struct): Fact @JsName("ruleOf") - fun ruleOf(head: Struct, body1: Term, vararg body: Term): Rule + fun ruleOf( + head: Struct, + body1: Term, + vararg body: Term, + ): Rule @JsName("directiveOf") - fun directiveOf(body1: Term, vararg body: Term): Directive + fun directiveOf( + body1: Term, + vararg body: Term, + ): Directive @JsName("clauseOf") - fun clauseOf(head: Struct?, vararg body: Term): Clause + fun clauseOf( + head: Struct?, + vararg body: Term, + ): Clause @JsName("consOf") - fun consOf(head: Term, tail: Term): Cons + fun consOf( + head: Term, + tail: Term, + ): Cons @JsName("indicatorOf") - fun indicatorOf(name: Term, arity: Term): Indicator + fun indicatorOf( + name: Term, + arity: Term, + ): Indicator @JsName("indicatorOfStringInt") - fun indicatorOf(name: String, arity: Int): Indicator + fun indicatorOf( + name: String, + arity: Int, + ): Indicator @JsName("anonymous") fun anonymous(): Var @@ -189,7 +231,10 @@ interface Scope { fun intOf(value: String): Integer @JsName("parseIntRadix") - fun intOf(value: String, radix: Int): Integer + fun intOf( + value: String, + radix: Int, + ): Integer @JsName("realOfBigDecimal") fun realOf(value: BigDecimal): Real @@ -225,7 +270,6 @@ interface Scope { fun substitutionOf(assignments: Sequence>): Substitution companion object { - @JvmStatic @JsName("empty") fun empty(): Scope = ScopeImpl(mutableMapOf()) @@ -236,7 +280,10 @@ interface Scope { @JvmStatic @JsName("ofVar") - fun of(`var`: Var, vararg vars: Var): Scope = of(listOf(`var`, *vars)) + fun of( + `var`: Var, + vararg vars: Var, + ): Scope = of(listOf(`var`, *vars)) @JvmStatic @JsName("ofVarIterable") @@ -256,22 +303,38 @@ interface Scope { @JvmStatic @JsName("ofWithFunction") - fun of(vararg vars: String, lambda: Scope.() -> R): R = of(*vars).with(lambda) + fun of( + vararg vars: String, + lambda: Scope.() -> R, + ): R = of(*vars).with(lambda) @JvmStatic @JsName("ofVarWithFunction") - fun of(`var`: Var, vararg vars: Var, lambda: Scope.() -> R): R = of(`var`, *vars).with(lambda) + fun of( + `var`: Var, + vararg vars: Var, + lambda: Scope.() -> R, + ): R = of(`var`, *vars).with(lambda) @JvmStatic @JsName("ofVarIterableWithFunction") - fun of(vars: Iterable, lambda: Scope.() -> R): R = of(vars).with(lambda) + fun of( + vars: Iterable, + lambda: Scope.() -> R, + ): R = of(vars).with(lambda) @JvmStatic @JsName("ofVarSequenceWithFunction") - fun of(vars: Sequence, lambda: Scope.() -> R): R = of(vars).with(lambda) + fun of( + vars: Sequence, + lambda: Scope.() -> R, + ): R = of(vars).with(lambda) @JvmStatic @JsName("ofVariabledWithFunction") - fun of(vars: Variabled, lambda: Scope.() -> R): R = of(vars).with(lambda) + fun of( + vars: Variabled, + lambda: Scope.() -> R, + ): R = of(vars).with(lambda) } } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Struct.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Struct.kt index 6bba4d69f..54e9a4974 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Struct.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Struct.kt @@ -21,16 +21,17 @@ import kotlin.collections.List as KtList * Each argument can be a [Term] of any sort. */ interface Struct : Term { - override val isStruct: Boolean get() = true override val isClause: Boolean - get() = CLAUSE_FUNCTOR == functor && when (arity) { - 2 -> getArgAt(0).isStruct - 1 -> true - else -> false - } + get() = + CLAUSE_FUNCTOR == functor && + when (arity) { + 2 -> getArgAt(0).isStruct + 1 -> true + else -> false + } override val isRule: Boolean get() = isClause && arity == 2 @@ -117,7 +118,10 @@ interface Struct : Term { * whose [arity] is greater than the current one, and whose [index]-th argument is [argument] */ @JsName("insertAt") - fun insertAt(index: Int, argument: Term): Struct + fun insertAt( + index: Int, + argument: Term, + ): Struct /** * Creates a novel [Struct] which is a copy of the current one, expect that is has a different functor. @@ -194,7 +198,6 @@ interface Struct : Term { operator fun get(index: Int): Term = getArgAt(index) companion object { - /** * The pattern of a well-formed functor for a [Struct]. * A functor is well-formed if and only if: @@ -228,8 +231,7 @@ interface Struct : Term { */ @JvmStatic @JsName("enquoteFunctor") - fun enquoteFunctor(string: String): String = - "'$string'" + fun enquoteFunctor(string: String): String = "'$string'" /** * Wraps the provided [string] within single quotes, but only if it is not well-formed. @@ -271,12 +273,13 @@ interface Struct : Term { fun escapeFunctor( string: String, escapeSingleQuotes: Boolean = true, - escapeDoubleQuotes: Boolean = !escapeSingleQuotes - ): String = string.toCharArray() - .asSequence() - .map { Terms.escapeChar(it, escapeSingleQuotes, escapeDoubleQuotes) } - .reduceOrNull(String::plus) - ?: "" + escapeDoubleQuotes: Boolean = !escapeSingleQuotes, + ): String = + string.toCharArray() + .asSequence() + .map { Terms.escapeChar(it, escapeSingleQuotes, escapeDoubleQuotes) } + .reduceOrNull(String::plus) + ?: "" /** * Escapes all occurrences of the characters `\n`, `\r`, `\t`, and `\` in [string], but only if a preliminary @@ -295,12 +298,13 @@ interface Struct : Term { fun escapeFunctorIfNecessary( string: String, escapeSingleQuotes: Boolean = true, - escapeDoubleQuotes: Boolean = !escapeSingleQuotes - ): String = if (functorNeedsEscape(string)) { - escapeFunctor(string, escapeSingleQuotes, escapeDoubleQuotes) - } else { - string - } + escapeDoubleQuotes: Boolean = !escapeSingleQuotes, + ): String = + if (functorNeedsEscape(string)) { + escapeFunctor(string, escapeSingleQuotes, escapeDoubleQuotes) + } else { + string + } /** * Creates a new [Struct] with [functor] as functor and a given amount of anonymous [Var]iables, namely [arity]. @@ -312,7 +316,10 @@ interface Struct : Term { */ @JvmStatic @JsName("template") - fun template(functor: String, arity: Int): Struct { + fun template( + functor: String, + arity: Int, + ): Struct { require(arity >= 0) { "Arity must be a non-negative integer" } return of(functor, (0 until arity).map { Var.anonymous() }) } @@ -335,7 +342,10 @@ interface Struct : Term { */ @JvmStatic @JsName("ofList") - fun of(functor: String, args: KtList): Struct = + fun of( + functor: String, + args: KtList, + ): Struct = when { args.size == 2 && CONS_FUNCTOR == functor -> Cons.of(args.first(), args.last()) args.size == 2 && CLAUSE_FUNCTOR == functor && args.first().isStruct -> @@ -366,7 +376,10 @@ interface Struct : Term { */ @JvmStatic @JsName("of") - fun of(functor: String, vararg args: Term): Struct = of(functor, args.toList()) + fun of( + functor: String, + vararg args: Term, + ): Struct = of(functor, args.toList()) /** * Creates a new [Struct] from the given [Sequence] of [Term]s. @@ -386,7 +399,10 @@ interface Struct : Term { */ @JvmStatic @JsName("ofSequence") - fun of(functor: String, args: Sequence): Struct = of(functor, args.toList()) + fun of( + functor: String, + args: Sequence, + ): Struct = of(functor, args.toList()) /** * Creates a new [Struct] from the given [Iterable] of [Term]s. @@ -406,7 +422,10 @@ interface Struct : Term { */ @JvmStatic @JsName("ofIterable") - fun of(functor: String, args: Iterable): Struct = of(functor, args.toList()) + fun of( + functor: String, + args: Iterable, + ): Struct = of(functor, args.toList()) /** * Folds the [Term]s in [terms] from left to right, creating binary structures having [operator] as functor. @@ -423,8 +442,10 @@ interface Struct : Term { */ @JvmStatic @JsName("foldListNullTerminated") - fun fold(operator: String, terms: KtList): Struct = - fold(operator, terms, null) + fun fold( + operator: String, + terms: KtList, + ): Struct = fold(operator, terms, null) /** * Folds the [Term]s in [terms] from left to right, creating binary structures having [operator] as functor. @@ -449,7 +470,11 @@ interface Struct : Term { */ @JvmStatic @JsName("foldList") - fun fold(operator: String, terms: KtList, terminal: Term?): Struct = + fun fold( + operator: String, + terms: KtList, + terminal: Term?, + ): Struct = when { operator == CONS_FUNCTOR && terminal == EmptyList() -> List.of(terms) operator == CONS_FUNCTOR && terminal == null -> List.from(terms) @@ -493,8 +518,11 @@ interface Struct : Term { */ @JvmStatic @JsName("foldSequence") - fun fold(operator: String, terms: Sequence, terminal: Term?): Struct = - fold(operator, terms.toList(), terminal) + fun fold( + operator: String, + terms: Sequence, + terminal: Term?, + ): Struct = fold(operator, terms.toList(), terminal) /** * Folds the [Term]s in [terms] from left to right, creating binary structures having [operator] as functor. @@ -511,8 +539,10 @@ interface Struct : Term { */ @JvmStatic @JsName("foldSequenceNullTerminated") - fun fold(operator: String, terms: Sequence): Struct = - fold(operator, terms, null) + fun fold( + operator: String, + terms: Sequence, + ): Struct = fold(operator, terms, null) /** * Folds the [Term]s in [terms] from left to right, creating binary structures having [operator] as functor. @@ -537,8 +567,11 @@ interface Struct : Term { */ @JvmStatic @JsName("foldIterable") - fun fold(operator: String, terms: Iterable, terminal: Term?): Struct = - fold(operator, terms.toList(), terminal) + fun fold( + operator: String, + terms: Iterable, + terminal: Term?, + ): Struct = fold(operator, terms.toList(), terminal) /** * Folds the [Term]s in [terms] from left to right, creating binary structures having [operator] as functor. @@ -555,8 +588,10 @@ interface Struct : Term { */ @JvmStatic @JsName("foldIterableNullTerminated") - fun fold(operator: String, terms: Iterable): Struct = - fold(operator, terms, null) + fun fold( + operator: String, + terms: Iterable, + ): Struct = fold(operator, terms, null) /** * Folds the [Term]s in [terms] from left to right, creating binary structures having [operator] as functor. @@ -581,8 +616,11 @@ interface Struct : Term { */ @JvmStatic @JsName("fold") - fun fold(operator: String, vararg terms: Term, terminal: Term?): Struct = - fold(operator, terms.toList(), terminal) + fun fold( + operator: String, + vararg terms: Term, + terminal: Term?, + ): Struct = fold(operator, terms.toList(), terminal) /** * Folds the [Term]s in [terms] from left to right, creating binary structures having [operator] as functor. @@ -599,7 +637,9 @@ interface Struct : Term { */ @JvmStatic @JsName("foldNullTerminated") - fun fold(operator: String, vararg terms: Term): Struct = - fold(operator, listOf(*terms)) + fun fold( + operator: String, + vararg terms: Term, + ): Struct = fold(operator, listOf(*terms)) } } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Substitution.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Substitution.kt index 436f48562..2a0f8986b 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Substitution.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Substitution.kt @@ -15,7 +15,6 @@ import kotlin.collections.Collection as KtCollection * - [Substitution.Fail], which represent the lack of possible assignments for any set of [Var]s */ sealed interface Substitution : Map, Taggable, Castable { - /** Whether this [Substitution] is a successful one (i.e., a [Unifier]) */ @JsName("isSuccess") val isSuccess: Boolean @@ -53,8 +52,7 @@ sealed interface Substitution : Map, Taggable, Castable * @return the current [Substitution], casted to [Fail] */ @JsName("castToFail") - fun castToFail(): Fail = - asFail() ?: throw ClassCastException("Cannot cast $this to ${Fail::class.simpleName}") + fun castToFail(): Fail = asFail() ?: throw ClassCastException("Cannot cast $this to ${Fail::class.simpleName}") /** Applies this [Substitution] to the given [Term], returning `null` if it is [Substitution.Fail] */ @JsName("applyTo") @@ -64,21 +62,19 @@ sealed interface Substitution : Map, Taggable, Castable fun whenIs( unifier: ((Unifier) -> T)? = null, fail: ((Fail) -> T)? = null, - otherwise: ((Substitution) -> T) = { throw IllegalStateException("Cannot handle solution $it") } + otherwise: ((Substitution) -> T) = { throw IllegalStateException("Cannot handle solution $it") }, ): T /** Retrieves the original variable name of the provided [variable], if any, or `null` otherwise * * Consider for instance the substitution `{ X -> Y, Y -> Z }`, * then the invocation of `getOriginal(Z)` should retrieve `X` - * */ - // TODO test this method + */ @JsName("getOriginal") - fun getOriginal(variable: Var): Var? + fun getOriginal(variable: Var): Var? // TODO test this method @JsName("getByName") - fun getByName(name: String): Term? = - keys.find { it.name == name }?.let { get(it) } + fun getByName(name: String): Term? = keys.find { it.name == name }?.let { get(it) } /** * Creates a new [Substitution] that is the *composition* (a.k.a. union) of `this` and [other]. @@ -107,7 +103,10 @@ sealed interface Substitution : Map, Taggable, Castable * [Substitution]s' tags via [tagsMerger]. */ @JsName("plusMergingTags") - fun plus(other: Substitution, tagsMerger: TagsOperator): Substitution + fun plus( + other: Substitution, + tagsMerger: TagsOperator, + ): Substitution /** * Returns a new substitution containing all entries of the original substitution except those @@ -122,7 +121,10 @@ sealed interface Substitution : Map, Taggable, Castable operator fun minus(variable: Var): Substitution @JsName("minusVars") - fun minus(variable: Var, vararg otherVariables: Var): Substitution + fun minus( + variable: Var, + vararg otherVariables: Var, + ): Substitution /** * Returns a new substitution containing all entries of the original substitution except those @@ -163,14 +165,16 @@ sealed interface Substitution : Map, Taggable, Castable /** A type for successful [Substitution]s (a.k.a. unifiers) actually assigning [Var]s to [Term]s */ sealed interface Unifier : Substitution { - override fun minus(keys: Iterable): Unifier override fun minus(other: Substitution): Unifier override fun minus(variable: Var): Unifier - override fun minus(variable: Var, vararg otherVariables: Var): Unifier + override fun minus( + variable: Var, + vararg otherVariables: Var, + ): Unifier override fun filter(predicate: (Map.Entry) -> Boolean): Unifier @@ -195,7 +199,10 @@ sealed interface Substitution : Map, Taggable, Castable override fun minus(variable: Var): Fail - override fun minus(variable: Var, vararg otherVariables: Var): Fail + override fun minus( + variable: Var, + vararg otherVariables: Var, + ): Fail override fun filter(predicate: (Map.Entry) -> Boolean): Fail @@ -212,9 +219,10 @@ sealed interface Substitution : Map, Taggable, Castable /** Substitution companion with factory functionality */ companion object { - - private inline fun castToUnifierOrThrowException(arg: T, ctor: (T) -> Substitution): Unifier = - ctor(arg).let { it.asUnifier() ?: throw SubstitutionException(it) } + private inline fun castToUnifierOrThrowException( + arg: T, + ctor: (T) -> Substitution, + ): Unifier = ctor(arg).let { it.asUnifier() ?: throw SubstitutionException(it) } private val FAILED: Fail = SubstitutionImpl.FailImpl() @@ -243,12 +251,18 @@ sealed interface Substitution : Map, Taggable, Castable /** Creates a singleton [Unifier] containing a single [Var]-[Term] assignment */ @JvmStatic @JsName("of") - fun of(variable: Var, term: Term): Unifier = of(mapOf(variable to term)) + fun of( + variable: Var, + term: Term, + ): Unifier = of(mapOf(variable to term)) /** Creates a [Unifier] of given a map assigning [Var]s to [Term]s */ @JvmStatic @JsName("unifier") - fun unifier(variable: Var, term: Term): Unifier = of(mapOf(variable to term)) + fun unifier( + variable: Var, + term: Term, + ): Unifier = of(mapOf(variable to term)) /** * Creates a singleton [Unifier] containing a single [Var]-[Term] assignment. @@ -256,7 +270,10 @@ sealed interface Substitution : Map, Taggable, Castable */ @JvmStatic @JsName("ofString") - fun of(variable: String, term: Term): Unifier = of(mapOf(Var.of(variable) to term)) + fun of( + variable: String, + term: Term, + ): Unifier = of(mapOf(Var.of(variable) to term)) /** * Creates a singleton [Unifier] containing a single [Var]-[Term] assignment. @@ -264,7 +281,10 @@ sealed interface Substitution : Map, Taggable, Castable */ @JvmStatic @JsName("unifierString") - fun unifier(variable: String, term: Term): Unifier = of(mapOf(Var.of(variable) to term)) + fun unifier( + variable: String, + term: Term, + ): Unifier = of(mapOf(Var.of(variable) to term)) /** * Crates a [Substitution] from the given [Var]-[Term] [Pair]s. @@ -272,8 +292,10 @@ sealed interface Substitution : Map, Taggable, Castable */ @JvmStatic @JsName("ofPair") - fun of(substitutionPair: Pair, vararg substitutionPairs: Pair): Substitution = - SubstitutionImpl.of(sequenceOf(substitutionPair, *substitutionPairs)) + fun of( + substitutionPair: Pair, + vararg substitutionPairs: Pair, + ): Substitution = SubstitutionImpl.of(sequenceOf(substitutionPair, *substitutionPairs)) /** * Crates a [Substitution] from the given [Var]-[Term] [Pair]s. @@ -281,8 +303,10 @@ sealed interface Substitution : Map, Taggable, Castable */ @JvmStatic @JsName("unifierPairs") - fun unifier(substitutionPair: Pair, vararg substitutionPairs: Pair): Unifier = - castToUnifierOrThrowException(sequenceOf(substitutionPair, *substitutionPairs), ::of) + fun unifier( + substitutionPair: Pair, + vararg substitutionPairs: Pair, + ): Unifier = castToUnifierOrThrowException(sequenceOf(substitutionPair, *substitutionPairs), ::of) /** * Crates a [Substitution] from the given [Iterable] of [Var]-[Term] [Pair]s. @@ -324,7 +348,9 @@ sealed interface Substitution : Map, Taggable, Castable */ @JvmStatic @JsName("ofSubstitution") - fun of(substitution: Substitution, vararg substitutions: Substitution): Substitution = - substitutions.fold(substitution, Substitution::plus) + fun of( + substitution: Substitution, + vararg substitutions: Substitution, + ): Substitution = substitutions.fold(substitution, Substitution::plus) } } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/SubstitutionImpl.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/SubstitutionImpl.kt index 821eed188..2d5bccdb3 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/SubstitutionImpl.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/SubstitutionImpl.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.utils.TagsOperator import kotlin.collections.Collection as KtCollection internal sealed class SubstitutionImpl : Substitution { - override val isSuccess: Boolean get() = false @@ -16,30 +15,36 @@ internal sealed class SubstitutionImpl : Substitution { override fun plus(other: Substitution): Substitution = plus(other) { x, y -> x + y } - override fun plus(other: Substitution, tagsMerger: TagsOperator): Substitution = when { - anyFailed(this, other) || anyContradiction(this, other) -> { - FailImpl(tagsMerger(tags, other.tags)) - } - else -> { - UnifierImpl.of( - this.mapValues { (_, value) -> value.apply(other) } + other, - tagsMerger(tags, other.tags) - ) + override fun plus( + other: Substitution, + tagsMerger: TagsOperator, + ): Substitution = + when { + anyFailed(this, other) || anyContradiction(this, other) -> { + FailImpl(tagsMerger(tags, other.tags)) + } + else -> { + UnifierImpl.of( + this.mapValues { (_, value) -> value.apply(other) } + other, + tagsMerger(tags, other.tags), + ) + } } - } override operator fun minus(keys: Iterable): Substitution { val thiz: Map = this return whenIs( unifier = { UnifierImpl.of(thiz - keys, tags) }, - fail = { FailImpl(tags) } + fail = { FailImpl(tags) }, ) } override fun minus(variable: Var): Substitution = minus(listOf(variable)) - override fun minus(variable: Var, vararg otherVariables: Var): Substitution = - minus(listOf(variable, *otherVariables)) + override fun minus( + variable: Var, + vararg otherVariables: Var, + ): Substitution = minus(listOf(variable, *otherVariables)) override operator fun minus(other: Substitution): Substitution = this - other.keys @@ -47,19 +52,24 @@ internal sealed class SubstitutionImpl : Substitution { val thiz: Map = this return whenIs( unifier = { UnifierImpl.of(thiz.filter(predicate), tags) }, - fail = { FailImpl(tags) } + fail = { FailImpl(tags) }, ) } override fun filter(variables: KtCollection): Substitution = filter { k, _ -> k in variables } override fun filter(predicate: (key: Var, value: Term) -> Boolean): Substitution = - filter { (key, value) -> predicate(key, value) } + filter { (key, value) -> + predicate( + key, + value, + ) + } override fun whenIs( unifier: ((Unifier) -> T)?, fail: ((Substitution.Fail) -> T)?, - otherwise: (Substitution) -> T + otherwise: (Substitution) -> T, ): T { if (isSuccess && unifier != null) { return unifier(castToUnifier()) @@ -73,12 +83,13 @@ internal sealed class SubstitutionImpl : Substitution { /** Creates a new Successful Substitution (aka Unifier) with given mappings (after some checks) */ class UnifierImpl private constructor( private val assignments: Map, - override val tags: Map + override val tags: Map, ) : SubstitutionImpl(), Unifier, Map by (assignments) { - companion object { - fun of(mappings: Map, tags: Map = emptyMap()) = - UnifierImpl(mappings.trimVariableChains().withoutIdentityMappings(), tags) + fun of( + mappings: Map, + tags: Map = emptyMap(), + ) = UnifierImpl(mappings.trimVariableChains().withoutIdentityMappings(), tags) } // NOTE: no check for contradictions is made upon object construction @@ -110,17 +121,22 @@ internal sealed class SubstitutionImpl : Substitution { override fun minus(variable: Var): Unifier = super.minus(variable).castToUnifier() - override fun minus(variable: Var, vararg otherVariables: Var): Unifier = - super.minus(variable, *otherVariables).castToUnifier() + override fun minus( + variable: Var, + vararg otherVariables: Var, + ): Unifier = super.minus(variable, *otherVariables).castToUnifier() override fun filter(predicate: (Map.Entry) -> Boolean): Unifier = - super.filter(predicate).castToUnifier() + super.filter( + predicate, + ).castToUnifier() override fun filter(predicate: (key: Var, value: Term) -> Boolean): Unifier = - super.filter(predicate).castToUnifier() + super.filter( + predicate, + ).castToUnifier() - override fun filter(variables: KtCollection): Unifier = - super.filter(variables).castToUnifier() + override fun filter(variables: KtCollection): Unifier = super.filter(variables).castToUnifier() override fun equals(other: Any?): Boolean { if (this === other) return true @@ -141,14 +157,20 @@ internal sealed class SubstitutionImpl : Substitution { override fun applyTo(term: Term): Term = term.apply(this) override fun replaceTags(tags: Map): Unifier = - if (tags == this.tags) this else UnifierImpl(assignments, tags) + if (tags == this.tags) { + this + } else { + UnifierImpl( + assignments, + tags, + ) + } } /** The Failed Substitution instance */ class FailImpl constructor( - override val tags: Map = emptyMap() + override val tags: Map = emptyMap(), ) : SubstitutionImpl(), Substitution.Fail, Map by emptyMap() { - override val isFailed: Boolean get() = true @@ -160,7 +182,10 @@ internal sealed class SubstitutionImpl : Substitution { override fun minus(variable: Var): FailImpl = this - override fun minus(variable: Var, vararg otherVariables: Var): FailImpl = this + override fun minus( + variable: Var, + vararg otherVariables: Var, + ): FailImpl = this override fun filter(predicate: (Map.Entry) -> Boolean): FailImpl = this @@ -172,8 +197,7 @@ internal sealed class SubstitutionImpl : Substitution { override fun applyTo(term: Term): Nothing? = null - override fun replaceTags(tags: Map): FailImpl = - if (tags == this.tags) this else FailImpl(tags) + override fun replaceTags(tags: Map): FailImpl = if (tags == this.tags) this else FailImpl(tags) override fun equals(other: Any?): Boolean { if (this === other) return true @@ -189,12 +213,12 @@ internal sealed class SubstitutionImpl : Substitution { /** Substitution companion with factory functionality */ companion object { - /** Crates a Substitution from given substitution pairs; if any contradiction is found, the result will be [Substitution.Fail] */ - fun of(substitutionPairs: Sequence>): Substitution = when { - anyContradiction(substitutionPairs) -> FailImpl() - else -> UnifierImpl.of(substitutionPairs.toMap()) - } + fun of(substitutionPairs: Sequence>): Substitution = + when { + anyContradiction(substitutionPairs) -> FailImpl() + else -> UnifierImpl.of(substitutionPairs.toMap()) + } /** Utility function to check if any of provided Substitution is failed */ private fun anyFailed(vararg substitution: Substitution): Boolean = substitution.any { it.isFailed } @@ -204,7 +228,10 @@ internal sealed class SubstitutionImpl : Substitution { * * Computational Complexity: length of the smaller among provided substitutions */ - private fun anyContradiction(substitution: Substitution, other: Substitution): Boolean = + private fun anyContradiction( + substitution: Substitution, + other: Substitution, + ): Boolean = when { substitution.size < other.size -> substitution to other else -> other to substitution @@ -223,7 +250,10 @@ internal sealed class SubstitutionImpl : Substitution { private fun anyContradiction(substitutionPairs: Sequence>): Boolean = when { substitutionPairs.none() -> false // no pair, no contradiction - with(substitutionPairs.iterator()) { next(); !hasNext() } -> false // one pair, no contradiction + with(substitutionPairs.iterator()) { + next() + !hasNext() + } -> false // one pair, no contradiction else -> mutableMapOf().let { alreadySeenSubstitutions -> substitutionPairs.forEach { (variable, substitution) -> @@ -262,6 +292,9 @@ internal sealed class SubstitutionImpl : Substitution { /** Utility function to filter out identity mappings from a Map */ private fun Map.withoutIdentityMappings(): Map = - filterNot { (`var`, term) -> `var` == term } + filterNot { + (`var`, term) -> + `var` == term + } } } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Term.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Term.kt index fdbb086e5..1b3c25154 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Term.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Term.kt @@ -9,7 +9,6 @@ import kotlin.js.JsName * [Term]s are immutable tree-like data structures. */ interface Term : Comparable, Taggable, Castable, Applicable, Variabled { - /** * Empty companion aimed at letting extensions be injected through extension methods */ @@ -38,8 +37,7 @@ interface Term : Comparable, Taggable, Castable, Applicable, Taggable, Castable, Applicable, Taggable, Castable, Applicable, Taggable, Castable, Applicable, Taggable, Castable, Applicable, Taggable, Castable, Applicable, Taggable, Castable, Applicable, Taggable, Castable, Applicable, Taggable, Castable, Applicable, Taggable, Castable, Applicable, Taggable, Castable, Applicable, Taggable, Castable, Applicable : Comparator { object AtomComparator : TermComparator { - override fun compare(a: Atom, b: Atom): Int = - compareStringsLocaleIndependently(a.value, b.value) + override fun compare( + a: Atom, + b: Atom, + ): Int = compareStringsLocaleIndependently(a.value, b.value) } object VarComparator : TermComparator { - override fun compare(a: Var, b: Var): Int = - compareStringsLocaleIndependently(a.completeName, b.completeName) + override fun compare( + a: Var, + b: Var, + ): Int = compareStringsLocaleIndependently(a.completeName, b.completeName) } object RealComparator : TermComparator { - override fun compare(a: Real, b: Real): Int = - a.decimalValue.compareTo(b.decimalValue) + override fun compare( + a: Real, + b: Real, + ): Int = a.decimalValue.compareTo(b.decimalValue) } object IntegerComparator : TermComparator { - override fun compare(a: Integer, b: Integer): Int = - a.intValue.compareTo(b.intValue) + override fun compare( + a: Integer, + b: Integer, + ): Int = a.intValue.compareTo(b.intValue) } object DefaultComparator : TermComparator { - - private fun compareVarAndTerm(a: Var, b: Term): Int = + private fun compareVarAndTerm( + a: Var, + b: Term, + ): Int = when { b.isVar -> VarComparator.compare(a, b.castToVar()) else -> -1 } - private fun compareRealAndTerm(a: Real, b: Term): Int = + private fun compareRealAndTerm( + a: Real, + b: Term, + ): Int = when { b.isReal -> RealComparator.compare(a, b.castToReal()) b.isVar -> 1 else -> -1 } - private fun compareIntegerAndTerm(a: Integer, b: Term): Int = + private fun compareIntegerAndTerm( + a: Integer, + b: Term, + ): Int = when { b.isInteger -> IntegerComparator.compare(a, b.castToInteger()) b.isVar || b.isReal -> 1 else -> -1 } - private fun compareAtomAndTerm(a: Atom, b: Term): Int = + private fun compareAtomAndTerm( + a: Atom, + b: Term, + ): Int = when { b.isAtom -> AtomComparator.compare(a, b.castToAtom()) b.isStruct -> -1 else -> 1 } - private fun compareStructAndTerm(a: Struct, b: Term): Int = + private fun compareStructAndTerm( + a: Struct, + b: Term, + ): Int = when { b.isStruct -> StructComparator.compare(a, b.castToStruct()) else -> 1 } - override fun compare(a: Term, b: Term): Int = + override fun compare( + a: Term, + b: Term, + ): Int = when { a.isVar -> compareVarAndTerm(a.castToVar(), b) a.isReal -> compareRealAndTerm(a.castToReal(), b) @@ -68,20 +93,24 @@ interface TermComparator : Comparator { } object StructComparator : TermComparator { - override fun compare(a: Struct, b: Struct): Int { + override fun compare( + a: Struct, + b: Struct, + ): Int { return when (val arityDelta = a.arity - b.arity) { - 0 -> when (val functorComparison = a.functor.compareTo(b.functor)) { - 0 -> { - for (i in 0 until a.arity) { - val ithArgComparison = DefaultComparator.compare(a[i], b[i]) - if (ithArgComparison != 0) { - return ithArgComparison + 0 -> + when (val functorComparison = a.functor.compareTo(b.functor)) { + 0 -> { + for (i in 0 until a.arity) { + val ithArgComparison = DefaultComparator.compare(a[i], b[i]) + if (ithArgComparison != 0) { + return ithArgComparison + } } + return 0 } - return 0 + else -> functorComparison } - else -> functorComparison - } else -> arityDelta } } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/TermConvertible.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/TermConvertible.kt index 5d70535f5..770ecc247 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/TermConvertible.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/TermConvertible.kt @@ -8,7 +8,6 @@ import kotlin.js.JsName * @author Enrico */ interface TermConvertible { - /** Converts this instance to a Prolog [Term] */ @JsName("toTerm") fun toTerm(): Term diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/TermFormatter.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/TermFormatter.kt index 4328b94cf..e98c77028 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/TermFormatter.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/TermFormatter.kt @@ -20,22 +20,21 @@ import kotlin.jvm.JvmStatic * A particular sort of [Formatter]s aimed at representing terms */ interface TermFormatter : Formatter, TermVisitor { - enum class VarFormat { COMPLETE_NAME, UNDERSCORE, - PRETTY + PRETTY, } enum class OpFormat { IGNORE_OPERATORS, COLLECTIONS, - EXPRESSIONS + EXPRESSIONS, } enum class FuncFormat { QUOTED_IF_NECESSARY, - LITERAL + LITERAL, } /** @@ -46,7 +45,6 @@ interface TermFormatter : Formatter, TermVisitor { override fun format(value: Term): String = value.accept(this) companion object { - @JvmStatic @JsName("of") fun of( @@ -54,15 +52,16 @@ interface TermFormatter : Formatter, TermVisitor { opFormat: OpFormat, funcFormat: FuncFormat = QUOTED_IF_NECESSARY, numberVars: Boolean = false, - operators: OperatorSet = OperatorSet.DEFAULT + operators: OperatorSet = OperatorSet.DEFAULT, ): TermFormatter { val quoted = funcFormat == QUOTED_IF_NECESSARY val ignoreOps = opFormat == IGNORE_OPERATORS - val inner = when (varFormat) { - COMPLETE_NAME -> SimpleTermFormatter(quoted, numberVars, ignoreOps) - UNDERSCORE -> TermFormatterWithAnonymousVariables(quoted, numberVars, ignoreOps) - PRETTY -> TermFormatterWithPrettyVariables(quoted, numberVars, ignoreOps) - } + val inner = + when (varFormat) { + COMPLETE_NAME -> SimpleTermFormatter(quoted, numberVars, ignoreOps) + UNDERSCORE -> TermFormatterWithAnonymousVariables(quoted, numberVars, ignoreOps) + PRETTY -> TermFormatterWithPrettyVariables(quoted, numberVars, ignoreOps) + } return when (opFormat) { EXPRESSIONS -> TermFormatterWithPrettyExpressions(inner, operators, quoted, numberVars, ignoreOps) else -> inner @@ -105,8 +104,10 @@ interface TermFormatter : Formatter, TermVisitor { */ @JvmStatic @JsName("prettyExpressions") - fun prettyExpressions(prettyVariables: Boolean, operatorSet: OperatorSet): TermFormatter = - of(if (prettyVariables) PRETTY else COMPLETE_NAME, EXPRESSIONS, operators = operatorSet) + fun prettyExpressions( + prettyVariables: Boolean, + operatorSet: OperatorSet, + ): TermFormatter = of(if (prettyVariables) PRETTY else COMPLETE_NAME, EXPRESSIONS, operators = operatorSet) /** * A [TermFormatter] representing terms in a pretty way, i.e. by representing prefix, postfix, or infix expressions diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/TermVisitor.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/TermVisitor.kt index 43d4cde7d..b1a59bf9c 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/TermVisitor.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/TermVisitor.kt @@ -3,7 +3,6 @@ package it.unibo.tuprolog.core import kotlin.js.JsName interface TermVisitor { - @JsName("defaultValue") fun defaultValue(term: Term): T diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Terms.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Terms.kt index 2620d6b1a..63159deb4 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Terms.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Terms.kt @@ -58,14 +58,15 @@ object Terms { fun escapeChar( char: Char, singleQuotes: Boolean = true, - doubleQuotes: Boolean = !singleQuotes - ): String = when (char) { - '\n' -> "\\n" - '\t' -> "\\t" - '\r' -> "\\r" - '\\' -> "\\\\" - '\'' -> if (singleQuotes) "\\'" else "'" - '\"' -> if (doubleQuotes) "\\\"" else "\"" - else -> "$char" - } + doubleQuotes: Boolean = !singleQuotes, + ): String = + when (char) { + '\n' -> "\\n" + '\t' -> "\\t" + '\r' -> "\\r" + '\\' -> "\\\\" + '\'' -> if (singleQuotes) "\\'" else "'" + '\"' -> if (doubleQuotes) "\\\"" else "\"" + else -> "$char" + } } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Truth.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Truth.kt index 9d880db1a..bd09777e2 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Truth.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Truth.kt @@ -6,7 +6,6 @@ import kotlin.jvm.JvmField import kotlin.jvm.JvmStatic interface Truth : Atom { - override val isTrue: Boolean override val isFail: Boolean @@ -23,7 +22,6 @@ interface Truth : Atom { @Suppress("MayBeConstant") companion object { - @JvmField val TRUE_FUNCTOR = Terms.TRUE_FUNCTOR @@ -44,8 +42,7 @@ interface Truth : Atom { @JvmStatic @JsName("of") - fun of(truth: Boolean): Truth = - if (truth) TRUE else FALSE + fun of(truth: Boolean): Truth = if (truth) TRUE else FALSE @JvmStatic @JsName("ofString") diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Tuple.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Tuple.kt index 5dc0da18d..365e43bcc 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Tuple.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Tuple.kt @@ -8,7 +8,6 @@ import kotlin.jvm.JvmStatic import kotlin.collections.List as KtList interface Tuple : Recursive { - override val isTuple: Boolean get() = true @@ -37,19 +36,23 @@ interface Tuple : Recursive { override fun freshCopy(scope: Scope): Tuple companion object { - const val FUNCTOR = TUPLE_FUNCTOR @JvmStatic @JsName("wrapIfNeeded") @JvmOverloads - fun wrapIfNeeded(vararg terms: Term, ifEmpty: () -> Term = { Truth.TRUE }): Term = - wrapIfNeeded(terms.asIterable(), ifEmpty) + fun wrapIfNeeded( + vararg terms: Term, + ifEmpty: () -> Term = { Truth.TRUE }, + ): Term = wrapIfNeeded(terms.asIterable(), ifEmpty) @JvmStatic @JsName("wrapIterableIfNeeded") @JvmOverloads - fun wrapIfNeeded(terms: Iterable, ifEmpty: () -> Term = { Truth.TRUE }): Term { + fun wrapIfNeeded( + terms: Iterable, + ifEmpty: () -> Term = { Truth.TRUE }, + ): Term { val i = terms.iterator() if (!i.hasNext()) return ifEmpty() val first = i.next() @@ -64,16 +67,25 @@ interface Tuple : Recursive { @JvmStatic @JsName("wrapSequenceIfNeeded") @JvmOverloads - fun wrapIfNeeded(terms: Sequence, ifEmpty: () -> Term = { Truth.TRUE }): Term = - wrapIfNeeded(terms.asIterable(), ifEmpty) + fun wrapIfNeeded( + terms: Sequence, + ifEmpty: () -> Term = { Truth.TRUE }, + ): Term = wrapIfNeeded(terms.asIterable(), ifEmpty) @JvmStatic @JsName("of") - fun of(left: Term, right: Term): Tuple = TupleImpl(left, right) + fun of( + left: Term, + right: Term, + ): Tuple = TupleImpl(left, right) @JvmStatic @JsName("ofMany") - fun of(first: Term, second: Term, vararg others: Term): Tuple = of(listOf(first, second, *others)) + fun of( + first: Term, + second: Term, + vararg others: Term, + ): Tuple = of(listOf(first, second, *others)) @JvmStatic @JsName("ofIterable") diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/TupleIterator.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/TupleIterator.kt index 97105252c..9c7112846 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/TupleIterator.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/TupleIterator.kt @@ -1,19 +1,19 @@ package it.unibo.tuprolog.core class TupleIterator(tuple: Tuple) : Iterator { + private val tupleIteratorVisitor = + object : TermVisitor { + override fun visitTuple(term: Tuple): Term { + current = term.right + return term.left + } - private val tupleIteratorVisitor = object : TermVisitor { - override fun visitTuple(term: Tuple): Term { - current = term.right - return term.left + override fun defaultValue(term: Term): Term { + current = null + return term + } } - override fun defaultValue(term: Term): Term { - current = null - return term - } - } - private var current: Term? = tuple override fun hasNext(): Boolean = current != null diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Var.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Var.kt index 57922cc00..ec704a74a 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Var.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/Var.kt @@ -6,7 +6,6 @@ import kotlin.jvm.JvmField import kotlin.jvm.JvmStatic interface Var : Term { - override val isVar: Boolean get() = true @@ -37,7 +36,6 @@ interface Var : Term { @Suppress("MayBeConstant") companion object { - @JvmField val ANONYMOUS_NAME = Terms.ANONYMOUS_VAR_NAME diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/VariablesProvider.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/VariablesProvider.kt index 88cc46c3c..af7649f30 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/VariablesProvider.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/VariablesProvider.kt @@ -8,8 +8,10 @@ import kotlin.reflect.KProperty @Suppress("PropertyName") interface VariablesProvider : Scope { - - operator fun getValue(thisRef: Any?, property: KProperty<*>): Var + operator fun getValue( + thisRef: Any?, + property: KProperty<*>, + ): Var @JsName("A") val A: Var diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/exception/SubstitutionApplicationException.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/exception/SubstitutionApplicationException.kt index 508cdea38..85f11b2fc 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/exception/SubstitutionApplicationException.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/exception/SubstitutionApplicationException.kt @@ -11,7 +11,7 @@ class SubstitutionApplicationException : SubstitutionException { constructor(term: Term, substitution: Substitution, message: String?, cause: Throwable? = null) : super( substitution, message, - cause + cause, ) { this.term = term } @@ -22,7 +22,7 @@ class SubstitutionApplicationException : SubstitutionException { term, substitution, "Could not apply $substitution to $term", - cause + cause, ) @JvmOverloads @@ -30,6 +30,6 @@ class SubstitutionApplicationException : SubstitutionException { this( term, Substitution.failed(), - cause + cause, ) } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/exception/SubstitutionException.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/exception/SubstitutionException.kt index 3de485ebe..613b98c18 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/exception/SubstitutionException.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/exception/SubstitutionException.kt @@ -4,7 +4,6 @@ import it.unibo.tuprolog.core.Substitution import kotlin.jvm.JvmOverloads open class SubstitutionException : TuPrologException { - val substitution: Substitution @JvmOverloads diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/AbstractCons.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/AbstractCons.kt index 34667c990..b39bcab46 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/AbstractCons.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/AbstractCons.kt @@ -11,9 +11,8 @@ import it.unibo.tuprolog.core.ListIterator as LogicListIterator internal abstract class AbstractCons( args: List, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : RecursiveImpl(CONS_FUNCTOR, args, tags), Cons { - companion object { const val SWITCH_TO_LAZY_THRESHOLD = 100 } @@ -48,11 +47,12 @@ internal abstract class AbstractCons( get() = unfoldedSequence.last() override fun toString(): String { - val (ending, take) = if (isWellFormed) { - "]" to size - } else { - " | $last]" to size - 1 - } + val (ending, take) = + if (isWellFormed) { + "]" to size + } else { + " | $last]" to size - 1 + } return unfoldedSequence.take(take).joinToString(", ", "[", ending) } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/AbstractStruct.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/AbstractStruct.kt index 30c1ee1c5..18f1d2dab 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/AbstractStruct.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/AbstractStruct.kt @@ -12,9 +12,8 @@ import it.unibo.tuprolog.utils.setTags internal abstract class AbstractStruct( override val functor: String, override val args: List, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : TermImpl(tags), Struct { - override val isGround: Boolean get() = checkGroundness() @@ -22,15 +21,17 @@ internal abstract class AbstractStruct( override fun freshCopy(): Struct = freshCopy(Scope.empty()) - override fun freshCopy(scope: Scope): Struct = when { - isGround -> this - else -> scope.structOf(functor, argsSequence.map { it.freshCopy(scope) }).setTags(tags) - } + override fun freshCopy(scope: Scope): Struct = + when { + isGround -> this + else -> scope.structOf(functor, argsSequence.map { it.freshCopy(scope) }).setTags(tags) + } final override fun structurallyEquals(other: Term): Boolean = - other.isStruct && other.castToStruct().let { - functor == it.functor && arity == it.arity && itemsAreStructurallyEqual(it) - } + other.isStruct && + other.castToStruct().let { + functor == it.functor && arity == it.arity && itemsAreStructurallyEqual(it) + } @Suppress("RedundantAsSequence") protected open fun itemsAreStructurallyEqual(other: Struct): Boolean { @@ -45,11 +46,13 @@ internal abstract class AbstractStruct( override val isFunctorWellFormed: Boolean get() = Struct.isWellFormedFunctor(functor) - final override fun equals(other: Any?): Boolean = - asTerm(other)?.asStruct()?.let { equalsImpl(it, true) } ?: false + final override fun equals(other: Any?): Boolean = asTerm(other)?.asStruct()?.let { equalsImpl(it, true) } ?: false @Suppress("RedundantAsSequence") - protected open fun itemsAreEqual(other: Struct, useVarCompleteName: Boolean): Boolean { + protected open fun itemsAreEqual( + other: Struct, + useVarCompleteName: Boolean, + ): Boolean { for (i in 0 until arity) { if (!getArgAt(i).equals(other[i], useVarCompleteName)) { return false @@ -58,10 +61,15 @@ internal abstract class AbstractStruct( return true } - final override fun equals(other: Term, useVarCompleteName: Boolean): Boolean = - other.asStruct()?.let { equalsImpl(it, useVarCompleteName) } ?: false + final override fun equals( + other: Term, + useVarCompleteName: Boolean, + ): Boolean = other.asStruct()?.let { equalsImpl(it, useVarCompleteName) } ?: false - private fun equalsImpl(other: Struct, useVarCompleteName: Boolean): Boolean { + private fun equalsImpl( + other: Struct, + useVarCompleteName: Boolean, + ): Boolean { if (this === other) return true if (functor != other.functor) return false if (arity != other.arity) return false @@ -88,14 +96,17 @@ internal abstract class AbstractStruct( override fun addFirst(argument: Term): Struct = Struct.of(functor, listOf(argument) + args) - override fun insertAt(index: Int, argument: Term): Struct = + override fun insertAt( + index: Int, + argument: Term, + ): Struct = if (index in 0 until arity) { val argsArray = args.toTypedArray() Struct.of( functor, *argsArray.sliceArray(0 until index), argument, - *argsArray.sliceArray(index until arity) + *argsArray.sliceArray(index until arity), ) } else { throw IndexOutOfBoundsException("Index $index is out of bounds ${args.indices}") diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/AbstractTermFormatter.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/AbstractTermFormatter.kt index edcccc1f4..6b95c23a0 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/AbstractTermFormatter.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/AbstractTermFormatter.kt @@ -21,9 +21,8 @@ import org.gciatto.kt.math.BigInteger internal abstract class AbstractTermFormatter( protected val quoted: Boolean = true, protected val numberVars: Boolean = false, - protected val ignoreOps: Boolean = false + protected val ignoreOps: Boolean = false, ) : TermFormatter { - companion object { private val TWENTY_SIX = BigInteger.of(26) private const val A_INDEX = 'A'.code @@ -43,9 +42,10 @@ internal abstract class AbstractTermFormatter( } private fun isNumberedVar(term: Struct): Boolean = - term.functor == "\$VAR" && term.arity == 1 && term[0].let { - it.isInteger && it.castToInteger().value >= BigInteger.ZERO - } + term.functor == "\$VAR" && term.arity == 1 && + term[0].let { + it.isInteger && it.castToInteger().value >= BigInteger.ZERO + } private fun numberedVar(integer: Integer): String { val letterIndex = (integer.value % TWENTY_SIX).toInt() + A_INDEX @@ -56,22 +56,24 @@ internal abstract class AbstractTermFormatter( private fun formatFunctor(term: Struct): String { return if (quoted) { Struct.enquoteFunctorIfNecessary( - Struct.escapeFunctorIfNecessary(term.functor) + Struct.escapeFunctorIfNecessary(term.functor), ) } else { term.functor } } - private fun visitStructImpl(term: T, actualVisit: (T) -> String): String = + private fun visitStructImpl( + term: T, + actualVisit: (T) -> String, + ): String = if (ignoreOps) { visitStruct(term) } else { actualVisit(term) } - override fun visitCollection(term: Recursive): String = - visitStructImpl(term) { defaultValue(term) } + override fun visitCollection(term: Recursive): String = visitStructImpl(term) { defaultValue(term) } override fun visitList(term: List): String = visitCollection(term) @@ -81,14 +83,16 @@ internal abstract class AbstractTermFormatter( visitStructImpl(term) { with(term.unfoldedList) { val last = last() - val base = subList(0, lastIndex).joinToString(", ", "[", "") { - it.accept(itemFormatter()) - } - val lastString = if (last.isEmptyList) { - "]" - } else { - " | ${last.accept(itemFormatter())}]" - } + val base = + subList(0, lastIndex).joinToString(", ", "[", "") { + it.accept(itemFormatter()) + } + val lastString = + if (last.isEmptyList) { + "]" + } else { + " | ${last.accept(itemFormatter())}]" + } base + lastString } } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/AbstractTermFormatterForVariables.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/AbstractTermFormatterForVariables.kt index b8b4a351a..92b877c50 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/AbstractTermFormatterForVariables.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/AbstractTermFormatterForVariables.kt @@ -6,12 +6,14 @@ import it.unibo.tuprolog.core.Var internal abstract class AbstractTermFormatterForVariables( quoted: Boolean = true, numberVars: Boolean = false, - ignoreOps: Boolean = false + ignoreOps: Boolean = false, ) : AbstractTermFormatter(quoted, numberVars, ignoreOps) { - private val variables: MutableMap> = mutableMapOf() - protected abstract fun formatVar(variable: Var, suffix: String): String + protected abstract fun formatVar( + variable: Var, + suffix: String, + ): String override fun visitVar(term: Var): String { return if (term.isAnonymous) { diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/AtomImpl.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/AtomImpl.kt index a74e8d74d..63e46681a 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/AtomImpl.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/AtomImpl.kt @@ -8,9 +8,8 @@ import it.unibo.tuprolog.core.Var internal open class AtomImpl( override val functor: String, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : AbstractStruct(functor, emptyList(), tags), Atom { - override val args: List get() = emptyList() diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/BlockImpl.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/BlockImpl.kt index 61ccfc08b..cdac65586 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/BlockImpl.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/BlockImpl.kt @@ -10,9 +10,8 @@ import it.unibo.tuprolog.utils.setTags internal open class BlockImpl( private val item: Term?, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : RecursiveImpl(BLOCK_FUNCTOR, listOfNotNull(item), tags), Block { - override val isGround: Boolean = checkGroundness() override fun checkGroundness(): Boolean = item?.isGround ?: true diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/BlockUnfolder.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/BlockUnfolder.kt index 19a605a97..58a763646 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/BlockUnfolder.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/BlockUnfolder.kt @@ -7,43 +7,45 @@ import it.unibo.tuprolog.core.TermVisitor import it.unibo.tuprolog.core.Tuple internal class BlockUnfolder(block: Block) : Iterator { - private var current: Term? = block private var setUnfolded = false override fun hasNext(): Boolean = current != null - private val tupleUnfolderVisitor = object : TermVisitor { - override fun visitTuple(term: Tuple): Term { - current = term.right - return term - } - - override fun defaultValue(term: Term): Term { - current = null - return term - } - } - - private val blockUnfolderVisitor = object : TermVisitor { - override fun visitEmptyBlock(term: EmptyBlock): Term { - current = null - return term - } - - override fun visitBlock(term: Block): Term { - current = term[0] - setUnfolded = true - return term + private val tupleUnfolderVisitor = + object : TermVisitor { + override fun visitTuple(term: Tuple): Term { + current = term.right + return term + } + + override fun defaultValue(term: Term): Term { + current = null + return term + } } - override fun defaultValue(term: Term): Term { - current = null - return term + private val blockUnfolderVisitor = + object : TermVisitor { + override fun visitEmptyBlock(term: EmptyBlock): Term { + current = null + return term + } + + override fun visitBlock(term: Block): Term { + current = term[0] + setUnfolded = true + return term + } + + override fun defaultValue(term: Term): Term { + current = null + return term + } } - } override fun next(): Term = - current?.accept(if (setUnfolded) tupleUnfolderVisitor else blockUnfolderVisitor) ?: throw NoSuchElementException() + current?.accept(if (setUnfolded) tupleUnfolderVisitor else blockUnfolderVisitor) + ?: throw NoSuchElementException() } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/ClauseImpl.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/ClauseImpl.kt index 1502dfbad..8ecba6e44 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/ClauseImpl.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/ClauseImpl.kt @@ -15,9 +15,8 @@ import it.unibo.tuprolog.utils.insertAt internal abstract class ClauseImpl( override val head: Struct?, override val body: Term, - tags: Map + tags: Map, ) : AbstractStruct(CLAUSE_FUNCTOR, (if (head === null) listOf(body) else listOf(head, body)), tags), Clause { - override val isWellFormed: Boolean by lazy { body.accept(bodyWellFormedVisitor) } override val functor: String = super.functor @@ -35,23 +34,25 @@ internal abstract class ClauseImpl( override fun freshCopy(scope: Scope): Clause = super.freshCopy(scope).castToClause() private val bodyItemsSequence: Sequence - get() = body.let { - when { - it.isTuple -> it.castToTuple().toSequence() - else -> sequenceOf(it) + get() = + body.let { + when { + it.isTuple -> it.castToTuple().toSequence() + else -> sequenceOf(it) + } } - } override val bodyItems: Iterable get() = bodyItemsSequence.asIterable() override val bodySize: Int - get() = body.let { - when { - it.isTuple -> it.castToTuple().size - else -> 1 + get() = + body.let { + when { + it.isTuple -> it.castToTuple().size + else -> 1 + } } - } override val bodyAsTuple: Tuple? get() = body.asTuple() @@ -80,7 +81,10 @@ internal abstract class ClauseImpl( override fun setHeadArgs(arguments: Sequence): Clause = of(head?.setArgs(arguments), body) - override fun insertHeadArg(index: Int, argument: Term): Clause = of(head?.insertAt(index, argument), body) + override fun insertHeadArg( + index: Int, + argument: Term, + ): Clause = of(head?.insertAt(index, argument), body) override fun addFirstHeadArg(argument: Term): Clause = of(head?.addFirst(argument), body) @@ -88,13 +92,19 @@ internal abstract class ClauseImpl( override fun appendHeadArg(argument: Term): Clause = addLastHeadArg(argument) - override fun setBodyItems(argument: Term, vararg arguments: Term): Clause = of(head, argument, *arguments) + override fun setBodyItems( + argument: Term, + vararg arguments: Term, + ): Clause = of(head, argument, *arguments) override fun setBodyItems(arguments: Iterable): Clause = of(head, arguments) override fun setBodyItems(arguments: Sequence): Clause = of(head, arguments) - override fun insertBodyItem(index: Int, argument: Term): Clause { + override fun insertBodyItem( + index: Int, + argument: Term, + ): Clause { ensureIndexIsInBodyRange(index) return of(head, bodyItemsSequence.insertAt(index, argument)) } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/ConsImpl.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/ConsImpl.kt index 6ea7cedcb..fa89c897b 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/ConsImpl.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/ConsImpl.kt @@ -10,25 +10,27 @@ import it.unibo.tuprolog.utils.setTags internal class ConsImpl( override val head: Term, override val tail: Term, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : AbstractCons(listOf(head, tail), tags), Cons { - override val isGround: Boolean = checkGroundness() - override val last: Term = when { - tail.isList -> tail.castToList().last - else -> tail - } + override val last: Term = + when { + tail.isList -> tail.castToList().last + else -> tail + } - override val size: Int = when { - tail.isList -> 1 + tail.castToList().size - else -> 2 - } + override val size: Int = + when { + tail.isList -> 1 + tail.castToList().size + else -> 2 + } - override val isWellFormed: Boolean = when { - tail.isList -> tail.castToList().isWellFormed - else -> false - } + override val isWellFormed: Boolean = + when { + tail.isList -> tail.castToList().isWellFormed + else -> false + } override fun checkGroundness(): Boolean = head.isGround && tail.isGround @@ -43,11 +45,20 @@ internal class ConsImpl( } override fun copyWithTags(tags: Map): ConsImpl = - if (this.tags === tags) this else ConsImpl(head, tail, tags) + if (this.tags === tags) { + this + } else { + ConsImpl( + head, + tail, + tags, + ) + } - override fun freshCopy(scope: Scope): Cons = when { - isGround -> this - isWellFormed -> scope.listOf(toList().map { it.freshCopy(scope) }).setTags(tags).castToCons() - else -> scope.listFrom(unfoldedList.map { it.freshCopy(scope) }).setTags(tags).castToCons() - } + override fun freshCopy(scope: Scope): Cons = + when { + isGround -> this + isWellFormed -> scope.listOf(toList().map { it.freshCopy(scope) }).setTags(tags).castToCons() + else -> scope.listFrom(unfoldedList.map { it.freshCopy(scope) }).setTags(tags).castToCons() + } } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/DirectiveImpl.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/DirectiveImpl.kt index 97b68dd3b..5cc547e68 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/DirectiveImpl.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/DirectiveImpl.kt @@ -8,9 +8,8 @@ import it.unibo.tuprolog.core.TermVisitor internal class DirectiveImpl( override val body: Term, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : ClauseImpl(null, body, tags), Directive { - override val head: Struct? = super.head override fun copyWithTags(tags: Map): Directive = DirectiveImpl(body, tags) diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/EmptyBlockImpl.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/EmptyBlockImpl.kt index 132fa8234..e5ad5b7bd 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/EmptyBlockImpl.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/EmptyBlockImpl.kt @@ -7,9 +7,8 @@ import it.unibo.tuprolog.core.TermVisitor import it.unibo.tuprolog.core.Var internal class EmptyBlockImpl( - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : BlockImpl(null, tags), EmptyBlock { - override val args: List get() = emptyList() override val functor: String = super.functor diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/EmptyListImpl.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/EmptyListImpl.kt index 7a5df4729..974b98d56 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/EmptyListImpl.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/EmptyListImpl.kt @@ -7,9 +7,8 @@ import it.unibo.tuprolog.core.TermVisitor import it.unibo.tuprolog.core.Terms.EMPTY_LIST_FUNCTOR internal class EmptyListImpl( - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : AtomImpl(EMPTY_LIST_FUNCTOR, tags), EmptyList { - override val unfoldedList: List = listOf(this) override val unfoldedSequence: Sequence = sequenceOf(this) diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/FactImpl.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/FactImpl.kt index 4660b73bf..8341aa428 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/FactImpl.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/FactImpl.kt @@ -9,9 +9,8 @@ import it.unibo.tuprolog.core.Truth internal class FactImpl( override val head: Struct, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : RuleImpl(head, Truth.TRUE, tags), Fact { - override val isWellFormed: Boolean = true override val body: Term = super.body @@ -30,7 +29,10 @@ internal class FactImpl( override fun setHeadArgs(arguments: Sequence): Fact = super.setHeadArgs(arguments).castToFact() - override fun insertHeadArg(index: Int, argument: Term): Fact = super.insertHeadArg(index, argument).castToFact() + override fun insertHeadArg( + index: Int, + argument: Term, + ): Fact = super.insertHeadArg(index, argument).castToFact() override fun addFirstHeadArg(argument: Term): Fact = super.addFirstHeadArg(argument).castToFact() diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/IndicatorImpl.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/IndicatorImpl.kt index 4005e5f69..9cfbc9703 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/IndicatorImpl.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/IndicatorImpl.kt @@ -14,9 +14,8 @@ import it.unibo.tuprolog.core.Terms.INDICATOR_FUNCTOR internal class IndicatorImpl( override val nameTerm: Term, override val arityTerm: Term, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : AbstractStruct(INDICATOR_FUNCTOR, listOf(nameTerm, arityTerm), tags), Indicator { - override val functor: String get() = INDICATOR_FUNCTOR diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/IntegerImpl.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/IntegerImpl.kt index affc3cd6a..8a77fa205 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/IntegerImpl.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/IntegerImpl.kt @@ -11,9 +11,8 @@ import org.gciatto.kt.math.BigInteger @Suppress("EqualsOrHashCode") internal class IntegerImpl( override val value: BigInteger, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : NumericImpl(tags), Integer { - override val decimalValue: BigDecimal by lazy { BigDecimal.of(intValue) } override val intValue: BigInteger = value @@ -28,11 +27,12 @@ internal class IntegerImpl( } @Suppress("NOTHING_TO_INLINE") - private inline fun equalsToInteger(other: Integer) = - value.compareTo(other.value) == 0 + private inline fun equalsToInteger(other: Integer) = value.compareTo(other.value) == 0 - override fun equals(other: Term, useVarCompleteName: Boolean): Boolean = - other.isInteger && equalsToInteger(other.castToInteger()) + override fun equals( + other: Term, + useVarCompleteName: Boolean, + ): Boolean = other.isInteger && equalsToInteger(other.castToInteger()) override val hashCodeCache: Int by lazy { value.hashCode() } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/LazyConsWithExplicitLast.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/LazyConsWithExplicitLast.kt index f38fb580e..e6327f36c 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/LazyConsWithExplicitLast.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/LazyConsWithExplicitLast.kt @@ -13,9 +13,8 @@ import it.unibo.tuprolog.utils.setTags internal class LazyConsWithExplicitLast( private val cursor: Cursor, private val termination: Term = EmptyList.instance, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : AbstractCons(emptyList(), tags), Cons { - override val head: Term get() = cursor.current!! @@ -54,6 +53,6 @@ internal class LazyConsWithExplicitLast( override fun freshCopy(scope: Scope): Cons = LazyConsWithExplicitLast( unfoldedSequence.dropLast().map { it.freshCopy(scope) }.cursor(), - last.freshCopy(scope) + last.freshCopy(scope), ).setTags(tags).castToCons() } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/LazyConsWithImplicitLast.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/LazyConsWithImplicitLast.kt index 3c0d9e7bd..9cb0a4418 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/LazyConsWithImplicitLast.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/LazyConsWithImplicitLast.kt @@ -11,9 +11,8 @@ import it.unibo.tuprolog.utils.setTags internal class LazyConsWithImplicitLast( private val cursor: Cursor, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : AbstractCons(emptyList(), tags), Cons { - override val head: Term by lazy { cursor.current!! } override val tail: Term by lazy { diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/ListUnfolder.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/ListUnfolder.kt index 85841bdeb..c938c7846 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/ListUnfolder.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/ListUnfolder.kt @@ -7,7 +7,6 @@ import it.unibo.tuprolog.core.Term import it.unibo.tuprolog.core.TermVisitor internal class ListUnfolder(list: List) : Iterator { - private var current: Term? = list override fun hasNext(): Boolean = current != null @@ -16,20 +15,21 @@ internal class ListUnfolder(list: List) : Iterator { return current?.accept(listUnfolderVisitor) ?: throw NoSuchElementException() } - private val listUnfolderVisitor = object : TermVisitor { - override fun visitCons(term: Cons): Term { - current = term.tail - return term - } - - override fun visitEmptyList(term: EmptyList): Term { - current = null - return term + private val listUnfolderVisitor = + object : TermVisitor { + override fun visitCons(term: Cons): Term { + current = term.tail + return term + } + + override fun visitEmptyList(term: EmptyList): Term { + current = null + return term + } + + override fun defaultValue(term: Term): Term { + current = null + return term + } } - - override fun defaultValue(term: Term): Term { - current = null - return term - } - } } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/NumericImpl.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/NumericImpl.kt index e7d1f39f1..c81e40b09 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/NumericImpl.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/NumericImpl.kt @@ -9,7 +9,6 @@ import org.gciatto.kt.math.BigInteger @Suppress("EqualsOrHashCode") internal abstract class NumericImpl(tags: Map) : TermImpl(tags), Numeric { - override fun structurallyEquals(other: Term): Boolean = other.isNumber && decimalValue.compareTo(other.castToNumeric().decimalValue) == 0 @@ -19,7 +18,10 @@ internal abstract class NumericImpl(tags: Map) : TermImpl(tags), Nu abstract override fun equals(other: Any?): Boolean - abstract override fun equals(other: Term, useVarCompleteName: Boolean): Boolean + abstract override fun equals( + other: Term, + useVarCompleteName: Boolean, + ): Boolean abstract override fun copyWithTags(tags: Map): Numeric diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/RealImpl.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/RealImpl.kt index 1f8a00eae..f3e81d303 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/RealImpl.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/RealImpl.kt @@ -10,9 +10,8 @@ import org.gciatto.kt.math.BigInteger @Suppress("EqualsOrHashCode") internal class RealImpl( override val value: BigDecimal, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : NumericImpl(tags), Real { - override val decimalValue: BigDecimal get() = value @@ -28,11 +27,12 @@ internal class RealImpl( } @Suppress("NOTHING_TO_INLINE") - private inline fun equalsToReal(other: Real) = - value.compareTo(other.value) == 0 + private inline fun equalsToReal(other: Real) = value.compareTo(other.value) == 0 - override fun equals(other: Term, useVarCompleteName: Boolean): Boolean = - other.isReal && equalsToReal(other.castToReal()) + override fun equals( + other: Term, + useVarCompleteName: Boolean, + ): Boolean = other.isReal && equalsToReal(other.castToReal()) override val hashCodeCache: Int by lazy { value.stripTrailingZeros().hashCode() } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/RecursiveImpl.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/RecursiveImpl.kt index 5d352308a..1b0b781c2 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/RecursiveImpl.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/RecursiveImpl.kt @@ -15,9 +15,8 @@ import kotlin.collections.List as KtList internal abstract class RecursiveImpl( functor: String, args: KtList, - tags: Map + tags: Map, ) : AbstractStruct(functor, args, tags), Recursive { - override val unfoldedList: KtList by lazy { dequeOf(unfoldedSequence) } override val unfoldedArray: Array @@ -49,7 +48,10 @@ internal abstract class RecursiveImpl( } } ?: false - override fun itemsAreEqual(other: Struct, useVarCompleteName: Boolean): Boolean = + override fun itemsAreEqual( + other: Struct, + useVarCompleteName: Boolean, + ): Boolean = other.asRecursive()?.let { itemWiseEquals(unfoldedSequence, it.unfoldedSequence) { a, b -> a.equals(b, useVarCompleteName) @@ -59,73 +61,78 @@ internal abstract class RecursiveImpl( override fun accept(visitor: TermVisitor): T = visitor.visitCollection(this) protected class LazyTwoItemsList(firstGenerator: () -> T, secondGenerator: () -> T) : KtList { - private val first: T by lazy(firstGenerator) + private val fst: T by lazy(firstGenerator) - private val second: T by lazy(secondGenerator) + private val snd: T by lazy(secondGenerator) override val size: Int get() = 2 - override fun contains(element: T): Boolean = - first == element || second == element + override fun contains(element: T): Boolean = fst == element || snd == element - override fun containsAll(elements: KtCollection): Boolean = - elements.any { contains(it) } + override fun containsAll(elements: KtCollection): Boolean = elements.any { contains(it) } - override fun get(index: Int): T = when (index) { - 0 -> first - 1 -> second - else -> throw IndexOutOfBoundsException("Index out of range: $index") - } + override fun get(index: Int): T = + when (index) { + 0 -> fst + 1 -> snd + else -> throw IndexOutOfBoundsException("Index out of range: $index") + } - override fun indexOf(element: T): Int = when (element) { - first -> 0 - second -> 1 - else -> -1 - } + override fun indexOf(element: T): Int = + when (element) { + fst -> 0 + snd -> 1 + else -> -1 + } override fun isEmpty(): Boolean = false - override fun iterator(): Iterator = iterator { - yield(first) - yield(second) - } + override fun iterator(): Iterator = + iterator { + yield(fst) + yield(snd) + } - override fun lastIndexOf(element: T): Int = when (element) { - second -> 1 - first -> 0 - else -> -1 - } + override fun lastIndexOf(element: T): Int = + when (element) { + snd -> 1 + fst -> 0 + else -> -1 + } override fun listIterator(): ListIterator = listIterator(0) - override fun listIterator(index: Int): ListIterator = object : ListIterator { - private var currentIndex = index + override fun listIterator(index: Int): ListIterator = + object : ListIterator { + private var currentIndex = index - override fun hasNext(): Boolean = currentIndex < size + override fun hasNext(): Boolean = currentIndex < size - override fun hasPrevious(): Boolean = currentIndex > 0 + override fun hasPrevious(): Boolean = currentIndex > 0 - override fun next(): T = - if (hasNext()) { - get(currentIndex++) - } else { - throw NoSuchElementException() - } + override fun next(): T = + if (hasNext()) { + get(currentIndex++) + } else { + throw NoSuchElementException() + } - override fun nextIndex(): Int = index + 1 + override fun nextIndex(): Int = index + 1 - override fun previous(): T = - if (hasPrevious()) { - get(currentIndex--) - } else { - throw NoSuchElementException() - } + override fun previous(): T = + if (hasPrevious()) { + get(currentIndex--) + } else { + throw NoSuchElementException() + } - override fun previousIndex(): Int = currentIndex - 1 - } + override fun previousIndex(): Int = currentIndex - 1 + } - override fun subList(fromIndex: Int, toIndex: Int): KtList = - (fromIndex until toIndex).map { get(it) } + override fun subList( + fromIndex: Int, + toIndex: Int, + ): KtList = (fromIndex until toIndex).map { get(it) } } } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/RuleImpl.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/RuleImpl.kt index e5d3675d6..6e4fa9491 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/RuleImpl.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/RuleImpl.kt @@ -9,9 +9,8 @@ import it.unibo.tuprolog.core.TermVisitor internal open class RuleImpl( override val head: Struct, override val body: Term, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : ClauseImpl(head, body, tags), Rule { - override fun copyWithTags(tags: Map): Rule = RuleImpl(head, body, tags) override fun freshCopy(): Rule = super.freshCopy().castToRule() @@ -36,7 +35,10 @@ internal open class RuleImpl( override fun setHeadArgs(arguments: Sequence): Rule = super.setHeadArgs(arguments).castToRule() - override fun insertHeadArg(index: Int, argument: Term): Rule = super.insertHeadArg(index, argument).castToRule() + override fun insertHeadArg( + index: Int, + argument: Term, + ): Rule = super.insertHeadArg(index, argument).castToRule() override fun addFirstHeadArg(argument: Term): Rule = super.addFirstHeadArg(argument).castToRule() @@ -44,14 +46,19 @@ internal open class RuleImpl( override fun appendHeadArg(argument: Term): Rule = super.appendHeadArg(argument).castToRule() - override fun setBodyItems(argument: Term, vararg arguments: Term): Rule = - super.setBodyItems(argument, *arguments).castToRule() + override fun setBodyItems( + argument: Term, + vararg arguments: Term, + ): Rule = super.setBodyItems(argument, *arguments).castToRule() override fun setBodyItems(arguments: Iterable): Rule = super.setBodyItems(arguments).castToRule() override fun setBodyItems(arguments: Sequence): Rule = super.setBodyItems(arguments).castToRule() - override fun insertBodyItem(index: Int, argument: Term): Rule = super.insertBodyItem(index, argument).castToRule() + override fun insertBodyItem( + index: Int, + argument: Term, + ): Rule = super.insertBodyItem(index, argument).castToRule() override fun addFirstBodyItem(argument: Term): Rule = super.addFirstBodyItem(argument).castToRule() diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/ScopeImpl.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/ScopeImpl.kt index a5fc1749d..0a1bb8d2b 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/ScopeImpl.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/ScopeImpl.kt @@ -27,7 +27,6 @@ import it.unibo.tuprolog.core.List as LogicList @Suppress("RemoveRedundantQualifierName") internal class ScopeImpl(private val _variables: MutableMap) : Scope { - override fun contains(variable: Var): Boolean = _variables.containsKey(variable.name) override fun contains(variable: String): Boolean = _variables.containsKey(variable) @@ -37,18 +36,17 @@ internal class ScopeImpl(private val _variables: MutableMap) : Scop override val variables: Map get() = _variables.toMap() - override fun varOf(name: String): Var = synchronizedOnSelf { - if (!_variables.containsKey(name)) { - _variables[name] = Var.of(name) + override fun varOf(name: String): Var = + synchronizedOnSelf { + if (!_variables.containsKey(name)) { + _variables[name] = Var.of(name) + } + _variables[name]!! } - _variables[name]!! - } - override fun where(lambda: Scope.() -> Unit): Scope = - this.also(lambda) + override fun where(lambda: Scope.() -> Unit): Scope = this.also(lambda) - override fun with(lambda: Scope.() -> R): R = - with(this, lambda) + override fun with(lambda: Scope.() -> R): R = with(this, lambda) override fun equals(other: Any?): Boolean { if (this === other) return true @@ -61,43 +59,37 @@ internal class ScopeImpl(private val _variables: MutableMap) : Scop return true } - override fun hashCode(): Int = - _variables.hashCode() + override fun hashCode(): Int = _variables.hashCode() - override fun toString(): String = - variables.toString() + override fun toString(): String = variables.toString() - override fun truthOf(value: Boolean): Truth = - Truth.of(value) + override fun truthOf(value: Boolean): Truth = Truth.of(value) override val fail: Truth get() = Truth.FAIL - override fun blockOf(terms: Iterable): Block = - Block.of(terms) + override fun blockOf(terms: Iterable): Block = Block.of(terms) - override fun blockOf(terms: Sequence): Block = - Block.of(terms) + override fun blockOf(terms: Sequence): Block = Block.of(terms) override fun ktSetOf(vararg items: T): Set = kotlin.collections.setOf(*items) override fun ktEmptySet(): Set = kotlin.collections.emptySet() - override fun blockOf(vararg terms: Term): Block = - Block.of(*terms) + override fun blockOf(vararg terms: Term): Block = Block.of(*terms) - override fun listOf(terms: Iterable): LogicList = - LogicList.of(terms) + override fun listOf(terms: Iterable): LogicList = LogicList.of(terms) - override fun listOf(terms: Sequence): LogicList = - LogicList.of(terms) + override fun listOf(terms: Sequence): LogicList = LogicList.of(terms) override fun ktListOf(vararg items: T): List = kotlin.collections.listOf(*items) override fun ktEmptyList(): List = kotlin.collections.emptyList() - override fun List.append(item: T, vararg items: T): List = - concat(ktListOf(item, *items)) + override fun List.append( + item: T, + vararg items: T, + ): List = concat(ktListOf(item, *items)) override fun List.concat(other: Iterable): List = plus(other) @@ -107,146 +99,152 @@ internal class ScopeImpl(private val _variables: MutableMap) : Scop override val emptyBlock: EmptyBlock get() = EmptyBlock() - override fun listOf(vararg terms: Term): LogicList = - LogicList.of(*terms) + override fun listOf(vararg terms: Term): LogicList = LogicList.of(*terms) - override fun listFrom(vararg terms: Term, last: Term?): LogicList = - LogicList.from(*terms, last = last) + override fun listFrom( + vararg terms: Term, + last: Term?, + ): LogicList = LogicList.from(*terms, last = last) - override fun listFrom(terms: Sequence, last: Term?): LogicList = - LogicList.from(terms, last) + override fun listFrom( + terms: Sequence, + last: Term?, + ): LogicList = LogicList.from(terms, last) - override fun listFrom(terms: Iterable, last: Term?): LogicList = - LogicList.from(terms, last) + override fun listFrom( + terms: Iterable, + last: Term?, + ): LogicList = LogicList.from(terms, last) - override fun tupleOf(terms: Iterable): Tuple = - Tuple.of(terms.toList()) + override fun tupleOf(terms: Iterable): Tuple = Tuple.of(terms.toList()) - override fun tupleOf(terms: Sequence): Tuple = - Tuple.of(terms.toList()) + override fun tupleOf(terms: Sequence): Tuple = Tuple.of(terms.toList()) - override fun tupleOf(vararg terms: Term): Tuple = - Tuple.of(terms.toList()) + override fun tupleOf(vararg terms: Term): Tuple = Tuple.of(terms.toList()) - override fun atomOf(value: String): Atom = - Atom.of(value) + override fun atomOf(value: String): Atom = Atom.of(value) - override fun structOf(functor: String, vararg args: Term): Struct = - Struct.of(functor, *args) + override fun structOf( + functor: String, + vararg args: Term, + ): Struct = Struct.of(functor, *args) - override fun structOf(functor: String, args: Sequence): Struct = - Struct.of(functor, args) + override fun structOf( + functor: String, + args: Sequence, + ): Struct = Struct.of(functor, args) - override fun structOf(functor: String, args: Iterable): Struct = - Struct.of(functor, args) + override fun structOf( + functor: String, + args: Iterable, + ): Struct = Struct.of(functor, args) - override fun structOf(functor: String, args: List): Struct = - Struct.of(functor, args) + override fun structOf( + functor: String, + args: List, + ): Struct = Struct.of(functor, args) - override fun factOf(head: Struct): Fact = - Fact.of(head) + override fun factOf(head: Struct): Fact = Fact.of(head) - override fun ruleOf(head: Struct, body1: Term, vararg body: Term): Rule = - Rule.of(head, body1, *body) + override fun ruleOf( + head: Struct, + body1: Term, + vararg body: Term, + ): Rule = Rule.of(head, body1, *body) - override fun directiveOf(body1: Term, vararg body: Term): Directive = - Directive.of(body1, *body) + override fun directiveOf( + body1: Term, + vararg body: Term, + ): Directive = Directive.of(body1, *body) - override fun clauseOf(head: Struct?, vararg body: Term): Clause = - Clause.of(head, *body) + override fun clauseOf( + head: Struct?, + vararg body: Term, + ): Clause = Clause.of(head, *body) - override fun consOf(head: Term, tail: Term): Cons = - Cons.of(head, tail) + override fun consOf( + head: Term, + tail: Term, + ): Cons = Cons.of(head, tail) - override fun indicatorOf(name: Term, arity: Term): Indicator = - Indicator.of(name, arity) + override fun indicatorOf( + name: Term, + arity: Term, + ): Indicator = Indicator.of(name, arity) - override fun indicatorOf(name: String, arity: Int): Indicator = - Indicator.of(name, arity) + override fun indicatorOf( + name: String, + arity: Int, + ): Indicator = Indicator.of(name, arity) - override fun anonymous(): Var = - Var.anonymous() + override fun anonymous(): Var = Var.anonymous() - override fun whatever(): Var = - anonymous() + override fun whatever(): Var = anonymous() - override fun numOf(value: BigDecimal): Real = - Numeric.of(value) + override fun numOf(value: BigDecimal): Real = Numeric.of(value) - override fun numOf(value: Double): Real = - Numeric.of(value) + override fun numOf(value: Double): Real = Numeric.of(value) - override fun numOf(value: Float): Real = - Numeric.of(value) + override fun numOf(value: Float): Real = Numeric.of(value) - override fun numOf(value: BigInteger): Integer = - Numeric.of(value) + override fun numOf(value: BigInteger): Integer = Numeric.of(value) - override fun numOf(value: Int): Integer = - Numeric.of(value) + override fun numOf(value: Int): Integer = Numeric.of(value) - override fun numOf(value: Long): Integer = - Numeric.of(value) + override fun numOf(value: Long): Integer = Numeric.of(value) - override fun numOf(value: Short): Integer = - Numeric.of(value) + override fun numOf(value: Short): Integer = Numeric.of(value) - override fun numOf(value: Byte): Integer = - Numeric.of(value) + override fun numOf(value: Byte): Integer = Numeric.of(value) - override fun numOf(value: String): Numeric = - Numeric.of(value) + override fun numOf(value: String): Numeric = Numeric.of(value) - override fun numOf(value: Number): Numeric = - Numeric.of(value) + override fun numOf(value: Number): Numeric = Numeric.of(value) - override fun intOf(value: BigInteger): Integer = - Integer.of(value) + override fun intOf(value: BigInteger): Integer = Integer.of(value) - override fun intOf(value: Int): Integer = - Integer.of(value) + override fun intOf(value: Int): Integer = Integer.of(value) - override fun intOf(value: Long): Integer = - Integer.of(value) + override fun intOf(value: Long): Integer = Integer.of(value) - override fun intOf(value: Short): Integer = - Integer.of(value) + override fun intOf(value: Short): Integer = Integer.of(value) - override fun intOf(value: Byte): Integer = - Integer.of(value) + override fun intOf(value: Byte): Integer = Integer.of(value) - override fun intOf(value: String): Integer = - Integer.of(value) + override fun intOf(value: String): Integer = Integer.of(value) - override fun intOf(value: String, radix: Int): Integer = - Integer.of(value, radix) + override fun intOf( + value: String, + radix: Int, + ): Integer = Integer.of(value, radix) - override fun realOf(value: BigDecimal): Real = - Real.of(value) + override fun realOf(value: BigDecimal): Real = Real.of(value) - override fun realOf(value: Double): Real = - Real.of(value) + override fun realOf(value: Double): Real = Real.of(value) - override fun realOf(value: Float): Real = - Real.of(value) + override fun realOf(value: Float): Real = Real.of(value) - override fun realOf(value: String): Real = - Real.of(value) + override fun realOf(value: String): Real = Real.of(value) override fun unifierOf(assignments: Iterable>): Substitution.Unifier = - Substitution.unifier(assignments) + Substitution.unifier( + assignments, + ) override fun unifierOf(assignments: Sequence>): Substitution.Unifier = - unifierOf(assignments.asIterable()) + unifierOf( + assignments.asIterable(), + ) override fun unifierOf(vararg assignments: Pair): Substitution.Unifier = unifierOf(assignments.map { (v, t) -> varOf(v) to t }) - override fun substitutionOf(assignments: Iterable>): Substitution = - Substitution.of(assignments) + override fun substitutionOf(assignments: Iterable>): Substitution = Substitution.of(assignments) override fun substitutionOf(assignments: Sequence>): Substitution = - substitutionOf(assignments.asIterable()) + substitutionOf( + assignments.asIterable(), + ) override fun substitutionOf(vararg assignments: Pair): Substitution = substitutionOf(assignments.map { (v, t) -> varOf(v) to t }) diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/SimpleTermFormatter.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/SimpleTermFormatter.kt index d45187b24..37a21f68e 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/SimpleTermFormatter.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/SimpleTermFormatter.kt @@ -3,5 +3,5 @@ package it.unibo.tuprolog.core.impl internal class SimpleTermFormatter( quoted: Boolean = true, numberVars: Boolean = false, - ignoreOps: Boolean = false + ignoreOps: Boolean = false, ) : AbstractTermFormatter(quoted, numberVars, ignoreOps) diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/StructImpl.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/StructImpl.kt index 5fe2eda62..f8c13f143 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/StructImpl.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/StructImpl.kt @@ -6,13 +6,12 @@ import it.unibo.tuprolog.core.Term internal class StructImpl( override val functor: String, override val args: List, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : AbstractStruct(functor, args, tags) { constructor(functor: String, args: Array, tags: Map = emptyMap()) : this(functor, listOf(*args), tags) override val isGround: Boolean by lazy { checkGroundness() } - override fun copyWithTags(tags: Map): Struct = - StructImpl(functor, args, tags) + override fun copyWithTags(tags: Map): Struct = StructImpl(functor, args, tags) } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TermFormatterWithAnonymousVariables.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TermFormatterWithAnonymousVariables.kt index 9ffcc61d8..d28f9e4c0 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TermFormatterWithAnonymousVariables.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TermFormatterWithAnonymousVariables.kt @@ -5,8 +5,7 @@ import it.unibo.tuprolog.core.Var internal class TermFormatterWithAnonymousVariables( quoted: Boolean = true, numberVars: Boolean = false, - ignoreOps: Boolean = false + ignoreOps: Boolean = false, ) : AbstractTermFormatter(quoted, numberVars, ignoreOps) { - override fun visitVar(term: Var): String = "_${term.id}" } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TermFormatterWithPrettyExpressions.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TermFormatterWithPrettyExpressions.kt index 0052597f1..48082f52c 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TermFormatterWithPrettyExpressions.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TermFormatterWithPrettyExpressions.kt @@ -23,19 +23,19 @@ internal class TermFormatterWithPrettyExpressions private constructor( private val forceParentheses: Set, quoted: Boolean = true, numberVars: Boolean = false, - ignoreOps: Boolean = false + ignoreOps: Boolean = false, ) : AbstractTermFormatter(quoted, numberVars, ignoreOps) { - companion object { private data class OperatorDecorations(val prefix: String, val suffix: String) private val defaultDecorations = OperatorDecorations(" ", " ") - private val adHocDecorations: Map = mapOf( - "," to OperatorDecorations("", " "), - ";" to OperatorDecorations("", " "), - "\\+" to OperatorDecorations("", " ") - ) + private val adHocDecorations: Map = + mapOf( + "," to OperatorDecorations("", " "), + ";" to OperatorDecorations("", " "), + "\\+" to OperatorDecorations("", " "), + ) private val String.decorations: OperatorDecorations get() = adHocDecorations[this] ?: defaultDecorations @@ -52,26 +52,20 @@ internal class TermFormatterWithPrettyExpressions private constructor( operators: OperatorSet, quoted: Boolean = true, numberVars: Boolean = false, - ignoreOps: Boolean = false + ignoreOps: Boolean = false, ) : this(Int.MAX_VALUE, delegate, operators.toOperatorsIndex(), emptySet(), quoted, numberVars, ignoreOps) - override fun visitVar(term: Var): String = - term.accept(delegate) + override fun visitVar(term: Var): String = term.accept(delegate) - override fun visitAtom(term: Atom): String = - term.accept(delegate) + override fun visitAtom(term: Atom): String = term.accept(delegate) - override fun visitInteger(term: Integer): String = - term.accept(delegate) + override fun visitInteger(term: Integer): String = term.accept(delegate) - override fun visitReal(term: Real): String = - term.accept(delegate) + override fun visitReal(term: Real): String = term.accept(delegate) - override fun visitEmptyBlock(term: EmptyBlock): String = - term.accept(delegate) + override fun visitEmptyBlock(term: EmptyBlock): String = term.accept(delegate) - override fun visitEmptyList(term: EmptyList): String = - term.accept(delegate) + override fun visitEmptyList(term: EmptyList): String = term.accept(delegate) override fun visitStruct(term: Struct): String = if (term.functor.isOperator()) { @@ -82,7 +76,10 @@ internal class TermFormatterWithPrettyExpressions private constructor( private fun String.wrapWithinParentheses(): String = "($this)" - private fun addingParenthesesIfForced(struct: Struct, stringGenerator: Struct.() -> String): String { + private fun addingParenthesesIfForced( + struct: Struct, + stringGenerator: Struct.() -> String, + ): String { val string = struct.stringGenerator() if (struct.functor in forceParentheses) { return string.wrapWithinParentheses() @@ -92,9 +89,10 @@ internal class TermFormatterWithPrettyExpressions private constructor( override fun visitTuple(term: Tuple): String { val op = TUPLE_FUNCTOR - val string = term.unfoldedSequence - .map { it.accept(itemFormatter()) } - .joinToString("${op.prefix}$op${op.suffix}") + val string = + term.unfoldedSequence + .map { it.accept(itemFormatter()) } + .joinToString("${op.prefix}$op${op.suffix}") if (op in forceParentheses) { return string.wrapWithinParentheses() } @@ -133,31 +131,43 @@ internal class TermFormatterWithPrettyExpressions private constructor( override fun childFormatter(): TermFormatter = childFormatter(Int.MAX_VALUE, setOf(",")) - private fun childFormatter(priority: Int, forceParentheses: Set = emptySet()): TermFormatter = - TermFormatterWithPrettyExpressions(priority, delegate, operators, forceParentheses, quoted, numberVars, ignoreOps) + private fun childFormatter( + priority: Int, + forceParentheses: Set = emptySet(), + ): TermFormatter = + TermFormatterWithPrettyExpressions( + priority, + delegate, + operators, + forceParentheses, + quoted, + numberVars, + ignoreOps, + ) private fun String.isOperator() = operators.containsKey(this) private fun OperatorsIndex.getSpecifierAndIndex( functor: String, priorityPredicate: (Int) -> Boolean, - specifierPredicate: Specifier.() -> Boolean - ): Pair? = this[functor]?.asSequence() - ?.filter { it.key.specifierPredicate() && priorityPredicate(it.value) } - ?.filter { it.key.name !in forceParentheses } - ?.map { it.toPair() } - ?.firstOrNull() + specifierPredicate: Specifier.() -> Boolean, + ): Pair? = + this[functor]?.asSequence() + ?.filter { it.key.specifierPredicate() && priorityPredicate(it.value) } + ?.filter { it.key.name !in forceParentheses } + ?.map { it.toPair() } + ?.firstOrNull() private fun OperatorsIndex.getSpecifierAndIndexWithNonGreaterPriority( functor: String, priority: Int, - specifierPredicate: Specifier.() -> Boolean + specifierPredicate: Specifier.() -> Boolean, ): Pair? = getSpecifierAndIndex(functor, { it <= priority }, specifierPredicate) private fun OperatorsIndex.getSpecifierAndIndexWithGreaterPriority( functor: String, priority: Int, - specifierPredicate: Specifier.() -> Boolean + specifierPredicate: Specifier.() -> Boolean, ): Pair? = getSpecifierAndIndex(functor, { it > priority }, specifierPredicate) private fun Struct.isPrefix(): Pair? = diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TermFormatterWithPrettyVariables.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TermFormatterWithPrettyVariables.kt index 8c0461791..ea613a3ff 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TermFormatterWithPrettyVariables.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TermFormatterWithPrettyVariables.kt @@ -5,10 +5,12 @@ import it.unibo.tuprolog.core.Var internal class TermFormatterWithPrettyVariables( quoted: Boolean = true, numberVars: Boolean = false, - ignoreOps: Boolean = false + ignoreOps: Boolean = false, ) : AbstractTermFormatterForVariables(quoted, numberVars, ignoreOps) { - - override fun formatVar(variable: Var, suffix: String): String { + override fun formatVar( + variable: Var, + suffix: String, + ): String { val baseName = variable.name + suffix return if (variable.isNameWellFormed) { baseName diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TermImpl.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TermImpl.kt index fbe1c6e4a..e273af9e1 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TermImpl.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TermImpl.kt @@ -8,7 +8,6 @@ import kotlin.js.JsName @Suppress("EqualsOrHashCode") internal abstract class TermImpl(override val tags: Map = emptyMap()) : Term { - @JsName("termMark") val termMark: Int get() = MARK @@ -17,7 +16,10 @@ internal abstract class TermImpl(override val tags: Map = emptyMap( final override fun hashCode(): Int = hashCodeCache - abstract override fun equals(other: Term, useVarCompleteName: Boolean): Boolean + abstract override fun equals( + other: Term, + useVarCompleteName: Boolean, + ): Boolean abstract override fun toString(): String @@ -34,16 +36,17 @@ internal abstract class TermImpl(override val tags: Map = emptyMap( protected abstract fun copyWithTags(tags: Map): Term - override fun apply(substitution: Substitution): Term = when { - substitution.isSuccess -> { - if (isUnifierSkippable(substitution.castToUnifier())) { - this - } else { - applyNonEmptyUnifier(substitution.castToUnifier()) + override fun apply(substitution: Substitution): Term = + when { + substitution.isSuccess -> { + if (isUnifierSkippable(substitution.castToUnifier())) { + this + } else { + applyNonEmptyUnifier(substitution.castToUnifier()) + } } + else -> throw SubstitutionApplicationException(this, substitution) } - else -> throw SubstitutionApplicationException(this, substitution) - } protected open fun isUnifierSkippable(unifier: Substitution.Unifier): Boolean = unifier.isEmpty() || this.isGround diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TruthImpl.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TruthImpl.kt index cb3d42498..432ec0f33 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TruthImpl.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TruthImpl.kt @@ -7,9 +7,8 @@ import it.unibo.tuprolog.core.Truth internal class TruthImpl( value: String, override val isTrue: Boolean, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : Truth, AtomImpl(value, tags) { - override fun toString(): String = value override fun copyWithTags(tags: Map): Truth = TruthImpl(value, isTrue, tags) diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TupleImpl.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TupleImpl.kt index b3f446d83..7ef65144a 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TupleImpl.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TupleImpl.kt @@ -11,9 +11,8 @@ import it.unibo.tuprolog.utils.setTags internal class TupleImpl( override val left: Term, override val right: Term, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : RecursiveImpl(TUPLE_FUNCTOR, listOf(left, right), tags), Tuple { - override val isGround: Boolean = checkGroundness() override fun checkGroundness(): Boolean = left.isGround && right.isGround diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TupleUnfolder.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TupleUnfolder.kt index 525d607f4..5b5d2446d 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TupleUnfolder.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/TupleUnfolder.kt @@ -5,22 +5,22 @@ import it.unibo.tuprolog.core.TermVisitor import it.unibo.tuprolog.core.Tuple internal class TupleUnfolder(tuple: Tuple) : Iterator { - private var current: Term? = tuple override fun hasNext(): Boolean = current != null - private val tupleUnfolderVisitor = object : TermVisitor { - override fun visitTuple(term: Tuple): Term { - current = term.right - return term - } + private val tupleUnfolderVisitor = + object : TermVisitor { + override fun visitTuple(term: Tuple): Term { + current = term.right + return term + } - override fun defaultValue(term: Term): Term { - current = null - return term + override fun defaultValue(term: Term): Term { + current = null + return term + } } - } override fun next(): Term = current?.accept(tupleUnfolderVisitor) ?: throw NoSuchElementException() } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/VarImpl.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/VarImpl.kt index 28c27bad3..5a959769d 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/VarImpl.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/VarImpl.kt @@ -13,17 +13,17 @@ import it.unibo.tuprolog.utils.synchronizedOn internal class VarImpl( override val name: String, private val identifier: Long = instanceId(name), - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : TermImpl(tags), Var { - companion object { private val nameToInstanceCount = mutableMapOf() - private fun instanceId(name: String): Long = synchronizedOn(nameToInstanceCount) { - val count = nameToInstanceCount[name]?.let { it + 1 } ?: 0 - nameToInstanceCount[name] = count - count - } + private fun instanceId(name: String): Long = + synchronizedOn(nameToInstanceCount) { + val count = nameToInstanceCount[name]?.let { it + 1 } ?: 0 + nameToInstanceCount[name] = count + count + } } override val completeName: String by lazy { "${name}_$identifier" } @@ -58,15 +58,19 @@ internal class VarImpl( @Suppress("NOTHING_TO_INLINE") private inline fun equalsByCompleteName(other: Var) = completeName == other.completeName - private fun equalsToVar(other: Var, useVarCompleteName: Boolean) = - if (useVarCompleteName) { - completeName == other.completeName - } else { - name == other.name - } + private fun equalsToVar( + other: Var, + useVarCompleteName: Boolean, + ) = if (useVarCompleteName) { + completeName == other.completeName + } else { + name == other.name + } - override fun equals(other: Term, useVarCompleteName: Boolean): Boolean = - other.isVar && equalsToVar(other.castToVar(), useVarCompleteName) + override fun equals( + other: Term, + useVarCompleteName: Boolean, + ): Boolean = other.isVar && equalsToVar(other.castToVar(), useVarCompleteName) override val hashCodeCache: Int by lazy { completeName.hashCode() } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/VariablesProviderImpl.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/VariablesProviderImpl.kt index c272057a3..15194455f 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/VariablesProviderImpl.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/impl/VariablesProviderImpl.kt @@ -6,7 +6,10 @@ import it.unibo.tuprolog.core.VariablesProvider import kotlin.reflect.KProperty internal class VariablesProviderImpl(scope: Scope) : VariablesProvider, Scope by scope { - override fun getValue(thisRef: Any?, property: KProperty<*>): Var = varOf(property.name) + override fun getValue( + thisRef: Any?, + property: KProperty<*>, + ): Var = varOf(property.name) override val A: Var get() = varOf("A") diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/operators/Operator.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/operators/Operator.kt index ed60e4f9a..d86dcf918 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/operators/Operator.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/operators/Operator.kt @@ -14,21 +14,20 @@ import kotlin.jvm.JvmStatic /** Class representing a logic operator */ class Operator(val functor: String, val specifier: Specifier, val priority: Int) : Comparable, TermConvertible { - override fun compareTo(other: Operator): Int = when { priority > other.priority -> 1 priority < other.priority -> -1 - else -> specifier.compareTo(other.specifier).let { specifierCompareTo -> - when (specifierCompareTo) { - 0 -> functor.compareTo(other.functor) - else -> specifierCompareTo + else -> + specifier.compareTo(other.specifier).let { specifierCompareTo -> + when (specifierCompareTo) { + 0 -> functor.compareTo(other.functor) + else -> specifierCompareTo + } } - } } - override fun toTerm(): Struct = - Struct.of(FUNCTOR, priority.toTerm(), specifier.toTerm(), functor.toAtom()) + override fun toTerm(): Struct = Struct.of(FUNCTOR, priority.toTerm(), specifier.toTerm(), functor.toAtom()) override fun equals(other: Any?): Boolean { if (this === other) return true @@ -51,7 +50,6 @@ class Operator(val functor: String, val specifier: Specifier, val priority: Int) override fun toString(): String = "Operator($priority, $specifier, '$functor')" companion object { - /** The Operator functor */ const val FUNCTOR = "op" @@ -61,31 +59,35 @@ class Operator(val functor: String, val specifier: Specifier, val priority: Int) @JvmStatic @JsName("fromTerms") - fun fromTerms(priority: Integer, specifier: Atom, functor: Atom): Operator? = - fromTerm(Struct.of(FUNCTOR, priority, specifier, functor)) + fun fromTerms( + priority: Integer, + specifier: Atom, + functor: Atom, + ): Operator? = fromTerm(Struct.of(FUNCTOR, priority, specifier, functor)) /** Creates an Operator instance from a well-formed Struct, or returns `null` if it cannot be interpreted as Operator */ @JvmStatic @JsName("fromTerm") - fun fromTerm(struct: Struct): Operator? = with(struct) { - when { - functor == FUNCTOR && arity == 3 && - getArgAt(0).isInteger && getArgAt(1).isAtom && getArgAt(2).isAtom -> { - try { - Operator( - getArgAt(2).castToAtom().value, - Specifier.fromTerm(getArgAt(1)), - getArgAt(0).castToNumeric().intValue.toInt() - ) - } catch (ex: IllegalArgumentException) { - null - } catch (ex: IllegalStateException) { - // Enum.valueOf throws IllegalStateException instead of IllegalArgumentException - null + fun fromTerm(struct: Struct): Operator? = + with(struct) { + when { + functor == FUNCTOR && arity == 3 && + getArgAt(0).isInteger && getArgAt(1).isAtom && getArgAt(2).isAtom -> { + try { + Operator( + getArgAt(2).castToAtom().value, + Specifier.fromTerm(getArgAt(1)), + getArgAt(0).castToNumeric().intValue.toInt(), + ) + } catch (ex: IllegalArgumentException) { + null + } catch (ex: IllegalStateException) { + // Enum.valueOf throws IllegalStateException instead of IllegalArgumentException + null + } } + else -> null } - else -> null } - } } } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/operators/OperatorSet.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/operators/OperatorSet.kt index 6f7ef9a0c..f38c80155 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/operators/OperatorSet.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/operators/OperatorSet.kt @@ -5,7 +5,6 @@ import kotlin.jvm.JvmField /** Class representing a [Set] of [Operator]s */ class OperatorSet(operators: Sequence) : Set by operators.toHashSet() { - /** Needed to support equals and hashCode */ private val operators by lazy { operators.toSet() } @@ -15,13 +14,11 @@ class OperatorSet(operators: Sequence) : Set by operators.to /** Creates a new OperatorSet adding to this the other Operator, overriding already present operator if one */ @JsName("plus") - operator fun plus(operator: Operator): OperatorSet = - OperatorSet(sequenceOf(operator, *this.toTypedArray())) + operator fun plus(operator: Operator): OperatorSet = OperatorSet(sequenceOf(operator, *this.toTypedArray())) /** Creates a new OperatorSet adding to this the other operators, overriding already present operators */ @JsName("plusOperatorSet") - operator fun plus(other: OperatorSet): OperatorSet = - OperatorSet(other.asSequence() + this.asSequence()) + operator fun plus(other: OperatorSet): OperatorSet = OperatorSet(other.asSequence() + this.asSequence()) /** Creates a new OperatorSet removing from this the other operators */ @JsName("minus") @@ -54,7 +51,6 @@ class OperatorSet(operators: Sequence) : Set by operators.to override fun toString(): String = "OperatorSet($operators)" companion object { - @JvmField @JsName("EMPTY") val EMPTY = OperatorSet(emptySequence()) @@ -62,60 +58,66 @@ class OperatorSet(operators: Sequence) : Set by operators.to /** Arithmetic Operator's OperatorSet */ @JvmField @JsName("ARITHMETIC") - val ARITHMETIC = OperatorSet( - sequenceOf("+", "-", "\\").map { Operator(it, Specifier.FY, 200) } + - sequenceOf("^").map { Operator(it, Specifier.XFY, 200) } + - sequenceOf("**").map { Operator(it, Specifier.XFX, 200) } + - sequenceOf("*", "/", "//", "rem", "mod", "<<", ">>").map { Operator(it, Specifier.YFX, 400) } + - sequenceOf("+", "-", "\\/", "/\\").map { Operator(it, Specifier.YFX, 500) } - ) + val ARITHMETIC = + OperatorSet( + sequenceOf("+", "-", "\\").map { Operator(it, Specifier.FY, 200) } + + sequenceOf("^").map { Operator(it, Specifier.XFY, 200) } + + sequenceOf("**").map { Operator(it, Specifier.XFX, 200) } + + sequenceOf("*", "/", "//", "rem", "mod", "<<", ">>").map { Operator(it, Specifier.YFX, 400) } + + sequenceOf("+", "-", "\\/", "/\\").map { Operator(it, Specifier.YFX, 500) }, + ) /** Arithmetic Comparison Operator's OperatorSet */ @JvmField @JsName("ARITHMETIC_COMPARISON") - val ARITHMETIC_COMPARISON = OperatorSet( - sequenceOf("=:=", "=\\=", "<", "=<", ">", ">=") - .map { Operator(it, Specifier.XFX, 700) } - ) + val ARITHMETIC_COMPARISON = + OperatorSet( + sequenceOf("=:=", "=\\=", "<", "=<", ">", ">=") + .map { Operator(it, Specifier.XFX, 700) }, + ) /** Term Comparison Operator's OperatorSet */ @JvmField @JsName("TERM_COMPARISON") - val TERM_COMPARISON = OperatorSet( - sequenceOf("=", "\\=").map { Operator(it, Specifier.XFX, 700) } + - sequenceOf("==", "\\==", "@<", "@=<", "@>", "@>=").map { Operator(it, Specifier.XFX, 700) } + - sequenceOf("=..").map { Operator(it, Specifier.XFX, 700) } + - sequenceOf("is").map { Operator(it, Specifier.XFX, 700) } - ) + val TERM_COMPARISON = + OperatorSet( + sequenceOf("=", "\\=").map { Operator(it, Specifier.XFX, 700) } + + sequenceOf("==", "\\==", "@<", "@=<", "@>", "@>=").map { Operator(it, Specifier.XFX, 700) } + + sequenceOf("=..").map { Operator(it, Specifier.XFX, 700) } + + sequenceOf("is").map { Operator(it, Specifier.XFX, 700) }, + ) /** Control Flow Operator's OperatorSet */ @JvmField @JsName("CONTROL_FLOW") - val CONTROL_FLOW = OperatorSet( - sequenceOf(",").map { Operator(it, Specifier.XFY, 1000) } + - sequenceOf("->").map { Operator(it, Specifier.XFY, 1050) } + - sequenceOf(";").map { Operator(it, Specifier.XFY, 1100) } + - sequenceOf("\\+").map { Operator(it, Specifier.FY, 900) } - ) + val CONTROL_FLOW = + OperatorSet( + sequenceOf(",").map { Operator(it, Specifier.XFY, 1000) } + + sequenceOf("->").map { Operator(it, Specifier.XFY, 1050) } + + sequenceOf(";").map { Operator(it, Specifier.XFY, 1100) } + + sequenceOf("\\+").map { Operator(it, Specifier.FY, 900) }, + ) /** Clauses Operator's OperatorSet */ @JvmField @JsName("CLAUSES") - val CLAUSES = OperatorSet( - sequenceOf(":-", "?-").map { Operator(it, Specifier.FX, 1200) } + - sequenceOf(":-", "-->").map { Operator(it, Specifier.XFX, 1200) } - ) + val CLAUSES = + OperatorSet( + sequenceOf(":-", "?-").map { Operator(it, Specifier.FX, 1200) } + + sequenceOf(":-", "-->").map { Operator(it, Specifier.XFX, 1200) }, + ) /** Standard OperatorSet */ @JvmField @JsName("STANDARD") - val STANDARD = OperatorSet( - ARITHMETIC.asSequence() + - ARITHMETIC_COMPARISON.asSequence() + - TERM_COMPARISON.asSequence() + - CONTROL_FLOW.asSequence() + - CLAUSES.asSequence() - ) + val STANDARD = + OperatorSet( + ARITHMETIC.asSequence() + + ARITHMETIC_COMPARISON.asSequence() + + TERM_COMPARISON.asSequence() + + CONTROL_FLOW.asSequence() + + CLAUSES.asSequence(), + ) /** Default OperatorSet */ @JvmField diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/operators/OperatorsIndex.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/operators/OperatorsIndex.kt index 8367409a8..c1051407f 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/operators/OperatorsIndex.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/operators/OperatorsIndex.kt @@ -19,5 +19,4 @@ fun Iterable.toOperatorsIndex(): OperatorsIndex { return temp } -fun Sequence.toOperatorsIndex(): OperatorsIndex = - this.asIterable().toOperatorsIndex() +fun Sequence.toOperatorsIndex(): OperatorsIndex = this.asIterable().toOperatorsIndex() diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/operators/Specifier.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/operators/Specifier.kt index 4a09b30e5..25a6344f4 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/operators/Specifier.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/operators/Specifier.kt @@ -39,7 +39,9 @@ enum class Specifier : TermConvertible { XFY, /** Infix and left-associative */ - YFX; + YFX, + + ; /** Whether this specifier is a prefix one */ @JsName("isPrefix") @@ -89,7 +91,8 @@ enum class Specifier : TermConvertible { fun fromTerm(atom: Atom): Specifier { try { return valueOf(atom.value.uppercase()) - } catch (e: IllegalStateException) { // Enum.valueOf throws IllegalStateException instead of IllegalArgumentException + } catch (e: IllegalStateException) { + // Enum.valueOf throws IllegalStateException instead of IllegalArgumentException throw IllegalArgumentException(e.message, e.cause) } } diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/visitors/AbstractTermVisitor.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/visitors/AbstractTermVisitor.kt index 52c3979a4..efd4d5ba2 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/visitors/AbstractTermVisitor.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/visitors/AbstractTermVisitor.kt @@ -7,7 +7,11 @@ import it.unibo.tuprolog.core.Term import it.unibo.tuprolog.core.TermVisitor abstract class AbstractTermVisitor : TermVisitor { - protected abstract fun join(term: X, f1: (X) -> T, vararg fs: (X) -> T): T + protected abstract fun join( + term: X, + f1: (X) -> T, + vararg fs: (X) -> T, + ): T override fun visitAtom(term: Atom): T = join(term, this::visitStruct, this::visitConstant) diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/visitors/DefaultTermVisitor.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/visitors/DefaultTermVisitor.kt index 7d06fd910..6062a5941 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/visitors/DefaultTermVisitor.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/visitors/DefaultTermVisitor.kt @@ -5,8 +5,11 @@ import kotlin.js.JsName import kotlin.jvm.JvmStatic abstract class DefaultTermVisitor : AbstractTermVisitor() { - override fun join(term: X, f1: (X) -> T, vararg fs: (X) -> T): T = - sequenceOf(f1, *fs).map { it(term) }.first() + override fun join( + term: X, + f1: (X) -> T, + vararg fs: (X) -> T, + ): T = sequenceOf(f1, *fs).map { it(term) }.first() companion object { @JvmStatic diff --git a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/visitors/ExhaustiveTermVisitor.kt b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/visitors/ExhaustiveTermVisitor.kt index 9588694b2..1c8552e9f 100644 --- a/core/src/commonMain/kotlin/it/unibo/tuprolog/core/visitors/ExhaustiveTermVisitor.kt +++ b/core/src/commonMain/kotlin/it/unibo/tuprolog/core/visitors/ExhaustiveTermVisitor.kt @@ -5,8 +5,11 @@ import kotlin.js.JsName import kotlin.jvm.JvmStatic abstract class ExhaustiveTermVisitor : AbstractTermVisitor() { - override fun join(term: X, f1: (X) -> T, vararg fs: (X) -> T): T = - sequenceOf(f1, *fs).map { it(term) }.last() + override fun join( + term: X, + f1: (X) -> T, + vararg fs: (X) -> T, + ): T = sequenceOf(f1, *fs).map { it(term) }.last() companion object { @JvmStatic diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/TestPlatform.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/TestPlatform.kt index d75889cce..ae7b99d25 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/TestPlatform.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/TestPlatform.kt @@ -4,5 +4,5 @@ import kotlin.test.Test expect class TestPlatform { @Test - fun testPlatform() + fun testCurrentPlatform() } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/AtomTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/AtomTest.kt index 6c9ee2dc5..68426a123 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/AtomTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/AtomTest.kt @@ -13,7 +13,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class AtomTest { - @Test fun emptySetAtomDetected() { assertEqualities(Atom.of("{}"), Empty.block()) diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/BigListTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/BigListTest.kt index 6665ae5c5..7bd37ade8 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/BigListTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/BigListTest.kt @@ -8,13 +8,13 @@ import kotlin.test.assertNotEquals import kotlin.test.assertTrue class BigListTest { - companion object { private const val MAX = 200_000 } private val nums = 0..MAX + @Suppress("ktlint:standard:property-naming", "PrivatePropertyName") private val X = Var.of("X") private val list1 by lazy { @@ -72,7 +72,7 @@ class BigListTest { assertTrue { itemWiseEquals( (nums.asSequence() + nums.asSequence()).map { Integer.of(it) }, - list2[Substitution.unifier(X, list1)].castToList().toSequence() + list2[Substitution.unifier(X, list1)].castToList().toSequence(), ) } } @@ -86,7 +86,7 @@ class BigListTest { assertTrue { itemWiseEquals( nums.asSequence().map { Integer.of(it) }, - list.apply(Substitution.unifier(X, Integer.of(n))).castToList().toSequence() + list.apply(Substitution.unifier(X, Integer.of(n))).castToList().toSequence(), ) } } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/BlockTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/BlockTest.kt index c44a0c996..00577728a 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/BlockTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/BlockTest.kt @@ -13,7 +13,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class BlockTest { - private val correctInstances = BlockUtils.mixedBlocksTupleWrapped.map(::BlockImpl) @Test diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ClauseTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ClauseTest.kt index 6044ca6f0..c76d046c8 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ClauseTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ClauseTest.kt @@ -17,7 +17,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class ClauseTest { - private val mixedClauses = RuleUtils.mixedRules + DirectiveUtils.mixedDirectives.map { Pair(null, it) } private val correctInstances = @@ -38,17 +37,18 @@ internal class ClauseTest { * For example, the [Clause] `product(A) :- A, A` is stored in the database, after preparation for execution, * as the Term: `product(A) :- call(A), call(A)` */ - private fun replaceCorrectVarWithCalls(term: Term): Term = when (term) { - is Clause -> Clause.of(term.head, replaceCorrectVarWithCalls(term.body)) - is Struct -> - when { - term.functor in Clause.notableFunctors && term.arity == 2 -> - Struct.of(term.functor, term.argsSequence.map { replaceCorrectVarWithCalls(it) }) - else -> term - } - is Var -> Struct.of("call", term) - else -> term - } + private fun replaceCorrectVarWithCalls(term: Term): Term = + when (term) { + is Clause -> Clause.of(term.head, replaceCorrectVarWithCalls(term.body)) + is Struct -> + when { + term.functor in Clause.notableFunctors && term.arity == 2 -> + Struct.of(term.functor, term.argsSequence.map { replaceCorrectVarWithCalls(it) }) + else -> term + } + is Var -> Struct.of("call", term) + else -> term + } private val wellFormedClausesCorrectlyPreparedForExecution = correctInstances.filter { it.isWellFormed }.map { replaceCorrectVarWithCalls(it) as Clause } @@ -119,19 +119,23 @@ internal class ClauseTest { val aRuleWithVarInHeadAfterPreparation = Rule.of(Tuple.of(aVar, aVar), Tuple.of(Struct.of("call", aVar), Struct.of("call", aVar))) - val toBeTested = ( - correctInstances.filter { it.isWellFormed } + listOf( - aFactWithVarInHead, - aRuleWithVarInHead, - aRuleWithVarInHeadAfterPreparation - ) + val toBeTested = + ( + correctInstances.filter { it.isWellFormed } + + listOf( + aFactWithVarInHead, + aRuleWithVarInHead, + aRuleWithVarInHeadAfterPreparation, + ) ).map { it.accept(Clause.defaultPreparationForExecutionVisitor) } - val correct = wellFormedClausesCorrectlyPreparedForExecution + listOf( - aFactWithVarInHead, - aRuleWithVarInHeadAfterPreparation, - aRuleWithVarInHeadAfterPreparation - ) + val correct = + wellFormedClausesCorrectlyPreparedForExecution + + listOf( + aFactWithVarInHead, + aRuleWithVarInHeadAfterPreparation, + aRuleWithVarInHeadAfterPreparation, + ) assertEquals(correct, toBeTested) } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ConsTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ConsTest.kt index 271971b36..320b58085 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ConsTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ConsTest.kt @@ -12,7 +12,6 @@ import kotlin.test.Test * @author Enrico */ internal class ConsTest { - @Test fun consOfWorksAsExpected() { val correctInstances = ConsUtils.mixedConsInstances(::ConsImpl) diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ConversionsTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ConversionsTest.kt index fa936210f..0a7cf1aa7 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ConversionsTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ConversionsTest.kt @@ -16,7 +16,6 @@ import kotlin.test.Test * @author Enrico */ internal class ConversionsTest { - @Test fun bigIntegersToTerm() { val correct = IntegerUtils.bigIntegers.map { Integer.of(it) } @@ -84,9 +83,10 @@ internal class ConversionsTest { @Test fun numberToTerm() { @Suppress("USELESS_CAST") - val numberValues = ( - with(IntegerUtils) { onlyBytes + onlyInts + onlyShorts + onlyLongs } + - with(RealUtils) { decimalsAsDoubles + decimalsAsFloats } + val numberValues = + ( + with(IntegerUtils) { onlyBytes + onlyInts + onlyShorts + onlyLongs } + + with(RealUtils) { decimalsAsDoubles + decimalsAsFloats } ).map { it as Number } val correct = numberValues.map { Numeric.of(it) } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/DirectiveTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/DirectiveTest.kt index 559420fc8..132ac0b85 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/DirectiveTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/DirectiveTest.kt @@ -13,7 +13,6 @@ import kotlin.test.assertFailsWith * @author Enrico */ internal class DirectiveTest { - private val correctInstances = DirectiveUtils.mixedDirectives.map(::DirectiveImpl) @Test diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/EmptyBlockTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/EmptyBlockTest.kt index 7f8fd4bcb..a26ca41b1 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/EmptyBlockTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/EmptyBlockTest.kt @@ -10,7 +10,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class EmptyBlockTest { - @Test fun emptyBlockCompanionReturnsEmptySetImpl() { assertEquals(EmptyBlockImpl(), EmptyBlock()) diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/EmptyListTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/EmptyListTest.kt index 67fa8f0d2..080648dde 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/EmptyListTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/EmptyListTest.kt @@ -10,7 +10,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class EmptyListTest { - @Test fun emptyListCompanionReturnsEmptyListImpl() { assertEquals(EmptyListImpl(), EmptyList()) diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/EmptyTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/EmptyTest.kt index d6ff658ac..06fb77f37 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/EmptyTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/EmptyTest.kt @@ -11,7 +11,6 @@ import kotlin.test.assertEquals * @author Enrico */ class EmptyTest { - @Test fun listMethodShouldReturnEmptyList() { assertEquals(EmptyListImpl(), Empty.list()) diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/FactTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/FactTest.kt index f542262ea..c07725a28 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/FactTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/FactTest.kt @@ -12,7 +12,6 @@ import kotlin.test.Test * @author Enrico */ internal class FactTest { - private val correctInstances = FactUtils.mixedFacts.map(::FactImpl) @Test diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/IndicatorTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/IndicatorTest.kt index f68948afb..ca3329d10 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/IndicatorTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/IndicatorTest.kt @@ -12,7 +12,6 @@ import kotlin.test.Test * @author Enrico */ internal class IndicatorTest { - private val correctInstances = IndicatorUtils.mixedIndicators.map { (name, arity) -> IndicatorImpl(name, arity) } @Test @@ -24,14 +23,15 @@ internal class IndicatorTest { @Test fun ofNameAndArityCreatesCorrectInstance() { - val toBeTested = IndicatorUtils.mixedIndicators - .filter { (name, arity) -> name.isAtom && arity.isInteger } - .map { (name, arity) -> - Indicator.of( - name.castToAtom().value, - arity.castToInteger().intValue.toInt() - ) - } + val toBeTested = + IndicatorUtils.mixedIndicators + .filter { (name, arity) -> name.isAtom && arity.isInteger } + .map { (name, arity) -> + Indicator.of( + name.castToAtom().value, + arity.castToInteger().intValue.toInt(), + ) + } onCorrespondingItems(correctInstances.filter { it.isWellFormed }, toBeTested, ::assertEqualities) } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/IntegerTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/IntegerTest.kt index 1adb92ced..d87e1c410 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/IntegerTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/IntegerTest.kt @@ -13,7 +13,6 @@ import kotlin.test.Test * @author Enrico */ internal class IntegerTest { - @Test fun integerOfBigInteger() { val correct = IntegerUtils.bigIntegers.map(::IntegerImpl) diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ListCreationTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ListCreationTest.kt index efb95de0e..b771af3b1 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ListCreationTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ListCreationTest.kt @@ -6,7 +6,6 @@ import kotlin.test.assertEquals import kotlin.test.assertTrue class ListCreationTest { - private fun IntRange.toTerms(): Sequence = asSequence().map { Integer.of(it) } @Test diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ListTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ListTest.kt index 802cddaa1..122866bb9 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ListTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ListTest.kt @@ -14,7 +14,6 @@ import it.unibo.tuprolog.core.List as LogicList * @author Enrico */ internal class ListTest { - private val emptyTerminatedInstances = ConsUtils.onlyConsEmptyListTerminated(Cons.Companion::of) private val pipedListInstances = ConsUtils.onlyConsPipeTerminated(Cons.Companion::of) diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/NumericTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/NumericTest.kt index ebe35bd09..15f595ffd 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/NumericTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/NumericTest.kt @@ -14,10 +14,13 @@ import kotlin.test.assertNotEquals * @author Enrico */ internal class NumericTest { - private inline val loggingOn get() = false - fun assertEquals(expected: T, actual: T, message: String? = "Failed assertion $expected == $actual") { + fun assertEquals( + expected: T, + actual: T, + message: String? = "Failed assertion $expected == $actual", + ) { if (loggingOn) println("Object\n\t$actual\nis expected to be equal to\n\t$expected") try { kotlin.test.assertEquals(expected, actual, message) @@ -36,7 +39,7 @@ internal class NumericTest { .flatMap { listOf( BigDecimal.of(it) to BigDecimal.of(it + "0"), - BigDecimal.of(it) to BigDecimal.of(it + "00") + BigDecimal.of(it) to BigDecimal.of(it + "00"), ) } } @@ -138,7 +141,7 @@ internal class NumericTest { IntegerUtils.bigIntegers.map { it to it.toDouble() }.forEach { (integer, sameValueToDouble) -> assertNotEquals( Numeric.of(integer), - Numeric.of(sameValueToDouble) + Numeric.of(sameValueToDouble), ) } } @@ -148,7 +151,7 @@ internal class NumericTest { realToRealWithTrailingZerosMap.forEach { (real, realWithTrailingZeros) -> assertEquals( Real.of(real), - Real.of(realWithTrailingZeros) + Real.of(realWithTrailingZeros), ) } } @@ -158,7 +161,7 @@ internal class NumericTest { realToRealWithTrailingZerosMap.forEach { (real, realWithTrailingZeros) -> assertEquals( Real.of(real).hashCode(), - Real.of(realWithTrailingZeros).hashCode() + Real.of(realWithTrailingZeros).hashCode(), ) } } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/RealTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/RealTest.kt index 0c9140da9..47417d45c 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/RealTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/RealTest.kt @@ -14,7 +14,6 @@ import kotlin.test.assertFailsWith * @author Enrico */ internal class RealTest { - @Test fun realOfBigDecimal() { val correct = RealUtils.bigDecimals.map(::RealImpl) diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/RuleTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/RuleTest.kt index f505c90a2..2ff82d9ee 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/RuleTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/RuleTest.kt @@ -13,7 +13,6 @@ import kotlin.test.Test * @author Enrico */ internal class RuleTest { - private val correctInstances = RuleUtils.mixedRules.map { (head, body) -> RuleImpl(head, body) } @Test diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ScopeTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ScopeTest.kt index 9df506347..96af9ef5b 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ScopeTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/ScopeTest.kt @@ -14,7 +14,6 @@ import kotlin.test.assertFailsWith * @author Enrico */ internal class ScopeTest { - private val correctEmptyInstance = ScopeImpl(ScopeUtils.emptyScope) private val correctNonEmptyScopeInstances = ScopeUtils.nonEmptyScopes.map(::ScopeImpl) @@ -40,7 +39,7 @@ internal class ScopeTest { onCorrespondingItems( correctNonEmptyScopeInstances.map { it.variables }, toBeTested, - ::assertScopeCorrectContents + ::assertScopeCorrectContents, ) } @@ -51,7 +50,7 @@ internal class ScopeTest { onCorrespondingItems( correctNonEmptyScopeInstances.map { it.variables }, toBeTested, - ::assertScopeCorrectContents + ::assertScopeCorrectContents, ) } @@ -66,7 +65,11 @@ internal class ScopeTest { @Test fun emptyWithLambdaCreatesCorrectInstanceAndReturnsLambdaResult() { val correctResult = 3 - val toBeTestedResult = Scope.empty { assertEquals(correctEmptyInstance, this); correctResult } + val toBeTestedResult = + Scope.empty { + assertEquals(correctEmptyInstance, this) + correctResult + } assertEquals(correctResult, toBeTestedResult) } @@ -76,12 +79,19 @@ internal class ScopeTest { val myResult = 3 Var.of("A").let { aVar -> val correct = Scope.of(aVar) - val toBeTestedResult = Scope.of(aVar) { assertEquals(correct, this); myResult } + val toBeTestedResult = + Scope.of(aVar) { + assertEquals(correct, this) + myResult + } assertEquals(myResult, toBeTestedResult) val toBeTestedResult2 = - Scope.of(aVar.name) { assertEquals(aVar.name, this[aVar.name]?.name); myResult } + Scope.of(aVar.name) { + assertEquals(aVar.name, this[aVar.name]?.name) + myResult + } assertEquals(myResult, toBeTestedResult2) } } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/StructTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/StructTest.kt index 0a7b63a04..4da377aa7 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/StructTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/StructTest.kt @@ -21,7 +21,6 @@ import kotlin.test.assertNotSame * @author Enrico */ internal class StructTest { - private val correctNonSpecialStructInstances = StructUtils.nonSpecialStructs.map { (functor, args) -> StructImpl(functor, args) } @@ -36,15 +35,16 @@ internal class StructTest { onCorrespondingItems( correctNonSpecialStructInstances, StructUtils.nonSpecialStructs.map { (functor, args) -> Struct.of(functor, args.asSequence()) }, - ::assertEqualities + ::assertEqualities, ) } @Test fun structOfCreatesConsIfNeeded() { - val consStructs = StructUtils.mixedStructs.filter { (functor, args) -> - args.size == 2 && Cons.FUNCTOR == functor - } + val consStructs = + StructUtils.mixedStructs.filter { (functor, args) -> + args.size == 2 && Cons.FUNCTOR == functor + } val correctInstances = consStructs.map { (_, args) -> Cons.of(args.first(), args.last()) } val toBeTested = consStructs.map { (functor, args) -> Struct.of(functor, args) } @@ -54,9 +54,10 @@ internal class StructTest { @Test fun structOfCreatesRuleIfNeeded() { - val ruleStructs = StructUtils.mixedStructs.filter { (functor, args) -> - args.size == 2 && Clause.FUNCTOR == functor && args.first() is Struct - } + val ruleStructs = + StructUtils.mixedStructs.filter { (functor, args) -> + args.size == 2 && Clause.FUNCTOR == functor && args.first() is Struct + } val correctInstances = ruleStructs.map { (_, args) -> Rule.of(args.first() as Struct, args.last()) } val toBeTested = ruleStructs.map { (functor, args) -> Struct.of(functor, args) } @@ -66,9 +67,10 @@ internal class StructTest { @Test fun structOfCreatesTupleIfNeeded() { - val tupleStructs = StructUtils.mixedStructs.filter { (functor, args) -> - args.size == 2 && Tuple.FUNCTOR == functor - } + val tupleStructs = + StructUtils.mixedStructs.filter { (functor, args) -> + args.size == 2 && Tuple.FUNCTOR == functor + } val correctInstances = tupleStructs.map { (_, args) -> Tuple.of(args.toList()) } val toBeTested = tupleStructs.map { (functor, args) -> Struct.of(functor, args) } @@ -78,9 +80,10 @@ internal class StructTest { @Test fun structOfCreatesSetIfNeeded() { - val setStructs = StructUtils.mixedStructs.filter { (functor, args) -> - args.size == 1 && Block.FUNCTOR == functor - } + val setStructs = + StructUtils.mixedStructs.filter { (functor, args) -> + args.size == 1 && Block.FUNCTOR == functor + } val correctInstances = setStructs.map { (_, args) -> Block.of(args) } val toBeTested = setStructs.map { (functor, args) -> Struct.of(functor, args) } @@ -90,9 +93,10 @@ internal class StructTest { @Test fun structOfCreatesDirectiveIfNeeded() { - val directiveStructs = StructUtils.mixedStructs.filter { (functor, args) -> - args.size == 1 && Clause.FUNCTOR == functor - } + val directiveStructs = + StructUtils.mixedStructs.filter { (functor, args) -> + args.size == 1 && Clause.FUNCTOR == functor + } val correctInstances = directiveStructs.map { (_, args) -> Directive.of(args.first()) } val toBeTested = directiveStructs.map { (functor, args) -> Struct.of(functor, args) } @@ -112,9 +116,10 @@ internal class StructTest { @Test fun structOfCreatesIndicatorIfNeeded() { - val indicatorStructs = StructUtils.mixedStructs.filter { (functor, args) -> - args.size == 2 && Indicator.FUNCTOR == functor - } + val indicatorStructs = + StructUtils.mixedStructs.filter { (functor, args) -> + args.size == 2 && Indicator.FUNCTOR == functor + } val correctInstances = indicatorStructs.map { (_, args) -> Indicator.of(args.first(), args.last()) } val toBeTested = indicatorStructs.map { (functor, args) -> Struct.of(functor, args) } @@ -179,10 +184,10 @@ internal class StructTest { "f", arrayOf( Atom.of("world"), - Atom.of("!") - ) - ) - ) + Atom.of("!"), + ), + ), + ), ) @Test @@ -194,32 +199,33 @@ internal class StructTest { @Test fun structFoldCreatesArbitraryFoldedStructsSpecifyingTerminal() { - val toBeTested = Struct.fold( - "f", - arbitraryFoldedStructElements.dropLast().asIterable(), - arbitraryFoldedStructElements.last() - ) + val toBeTested = + Struct.fold( + "f", + arbitraryFoldedStructElements.dropLast().asIterable(), + arbitraryFoldedStructElements.last(), + ) assertEqualities(arbitraryFoldedStructCorrectInstance, toBeTested) } @Test fun equalityOfNonGroundStructsWorksAsExpected() { - val f_ = Struct.of("f", Var.anonymous()) - val g_ = Struct.of("g", Var.anonymous()) + val f = Struct.of("f", Var.anonymous()) + val g = Struct.of("g", Var.anonymous()) - assertEqualities(f_, f_) - assertNoEqualities(f_, g_) + assertEqualities(f, f) + assertNoEqualities(f, g) - assertEqualsUsingVariablesSimpleNames(Struct.of("f", Var.of("_")), f_) - assertStructurallyEquals(Struct.of("f", Var.of("_")), f_) - assertEqualsUsingVariablesSimpleNames(Struct.of("f", Var.anonymous()), f_) - assertStructurallyEquals(Struct.of("f", Var.anonymous()), f_) + assertEqualsUsingVariablesSimpleNames(Struct.of("f", Var.of("_")), f) + assertStructurallyEquals(Struct.of("f", Var.of("_")), f) + assertEqualsUsingVariablesSimpleNames(Struct.of("f", Var.anonymous()), f) + assertStructurallyEquals(Struct.of("f", Var.anonymous()), f) - assertNotEquals(Struct.of("f", Var.of("_")), f_) - assertNotSame(Struct.of("f", Var.of("_")), f_) - assertNotEquals(Struct.of("f", Var.anonymous()), f_) - assertNotSame(Struct.of("f", Var.anonymous()), f_) + assertNotEquals(Struct.of("f", Var.of("_")), f) + assertNotSame(Struct.of("f", Var.of("_")), f) + assertNotEquals(Struct.of("f", Var.anonymous()), f) + assertNotSame(Struct.of("f", Var.anonymous()), f) val fX = Struct.of("f", Var.of("X")) val gX = Struct.of("g", Var.of("X")) diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/SubstitutionFailTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/SubstitutionFailTest.kt index 8000e0970..87737d2c0 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/SubstitutionFailTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/SubstitutionFailTest.kt @@ -12,7 +12,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class SubstitutionFailTest { - private val failedSubstitution = Substitution.failed() @Test diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/SubstitutionTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/SubstitutionTest.kt index d7a2eaf78..6791f21f9 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/SubstitutionTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/SubstitutionTest.kt @@ -16,7 +16,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class SubstitutionTest { - private val aVar = Var.of("A") private val bVar = Var.of("B") @@ -73,8 +72,9 @@ internal class SubstitutionTest { @Test fun ofVariableAndTerm() { val correct = correctInstances.filter { it.size == 1 } - val toBeTested = SubstitutionUtils.mixedSubstitutionsAsPairs.filter { it.size == 1 }.map { it.first() } - .map { (variable, withTerm) -> Substitution.of(variable, withTerm) } + val toBeTested = + SubstitutionUtils.mixedSubstitutionsAsPairs.filter { it.size == 1 }.map { it.first() } + .map { (variable, withTerm) -> Substitution.of(variable, withTerm) } onCorrespondingItems(correct, toBeTested) { expected, actual -> assertEquals(expected, actual) } } @@ -82,8 +82,9 @@ internal class SubstitutionTest { @Test fun ofStringVariableAndTerm() { val correct = correctInstances.filter { it.size == 1 } - val toBeTested = SubstitutionUtils.mixedSubstitutionsAsPairs.filter { it.size == 1 }.map { it.first() } - .map { (variable, withTerm) -> Substitution.of(variable.name, withTerm) } + val toBeTested = + SubstitutionUtils.mixedSubstitutionsAsPairs.filter { it.size == 1 }.map { it.first() } + .map { (variable, withTerm) -> Substitution.of(variable.name, withTerm) } onCorrespondingItems(correct, toBeTested) { expectedMap, actualMap -> onCorrespondingItems(expectedMap.keys, actualMap.keys, ::assertDifferentVariableExceptForName) @@ -93,18 +94,20 @@ internal class SubstitutionTest { @Test fun ofVariableTermPairs() { - val toBeTested = SubstitutionUtils.mixedSubstitutionsAsPairs.map { - Substitution.of(it.first(), *it.dropFirst().toTypedArray()) - } + val toBeTested = + SubstitutionUtils.mixedSubstitutionsAsPairs.map { + Substitution.of(it.first(), *it.dropFirst().toTypedArray()) + } onCorrespondingItems(correctInstances, toBeTested) { expected, actual -> assertEquals(expected, actual) } } @Test fun ofVariableTermPairsDoesntComplainIfExactDuplicates() { - val toBeTested = SubstitutionUtils.duplicatedPairSubstitution.map { - Substitution.of(it.first(), *it.dropFirst().toTypedArray()) - } + val toBeTested = + SubstitutionUtils.duplicatedPairSubstitution.map { + Substitution.of(it.first(), *it.dropFirst().toTypedArray()) + } val correctInstances = SubstitutionUtils.duplicatedPairSubstitution.map { Substitution.of(it.toMap()) } @@ -113,9 +116,10 @@ internal class SubstitutionTest { @Test fun ofVariableTermPairsResultInFailedSubstitutionIfContradicting() { - val toBeTested = SubstitutionUtils.contradictingSubstitutions.map { - Substitution.of(it.first(), *it.dropFirst().toTypedArray()) - } + val toBeTested = + SubstitutionUtils.contradictingSubstitutions.map { + Substitution.of(it.first(), *it.dropFirst().toTypedArray()) + } toBeTested.forEach { assertEquals(Substitution.failed(), it) } } @@ -159,20 +163,22 @@ internal class SubstitutionTest { @Test fun ofSubstitutionsWithAlwaysSameSubstitutionsReturnsThemNotDuplicated() { Scope.of("A", "B") { - val correct = Substitution.unifier( - mapOf( - varOf("A") to atomOf("a"), - varOf("B") to atomOf("b") + val correct = + Substitution.unifier( + mapOf( + varOf("A") to atomOf("a"), + varOf("B") to atomOf("b"), + ), ) - ) - val toBeTested = Substitution.of( - Substitution.unifier(mapOf(varOf("B") to atomOf("b"))), - Substitution.unifier(mapOf(varOf("A") to atomOf("a"))), - Substitution.unifier(mapOf(varOf("B") to atomOf("b"))), - Substitution.unifier(mapOf(varOf("A") to atomOf("a"))), - Substitution.unifier(mapOf(varOf("B") to atomOf("b"))) - ) + val toBeTested = + Substitution.of( + Substitution.unifier(mapOf(varOf("B") to atomOf("b"))), + Substitution.unifier(mapOf(varOf("A") to atomOf("a"))), + Substitution.unifier(mapOf(varOf("B") to atomOf("b"))), + Substitution.unifier(mapOf(varOf("A") to atomOf("a"))), + Substitution.unifier(mapOf(varOf("B") to atomOf("b"))), + ) assertEquals(correct, toBeTested) } @@ -181,13 +187,14 @@ internal class SubstitutionTest { @Test fun ofSubstitutionsWithContradictingOnesReturnsFailed() { Scope.of("A", "B") { - val toBeTested = Substitution.of( - Substitution.unifier(mapOf(varOf("B") to atomOf("f"))), - Substitution.unifier(mapOf(varOf("B") to varOf("A"))), - Substitution.unifier(mapOf(varOf("A") to atomOf("b"))), - Substitution.unifier(mapOf(varOf("A") to atomOf("a"))), - Substitution.unifier(mapOf(varOf("B") to atomOf("b"))) - ) + val toBeTested = + Substitution.of( + Substitution.unifier(mapOf(varOf("B") to atomOf("f"))), + Substitution.unifier(mapOf(varOf("B") to varOf("A"))), + Substitution.unifier(mapOf(varOf("A") to atomOf("b"))), + Substitution.unifier(mapOf(varOf("A") to atomOf("a"))), + Substitution.unifier(mapOf(varOf("B") to atomOf("b"))), + ) assertEquals(Substitution.failed(), toBeTested) } @@ -200,19 +207,21 @@ internal class SubstitutionTest { val first = Substitution.unifier(mapOf(bVar to Struct.of("f", aVar))) val second = Substitution.unifier(mapOf(aVar to xAtom)) - val firstComposedSecondExpected = Substitution.unifier( - mapOf( - bVar to Struct.of("f", xAtom), - aVar to xAtom + val firstComposedSecondExpected = + Substitution.unifier( + mapOf( + bVar to Struct.of("f", xAtom), + aVar to xAtom, + ), ) - ) - val secondComposedFirstExpected = Substitution.unifier( - mapOf( - aVar to xAtom, - bVar to Struct.of("f", aVar) + val secondComposedFirstExpected = + Substitution.unifier( + mapOf( + aVar to xAtom, + bVar to Struct.of("f", aVar), + ), ) - ) assertEquals(firstComposedSecondExpected, Substitution.of(first, second)) assertEquals(secondComposedFirstExpected, Substitution.of(second, first)) @@ -223,12 +232,13 @@ internal class SubstitutionTest { Scope.empty { val identityPairA = varOf("A") to varOf("A") val identityPairB = varOf("B") to varOf("B") - val toBeTested = ktListOf( - Substitution.of(identityPairA.first, identityPairA.second), - Substitution.of(identityPairA, identityPairB), - Substitution.of(ktListOf(identityPairA, identityPairB)), - Substitution.of(Substitution.of(identityPairA), Substitution.of(identityPairB)) - ) + val toBeTested = + ktListOf( + Substitution.of(identityPairA.first, identityPairA.second), + Substitution.of(identityPairA, identityPairB), + Substitution.of(ktListOf(identityPairA, identityPairB)), + Substitution.of(Substitution.of(identityPairA), Substitution.of(identityPairB)), + ) toBeTested.forEach { assertEquals(Substitution.empty(), it) } } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/SubstitutionUnifierTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/SubstitutionUnifierTest.kt index ea9d44057..4e8caefa4 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/SubstitutionUnifierTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/SubstitutionUnifierTest.kt @@ -17,7 +17,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class SubstitutionUnifierTest { - private val aVar = Var.of("A") private val bVar = Var.of("B") private val xAtom = Atom.of("x") @@ -32,11 +31,12 @@ internal class SubstitutionUnifierTest { @Test fun unifierGetByNameRetrievesSomeMatchingVariable() { val anotherVar = Var.of("A") - val unifier = Substitution.unifier( - aVar to Integer.of(1), - anotherVar to Integer.of(2), - bVar to xAtom - ) + val unifier = + Substitution.unifier( + aVar to Integer.of(1), + anotherVar to Integer.of(2), + bVar to xAtom, + ) assertTrue { unifier.getByName("A") is Integer } assertTrue { unifier.getByName("B") is Atom } assertNull(unifier.getByName("C")) @@ -101,7 +101,7 @@ internal class SubstitutionUnifierTest { assertEquals(Substitution.unifier(mapOf(aVar to xAtom)), Substitution.unifier(mapOf(aVar to xAtom))) assertNotEquals( Substitution.unifier(mapOf(Var.of("A") to xAtom)), - Substitution.unifier(mapOf(Var.of("A") to xAtom)) + Substitution.unifier(mapOf(Var.of("A") to xAtom)), ) assertNotEquals(aVarToXAtomSubstitution, bVarToXAtomSubstitution) } @@ -134,10 +134,11 @@ internal class SubstitutionUnifierTest { @Test fun plusOtherSubstitutionContradictingBaseOneReturnsFailedSubstitution() { - val toBeTested = listOf( - Substitution.of(bVar to Truth.TRUE) + bVarToXAtomSubstitution, - bVarToXAtomSubstitution + Substitution.of(bVar to Truth.TRUE) - ) + val toBeTested = + listOf( + Substitution.of(bVar to Truth.TRUE) + bVarToXAtomSubstitution, + bVarToXAtomSubstitution + Substitution.of(bVar to Truth.TRUE), + ) toBeTested.forEach { assertEquals(Substitution.failed(), it) } } @@ -155,19 +156,21 @@ internal class SubstitutionUnifierTest { val first = Substitution.unifier(mapOf(bVar to Struct.of("f", aVar))) val second = Substitution.unifier(mapOf(aVar to xAtom)) - val firstComposedSecondExpected = Substitution.unifier( - mapOf( - bVar to Struct.of("f", xAtom), - aVar to xAtom + val firstComposedSecondExpected = + Substitution.unifier( + mapOf( + bVar to Struct.of("f", xAtom), + aVar to xAtom, + ), ) - ) - val secondComposedFirstExpected = Substitution.unifier( - mapOf( - aVar to xAtom, - bVar to Struct.of("f", aVar) + val secondComposedFirstExpected = + Substitution.unifier( + mapOf( + aVar to xAtom, + bVar to Struct.of("f", aVar), + ), ) - ) assertEquals(firstComposedSecondExpected, first + second) assertEquals(secondComposedFirstExpected, second + first) @@ -208,7 +211,7 @@ internal class SubstitutionUnifierTest { fun filterMapEntryReturnsOnlyCorrectBindings() { assertEquals( aVarToXAtomSubstitution, - (aVarToXAtomSubstitution + bVarToXAtomSubstitution).filter { (`var`, _) -> `var` == aVar } + (aVarToXAtomSubstitution + bVarToXAtomSubstitution).filter { (`var`, _) -> `var` == aVar }, ) assertEquals(Substitution.empty(), bVarToXAtomSubstitution.filter { (`var`, _) -> `var` == aVar }) } @@ -217,7 +220,7 @@ internal class SubstitutionUnifierTest { fun filterPredicateReturnsOnlyCorrectBindings() { assertEquals( aVarToXAtomSubstitution, - (aVarToXAtomSubstitution + bVarToXAtomSubstitution).filter { `var`, _ -> `var` == aVar } + (aVarToXAtomSubstitution + bVarToXAtomSubstitution).filter { `var`, _ -> `var` == aVar }, ) assertEquals(Substitution.empty(), bVarToXAtomSubstitution.filter { `var`, _ -> `var` == aVar }) } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TermCastTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TermCastTest.kt index b01a76494..ebbf2b1a0 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TermCastTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TermCastTest.kt @@ -7,23 +7,24 @@ import kotlin.test.assertNull import kotlin.test.assertSame class TermCastTest { - private val terms = listOf( - Integer.ONE, - Real.ONE_HALF, - Atom.of("a"), - Struct.of("f", Var.of("X")), - Var.of("X"), - EmptyList(), - EmptyBlock(), - List.of(Integer.ZERO, Real.ZERO), - Block.of(Integer.ZERO, Real.ZERO), - Tuple.of(Integer.ZERO, Real.ZERO), - Indicator.of("a", 2), - Directive.of(Atom.of("b")), - Rule.of(Atom.of("c"), Atom.of("d")), - Fact.of(Atom.of("e")), - Truth.FAIL - ) + private val terms = + listOf( + Integer.ONE, + Real.ONE_HALF, + Atom.of("a"), + Struct.of("f", Var.of("X")), + Var.of("X"), + EmptyList(), + EmptyBlock(), + List.of(Integer.ZERO, Real.ZERO), + Block.of(Integer.ZERO, Real.ZERO), + Tuple.of(Integer.ZERO, Real.ZERO), + Indicator.of("a", 2), + Directive.of(Atom.of("b")), + Rule.of(Atom.of("c"), Atom.of("d")), + Fact.of(Atom.of("e")), + Truth.FAIL, + ) @Test fun testTypeCheckingAndCasting() { @@ -34,815 +35,818 @@ class TermCastTest { } } - private val asTypeTester = object : TermVisitor { - override fun defaultValue(term: Term) = Unit - - override fun visitVar(term: Var) { - assertNull(term.asAtom()) - assertNull(term.asClause()) - assertNull(term.asCons()) - assertNull(term.asConstant()) - assertNull(term.asDirective()) - assertNull(term.asEmptyList()) - assertNull(term.asEmptyBlock()) - assertNull(term.asFact()) - assertNull(term.asIndicator()) - assertNull(term.asInteger()) - assertNull(term.asList()) - assertNull(term.asNumeric()) - assertNull(term.asReal()) - assertNull(term.asRule()) - assertNull(term.asBlock()) - assertNull(term.asStruct()) - assertNotNull(term.asTerm()) - assertNull(term.asTruth()) - assertNull(term.asTuple()) - assertNotNull(term.asVar()) + private val asTypeTester = + object : TermVisitor { + override fun defaultValue(term: Term) = Unit + + override fun visitVar(term: Var) { + assertNull(term.asAtom()) + assertNull(term.asClause()) + assertNull(term.asCons()) + assertNull(term.asConstant()) + assertNull(term.asDirective()) + assertNull(term.asEmptyList()) + assertNull(term.asEmptyBlock()) + assertNull(term.asFact()) + assertNull(term.asIndicator()) + assertNull(term.asInteger()) + assertNull(term.asList()) + assertNull(term.asNumeric()) + assertNull(term.asReal()) + assertNull(term.asRule()) + assertNull(term.asBlock()) + assertNull(term.asStruct()) + assertNotNull(term.asTerm()) + assertNull(term.asTruth()) + assertNull(term.asTuple()) + assertNotNull(term.asVar()) + } + + override fun visitStruct(term: Struct) { + assertNull(term.asAtom()) + assertNull(term.asClause()) + assertNull(term.asCons()) + assertNull(term.asConstant()) + assertNull(term.asDirective()) + assertNull(term.asEmptyList()) + assertNull(term.asEmptyBlock()) + assertNull(term.asFact()) + assertNull(term.asIndicator()) + assertNull(term.asInteger()) + assertNull(term.asList()) + assertNull(term.asNumeric()) + assertNull(term.asReal()) + assertNull(term.asRule()) + assertNull(term.asBlock()) + assertNotNull(term.asStruct()) + assertNotNull(term.asTerm()) + assertNull(term.asTruth()) + assertNull(term.asTuple()) + assertNull(term.asVar()) + } + + override fun visitAtom(term: Atom) { + assertNotNull(term.asAtom()) + assertNull(term.asClause()) + assertNull(term.asCons()) + assertNotNull(term.asConstant()) + assertNull(term.asDirective()) + assertNull(term.asEmptyList()) + assertNull(term.asEmptyBlock()) + assertNull(term.asFact()) + assertNull(term.asIndicator()) + assertNull(term.asInteger()) + assertNull(term.asList()) + assertNull(term.asNumeric()) + assertNull(term.asReal()) + assertNull(term.asRule()) + assertNull(term.asBlock()) + assertNotNull(term.asStruct()) + assertNotNull(term.asTerm()) + assertNull(term.asTruth()) + assertNull(term.asTuple()) + assertNull(term.asVar()) + } + + override fun visitTruth(term: Truth) { + assertNotNull(term.asAtom()) + assertNull(term.asClause()) + assertNull(term.asCons()) + assertNotNull(term.asConstant()) + assertNull(term.asDirective()) + assertNull(term.asEmptyList()) + assertNull(term.asEmptyBlock()) + assertNull(term.asFact()) + assertNull(term.asIndicator()) + assertNull(term.asInteger()) + assertNull(term.asList()) + assertNull(term.asNumeric()) + assertNull(term.asReal()) + assertNull(term.asRule()) + assertNull(term.asBlock()) + assertNotNull(term.asStruct()) + assertNotNull(term.asTerm()) + assertNotNull(term.asTruth()) + assertNull(term.asTuple()) + assertNull(term.asVar()) + } + + override fun visitInteger(term: Integer) { + assertNull(term.asAtom()) + assertNull(term.asClause()) + assertNull(term.asCons()) + assertNotNull(term.asConstant()) + assertNull(term.asDirective()) + assertNull(term.asEmptyList()) + assertNull(term.asEmptyBlock()) + assertNull(term.asFact()) + assertNull(term.asIndicator()) + assertNotNull(term.asInteger()) + assertNull(term.asList()) + assertNotNull(term.asNumeric()) + assertNull(term.asReal()) + assertNull(term.asRule()) + assertNull(term.asBlock()) + assertNull(term.asStruct()) + assertNotNull(term.asTerm()) + assertNull(term.asTruth()) + assertNull(term.asTuple()) + assertNull(term.asVar()) + } + + override fun visitReal(term: Real) { + assertNull(term.asAtom()) + assertNull(term.asClause()) + assertNull(term.asCons()) + assertNotNull(term.asConstant()) + assertNull(term.asDirective()) + assertNull(term.asEmptyList()) + assertNull(term.asEmptyBlock()) + assertNull(term.asFact()) + assertNull(term.asIndicator()) + assertNull(term.asInteger()) + assertNull(term.asList()) + assertNotNull(term.asNumeric()) + assertNotNull(term.asReal()) + assertNull(term.asRule()) + assertNull(term.asBlock()) + assertNull(term.asStruct()) + assertNotNull(term.asTerm()) + assertNull(term.asTruth()) + assertNull(term.asTuple()) + assertNull(term.asVar()) + } + + override fun visitBlock(term: Block) { + assertNull(term.asAtom()) + assertNull(term.asClause()) + assertNull(term.asCons()) + assertNull(term.asConstant()) + assertNull(term.asDirective()) + assertNull(term.asEmptyList()) + assertNull(term.asEmptyBlock()) + assertNull(term.asFact()) + assertNull(term.asIndicator()) + assertNull(term.asInteger()) + assertNull(term.asList()) + assertNull(term.asNumeric()) + assertNull(term.asReal()) + assertNull(term.asRule()) + assertNotNull(term.asBlock()) + assertNotNull(term.asStruct()) + assertNotNull(term.asTerm()) + assertNull(term.asTruth()) + assertNull(term.asTuple()) + assertNull(term.asVar()) + } + + override fun visitEmptyBlock(term: EmptyBlock) { + assertNotNull(term.asAtom()) + assertNull(term.asClause()) + assertNull(term.asCons()) + assertNotNull(term.asConstant()) + assertNull(term.asDirective()) + assertNull(term.asEmptyList()) + assertNotNull(term.asEmptyBlock()) + assertNull(term.asFact()) + assertNull(term.asIndicator()) + assertNull(term.asInteger()) + assertNull(term.asList()) + assertNull(term.asNumeric()) + assertNull(term.asReal()) + assertNull(term.asRule()) + assertNotNull(term.asBlock()) + assertNotNull(term.asStruct()) + assertNotNull(term.asTerm()) + assertNull(term.asTruth()) + assertNull(term.asTuple()) + assertNull(term.asVar()) + } + + override fun visitCons(term: Cons) { + assertNull(term.asAtom()) + assertNull(term.asClause()) + assertNotNull(term.asCons()) + assertNull(term.asConstant()) + assertNull(term.asDirective()) + assertNull(term.asEmptyList()) + assertNull(term.asEmptyBlock()) + assertNull(term.asFact()) + assertNull(term.asIndicator()) + assertNull(term.asInteger()) + assertNotNull(term.asList()) + assertNull(term.asNumeric()) + assertNull(term.asReal()) + assertNull(term.asRule()) + assertNull(term.asBlock()) + assertNotNull(term.asStruct()) + assertNotNull(term.asTerm()) + assertNull(term.asTruth()) + assertNull(term.asTuple()) + assertNull(term.asVar()) + } + + override fun visitEmptyList(term: EmptyList) { + assertNotNull(term.asAtom()) + assertNull(term.asClause()) + assertNull(term.asCons()) + assertNotNull(term.asConstant()) + assertNull(term.asDirective()) + assertNotNull(term.asEmptyList()) + assertNull(term.asEmptyBlock()) + assertNull(term.asFact()) + assertNull(term.asIndicator()) + assertNull(term.asInteger()) + assertNotNull(term.asList()) + assertNull(term.asNumeric()) + assertNull(term.asReal()) + assertNull(term.asRule()) + assertNull(term.asBlock()) + assertNotNull(term.asStruct()) + assertNotNull(term.asTerm()) + assertNull(term.asTruth()) + assertNull(term.asTuple()) + assertNull(term.asVar()) + } + + override fun visitTuple(term: Tuple) { + assertNull(term.asAtom()) + assertNull(term.asClause()) + assertNull(term.asCons()) + assertNull(term.asConstant()) + assertNull(term.asDirective()) + assertNull(term.asEmptyList()) + assertNull(term.asEmptyBlock()) + assertNull(term.asFact()) + assertNull(term.asIndicator()) + assertNull(term.asInteger()) + assertNull(term.asList()) + assertNull(term.asNumeric()) + assertNull(term.asReal()) + assertNull(term.asRule()) + assertNull(term.asBlock()) + assertNotNull(term.asStruct()) + assertNotNull(term.asTerm()) + assertNull(term.asTruth()) + assertNotNull(term.asTuple()) + assertNull(term.asVar()) + } + + override fun visitIndicator(term: Indicator) { + assertNull(term.asAtom()) + assertNull(term.asClause()) + assertNull(term.asCons()) + assertNull(term.asConstant()) + assertNull(term.asDirective()) + assertNull(term.asEmptyList()) + assertNull(term.asEmptyBlock()) + assertNull(term.asFact()) + assertNotNull(term.asIndicator()) + assertNull(term.asInteger()) + assertNull(term.asList()) + assertNull(term.asNumeric()) + assertNull(term.asReal()) + assertNull(term.asRule()) + assertNull(term.asBlock()) + assertNotNull(term.asStruct()) + assertNotNull(term.asTerm()) + assertNull(term.asTruth()) + assertNull(term.asTuple()) + assertNull(term.asVar()) + } + + override fun visitRule(term: Rule) { + assertNull(term.asAtom()) + assertNotNull(term.asClause()) + assertNull(term.asCons()) + assertNull(term.asConstant()) + assertNull(term.asDirective()) + assertNull(term.asEmptyList()) + assertNull(term.asEmptyBlock()) + assertNull(term.asFact()) + assertNull(term.asIndicator()) + assertNull(term.asInteger()) + assertNull(term.asList()) + assertNull(term.asNumeric()) + assertNull(term.asReal()) + assertNotNull(term.asRule()) + assertNull(term.asBlock()) + assertNotNull(term.asStruct()) + assertNotNull(term.asTerm()) + assertNull(term.asTruth()) + assertNull(term.asTuple()) + assertNull(term.asVar()) + } + + override fun visitFact(term: Fact) { + assertNull(term.asAtom()) + assertNotNull(term.asClause()) + assertNull(term.asCons()) + assertNull(term.asConstant()) + assertNull(term.asDirective()) + assertNull(term.asEmptyList()) + assertNull(term.asEmptyBlock()) + assertNotNull(term.asFact()) + assertNull(term.asIndicator()) + assertNull(term.asInteger()) + assertNull(term.asList()) + assertNull(term.asNumeric()) + assertNull(term.asReal()) + assertNotNull(term.asRule()) + assertNull(term.asBlock()) + assertNotNull(term.asStruct()) + assertNotNull(term.asTerm()) + assertNull(term.asTruth()) + assertNull(term.asTuple()) + assertNull(term.asVar()) + } + + override fun visitDirective(term: Directive) { + assertNull(term.asAtom()) + assertNotNull(term.asClause()) + assertNull(term.asCons()) + assertNull(term.asConstant()) + assertNotNull(term.asDirective()) + assertNull(term.asEmptyList()) + assertNull(term.asEmptyBlock()) + assertNull(term.asFact()) + assertNull(term.asIndicator()) + assertNull(term.asInteger()) + assertNull(term.asList()) + assertNull(term.asNumeric()) + assertNull(term.asReal()) + assertNull(term.asRule()) + assertNull(term.asBlock()) + assertNotNull(term.asStruct()) + assertNotNull(term.asTerm()) + assertNull(term.asTruth()) + assertNull(term.asTuple()) + assertNull(term.asVar()) + } + } + + private val castToTypeTester = + object : TermVisitor { + override fun defaultValue(term: Term) = Unit + + override fun visitVar(term: Var) { + assertFailsWith(ClassCastException::class) { term.castToAtom() } + assertFailsWith(ClassCastException::class) { term.castToClause() } + assertFailsWith(ClassCastException::class) { term.castToCons() } + assertFailsWith(ClassCastException::class) { term.castToConstant() } + assertFailsWith(ClassCastException::class) { term.castToDirective() } + assertFailsWith(ClassCastException::class) { term.castToEmptyList() } + assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } + assertFailsWith(ClassCastException::class) { term.castToFact() } + assertFailsWith(ClassCastException::class) { term.castToIndicator() } + assertFailsWith(ClassCastException::class) { term.castToInteger() } + assertFailsWith(ClassCastException::class) { term.castToList() } + assertFailsWith(ClassCastException::class) { term.castToNumeric() } + assertFailsWith(ClassCastException::class) { term.castToReal() } + assertFailsWith(ClassCastException::class) { term.castToRule() } + assertFailsWith(ClassCastException::class) { term.castToBlock() } + assertFailsWith(ClassCastException::class) { term.castToStruct() } + assertNotNull(term.castToTerm()) + assertFailsWith(ClassCastException::class) { term.castToTruth() } + assertFailsWith(ClassCastException::class) { term.castToTuple() } + assertNotNull(term.castToVar()) + } + + override fun visitStruct(term: Struct) { + assertFailsWith(ClassCastException::class) { term.castToAtom() } + assertFailsWith(ClassCastException::class) { term.castToClause() } + assertFailsWith(ClassCastException::class) { term.castToCons() } + assertFailsWith(ClassCastException::class) { term.castToConstant() } + assertFailsWith(ClassCastException::class) { term.castToDirective() } + assertFailsWith(ClassCastException::class) { term.castToEmptyList() } + assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } + assertFailsWith(ClassCastException::class) { term.castToFact() } + assertFailsWith(ClassCastException::class) { term.castToIndicator() } + assertFailsWith(ClassCastException::class) { term.castToInteger() } + assertFailsWith(ClassCastException::class) { term.castToList() } + assertFailsWith(ClassCastException::class) { term.castToNumeric() } + assertFailsWith(ClassCastException::class) { term.castToReal() } + assertFailsWith(ClassCastException::class) { term.castToRule() } + assertFailsWith(ClassCastException::class) { term.castToBlock() } + assertNotNull(term.castToStruct()) + assertNotNull(term.castToTerm()) + assertFailsWith(ClassCastException::class) { term.castToTruth() } + assertFailsWith(ClassCastException::class) { term.castToTuple() } + assertFailsWith(ClassCastException::class) { term.castToVar() } + } + + override fun visitAtom(term: Atom) { + assertNotNull(term.castToAtom()) + assertFailsWith(ClassCastException::class) { term.castToClause() } + assertFailsWith(ClassCastException::class) { term.castToCons() } + assertNotNull(term.castToConstant()) + assertFailsWith(ClassCastException::class) { term.castToDirective() } + assertFailsWith(ClassCastException::class) { term.castToEmptyList() } + assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } + assertFailsWith(ClassCastException::class) { term.castToFact() } + assertFailsWith(ClassCastException::class) { term.castToIndicator() } + assertFailsWith(ClassCastException::class) { term.castToInteger() } + assertFailsWith(ClassCastException::class) { term.castToList() } + assertFailsWith(ClassCastException::class) { term.castToNumeric() } + assertFailsWith(ClassCastException::class) { term.castToReal() } + assertFailsWith(ClassCastException::class) { term.castToRule() } + assertFailsWith(ClassCastException::class) { term.castToBlock() } + assertNotNull(term.castToStruct()) + assertNotNull(term.castToTerm()) + assertFailsWith(ClassCastException::class) { term.castToTruth() } + assertFailsWith(ClassCastException::class) { term.castToTuple() } + assertFailsWith(ClassCastException::class) { term.castToVar() } + } + + override fun visitTruth(term: Truth) { + assertNotNull(term.castToAtom()) + assertFailsWith(ClassCastException::class) { term.castToClause() } + assertFailsWith(ClassCastException::class) { term.castToCons() } + assertNotNull(term.castToConstant()) + assertFailsWith(ClassCastException::class) { term.castToDirective() } + assertFailsWith(ClassCastException::class) { term.castToEmptyList() } + assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } + assertFailsWith(ClassCastException::class) { term.castToFact() } + assertFailsWith(ClassCastException::class) { term.castToIndicator() } + assertFailsWith(ClassCastException::class) { term.castToInteger() } + assertFailsWith(ClassCastException::class) { term.castToList() } + assertFailsWith(ClassCastException::class) { term.castToNumeric() } + assertFailsWith(ClassCastException::class) { term.castToReal() } + assertFailsWith(ClassCastException::class) { term.castToRule() } + assertFailsWith(ClassCastException::class) { term.castToBlock() } + assertNotNull(term.castToStruct()) + assertNotNull(term.castToTerm()) + assertNotNull(term.castToTruth()) + assertFailsWith(ClassCastException::class) { term.castToTuple() } + assertFailsWith(ClassCastException::class) { term.castToVar() } + } + + override fun visitInteger(term: Integer) { + assertFailsWith(ClassCastException::class) { term.castToAtom() } + assertFailsWith(ClassCastException::class) { term.castToClause() } + assertFailsWith(ClassCastException::class) { term.castToCons() } + assertNotNull(term.castToConstant()) + assertFailsWith(ClassCastException::class) { term.castToDirective() } + assertFailsWith(ClassCastException::class) { term.castToEmptyList() } + assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } + assertFailsWith(ClassCastException::class) { term.castToFact() } + assertFailsWith(ClassCastException::class) { term.castToIndicator() } + assertNotNull(term.castToInteger()) + assertFailsWith(ClassCastException::class) { term.castToList() } + assertNotNull(term.castToNumeric()) + assertFailsWith(ClassCastException::class) { term.castToReal() } + assertFailsWith(ClassCastException::class) { term.castToRule() } + assertFailsWith(ClassCastException::class) { term.castToBlock() } + assertFailsWith(ClassCastException::class) { term.castToStruct() } + assertNotNull(term.castToTerm()) + assertFailsWith(ClassCastException::class) { term.castToTruth() } + assertFailsWith(ClassCastException::class) { term.castToTuple() } + assertFailsWith(ClassCastException::class) { term.castToVar() } + } + + override fun visitReal(term: Real) { + assertFailsWith(ClassCastException::class) { term.castToAtom() } + assertFailsWith(ClassCastException::class) { term.castToClause() } + assertFailsWith(ClassCastException::class) { term.castToCons() } + assertNotNull(term.castToConstant()) + assertFailsWith(ClassCastException::class) { term.castToDirective() } + assertFailsWith(ClassCastException::class) { term.castToEmptyList() } + assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } + assertFailsWith(ClassCastException::class) { term.castToFact() } + assertFailsWith(ClassCastException::class) { term.castToIndicator() } + assertFailsWith(ClassCastException::class) { term.castToInteger() } + assertFailsWith(ClassCastException::class) { term.castToList() } + assertNotNull(term.castToNumeric()) + assertNotNull(term.castToReal()) + assertFailsWith(ClassCastException::class) { term.castToRule() } + assertFailsWith(ClassCastException::class) { term.castToBlock() } + assertFailsWith(ClassCastException::class) { term.castToStruct() } + assertNotNull(term.castToTerm()) + assertFailsWith(ClassCastException::class) { term.castToTruth() } + assertFailsWith(ClassCastException::class) { term.castToTuple() } + assertFailsWith(ClassCastException::class) { term.castToVar() } + } + + override fun visitBlock(term: Block) { + assertFailsWith(ClassCastException::class) { term.castToAtom() } + assertFailsWith(ClassCastException::class) { term.castToClause() } + assertFailsWith(ClassCastException::class) { term.castToCons() } + assertFailsWith(ClassCastException::class) { term.castToConstant() } + assertFailsWith(ClassCastException::class) { term.castToDirective() } + assertFailsWith(ClassCastException::class) { term.castToEmptyList() } + assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } + assertFailsWith(ClassCastException::class) { term.castToFact() } + assertFailsWith(ClassCastException::class) { term.castToIndicator() } + assertFailsWith(ClassCastException::class) { term.castToInteger() } + assertFailsWith(ClassCastException::class) { term.castToList() } + assertFailsWith(ClassCastException::class) { term.castToNumeric() } + assertFailsWith(ClassCastException::class) { term.castToReal() } + assertFailsWith(ClassCastException::class) { term.castToRule() } + assertNotNull(term.castToBlock()) + assertNotNull(term.castToStruct()) + assertNotNull(term.castToTerm()) + assertFailsWith(ClassCastException::class) { term.castToTruth() } + assertFailsWith(ClassCastException::class) { term.castToTuple() } + assertFailsWith(ClassCastException::class) { term.castToVar() } + } + + override fun visitEmptyBlock(term: EmptyBlock) { + assertNotNull(term.castToAtom()) + assertFailsWith(ClassCastException::class) { term.castToClause() } + assertFailsWith(ClassCastException::class) { term.castToCons() } + assertNotNull(term.castToConstant()) + assertFailsWith(ClassCastException::class) { term.castToDirective() } + assertFailsWith(ClassCastException::class) { term.castToEmptyList() } + assertNotNull(term.castToEmptyBlock()) + assertFailsWith(ClassCastException::class) { term.castToFact() } + assertFailsWith(ClassCastException::class) { term.castToIndicator() } + assertFailsWith(ClassCastException::class) { term.castToInteger() } + assertFailsWith(ClassCastException::class) { term.castToList() } + assertFailsWith(ClassCastException::class) { term.castToNumeric() } + assertFailsWith(ClassCastException::class) { term.castToReal() } + assertFailsWith(ClassCastException::class) { term.castToRule() } + assertNotNull(term.castToBlock()) + assertNotNull(term.castToStruct()) + assertNotNull(term.castToTerm()) + assertFailsWith(ClassCastException::class) { term.castToTruth() } + assertFailsWith(ClassCastException::class) { term.castToTuple() } + assertFailsWith(ClassCastException::class) { term.castToVar() } + } + + override fun visitCons(term: Cons) { + assertFailsWith(ClassCastException::class) { term.castToAtom() } + assertFailsWith(ClassCastException::class) { term.castToClause() } + assertNotNull(term.castToCons()) + assertFailsWith(ClassCastException::class) { term.castToConstant() } + assertFailsWith(ClassCastException::class) { term.castToDirective() } + assertFailsWith(ClassCastException::class) { term.castToEmptyList() } + assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } + assertFailsWith(ClassCastException::class) { term.castToFact() } + assertFailsWith(ClassCastException::class) { term.castToIndicator() } + assertFailsWith(ClassCastException::class) { term.castToInteger() } + assertNotNull(term.castToList()) + assertFailsWith(ClassCastException::class) { term.castToNumeric() } + assertFailsWith(ClassCastException::class) { term.castToReal() } + assertFailsWith(ClassCastException::class) { term.castToRule() } + assertFailsWith(ClassCastException::class) { term.castToBlock() } + assertNotNull(term.castToStruct()) + assertNotNull(term.castToTerm()) + assertFailsWith(ClassCastException::class) { term.castToTruth() } + assertFailsWith(ClassCastException::class) { term.castToTuple() } + assertFailsWith(ClassCastException::class) { term.castToVar() } + } + + override fun visitEmptyList(term: EmptyList) { + assertNotNull(term.castToAtom()) + assertFailsWith(ClassCastException::class) { term.castToClause() } + assertFailsWith(ClassCastException::class) { term.castToCons() } + assertNotNull(term.castToConstant()) + assertFailsWith(ClassCastException::class) { term.castToDirective() } + assertNotNull(term.castToEmptyList()) + assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } + assertFailsWith(ClassCastException::class) { term.castToFact() } + assertFailsWith(ClassCastException::class) { term.castToIndicator() } + assertFailsWith(ClassCastException::class) { term.castToInteger() } + assertNotNull(term.castToList()) + assertFailsWith(ClassCastException::class) { term.castToNumeric() } + assertFailsWith(ClassCastException::class) { term.castToReal() } + assertFailsWith(ClassCastException::class) { term.castToRule() } + assertFailsWith(ClassCastException::class) { term.castToBlock() } + assertNotNull(term.castToStruct()) + assertNotNull(term.castToTerm()) + assertFailsWith(ClassCastException::class) { term.castToTruth() } + assertFailsWith(ClassCastException::class) { term.castToTuple() } + assertFailsWith(ClassCastException::class) { term.castToVar() } + } + + override fun visitTuple(term: Tuple) { + assertFailsWith(ClassCastException::class) { term.castToAtom() } + assertFailsWith(ClassCastException::class) { term.castToClause() } + assertFailsWith(ClassCastException::class) { term.castToCons() } + assertFailsWith(ClassCastException::class) { term.castToConstant() } + assertFailsWith(ClassCastException::class) { term.castToDirective() } + assertFailsWith(ClassCastException::class) { term.castToEmptyList() } + assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } + assertFailsWith(ClassCastException::class) { term.castToFact() } + assertFailsWith(ClassCastException::class) { term.castToIndicator() } + assertFailsWith(ClassCastException::class) { term.castToInteger() } + assertFailsWith(ClassCastException::class) { term.castToList() } + assertFailsWith(ClassCastException::class) { term.castToNumeric() } + assertFailsWith(ClassCastException::class) { term.castToReal() } + assertFailsWith(ClassCastException::class) { term.castToRule() } + assertFailsWith(ClassCastException::class) { term.castToBlock() } + assertNotNull(term.castToStruct()) + assertNotNull(term.castToTerm()) + assertFailsWith(ClassCastException::class) { term.castToTruth() } + assertNotNull(term.castToTuple()) + assertFailsWith(ClassCastException::class) { term.castToVar() } + } + + override fun visitIndicator(term: Indicator) { + assertFailsWith(ClassCastException::class) { term.castToAtom() } + assertFailsWith(ClassCastException::class) { term.castToClause() } + assertFailsWith(ClassCastException::class) { term.castToCons() } + assertFailsWith(ClassCastException::class) { term.castToConstant() } + assertFailsWith(ClassCastException::class) { term.castToDirective() } + assertFailsWith(ClassCastException::class) { term.castToEmptyList() } + assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } + assertFailsWith(ClassCastException::class) { term.castToFact() } + assertNotNull(term.castToIndicator()) + assertFailsWith(ClassCastException::class) { term.castToInteger() } + assertFailsWith(ClassCastException::class) { term.castToList() } + assertFailsWith(ClassCastException::class) { term.castToNumeric() } + assertFailsWith(ClassCastException::class) { term.castToReal() } + assertFailsWith(ClassCastException::class) { term.castToRule() } + assertFailsWith(ClassCastException::class) { term.castToBlock() } + assertNotNull(term.castToStruct()) + assertNotNull(term.castToTerm()) + assertFailsWith(ClassCastException::class) { term.castToTruth() } + assertFailsWith(ClassCastException::class) { term.castToTuple() } + assertFailsWith(ClassCastException::class) { term.castToVar() } + } + + override fun visitRule(term: Rule) { + assertFailsWith(ClassCastException::class) { term.castToAtom() } + assertNotNull(term.castToClause()) + assertFailsWith(ClassCastException::class) { term.castToCons() } + assertFailsWith(ClassCastException::class) { term.castToConstant() } + assertFailsWith(ClassCastException::class) { term.castToDirective() } + assertFailsWith(ClassCastException::class) { term.castToEmptyList() } + assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } + assertFailsWith(ClassCastException::class) { term.castToFact() } + assertFailsWith(ClassCastException::class) { term.castToIndicator() } + assertFailsWith(ClassCastException::class) { term.castToInteger() } + assertFailsWith(ClassCastException::class) { term.castToList() } + assertFailsWith(ClassCastException::class) { term.castToNumeric() } + assertFailsWith(ClassCastException::class) { term.castToReal() } + assertNotNull(term.castToRule()) + assertFailsWith(ClassCastException::class) { term.castToBlock() } + assertNotNull(term.castToStruct()) + assertNotNull(term.castToTerm()) + assertFailsWith(ClassCastException::class) { term.castToTruth() } + assertFailsWith(ClassCastException::class) { term.castToTuple() } + assertFailsWith(ClassCastException::class) { term.castToVar() } + } + + override fun visitFact(term: Fact) { + assertFailsWith(ClassCastException::class) { term.castToAtom() } + assertNotNull(term.castToClause()) + assertFailsWith(ClassCastException::class) { term.castToCons() } + assertFailsWith(ClassCastException::class) { term.castToConstant() } + assertFailsWith(ClassCastException::class) { term.castToDirective() } + assertFailsWith(ClassCastException::class) { term.castToEmptyList() } + assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } + assertNotNull(term.castToFact()) + assertFailsWith(ClassCastException::class) { term.castToIndicator() } + assertFailsWith(ClassCastException::class) { term.castToInteger() } + assertFailsWith(ClassCastException::class) { term.castToList() } + assertFailsWith(ClassCastException::class) { term.castToNumeric() } + assertFailsWith(ClassCastException::class) { term.castToReal() } + assertNotNull(term.castToRule()) + assertFailsWith(ClassCastException::class) { term.castToBlock() } + assertNotNull(term.castToStruct()) + assertNotNull(term.castToTerm()) + assertFailsWith(ClassCastException::class) { term.castToTruth() } + assertFailsWith(ClassCastException::class) { term.castToTuple() } + assertFailsWith(ClassCastException::class) { term.castToVar() } + } + + override fun visitDirective(term: Directive) { + assertFailsWith(ClassCastException::class) { term.castToAtom() } + assertNotNull(term.castToClause()) + assertFailsWith(ClassCastException::class) { term.castToCons() } + assertFailsWith(ClassCastException::class) { term.castToConstant() } + assertNotNull(term.castToDirective()) + assertFailsWith(ClassCastException::class) { term.castToEmptyList() } + assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } + assertFailsWith(ClassCastException::class) { term.castToFact() } + assertFailsWith(ClassCastException::class) { term.castToIndicator() } + assertFailsWith(ClassCastException::class) { term.castToInteger() } + assertFailsWith(ClassCastException::class) { term.castToList() } + assertFailsWith(ClassCastException::class) { term.castToNumeric() } + assertFailsWith(ClassCastException::class) { term.castToReal() } + assertFailsWith(ClassCastException::class) { term.castToRule() } + assertFailsWith(ClassCastException::class) { term.castToBlock() } + assertNotNull(term.castToStruct()) + assertNotNull(term.castToTerm()) + assertFailsWith(ClassCastException::class) { term.castToTruth() } + assertFailsWith(ClassCastException::class) { term.castToTuple() } + assertFailsWith(ClassCastException::class) { term.castToVar() } + } + } + + private val positiveTypeTester = + object : TermVisitor { + override fun defaultValue(term: Term) { + assertSame(term, term.castToTerm()) + assertSame(term, term.asTerm()) + assertSame(term, term.castTo()) + assertSame(term, term.`as`()) + } + + override fun visitVar(term: Var) { + assertSame(term, term.castToVar()) + assertSame(term, term.asVar()) + assertSame(term, term.castTo()) + assertSame(term, term.`as`()) + } + + override fun visitStruct(term: Struct) { + assertSame(term, term.castToStruct()) + assertSame(term, term.asStruct()) + assertSame(term, term.castTo()) + assertSame(term, term.`as`()) + } + + override fun visitAtom(term: Atom) { + assertSame(term, term.castToAtom()) + assertSame(term, term.asAtom()) + assertSame(term, term.castTo()) + assertSame(term, term.`as`()) + } + + override fun visitTruth(term: Truth) { + assertSame(term, term.castToTruth()) + assertSame(term, term.asTruth()) + assertSame(term, term.castTo()) + assertSame(term, term.`as`()) + } + + override fun visitInteger(term: Integer) { + assertSame(term, term.castToInteger()) + assertSame(term, term.asInteger()) + assertSame(term, term.castTo()) + assertSame(term, term.`as`()) + } + + override fun visitReal(term: Real) { + assertSame(term, term.castToReal()) + assertSame(term, term.asReal()) + assertSame(term, term.castTo()) + assertSame(term, term.`as`()) + } + + override fun visitBlock(term: Block) { + assertSame(term, term.castToBlock()) + assertSame(term, term.asBlock()) + assertSame(term, term.castTo()) + assertSame(term, term.`as`()) + } + + override fun visitEmptyBlock(term: EmptyBlock) { + assertSame(term, term.castToEmptyBlock()) + assertSame(term, term.asEmptyBlock()) + assertSame(term, term.castTo()) + assertSame(term, term.`as`()) + } + + override fun visitCons(term: Cons) { + assertSame(term, term.castToCons()) + assertSame(term, term.asCons()) + assertSame(term, term.castTo()) + assertSame(term, term.`as`()) + } + + override fun visitEmptyList(term: EmptyList) { + assertSame(term, term.castToEmptyList()) + assertSame(term, term.asEmptyList()) + assertSame(term, term.castTo()) + assertSame(term, term.`as`()) + } + + override fun visitTuple(term: Tuple) { + assertSame(term, term.castToTuple()) + assertSame(term, term.asTuple()) + assertSame(term, term.castTo()) + assertSame(term, term.`as`()) + } + + override fun visitIndicator(term: Indicator) { + assertSame(term, term.castToIndicator()) + assertSame(term, term.asIndicator()) + assertSame(term, term.castTo()) + assertSame(term, term.`as`()) + } + + override fun visitRule(term: Rule) { + assertSame(term, term.castToRule()) + assertSame(term, term.asRule()) + assertSame(term, term.castTo()) + assertSame(term, term.`as`()) + } + + override fun visitFact(term: Fact) { + assertSame(term, term.castToFact()) + assertSame(term, term.asFact()) + assertSame(term, term.castTo()) + assertSame(term, term.`as`()) + } + + override fun visitDirective(term: Directive) { + assertSame(term, term.castToDirective()) + assertSame(term, term.asDirective()) + assertSame(term, term.castTo()) + assertSame(term, term.`as`()) + } } - - override fun visitStruct(term: Struct) { - assertNull(term.asAtom()) - assertNull(term.asClause()) - assertNull(term.asCons()) - assertNull(term.asConstant()) - assertNull(term.asDirective()) - assertNull(term.asEmptyList()) - assertNull(term.asEmptyBlock()) - assertNull(term.asFact()) - assertNull(term.asIndicator()) - assertNull(term.asInteger()) - assertNull(term.asList()) - assertNull(term.asNumeric()) - assertNull(term.asReal()) - assertNull(term.asRule()) - assertNull(term.asBlock()) - assertNotNull(term.asStruct()) - assertNotNull(term.asTerm()) - assertNull(term.asTruth()) - assertNull(term.asTuple()) - assertNull(term.asVar()) - } - - override fun visitAtom(term: Atom) { - assertNotNull(term.asAtom()) - assertNull(term.asClause()) - assertNull(term.asCons()) - assertNotNull(term.asConstant()) - assertNull(term.asDirective()) - assertNull(term.asEmptyList()) - assertNull(term.asEmptyBlock()) - assertNull(term.asFact()) - assertNull(term.asIndicator()) - assertNull(term.asInteger()) - assertNull(term.asList()) - assertNull(term.asNumeric()) - assertNull(term.asReal()) - assertNull(term.asRule()) - assertNull(term.asBlock()) - assertNotNull(term.asStruct()) - assertNotNull(term.asTerm()) - assertNull(term.asTruth()) - assertNull(term.asTuple()) - assertNull(term.asVar()) - } - - override fun visitTruth(term: Truth) { - assertNotNull(term.asAtom()) - assertNull(term.asClause()) - assertNull(term.asCons()) - assertNotNull(term.asConstant()) - assertNull(term.asDirective()) - assertNull(term.asEmptyList()) - assertNull(term.asEmptyBlock()) - assertNull(term.asFact()) - assertNull(term.asIndicator()) - assertNull(term.asInteger()) - assertNull(term.asList()) - assertNull(term.asNumeric()) - assertNull(term.asReal()) - assertNull(term.asRule()) - assertNull(term.asBlock()) - assertNotNull(term.asStruct()) - assertNotNull(term.asTerm()) - assertNotNull(term.asTruth()) - assertNull(term.asTuple()) - assertNull(term.asVar()) - } - - override fun visitInteger(term: Integer) { - assertNull(term.asAtom()) - assertNull(term.asClause()) - assertNull(term.asCons()) - assertNotNull(term.asConstant()) - assertNull(term.asDirective()) - assertNull(term.asEmptyList()) - assertNull(term.asEmptyBlock()) - assertNull(term.asFact()) - assertNull(term.asIndicator()) - assertNotNull(term.asInteger()) - assertNull(term.asList()) - assertNotNull(term.asNumeric()) - assertNull(term.asReal()) - assertNull(term.asRule()) - assertNull(term.asBlock()) - assertNull(term.asStruct()) - assertNotNull(term.asTerm()) - assertNull(term.asTruth()) - assertNull(term.asTuple()) - assertNull(term.asVar()) - } - - override fun visitReal(term: Real) { - assertNull(term.asAtom()) - assertNull(term.asClause()) - assertNull(term.asCons()) - assertNotNull(term.asConstant()) - assertNull(term.asDirective()) - assertNull(term.asEmptyList()) - assertNull(term.asEmptyBlock()) - assertNull(term.asFact()) - assertNull(term.asIndicator()) - assertNull(term.asInteger()) - assertNull(term.asList()) - assertNotNull(term.asNumeric()) - assertNotNull(term.asReal()) - assertNull(term.asRule()) - assertNull(term.asBlock()) - assertNull(term.asStruct()) - assertNotNull(term.asTerm()) - assertNull(term.asTruth()) - assertNull(term.asTuple()) - assertNull(term.asVar()) - } - - override fun visitBlock(term: Block) { - assertNull(term.asAtom()) - assertNull(term.asClause()) - assertNull(term.asCons()) - assertNull(term.asConstant()) - assertNull(term.asDirective()) - assertNull(term.asEmptyList()) - assertNull(term.asEmptyBlock()) - assertNull(term.asFact()) - assertNull(term.asIndicator()) - assertNull(term.asInteger()) - assertNull(term.asList()) - assertNull(term.asNumeric()) - assertNull(term.asReal()) - assertNull(term.asRule()) - assertNotNull(term.asBlock()) - assertNotNull(term.asStruct()) - assertNotNull(term.asTerm()) - assertNull(term.asTruth()) - assertNull(term.asTuple()) - assertNull(term.asVar()) - } - - override fun visitEmptyBlock(term: EmptyBlock) { - assertNotNull(term.asAtom()) - assertNull(term.asClause()) - assertNull(term.asCons()) - assertNotNull(term.asConstant()) - assertNull(term.asDirective()) - assertNull(term.asEmptyList()) - assertNotNull(term.asEmptyBlock()) - assertNull(term.asFact()) - assertNull(term.asIndicator()) - assertNull(term.asInteger()) - assertNull(term.asList()) - assertNull(term.asNumeric()) - assertNull(term.asReal()) - assertNull(term.asRule()) - assertNotNull(term.asBlock()) - assertNotNull(term.asStruct()) - assertNotNull(term.asTerm()) - assertNull(term.asTruth()) - assertNull(term.asTuple()) - assertNull(term.asVar()) - } - - override fun visitCons(term: Cons) { - assertNull(term.asAtom()) - assertNull(term.asClause()) - assertNotNull(term.asCons()) - assertNull(term.asConstant()) - assertNull(term.asDirective()) - assertNull(term.asEmptyList()) - assertNull(term.asEmptyBlock()) - assertNull(term.asFact()) - assertNull(term.asIndicator()) - assertNull(term.asInteger()) - assertNotNull(term.asList()) - assertNull(term.asNumeric()) - assertNull(term.asReal()) - assertNull(term.asRule()) - assertNull(term.asBlock()) - assertNotNull(term.asStruct()) - assertNotNull(term.asTerm()) - assertNull(term.asTruth()) - assertNull(term.asTuple()) - assertNull(term.asVar()) - } - - override fun visitEmptyList(term: EmptyList) { - assertNotNull(term.asAtom()) - assertNull(term.asClause()) - assertNull(term.asCons()) - assertNotNull(term.asConstant()) - assertNull(term.asDirective()) - assertNotNull(term.asEmptyList()) - assertNull(term.asEmptyBlock()) - assertNull(term.asFact()) - assertNull(term.asIndicator()) - assertNull(term.asInteger()) - assertNotNull(term.asList()) - assertNull(term.asNumeric()) - assertNull(term.asReal()) - assertNull(term.asRule()) - assertNull(term.asBlock()) - assertNotNull(term.asStruct()) - assertNotNull(term.asTerm()) - assertNull(term.asTruth()) - assertNull(term.asTuple()) - assertNull(term.asVar()) - } - - override fun visitTuple(term: Tuple) { - assertNull(term.asAtom()) - assertNull(term.asClause()) - assertNull(term.asCons()) - assertNull(term.asConstant()) - assertNull(term.asDirective()) - assertNull(term.asEmptyList()) - assertNull(term.asEmptyBlock()) - assertNull(term.asFact()) - assertNull(term.asIndicator()) - assertNull(term.asInteger()) - assertNull(term.asList()) - assertNull(term.asNumeric()) - assertNull(term.asReal()) - assertNull(term.asRule()) - assertNull(term.asBlock()) - assertNotNull(term.asStruct()) - assertNotNull(term.asTerm()) - assertNull(term.asTruth()) - assertNotNull(term.asTuple()) - assertNull(term.asVar()) - } - - override fun visitIndicator(term: Indicator) { - assertNull(term.asAtom()) - assertNull(term.asClause()) - assertNull(term.asCons()) - assertNull(term.asConstant()) - assertNull(term.asDirective()) - assertNull(term.asEmptyList()) - assertNull(term.asEmptyBlock()) - assertNull(term.asFact()) - assertNotNull(term.asIndicator()) - assertNull(term.asInteger()) - assertNull(term.asList()) - assertNull(term.asNumeric()) - assertNull(term.asReal()) - assertNull(term.asRule()) - assertNull(term.asBlock()) - assertNotNull(term.asStruct()) - assertNotNull(term.asTerm()) - assertNull(term.asTruth()) - assertNull(term.asTuple()) - assertNull(term.asVar()) - } - - override fun visitRule(term: Rule) { - assertNull(term.asAtom()) - assertNotNull(term.asClause()) - assertNull(term.asCons()) - assertNull(term.asConstant()) - assertNull(term.asDirective()) - assertNull(term.asEmptyList()) - assertNull(term.asEmptyBlock()) - assertNull(term.asFact()) - assertNull(term.asIndicator()) - assertNull(term.asInteger()) - assertNull(term.asList()) - assertNull(term.asNumeric()) - assertNull(term.asReal()) - assertNotNull(term.asRule()) - assertNull(term.asBlock()) - assertNotNull(term.asStruct()) - assertNotNull(term.asTerm()) - assertNull(term.asTruth()) - assertNull(term.asTuple()) - assertNull(term.asVar()) - } - - override fun visitFact(term: Fact) { - assertNull(term.asAtom()) - assertNotNull(term.asClause()) - assertNull(term.asCons()) - assertNull(term.asConstant()) - assertNull(term.asDirective()) - assertNull(term.asEmptyList()) - assertNull(term.asEmptyBlock()) - assertNotNull(term.asFact()) - assertNull(term.asIndicator()) - assertNull(term.asInteger()) - assertNull(term.asList()) - assertNull(term.asNumeric()) - assertNull(term.asReal()) - assertNotNull(term.asRule()) - assertNull(term.asBlock()) - assertNotNull(term.asStruct()) - assertNotNull(term.asTerm()) - assertNull(term.asTruth()) - assertNull(term.asTuple()) - assertNull(term.asVar()) - } - - override fun visitDirective(term: Directive) { - assertNull(term.asAtom()) - assertNotNull(term.asClause()) - assertNull(term.asCons()) - assertNull(term.asConstant()) - assertNotNull(term.asDirective()) - assertNull(term.asEmptyList()) - assertNull(term.asEmptyBlock()) - assertNull(term.asFact()) - assertNull(term.asIndicator()) - assertNull(term.asInteger()) - assertNull(term.asList()) - assertNull(term.asNumeric()) - assertNull(term.asReal()) - assertNull(term.asRule()) - assertNull(term.asBlock()) - assertNotNull(term.asStruct()) - assertNotNull(term.asTerm()) - assertNull(term.asTruth()) - assertNull(term.asTuple()) - assertNull(term.asVar()) - } - } - - private val castToTypeTester = object : TermVisitor { - override fun defaultValue(term: Term) = Unit - - override fun visitVar(term: Var) { - assertFailsWith(ClassCastException::class) { term.castToAtom() } - assertFailsWith(ClassCastException::class) { term.castToClause() } - assertFailsWith(ClassCastException::class) { term.castToCons() } - assertFailsWith(ClassCastException::class) { term.castToConstant() } - assertFailsWith(ClassCastException::class) { term.castToDirective() } - assertFailsWith(ClassCastException::class) { term.castToEmptyList() } - assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } - assertFailsWith(ClassCastException::class) { term.castToFact() } - assertFailsWith(ClassCastException::class) { term.castToIndicator() } - assertFailsWith(ClassCastException::class) { term.castToInteger() } - assertFailsWith(ClassCastException::class) { term.castToList() } - assertFailsWith(ClassCastException::class) { term.castToNumeric() } - assertFailsWith(ClassCastException::class) { term.castToReal() } - assertFailsWith(ClassCastException::class) { term.castToRule() } - assertFailsWith(ClassCastException::class) { term.castToBlock() } - assertFailsWith(ClassCastException::class) { term.castToStruct() } - assertNotNull(term.castToTerm()) - assertFailsWith(ClassCastException::class) { term.castToTruth() } - assertFailsWith(ClassCastException::class) { term.castToTuple() } - assertNotNull(term.castToVar()) - } - - override fun visitStruct(term: Struct) { - assertFailsWith(ClassCastException::class) { term.castToAtom() } - assertFailsWith(ClassCastException::class) { term.castToClause() } - assertFailsWith(ClassCastException::class) { term.castToCons() } - assertFailsWith(ClassCastException::class) { term.castToConstant() } - assertFailsWith(ClassCastException::class) { term.castToDirective() } - assertFailsWith(ClassCastException::class) { term.castToEmptyList() } - assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } - assertFailsWith(ClassCastException::class) { term.castToFact() } - assertFailsWith(ClassCastException::class) { term.castToIndicator() } - assertFailsWith(ClassCastException::class) { term.castToInteger() } - assertFailsWith(ClassCastException::class) { term.castToList() } - assertFailsWith(ClassCastException::class) { term.castToNumeric() } - assertFailsWith(ClassCastException::class) { term.castToReal() } - assertFailsWith(ClassCastException::class) { term.castToRule() } - assertFailsWith(ClassCastException::class) { term.castToBlock() } - assertNotNull(term.castToStruct()) - assertNotNull(term.castToTerm()) - assertFailsWith(ClassCastException::class) { term.castToTruth() } - assertFailsWith(ClassCastException::class) { term.castToTuple() } - assertFailsWith(ClassCastException::class) { term.castToVar() } - } - - override fun visitAtom(term: Atom) { - assertNotNull(term.castToAtom()) - assertFailsWith(ClassCastException::class) { term.castToClause() } - assertFailsWith(ClassCastException::class) { term.castToCons() } - assertNotNull(term.castToConstant()) - assertFailsWith(ClassCastException::class) { term.castToDirective() } - assertFailsWith(ClassCastException::class) { term.castToEmptyList() } - assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } - assertFailsWith(ClassCastException::class) { term.castToFact() } - assertFailsWith(ClassCastException::class) { term.castToIndicator() } - assertFailsWith(ClassCastException::class) { term.castToInteger() } - assertFailsWith(ClassCastException::class) { term.castToList() } - assertFailsWith(ClassCastException::class) { term.castToNumeric() } - assertFailsWith(ClassCastException::class) { term.castToReal() } - assertFailsWith(ClassCastException::class) { term.castToRule() } - assertFailsWith(ClassCastException::class) { term.castToBlock() } - assertNotNull(term.castToStruct()) - assertNotNull(term.castToTerm()) - assertFailsWith(ClassCastException::class) { term.castToTruth() } - assertFailsWith(ClassCastException::class) { term.castToTuple() } - assertFailsWith(ClassCastException::class) { term.castToVar() } - } - - override fun visitTruth(term: Truth) { - assertNotNull(term.castToAtom()) - assertFailsWith(ClassCastException::class) { term.castToClause() } - assertFailsWith(ClassCastException::class) { term.castToCons() } - assertNotNull(term.castToConstant()) - assertFailsWith(ClassCastException::class) { term.castToDirective() } - assertFailsWith(ClassCastException::class) { term.castToEmptyList() } - assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } - assertFailsWith(ClassCastException::class) { term.castToFact() } - assertFailsWith(ClassCastException::class) { term.castToIndicator() } - assertFailsWith(ClassCastException::class) { term.castToInteger() } - assertFailsWith(ClassCastException::class) { term.castToList() } - assertFailsWith(ClassCastException::class) { term.castToNumeric() } - assertFailsWith(ClassCastException::class) { term.castToReal() } - assertFailsWith(ClassCastException::class) { term.castToRule() } - assertFailsWith(ClassCastException::class) { term.castToBlock() } - assertNotNull(term.castToStruct()) - assertNotNull(term.castToTerm()) - assertNotNull(term.castToTruth()) - assertFailsWith(ClassCastException::class) { term.castToTuple() } - assertFailsWith(ClassCastException::class) { term.castToVar() } - } - - override fun visitInteger(term: Integer) { - assertFailsWith(ClassCastException::class) { term.castToAtom() } - assertFailsWith(ClassCastException::class) { term.castToClause() } - assertFailsWith(ClassCastException::class) { term.castToCons() } - assertNotNull(term.castToConstant()) - assertFailsWith(ClassCastException::class) { term.castToDirective() } - assertFailsWith(ClassCastException::class) { term.castToEmptyList() } - assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } - assertFailsWith(ClassCastException::class) { term.castToFact() } - assertFailsWith(ClassCastException::class) { term.castToIndicator() } - assertNotNull(term.castToInteger()) - assertFailsWith(ClassCastException::class) { term.castToList() } - assertNotNull(term.castToNumeric()) - assertFailsWith(ClassCastException::class) { term.castToReal() } - assertFailsWith(ClassCastException::class) { term.castToRule() } - assertFailsWith(ClassCastException::class) { term.castToBlock() } - assertFailsWith(ClassCastException::class) { term.castToStruct() } - assertNotNull(term.castToTerm()) - assertFailsWith(ClassCastException::class) { term.castToTruth() } - assertFailsWith(ClassCastException::class) { term.castToTuple() } - assertFailsWith(ClassCastException::class) { term.castToVar() } - } - - override fun visitReal(term: Real) { - assertFailsWith(ClassCastException::class) { term.castToAtom() } - assertFailsWith(ClassCastException::class) { term.castToClause() } - assertFailsWith(ClassCastException::class) { term.castToCons() } - assertNotNull(term.castToConstant()) - assertFailsWith(ClassCastException::class) { term.castToDirective() } - assertFailsWith(ClassCastException::class) { term.castToEmptyList() } - assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } - assertFailsWith(ClassCastException::class) { term.castToFact() } - assertFailsWith(ClassCastException::class) { term.castToIndicator() } - assertFailsWith(ClassCastException::class) { term.castToInteger() } - assertFailsWith(ClassCastException::class) { term.castToList() } - assertNotNull(term.castToNumeric()) - assertNotNull(term.castToReal()) - assertFailsWith(ClassCastException::class) { term.castToRule() } - assertFailsWith(ClassCastException::class) { term.castToBlock() } - assertFailsWith(ClassCastException::class) { term.castToStruct() } - assertNotNull(term.castToTerm()) - assertFailsWith(ClassCastException::class) { term.castToTruth() } - assertFailsWith(ClassCastException::class) { term.castToTuple() } - assertFailsWith(ClassCastException::class) { term.castToVar() } - } - - override fun visitBlock(term: Block) { - assertFailsWith(ClassCastException::class) { term.castToAtom() } - assertFailsWith(ClassCastException::class) { term.castToClause() } - assertFailsWith(ClassCastException::class) { term.castToCons() } - assertFailsWith(ClassCastException::class) { term.castToConstant() } - assertFailsWith(ClassCastException::class) { term.castToDirective() } - assertFailsWith(ClassCastException::class) { term.castToEmptyList() } - assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } - assertFailsWith(ClassCastException::class) { term.castToFact() } - assertFailsWith(ClassCastException::class) { term.castToIndicator() } - assertFailsWith(ClassCastException::class) { term.castToInteger() } - assertFailsWith(ClassCastException::class) { term.castToList() } - assertFailsWith(ClassCastException::class) { term.castToNumeric() } - assertFailsWith(ClassCastException::class) { term.castToReal() } - assertFailsWith(ClassCastException::class) { term.castToRule() } - assertNotNull(term.castToBlock()) - assertNotNull(term.castToStruct()) - assertNotNull(term.castToTerm()) - assertFailsWith(ClassCastException::class) { term.castToTruth() } - assertFailsWith(ClassCastException::class) { term.castToTuple() } - assertFailsWith(ClassCastException::class) { term.castToVar() } - } - - override fun visitEmptyBlock(term: EmptyBlock) { - assertNotNull(term.castToAtom()) - assertFailsWith(ClassCastException::class) { term.castToClause() } - assertFailsWith(ClassCastException::class) { term.castToCons() } - assertNotNull(term.castToConstant()) - assertFailsWith(ClassCastException::class) { term.castToDirective() } - assertFailsWith(ClassCastException::class) { term.castToEmptyList() } - assertNotNull(term.castToEmptyBlock()) - assertFailsWith(ClassCastException::class) { term.castToFact() } - assertFailsWith(ClassCastException::class) { term.castToIndicator() } - assertFailsWith(ClassCastException::class) { term.castToInteger() } - assertFailsWith(ClassCastException::class) { term.castToList() } - assertFailsWith(ClassCastException::class) { term.castToNumeric() } - assertFailsWith(ClassCastException::class) { term.castToReal() } - assertFailsWith(ClassCastException::class) { term.castToRule() } - assertNotNull(term.castToBlock()) - assertNotNull(term.castToStruct()) - assertNotNull(term.castToTerm()) - assertFailsWith(ClassCastException::class) { term.castToTruth() } - assertFailsWith(ClassCastException::class) { term.castToTuple() } - assertFailsWith(ClassCastException::class) { term.castToVar() } - } - - override fun visitCons(term: Cons) { - assertFailsWith(ClassCastException::class) { term.castToAtom() } - assertFailsWith(ClassCastException::class) { term.castToClause() } - assertNotNull(term.castToCons()) - assertFailsWith(ClassCastException::class) { term.castToConstant() } - assertFailsWith(ClassCastException::class) { term.castToDirective() } - assertFailsWith(ClassCastException::class) { term.castToEmptyList() } - assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } - assertFailsWith(ClassCastException::class) { term.castToFact() } - assertFailsWith(ClassCastException::class) { term.castToIndicator() } - assertFailsWith(ClassCastException::class) { term.castToInteger() } - assertNotNull(term.castToList()) - assertFailsWith(ClassCastException::class) { term.castToNumeric() } - assertFailsWith(ClassCastException::class) { term.castToReal() } - assertFailsWith(ClassCastException::class) { term.castToRule() } - assertFailsWith(ClassCastException::class) { term.castToBlock() } - assertNotNull(term.castToStruct()) - assertNotNull(term.castToTerm()) - assertFailsWith(ClassCastException::class) { term.castToTruth() } - assertFailsWith(ClassCastException::class) { term.castToTuple() } - assertFailsWith(ClassCastException::class) { term.castToVar() } - } - - override fun visitEmptyList(term: EmptyList) { - assertNotNull(term.castToAtom()) - assertFailsWith(ClassCastException::class) { term.castToClause() } - assertFailsWith(ClassCastException::class) { term.castToCons() } - assertNotNull(term.castToConstant()) - assertFailsWith(ClassCastException::class) { term.castToDirective() } - assertNotNull(term.castToEmptyList()) - assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } - assertFailsWith(ClassCastException::class) { term.castToFact() } - assertFailsWith(ClassCastException::class) { term.castToIndicator() } - assertFailsWith(ClassCastException::class) { term.castToInteger() } - assertNotNull(term.castToList()) - assertFailsWith(ClassCastException::class) { term.castToNumeric() } - assertFailsWith(ClassCastException::class) { term.castToReal() } - assertFailsWith(ClassCastException::class) { term.castToRule() } - assertFailsWith(ClassCastException::class) { term.castToBlock() } - assertNotNull(term.castToStruct()) - assertNotNull(term.castToTerm()) - assertFailsWith(ClassCastException::class) { term.castToTruth() } - assertFailsWith(ClassCastException::class) { term.castToTuple() } - assertFailsWith(ClassCastException::class) { term.castToVar() } - } - - override fun visitTuple(term: Tuple) { - assertFailsWith(ClassCastException::class) { term.castToAtom() } - assertFailsWith(ClassCastException::class) { term.castToClause() } - assertFailsWith(ClassCastException::class) { term.castToCons() } - assertFailsWith(ClassCastException::class) { term.castToConstant() } - assertFailsWith(ClassCastException::class) { term.castToDirective() } - assertFailsWith(ClassCastException::class) { term.castToEmptyList() } - assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } - assertFailsWith(ClassCastException::class) { term.castToFact() } - assertFailsWith(ClassCastException::class) { term.castToIndicator() } - assertFailsWith(ClassCastException::class) { term.castToInteger() } - assertFailsWith(ClassCastException::class) { term.castToList() } - assertFailsWith(ClassCastException::class) { term.castToNumeric() } - assertFailsWith(ClassCastException::class) { term.castToReal() } - assertFailsWith(ClassCastException::class) { term.castToRule() } - assertFailsWith(ClassCastException::class) { term.castToBlock() } - assertNotNull(term.castToStruct()) - assertNotNull(term.castToTerm()) - assertFailsWith(ClassCastException::class) { term.castToTruth() } - assertNotNull(term.castToTuple()) - assertFailsWith(ClassCastException::class) { term.castToVar() } - } - - override fun visitIndicator(term: Indicator) { - assertFailsWith(ClassCastException::class) { term.castToAtom() } - assertFailsWith(ClassCastException::class) { term.castToClause() } - assertFailsWith(ClassCastException::class) { term.castToCons() } - assertFailsWith(ClassCastException::class) { term.castToConstant() } - assertFailsWith(ClassCastException::class) { term.castToDirective() } - assertFailsWith(ClassCastException::class) { term.castToEmptyList() } - assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } - assertFailsWith(ClassCastException::class) { term.castToFact() } - assertNotNull(term.castToIndicator()) - assertFailsWith(ClassCastException::class) { term.castToInteger() } - assertFailsWith(ClassCastException::class) { term.castToList() } - assertFailsWith(ClassCastException::class) { term.castToNumeric() } - assertFailsWith(ClassCastException::class) { term.castToReal() } - assertFailsWith(ClassCastException::class) { term.castToRule() } - assertFailsWith(ClassCastException::class) { term.castToBlock() } - assertNotNull(term.castToStruct()) - assertNotNull(term.castToTerm()) - assertFailsWith(ClassCastException::class) { term.castToTruth() } - assertFailsWith(ClassCastException::class) { term.castToTuple() } - assertFailsWith(ClassCastException::class) { term.castToVar() } - } - - override fun visitRule(term: Rule) { - assertFailsWith(ClassCastException::class) { term.castToAtom() } - assertNotNull(term.castToClause()) - assertFailsWith(ClassCastException::class) { term.castToCons() } - assertFailsWith(ClassCastException::class) { term.castToConstant() } - assertFailsWith(ClassCastException::class) { term.castToDirective() } - assertFailsWith(ClassCastException::class) { term.castToEmptyList() } - assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } - assertFailsWith(ClassCastException::class) { term.castToFact() } - assertFailsWith(ClassCastException::class) { term.castToIndicator() } - assertFailsWith(ClassCastException::class) { term.castToInteger() } - assertFailsWith(ClassCastException::class) { term.castToList() } - assertFailsWith(ClassCastException::class) { term.castToNumeric() } - assertFailsWith(ClassCastException::class) { term.castToReal() } - assertNotNull(term.castToRule()) - assertFailsWith(ClassCastException::class) { term.castToBlock() } - assertNotNull(term.castToStruct()) - assertNotNull(term.castToTerm()) - assertFailsWith(ClassCastException::class) { term.castToTruth() } - assertFailsWith(ClassCastException::class) { term.castToTuple() } - assertFailsWith(ClassCastException::class) { term.castToVar() } - } - - override fun visitFact(term: Fact) { - assertFailsWith(ClassCastException::class) { term.castToAtom() } - assertNotNull(term.castToClause()) - assertFailsWith(ClassCastException::class) { term.castToCons() } - assertFailsWith(ClassCastException::class) { term.castToConstant() } - assertFailsWith(ClassCastException::class) { term.castToDirective() } - assertFailsWith(ClassCastException::class) { term.castToEmptyList() } - assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } - assertNotNull(term.castToFact()) - assertFailsWith(ClassCastException::class) { term.castToIndicator() } - assertFailsWith(ClassCastException::class) { term.castToInteger() } - assertFailsWith(ClassCastException::class) { term.castToList() } - assertFailsWith(ClassCastException::class) { term.castToNumeric() } - assertFailsWith(ClassCastException::class) { term.castToReal() } - assertNotNull(term.castToRule()) - assertFailsWith(ClassCastException::class) { term.castToBlock() } - assertNotNull(term.castToStruct()) - assertNotNull(term.castToTerm()) - assertFailsWith(ClassCastException::class) { term.castToTruth() } - assertFailsWith(ClassCastException::class) { term.castToTuple() } - assertFailsWith(ClassCastException::class) { term.castToVar() } - } - - override fun visitDirective(term: Directive) { - assertFailsWith(ClassCastException::class) { term.castToAtom() } - assertNotNull(term.castToClause()) - assertFailsWith(ClassCastException::class) { term.castToCons() } - assertFailsWith(ClassCastException::class) { term.castToConstant() } - assertNotNull(term.castToDirective()) - assertFailsWith(ClassCastException::class) { term.castToEmptyList() } - assertFailsWith(ClassCastException::class) { term.castToEmptyBlock() } - assertFailsWith(ClassCastException::class) { term.castToFact() } - assertFailsWith(ClassCastException::class) { term.castToIndicator() } - assertFailsWith(ClassCastException::class) { term.castToInteger() } - assertFailsWith(ClassCastException::class) { term.castToList() } - assertFailsWith(ClassCastException::class) { term.castToNumeric() } - assertFailsWith(ClassCastException::class) { term.castToReal() } - assertFailsWith(ClassCastException::class) { term.castToRule() } - assertFailsWith(ClassCastException::class) { term.castToBlock() } - assertNotNull(term.castToStruct()) - assertNotNull(term.castToTerm()) - assertFailsWith(ClassCastException::class) { term.castToTruth() } - assertFailsWith(ClassCastException::class) { term.castToTuple() } - assertFailsWith(ClassCastException::class) { term.castToVar() } - } - } - - private val positiveTypeTester = object : TermVisitor { - override fun defaultValue(term: Term) { - assertSame(term, term.castToTerm()) - assertSame(term, term.asTerm()) - assertSame(term, term.castTo()) - assertSame(term, term.`as`()) - } - - override fun visitVar(term: Var) { - assertSame(term, term.castToVar()) - assertSame(term, term.asVar()) - assertSame(term, term.castTo()) - assertSame(term, term.`as`()) - } - - override fun visitStruct(term: Struct) { - assertSame(term, term.castToStruct()) - assertSame(term, term.asStruct()) - assertSame(term, term.castTo()) - assertSame(term, term.`as`()) - } - - override fun visitAtom(term: Atom) { - assertSame(term, term.castToAtom()) - assertSame(term, term.asAtom()) - assertSame(term, term.castTo()) - assertSame(term, term.`as`()) - } - - override fun visitTruth(term: Truth) { - assertSame(term, term.castToTruth()) - assertSame(term, term.asTruth()) - assertSame(term, term.castTo()) - assertSame(term, term.`as`()) - } - - override fun visitInteger(term: Integer) { - assertSame(term, term.castToInteger()) - assertSame(term, term.asInteger()) - assertSame(term, term.castTo()) - assertSame(term, term.`as`()) - } - - override fun visitReal(term: Real) { - assertSame(term, term.castToReal()) - assertSame(term, term.asReal()) - assertSame(term, term.castTo()) - assertSame(term, term.`as`()) - } - - override fun visitBlock(term: Block) { - assertSame(term, term.castToBlock()) - assertSame(term, term.asBlock()) - assertSame(term, term.castTo()) - assertSame(term, term.`as`()) - } - - override fun visitEmptyBlock(term: EmptyBlock) { - assertSame(term, term.castToEmptyBlock()) - assertSame(term, term.asEmptyBlock()) - assertSame(term, term.castTo()) - assertSame(term, term.`as`()) - } - - override fun visitCons(term: Cons) { - assertSame(term, term.castToCons()) - assertSame(term, term.asCons()) - assertSame(term, term.castTo()) - assertSame(term, term.`as`()) - } - - override fun visitEmptyList(term: EmptyList) { - assertSame(term, term.castToEmptyList()) - assertSame(term, term.asEmptyList()) - assertSame(term, term.castTo()) - assertSame(term, term.`as`()) - } - - override fun visitTuple(term: Tuple) { - assertSame(term, term.castToTuple()) - assertSame(term, term.asTuple()) - assertSame(term, term.castTo()) - assertSame(term, term.`as`()) - } - - override fun visitIndicator(term: Indicator) { - assertSame(term, term.castToIndicator()) - assertSame(term, term.asIndicator()) - assertSame(term, term.castTo()) - assertSame(term, term.`as`()) - } - - override fun visitRule(term: Rule) { - assertSame(term, term.castToRule()) - assertSame(term, term.asRule()) - assertSame(term, term.castTo()) - assertSame(term, term.`as`()) - } - - override fun visitFact(term: Fact) { - assertSame(term, term.castToFact()) - assertSame(term, term.asFact()) - assertSame(term, term.castTo()) - assertSame(term, term.`as`()) - } - - override fun visitDirective(term: Directive) { - assertSame(term, term.castToDirective()) - assertSame(term, term.asDirective()) - assertSame(term, term.castTo()) - assertSame(term, term.`as`()) - } - } } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TermComparisonTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TermComparisonTest.kt index 893da17f2..7cad051e6 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TermComparisonTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TermComparisonTest.kt @@ -4,26 +4,29 @@ import kotlin.test.Test import kotlin.test.assertEquals class TermComparisonTest { - - private val base = listOf( - Var.of("A"), - Var.of("A"), - Var.of("B"), - Var.of("C"), - Var.anonymous(), - Var.anonymous() - ).sortedWith { x, y -> compareStringsLocaleIndependently(x.completeName, y.completeName) } + listOf( - Real.of(1.1), - Real.of(2.2) - ).sortedWith { x, y -> x.decimalValue.compareTo(y.decimalValue) } + listOf( - Integer.of(1), - Integer.of(2) - ).sortedWith { x, y -> x.intValue.compareTo(y.intValue) } + listOf( - Atom.of(""), - Atom.of("a"), - Atom.of("a b"), - Atom.of("b") - ).sortedWith { x, y -> compareStringsLocaleIndependently(x.value, y.value) } + private val base = + listOf( + Var.of("A"), + Var.of("A"), + Var.of("B"), + Var.of("C"), + Var.anonymous(), + Var.anonymous(), + ).sortedWith { x, y -> compareStringsLocaleIndependently(x.completeName, y.completeName) } + + listOf( + Real.of(1.1), + Real.of(2.2), + ).sortedWith { x, y -> x.decimalValue.compareTo(y.decimalValue) } + + listOf( + Integer.of(1), + Integer.of(2), + ).sortedWith { x, y -> x.intValue.compareTo(y.intValue) } + + listOf( + Atom.of(""), + Atom.of("a"), + Atom.of("a b"), + Atom.of("b"), + ).sortedWith { x, y -> compareStringsLocaleIndependently(x.value, y.value) } private val ordered = base + base.map { Struct.of("f", it) } + base.map { Struct.of("g", it) } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TermTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TermTest.kt index 5578cfca5..bd0ac0455 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TermTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TermTest.kt @@ -9,9 +9,7 @@ import kotlin.test.assertTrue import kotlin.collections.List as KtList class TermTest { - private data class MyStruct(override val functor: String, override val args: KtList) : Struct { - override fun freshCopy(): Struct { return freshCopy(Scope.empty()) } @@ -24,7 +22,10 @@ class TermTest { override fun addFirst(argument: Term): Struct = throw NotImplementedError() - override fun insertAt(index: Int, argument: Term): Struct = throw NotImplementedError() + override fun insertAt( + index: Int, + argument: Term, + ): Struct = throw NotImplementedError() override fun setFunctor(functor: String): Struct = throw NotImplementedError() @@ -41,7 +42,10 @@ class TermTest { return if (other is Term) equals(other, true) else false } - override fun equals(other: Term, useVarCompleteName: Boolean): Boolean { + override fun equals( + other: Term, + useVarCompleteName: Boolean, + ): Boolean { return other is MyStruct && other.arity == arity && other.functor == functor && other.args.mapIndexed { i, term -> term.equals(args[i], useVarCompleteName) }.all { it } } @@ -69,35 +73,38 @@ class TermTest { override fun accept(visitor: TermVisitor): T = visitor.visitStruct(this) } + @Suppress("ktlint:standard:property-naming", "PrivatePropertyName") private val X = Var.of("X") private val sub = Substitution.unifier(X, Integer.ONE) - private val compounds = listOf( - MyStruct("f", listOf(X)), - Struct.of("g", X), - List.of(X), - Block.of(X), - Tuple.of(X, X), - Fact.of(MyStruct("f", listOf(X))), - Fact.of(Struct.of("g", X)), - Fact.of(List.of(X)), - Fact.of(Block.of(X)), - Fact.of(Tuple.of(X, X)) - ) - - private val expected = listOf( - MyStruct("f", listOf(Integer.ONE)), - Struct.of("g", Integer.ONE), - List.of(Integer.ONE), - Block.of(Integer.ONE), - Tuple.of(Integer.ONE, Integer.ONE), - Fact.of(MyStruct("f", listOf(Integer.ONE))), - Fact.of(Struct.of("g", Integer.ONE)), - Fact.of(List.of(Integer.ONE)), - Fact.of(Block.of(Integer.ONE)), - Fact.of(Tuple.of(Integer.ONE, Integer.ONE)) - ) + private val compounds = + listOf( + MyStruct("f", listOf(X)), + Struct.of("g", X), + List.of(X), + Block.of(X), + Tuple.of(X, X), + Fact.of(MyStruct("f", listOf(X))), + Fact.of(Struct.of("g", X)), + Fact.of(List.of(X)), + Fact.of(Block.of(X)), + Fact.of(Tuple.of(X, X)), + ) + + private val expected = + listOf( + MyStruct("f", listOf(Integer.ONE)), + Struct.of("g", Integer.ONE), + List.of(Integer.ONE), + Block.of(Integer.ONE), + Tuple.of(Integer.ONE, Integer.ONE), + Fact.of(MyStruct("f", listOf(Integer.ONE))), + Fact.of(Struct.of("g", Integer.ONE)), + Fact.of(List.of(Integer.ONE)), + Fact.of(Block.of(Integer.ONE)), + Fact.of(Tuple.of(Integer.ONE, Integer.ONE)), + ) @Test fun substitutionApplyToPreservesReturnsNullWithFailedSubstitution() { diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TestClauseManipulation.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TestClauseManipulation.kt index 70c461bf4..6ead2c7a7 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TestClauseManipulation.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TestClauseManipulation.kt @@ -4,7 +4,6 @@ import kotlin.test.Test import kotlin.test.assertEquals class TestClauseManipulation { - val directive = Directive.of(Atom.of("a"), Atom.of("b")) // :- a, b. val fact = Fact.of(Struct.of("f", Integer.ONE)) // f(1). @@ -16,15 +15,15 @@ class TestClauseManipulation { val otherHead = Struct.of("f", Integer.of(2)) assertEquals( Rule.of(otherHead, directive.body), - directive.setHead(otherHead) + directive.setHead(otherHead), ) assertEquals( Rule.of(otherHead, rule.body), - rule.setHead(otherHead) + rule.setHead(otherHead), ) assertEquals( Fact.of(otherHead), - fact.setHead(otherHead) + fact.setHead(otherHead), ) } @@ -33,15 +32,15 @@ class TestClauseManipulation { val otherHead = Struct.of("g", Integer.ONE) assertEquals( directive, - directive.setHeadFunctor("g") + directive.setHeadFunctor("g"), ) assertEquals( Rule.of(otherHead, rule.body), - rule.setHeadFunctor("g") + rule.setHeadFunctor("g"), ) assertEquals( Fact.of(otherHead), - fact.setHeadFunctor("g") + fact.setHeadFunctor("g"), ) } @@ -50,15 +49,15 @@ class TestClauseManipulation { val otherHead = Struct.of("f", Atom.of("a"), Atom.of("b")) assertEquals( directive, - directive.setHeadArgs(*otherHead.args.toTypedArray()) + directive.setHeadArgs(*otherHead.args.toTypedArray()), ) assertEquals( Rule.of(otherHead, rule.body), - rule.setHeadArgs(*otherHead.args.toTypedArray()) + rule.setHeadArgs(*otherHead.args.toTypedArray()), ) assertEquals( Fact.of(otherHead), - fact.setHeadArgs(*otherHead.args.toTypedArray()) + fact.setHeadArgs(*otherHead.args.toTypedArray()), ) } @@ -67,15 +66,15 @@ class TestClauseManipulation { val otherHead = Struct.of("f", Integer.ONE, Atom.of("b")) assertEquals( directive, - directive.addLastHeadArg(otherHead.args.last()) + directive.addLastHeadArg(otherHead.args.last()), ) assertEquals( Rule.of(otherHead, rule.body), - rule.addLastHeadArg(otherHead.args.last()) + rule.addLastHeadArg(otherHead.args.last()), ) assertEquals( Fact.of(otherHead), - fact.addLastHeadArg(otherHead.args.last()) + fact.addLastHeadArg(otherHead.args.last()), ) } @@ -84,15 +83,15 @@ class TestClauseManipulation { val otherHead = Struct.of("f", Integer.ONE, Atom.of("b")) assertEquals( directive, - directive.appendHeadArg(otherHead.args.last()) + directive.appendHeadArg(otherHead.args.last()), ) assertEquals( Rule.of(otherHead, rule.body), - rule.appendHeadArg(otherHead.args.last()) + rule.appendHeadArg(otherHead.args.last()), ) assertEquals( Fact.of(otherHead), - fact.appendHeadArg(otherHead.args.last()) + fact.appendHeadArg(otherHead.args.last()), ) } @@ -101,15 +100,15 @@ class TestClauseManipulation { val otherHead = Struct.of("f", Atom.of("b"), Integer.ONE) assertEquals( directive, - directive.addFirstHeadArg(otherHead.args.first()) + directive.addFirstHeadArg(otherHead.args.first()), ) assertEquals( Rule.of(otherHead, rule.body), - rule.addFirstHeadArg(otherHead.args.first()) + rule.addFirstHeadArg(otherHead.args.first()), ) assertEquals( Fact.of(otherHead), - fact.addFirstHeadArg(otherHead.args.first()) + fact.addFirstHeadArg(otherHead.args.first()), ) } @@ -118,15 +117,15 @@ class TestClauseManipulation { val otherHead = Struct.of("f", Atom.of("b"), Integer.ONE) assertEquals( directive, - directive.insertHeadArg(0, otherHead[0]) + directive.insertHeadArg(0, otherHead[0]), ) assertEquals( Rule.of(otherHead, rule.body), - rule.insertHeadArg(0, otherHead[0]) + rule.insertHeadArg(0, otherHead[0]), ) assertEquals( Fact.of(otherHead), - fact.insertHeadArg(0, otherHead[0]) + fact.insertHeadArg(0, otherHead[0]), ) } @@ -134,19 +133,19 @@ class TestClauseManipulation { fun testHeadInspection() { assertEquals( rule.head.args, - rule.headArgs.toList() + rule.headArgs.toList(), ) assertEquals( fact.head.args, - fact.headArgs.toList() + fact.headArgs.toList(), ) assertEquals( rule.head.arity, - rule.headArity + rule.headArity, ) assertEquals( fact.head.arity, - fact.headArity + fact.headArity, ) for (i in 0 until rule.headArity) { @@ -163,15 +162,15 @@ class TestClauseManipulation { val otherBody = Tuple.of(Integer.ONE, Integer.of(2), Integer.of(3)) assertEquals( Directive.of(otherBody), - directive.setBody(otherBody) + directive.setBody(otherBody), ) assertEquals( Rule.of(rule.head, otherBody), - rule.setBody(otherBody) + rule.setBody(otherBody), ) assertEquals( Rule.of(fact.head, otherBody), - fact.setBody(otherBody) + fact.setBody(otherBody), ) } @@ -180,15 +179,15 @@ class TestClauseManipulation { val otherBody = Var.of("X") assertEquals( Directive.of(otherBody), - directive.setBodyItems(otherBody) + directive.setBodyItems(otherBody), ) assertEquals( Rule.of(rule.head, otherBody), - rule.setBodyItems(otherBody) + rule.setBodyItems(otherBody), ) assertEquals( Rule.of(fact.head, otherBody), - fact.setBodyItems(otherBody) + fact.setBodyItems(otherBody), ) } @@ -198,15 +197,15 @@ class TestClauseManipulation { val otherBody = tupleOf(varOf("X"), varOf("Y")) assertEquals( directiveOf(otherBody), - directive.setBodyItems(varOf("X"), varOf("Y")) + directive.setBodyItems(varOf("X"), varOf("Y")), ) assertEquals( ruleOf(rule.head, otherBody), - rule.setBodyItems(varOf("X"), varOf("Y")) + rule.setBodyItems(varOf("X"), varOf("Y")), ) assertEquals( ruleOf(fact.head, otherBody), - fact.setBodyItems(varOf("X"), varOf("Y")) + fact.setBodyItems(varOf("X"), varOf("Y")), ) } } @@ -216,15 +215,15 @@ class TestClauseManipulation { val otherBody = Tuple.of(Atom.of("a"), Atom.of("b"), Atom.of("c")) assertEquals( Directive.of(otherBody), - directive.addLastBodyItem(otherBody.unfoldedSequence.last()) + directive.addLastBodyItem(otherBody.unfoldedSequence.last()), ) assertEquals( Rule.of(rule.head, otherBody), - rule.addLastBodyItem(otherBody.unfoldedSequence.last()) + rule.addLastBodyItem(otherBody.unfoldedSequence.last()), ) assertEquals( Rule.of(fact.head, Truth.TRUE, otherBody.unfoldedSequence.last()), - fact.addLastBodyItem(otherBody.unfoldedSequence.last()) + fact.addLastBodyItem(otherBody.unfoldedSequence.last()), ) } @@ -233,15 +232,15 @@ class TestClauseManipulation { val otherBody = Tuple.of(Atom.of("a"), Atom.of("b"), Atom.of("c")) assertEquals( Directive.of(otherBody), - directive.appendBodyItem(otherBody.unfoldedSequence.last()) + directive.appendBodyItem(otherBody.unfoldedSequence.last()), ) assertEquals( Rule.of(rule.head, otherBody), - rule.appendBodyItem(otherBody.unfoldedSequence.last()) + rule.appendBodyItem(otherBody.unfoldedSequence.last()), ) assertEquals( Rule.of(fact.head, Truth.TRUE, otherBody.unfoldedSequence.last()), - fact.appendBodyItem(otherBody.unfoldedSequence.last()) + fact.appendBodyItem(otherBody.unfoldedSequence.last()), ) } @@ -250,15 +249,15 @@ class TestClauseManipulation { val otherBody = Tuple.of(Atom.of("c"), Atom.of("a"), Atom.of("b")) assertEquals( Directive.of(otherBody), - directive.addFirstBodyItem(otherBody.left) + directive.addFirstBodyItem(otherBody.left), ) assertEquals( Rule.of(rule.head, otherBody), - rule.addFirstBodyItem(otherBody.left) + rule.addFirstBodyItem(otherBody.left), ) assertEquals( Rule.of(fact.head, otherBody.left, Truth.TRUE), - fact.addFirstBodyItem(otherBody.left) + fact.addFirstBodyItem(otherBody.left), ) } @@ -267,15 +266,15 @@ class TestClauseManipulation { val otherBody = Tuple.of(Atom.of("c"), Atom.of("a"), Atom.of("b")) assertEquals( Directive.of(otherBody), - directive.insertBodyItem(0, otherBody.left) + directive.insertBodyItem(0, otherBody.left), ) assertEquals( Rule.of(rule.head, otherBody), - rule.insertBodyItem(0, otherBody.left) + rule.insertBodyItem(0, otherBody.left), ) assertEquals( Rule.of(fact.head, otherBody.left, Truth.TRUE), - fact.insertBodyItem(0, otherBody.left) + fact.insertBodyItem(0, otherBody.left), ) } @@ -283,40 +282,40 @@ class TestClauseManipulation { fun testBodyInspection() { assertEquals( directive.bodyAsTuple?.toList(), - directive.bodyItems.toList() + directive.bodyItems.toList(), ) assertEquals( rule.bodyAsTuple?.toList(), - rule.bodyItems.toList() + rule.bodyItems.toList(), ) assertEquals( fact.body, - fact.bodyItems.single() + fact.bodyItems.single(), ) assertEquals( directive.body.asTuple()?.size, - directive.bodySize + directive.bodySize, ) assertEquals( rule.body.asTuple()?.size, - rule.bodySize + rule.bodySize, ) assertEquals( 1, - fact.bodySize + fact.bodySize, ) for (i in 0 until directive.bodySize) { assertEquals( directive.bodyAsTuple?.unfoldedSequence?.drop(i)?.first(), - directive.getBodyItem(i) + directive.getBodyItem(i), ) } for (i in 0 until rule.bodySize) { assertEquals( rule.bodyAsTuple?.unfoldedSequence?.drop(i)?.first(), - rule.getBodyItem(i) + rule.getBodyItem(i), ) } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TestStructManipulation.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TestStructManipulation.kt index 4687db3f6..c8a9d5be5 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TestStructManipulation.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TestStructManipulation.kt @@ -4,54 +4,53 @@ import kotlin.test.Test import kotlin.test.assertEquals class TestStructManipulation { - - val f1 = Struct.of("f", Integer.ONE) // f(1) + val f1 = Struct.of("f", Integer.ONE) @Test fun testAddLast() { assertEquals( - Struct.of("f", Integer.ONE, Integer.of(2)), // f(1, 2) - f1.addLast(Integer.of(2)) + Struct.of("f", Integer.ONE, Integer.of(2)), + f1.addLast(Integer.of(2)), ) } @Test fun testAppend() { assertEquals( - Struct.of("f", Integer.ONE, Integer.of(2)), // f(1, 2) - f1.append(Integer.of(2)) + Struct.of("f", Integer.ONE, Integer.of(2)), + f1.append(Integer.of(2)), ) } @Test fun testAddFirst() { assertEquals( - Struct.of("f", Integer.of(2), Integer.ONE), // f(2, 1) - f1.addFirst(Integer.of(2)) + Struct.of("f", Integer.of(2), Integer.ONE), + f1.addFirst(Integer.of(2)), ) } @Test fun testSetArgs() { assertEquals( - Struct.of("f", Integer.of(2), Integer.of(3)), // f(2, 3) - f1.setArgs(Integer.of(2), Integer.of(3)) + Struct.of("f", Integer.of(2), Integer.of(3)), + f1.setArgs(Integer.of(2), Integer.of(3)), ) } @Test fun testSetFunctor() { assertEquals( - Struct.of("g", Integer.ONE), // g(1) - f1.setFunctor("g") + Struct.of("g", Integer.ONE), + f1.setFunctor("g"), ) } @Test fun testInsertAt() { assertEquals( - Struct.of("f", Integer.of(2), Integer.ONE), // f(2, 1) - f1.insertAt(0, Integer.of(2)) + Struct.of("f", Integer.of(2), Integer.ONE), + f1.insertAt(0, Integer.of(2)), ) } } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TestSubstitutionsMetadata.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TestSubstitutionsMetadata.kt index 9cfa655ff..1d7b8cd67 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TestSubstitutionsMetadata.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TestSubstitutionsMetadata.kt @@ -11,54 +11,55 @@ import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue +@Suppress("ktlint:standard:property-naming", "PrivatePropertyName") class TestSubstitutionsMetadata { - private val X = Var.of("X") private val Y = Var.of("Y") private val Z = Var.of("Z") - private val substitutions = listOf( - Substitution.failed(), - Substitution.empty(), - Substitution.unifier(Y, X), - Substitution.unifier(Y, Var.anonymous()), - Substitution.unifier(Y, Atom.of("atom")), - Substitution.unifier(Y, Integer.ONE), - Substitution.unifier(Y, Real.ONE_TENTH), - Substitution.unifier(Y, EmptyList()), - Substitution.unifier(Y, EmptyBlock()), - Substitution.unifier(Y, Cons.of(Real.ONE_HALF, X)), - Substitution.unifier(Y, Struct.of("g", X)), - Substitution.unifier(Y, List.of(X)), - Substitution.unifier(Y, Block.of(X)), - Substitution.unifier(Y, Tuple.of(X, X)), - Substitution.unifier(Y, Fact.of(Struct.of("f", X))), - Substitution.unifier(Y, Fact.of(List.of(X))), - Substitution.unifier(Y, Fact.of(Block.of(X))), - Substitution.unifier(Y, Fact.of(Tuple.of(X, X))), - Substitution.unifier(Y, Directive.of(Struct.of("h", X), Tuple.of(X, X))), - Substitution.unifier(Y, Rule.of(Struct.of("h", X), Tuple.of(X, X))), - Substitution.of(Z, X), - Substitution.of(Z, Var.anonymous()), - Substitution.of(Z, Atom.of("atom")), - Substitution.of(Z, Integer.ONE), - Substitution.of(Z, Real.ONE_TENTH), - Substitution.of(Z, EmptyList()), - Substitution.of(Z, EmptyBlock()), - Substitution.of(Z, Cons.of(Real.ONE_HALF, X)), - Substitution.of(Z, Struct.of("g", X)), - Substitution.of(Z, List.of(X)), - Substitution.of(Z, Block.of(X)), - Substitution.of(Z, Tuple.of(X, X)), - Substitution.of(Z, Fact.of(Struct.of("f", X))), - Substitution.of(Z, Fact.of(List.of(X))), - Substitution.of(Z, Fact.of(Block.of(X))), - Substitution.of(Z, Fact.of(Tuple.of(X, X))), - Substitution.of(Z, Directive.of(Struct.of("h", X), Tuple.of(X, X))), - Substitution.of(Z, Rule.of(Struct.of("h", X), Tuple.of(X, X))) - ) + private val substitutions = + listOf( + Substitution.failed(), + Substitution.empty(), + Substitution.unifier(Y, X), + Substitution.unifier(Y, Var.anonymous()), + Substitution.unifier(Y, Atom.of("atom")), + Substitution.unifier(Y, Integer.ONE), + Substitution.unifier(Y, Real.ONE_TENTH), + Substitution.unifier(Y, EmptyList()), + Substitution.unifier(Y, EmptyBlock()), + Substitution.unifier(Y, Cons.of(Real.ONE_HALF, X)), + Substitution.unifier(Y, Struct.of("g", X)), + Substitution.unifier(Y, List.of(X)), + Substitution.unifier(Y, Block.of(X)), + Substitution.unifier(Y, Tuple.of(X, X)), + Substitution.unifier(Y, Fact.of(Struct.of("f", X))), + Substitution.unifier(Y, Fact.of(List.of(X))), + Substitution.unifier(Y, Fact.of(Block.of(X))), + Substitution.unifier(Y, Fact.of(Tuple.of(X, X))), + Substitution.unifier(Y, Directive.of(Struct.of("h", X), Tuple.of(X, X))), + Substitution.unifier(Y, Rule.of(Struct.of("h", X), Tuple.of(X, X))), + Substitution.of(Z, X), + Substitution.of(Z, Var.anonymous()), + Substitution.of(Z, Atom.of("atom")), + Substitution.of(Z, Integer.ONE), + Substitution.of(Z, Real.ONE_TENTH), + Substitution.of(Z, EmptyList()), + Substitution.of(Z, EmptyBlock()), + Substitution.of(Z, Cons.of(Real.ONE_HALF, X)), + Substitution.of(Z, Struct.of("g", X)), + Substitution.of(Z, List.of(X)), + Substitution.of(Z, Block.of(X)), + Substitution.of(Z, Tuple.of(X, X)), + Substitution.of(Z, Fact.of(Struct.of("f", X))), + Substitution.of(Z, Fact.of(List.of(X))), + Substitution.of(Z, Fact.of(Block.of(X))), + Substitution.of(Z, Fact.of(Tuple.of(X, X))), + Substitution.of(Z, Directive.of(Struct.of("h", X), Tuple.of(X, X))), + Substitution.of(Z, Rule.of(Struct.of("h", X), Tuple.of(X, X))), + ) private data class Metadata(val value: T) @@ -126,7 +127,13 @@ class TestSubstitutionsMetadata { @Test fun settingMultipleTagsPreservesEquality() { - val taggedSubstitutions = substitutions.map { it.setTags(someKey to someValue1, someOtherKey to someOtherValue) } + val taggedSubstitutions = + substitutions.map { + it.setTags( + someKey to someValue1, + someOtherKey to someOtherValue, + ) + } for ((nonTagged, tagged) in substitutions.zip(taggedSubstitutions)) { assertEquals(nonTagged, tagged) assertEquals(nonTagged.hashCode(), tagged.hashCode()) @@ -137,7 +144,13 @@ class TestSubstitutionsMetadata { @Test fun clearingTagsPreservesEquality() { - val taggedSubstitutions = substitutions.map { it.setTags(someKey to someValue1, someOtherKey to someOtherValue) } + val taggedSubstitutions = + substitutions.map { + it.setTags( + someKey to someValue1, + someOtherKey to someOtherValue, + ) + } for ((tagged, cleared) in taggedSubstitutions.zip(taggedSubstitutions.map { it.clearTags() })) { assertEquals(tagged, cleared) assertEquals(tagged.hashCode(), cleared.hashCode()) @@ -148,7 +161,13 @@ class TestSubstitutionsMetadata { @Test fun addingAnExistingTagReplacesThatTag() { - val taggedSubstitutions = substitutions.map { it.setTags(someKey to someValue1, someOtherKey to someOtherValue) } + val taggedSubstitutions = + substitutions.map { + it.setTags( + someKey to someValue1, + someOtherKey to someOtherValue, + ) + } for (replaced in taggedSubstitutions.map { it.addTag(someKey, someValue2) }) { assertEquals(someValue2, replaced.getTag>(someKey)) } @@ -171,7 +190,10 @@ class TestSubstitutionsMetadata { } } - private fun summingMergesTags(other: Substitution, sum: Substitution.(Substitution) -> Substitution) { + private fun summingMergesTags( + other: Substitution, + sum: Substitution.(Substitution) -> Substitution, + ) { val tags = mapOf(someKey to someValue1, someOtherKey to someValue2) for (substitution in substitutions.map { it.setTags(tags) }) { assertEquals(tags, substitution.tags) diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TestTermMetadata.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TestTermMetadata.kt index 5699f7247..96d24d5be 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TestTermMetadata.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TestTermMetadata.kt @@ -12,28 +12,30 @@ import kotlin.test.assertNull import kotlin.test.assertTrue class TestTermMetadata { + @Suppress("ktlint:standard:property-naming", "PrivatePropertyName") private val X = Var.of("X") - private val terms = listOf( - X, - Var.anonymous(), - Atom.of("atom"), - Integer.ONE, - Real.ONE_TENTH, - EmptyList(), - EmptyBlock(), - Cons.of(Real.ONE_HALF, X), - Struct.of("g", X), - List.of(X), - Block.of(X), - Tuple.of(X, X), - Fact.of(Struct.of("f", X)), - Fact.of(List.of(X)), - Fact.of(Block.of(X)), - Fact.of(Tuple.of(X, X)), - Directive.of(Struct.of("h", X), Tuple.of(X, X)), - Rule.of(Struct.of("h", X), Tuple.of(X, X)) - ) + private val terms = + listOf( + X, + Var.anonymous(), + Atom.of("atom"), + Integer.ONE, + Real.ONE_TENTH, + EmptyList(), + EmptyBlock(), + Cons.of(Real.ONE_HALF, X), + Struct.of("g", X), + List.of(X), + Block.of(X), + Tuple.of(X, X), + Fact.of(Struct.of("f", X)), + Fact.of(List.of(X)), + Fact.of(Block.of(X)), + Fact.of(Tuple.of(X, X)), + Directive.of(Struct.of("h", X), Tuple.of(X, X)), + Rule.of(Struct.of("h", X), Tuple.of(X, X)), + ) private data class Metadata(val value: T) diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TruthTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TruthTest.kt index 27c52e986..0562f06f5 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TruthTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TruthTest.kt @@ -10,8 +10,8 @@ import kotlin.test.assertSame * * @author Enrico */ +@Suppress("ktlint:standard:property-naming", "PrivatePropertyName") internal class TruthTest { - private val TRUE = TruthImpl(Terms.TRUE_FUNCTOR, true) private val FAIL = TruthImpl(Terms.FAIL_FUNCTOR, false) private val FALSE = TruthImpl(Terms.FALSE_FUNCTOR, false) diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TupleTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TupleTest.kt index 6589e0799..d289f94be 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TupleTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/TupleTest.kt @@ -16,7 +16,6 @@ import kotlin.test.assertSame * @author Enrico */ internal class TupleTest { - private val correctInstances = TupleUtils.tupleInstances(::TupleImpl) @Test diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/VarTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/VarTest.kt index 510a603c8..0f2981aa7 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/VarTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/VarTest.kt @@ -20,7 +20,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class VarTest { - @Test fun varRegexCorrect() { assertTrue(VarUtils.correctlyNamedVars.all { it matches Var.NAME_PATTERN }) diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/AtomImplTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/AtomImplTest.kt index ce8c28df5..c97cc0cc2 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/AtomImplTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/AtomImplTest.kt @@ -19,14 +19,13 @@ import kotlin.test.assertTrue * @author Enrico */ internal class AtomImplTest { - private val mixedAtomInstances = AtomUtils.mixedAtoms.map(::AtomImpl) @Test fun functorCorrectness() { onCorrespondingItems( AtomUtils.mixedAtoms, - mixedAtomInstances.map { it.functor } + mixedAtomInstances.map { it.functor }, ) { atomString, atomInstanceFunctor -> assertEquals(atomString, atomInstanceFunctor) } } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/BlockImplTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/BlockImplTest.kt index 1d4117459..a274ccbf6 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/BlockImplTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/BlockImplTest.kt @@ -22,7 +22,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class BlockImplTest { - private val mixedBlocksInstances = BlockUtils.mixedBlocksTupleWrapped.map(::BlockImpl) @Test @@ -35,7 +34,7 @@ internal class BlockImplTest { onCorrespondingItems( BlockUtils.mixedBlocksTupleWrapped, mixedBlocksInstances.map { it.args.first() }, - ::assertEqualities + ::assertEqualities, ) } @@ -54,7 +53,7 @@ internal class BlockImplTest { onCorrespondingItems( correctElementLists, - mixedBlocksInstances.map { it.unfoldedSequence.toList() } + mixedBlocksInstances.map { it.unfoldedSequence.toList() }, ) { expected, actual -> assertEquals(expected, actual) } } @@ -64,7 +63,7 @@ internal class BlockImplTest { onCorrespondingItems( correctElementLists, - mixedBlocksInstances.map { it.unfoldedArray.toList() } + mixedBlocksInstances.map { it.unfoldedArray.toList() }, ) { expectedList, actualList -> assertEquals(expectedList, actualList) } } @@ -74,7 +73,7 @@ internal class BlockImplTest { onCorrespondingItems( blocksToString, - mixedBlocksInstances.map { it.toString() } + mixedBlocksInstances.map { it.toString() }, ) { expectedToString, actualToString -> assertEquals(expectedToString, actualToString) } } @@ -110,7 +109,10 @@ internal class BlockImplTest { fun toArrayReturnValue() { val mixedBlocks = BlockUtils.mixedBlocks.map { it.toList() } - onCorrespondingItems(mixedBlocks, mixedBlocksInstances.map { it.toArray().toList() }) { expectedList, actualList -> + onCorrespondingItems( + mixedBlocks, + mixedBlocksInstances.map { it.toArray().toList() }, + ) { expectedList, actualList -> assertEquals(expectedList, actualList) } } @@ -121,7 +123,7 @@ internal class BlockImplTest { onCorrespondingItems( mixedBlocks, - mixedBlocksInstances.map { it.toSequence().toList() } + mixedBlocksInstances.map { it.toSequence().toList() }, ) { expectedList, actualList -> assertEquals(expectedList, actualList) } } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/ConsImplTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/ConsImplTest.kt index d35855a2b..03a753b17 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/ConsImplTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/ConsImplTest.kt @@ -18,7 +18,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class ConsImplTest { - private val consInstances = ConsUtils.mixedConsInstances(::ConsImpl) private val consInstancesHeads = ConsUtils.mixedConsInstancesHeads private val consInstancesTails = ConsUtils.mixedConsInstancesTails(::ConsImpl) @@ -53,7 +52,7 @@ internal class ConsImplTest { fun unfoldedListCorrect() { onCorrespondingItems( consInstancesUnfoldedLists, - consInstances.map { it.unfoldedList } + consInstances.map { it.unfoldedList }, ) { expectedList, actualList -> assertEquals(expectedList, actualList) } } @@ -61,7 +60,7 @@ internal class ConsImplTest { fun unfoldedSequenceCorrect() { onCorrespondingItems( consInstancesUnfoldedLists, - consInstances.map { it.unfoldedSequence.toList() } + consInstances.map { it.unfoldedSequence.toList() }, ) { expectedList, actualList -> assertEquals(expectedList, actualList) } } @@ -69,7 +68,7 @@ internal class ConsImplTest { fun unfoldedArrayCorrect() { onCorrespondingItems( consInstancesUnfoldedLists, - consInstances.map { it.unfoldedArray.toList() } + consInstances.map { it.unfoldedArray.toList() }, ) { expectedList, actualList -> assertEquals(expectedList, actualList) } } @@ -84,7 +83,7 @@ internal class ConsImplTest { fun toArrayReturnValue() { onCorrespondingItems( consInstancesElementLists, - consInstances.map { it.toArray().toList() } + consInstances.map { it.toArray().toList() }, ) { expectedList, actualList -> assertEquals(expectedList, actualList) } } @@ -92,7 +91,7 @@ internal class ConsImplTest { fun toSequenceReturnValue() { onCorrespondingItems( consInstancesElementLists, - consInstances.map { it.toSequence().toList() } + consInstances.map { it.toSequence().toList() }, ) { expectedList, actualList -> assertEquals(expectedList, actualList) } } @@ -120,7 +119,7 @@ internal class ConsImplTest { ConsUtils.oneElementList(::ConsImpl).isGround, ConsUtils.twoElementList(::ConsImpl).isGround, ConsUtils.twoElementListWithPipe(::ConsImpl).isGround, - ConsUtils.threeElementListWithPipe(::ConsImpl).isGround + ConsUtils.threeElementListWithPipe(::ConsImpl).isGround, ) assertTrue(ConsUtils.threeElementList(::ConsImpl).isGround) diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/DirectiveImplTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/DirectiveImplTest.kt index 04426514c..344c876fe 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/DirectiveImplTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/DirectiveImplTest.kt @@ -19,7 +19,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class DirectiveImplTest { - private val groundDirectivesInstances = DirectiveUtils.groundDirectives.map(::DirectiveImpl) private val nonGroundDirectivesInstances = DirectiveUtils.nonGroundDirectives.map(::DirectiveImpl) private val wellFormedDirectivesInstances = DirectiveUtils.wellFormedDirectives.map(::DirectiveImpl) @@ -36,7 +35,7 @@ internal class DirectiveImplTest { onCorrespondingItems( DirectiveUtils.mixedDirectives, mixedDirectivesInstances.map { it.body }, - ::assertEqualities + ::assertEqualities, ) } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/EmptyBlockImplTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/EmptyBlockImplTest.kt index 5b942c82c..65a78c731 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/EmptyBlockImplTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/EmptyBlockImplTest.kt @@ -15,7 +15,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class EmptyBlockImplTest { - private val testedObj = EmptyBlockImpl() @Test diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/EmptyListImplTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/EmptyListImplTest.kt index 4ec91f104..900b28f03 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/EmptyListImplTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/EmptyListImplTest.kt @@ -14,7 +14,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class EmptyListImplTest { - private val testedObj = EmptyListImpl() @Test diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/FactImplTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/FactImplTest.kt index 845d3dce1..0959bd837 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/FactImplTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/FactImplTest.kt @@ -20,7 +20,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class FactImplTest { - private val mixedFactInstances by lazy { FactUtils.mixedFacts.map(::FactImpl) } private val groundFactInstances by lazy { FactUtils.groundFacts.map(::FactImpl) } private val nonGroundFactInstances by lazy { FactUtils.nonGroundFacts.map(::FactImpl) } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/IndicatorImplTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/IndicatorImplTest.kt index 40f895c9e..7da5f5063 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/IndicatorImplTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/IndicatorImplTest.kt @@ -18,7 +18,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class IndicatorImplTest { - private val indicatorInstances = IndicatorUtils.mixedIndicators.map { (name, arity) -> IndicatorImpl(name, arity) } private val wellFormedIndicatorInstances = IndicatorUtils.wellFormedIndicators.map { (name, arity) -> IndicatorImpl(name, arity) } @@ -57,16 +56,17 @@ internal class IndicatorImplTest { onCorrespondingItems( correctIndicatedName, - wellFormedIndicatorInstances.map { it.indicatedName } + wellFormedIndicatorInstances.map { it.indicatedName }, ) { expected, actual -> assertEquals(expected, actual) } } @Test fun indicatedNameNullIfIndicatorNameNotWellFormed() { val correct = arrayOfNulls(IndicatorUtils.nonWellFormedNameIndicator.count()).toList() - val toBeTested = IndicatorUtils.nonWellFormedNameIndicator - .map { (name, arity) -> IndicatorImpl(name, arity) } - .map { it.indicatedName } + val toBeTested = + IndicatorUtils.nonWellFormedNameIndicator + .map { (name, arity) -> IndicatorImpl(name, arity) } + .map { it.indicatedName } onCorrespondingItems(correct, toBeTested) { expected, actual -> assertEquals(expected, actual) } } @@ -77,16 +77,17 @@ internal class IndicatorImplTest { onCorrespondingItems( correctIndicatedArity, - wellFormedIndicatorInstances.map { it.indicatedArity } + wellFormedIndicatorInstances.map { it.indicatedArity }, ) { expected, actual -> assertEquals(expected, actual) } } @Test fun indicatedArityNullIfIndicatorArityNotWellFormed() { val correct = arrayOfNulls(IndicatorUtils.nonWellFormedArityIndicator.count()).toList() - val toBeTested = IndicatorUtils.nonWellFormedArityIndicator - .map { (name, arity) -> IndicatorImpl(name, arity) } - .map { it.indicatedArity } + val toBeTested = + IndicatorUtils.nonWellFormedArityIndicator + .map { (name, arity) -> IndicatorImpl(name, arity) } + .map { it.indicatedArity } onCorrespondingItems(correct, toBeTested) { expected, actual -> assertEquals(expected, actual) } } @@ -97,7 +98,7 @@ internal class IndicatorImplTest { onCorrespondingItems( correctToString, - indicatorInstances.map { it.toString() } + indicatorInstances.map { it.toString() }, ) { expected, actual -> assertEquals(expected, actual) } } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/IntegerImplTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/IntegerImplTest.kt index 48c6720d8..1202bf113 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/IntegerImplTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/IntegerImplTest.kt @@ -25,14 +25,13 @@ import kotlin.test.assertTrue * @author Enrico */ class IntegerImplTest { - private val integerInstances = IntegerUtils.bigIntegers.map(::IntegerImpl) @Test fun correctValue() { onCorrespondingItems( IntegerUtils.bigIntegers, - integerInstances.map { it.value } + integerInstances.map { it.value }, ) { expectedValue, integerValue -> assertEquals(expectedValue, integerValue) } } @@ -40,7 +39,7 @@ class IntegerImplTest { fun correctIntValue() { onCorrespondingItems( IntegerUtils.bigIntegers, - integerInstances.map { it.intValue } + integerInstances.map { it.intValue }, ) { expectedValue, integerIntValue -> assertEquals(expectedValue, integerIntValue) } } @@ -50,7 +49,7 @@ class IntegerImplTest { onCorrespondingItems( expectedDecimals, - integerInstances.map { it.decimalValue } + integerInstances.map { it.decimalValue }, ) { expectedValue, integerDecimalValue -> assertEquals(expectedValue, integerDecimalValue) } } @@ -60,25 +59,25 @@ class IntegerImplTest { onCorrespondingItems( expectedToString, - integerInstances.map { it.toString() } + integerInstances.map { it.toString() }, ) { expectedString, integerToString -> assertEquals(expectedString, integerToString) } } @Suppress("LocalVariableName") @Test fun compareToWorksAsExpected() { - val `1` = IntegerImpl(BigInteger.of(1)) - val `2` = IntegerImpl(BigInteger.of(2)) + val one = IntegerImpl(BigInteger.of(1)) + val two = IntegerImpl(BigInteger.of(2)) - assertTrue(`1`.compareValueTo(`1`) == 0) - assertTrue(`1`.compareValueTo(`1`) >= 0) + assertTrue(one.compareValueTo(one) == 0) + assertTrue(one.compareValueTo(one) >= 0) - assertTrue(`1`.compareValueTo(`2`) != 0) - assertTrue(`1`.compareValueTo(`2`) <= 0) - assertTrue(`1`.compareValueTo(`2`) < 0) + assertTrue(one.compareValueTo(two) != 0) + assertTrue(one.compareValueTo(two) <= 0) + assertTrue(one.compareValueTo(two) < 0) - assertFalse(`1`.compareValueTo(`2`) >= 0) - assertFalse(`1`.compareValueTo(`2`) > 0) + assertFalse(one.compareValueTo(two) >= 0) + assertFalse(one.compareValueTo(two) > 0) } @Test diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/RealImplTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/RealImplTest.kt index b948a0c84..26028e357 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/RealImplTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/RealImplTest.kt @@ -22,7 +22,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class RealImplTest { - private val realInstances = RealUtils.bigDecimals.map(::RealImpl) @Test @@ -36,7 +35,7 @@ internal class RealImplTest { fun correctDecimalValue() { onCorrespondingItems( RealUtils.bigDecimals, - realInstances.map { it.decimalValue } + realInstances.map { it.decimalValue }, ) { expectedValue, realDecimalValue -> assertEquals(expectedValue, realDecimalValue) } } @@ -61,18 +60,18 @@ internal class RealImplTest { @Suppress("LocalVariableName") @Test fun compareToWorksAsExpected() { - val `1,1` = RealImpl(BigDecimal.of(1.1)) - val `1,22f` = RealImpl(BigDecimal.of(1.22f)) + val oneDotOne = RealImpl(BigDecimal.of(1.1)) + val oneDotTwentyTwo = RealImpl(BigDecimal.of(1.22f)) - assertTrue(`1,1`.compareValueTo(`1,1`) == 0) - assertTrue(`1,1`.compareValueTo(`1,1`) >= 0) + assertTrue(oneDotOne.compareValueTo(oneDotOne) == 0) + assertTrue(oneDotOne.compareValueTo(oneDotOne) >= 0) - assertTrue(`1,1`.compareValueTo(`1,22f`) != 0) - assertTrue(`1,1`.compareValueTo(`1,22f`) <= 0) - assertTrue(`1,1`.compareValueTo(`1,22f`) < 0) + assertTrue(oneDotOne.compareValueTo(oneDotTwentyTwo) != 0) + assertTrue(oneDotOne.compareValueTo(oneDotTwentyTwo) <= 0) + assertTrue(oneDotOne.compareValueTo(oneDotTwentyTwo) < 0) - assertFalse(`1,1`.compareValueTo(`1,22f`) >= 0) - assertFalse(`1,1`.compareValueTo(`1,22f`) > 0) + assertFalse(oneDotOne.compareValueTo(oneDotTwentyTwo) >= 0) + assertFalse(oneDotOne.compareValueTo(oneDotTwentyTwo) > 0) } @Test diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/RuleImplTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/RuleImplTest.kt index a834d12b3..ec5587574 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/RuleImplTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/RuleImplTest.kt @@ -20,7 +20,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class RuleImplTest { - private val groundRulesInstances = RuleUtils.groundRules.map { (head, body) -> RuleImpl(head, body) } private val nonGroundRulesInstances = RuleUtils.nonGroundRules.map { (head, body) -> RuleImpl(head, body) } private val wellFormedRulesInstances = RuleUtils.wellFormedRules.map { (head, body) -> RuleImpl(head, body) } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/ScopeImplTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/ScopeImplTest.kt index d80b7dd1b..cb1f1e266 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/ScopeImplTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/ScopeImplTest.kt @@ -48,7 +48,6 @@ import it.unibo.tuprolog.core.List as LogicList * @author Enrico */ internal class ScopeImplTest { - private lateinit var emptyScopeInstance: Scope private lateinit var nonEmptyScopeInstances: List private lateinit var mixedScopeInstances: List @@ -87,7 +86,7 @@ internal class ScopeImplTest { onCorrespondingItems( ScopeUtils.mixedScopes, mixedScopeInstances.map { it.variables }, - ::assertScopeCorrectContents + ::assertScopeCorrectContents, ) } @@ -151,7 +150,7 @@ internal class ScopeImplTest { val myResult = 3 onCorrespondingItems( mixedScopeInstances.map { myResult }, - mixedScopeInstances.map { it.with { myResult } } + mixedScopeInstances.map { it.with { myResult } }, ) { expected, actual -> assertEquals(expected, actual) } } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/StructImplTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/StructImplTest.kt index a72b7231e..e61e26b19 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/StructImplTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/StructImplTest.kt @@ -28,7 +28,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class StructImplTest { - private val mixedStructInstances = StructUtils.mixedStructs.map { (functor, args) -> StructImpl(functor, args) } private val nonSpecialStructInstances = StructUtils.nonSpecialStructs.map { (functor, args) -> StructImpl(functor, args) } @@ -40,7 +39,7 @@ internal class StructImplTest { fun functorCorrect() { onCorrespondingItems( StructUtils.mixedStructFunctors, - mixedStructInstances.map { it.functor } + mixedStructInstances.map { it.functor }, ) { expected, actual -> assertEquals(expected, actual) } @@ -50,7 +49,7 @@ internal class StructImplTest { fun argsCorrect() { onCorrespondingItems( StructUtils.mixedStructArguments, - mixedStructInstances.map { it.args } + mixedStructInstances.map { it.args }, ) { expected, actual -> assertEquals(expected, actual) } @@ -78,7 +77,7 @@ internal class StructImplTest { fun variablesCorrect() { onCorrespondingItems( StructUtils.mixedStructVariables, - mixedStructInstances.map { it.variables } + mixedStructInstances.map { it.variables }, ) { expected, actual -> assertEquals(expected.toList(), actual.toList()) } } @@ -110,10 +109,11 @@ internal class StructImplTest { @Test fun toStringWorksAsExpected() { - val correctToStrings = mixedStructInstances.map { - (if (it.isFunctorWellFormed) it.functor else "'${it.functor}'") + - (if (it.arity > 0) "(${it.args.joinToString(", ")})" else "") - } + val correctToStrings = + mixedStructInstances.map { + (if (it.isFunctorWellFormed) it.functor else "'${it.functor}'") + + (if (it.arity > 0) "(${it.args.joinToString(", ")})" else "") + } onCorrespondingItems(correctToStrings, mixedStructInstances.map { it.toString() }) { expected, actual -> assertEquals(expected, actual) } @@ -265,8 +265,9 @@ internal class StructImplTest { @Test fun freshCopyShouldRenewVariables() { - val nonGroundNonSpecialStructInstances = (StructUtils.nonGroundStructs - StructUtils.specialStructs) - .map { (functor, args) -> StructImpl(functor, args) } + val nonGroundNonSpecialStructInstances = + (StructUtils.nonGroundStructs - StructUtils.specialStructs) + .map { (functor, args) -> StructImpl(functor, args) } nonGroundNonSpecialStructInstances.forEach(StructUtils::assertFreshCopyRenewsContainedVariables) } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/TruthImplTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/TruthImplTest.kt index bfc86c149..69bee7edd 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/TruthImplTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/TruthImplTest.kt @@ -13,7 +13,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class TruthImplTest { - private val truthInstances = listOf(Truth.TRUE, Truth.FAIL, Truth.FALSE) @Test diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/TupleImplTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/TupleImplTest.kt index 06519cb43..6555c6055 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/TupleImplTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/TupleImplTest.kt @@ -18,7 +18,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class TupleImplTest { - private val twoElementsTuple = TupleUtils.twoElementTuple(::TupleImpl) private val threeElementsTuple = TupleUtils.threeElementTuple(::TupleImpl) @@ -56,7 +55,7 @@ internal class TupleImplTest { fun unfoldedListCorrect() { onCorrespondingItems( tupleInstancesElementLists, - tupleInstances.map { it.unfoldedList } + tupleInstances.map { it.unfoldedList }, ) { expectedList, actualList -> assertEquals(expectedList, actualList) } } @@ -64,7 +63,7 @@ internal class TupleImplTest { fun unfoldedSequenceCorrect() { onCorrespondingItems( tupleInstancesElementLists, - tupleInstances.map { it.unfoldedSequence.toList() } + tupleInstances.map { it.unfoldedSequence.toList() }, ) { expectedList, actualList -> assertEquals(expectedList, actualList) } } @@ -72,7 +71,7 @@ internal class TupleImplTest { fun unfoldedArrayCorrect() { onCorrespondingItems( tupleInstancesElementLists, - tupleInstances.map { it.unfoldedArray.toList() } + tupleInstances.map { it.unfoldedArray.toList() }, ) { expectedList, actualList -> assertEquals(expectedList, actualList) } } @@ -80,7 +79,7 @@ internal class TupleImplTest { fun toListReturnValue() { onCorrespondingItems( tupleInstancesElementLists, - tupleInstances.map { it.toList() } + tupleInstances.map { it.toList() }, ) { expectedList, actualList -> assertEquals(expectedList, actualList) } } @@ -88,7 +87,7 @@ internal class TupleImplTest { fun toArrayReturnValue() { onCorrespondingItems( tupleInstancesElementLists, - tupleInstances.map { it.toArray().toList() } + tupleInstances.map { it.toArray().toList() }, ) { expectedList, actualList -> assertEquals(expectedList, actualList) } } @@ -96,7 +95,7 @@ internal class TupleImplTest { fun toSequenceReturnValue() { onCorrespondingItems( tupleInstancesElementLists, - tupleInstances.map { it.toSequence().toList() } + tupleInstances.map { it.toSequence().toList() }, ) { expectedList, actualList -> assertEquals(expectedList, actualList) } } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/VarImplTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/VarImplTest.kt index aa39353e8..84d049da8 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/VarImplTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/impl/VarImplTest.kt @@ -24,7 +24,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class VarImplTest { - /** Contains mixed variables instances, correctly and incorrectly named */ private val mixedVarInstances = VarUtils.mixedVars.map { VarImpl(it) } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/integrationtests/TestEmptyBlock.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/integrationtests/TestEmptyBlock.kt index 3ff138e06..9c6a7ea24 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/integrationtests/TestEmptyBlock.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/integrationtests/TestEmptyBlock.kt @@ -12,18 +12,18 @@ import it.unibo.tuprolog.core.testutils.TermTypeAssertionUtils import kotlin.test.Test class TestEmptyBlock { - private val correctAtom = "{}" private val notCorrectAtom = "{ }" - private val heterogeneousCreatedInstances = listOf( - EmptyBlock(), - Empty.block(), - Block.empty(), - Block.of(), - Atom.of(correctAtom), - Struct.of(correctAtom) - ) + private val heterogeneousCreatedInstances = + listOf( + EmptyBlock(), + Empty.block(), + Block.empty(), + Block.of(), + Atom.of(correctAtom), + Struct.of(correctAtom), + ) @Test fun variousCreationMethodsCreateCorrectlyEmptyBlock() { diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/integrationtests/TestEmptyList.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/integrationtests/TestEmptyList.kt index 0706113be..640a67d78 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/integrationtests/TestEmptyList.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/integrationtests/TestEmptyList.kt @@ -12,18 +12,18 @@ import kotlin.test.Test import it.unibo.tuprolog.core.List as LogicList class TestEmptyList { - private val correctAtom = "[]" private val notCorrectAtom = "[ ]" - private val heterogeneousCreatedInstances = listOf( - EmptyList(), - Empty.list(), - LogicList.empty(), - LogicList.of(), - Atom.of(correctAtom), - Struct.of(correctAtom) - ) + private val heterogeneousCreatedInstances = + listOf( + EmptyList(), + Empty.list(), + LogicList.empty(), + LogicList.of(), + Atom.of(correctAtom), + Struct.of(correctAtom), + ) @Test fun variousCreationMethodsCreateCorrectlyEmptyList() { diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/integrationtests/TestFail.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/integrationtests/TestFail.kt index 514e9b5b6..6f195dbc2 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/integrationtests/TestFail.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/integrationtests/TestFail.kt @@ -11,15 +11,15 @@ import kotlin.test.Test import kotlin.test.assertTrue class TestFail { - private val correctAtom = "fail" private val notCorrectAtom = "false" - private val heterogeneousCreatedInstances = listOf( - Truth.FAIL, - Atom.of(correctAtom), - Struct.of(correctAtom) - ) + private val heterogeneousCreatedInstances = + listOf( + Truth.FAIL, + Atom.of(correctAtom), + Struct.of(correctAtom), + ) @Test fun variousCreationMethodsCreateCorrectlyFail() { diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/integrationtests/TestFalse.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/integrationtests/TestFalse.kt index 6bf88cb66..e5d2c6e6b 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/integrationtests/TestFalse.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/integrationtests/TestFalse.kt @@ -11,16 +11,16 @@ import kotlin.test.Test import kotlin.test.assertTrue class TestFalse { - private val correctAtom = "false" private val notCorrectAtom = "fail" - private val heterogeneousCreatedInstances = listOf( - Truth.FALSE, - Truth.of(false), - Atom.of(correctAtom), - Struct.of(correctAtom) - ) + private val heterogeneousCreatedInstances = + listOf( + Truth.FALSE, + Truth.of(false), + Atom.of(correctAtom), + Struct.of(correctAtom), + ) @Test fun variousCreationMethodsCreateCorrectlyFail() { diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/integrationtests/TestTrue.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/integrationtests/TestTrue.kt index 6cd8e8e15..929cd01b7 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/integrationtests/TestTrue.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/integrationtests/TestTrue.kt @@ -11,16 +11,16 @@ import kotlin.test.Test import kotlin.test.assertTrue class TestTrue { - private val correctAtom = "true" private val notCorrectAtom = "true " - private val heterogeneousCreatedInstances = listOf( - Truth.TRUE, - Truth.of(true), - Atom.of(correctAtom), - Struct.of(correctAtom) - ) + private val heterogeneousCreatedInstances = + listOf( + Truth.TRUE, + Truth.of(true), + Atom.of(correctAtom), + Struct.of(correctAtom), + ) @Test fun variousCreationMethodsCreateCorrectlyTrue() { diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/operators/OperatorSetTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/operators/OperatorSetTest.kt index f07c2319e..51f353331 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/operators/OperatorSetTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/operators/OperatorSetTest.kt @@ -12,7 +12,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class OperatorSetTest { - private val fakePlusOperator = Operator("+", Specifier.YFX, 500) private val fakeMinusOperator = Operator("-", Specifier.YFX, 500) private val fakeTimesOperator = Operator("*", Specifier.YFX, 400) @@ -68,11 +67,11 @@ internal class OperatorSetTest { assertEquals(OperatorSet(), OperatorSet()) assertEquals( operatorSet, - OperatorSet(fakePlusOperator, fakeMinusOperator, fakeTimesOperator, fakeDivisionOperator) + OperatorSet(fakePlusOperator, fakeMinusOperator, fakeTimesOperator, fakeDivisionOperator), ) assertEquals( operatorSet, - OperatorSet(fakeMinusOperator, fakePlusOperator, fakeDivisionOperator, fakeTimesOperator) + OperatorSet(fakeMinusOperator, fakePlusOperator, fakeDivisionOperator, fakeTimesOperator), ) assertNotEquals(operatorSet, OperatorSet()) @@ -92,17 +91,17 @@ internal class OperatorSetTest { assertEquals( expectedFunctor, actualOperator.functor, - "$actualOperator functor expected to be: $expectedFunctor" + "$actualOperator functor expected to be: $expectedFunctor", ) assertEquals( expectedSpecifier, actualOperator.specifier, - "$actualOperator specifier expected to be: $expectedSpecifier" + "$actualOperator specifier expected to be: $expectedSpecifier", ) assertEquals( expectedPriority, actualOperator.priority, - "$actualOperator priority expected to be: $expectedPriority" + "$actualOperator priority expected to be: $expectedPriority", ) } } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/operators/OperatorTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/operators/OperatorTest.kt index 2e2eb6e3c..c27a466e1 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/operators/OperatorTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/operators/OperatorTest.kt @@ -20,7 +20,6 @@ import kotlin.test.fail * @author Enrico */ internal class OperatorTest { - private val plusFunctor = "+" private val plusSpecifier = Specifier.YFX private val plusPriority = 500 @@ -91,20 +90,21 @@ internal class OperatorTest { fun templateCorrect() { assertStructurallyEquals( Operator.TEMPLATE, - Struct.of(Operator.FUNCTOR, Var.anonymous(), Var.anonymous(), Var.anonymous()) + Struct.of(Operator.FUNCTOR, Var.anonymous(), Var.anonymous(), Var.anonymous()), ) } @Test fun fromTermParsesCorrectOperator() { - val toBeTested = Operator.fromTerm( - Struct.of( - Operator.FUNCTOR, - plusPriority.toTerm(), - plusSpecifier.toTerm(), - plusFunctor.toTerm() + val toBeTested = + Operator.fromTerm( + Struct.of( + Operator.FUNCTOR, + plusPriority.toTerm(), + plusSpecifier.toTerm(), + plusFunctor.toTerm(), + ), ) - ) assertEquals(plusOperator, toBeTested) toBeTested?.run { assertTrue(plusOperator.compareTo(toBeTested) == 0) } @@ -118,7 +118,7 @@ internal class OperatorTest { functor: String = Operator.FUNCTOR, priority: Term = plusPriority.toTerm(), specifier: Term = plusSpecifier.toTerm(), - opFunctor: Term = plusFunctor.toTerm() + opFunctor: Term = plusFunctor.toTerm(), ) = Operator.fromTerm(Struct.of(functor, priority, specifier, opFunctor)) assertEquals(plusOperator, testFromTerm()) diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/operators/SpecifierTest.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/operators/SpecifierTest.kt index c1ed5914d..28c080cea 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/operators/SpecifierTest.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/operators/SpecifierTest.kt @@ -27,7 +27,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class SpecifierTest { - private val prefixSpecifiers = setOf(FX, FY) private val postfixSpecifiers = setOf(XF, YF) private val infixSpecifiers = setOf(XFX, YFX, XFY) diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/operators/testutils/OperatorSetUtils.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/operators/testutils/OperatorSetUtils.kt index b56073891..dde52ce56 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/operators/testutils/OperatorSetUtils.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/operators/testutils/OperatorSetUtils.kt @@ -10,7 +10,6 @@ import it.unibo.tuprolog.core.operators.Specifier * @author Enrico */ internal object OperatorSetUtils { - /** The reference "table" of [Operator]s to test if they are stored correctly */ internal val defaultOperators by lazy { listOf( @@ -53,7 +52,7 @@ internal object OperatorSetUtils { Triple(":-", Specifier.FX, 1200), Triple("?-", Specifier.FX, 1200), Triple(":-", Specifier.XFX, 1200), - Triple("-->", Specifier.XFX, 1200) + Triple("-->", Specifier.XFX, 1200), ) } } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/AssertionUtils.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/AssertionUtils.kt index 795695538..fcd103239 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/AssertionUtils.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/AssertionUtils.kt @@ -11,7 +11,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal object AssertionUtils { - /** Utility extension function to drop last element of a List */ fun List.dropLast(): List = this.dropLast(1) @@ -27,7 +26,10 @@ internal object AssertionUtils { assertTrue("Element at index ${boolean.indexOf(true)} expected to be `false`") { boolean.none { it } } /** Asserts mutual structural equality for two [Term]s */ - fun assertStructurallyEquals(expected: Term, actual: Term) { + fun assertStructurallyEquals( + expected: Term, + actual: Term, + ) { assertTrue("$actual should be structurally equal to $expected, while it is not") { expected structurallyEquals actual } @@ -37,52 +39,72 @@ internal object AssertionUtils { } /** Asserts mutual equality for two [Term]s, using simple names for [Var]iables */ - fun assertEqualsUsingVariablesSimpleNames(expected: Term, actual: Term) = - assertTrue( - expected.equals(actual, false), - actual.equals(expected, false) - ) + fun assertEqualsUsingVariablesSimpleNames( + expected: Term, + actual: Term, + ) = assertTrue( + expected.equals(actual, false), + actual.equals(expected, false), + ) /** Asserts mutual inequality for two [Term]s, using simple names for [Var]iables */ - fun assertNotEqualsUsingVariablesSimpleNames(expected: Term, actual: Term) = - assertFalse( - expected.equals(actual, false), - actual.equals(expected, false) - ) + fun assertNotEqualsUsingVariablesSimpleNames( + expected: Term, + actual: Term, + ) = assertFalse( + expected.equals(actual, false), + actual.equals(expected, false), + ) /** Asserts mutual not structural equality for two [Term]s */ - fun assertNotStructurallyEquals(expected: Term, actual: Term) = - assertFalse( - expected structurallyEquals actual, - actual structurallyEquals expected - ) + fun assertNotStructurallyEquals( + expected: Term, + actual: Term, + ) = assertFalse( + expected structurallyEquals actual, + actual structurallyEquals expected, + ) /** Asserts all types of equalities (normal, strict and structural) for two [Term]s */ - fun assertEqualities(expected: Term, actual: Term) { + fun assertEqualities( + expected: Term, + actual: Term, + ) { assertStructurallyEquals(expected, actual) assertEquals(expected, actual) assertEqualsUsingVariablesSimpleNames(expected, actual) } /** Asserts not equality of all types (normal, strict and structural) for two [Term]s */ - fun assertNoEqualities(expected: Term, actual: Term) { + fun assertNoEqualities( + expected: Term, + actual: Term, + ) { assertNotEquals(expected, actual) assertNotStructurallyEquals(expected, actual) assertNotEqualsUsingVariablesSimpleNames(expected, actual) } /** Executes the [function] with corresponding items in order */ - fun onCorrespondingItems(expected: Iterable, actual: Iterable, function: (A, B) -> Unit) = - expected.zip(actual).forEach { (expected, actual) -> function(expected, actual) } + fun onCorrespondingItems( + expected: Iterable, + actual: Iterable, + function: (A, B) -> Unit, + ) = expected.zip(actual).forEach { (expected, actual) -> function(expected, actual) } /** Asserts the [assertion] for each [E] versus all the [E]s (itself included). */ - fun assertAllVsAll(toBeTested: Iterable, assertion: (E, E) -> Unit) { + fun assertAllVsAll( + toBeTested: Iterable, + assertion: (E, E) -> Unit, + ) { val toTestItems = toBeTested.count() - val repeatedElementsSequence = toBeTested.flatMap { underTestItem -> - generateSequence { underTestItem }.take(toTestItems).asIterable() - } - val repeatedSequenceOfElements = generateSequence { toBeTested } - .take(toTestItems).flatten().asIterable() + val repeatedElementsSequence = + toBeTested.flatMap { underTestItem -> + generateSequence { underTestItem }.take(toTestItems).asIterable() + } + val repeatedSequenceOfElements = + generateSequence { toBeTested } + .take(toTestItems).flatten().asIterable() onCorrespondingItems(repeatedElementsSequence, repeatedSequenceOfElements, assertion) } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/AtomUtils.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/AtomUtils.kt index 0b8ca5c59..30ee6e3fe 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/AtomUtils.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/AtomUtils.kt @@ -9,7 +9,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal object AtomUtils { - /** For non special atoms are intended all valid atoms excluding: `true, fail, [], {}` */ internal val nonSpecialAtoms by lazy { // these could be randomly generated from some library in future, maybe starting from Atom regex @@ -24,7 +23,7 @@ internal object AtomUtils { "+", ",", "is", - "!" + "!", ) } @@ -35,7 +34,7 @@ internal object AtomUtils { "{}", "true", "fail", - "false" + "false", ) } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/BlockUtils.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/BlockUtils.kt index 76aa40da7..83a31fcf9 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/BlockUtils.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/BlockUtils.kt @@ -15,13 +15,12 @@ import it.unibo.tuprolog.core.Var * @author Enrico */ internal object BlockUtils { - /** Contains block arguments, containing ground terms */ internal val groundBlocks by lazy { listOf( arrayOf(Truth.TRUE), arrayOf(Atom.of("hey"), Atom.of("!")), - arrayOf(Integer.of(1), Real.of(1.5), Truth.FALSE, Atom.of("ciao")) + arrayOf(Integer.of(1), Real.of(1.5), Truth.FALSE, Atom.of("ciao")), ) } @@ -32,7 +31,7 @@ internal object BlockUtils { internal val nonGroundBlocks by lazy { listOf( arrayOf(Var.of("MyVar")), - arrayOf(Var.of("A"), Var.anonymous(), Cons.singleton(Var.of("Var"))) + arrayOf(Var.of("A"), Var.anonymous(), Cons.singleton(Var.of("Var"))), ) } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/ConsUtils.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/ConsUtils.kt index 0b371bf54..063862768 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/ConsUtils.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/ConsUtils.kt @@ -15,7 +15,6 @@ import it.unibo.tuprolog.core.testutils.AssertionUtils.dropLast * @author Enrico */ internal object ConsUtils { - private val headOfFirstList = Var.of("H") private val tailOfFirstList = Empty.list() private val elementsOfFirstList = listOf(headOfFirstList) @@ -25,7 +24,9 @@ internal object ConsUtils { private val headOfSecondList = Var.of("H") private val tailOfSecondListElement = Var.of("T") + private fun tailOfSecondList(constructor: (Term, Term) -> Cons) = constructor(tailOfSecondListElement, Empty.list()) + private val elementsOfSecondList = listOf(headOfSecondList, tailOfSecondListElement) /** Constructs a non ground Cons with two Terms */ @@ -35,6 +36,7 @@ internal object ConsUtils { private val headOfThirdList = Atom.of("bigList") private val tailOfThirdListFirstElement = Integer.of(4) private val tailOfThirdListSecondElement = Real.of(1.5) + private fun tailOfThirdList(constructor: (Term, Term) -> Cons) = constructor(tailOfThirdListFirstElement, constructor(tailOfThirdListSecondElement, Empty.list())) @@ -55,8 +57,12 @@ internal object ConsUtils { private val headOfFifthList = Atom.of("head") private val tailOfFifthListFirstElement = Var.of("M") private val tailOfFifthListSecondElement = Var.of("N") + private fun tailOfFifthList(constructor: (Term, Term) -> Cons) = - constructor(tailOfFifthListFirstElement, tailOfFifthListSecondElement) + constructor( + tailOfFifthListFirstElement, + tailOfFifthListSecondElement, + ) private val elementsOfFifthList = listOf(headOfFifthList, tailOfFifthListFirstElement, tailOfFifthListSecondElement) @@ -69,14 +75,14 @@ internal object ConsUtils { listOf( oneElementList(constructor), twoElementList(constructor), - threeElementList(constructor) + threeElementList(constructor), ) /** Returns only those Cons that *NOT* terminate with an EmptyList */ internal fun onlyConsPipeTerminated(constructor: (Term, Term) -> Cons) = listOf( twoElementListWithPipe(constructor), - threeElementListWithPipe(constructor) + threeElementListWithPipe(constructor), ) /** Returns all Cons mixing [onlyConsEmptyListTerminated] and [onlyConsPipeTerminated] */ @@ -95,7 +101,7 @@ internal object ConsUtils { tailOfSecondList(constructor), tailOfThirdList(constructor), tailOfFourthList, - tailOfFifthList(constructor) + tailOfFifthList(constructor), ) /** All Cons correct toString representations */ @@ -124,7 +130,7 @@ internal object ConsUtils { elementsOfSecondList + Empty.list(), elementsOfThirdList + Empty.list(), elementsOfFourthList, - elementsOfFifthList + elementsOfFifthList, ) } } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/ConstantUtils.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/ConstantUtils.kt index 2d85f9e76..0a68e1f07 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/ConstantUtils.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/ConstantUtils.kt @@ -13,7 +13,6 @@ import kotlin.test.assertSame * @author Enrico */ internal object ConstantUtils { - /** Asserts that a freshCopy of a ground [Term] is the [Term] itself */ internal fun assertFreshCopyIsItself(constant: Term) { assertEqualities(constant, constant.freshCopy()) diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/DirectiveUtils.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/DirectiveUtils.kt index 87279452f..8e8b4d46b 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/DirectiveUtils.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/DirectiveUtils.kt @@ -13,16 +13,14 @@ import it.unibo.tuprolog.core.Var * @author Enrico */ internal object DirectiveUtils { - /** Contains ground Directives (aka without variables), well-formed */ val groundWellFormedDirectives by lazy { listOf( Struct.of("assert", Struct.of("son", Atom.of("jack"), Atom.of("bob"))), Tuple.wrapIfNeeded( Struct.of("assertZ", Struct.of("money", Integer.of(50))), - Struct.of("assertA", Struct.of("debt", Integer.of(30))) - ) - + Struct.of("assertA", Struct.of("debt", Integer.of(30))), + ), ) + RuleUtils.groundWellFormedRules.map { (_, body) -> body } } @@ -30,7 +28,7 @@ internal object DirectiveUtils { val nonGroundWellFormedDirectives by lazy { listOf( Struct.of("retract", Struct.of("f", Var.anonymous())), - Struct.of("retractAll", Struct.of("x", Var.of("X"))) + Struct.of("retractAll", Struct.of("x", Var.of("X"))), ) + RuleUtils.nonGroundWellFormedRules.map { (_, body) -> body }.filterNot { it.isGround } } @@ -58,6 +56,9 @@ internal object DirectiveUtils { /** Contains mixed [groundDirectives] and [nonGroundDirectives] */ val mixedDirectives by lazy { - groundWellFormedDirectives + groundNonWellFormedDirectives + nonGroundWellFormedDirectives + nonGroundNonWellFormedDirectives + groundWellFormedDirectives + + groundNonWellFormedDirectives + + nonGroundWellFormedDirectives + + nonGroundNonWellFormedDirectives } } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/FactUtils.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/FactUtils.kt index fbb82e5e8..c43a7249b 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/FactUtils.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/FactUtils.kt @@ -14,13 +14,12 @@ import it.unibo.tuprolog.core.Var * @author Enrico */ internal object FactUtils { - /** Contains ground Facts (aka without variables) */ val groundFacts by lazy { listOf( Struct.of("parent", Atom.of("jack"), Atom.of("bob")), Struct.of("parent", Integer.of(5), Real.of("2.5")), - Truth.TRUE + Truth.TRUE, ) } @@ -28,7 +27,7 @@ internal object FactUtils { val nonGroundFacts by lazy { listOf( Struct.of("myFunc", Var.anonymous(), Var.anonymous()), - Struct.of("win", Var.of("X")) + Struct.of("win", Var.of("X")), ) } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/IndicatorUtils.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/IndicatorUtils.kt index 92f602216..e8ef45ab8 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/IndicatorUtils.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/IndicatorUtils.kt @@ -14,7 +14,6 @@ import it.unibo.tuprolog.core.Var * @author Enrico */ internal object IndicatorUtils { - /** Contains well-formed [Indicator]s in raw format */ internal val rawWellFormedIndicators by lazy { listOf( @@ -26,7 +25,7 @@ internal object IndicatorUtils { "true" to 0, "fail" to 0, "[]" to 0, - "{}" to 0 + "{}" to 0, ) } @@ -39,7 +38,7 @@ internal object IndicatorUtils { internal val nonWellFormedNameIndicator by lazy { listOf( Var.anonymous() to Integer.of(2), - Struct.of(".", Truth.TRUE) to Integer.of(2) + Struct.of(".", Truth.TRUE) to Integer.of(2), ) } @@ -49,7 +48,7 @@ internal object IndicatorUtils { Atom.of("/") to Integer.of(-2), Atom.of("animal") to Integer.of(-1), Atom.of("1") to Real.of(0.5), - Truth.TRUE to Var.anonymous() + Truth.TRUE to Var.anonymous(), ) } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/IntegerUtils.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/IntegerUtils.kt index af0912682..ed98fa42a 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/IntegerUtils.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/IntegerUtils.kt @@ -9,7 +9,6 @@ import org.gciatto.kt.math.BigInteger * @author Enrico */ internal object IntegerUtils { - /** Map from an integer in string format to it's corresponding BigInteger instance */ private val stringToIntegerCorrectnessMap by lazy { mapOf( @@ -27,7 +26,7 @@ internal object IntegerUtils { "0b0" to BigInteger.of(0), "0B1" to BigInteger.of(1), "0o7" to BigInteger.of(7), - "0O10" to BigInteger.of(8) + "0O10" to BigInteger.of(8), ) } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/RealUtils.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/RealUtils.kt index 39784da60..0e32f9e69 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/RealUtils.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/RealUtils.kt @@ -8,8 +8,8 @@ import org.gciatto.kt.math.BigDecimal * * @author Enrico */ +@Suppress("ktlint:standard:max-line-length") internal object RealUtils { - /** Map from a real number in string format to it's corresponding BigDecimal instance */ private val stringToRealCorrectnessMap by lazy { mapOf( @@ -37,7 +37,7 @@ internal object RealUtils { "-" + Double.MAX_VALUE.toString() to -BigDecimal.of(Double.MAX_VALUE.toString()), "-" + Double.MIN_VALUE.toString() to -BigDecimal.of(Double.MIN_VALUE.toString()), "10.0" to BigDecimal.TEN, - "10.000" to BigDecimal.TEN + "10.000" to BigDecimal.TEN, ) } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/RuleUtils.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/RuleUtils.kt index fea359f5d..81a139e0a 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/RuleUtils.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/RuleUtils.kt @@ -18,7 +18,6 @@ import it.unibo.tuprolog.core.Var * @author Enrico */ internal object RuleUtils { - /** Contains ground Rules (aka without variables) "well formed" */ val groundWellFormedRules by lazy { listOf( @@ -28,7 +27,7 @@ internal object RuleUtils { Atom.of("a") to Struct.of("?", Integer.of(1), Integer.of(2)), Atom.of("b") to Struct.of(",", Real.of(0.5), Real.of(0.6), Real.of(0.7)), Empty.block() to Struct.of(";", Integer.of(2)), - Empty.list() to Struct.of("->", Integer.of(4)) + Empty.list() to Struct.of("->", Integer.of(4)), ) } @@ -38,7 +37,7 @@ internal object RuleUtils { Struct.of("f", Var.anonymous()) to Atom.of("ciao"), Struct.of("f", Integer.of(2)) to Var.of("Ciao"), Struct.of("x", Var.of("X")) to Struct.of("y", Var.of("X"), Real.of(1f)), - Struct.of("myFunc", Atom.of("a")) to Tuple.wrapIfNeeded(Var.anonymous(), Var.anonymous()) + Struct.of("myFunc", Atom.of("a")) to Tuple.wrapIfNeeded(Var.anonymous(), Var.anonymous()), ) } @@ -50,7 +49,7 @@ internal object RuleUtils { Atom.of("a") to Tuple.wrapIfNeeded(Atom.of("b"), Integer.of(2)), Atom.of("b") to Tuple.wrapIfNeeded(Real.of(0.5), Real.of(0.6), Real.of(0.7)), Atom.of("a") to Struct.fold(";", Truth.TRUE, Empty.list(), Real.of("2.4")), - Atom.of("a") to Struct.fold("->", Truth.TRUE, Empty.list(), Numeric.of(2.8)) + Atom.of("a") to Struct.fold("->", Truth.TRUE, Empty.list(), Numeric.of(2.8)), ) } @@ -59,7 +58,7 @@ internal object RuleUtils { listOf( Struct.of("A", Var.anonymous()) to Struct.of(",", Var.of("B"), Integer.of(1)), Atom.of("a") to Struct.fold(";", Truth.TRUE, Var.of("A"), Real.of("2.4")), - Atom.of("a") to Struct.fold("->", Truth.TRUE, Var.anonymous(), Var.anonymous(), Numeric.of(2.8)) + Atom.of("a") to Struct.fold("->", Truth.TRUE, Var.anonymous(), Var.anonymous(), Numeric.of(2.8)), ) } @@ -76,5 +75,7 @@ internal object RuleUtils { val nonGroundRules by lazy { nonGroundWellFormedRules + nonGroundNonWellFormedRules } /** Contains mixed Rules, ground and non ground, well-formed and not */ - val mixedRules by lazy { groundWellFormedRules + nonGroundWellFormedRules + groundNonWellFormedRules + nonGroundNonWellFormedRules } + val mixedRules by lazy { + groundWellFormedRules + nonGroundWellFormedRules + groundNonWellFormedRules + nonGroundNonWellFormedRules + } } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/ScopeUtils.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/ScopeUtils.kt index 74acb2640..5b71825bc 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/ScopeUtils.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/ScopeUtils.kt @@ -12,18 +12,18 @@ import kotlin.test.assertEquals * @author Enrico */ internal object ScopeUtils { - /** Returns an empty Scope */ internal val emptyScope get() = mutableMapOf() /** Contains some non empty variable Scopes */ internal val nonEmptyScopes - get() = listOf( - mutableMapOf("X" to Var.of("X")), - mutableMapOf("H" to Var.of("H"), "T" to Var.of("T")), - mutableMapOf("A" to Var.of("A"), "B" to Var.of("B"), "C" to Var.of("C")) - ) + get() = + listOf( + mutableMapOf("X" to Var.of("X")), + mutableMapOf("H" to Var.of("H"), "T" to Var.of("T")), + mutableMapOf("A" to Var.of("A"), "B" to Var.of("B"), "C" to Var.of("C")), + ) /** Contains the variables inside [nonEmptyScopes] */ internal val nonEmptyScopeVars @@ -38,7 +38,10 @@ internal object ScopeUtils { get() = nonEmptyScopes + emptyScope /** Asserts that two Scope Maps have same keys (Var names) and, on the value side, only Var name in common */ - internal fun assertScopeCorrectContents(expected: Map, actual: Map) { + internal fun assertScopeCorrectContents( + expected: Map, + actual: Map, + ) { assertEquals(expected.keys, actual.keys) onCorrespondingItems(expected.values, actual.values, VarUtils::assertDifferentVariableExceptForName) } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/StructUtils.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/StructUtils.kt index 66b39bb0a..4da129ff6 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/StructUtils.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/StructUtils.kt @@ -27,7 +27,6 @@ import kotlin.test.assertSame * @author Enrico */ internal object StructUtils { - /** * Asserts that passed term with variables, when copied, renews variables contained; * @@ -75,7 +74,7 @@ internal object StructUtils { "." to listOf(Real.of(0.1), Real.of(0.5f), Var.of("MyVar")), "," to listOf(EmptyList(), EmptyBlock(), Truth.TRUE), "/" to listOf(Truth.FALSE), - "sameVar" to Scope.empty { ktListOf(varOf("X"), varOf("X")) } + "sameVar" to Scope.empty { ktListOf(varOf("X"), varOf("X")) }, ) } @@ -93,7 +92,7 @@ internal object StructUtils { Empty.EMPTY_BLOCK_FUNCTOR to listOf(), Truth.TRUE_FUNCTOR to listOf(), Truth.FAIL_FUNCTOR to listOf(), - Indicator.FUNCTOR to listOf(Atom.of("func"), Integer.of(4)) + Indicator.FUNCTOR to listOf(Atom.of("func"), Integer.of(4)), ) } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/SubstitutionUtils.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/SubstitutionUtils.kt index f183f7bca..fdb3ff4a4 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/SubstitutionUtils.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/SubstitutionUtils.kt @@ -15,13 +15,12 @@ import kotlin.collections.listOf as ktListOf * @author Enrico */ internal object SubstitutionUtils { - /** Returns terms that internally can have multiple times the provided [internalTerm] */ internal fun termsWith(internalTerm: Term) = ktListOf( internalTerm, Struct.of("f", internalTerm, internalTerm), - Struct.fold("f", internalTerm, Atom.of("ciao"), internalTerm) + Struct.fold("f", internalTerm, Atom.of("ciao"), internalTerm), ) /** Contains mixed groundSubstitutions and nonGroundSubstitutions */ @@ -30,16 +29,23 @@ internal object SubstitutionUtils { mapOf(Var.of("X") to Atom.of("x")), mapOf( Var.of("A") to Struct.of("f", Atom.of("ciao")), - Var.of("B") to Empty.list() + Var.of("B") to Empty.list(), ), mapOf(Var.of("Var") to Struct.of("f", Var.of("A"), Var.of("B"))), mapOf(Var.of("Z") to Struct.of("f", Var.of("Z"))), - mapOf(Var.anonymous() to Var.of("A")) + mapOf(Var.anonymous() to Var.of("A")), ) } /** Contains [mixedSubstitutions] represented as list of pairs */ - internal val mixedSubstitutionsAsPairs by lazy { mixedSubstitutions.map { it.entries.map { entry -> entry.toPair() } } } + internal val mixedSubstitutionsAsPairs by lazy { + mixedSubstitutions.map { + it.entries.map { + entry -> + entry.toPair() + } + } + } /** Contains a duplicated pair substitution, that should result in unique final substitution */ internal val duplicatedPairSubstitution by lazy { @@ -50,8 +56,8 @@ internal object SubstitutionUtils { varOf("A") to atomOf("a"), varOf("A") to atomOf("a"), varOf("B") to atomOf("b"), - varOf("B") to atomOf("b") - ) + varOf("B") to atomOf("b"), + ), ) } } @@ -63,7 +69,7 @@ internal object SubstitutionUtils { ktListOf(varOf("A") to atomOf("a"), varOf("A") to atomOf("b")), ktListOf(varOf("A") to atomOf("a"), varOf("A") to varOf("C")), ktListOf(varOf("A") to atomOf("a"), varOf("A") to varOf("C"), varOf("C") to atomOf("a")), - ktListOf(varOf("A") to atomOf("a"), varOf("A") to varOf("C"), varOf("C") to atomOf("b")) + ktListOf(varOf("A") to atomOf("a"), varOf("A") to varOf("C"), varOf("C") to atomOf("b")), ) } } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/TermFormatterUtils.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/TermFormatterUtils.kt index 62c33ba68..aab9c58f5 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/TermFormatterUtils.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/TermFormatterUtils.kt @@ -20,95 +20,103 @@ import it.unibo.tuprolog.core.format import kotlin.test.assertEquals object TermFormatterUtils { - private val common: Map = mapOf( - Atom.of("a") to "a", - Atom.of("a b") to "'a b'", - Integer.of(1) to "1", - Real.of("3.2") to "3.2", - Var.of("A") to "A", - Var.anonymous() to Var.ANONYMOUS_NAME, - Var.of("A b") to Var.escapeName("A b"), - Struct.of("f", Var.of("A"), Atom.of("b")) to "f(A, b)", - Struct.of("f", Var.of("A"), Var.of("B"), Var.of("A")) to "f(A, B, A1)", - Var.of("A").let { Struct.of("f", it, Var.of("B"), it) } to "f(A, B, A)", - Struct.of("F", Atom.of("a"), Integer.of(1), Real.of("3.2")) to "'F'(a, 1, 3.2)", - List.empty() to EmptyList.FUNCTOR, - List.of(Var.of("A"), Var.of("A"), Var.of("A")) to "[A, A1, A2]", - Var.of("A").let { List.of(it, it, it) } to "[A, A, A]", - List.from(items = listOf(Var.of("A"), Var.of("A"), Var.of("A")), last = Var.of("A")) to "[A, A1, A2 | A3]", - Var.of("A").let { List.from(items = listOf(it, it, it), last = it) } to "[A, A, A | A]", - Block.empty() to EmptyBlock.FUNCTOR, - Block.of(Var.of("A"), Var.of("A"), Var.of("A")) to "{A, A1, A2}", - Var.of("A").let { Block.of(it, it, it) } to "{A, A, A}" - ) + private val common: Map = + mapOf( + Atom.of("a") to "a", + Atom.of("a b") to "'a b'", + Integer.of(1) to "1", + Real.of("3.2") to "3.2", + Var.of("A") to "A", + Var.anonymous() to Var.ANONYMOUS_NAME, + Var.of("A b") to Var.escapeName("A b"), + Struct.of("f", Var.of("A"), Atom.of("b")) to "f(A, b)", + Struct.of("f", Var.of("A"), Var.of("B"), Var.of("A")) to "f(A, B, A1)", + Var.of("A").let { Struct.of("f", it, Var.of("B"), it) } to "f(A, B, A)", + Struct.of("F", Atom.of("a"), Integer.of(1), Real.of("3.2")) to "'F'(a, 1, 3.2)", + List.empty() to EmptyList.FUNCTOR, + List.of(Var.of("A"), Var.of("A"), Var.of("A")) to "[A, A1, A2]", + Var.of("A").let { List.of(it, it, it) } to "[A, A, A]", + List.from(items = listOf(Var.of("A"), Var.of("A"), Var.of("A")), last = Var.of("A")) to "[A, A1, A2 | A3]", + Var.of("A").let { List.from(items = listOf(it, it, it), last = it) } to "[A, A, A | A]", + Block.empty() to EmptyBlock.FUNCTOR, + Block.of(Var.of("A"), Var.of("A"), Var.of("A")) to "{A, A1, A2}", + Var.of("A").let { Block.of(it, it, it) } to "{A, A, A}", + ) - val expectedFormatsWithPrettyVariables: Map = common + mapOf( - Tuple.of(Var.of("A"), Var.of("A"), Var.of("A")) to "(A, A1, A2)", - Var.of("A").let { Tuple.of(it, it, it) } to "(A, A, A)", - Indicator.of(Var.of("A"), Var.of("B")) to "'/'(A, B)", - Rule.of( - Tuple.of(Var.of("A"), Var.of("B")), - Tuple.of(Var.of("C"), Var.of("D")) - ) to "':-'((A, B), (C, D))", - Fact.of( - Tuple.of(Var.of("A"), Var.of("B"), Var.of("A"), Var.of("B")) - ) to "':-'((A, B, A1, B1), true)", - Directive.of( - Tuple.of(Var.of("A"), Var.of("B"), Var.of("A"), Var.of("B")) - ) to "':-'((A, B, A1, B1))" - ) + val expectedFormatsWithPrettyVariables: Map = + common + + mapOf( + Tuple.of(Var.of("A"), Var.of("A"), Var.of("A")) to "(A, A1, A2)", + Var.of("A").let { Tuple.of(it, it, it) } to "(A, A, A)", + Indicator.of(Var.of("A"), Var.of("B")) to "'/'(A, B)", + Rule.of( + Tuple.of(Var.of("A"), Var.of("B")), + Tuple.of(Var.of("C"), Var.of("D")), + ) to "':-'((A, B), (C, D))", + Fact.of( + Tuple.of(Var.of("A"), Var.of("B"), Var.of("A"), Var.of("B")), + ) to "':-'((A, B, A1, B1), true)", + Directive.of( + Tuple.of(Var.of("A"), Var.of("B"), Var.of("A"), Var.of("B")), + ) to "':-'((A, B, A1, B1))", + ) - val expectedFormatsWithPrettyExpressions: Map = common + mapOf( - Tuple.of(Var.of("A"), Var.of("A"), Var.of("A")) to "A, A1, A2", - Var.of("A").let { Tuple.of(it, it, it) } to "A, A, A", - Struct.of("f", Tuple.of(Var.of("A"), Var.of("B")), Var.of("A")) to "f((A, B), A1)", - Struct.of("f", Var.of("A"), Tuple.of(Var.of("B"), Var.of("A"))) to "f(A, (B, A1))", - Tuple.of(Tuple.of(Var.of("A"), Var.of("B")), Tuple.of(Var.of("A"), Var.of("B"))) to "(A, B), A1, B1", - Block.of(Tuple.of(Var.of("A"), Var.of("B")), Tuple.of(Var.of("A"), Var.of("B"))) to "{(A, B), A1, B1}", - List.of(Tuple.of(Var.of("A"), Var.of("B")), Tuple.of(Var.of("A"), Var.of("B"))) to "[(A, B), (A1, B1)]", - List.of(Tuple.of(Var.of("A"), Var.of("B")), Var.of("A"), Var.of("B")) to "[(A, B), A1, B1]", - List.from( - items = listOf(Tuple.of(Var.of("A"), Var.of("B")), Tuple.of(Var.of("A"), Var.of("B"))), - last = Tuple.of(Var.of("A"), Var.of("B")) - ) to "[(A, B), (A1, B1) | (A2, B2)]", - List.from( - items = listOf(Tuple.of(Var.of("A"), Var.of("B")), Var.of("A"), Var.of("B")), - last = Tuple.of(Var.of("A"), Var.of("B")) - ) to "[(A, B), A1, B1 | (A2, B2)]", - Struct.of( - "+", - Struct.of("+", Var.of("A"), Var.of("B")), - Struct.of("+", Var.of("C"), Var.of("D")) - ) to "A + B + C + D", - Struct.of( - "+", - Struct.of("-", Var.of("A"), Var.of("B")), - Struct.of("-", Var.of("C"), Var.of("D")) - ) to "A - B + C - D", - Indicator.of(Var.of("A"), Var.of("B")) to "A / B", - Rule.of( - Tuple.of(Var.of("A"), Var.of("B")), - Tuple.of(Var.of("C"), Var.of("D")) - ) to "A, B :- C, D", - Fact.of( - Tuple.of(Var.of("A"), Var.of("B"), Var.of("A"), Var.of("B")) - ) to "A, B, A1, B1 :- true", - Directive.of( - Tuple.of(Var.of("A"), Var.of("B"), Var.of("A"), Var.of("B")) - ) to ":- A, B, A1, B1" - ) + val expectedFormatsWithPrettyExpressions: Map = + common + + mapOf( + Tuple.of(Var.of("A"), Var.of("A"), Var.of("A")) to "A, A1, A2", + Var.of("A").let { Tuple.of(it, it, it) } to "A, A, A", + Struct.of("f", Tuple.of(Var.of("A"), Var.of("B")), Var.of("A")) to "f((A, B), A1)", + Struct.of("f", Var.of("A"), Tuple.of(Var.of("B"), Var.of("A"))) to "f(A, (B, A1))", + Tuple.of(Tuple.of(Var.of("A"), Var.of("B")), Tuple.of(Var.of("A"), Var.of("B"))) to "(A, B), A1, B1", + Block.of(Tuple.of(Var.of("A"), Var.of("B")), Tuple.of(Var.of("A"), Var.of("B"))) to "{(A, B), A1, B1}", + List.of(Tuple.of(Var.of("A"), Var.of("B")), Tuple.of(Var.of("A"), Var.of("B"))) to "[(A, B), (A1, B1)]", + List.of(Tuple.of(Var.of("A"), Var.of("B")), Var.of("A"), Var.of("B")) to "[(A, B), A1, B1]", + List.from( + items = listOf(Tuple.of(Var.of("A"), Var.of("B")), Tuple.of(Var.of("A"), Var.of("B"))), + last = Tuple.of(Var.of("A"), Var.of("B")), + ) to "[(A, B), (A1, B1) | (A2, B2)]", + List.from( + items = listOf(Tuple.of(Var.of("A"), Var.of("B")), Var.of("A"), Var.of("B")), + last = Tuple.of(Var.of("A"), Var.of("B")), + ) to "[(A, B), A1, B1 | (A2, B2)]", + Struct.of( + "+", + Struct.of("+", Var.of("A"), Var.of("B")), + Struct.of("+", Var.of("C"), Var.of("D")), + ) to "A + B + C + D", + Struct.of( + "+", + Struct.of("-", Var.of("A"), Var.of("B")), + Struct.of("-", Var.of("C"), Var.of("D")), + ) to "A - B + C - D", + Indicator.of(Var.of("A"), Var.of("B")) to "A / B", + Rule.of( + Tuple.of(Var.of("A"), Var.of("B")), + Tuple.of(Var.of("C"), Var.of("D")), + ) to "A, B :- C, D", + Fact.of( + Tuple.of(Var.of("A"), Var.of("B"), Var.of("A"), Var.of("B")), + ) to "A, B, A1, B1 :- true", + Directive.of( + Tuple.of(Var.of("A"), Var.of("B"), Var.of("A"), Var.of("B")), + ) to ":- A, B, A1, B1", + ) fun TermFormatter.assertProperlyFormats(entry: Map.Entry) { this.assertProperlyFormats(entry.component2(), entry.component1()) } - fun TermFormatter.assertProperlyFormats(expected: String, actual: Term) { + fun TermFormatter.assertProperlyFormats( + expected: String, + actual: Term, + ) { val formatted = actual.format(this) assertEquals( expected, formatted, message = - """ + """ |Formatting | $actual |with ${this::class} should result in @@ -117,7 +125,7 @@ object TermFormatterUtils { | $formatted |is produced instead | - """.trimMargin() + """.trimMargin(), ) } } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/TermTypeAssertionUtils.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/TermTypeAssertionUtils.kt index 5dcd204d1..e9c7b4e4c 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/TermTypeAssertionUtils.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/TermTypeAssertionUtils.kt @@ -32,7 +32,6 @@ import it.unibo.tuprolog.core.List as LogicList * @author Enrico */ internal object TermTypeAssertionUtils { - /** Checks passed term to be a Variable or fails otherwise */ fun assertIsVar(any: Any) { assertTrue(any is Term) @@ -65,7 +64,7 @@ internal object TermTypeAssertionUtils { any is Struct, any is Clause, any is Cons, - any is Constant + any is Constant, ) } @@ -78,7 +77,7 @@ internal object TermTypeAssertionUtils { assertTrue( any.isConstant, any.isNumber, - any.isGround + any.isGround, ) assertFalse( @@ -101,7 +100,7 @@ internal object TermTypeAssertionUtils { any is Var, any is Struct, any is Clause, - any is Cons + any is Cons, ) } @@ -160,7 +159,7 @@ internal object TermTypeAssertionUtils { any is Cons, any is Tuple, any is Constant, - any is Indicator + any is Indicator, ) } @@ -175,7 +174,7 @@ internal object TermTypeAssertionUtils { any.isStruct, any.isConstant, any.isAtom, - any.isGround + any.isGround, ) assertFalse( @@ -193,7 +192,7 @@ internal object TermTypeAssertionUtils { any is Numeric, any is Clause, any is Var, - any is Cons + any is Cons, ) } @@ -213,7 +212,7 @@ internal object TermTypeAssertionUtils { any is LogicList, any is Block, any is Empty, - any is Truth + any is Truth, ) } @@ -235,7 +234,7 @@ internal object TermTypeAssertionUtils { any is LogicList, any is Empty, any is EmptyBlock, - any is EmptyList + any is EmptyList, ) } @@ -247,7 +246,7 @@ internal object TermTypeAssertionUtils { assertTrue( any.isStruct, - any.isTuple + any.isTuple, ) assertFalse( @@ -275,7 +274,7 @@ internal object TermTypeAssertionUtils { any is Cons, any is Var, any is Constant, - any is Indicator + any is Indicator, ) } @@ -287,7 +286,7 @@ internal object TermTypeAssertionUtils { assertTrue( any.isStruct, - any.isIndicator + any.isIndicator, ) assertFalse( @@ -315,7 +314,7 @@ internal object TermTypeAssertionUtils { any is Cons, any is Var, any is Constant, - any is Tuple + any is Tuple, ) } @@ -329,7 +328,7 @@ internal object TermTypeAssertionUtils { assertTrue( any.isStruct, any.isList, - any.isCons + any.isCons, ) assertFalse( @@ -354,7 +353,7 @@ internal object TermTypeAssertionUtils { any is Atom, any is Clause, any is Var, - any is Constant + any is Constant, ) } @@ -366,7 +365,7 @@ internal object TermTypeAssertionUtils { assertTrue( any.isStruct, - any.isBlock + any.isBlock, ) assertFalse( @@ -393,7 +392,7 @@ internal object TermTypeAssertionUtils { any is Clause, any is Cons, any is Var, - any is Constant + any is Constant, ) } @@ -406,7 +405,7 @@ internal object TermTypeAssertionUtils { assertFalse( any.isTrue, any.isFail, - any is Truth + any is Truth, ) } @@ -419,14 +418,14 @@ internal object TermTypeAssertionUtils { assertTrue( any.isList, - any.isEmptyList + any.isEmptyList, ) assertFalse( any.isEmptyBlock, any.isBlock, any is Block, - any is EmptyBlock + any is EmptyBlock, ) } @@ -439,14 +438,14 @@ internal object TermTypeAssertionUtils { assertTrue( any.isEmptyBlock, - any.isBlock + any.isBlock, ) assertFalse( any.isList, any.isEmptyList, any is LogicList, - any is EmptyList + any is EmptyList, ) } @@ -458,7 +457,7 @@ internal object TermTypeAssertionUtils { assertTrue( any.isStruct, - any.isClause + any.isClause, ) assertFalse( @@ -484,7 +483,7 @@ internal object TermTypeAssertionUtils { any is LogicList, any is Atom, any is Constant, - any is Indicator + any is Indicator, ) } @@ -497,7 +496,7 @@ internal object TermTypeAssertionUtils { assertFalse( any.isDirective, - any is Directive + any is Directive, ) } @@ -512,7 +511,7 @@ internal object TermTypeAssertionUtils { any.isRule, any.isFact, any is Rule, - any is Fact + any is Fact, ) } @@ -525,12 +524,12 @@ internal object TermTypeAssertionUtils { assertTrue( any.isRule, - any.isFact + any.isFact, ) assertFalse( any.isDirective, - any is Directive + any is Directive, ) } } diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/TupleUtils.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/TupleUtils.kt index baf29c619..bcd35a6e2 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/TupleUtils.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/TupleUtils.kt @@ -13,7 +13,6 @@ import it.unibo.tuprolog.core.Var * @author Enrico */ internal object TupleUtils { - private val firstOfFirstTuple = Var.of("A") private val secondOfFirstTuple = Var.of("B") private val elementsOfFirstTuple = listOf(firstOfFirstTuple, secondOfFirstTuple) @@ -25,8 +24,12 @@ internal object TupleUtils { private val firstOfSecondTuple = Atom.of("bigTuple") private val secondOfSecondTuple = Integer.of(4) private val thirdOfSecondTuple = Real.of(1.5) + private fun rightOfSecondTuple(constructor: (Term, Term) -> Tuple) = - constructor(secondOfSecondTuple, thirdOfSecondTuple) + constructor( + secondOfSecondTuple, + thirdOfSecondTuple, + ) private val elementsOfSecondTuple = listOf(firstOfSecondTuple, secondOfSecondTuple, thirdOfSecondTuple) @@ -38,7 +41,7 @@ internal object TupleUtils { internal fun tupleInstances(constructor: (Term, Term) -> Tuple) = listOf( twoElementTuple(constructor), - threeElementTuple(constructor) + threeElementTuple(constructor), ) /** Tuple instances left element */ @@ -50,7 +53,7 @@ internal object TupleUtils { internal fun tupleInstancesRights(constructor: (Term, Term) -> Tuple) = listOf( secondOfFirstTuple, - rightOfSecondTuple(constructor) + rightOfSecondTuple(constructor), ) /** Tuples elements lists */ diff --git a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/VarUtils.kt b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/VarUtils.kt index 126fada6b..c2cb17518 100644 --- a/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/VarUtils.kt +++ b/core/src/commonTest/kotlin/it/unibo/tuprolog/core/testutils/VarUtils.kt @@ -12,7 +12,6 @@ import kotlin.test.assertNotEquals * @author Enrico */ internal object VarUtils { - /** Contains variables that are correctly named */ val correctlyNamedVars by lazy { listOf("A", "X", "_", "_X", "_1", "X1", "X_1") } @@ -23,7 +22,10 @@ internal object VarUtils { val mixedVars by lazy { correctlyNamedVars + incorrectlyNamedVars } /** Asserts that the refreshed variable is not tied to the original variable, except for the name */ - internal fun assertDifferentVariableExceptForName(expected: Var, actual: Var) { + internal fun assertDifferentVariableExceptForName( + expected: Var, + actual: Var, + ) { assertEquals(expected.name, actual.name) assertNotEquals(expected.completeName, actual.completeName) @@ -32,7 +34,10 @@ internal object VarUtils { } /** Asserts that the variables are tied with each other, so are the same */ - internal fun assertSameVariable(expected: Var, actual: Var) { + internal fun assertSameVariable( + expected: Var, + actual: Var, + ) { assertEquals(expected.name, actual.name) assertEquals(expected.completeName, actual.completeName) diff --git a/core/src/jsMain/kotlin/it/unibo/tuprolog/Introspection.kt b/core/src/jsMain/kotlin/it/unibo/tuprolog/Introspection.kt index 095e8bea5..eb4e90be5 100644 --- a/core/src/jsMain/kotlin/it/unibo/tuprolog/Introspection.kt +++ b/core/src/jsMain/kotlin/it/unibo/tuprolog/Introspection.kt @@ -2,6 +2,7 @@ package it.unibo.tuprolog import kotlinx.browser.window +@Suppress("TooGenericExceptionCaught", "SwallowedException") internal actual fun currentPlatform(): Platform = try { if (window === undefined) { @@ -14,10 +15,11 @@ internal actual fun currentPlatform(): Platform = } internal actual fun currentOs(): Os { - val name = when (currentPlatform()) { - Platform.NODE -> js("require('os').platform()") as String? - Platform.BROWSER -> window.navigator.platform - else -> null - } + val name = + when (currentPlatform()) { + Platform.NODE -> js("require('os').platform()") as String? + Platform.BROWSER -> window.navigator.platform + else -> null + } return name?.let(Os.Companion::detect) ?: error("Cannot determine current OS: $name") } diff --git a/core/src/jsMain/kotlin/it/unibo/tuprolog/core/ComparisonUtils.kt b/core/src/jsMain/kotlin/it/unibo/tuprolog/core/ComparisonUtils.kt index 2acab92a5..dddd5b2e2 100644 --- a/core/src/jsMain/kotlin/it/unibo/tuprolog/core/ComparisonUtils.kt +++ b/core/src/jsMain/kotlin/it/unibo/tuprolog/core/ComparisonUtils.kt @@ -1,4 +1,6 @@ package it.unibo.tuprolog.core -actual fun compareStringsLocaleIndependently(string1: String, string2: String): Int = - string1.compareTo(string2) +actual fun compareStringsLocaleIndependently( + string1: String, + string2: String, +): Int = string1.compareTo(string2) diff --git a/core/src/jsTest/kotlin/it/unibo/tuprolog/TestPlatform.kt b/core/src/jsTest/kotlin/it/unibo/tuprolog/TestPlatform.kt index 767328c99..0e1463499 100644 --- a/core/src/jsTest/kotlin/it/unibo/tuprolog/TestPlatform.kt +++ b/core/src/jsTest/kotlin/it/unibo/tuprolog/TestPlatform.kt @@ -5,7 +5,7 @@ import kotlin.test.assertEquals actual class TestPlatform { @Test - actual fun testPlatform() { + actual fun testCurrentPlatform() { // assumes testing is performed on node assertEquals(Platform.NODE, Info.PLATFORM) } diff --git a/core/src/jvmMain/kotlin/it/unibo/tuprolog/core/ComparisonUtils.kt b/core/src/jvmMain/kotlin/it/unibo/tuprolog/core/ComparisonUtils.kt index 26ae94185..51d0dd254 100644 --- a/core/src/jvmMain/kotlin/it/unibo/tuprolog/core/ComparisonUtils.kt +++ b/core/src/jvmMain/kotlin/it/unibo/tuprolog/core/ComparisonUtils.kt @@ -2,5 +2,7 @@ package it.unibo.tuprolog.core import java.text.Collator -actual fun compareStringsLocaleIndependently(string1: String, string2: String): Int = - Collator.getInstance().compare(string1, string2) +actual fun compareStringsLocaleIndependently( + string1: String, + string2: String, +): Int = Collator.getInstance().compare(string1, string2) diff --git a/core/src/jvmTest/kotlin/it/unibo/tuprolog/TestPlatform.kt b/core/src/jvmTest/kotlin/it/unibo/tuprolog/TestPlatform.kt index d251f0095..236e78fd0 100644 --- a/core/src/jvmTest/kotlin/it/unibo/tuprolog/TestPlatform.kt +++ b/core/src/jvmTest/kotlin/it/unibo/tuprolog/TestPlatform.kt @@ -5,7 +5,7 @@ import kotlin.test.assertEquals actual class TestPlatform { @Test - actual fun testPlatform() { + actual fun testCurrentPlatform() { assertEquals(Platform.JVM, Info.PLATFORM) } } diff --git a/datalog/src/commonMain/kotlin/it/unibo/tuprolog/datalog/Datalog.kt b/datalog/src/commonMain/kotlin/it/unibo/tuprolog/datalog/Datalog.kt index b739597c4..31c51fb7c 100644 --- a/datalog/src/commonMain/kotlin/it/unibo/tuprolog/datalog/Datalog.kt +++ b/datalog/src/commonMain/kotlin/it/unibo/tuprolog/datalog/Datalog.kt @@ -64,7 +64,7 @@ fun Clause.ensureAllHeadVariablesInNonNegatedLiterals() { throw DatalogViolationException( "some variable occurring in head of", this, - " does not occur within any non-negated literal of the same clause" + " does not occur within any non-negated literal of the same clause", ) } } @@ -81,7 +81,7 @@ fun Clause.ensureAllNegatedLiteralsVariablesInNonNegatedLiteralsToo() { throw DatalogViolationException( "some variable occurring in some negated literal of ", this, - " does not occur in any non-negated literal of the same clause" + " does not occur in any non-negated literal of the same clause", ) } } @@ -100,9 +100,10 @@ private fun MutableGraph.register(rule: Rule) { } val Theory.callGraph: Graph - get() = Graph.build { - rules.forEach { register(it) } - } + get() = + Graph.build { + rules.forEach { register(it) } + } val Theory.isNonRecursive: Boolean get() = callGraph.isAcyclic @@ -112,15 +113,18 @@ fun Theory.ensureIsNonRecursive() { throw DatalogViolationException( "the theory ", this.joinToString("", "{", "}") { "$it." }, - " contains either direct or indirect recursion" + " contains either direct or indirect recursion", ) } } val Theory.isDatalog: Boolean - get() = rules.all { - it.hasNoCompound && it.allHeadVariablesInNonNegatedLiterals && it.allNegatedLiteralsVariablesInNonNegatedLiteralsToo - } && isNonRecursive + get() = + rules.all { + it.hasNoCompound && + it.allHeadVariablesInNonNegatedLiterals && + it.allNegatedLiteralsVariablesInNonNegatedLiteralsToo + } && isNonRecursive fun Theory.ensureIsDatalog() { for (rule in rules) { diff --git a/datalog/src/commonMain/kotlin/it/unibo/tuprolog/datalog/exception/DatalogViolationException.kt b/datalog/src/commonMain/kotlin/it/unibo/tuprolog/datalog/exception/DatalogViolationException.kt index ff1e2907e..2c258ca85 100644 --- a/datalog/src/commonMain/kotlin/it/unibo/tuprolog/datalog/exception/DatalogViolationException.kt +++ b/datalog/src/commonMain/kotlin/it/unibo/tuprolog/datalog/exception/DatalogViolationException.kt @@ -6,9 +6,8 @@ import it.unibo.tuprolog.core.exception.TuPrologException class DatalogViolationException(prefix: String = "", val culprit: Any, suffix: String = "", cause: Throwable? = null) : TuPrologException( message = "Datalog restriction violation: $prefix$culprit$suffix", - cause = cause + cause = cause, ) { - override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || this::class != other::class) return false diff --git a/datalog/src/commonMain/kotlin/it/unibo/tuprolog/datalog/exception/InvalidLiteralException.kt b/datalog/src/commonMain/kotlin/it/unibo/tuprolog/datalog/exception/InvalidLiteralException.kt index a17b87ae6..5285c6145 100644 --- a/datalog/src/commonMain/kotlin/it/unibo/tuprolog/datalog/exception/InvalidLiteralException.kt +++ b/datalog/src/commonMain/kotlin/it/unibo/tuprolog/datalog/exception/InvalidLiteralException.kt @@ -12,7 +12,7 @@ class InvalidLiteralException : TuPrologException { constructor(literal: Term, clause: Clause?, cause: Throwable? = null) : super( message = "Invalid literal in clause${clause?.let { " $it" } ?: ""}: $literal", - cause = cause + cause = cause, ) { this.literal = literal this.clause = clause diff --git a/datalog/src/commonMain/kotlin/it/unibo/tuprolog/datalog/visitors/AbstractClauseVisitor.kt b/datalog/src/commonMain/kotlin/it/unibo/tuprolog/datalog/visitors/AbstractClauseVisitor.kt index 1e962c4d2..c1cc79a1b 100644 --- a/datalog/src/commonMain/kotlin/it/unibo/tuprolog/datalog/visitors/AbstractClauseVisitor.kt +++ b/datalog/src/commonMain/kotlin/it/unibo/tuprolog/datalog/visitors/AbstractClauseVisitor.kt @@ -13,8 +13,7 @@ abstract class AbstractClauseVisitor : ClauseVisitor, ExhaustiveTermVisito if (it.isClause) visitStruct(it.castToStruct()) else it.accept(this) }.let { reduce(it) } - private fun dispatchHead(head: Struct): T = - visitHead(head) + private fun dispatchHead(head: Struct): T = visitHead(head) private fun dispatchLiteral(literal: Struct): T = if (literal.isNegated) { @@ -24,7 +23,9 @@ abstract class AbstractClauseVisitor : ClauseVisitor, ExhaustiveTermVisito } protected fun dispatchHead(clause: Clause): Sequence = - sequenceOf(clause.head).filterNotNull().map { dispatchHead(it) } + sequenceOf(clause.head).filterNotNull().map { + dispatchHead(it) + } protected fun dispatchBody(clause: Clause): Sequence = clause.bodyItems.asSequence().map { diff --git a/datalog/src/commonMain/kotlin/it/unibo/tuprolog/datalog/visitors/CompoundFinder.kt b/datalog/src/commonMain/kotlin/it/unibo/tuprolog/datalog/visitors/CompoundFinder.kt index 6cfb9df8f..9fa1a9810 100644 --- a/datalog/src/commonMain/kotlin/it/unibo/tuprolog/datalog/visitors/CompoundFinder.kt +++ b/datalog/src/commonMain/kotlin/it/unibo/tuprolog/datalog/visitors/CompoundFinder.kt @@ -4,8 +4,7 @@ import it.unibo.tuprolog.core.Struct import it.unibo.tuprolog.core.Term object CompoundFinder : AbstractClauseVisitor() { - override fun reduce(results: Sequence): Boolean = - results.any { it } + override fun reduce(results: Sequence): Boolean = results.any { it } override fun defaultValue(term: Term): Boolean = false diff --git a/datalog/src/commonTest/kotlin/it/unibo/tuprolog/datalog/Instances.kt b/datalog/src/commonTest/kotlin/it/unibo/tuprolog/datalog/Instances.kt index 7167a52d4..c21a5515f 100644 --- a/datalog/src/commonTest/kotlin/it/unibo/tuprolog/datalog/Instances.kt +++ b/datalog/src/commonTest/kotlin/it/unibo/tuprolog/datalog/Instances.kt @@ -4,46 +4,51 @@ import it.unibo.tuprolog.dsl.theory.logicProgramming import it.unibo.tuprolog.theory.Theory object Instances { - val theoryWithCompoundTerms: Theory = logicProgramming { - theoryOf( - rule { "f"(X) impliedBy "g"("h"(X)) } - ) - } + val theoryWithCompoundTerms: Theory = + logicProgramming { + theoryOf( + rule { "f"(X) impliedBy "g"("h"(X)) }, + ) + } - val theoryWithFreeVariablesInTheHead: Theory = logicProgramming { - theoryOf( - rule { "f"(X, Y).impliedBy("g"(X, Z), "h"(Z, X)) } - ) - } + val theoryWithFreeVariablesInTheHead: Theory = + logicProgramming { + theoryOf( + rule { "f"(X, Y).impliedBy("g"(X, Z), "h"(Z, X)) }, + ) + } - val theoryWithFreeVariablesInNegatedBodyLiterals: Theory = logicProgramming { - theoryOf( - rule { "f"(X).impliedBy("g"(X, Z), "not"("h"(Y)), "i"(Z, X)) } - ) - } + val theoryWithFreeVariablesInNegatedBodyLiterals: Theory = + logicProgramming { + theoryOf( + rule { "f"(X).impliedBy("g"(X, Z), "not"("h"(Y)), "i"(Z, X)) }, + ) + } - val theoryWithRecursion: Theory = logicProgramming { - theoryOf( - rule { "a"(X).impliedBy("b"(X), "c"(X)) }, - rule { "b"(X).impliedBy("d"(X), "e"(X)) }, - rule { "c"(X).impliedBy("f"(X), "g"(X)) }, - fact { "d"(1) }, - fact { "e"(2) }, - rule { "f"(X) impliedBy "a"(X) }, - fact { "g"(4) } - ) - } + val theoryWithRecursion: Theory = + logicProgramming { + theoryOf( + rule { "a"(X).impliedBy("b"(X), "c"(X)) }, + rule { "b"(X).impliedBy("d"(X), "e"(X)) }, + rule { "c"(X).impliedBy("f"(X), "g"(X)) }, + fact { "d"(1) }, + fact { "e"(2) }, + rule { "f"(X) impliedBy "a"(X) }, + fact { "g"(4) }, + ) + } - val datalogTheory: Theory = logicProgramming { - theoryOf( - rule { "a"(X).impliedBy("b"(X), "c"(X)) }, - rule { "b"(X).impliedBy("d"(X), "e"(X)) }, - rule { "c"(X).impliedBy("f"(X), "g"(X)) }, - fact { "d"(1) }, - fact { "e"(2) }, - fact { "f"(3) }, - fact { "g"(4) }, - rule { "f"(X, Y).impliedBy("g"(X, Z), "h"(Z, Y)) } - ) - } + val datalogTheory: Theory = + logicProgramming { + theoryOf( + rule { "a"(X).impliedBy("b"(X), "c"(X)) }, + rule { "b"(X).impliedBy("d"(X), "e"(X)) }, + rule { "c"(X).impliedBy("f"(X), "g"(X)) }, + fact { "d"(1) }, + fact { "e"(2) }, + fact { "f"(3) }, + fact { "g"(4) }, + rule { "f"(X, Y).impliedBy("g"(X, Z), "h"(Z, Y)) }, + ) + } } diff --git a/datalog/src/commonTest/kotlin/it/unibo/tuprolog/datalog/TestDatalog.kt b/datalog/src/commonTest/kotlin/it/unibo/tuprolog/datalog/TestDatalog.kt index 23db79f15..6263fa182 100644 --- a/datalog/src/commonTest/kotlin/it/unibo/tuprolog/datalog/TestDatalog.kt +++ b/datalog/src/commonTest/kotlin/it/unibo/tuprolog/datalog/TestDatalog.kt @@ -9,8 +9,10 @@ import kotlin.test.assertTrue import kotlin.test.fail class TestDatalog { - - private fun assertTheoryIsBroken(theory: Theory, error: DatalogViolationException) { + private fun assertTheoryIsBroken( + theory: Theory, + error: DatalogViolationException, + ) { assertFalse(theory.isDatalog) try { theory.ensureIsDatalog() @@ -25,12 +27,13 @@ class TestDatalog { Instances.theoryWithCompoundTerms.let { val rule = it.rules.first() assertFalse(rule.hasNoCompound) - val error: DatalogViolationException? = try { - rule.ensureHasNoCompound() - null - } catch (e: DatalogViolationException) { - e - } + val error: DatalogViolationException? = + try { + rule.ensureHasNoCompound() + null + } catch (e: DatalogViolationException) { + e + } assertTheoryIsBroken(it, error!!) } } @@ -40,12 +43,13 @@ class TestDatalog { Instances.theoryWithFreeVariablesInTheHead.let { val rule = it.rules.first() assertFalse(rule.allHeadVariablesInNonNegatedLiterals) - val error: DatalogViolationException? = try { - rule.ensureAllHeadVariablesInNonNegatedLiterals() - null - } catch (e: DatalogViolationException) { - e - } + val error: DatalogViolationException? = + try { + rule.ensureAllHeadVariablesInNonNegatedLiterals() + null + } catch (e: DatalogViolationException) { + e + } assertTheoryIsBroken(it, error!!) } } @@ -55,12 +59,13 @@ class TestDatalog { Instances.theoryWithFreeVariablesInNegatedBodyLiterals.let { val rule = it.rules.first() assertFalse(rule.allNegatedLiteralsVariablesInNonNegatedLiteralsToo) - val error: DatalogViolationException? = try { - rule.ensureAllNegatedLiteralsVariablesInNonNegatedLiteralsToo() - null - } catch (e: DatalogViolationException) { - e - } + val error: DatalogViolationException? = + try { + rule.ensureAllNegatedLiteralsVariablesInNonNegatedLiteralsToo() + null + } catch (e: DatalogViolationException) { + e + } assertTheoryIsBroken(it, error!!) } } @@ -69,12 +74,13 @@ class TestDatalog { fun testRecursionDetection() { Instances.theoryWithRecursion.let { assertFalse(it.isNonRecursive) - val error: DatalogViolationException? = try { - it.ensureIsNonRecursive() - null - } catch (e: DatalogViolationException) { - e - } + val error: DatalogViolationException? = + try { + it.ensureIsNonRecursive() + null + } catch (e: DatalogViolationException) { + e + } assertTheoryIsBroken(it, error!!) } } diff --git a/dsl-core/src/commonMain/kotlin/it/unibo/tuprolog/dsl/AnyToTermConverter.kt b/dsl-core/src/commonMain/kotlin/it/unibo/tuprolog/dsl/AnyToTermConverter.kt index d945c9ae2..c840e69b0 100644 --- a/dsl-core/src/commonMain/kotlin/it/unibo/tuprolog/dsl/AnyToTermConverter.kt +++ b/dsl-core/src/commonMain/kotlin/it/unibo/tuprolog/dsl/AnyToTermConverter.kt @@ -13,31 +13,33 @@ import kotlin.js.JsName import it.unibo.tuprolog.core.toTerm as extToTerm internal interface AnyToTermConverter { - @JsName("prologScope") val prologScope: LogicProgrammingScope @JsName("toTerm") - fun toTerm(any: Any): Term = when (any) { - is Term -> any - is TermConvertible -> any.toTerm() - is BigInteger -> prologScope.numOf(any) - is BigDecimal -> prologScope.numOf(any) - is Number -> when { - any.isInteger -> any.toInteger() - else -> any.toReal() - } - is String -> when { - any.isVariable -> prologScope.varOf(any) - else -> prologScope.atomOf(any) + fun toTerm(any: Any): Term = + when (any) { + is Term -> any + is TermConvertible -> any.toTerm() + is BigInteger -> prologScope.numOf(any) + is BigDecimal -> prologScope.numOf(any) + is Number -> + when { + any.isInteger -> any.toInteger() + else -> any.toReal() + } + is String -> + when { + any.isVariable -> prologScope.varOf(any) + else -> prologScope.atomOf(any) + } + is Boolean -> any.toTruth() + is Array<*> -> any.map { toTerm(it!!) }.extToTerm() + is Sequence<*> -> any.map { toTerm(it!!) }.extToTerm() + is Iterable<*> -> any.map { toTerm(it!!) }.extToTerm() + else -> + any.raiseErrorConvertingTo(Term::class) } - is Boolean -> any.toTruth() - is Array<*> -> any.map { toTerm(it!!) }.extToTerm() - is Sequence<*> -> any.map { toTerm(it!!) }.extToTerm() - is Iterable<*> -> any.map { toTerm(it!!) }.extToTerm() - else -> - any.raiseErrorConvertingTo(Term::class) - } val Number.isInteger: Boolean diff --git a/dsl-core/src/commonMain/kotlin/it/unibo/tuprolog/dsl/LogicProgrammingScope.kt b/dsl-core/src/commonMain/kotlin/it/unibo/tuprolog/dsl/LogicProgrammingScope.kt index e7558760c..0a7f93b0e 100644 --- a/dsl-core/src/commonMain/kotlin/it/unibo/tuprolog/dsl/LogicProgrammingScope.kt +++ b/dsl-core/src/commonMain/kotlin/it/unibo/tuprolog/dsl/LogicProgrammingScope.kt @@ -18,12 +18,17 @@ import kotlin.js.JsName import it.unibo.tuprolog.core.List as LogicList interface LogicProgrammingScope : PrologStdLibScope, VariablesProvider { - @JsName("stringInvoke") - operator fun String.invoke(term: Any, vararg terms: Any): Struct + operator fun String.invoke( + term: Any, + vararg terms: Any, + ): Struct @JsName("structOfAny") - fun structOf(functor: String, vararg args: Any): Struct + fun structOf( + functor: String, + vararg args: Any, + ): Struct @JsName("anyPlus") operator fun Any.plus(other: Any): Struct @@ -80,6 +85,7 @@ interface LogicProgrammingScope : PrologStdLibScope, VariablesProvider { @JsName("anySup") infix fun Any.sup(other: Any): Struct + @Suppress("ktlint:standard:function-naming") @JsName("anyIs") infix fun Any.`is`(other: Any): Struct @@ -89,12 +95,14 @@ interface LogicProgrammingScope : PrologStdLibScope, VariablesProvider { @JsName("anyImpliedBy") infix fun Any.impliedBy(other: Any): Rule + @Suppress("ktlint:standard:function-naming") @JsName("anyIf") infix fun Any.`if`(other: Any): Rule @JsName("anyImpliedByVararg") fun Any.impliedBy(vararg other: Any): Rule + @Suppress("ktlint:standard:function-naming") @JsName("anyIfVararg") fun Any.`if`(vararg other: Any): Rule @@ -111,16 +119,25 @@ interface LogicProgrammingScope : PrologStdLibScope, VariablesProvider { fun factOf(term: Any): Fact @JsName("consOfAny") - fun consOf(head: Any, tail: Any): Cons + fun consOf( + head: Any, + tail: Any, + ): Cons @JsName("directiveOfAny") - fun directiveOf(term: Any, vararg terms: Any): Directive + fun directiveOf( + term: Any, + vararg terms: Any, + ): Directive @JsName("scope") fun scope(function: LogicProgrammingScope.() -> R): R @JsName("list") - fun list(vararg items: Any, tail: Any? = null): LogicList + fun list( + vararg items: Any, + tail: Any? = null, + ): LogicList @JsName("rule") fun rule(function: LogicProgrammingScope.() -> Any): Rule diff --git a/dsl-core/src/commonMain/kotlin/it/unibo/tuprolog/dsl/LogicProgrammingScopeImpl.kt b/dsl-core/src/commonMain/kotlin/it/unibo/tuprolog/dsl/LogicProgrammingScopeImpl.kt index 24a797bb9..a640fc180 100644 --- a/dsl-core/src/commonMain/kotlin/it/unibo/tuprolog/dsl/LogicProgrammingScopeImpl.kt +++ b/dsl-core/src/commonMain/kotlin/it/unibo/tuprolog/dsl/LogicProgrammingScopeImpl.kt @@ -19,17 +19,19 @@ import it.unibo.tuprolog.core.VariablesProvider internal class LogicProgrammingScopeImpl(scope: Scope) : LogicProgrammingScope, VariablesProvider by VariablesProvider.of(scope) { - private val anyToTermConverter = AnyToTermConverter.of(this) - override fun Any.toTerm(): Term = - anyToTermConverter.toTerm(this) + override fun Any.toTerm(): Term = anyToTermConverter.toTerm(this) - override fun String.invoke(term: Any, vararg terms: Any): Struct = - structOf(this, sequenceOf(term, *terms).map { it.toTerm() }) + override fun String.invoke( + term: Any, + vararg terms: Any, + ): Struct = structOf(this, sequenceOf(term, *terms).map { it.toTerm() }) - override fun structOf(functor: String, vararg args: Any): Struct = - structOf(functor, *args.map { it.toTerm() }.toTypedArray()) + override fun structOf( + functor: String, + vararg args: Any, + ): Struct = structOf(functor, *args.map { it.toTerm() }.toTypedArray()) override fun Any.plus(other: Any): Struct = structOf("+", this.toTerm(), other.toTerm()) @@ -46,15 +48,13 @@ internal class LogicProgrammingScopeImpl(scope: Scope) : override fun Any.greaterThan(other: Any): Struct = structOf(">", this.toTerm(), other.toTerm()) - override fun Any.greaterThanOrEqualsTo(other: Any): Struct = - structOf(">=", this.toTerm(), other.toTerm()) + override fun Any.greaterThanOrEqualsTo(other: Any): Struct = structOf(">=", this.toTerm(), other.toTerm()) override fun Any.nonLowerThan(other: Any): Struct = this greaterThanOrEqualsTo other override fun Any.lowerThan(other: Any): Struct = structOf("<", this.toTerm(), other.toTerm()) - override fun Any.lowerThanOrEqualsTo(other: Any): Struct = - structOf("=<", this.toTerm(), other.toTerm()) + override fun Any.lowerThanOrEqualsTo(other: Any): Struct = structOf("=<", this.toTerm(), other.toTerm()) override fun Any.nonGreaterThan(other: Any): Struct = this lowerThanOrEqualsTo other @@ -84,61 +84,76 @@ internal class LogicProgrammingScopeImpl(scope: Scope) : override fun Any.`if`(other: Any): Rule = this impliedBy other override fun Any.impliedBy(vararg other: Any): Rule = - this impliedBy Tuple.wrapIfNeeded(*other.map { it.toTerm() }.toTypedArray()) + this impliedBy + Tuple.wrapIfNeeded( + *other.map { + it.toTerm() + }.toTypedArray(), + ) - override fun Any.`if`(vararg other: Any): Rule = - this.impliedBy(*other) + override fun Any.`if`(vararg other: Any): Rule = this.impliedBy(*other) override fun tupleOf(vararg terms: Any): Tuple = tupleOf(*terms.map { it.toTerm() }.toTypedArray()) - override fun listOf(vararg terms: Any): List = - this.listOf(*terms.map { it.toTerm() }.toTypedArray()) + override fun listOf(vararg terms: Any): List = this.listOf(*terms.map { it.toTerm() }.toTypedArray()) - override fun blockOf(vararg terms: Any): Block = - this.blockOf(*terms.map { it.toTerm() }.toTypedArray()) + override fun blockOf(vararg terms: Any): Block = this.blockOf(*terms.map { it.toTerm() }.toTypedArray()) override fun factOf(term: Any): Fact = factOf(term.toTerm() as Struct) - override fun consOf(head: Any, tail: Any): Cons = consOf(head.toTerm(), tail.toTerm()) + override fun consOf( + head: Any, + tail: Any, + ): Cons = consOf(head.toTerm(), tail.toTerm()) - override fun directiveOf(term: Any, vararg terms: Any): Directive = - directiveOf(term.toTerm(), *terms.map { it.toTerm() }.toTypedArray()) + override fun directiveOf( + term: Any, + vararg terms: Any, + ): Directive = directiveOf(term.toTerm(), *terms.map { it.toTerm() }.toTypedArray()) override fun scope(function: LogicProgrammingScope.() -> R): R = LogicProgrammingScope.empty().function() - override fun list(vararg items: Any, tail: Any?): List = ktListOf(*items).map { it.toTerm() }.let { - if (tail != null) { - listFrom(it, last = tail.toTerm()) - } else { - listOf(it) + override fun list( + vararg items: Any, + tail: Any?, + ): List = + ktListOf(*items).map { it.toTerm() }.let { + if (tail != null) { + listFrom(it, last = tail.toTerm()) + } else { + listOf(it) + } } - } - override fun rule(function: LogicProgrammingScope.() -> Any): Rule = LogicProgrammingScope.empty().function().toTerm() as Rule + override fun rule(function: LogicProgrammingScope.() -> Any): Rule = + LogicProgrammingScope.empty().function().toTerm() as Rule - override fun clause(function: LogicProgrammingScope.() -> Any): Clause = LogicProgrammingScope.empty().function().let { - when (val t = it.toTerm()) { - is Clause -> t - is Struct -> return factOf(t) - else -> it.raiseErrorConvertingTo(Clause::class) + override fun clause(function: LogicProgrammingScope.() -> Any): Clause = + LogicProgrammingScope.empty().function().let { + when (val t = it.toTerm()) { + is Clause -> t + is Struct -> return factOf(t) + else -> it.raiseErrorConvertingTo(Clause::class) + } } - } - override fun directive(function: LogicProgrammingScope.() -> Any): Directive = LogicProgrammingScope.empty().function().let { - when (val t = it.toTerm()) { - is Directive -> t - is Struct -> return directiveOf(t) - else -> it.raiseErrorConvertingTo(Directive::class) + override fun directive(function: LogicProgrammingScope.() -> Any): Directive = + LogicProgrammingScope.empty().function().let { + when (val t = it.toTerm()) { + is Directive -> t + is Struct -> return directiveOf(t) + else -> it.raiseErrorConvertingTo(Directive::class) + } } - } - override fun fact(function: LogicProgrammingScope.() -> Any): Fact = LogicProgrammingScope.empty().function().let { - when (val t = it.toTerm()) { - is Fact -> t - is Struct -> return factOf(t) - else -> it.raiseErrorConvertingTo(Fact::class) + override fun fact(function: LogicProgrammingScope.() -> Any): Fact = + LogicProgrammingScope.empty().function().let { + when (val t = it.toTerm()) { + is Fact -> t + is Struct -> return factOf(t) + else -> it.raiseErrorConvertingTo(Fact::class) + } } - } override fun Var.to(termObject: Any) = Substitution.of(this, termObject.toTerm()) @@ -158,6 +173,5 @@ internal class LogicProgrammingScopeImpl(scope: Scope) : override fun Substitution.contains(term: Any): Boolean = containsKey(term) - override fun Substitution.containsValue(term: Any): Boolean = - this.containsValue(term.toTerm()) + override fun Substitution.containsValue(term: Any): Boolean = this.containsValue(term.toTerm()) } diff --git a/dsl-core/src/commonMain/kotlin/it/unibo/tuprolog/dsl/PrologStdLibScope.kt b/dsl-core/src/commonMain/kotlin/it/unibo/tuprolog/dsl/PrologStdLibScope.kt index 28a64ecf1..d8f928014 100644 --- a/dsl-core/src/commonMain/kotlin/it/unibo/tuprolog/dsl/PrologStdLibScope.kt +++ b/dsl-core/src/commonMain/kotlin/it/unibo/tuprolog/dsl/PrologStdLibScope.kt @@ -6,7 +6,6 @@ import kotlin.js.JsName @Suppress("PropertyName", "unused", "FunctionName") interface PrologStdLibScope : LogicProgrammingAwareScope { - val at_end_of_stream: Atom get() = atomOf("at_end_of_stream") @@ -23,253 +22,287 @@ interface PrologStdLibScope : LogicProgrammingAwareScope { get() = atomOf("!") @JsName("at_end_of_stream1") - fun at_end_of_stream(alias: Any): Struct = - structOf("at_end_of_stream", alias.toTerm()) + fun at_end_of_stream(alias: Any): Struct = structOf("at_end_of_stream", alias.toTerm()) @JsName("call1") - fun call(goal: Any): Struct = - structOf("call", goal.toTerm()) + fun call(goal: Any): Struct = structOf("call", goal.toTerm()) @JsName("catch3") - fun `catch`(goal: Any, error: Any, continuation: Any): Struct = - structOf("catch", goal.toTerm(), error.toTerm(), continuation.toTerm()) + fun `catch`( + goal: Any, + error: Any, + continuation: Any, + ): Struct = structOf("catch", goal.toTerm(), error.toTerm(), continuation.toTerm()) @JsName("throw1") - fun `throw`(error: Any): Struct = - structOf("throw", error.toTerm()) + fun `throw`(error: Any): Struct = structOf("throw", error.toTerm()) @JsName("not1") - fun not(goal: Any): Struct = - structOf("not", goal.toTerm()) + fun not(goal: Any): Struct = structOf("not", goal.toTerm()) @JsName("naf1") - fun naf(goal: Any): Struct = - structOf("\\+", goal.toTerm()) + fun naf(goal: Any): Struct = structOf("\\+", goal.toTerm()) @JsName("assert1") - fun assert(clause: Any): Struct = - structOf("assert", clause.toTerm()) + fun assert(clause: Any): Struct = structOf("assert", clause.toTerm()) @JsName("asserta1") - fun asserta(clause: Any): Struct = - structOf("asserta", clause.toTerm()) + fun asserta(clause: Any): Struct = structOf("asserta", clause.toTerm()) @JsName("assertz1") - fun assertz(clause: Any): Struct = - structOf("assertz", clause.toTerm()) + fun assertz(clause: Any): Struct = structOf("assertz", clause.toTerm()) @JsName("arg3") - fun arg(index: Any, compound: Any, argument: Any): Struct = - structOf("arg", index.toTerm(), compound.toTerm(), argument.toTerm()) + fun arg( + index: Any, + compound: Any, + argument: Any, + ): Struct = structOf("arg", index.toTerm(), compound.toTerm(), argument.toTerm()) @JsName("atom1") - fun atom(atom: Any): Struct = - structOf("atom", atom.toTerm()) + fun atom(atom: Any): Struct = structOf("atom", atom.toTerm()) @JsName("atomic1") - fun atomic(atomic: Any): Struct = - structOf("atomic", atomic.toTerm()) + fun atomic(atomic: Any): Struct = structOf("atomic", atomic.toTerm()) @JsName("between3") - fun between(min: Any, max: Any, number: Any): Struct = - structOf("between", min.toTerm(), max.toTerm(), number.toTerm()) + fun between( + min: Any, + max: Any, + number: Any, + ): Struct = structOf("between", min.toTerm(), max.toTerm(), number.toTerm()) @JsName("callable1") - fun callable(goal: Any): Struct = - structOf("callable", goal.toTerm()) + fun callable(goal: Any): Struct = structOf("callable", goal.toTerm()) @JsName("compound1") - fun compound(struct: Any): Struct = - structOf("compound", struct.toTerm()) + fun compound(struct: Any): Struct = structOf("compound", struct.toTerm()) @JsName("current_op3") - fun current_op(precedence: Any, specifier: Any, functor: Any): Struct = - structOf("current_op", precedence.toTerm(), specifier.toTerm(), functor.toTerm()) + fun current_op( + precedence: Any, + specifier: Any, + functor: Any, + ): Struct = structOf("current_op", precedence.toTerm(), specifier.toTerm(), functor.toTerm()) @JsName("op3") - fun op(precedence: Any, specifier: Any, functor: Any): Struct = - structOf("op", precedence.toTerm(), specifier.toTerm(), functor.toTerm()) + fun op( + precedence: Any, + specifier: Any, + functor: Any, + ): Struct = structOf("op", precedence.toTerm(), specifier.toTerm(), functor.toTerm()) @JsName("findall3") - fun findall(template: Any, goal: Any, bag: Any): Struct = - structOf("findall", template.toTerm(), goal.toTerm(), bag.toTerm()) + fun findall( + template: Any, + goal: Any, + bag: Any, + ): Struct = structOf("findall", template.toTerm(), goal.toTerm(), bag.toTerm()) @JsName("float1") - fun float(number: Any): Struct = - structOf("float", number.toTerm()) + fun float(number: Any): Struct = structOf("float", number.toTerm()) @JsName("functor3") - fun functor(struct: Any, functor: Any, arity: Any): Struct = - structOf("functor", struct.toTerm(), functor.toTerm(), arity.toTerm()) + fun functor( + struct: Any, + functor: Any, + arity: Any, + ): Struct = structOf("functor", struct.toTerm(), functor.toTerm(), arity.toTerm()) @JsName("ground1") - fun ground(term: Any): Struct = - structOf("ground", term.toTerm()) + fun ground(term: Any): Struct = structOf("ground", term.toTerm()) @JsName("integer1") - fun integer(number: Any): Struct = - structOf("integer", number.toTerm()) + fun integer(number: Any): Struct = structOf("integer", number.toTerm()) @JsName("natural") - fun natural(number: Any): Struct = - structOf("natural", number.toTerm()) + fun natural(number: Any): Struct = structOf("natural", number.toTerm()) @JsName("nonvar1") - fun nonvar(number: Any): Struct = - structOf("nonvar", number.toTerm()) + fun nonvar(number: Any): Struct = structOf("nonvar", number.toTerm()) @JsName("number1") - fun number(number: Any): Struct = - structOf("number", number.toTerm()) + fun number(number: Any): Struct = structOf("number", number.toTerm()) @JsName("var1") - fun `var`(term: Any): Struct = - structOf("var", term.toTerm()) + fun `var`(term: Any): Struct = structOf("var", term.toTerm()) @JsName("write1") - fun write(term: Any): Struct = - structOf("write", term.toTerm()) + fun write(term: Any): Struct = structOf("write", term.toTerm()) @JsName("univ2") infix fun Any.univ(other: Any): Struct = structOf("=..", this.toTerm(), other.toTerm()) @JsName("eq2") - infix fun Any.eq(right: Any): Struct = - structOf("=", this.toTerm(), right.toTerm()) + infix fun Any.eq(right: Any): Struct = structOf("=", this.toTerm(), right.toTerm()) @JsName("neq2") - infix fun Any.neq(right: Any): Struct = - structOf("\\=", this.toTerm(), right.toTerm()) + infix fun Any.neq(right: Any): Struct = structOf("\\=", this.toTerm(), right.toTerm()) @JsName("id2") - infix fun Any.id(right: Any): Struct = - structOf("==", this.toTerm(), right.toTerm()) + infix fun Any.id(right: Any): Struct = structOf("==", this.toTerm(), right.toTerm()) @JsName("nid2") - infix fun Any.nid(right: Any): Struct = - structOf("\\==", this.toTerm(), right.toTerm()) + infix fun Any.nid(right: Any): Struct = structOf("\\==", this.toTerm(), right.toTerm()) @JsName("arithEq2") - infix fun Any.arithEq(right: Any): Struct = - structOf("=:=", this.toTerm(), right.toTerm()) + infix fun Any.arithEq(right: Any): Struct = structOf("=:=", this.toTerm(), right.toTerm()) @JsName("arithNeq2") - infix fun Any.arithNeq(right: Any): Struct = - structOf("=\\=", this.toTerm(), right.toTerm()) + infix fun Any.arithNeq(right: Any): Struct = structOf("=\\=", this.toTerm(), right.toTerm()) @JsName("member2") - fun member(item: Any, list: Any): Struct = - structOf("member", item.toTerm(), list.toTerm()) + fun member( + item: Any, + list: Any, + ): Struct = structOf("member", item.toTerm(), list.toTerm()) @JsName("retract1") - fun retract(clause: Any): Struct = - structOf("retract", clause.toTerm()) + fun retract(clause: Any): Struct = structOf("retract", clause.toTerm()) @JsName("append3") - fun append(left: Any, right: Any, result: Any): Struct = - structOf("append", left.toTerm(), right.toTerm(), result.toTerm()) + fun append( + left: Any, + right: Any, + result: Any, + ): Struct = structOf("append", left.toTerm(), right.toTerm(), result.toTerm()) @JsName("retractall1") - fun retractall(clause: Any): Struct = - structOf("retractall", clause.toTerm()) + fun retractall(clause: Any): Struct = structOf("retractall", clause.toTerm()) @JsName("abolish1") - fun abolish(indicator: Any): Struct = - structOf("abolish", indicator.toTerm()) + fun abolish(indicator: Any): Struct = structOf("abolish", indicator.toTerm()) @JsName("atom_chars2") - fun atom_chars(atom: Any, chars: Any): Struct = - structOf("atom_chars", atom.toTerm(), chars.toTerm()) + fun atom_chars( + atom: Any, + chars: Any, + ): Struct = structOf("atom_chars", atom.toTerm(), chars.toTerm()) @JsName("atom_codes2") - fun atom_codes(atom: Any, codes: Any): Struct = - structOf("atom_codes", atom.toTerm(), codes.toTerm()) + fun atom_codes( + atom: Any, + codes: Any, + ): Struct = structOf("atom_codes", atom.toTerm(), codes.toTerm()) @JsName("atom_concat3") - fun atom_concat(first: Any, second: Any, result: Any): Struct = - structOf("atom_concat", first.toTerm(), second.toTerm(), result.toTerm()) + fun atom_concat( + first: Any, + second: Any, + result: Any, + ): Struct = structOf("atom_concat", first.toTerm(), second.toTerm(), result.toTerm()) @JsName("atom_length2") - fun atom_length(atom: Any, length: Any): Struct = - structOf("atom_length", atom.toTerm(), length.toTerm()) + fun atom_length( + atom: Any, + length: Any, + ): Struct = structOf("atom_length", atom.toTerm(), length.toTerm()) @JsName("char_code2") - fun char_code(char: Any, code: Any): Struct = - structOf("char_code", char.toTerm(), code.toTerm()) + fun char_code( + char: Any, + code: Any, + ): Struct = structOf("char_code", char.toTerm(), code.toTerm()) @JsName("clause2") - fun clause(head: Any, body: Any): Struct = - structOf("clause", head.toTerm(), body.toTerm()) + fun clause( + head: Any, + body: Any, + ): Struct = structOf("clause", head.toTerm(), body.toTerm()) @JsName("copy_term2") - fun copy_term(term: Any, copy: Any): Struct = - structOf("copy_term", term.toTerm(), copy.toTerm()) + fun copy_term( + term: Any, + copy: Any, + ): Struct = structOf("copy_term", term.toTerm(), copy.toTerm()) @JsName("current_flag2") - fun current_flag(name: Any, value: Any): Struct = - structOf("current_flag", name.toTerm(), value.toTerm()) - - @Deprecated("Despite current_prolog_flag/2 is a standard predicate, we suggest using current_flag/2", ReplaceWith("current_flag")) + fun current_flag( + name: Any, + value: Any, + ): Struct = structOf("current_flag", name.toTerm(), value.toTerm()) + + @Deprecated( + "Despite current_prolog_flag/2 is a standard predicate, we suggest using current_flag/2", + ReplaceWith("current_flag"), + ) @JsName("current_prolog_flag2") - fun current_prolog_flag(name: Any, value: Any): Struct = - structOf("current_prolog_flag", name.toTerm(), value.toTerm()) + fun current_prolog_flag( + name: Any, + value: Any, + ): Struct = structOf("current_prolog_flag", name.toTerm(), value.toTerm()) @JsName("sub_atom5") - fun sub_atom(atom: Any, before: Any, length: Any, after: Any, sub_atom: Any): Struct = - structOf("sub_atom", atom.toTerm(), before.toTerm(), length.toTerm(), after.toTerm(), sub_atom.toTerm()) + fun sub_atom( + atom: Any, + before: Any, + length: Any, + after: Any, + sub_atom: Any, + ): Struct = structOf("sub_atom", atom.toTerm(), before.toTerm(), length.toTerm(), after.toTerm(), sub_atom.toTerm()) @JsName("number_chars2") - fun number_chars(first: Any, second: Any): Struct = - structOf("number_chars", first.toTerm(), second.toTerm()) + fun number_chars( + first: Any, + second: Any, + ): Struct = structOf("number_chars", first.toTerm(), second.toTerm()) @JsName("number_codes2") - fun number_codes(first: Any, second: Any): Struct = - structOf("number_codes", first.toTerm(), second.toTerm()) + fun number_codes( + first: Any, + second: Any, + ): Struct = structOf("number_codes", first.toTerm(), second.toTerm()) @JsName("bagof3") - fun bagof(template: Any, goal: Any, bag: Any): Struct = - structOf("bagof", template.toTerm(), goal.toTerm(), bag.toTerm()) + fun bagof( + template: Any, + goal: Any, + bag: Any, + ): Struct = structOf("bagof", template.toTerm(), goal.toTerm(), bag.toTerm()) @JsName("setof3") - fun setof(template: Any, goal: Any, bag: Any): Struct = - structOf("setof", template.toTerm(), goal.toTerm(), bag.toTerm()) + fun setof( + template: Any, + goal: Any, + bag: Any, + ): Struct = structOf("setof", template.toTerm(), goal.toTerm(), bag.toTerm()) @JsName("consult1") - fun consult(url: Any): Struct = - structOf("consult", url.toTerm()) + fun consult(url: Any): Struct = structOf("consult", url.toTerm()) @JsName("set_flag2") - fun set_flag(name: Any, value: Any): Struct = - structOf("set_flag", name.toTerm(), value.toTerm()) - - @Deprecated("Despite set_prolog_flag/2 is a standard predicate, we suggest using set_flag/2", ReplaceWith("set_flag")) + fun set_flag( + name: Any, + value: Any, + ): Struct = structOf("set_flag", name.toTerm(), value.toTerm()) + + @Deprecated( + "Despite set_prolog_flag/2 is a standard predicate, we suggest using set_flag/2", + ReplaceWith("set_flag"), + ) @JsName("set_prolog_flag2") - fun set_prolog_flag(name: Any, value: Any): Struct = - structOf("set_prolog_flag", name.toTerm(), value.toTerm()) + fun set_prolog_flag( + name: Any, + value: Any, + ): Struct = structOf("set_prolog_flag", name.toTerm(), value.toTerm()) @JsName("dynamic1") - fun dynamic(indicator: Any): Struct = - structOf("dynamic", indicator.toTerm()) + fun dynamic(indicator: Any): Struct = structOf("dynamic", indicator.toTerm()) @JsName("static1") - fun static(indicator: Any): Struct = - structOf("static", indicator.toTerm()) + fun static(indicator: Any): Struct = structOf("static", indicator.toTerm()) @JsName("solve1") - fun solve(goal: Any): Struct = - structOf("solve", goal.toTerm()) + fun solve(goal: Any): Struct = structOf("solve", goal.toTerm()) @JsName("initialization1") - fun initialization(goal: Any): Struct = - structOf("initialization", goal.toTerm()) + fun initialization(goal: Any): Struct = structOf("initialization", goal.toTerm()) @JsName("load1") - fun load(url: Any): Struct = - structOf("load", url.toTerm()) + fun load(url: Any): Struct = structOf("load", url.toTerm()) @JsName("include1") - fun include(url: Any): Struct = - structOf("include", url.toTerm()) + fun include(url: Any): Struct = structOf("include", url.toTerm()) // close/1 // close/2 diff --git a/dsl-core/src/commonTest/kotlin/it/unibo/tuprolog/dsl/TestLogicProgrammingScope.kt b/dsl-core/src/commonTest/kotlin/it/unibo/tuprolog/dsl/TestLogicProgrammingScope.kt index 594de9bce..7b132fc1c 100644 --- a/dsl-core/src/commonTest/kotlin/it/unibo/tuprolog/dsl/TestLogicProgrammingScope.kt +++ b/dsl-core/src/commonTest/kotlin/it/unibo/tuprolog/dsl/TestLogicProgrammingScope.kt @@ -18,13 +18,18 @@ import kotlin.test.assertNotEquals import kotlin.test.assertSame class TestLogicProgrammingScope { - companion object { - fun assertDSLCreationIsCorrect(expected: Term, actualCreator: LogicProgrammingScope.() -> Term) { + fun assertDSLCreationIsCorrect( + expected: Term, + actualCreator: LogicProgrammingScope.() -> Term, + ) { assertEquals(expected, LogicProgrammingScope.empty().actualCreator()) } - fun assertDSLCreationIsCorrect(expectedCreator: LogicProgrammingScope.() -> Term, actualCreator: LogicProgrammingScope.() -> Term) { + fun assertDSLCreationIsCorrect( + expectedCreator: LogicProgrammingScope.() -> Term, + actualCreator: LogicProgrammingScope.() -> Term, + ) { val prolog = LogicProgrammingScope.empty() assertEquals(prolog.expectedCreator(), prolog.actualCreator()) } diff --git a/dsl-core/src/jsMain/kotlin/it/unibo/tuprolog/dsl/AnyToTermConverterImpl.kt b/dsl-core/src/jsMain/kotlin/it/unibo/tuprolog/dsl/AnyToTermConverterImpl.kt index 39decf5f9..205b97f32 100644 --- a/dsl-core/src/jsMain/kotlin/it/unibo/tuprolog/dsl/AnyToTermConverterImpl.kt +++ b/dsl-core/src/jsMain/kotlin/it/unibo/tuprolog/dsl/AnyToTermConverterImpl.kt @@ -4,8 +4,9 @@ import it.unibo.tuprolog.core.Integer import it.unibo.tuprolog.core.Real import it.unibo.tuprolog.utils.NumberTypeTester -actual class AnyToTermConverterImpl actual constructor(override val prologScope: LogicProgrammingScope) : AnyToTermConverter { - +actual class AnyToTermConverterImpl actual constructor( + override val prologScope: LogicProgrammingScope, +) : AnyToTermConverter { private val numberTypeTester = NumberTypeTester() override val Number.isInteger: Boolean diff --git a/dsl-core/src/jvmMain/kotlin/it/unibo/tuprolog/dsl/AnyToTermConverterImpl.kt b/dsl-core/src/jvmMain/kotlin/it/unibo/tuprolog/dsl/AnyToTermConverterImpl.kt index 98e43d136..7be127a2f 100644 --- a/dsl-core/src/jvmMain/kotlin/it/unibo/tuprolog/dsl/AnyToTermConverterImpl.kt +++ b/dsl-core/src/jvmMain/kotlin/it/unibo/tuprolog/dsl/AnyToTermConverterImpl.kt @@ -3,7 +3,9 @@ package it.unibo.tuprolog.dsl import it.unibo.tuprolog.core.Integer import it.unibo.tuprolog.core.Real -actual class AnyToTermConverterImpl actual constructor(override val prologScope: LogicProgrammingScope) : AnyToTermConverter { +actual class AnyToTermConverterImpl actual constructor( + override val prologScope: LogicProgrammingScope, +) : AnyToTermConverter { override val Number.isInteger: Boolean get() = this is Int || this is Long diff --git a/dsl-solve/src/commonMain/kotlin/it/unibo/tuprolog/dsl/solve/DSL.kt b/dsl-solve/src/commonMain/kotlin/it/unibo/tuprolog/dsl/solve/DSL.kt index b52d8e92a..9a68148f3 100644 --- a/dsl-solve/src/commonMain/kotlin/it/unibo/tuprolog/dsl/solve/DSL.kt +++ b/dsl-solve/src/commonMain/kotlin/it/unibo/tuprolog/dsl/solve/DSL.kt @@ -12,7 +12,7 @@ import kotlin.jvm.JvmName fun logicProgramming( solverFactory: SolverFactory, unificator: Unificator = solverFactory.defaultUnificator, - function: LogicProgrammingScopeWithResolution.() -> R + function: LogicProgrammingScopeWithResolution.() -> R, ): R { return LogicProgrammingScopeWithResolution.of(solverFactory, unificator).function() } @@ -21,11 +21,11 @@ fun logicProgramming( fun lp( solverFactory: SolverFactory, unificator: Unificator = solverFactory.defaultUnificator, - function: LogicProgrammingScopeWithResolution.() -> R + function: LogicProgrammingScopeWithResolution.() -> R, ): R = logicProgramming(solverFactory, unificator, function) @JsName("prolog") fun prolog( unificator: Unificator = Unificator.default, - function: LogicProgrammingScopeWithResolution.() -> R + function: LogicProgrammingScopeWithResolution.() -> R, ): R = logicProgramming(Solver.prolog, unificator, function) diff --git a/dsl-solve/src/commonMain/kotlin/it/unibo/tuprolog/dsl/solve/LogicProgrammingScopeWithResolution.kt b/dsl-solve/src/commonMain/kotlin/it/unibo/tuprolog/dsl/solve/LogicProgrammingScopeWithResolution.kt index 15f17a678..f38f5a123 100644 --- a/dsl-solve/src/commonMain/kotlin/it/unibo/tuprolog/dsl/solve/LogicProgrammingScopeWithResolution.kt +++ b/dsl-solve/src/commonMain/kotlin/it/unibo/tuprolog/dsl/solve/LogicProgrammingScopeWithResolution.kt @@ -31,18 +31,19 @@ interface LogicProgrammingScopeWithResolution : LogicProgrammingScopeWithTheorie stdIn: InputChannel = solverFactory.defaultInputChannel, stdOut: OutputChannel = solverFactory.defaultOutputChannel, stdErr: OutputChannel = solverFactory.defaultErrorChannel, - warnings: OutputChannel = solverFactory.defaultWarningsChannel - ): MutableSolver = solverFactory.mutableSolverWithDefaultBuiltins( - unificator, - otherLibraries, - flags, - staticKb, - dynamicKb, - stdIn, - stdOut, - stdErr, - warnings - ) + warnings: OutputChannel = solverFactory.defaultWarningsChannel, + ): MutableSolver = + solverFactory.mutableSolverWithDefaultBuiltins( + unificator, + otherLibraries, + flags, + staticKb, + dynamicKb, + stdIn, + stdOut, + stdErr, + warnings, + ) @JsName("staticKbByArray") fun staticKb(vararg clauses: Clause) = loadStaticClauses(*clauses) @@ -73,7 +74,12 @@ interface LogicProgrammingScopeWithResolution : LogicProgrammingScopeWithTheorie fun of( solverFactory: SolverFactory, unificator: Unificator = solverFactory.defaultUnificator, - scope: Scope = Scope.empty() - ): LogicProgrammingScopeWithResolution = LogicProgrammingScopeWithResolutionImpl(solverFactory, unificator, scope) + scope: Scope = Scope.empty(), + ): LogicProgrammingScopeWithResolution = + LogicProgrammingScopeWithResolutionImpl( + solverFactory, + unificator, + scope, + ) } } diff --git a/dsl-solve/src/commonMain/kotlin/it/unibo/tuprolog/dsl/solve/LogicProgrammingScopeWithResolutionImpl.kt b/dsl-solve/src/commonMain/kotlin/it/unibo/tuprolog/dsl/solve/LogicProgrammingScopeWithResolutionImpl.kt index c036d61bc..df5024cf9 100644 --- a/dsl-solve/src/commonMain/kotlin/it/unibo/tuprolog/dsl/solve/LogicProgrammingScopeWithResolutionImpl.kt +++ b/dsl-solve/src/commonMain/kotlin/it/unibo/tuprolog/dsl/solve/LogicProgrammingScopeWithResolutionImpl.kt @@ -10,7 +10,7 @@ class LogicProgrammingScopeWithResolutionImpl( override val solverFactory: SolverFactory, override val unificator: Unificator, scope: Scope, - override val defaultSolver: MutableSolver = solverFactory.mutableSolverWithDefaultBuiltins() + override val defaultSolver: MutableSolver = solverFactory.mutableSolverWithDefaultBuiltins(), ) : LogicProgrammingScopeWithResolution, LogicProgrammingScopeWithTheories by LogicProgrammingScopeWithTheories.of(unificator, scope), MutableSolver by defaultSolver diff --git a/dsl-solve/src/commonTest/kotlin/it/unibo/tuprolog/dsl/solve/TestNQueens.kt b/dsl-solve/src/commonTest/kotlin/it/unibo/tuprolog/dsl/solve/TestNQueens.kt index 4eae1af1e..1e4b3d173 100644 --- a/dsl-solve/src/commonTest/kotlin/it/unibo/tuprolog/dsl/solve/TestNQueens.kt +++ b/dsl-solve/src/commonTest/kotlin/it/unibo/tuprolog/dsl/solve/TestNQueens.kt @@ -7,50 +7,51 @@ import kotlin.test.Test import kotlin.test.assertEquals class TestNQueens { + private val solutions = + listOf( + listOf((1 to 3), (2 to 1), (3 to 4), (4 to 2)), + listOf((1 to 2), (2 to 4), (3 to 1), (4 to 3)), + ) - private val solutions = listOf( - listOf((1 to 3), (2 to 1), (3 to 4), (4 to 2)), - listOf((1 to 2), (2 to 4), (3 to 1), (4 to 3)) - ) - - private fun nQueens(n: Int): Sequence>> = prolog { - staticKb( - rule { - "no_attack"(("X1" and "Y1"), ("X2" and "Y2")) `if` ( - ("X1" arithNeq "X2") and - ("Y1" arithNeq "Y2") and - (("Y2" - "Y1") arithNeq ("X2" - "X1")) and - (("Y2" - "Y1") arithNeq ("X1" - "X2")) + private fun nQueens(n: Int): Sequence>> = + prolog { + staticKb( + rule { + "no_attack"(("X1" and "Y1"), ("X2" and "Y2")) `if` ( + ("X1" arithNeq "X2") and + ("Y1" arithNeq "Y2") and + (("Y2" - "Y1") arithNeq ("X2" - "X1")) and + (("Y2" - "Y1") arithNeq ("X1" - "X2")) ) - }, - fact { "no_attack_all"(`_`, emptyList) }, - rule { - "no_attack_all"("C", consOf("H", "Hs")) `if` ( - "no_attack"("C", "H") and - "no_attack_all"("C", "Hs") + }, + fact { "no_attack_all"(`_`, emptyList) }, + rule { + "no_attack_all"("C", consOf("H", "Hs")) `if` ( + "no_attack"("C", "H") and + "no_attack_all"("C", "Hs") ) - }, - fact { "solution"(`_`, emptyList) }, - rule { - "solution"("N", consOf(("X" and "Y"), "Cs")) `if` ( - "solution"("N", "Cs") and - between(1, "N", "Y") and - "no_attack_all"(("X" and "Y"), "Cs") + }, + fact { "solution"(`_`, emptyList) }, + rule { + "solution"("N", consOf(("X" and "Y"), "Cs")) `if` ( + "solution"("N", "Cs") and + between(1, "N", "Y") and + "no_attack_all"(("X" and "Y"), "Cs") ) - } - ) + }, + ) - solve("solution"(n, (1..n).map { it and "Y$it" })) - .filterIsInstance() - .map { it.solvedQuery[1].castToRecursive() } - .map { it.toList() } - .map { list -> - list.map { it as Tuple } - .map { - (it.left as Integer).value.toIntExact() to (it.right as Integer).value.toIntExact() - } - } - } + solve("solution"(n, (1..n).map { it and "Y$it" })) + .filterIsInstance() + .map { it.solvedQuery[1].castToRecursive() } + .map { it.toList() } + .map { list -> + list.map { it as Tuple } + .map { + (it.left as Integer).value.toIntExact() to (it.right as Integer).value.toIntExact() + } + } + } @Test fun testNQueens() { diff --git a/dsl-solve/src/commonTest/kotlin/it/unibo/tuprolog/dsl/solve/TestPrologWithResolution.kt b/dsl-solve/src/commonTest/kotlin/it/unibo/tuprolog/dsl/solve/TestPrologWithResolution.kt index c04d72d93..7cb2f73fd 100644 --- a/dsl-solve/src/commonTest/kotlin/it/unibo/tuprolog/dsl/solve/TestPrologWithResolution.kt +++ b/dsl-solve/src/commonTest/kotlin/it/unibo/tuprolog/dsl/solve/TestPrologWithResolution.kt @@ -15,11 +15,11 @@ class TestPrologWithResolution { rule { "ancestor"("X", "Y") `if` ( "parent"("X", "Z") and "ancestor"("Z", "Y") - ) + ) }, fact { "parent"("abraham", "isaac") }, fact { "parent"("isaac", "jacob") }, - fact { "parent"("jacob", "joseph") } + fact { "parent"("jacob", "joseph") }, ) val actual = mutableListOf() @@ -31,7 +31,7 @@ class TestPrologWithResolution { assertEquals( mutableListOf("isaac", "jacob", "joseph"), - actual + actual, ) } } diff --git a/dsl-theory/src/commonMain/kotlin/it/unibo/tuprolog/dsl/theory/DSL.kt b/dsl-theory/src/commonMain/kotlin/it/unibo/tuprolog/dsl/theory/DSL.kt index 6a27ca0b5..d0a507f69 100644 --- a/dsl-theory/src/commonMain/kotlin/it/unibo/tuprolog/dsl/theory/DSL.kt +++ b/dsl-theory/src/commonMain/kotlin/it/unibo/tuprolog/dsl/theory/DSL.kt @@ -10,7 +10,7 @@ import kotlin.jvm.JvmName @JsName("logicProgramming") fun logicProgramming( unificator: Unificator = Unificator.default, - function: LogicProgrammingScopeWithTheories.() -> R + function: LogicProgrammingScopeWithTheories.() -> R, ): R { return LogicProgrammingScopeWithTheories.of(unificator).function() } @@ -18,12 +18,12 @@ fun logicProgramming( @JsName("lp") fun lp( unificator: Unificator = Unificator.default, - function: LogicProgrammingScopeWithUnification.() -> R + function: LogicProgrammingScopeWithUnification.() -> R, ): R = logicProgramming(unificator, function) @Deprecated("Use `lp` or `logicProgramming` instead", ReplaceWith("lp(function)")) @JsName("prolog") fun prolog( unificator: Unificator = Unificator.default, - function: LogicProgrammingScopeWithUnification.() -> R + function: LogicProgrammingScopeWithUnification.() -> R, ): R = logicProgramming(unificator, function) diff --git a/dsl-theory/src/commonMain/kotlin/it/unibo/tuprolog/dsl/theory/LogicProgrammingScopeWithTheories.kt b/dsl-theory/src/commonMain/kotlin/it/unibo/tuprolog/dsl/theory/LogicProgrammingScopeWithTheories.kt index a5d3b769a..87b0d2cdd 100644 --- a/dsl-theory/src/commonMain/kotlin/it/unibo/tuprolog/dsl/theory/LogicProgrammingScopeWithTheories.kt +++ b/dsl-theory/src/commonMain/kotlin/it/unibo/tuprolog/dsl/theory/LogicProgrammingScopeWithTheories.kt @@ -10,7 +10,6 @@ import it.unibo.tuprolog.unify.Unificator import kotlin.js.JsName interface LogicProgrammingScopeWithTheories : LogicProgrammingScopeWithUnification { - @JsName("emptyTheory") fun emptyTheory(): Theory { return Theory.emptyIndexed(unificator) @@ -22,21 +21,28 @@ interface LogicProgrammingScopeWithTheories : LogicProgrammingScopeWithUnificati } @JsName("theoryOfIterable") - fun theoryOf(clauses: Iterable, vararg otherClauses: Iterable): Theory { + fun theoryOf( + clauses: Iterable, + vararg otherClauses: Iterable, + ): Theory { return Theory.indexedOf(unificator, sequenceOf(clauses, *otherClauses).flatMap { it.asSequence() }) } @JsName("theoryOfSequence") - fun theoryOf(clauses: Sequence, vararg otherClauses: Sequence): Theory { + fun theoryOf( + clauses: Sequence, + vararg otherClauses: Sequence, + ): Theory { return Theory.indexedOf(unificator, sequenceOf(clauses, *otherClauses).flatten()) } @JsName("theory") - fun theory(vararg clauseFunctions: LogicProgrammingScope.() -> Any): Theory = theoryOf( - *clauseFunctions.map { function -> - LogicProgrammingScope.empty().function().let { clause { it } } - }.toTypedArray() - ) + fun theory(vararg clauseFunctions: LogicProgrammingScope.() -> Any): Theory = + theoryOf( + *clauseFunctions.map { function -> + LogicProgrammingScope.empty().function().let { clause { it } } + }.toTypedArray(), + ) @JsName("emptyMutableTheory") fun emptyMutableTheory(): MutableTheory { @@ -49,27 +55,34 @@ interface LogicProgrammingScopeWithTheories : LogicProgrammingScopeWithUnificati } @JsName("mutableTheoryOfIterable") - fun mutableTheoryOf(clauses: Iterable, vararg otherClauses: Iterable): MutableTheory { + fun mutableTheoryOf( + clauses: Iterable, + vararg otherClauses: Iterable, + ): MutableTheory { return MutableTheory.indexedOf(unificator, sequenceOf(clauses, *otherClauses).flatMap { it.asSequence() }) } @JsName("mutableTheoryOfSequence") - fun mutableTheoryOf(clauses: Sequence, vararg otherClauses: Sequence): MutableTheory { + fun mutableTheoryOf( + clauses: Sequence, + vararg otherClauses: Sequence, + ): MutableTheory { return MutableTheory.indexedOf(unificator, sequenceOf(clauses, *otherClauses).flatten()) } @JsName("mutableTheory") - fun mutableTheory(vararg clauseFunctions: LogicProgrammingScope.() -> Any): MutableTheory = mutableTheoryOf( - *clauseFunctions.map { function -> - LogicProgrammingScope.empty().function().let { clause { it } } - }.toTypedArray() - ) + fun mutableTheory(vararg clauseFunctions: LogicProgrammingScope.() -> Any): MutableTheory = + mutableTheoryOf( + *clauseFunctions.map { function -> + LogicProgrammingScope.empty().function().let { clause { it } } + }.toTypedArray(), + ) companion object { @JsName("of") fun of( unificator: Unificator = Unificator.default, - scope: Scope = Scope.empty() + scope: Scope = Scope.empty(), ): LogicProgrammingScopeWithTheories = LogicProgrammingScopeWithTheoriesImpl(unificator, scope) } } diff --git a/dsl-theory/src/commonMain/kotlin/it/unibo/tuprolog/dsl/theory/LogicProgrammingScopeWithTheoriesImpl.kt b/dsl-theory/src/commonMain/kotlin/it/unibo/tuprolog/dsl/theory/LogicProgrammingScopeWithTheoriesImpl.kt index 7204e2de5..6f3735cb4 100644 --- a/dsl-theory/src/commonMain/kotlin/it/unibo/tuprolog/dsl/theory/LogicProgrammingScopeWithTheoriesImpl.kt +++ b/dsl-theory/src/commonMain/kotlin/it/unibo/tuprolog/dsl/theory/LogicProgrammingScopeWithTheoriesImpl.kt @@ -6,6 +6,6 @@ import it.unibo.tuprolog.unify.Unificator class LogicProgrammingScopeWithTheoriesImpl( unificator: Unificator, - scope: Scope + scope: Scope, ) : LogicProgrammingScopeWithTheories, LogicProgrammingScopeWithUnification by LogicProgrammingScopeWithUnification.of(unificator, scope) diff --git a/dsl-theory/src/commonTest/kotlin/it/unibo/tuprolog/dsl/theory/Prova.kt b/dsl-theory/src/commonTest/kotlin/it/unibo/tuprolog/dsl/theory/Prova.kt index d689c3e5d..286044bd5 100644 --- a/dsl-theory/src/commonTest/kotlin/it/unibo/tuprolog/dsl/theory/Prova.kt +++ b/dsl-theory/src/commonTest/kotlin/it/unibo/tuprolog/dsl/theory/Prova.kt @@ -3,15 +3,14 @@ package it.unibo.tuprolog.dsl.theory import kotlin.test.Test class Prova { - @Test fun testProlog() { logicProgramming { println( theoryOf( fact { "member"("X", consOf("X", `_`)) }, - rule { "member"("X", consOf(`_`, "T")) impliedBy "member"("X", "T") } - ) + rule { "member"("X", consOf(`_`, "T")) impliedBy "member"("X", "T") }, + ), ) } } diff --git a/dsl-unify/src/commonMain/kotlin/it/unibo/tuprolog/dsl/unify/DSL.kt b/dsl-unify/src/commonMain/kotlin/it/unibo/tuprolog/dsl/unify/DSL.kt index 01dc7afec..eb6088a21 100644 --- a/dsl-unify/src/commonMain/kotlin/it/unibo/tuprolog/dsl/unify/DSL.kt +++ b/dsl-unify/src/commonMain/kotlin/it/unibo/tuprolog/dsl/unify/DSL.kt @@ -9,18 +9,18 @@ import kotlin.jvm.JvmName @JsName("logicProgramming") fun logicProgramming( unificator: Unificator = Unificator.default, - function: LogicProgrammingScopeWithUnification.() -> R + function: LogicProgrammingScopeWithUnification.() -> R, ): R = LogicProgrammingScopeWithUnification.of(unificator).function() @JsName("lp") fun lp( unificator: Unificator = Unificator.default, - function: LogicProgrammingScopeWithUnification.() -> R + function: LogicProgrammingScopeWithUnification.() -> R, ): R = logicProgramming(unificator, function) @Deprecated("Use `lp` or `logicProgramming` instead", ReplaceWith("lp(function)")) @JsName("prolog") fun prolog( unificator: Unificator = Unificator.default, - function: LogicProgrammingScopeWithUnification.() -> R + function: LogicProgrammingScopeWithUnification.() -> R, ): R = logicProgramming(unificator, function) diff --git a/dsl-unify/src/commonMain/kotlin/it/unibo/tuprolog/dsl/unify/LogicProgrammingScopeWithUnification.kt b/dsl-unify/src/commonMain/kotlin/it/unibo/tuprolog/dsl/unify/LogicProgrammingScopeWithUnification.kt index 50c23eb30..620ace8fd 100644 --- a/dsl-unify/src/commonMain/kotlin/it/unibo/tuprolog/dsl/unify/LogicProgrammingScopeWithUnification.kt +++ b/dsl-unify/src/commonMain/kotlin/it/unibo/tuprolog/dsl/unify/LogicProgrammingScopeWithUnification.kt @@ -8,7 +8,6 @@ import it.unibo.tuprolog.unify.Unificator import kotlin.js.JsName interface LogicProgrammingScopeWithUnification : LogicProgrammingScope, Unificator { - @JsName("unificator") val unificator: Unificator @@ -25,22 +24,31 @@ interface LogicProgrammingScopeWithUnification : LogicProgrammingScope, Unificat this@LogicProgrammingScopeWithUnification.unify(this.toTerm(), other.toTerm()) @JsName("mguAny") - fun mgu(term1: Any, term2: Any, occurCheckEnabled: Boolean = true): Substitution = - mgu(term1.toTerm(), term2.toTerm(), occurCheckEnabled) + fun mgu( + term1: Any, + term2: Any, + occurCheckEnabled: Boolean = true, + ): Substitution = mgu(term1.toTerm(), term2.toTerm(), occurCheckEnabled) @JsName("matchAny") - fun match(term1: Any, term2: Any, occurCheckEnabled: Boolean = true): Boolean = - match(term1.toTerm(), term2.toTerm(), occurCheckEnabled) + fun match( + term1: Any, + term2: Any, + occurCheckEnabled: Boolean = true, + ): Boolean = match(term1.toTerm(), term2.toTerm(), occurCheckEnabled) @JsName("unifyAny") - fun unify(term1: Any, term2: Any, occurCheckEnabled: Boolean = true): Term? = - unify(term1.toTerm(), term2.toTerm(), occurCheckEnabled) + fun unify( + term1: Any, + term2: Any, + occurCheckEnabled: Boolean = true, + ): Term? = unify(term1.toTerm(), term2.toTerm(), occurCheckEnabled) companion object { @JsName("of") fun of( unificator: Unificator = Unificator.default, - scope: Scope = Scope.empty() + scope: Scope = Scope.empty(), ): LogicProgrammingScopeWithUnification = LogicProgrammingScopeWithUnificationImpl(unificator, scope) } } diff --git a/dsl-unify/src/commonMain/kotlin/it/unibo/tuprolog/dsl/unify/LogicProgrammingScopeWithUnificationImpl.kt b/dsl-unify/src/commonMain/kotlin/it/unibo/tuprolog/dsl/unify/LogicProgrammingScopeWithUnificationImpl.kt index c61c23b3e..b568ac5f1 100644 --- a/dsl-unify/src/commonMain/kotlin/it/unibo/tuprolog/dsl/unify/LogicProgrammingScopeWithUnificationImpl.kt +++ b/dsl-unify/src/commonMain/kotlin/it/unibo/tuprolog/dsl/unify/LogicProgrammingScopeWithUnificationImpl.kt @@ -6,7 +6,7 @@ import it.unibo.tuprolog.unify.Unificator class LogicProgrammingScopeWithUnificationImpl( override val unificator: Unificator, - scope: Scope + scope: Scope, ) : LogicProgrammingScopeWithUnification, LogicProgrammingScope by LogicProgrammingScope.of(scope), Unificator by unificator diff --git a/dsl-unify/src/commonTest/kotlin/it/unibo/tuprolog/dsl/unify/Prova.kt b/dsl-unify/src/commonTest/kotlin/it/unibo/tuprolog/dsl/unify/Prova.kt index 3eefc13b7..a02dfd6e9 100644 --- a/dsl-unify/src/commonTest/kotlin/it/unibo/tuprolog/dsl/unify/Prova.kt +++ b/dsl-unify/src/commonTest/kotlin/it/unibo/tuprolog/dsl/unify/Prova.kt @@ -3,7 +3,6 @@ package it.unibo.tuprolog.dsl.unify import kotlin.test.Test class Prova { - @Test fun testProlog() { logicProgramming { diff --git a/examples/src/main/kotlin/it/unibo/tuprolog/examples/concurrent/ConcurrentSolverPerformance.kt b/examples/src/main/kotlin/it/unibo/tuprolog/examples/concurrent/ConcurrentSolverPerformance.kt index 1bedbca29..ec5167e78 100644 --- a/examples/src/main/kotlin/it/unibo/tuprolog/examples/concurrent/ConcurrentSolverPerformance.kt +++ b/examples/src/main/kotlin/it/unibo/tuprolog/examples/concurrent/ConcurrentSolverPerformance.kt @@ -14,8 +14,8 @@ import it.unibo.tuprolog.solve.currentTimeInstant import it.unibo.tuprolog.theory.Theory import it.unibo.tuprolog.theory.parsing.ClausesReader +@Suppress("ktlint:standard:property-naming") object ConcurrentSolverPerformance { - const val nQueens = 8 val theoryNQueens = loadTheoryFromFile("nQueens.pl") val queryNQueens = Struct.of("queenCountSolution", Integer.of(nQueens), Var.of("Count")) @@ -32,13 +32,19 @@ object ConcurrentSolverPerformance { return end - start } - fun runConcurrent(theory: Theory, query: Struct) { + fun runConcurrent( + theory: Theory, + query: Struct, + ) { val solver = ConcurrentSolverFactory.solverWithDefaultBuiltins(staticKb = theory) val executionTime = computeTime { solver.solveOnce(query) } println("Concurrent Execution time: ${executionTime}ms") } - fun runClassic(theory: Theory, query: Struct) { + fun runClassic( + theory: Theory, + query: Struct, + ) { val solver = ClassicSolverFactory.solverWithDefaultBuiltins(staticKb = theory) val executionTime = computeTime { solver.solveOnce(query) } println("Classic Execution time: ${executionTime}ms") diff --git a/examples/src/main/kotlin/it/unibo/tuprolog/examples/core/substitution/Chain.kt b/examples/src/main/kotlin/it/unibo/tuprolog/examples/core/substitution/Chain.kt index 9c45fb00a..3e330348a 100644 --- a/examples/src/main/kotlin/it/unibo/tuprolog/examples/core/substitution/Chain.kt +++ b/examples/src/main/kotlin/it/unibo/tuprolog/examples/core/substitution/Chain.kt @@ -10,10 +10,11 @@ import it.unibo.tuprolog.core.Substitution */ fun main() { Scope.empty { - val substitution = Substitution.of( - varOf("X") to varOf("Y"), - varOf("Y") to varOf("Z") - ) + val substitution = + Substitution.of( + varOf("X") to varOf("Y"), + varOf("Y") to varOf("Z"), + ) val originalZ = substitution.getOriginal(varOf("Z")) diff --git a/examples/src/main/kotlin/it/unibo/tuprolog/examples/core/substitution/Creation.kt b/examples/src/main/kotlin/it/unibo/tuprolog/examples/core/substitution/Creation.kt index a3aecf1b9..539431fea 100644 --- a/examples/src/main/kotlin/it/unibo/tuprolog/examples/core/substitution/Creation.kt +++ b/examples/src/main/kotlin/it/unibo/tuprolog/examples/core/substitution/Creation.kt @@ -10,10 +10,11 @@ import it.unibo.tuprolog.core.Substitution */ fun main() { Scope.empty { - val substitution = Substitution.of( - varOf("X") to atomOf("abraham"), - varOf("Y") to atomOf("isaac") - ) + val substitution = + Substitution.of( + varOf("X") to atomOf("abraham"), + varOf("Y") to atomOf("isaac"), + ) println(substitution) } diff --git a/examples/src/main/kotlin/it/unibo/tuprolog/examples/solve/SolverExample.kt b/examples/src/main/kotlin/it/unibo/tuprolog/examples/solve/SolverExample.kt index 63c040745..c74c595f5 100644 --- a/examples/src/main/kotlin/it/unibo/tuprolog/examples/solve/SolverExample.kt +++ b/examples/src/main/kotlin/it/unibo/tuprolog/examples/solve/SolverExample.kt @@ -24,7 +24,7 @@ fun gt(request: Solve.Request): Sequence { request.context, request.signature, TypeError.Expected.NUMBER, - arg1 + arg1, ) } if (arg2 !is Numeric) { @@ -32,7 +32,7 @@ fun gt(request: Solve.Request): Sequence { request.context, request.signature, TypeError.Expected.NUMBER, - arg2 + arg2, ) } @@ -45,19 +45,22 @@ fun gt(request: Solve.Request): Sequence { fun main() { logicProgramming { - val solver = Solver.prolog.solverWithDefaultBuiltins( - otherLibraries = Runtime.of( - Library.of( - alias = "it.unibo.lrizzato.myprimives", - primitives = mapOf(gtSignature to Primitive(::gt)) - ) - ), - staticKb = theoryOf( - fact { "user"("giovanni") }, - fact { "user"("lorenzo") }, - rule { "user"(`_`) impliedBy fail } + val solver = + Solver.prolog.solverWithDefaultBuiltins( + otherLibraries = + Runtime.of( + Library.of( + alias = "it.unibo.lrizzato.myprimives", + primitives = mapOf(gtSignature to Primitive(::gt)), + ), + ), + staticKb = + theoryOf( + fact { "user"("giovanni") }, + fact { "user"("lorenzo") }, + rule { "user"(`_`) impliedBy fail }, + ), ) - ) val query = "user"("X") and "write"("hello: ") and "write"("X") and "nl" and "gt"(2, 1) solver.solve(query).forEach { when (it) { diff --git a/examples/src/main/kotlin/it/unibo/tuprolog/examples/solve/ThermostatAgentKt.kt b/examples/src/main/kotlin/it/unibo/tuprolog/examples/solve/ThermostatAgentKt.kt index dde47757a..54cac0a59 100644 --- a/examples/src/main/kotlin/it/unibo/tuprolog/examples/solve/ThermostatAgentKt.kt +++ b/examples/src/main/kotlin/it/unibo/tuprolog/examples/solve/ThermostatAgentKt.kt @@ -16,31 +16,32 @@ class ThermostatAgentKt( name: String, private val coldThreshold: Int, private val hotThreshold: Int, - initialTemperature: Int + initialTemperature: Int, ) : Thread(name) { - var temperature: Int = initialTemperature private set - private val getTemp = object : UnaryPredicate.Functional("get_temp") { - override fun Solve.Request.computeOneSubstitution(first: Term): Substitution { - ensuringArgumentIsVariable(0) - return mgu(first, Integer.of(temperature)) + private val getTemp = + object : UnaryPredicate.Functional("get_temp") { + override fun Solve.Request.computeOneSubstitution(first: Term): Substitution { + ensuringArgumentIsVariable(0) + return mgu(first, Integer.of(temperature)) + } } - } - private val push = object : UnaryPredicate.Predicative("push") { - override fun Solve.Request.compute(first: Term): Boolean { - ensuringAllArgumentsAreInstantiated() - ensuringArgumentIsAtom(0) - when (first.castToAtom().value) { - "hot" -> temperature++ - "cold" -> temperature-- - else -> return false + private val push = + object : UnaryPredicate.Predicative("push") { + override fun Solve.Request.compute(first: Term): Boolean { + ensuringAllArgumentsAreInstantiated() + ensuringArgumentIsAtom(0) + when (first.castToAtom().value) { + "hot" -> temperature++ + "cold" -> temperature-- + else -> return false + } + return true } - return true } - } private fun agentProgram(): String = this::class.java.getResource("thermostat.pl")!!.readText() @@ -51,11 +52,12 @@ class ThermostatAgentKt( override fun run() { val theory = prologParser.parseTheory(agentProgram()) - val solver = Solver.prolog.newBuilder() - .staticKb(theory) - .flag(TrackVariables) { ON } - .library("libs.agency.thermostat", getTemp, push) - .build() + val solver = + Solver.prolog.newBuilder() + .staticKb(theory) + .flag(TrackVariables) { ON } + .library("libs.agency.thermostat", getTemp, push) + .build() when (val solution = solver.solveOnce(Atom.of("start"))) { is Solution.Yes -> println("Reached target temperature: $temperature") is Solution.No -> println("Failure in logic program") @@ -71,12 +73,13 @@ class ThermostatAgentKt( companion object { @JvmStatic fun main(args: Array) { - val thermostatAgent = ThermostatAgentKt( - name = "thermostat", - coldThreshold = 20, - hotThreshold = 24, - initialTemperature = 15 - ) + val thermostatAgent = + ThermostatAgentKt( + name = "thermostat", + coldThreshold = 20, + hotThreshold = 24, + initialTemperature = 15, + ) thermostatAgent.start() thermostatAgent.join() } diff --git a/examples/src/main/kotlin/it/unibo/tuprolog/examples/unify/CustomUnificator.kt b/examples/src/main/kotlin/it/unibo/tuprolog/examples/unify/CustomUnificator.kt index f89ca02b9..2fcbc9008 100644 --- a/examples/src/main/kotlin/it/unibo/tuprolog/examples/unify/CustomUnificator.kt +++ b/examples/src/main/kotlin/it/unibo/tuprolog/examples/unify/CustomUnificator.kt @@ -13,15 +13,20 @@ import it.unibo.tuprolog.unify.AbstractUnificator */ fun main() { Scope.empty { - val unificator = object : AbstractUnificator() { - override fun checkTermsEquality(first: Term, second: Term): Boolean = when { - first is Integer && second is Integer -> - first.value.absoluteValue.compareTo(second.value.absoluteValue) == 0 - first is Numeric && second is Numeric -> - first.decimalValue.absoluteValue.compareTo(second.decimalValue.absoluteValue) == 0 - else -> first == second + val unificator = + object : AbstractUnificator() { + override fun checkTermsEquality( + first: Term, + second: Term, + ): Boolean = + when { + first is Integer && second is Integer -> + first.value.absoluteValue.compareTo(second.value.absoluteValue) == 0 + first is Numeric && second is Numeric -> + first.decimalValue.absoluteValue.compareTo(second.decimalValue.absoluteValue) == 0 + else -> first == second + } } - } val term1 = structOf("f", numOf("1")) val term2 = structOf("f", numOf("-1")) diff --git a/examples/src/test/kotlin/it/unibo/tuprolog/examples/ExampleProbLogSolver.kt b/examples/src/test/kotlin/it/unibo/tuprolog/examples/ExampleProbLogSolver.kt index d41e0260e..822a57da9 100644 --- a/examples/src/test/kotlin/it/unibo/tuprolog/examples/ExampleProbLogSolver.kt +++ b/examples/src/test/kotlin/it/unibo/tuprolog/examples/ExampleProbLogSolver.kt @@ -15,8 +15,9 @@ class ExampleProbLogSolver { fun examplifyProblogSolver() { val clausesParser = ClausesParser.withOperators(PROBLOG_OPERATORS) - val probabilisticTheory = clausesParser.parseTheory( - """ + val probabilisticTheory = + clausesParser.parseTheory( + """ 0.6::edge(1,2). 0.1::edge(1,3). 0.4::edge(2,5). @@ -27,8 +28,8 @@ class ExampleProbLogSolver { path(X,Y) :- edge(X,Y). path(X,Y) :- edge(X,Z),Y \== Z,path(Z,Y). - """ - ) + """, + ) val problogSolver = Solver.problog.solverWithDefaultBuiltins(staticKb = probabilisticTheory) val goal = Struct.of("path", Var.of("From"), Var.of("To")) diff --git a/examples/src/test/kotlin/it/unibo/tuprolog/examples/ExamplePrologSolver.kt b/examples/src/test/kotlin/it/unibo/tuprolog/examples/ExamplePrologSolver.kt index f95dfd731..d66a51524 100644 --- a/examples/src/test/kotlin/it/unibo/tuprolog/examples/ExamplePrologSolver.kt +++ b/examples/src/test/kotlin/it/unibo/tuprolog/examples/ExamplePrologSolver.kt @@ -28,16 +28,19 @@ import it.unibo.tuprolog.theory.Theory import kotlin.test.Ignore import kotlin.test.Test +@Suppress("ktlint:standard:discouraged-comment-location") class ExamplePrologSolver { @Test fun exampleYesSolutionList() { - val prolog = Solver.prolog.solverWithDefaultBuiltins( - staticKb = Theory.of( - Fact.of(Struct.of("f", Atom.of("a"))), - Fact.of(Struct.of("f", Atom.of("b"))), - Fact.of(Struct.of("f", Atom.of("c"))) + val prolog = + Solver.prolog.solverWithDefaultBuiltins( + staticKb = + Theory.of( + Fact.of(Struct.of("f", Atom.of("a"))), + Fact.of(Struct.of("f", Atom.of("b"))), + Fact.of(Struct.of("f", Atom.of("c"))), + ), ) - ) val goal = Struct.of("f", Var.of("X")) @@ -58,13 +61,15 @@ class ExamplePrologSolver { @Test fun exampleYesSolutions() { - val prolog = Solver.prolog.solverWithDefaultBuiltins( - staticKb = Theory.of( - Fact.of(Struct.of("f", Atom.of("a"))), - Fact.of(Struct.of("f", Atom.of("b"))), - Fact.of(Struct.of("f", Atom.of("c"))) + val prolog = + Solver.prolog.solverWithDefaultBuiltins( + staticKb = + Theory.of( + Fact.of(Struct.of("f", Atom.of("a"))), + Fact.of(Struct.of("f", Atom.of("b"))), + Fact.of(Struct.of("f", Atom.of("c"))), + ), ) - ) val goal = Struct.of("f", Var.of("X")) @@ -83,15 +88,17 @@ class ExamplePrologSolver { } @Test - @Suppress("ktlint:experimental:comment-wrapping") + @Suppress("ktlint:standard:comment-wrapping") fun exampleTimeoutSolutions() { - val prolog = Solver.prolog.solverWithDefaultBuiltins( - staticKb = Theory.of( - Fact.of(Struct.of("f", Atom.of("a"))), - Fact.of(Struct.of("f", Atom.of("b"))), - Fact.of(Struct.of("f", Atom.of("c"))) + val prolog = + Solver.prolog.solverWithDefaultBuiltins( + staticKb = + Theory.of( + Fact.of(Struct.of("f", Atom.of("a"))), + Fact.of(Struct.of("f", Atom.of("b"))), + Fact.of(Struct.of("f", Atom.of("c"))), + ), ) - ) val goal = Struct.of("f", Var.of("X")) @@ -127,17 +134,19 @@ class ExamplePrologSolver { @Test fun manySolutionsLazy() { - val prolog = Solver.prolog.solverOf( - staticKb = Theory.of( - { factOf(structOf("nat", atomOf("z"))) }, - { - ruleOf( - structOf("nat", structOf("s", varOf("Z"))), - structOf("nat", varOf("Z")) - ) - } + val prolog = + Solver.prolog.solverOf( + staticKb = + Theory.of( + { factOf(structOf("nat", atomOf("z"))) }, + { + ruleOf( + structOf("nat", structOf("s", varOf("Z"))), + structOf("nat", varOf("Z")), + ) + }, + ), ) - ) val goal = Struct.of("nat", Var.of("X")) val solutions = prolog.solve(goal, SolveOptions.someLazily(limit = 1000)) @@ -148,17 +157,19 @@ class ExamplePrologSolver { @Test @Ignore fun manySolutionsEager() { - val prolog = Solver.prolog.solverOf( - staticKb = Theory.of( - { factOf(structOf("nat", atomOf("z"))) }, - { - ruleOf( - structOf("nat", structOf("s", varOf("Z"))), - structOf("nat", varOf("Z")) - ) - } + val prolog = + Solver.prolog.solverOf( + staticKb = + Theory.of( + { factOf(structOf("nat", atomOf("z"))) }, + { + ruleOf( + structOf("nat", structOf("s", varOf("Z"))), + structOf("nat", varOf("Z")), + ) + }, + ), ) - ) val goal = Struct.of("nat", Var.of("X")) val solutions = prolog.solve(goal, SolveOptions.someEagerly(limit = 1000)) @@ -168,19 +179,21 @@ class ExamplePrologSolver { @Test fun mutableVsNonMutableSolvers() { - val theory = Theory.of( - Fact.of(Struct.of("f", Atom.of("a"))), // f(a). - Fact.of(Struct.of("f", Atom.of("b"))), // f(b). - Fact.of(Struct.of("f", Atom.of("c"))) // f(c). - ) + val theory = + Theory.of( + Fact.of(Struct.of("f", Atom.of("a"))), // f(a). + Fact.of(Struct.of("f", Atom.of("b"))), // f(b). + Fact.of(Struct.of("f", Atom.of("c"))), // f(c). + ) val fact = Struct.of("g", Integer.ONE) // g(1). // solvers require information to be provided at instantiation time: - val solver: Solver = Solver.prolog.solverOf( - libraries = Runtime.of(DefaultBuiltins), - staticKb = theory - ) + val solver: Solver = + Solver.prolog.solverOf( + libraries = Runtime.of(DefaultBuiltins), + staticKb = theory, + ) solver.solveOnce(Struct.of("assert", fact)) println(solver.dynamicKb) // MutableIndexedTheory{ g(1) :- true } @@ -197,19 +210,22 @@ class ExamplePrologSolver { @Test fun customTheoriesSolver() { - val theory1 = Theory.of( - Fact.of(Struct.of("f", Atom.of("a"))), // f(a). - Fact.of(Struct.of("f", Atom.of("b"))) // f(b). - ) - val theory2 = Theory.of( - Fact.of(Struct.of("g", Integer.of(1))), // g(1). - Fact.of(Struct.of("g", Integer.of(2))) // g(2). - ) - - val solver = Solver.prolog.solverWithDefaultBuiltins( - staticKb = theory1, - dynamicKb = theory2 - ) + val theory1 = + Theory.of( + Fact.of(Struct.of("f", Atom.of("a"))), // f(a). + Fact.of(Struct.of("f", Atom.of("b"))), // f(b). + ) + val theory2 = + Theory.of( + Fact.of(Struct.of("g", Integer.of(1))), // g(1). + Fact.of(Struct.of("g", Integer.of(2))), // g(2). + ) + + val solver = + Solver.prolog.solverWithDefaultBuiltins( + staticKb = theory1, + dynamicKb = theory2, + ) println(solver.staticKb) // IndexedTheory{ f(a) :- true. f(b) :- true } println(solver.dynamicKb) // MutableIndexedTheory{ g(1) :- true. g(2) :- true } @@ -217,14 +233,16 @@ class ExamplePrologSolver { @Test fun customTheoriesMutableSolver() { - val theory1 = Theory.of( - Fact.of(Struct.of("f", Atom.of("a"))), // f(a). - Fact.of(Struct.of("f", Atom.of("b"))) // f(b). - ) - val theory2 = Theory.of( - Fact.of(Struct.of("g", Integer.of(1))), // g(1). - Fact.of(Struct.of("g", Integer.of(2))) // g(2). - ) + val theory1 = + Theory.of( + Fact.of(Struct.of("f", Atom.of("a"))), // f(a). + Fact.of(Struct.of("f", Atom.of("b"))), // f(b). + ) + val theory2 = + Theory.of( + Fact.of(Struct.of("g", Integer.of(1))), // g(1). + Fact.of(Struct.of("g", Integer.of(2))), // g(2). + ) val solver = Solver.prolog.mutableSolverWithDefaultBuiltins() println(solver.staticKb) // IndexedTheory{ } @@ -238,17 +256,19 @@ class ExamplePrologSolver { @Test fun directives() { - val theory = Theory.of( - Fact.of(Struct.of("f", Atom.of("a"))), // f(a). - Fact.of(Struct.of("f", Atom.of("b"))), // f(b). - Directive.of(Struct.of("dynamic", Indicator.of("g", 1))), // :- dynamic(g/1). - Fact.of(Struct.of("g", Integer.of(1))), // g(1). - Fact.of(Struct.of("g", Integer.of(2))) // g(2). - ) - - val solver = Solver.prolog.solverWithDefaultBuiltins( - staticKb = theory - ) + val theory = + Theory.of( + Fact.of(Struct.of("f", Atom.of("a"))), // f(a). + Fact.of(Struct.of("f", Atom.of("b"))), // f(b). + Directive.of(Struct.of("dynamic", Indicator.of("g", 1))), // :- dynamic(g/1). + Fact.of(Struct.of("g", Integer.of(1))), // g(1). + Fact.of(Struct.of("g", Integer.of(2))), // g(2). + ) + + val solver = + Solver.prolog.solverWithDefaultBuiltins( + staticKb = theory, + ) println(solver.staticKb) // IndexedTheory{ f(a) :- true. f(b) :- true. :- dynamic(g/1) } println(solver.dynamicKb) // MutableIndexedTheory{ g(1) :- true. g(2) :- true } @@ -256,9 +276,10 @@ class ExamplePrologSolver { @Test fun usingLibraries() { - val solver = Solver.prolog.solverOf( - libraries = Runtime.of(DefaultBuiltins, IOLib, OOPLib) - ) + val solver = + Solver.prolog.solverOf( + libraries = Runtime.of(DefaultBuiltins, IOLib, OOPLib), + ) println(solver.libraries.keys) // [prolog.lang, prolog.io, prolog.oop] } @@ -266,22 +287,27 @@ class ExamplePrologSolver { @Suppress("UNUSED_ANONYMOUS_PARAMETER") @Test fun definingLibraries() { - val myLibrary = object : Library by - Library.of( - alias = "alias.of.the.lib", - primitives = mapOf( - Signature("f", 2) to Primitive { request: Solve.Request -> - TODO("compute response sequence here") - } - ), - clauses = emptyList(), - operators = OperatorSet(), - functions = mapOf( - Signature("+", 2) to LogicFunction { request: Compute.Request -> - TODO("compute response here") - } - ) - ) {} + val myLibrary = + object : Library by + Library.of( + alias = "alias.of.the.lib", + primitives = + mapOf( + Signature("f", 2) to + Primitive { request: Solve.Request -> + TODO("compute response sequence here") + }, + ), + clauses = emptyList(), + operators = OperatorSet(), + functions = + mapOf( + Signature("+", 2) to + LogicFunction { request: Compute.Request -> + TODO("compute response here") + }, + ), + ) {} println(myLibrary) } diff --git a/full/build.gradle.kts b/full/build.gradle.kts index 0d0ccad68..491779b98 100644 --- a/full/build.gradle.kts +++ b/full/build.gradle.kts @@ -4,7 +4,7 @@ plugins { id(libs.plugins.ktMpp.mavenPublish.get().pluginId) id(libs.plugins.ktMpp.npmPublish.get().pluginId) id(libs.plugins.ktMpp.multiProjectHelper.get().pluginId) - id(libs.plugins.shadowJar.get().pluginId) + id(libs.plugins.ktMpp.fatJar.get().pluginId) } val thisProject = project.name @@ -34,11 +34,3 @@ multiProjectHelper { } } } - -val supportedPlatforms by extra { listOf("win", "linux", "mac", "mac-aarch64") } - -shadowJar(classifier = "full") - -for (platform in supportedPlatforms) { - shadowJar(platform = platform, classifier = "full") -} diff --git a/full/gradle.properties b/full/gradle.properties index a9523d64c..2fa3b4e08 100644 --- a/full/gradle.properties +++ b/full/gradle.properties @@ -1,2 +1,5 @@ projectDescription=Umbrella package, depending on all 2P-Kt projectLongName=2P-Kt Full +fatJarPlatformNames=win;linux;mac +fatJarEntryPoint=org.example.MainKt +fatJarPlatformInclude=mac:linux diff --git a/gradle.properties b/gradle.properties index 73ee7a769..886fec7c8 100644 --- a/gradle.properties +++ b/gradle.properties @@ -28,7 +28,7 @@ signingKey= signingPassword= # semicolon separated -ktCompilerArgs=-opt-in=kotlin.js.ExperimentalJsExport;-opt-in=kotlin.time.ExperimentalTime +ktCompilerArgs=-opt-in=kotlin.js.ExperimentalJsExport;-opt-in=kotlin.time.ExperimentalTime;-Xexpect-actual-classes ktCompilerArgsJvm=-Xjvm-default=all ktCompilerArgsJs= # mocha timeout for a single test method, in milli-seconds diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 2e7811501..b75939462 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,9 +1,7 @@ [versions] -kotlin = "1.8.21" -dokka = "1.8.20" +kotlin = "1.9.22" jvm = "11" node = "16-latest" -npmPublish = "3.4.1" jackson = "2.16.1" orchid = "0.21.1" antlr = "4.13.1" @@ -12,10 +10,7 @@ javafx = "19.0.2.1" npm-yaml = "1.10.0" # yaml npm-tuprolog-parserUtils = "0.4.1" # @tuprolog/parser-utils npm-syncRequest = "6.1.0" # sync-request -ktlint = "10.3.0" -detekt = "1.22.0" -shadowJar = "8.0.0" -ktMpp = "2.1.3" +ktMpp = "4.1.0" [plugins] kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } @@ -30,15 +25,11 @@ ktMpp-jsOnly = { id = "io.github.gciatto.kt-mpp.js-only", version.ref = "ktMpp" ktMpp-jvmOnly = { id = "io.github.gciatto.kt-mpp.jvm-only", version.ref = "ktMpp" } ktMpp-multiplatform = { id = "io.github.gciatto.kt-mpp.multiplatform", version.ref = "ktMpp" } ktMpp-multiProjectHelper = { id = "io.github.gciatto.kt-mpp.multi-project-helper", version.ref = "ktMpp" } +ktMpp-fatJar = { id = "io.github.gciatto.kt-mpp.fat-jar", version.ref = "ktMpp" } gradleMockService = "io.github.gciatto.gradle-mock-service:1.0.7" -nexusPublish = "de.marcphilipp.nexus-publish:0.4.0" orchid = { id = "com.eden.orchidPlugin", version.ref = "orchid" } -shadowJar = { id = "com.github.johnrengelman.shadow", version.ref = "shadowJar" } [libraries] -kotlin-gradlePlugin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" } -ktNpmPublish = "io.github.gciatto:kt-npm-publish:0.3.9" -npmPublish = { module = "dev.petuska:npm-publish-gradle-plugin", version.ref = "npmPublish" } javafx-base = { module = "org.openjfx:javafx-base", version.ref = "javafx" } javafx-fxml = { module = "org.openjfx:javafx-fxml", version.ref = "javafx" } javafx-controls = { module = "org.openjfx:javafx-controls", version.ref = "javafx" } @@ -49,7 +40,7 @@ jackson-yaml = { module = "com.fasterxml.jackson.dataformat:jackson-dataformat-y jackson-jsr310 = { module = "com.fasterxml.jackson.datatype:jackson-datatype-jsr310", version.ref = "jackson" } clikt = "com.github.ajalt.clikt:clikt:3.5.4" graphviz = "guru.nidi:graphviz-java:0.18.1" -ktMath = "io.github.gciatto:kt-math:0.9.0" +ktMath = "io.github.gciatto:kt-math:0.10.0" orchid-docs = { module = "io.github.javaeden.orchid:OrchidDocs", version.ref = "orchid" } orchid-kotlinDocs = { module = "io.github.javaeden.orchid:OrchidKotlindoc", version.ref = "orchid" } orchid-pluginDocs = { module = "io.github.javaeden.orchid:OrchidPluginDocs", version.ref = "orchid" } @@ -59,9 +50,7 @@ antlr-runtime = { module = "org.antlr:antlr4-runtime", version.ref = "antlr" } richtextFx = "org.fxmisc.richtext:richtextfx:0.11.2" kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinx-coroutines" } kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinx-coroutines" } -kotlin-bom = { module = "org.jetbrains.kotlin:kotlin-bom", version.ref = "kotlin" } kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib", version.ref = "kotlin" } kotlin-stdlib-jvm = { module = "org.jetbrains.kotlin:kotlin-stdlib-jdk8", version.ref = "kotlin" } kotlin-stdlib-js = { module = "org.jetbrains.kotlin:kotlin-stdlib-js", version.ref = "kotlin" } kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin" } -shadowJar = { module = "gradle.plugin.com.github.johnrengelman:shadow", version.ref = "shadowJar" } diff --git a/ide-plp/build.gradle.kts b/ide-plp/build.gradle.kts index d8d7c9503..8543b8c3d 100644 --- a/ide-plp/build.gradle.kts +++ b/ide-plp/build.gradle.kts @@ -1,11 +1,13 @@ +import io.github.gciatto.kt.mpp.jar.javaFxFatJars + plugins { - id(libs.plugins.shadowJar.get().pluginId) id(libs.plugins.ktMpp.mavenPublish.get().pluginId) + id(libs.plugins.ktMpp.fatJar.get().pluginId) } -val arguments: String? by project - -val supportedPlatforms by extra { listOf("win", "linux", "mac", "mac-aarch64") } +multiPlatformHelper { + javaFxFatJars() +} dependencies { api(project(":ide")) @@ -14,22 +16,13 @@ dependencies { testImplementation(kotlin("test-junit")) } -val entryPoint = "it.unibo.tuprolog.ui.gui.PLPMain" - tasks.create("run") { group = "application" - mainClass.set(entryPoint) + mainClass.set(multiPlatformHelper.fatJarEntryPoint) dependsOn("jvmMainClasses") classpath = sourceSets.getByName("main").runtimeClasspath standardInput = System.`in` -} - -shadowJar(entryPoint) - -for (platform in supportedPlatforms) { - if ("mac" in platform) { - shadowJar(entryPoint, platform, excludedPlatforms = supportedPlatforms - setOf(platform, "linux")) - } else { - shadowJar(entryPoint, platform) + project.findProperty("arguments")?.let { + args = it.toString().split("\\s+".toRegex()).filterNot(String::isBlank) } } diff --git a/ide-plp/gradle.properties b/ide-plp/gradle.properties index 0a78285f5..682d0c46d 100644 --- a/ide-plp/gradle.properties +++ b/ide-plp/gradle.properties @@ -1,2 +1,3 @@ projectDescription=Customisable, JavaFX-based GUI for probabilistic logic solvers projectLongName=2P-Kt, Probabilistic Logic Programming IDE Module +fatJarEntryPoint=it.unibo.tuprolog.ui.gui.PLPMain diff --git a/ide-plp/src/main/kotlin/it/unibo/tuprolog/ui/gui/GraphRenderView.kt b/ide-plp/src/main/kotlin/it/unibo/tuprolog/ui/gui/GraphRenderView.kt index ed9149f05..4378f14c1 100644 --- a/ide-plp/src/main/kotlin/it/unibo/tuprolog/ui/gui/GraphRenderView.kt +++ b/ide-plp/src/main/kotlin/it/unibo/tuprolog/ui/gui/GraphRenderView.kt @@ -21,9 +21,8 @@ import java.io.IOException import java.util.concurrent.CompletableFuture class GraphRenderView( - private val dotGraph: String + private val dotGraph: String, ) : VBox() { - companion object { private const val FXML = "GraphRenderView.fxml" } @@ -51,13 +50,13 @@ class GraphRenderView( showMessage( "The image renderer is still initializing...\n" + "Close and reopen this panel in few seconds.", - true + true, ) } else if (!GraphvizRenderer.isAvailable) { showMessage( "The image renderer is not available.\n" + "Please check the docs at: https://github.com/nidi3/graphviz-java", - true + true, ) } else { showMessage("The image rendered is ready.", false) @@ -128,7 +127,7 @@ class GraphRenderView( fileChooser.title = "Save Image" fileChooser.extensionFilters.addAll( FileChooser.ExtensionFilter("PNG image file", "*.png"), - FileChooser.ExtensionFilter("All files", "*.*") + FileChooser.ExtensionFilter("All files", "*.*"), ) fileChooser.initialFileName = "bdd-${System.currentTimeMillis()}.png" val file = fileChooser.showSaveDialog(scene.window) @@ -139,7 +138,10 @@ class GraphRenderView( } } - private fun showMessage(text: String, error: Boolean) { + private fun showMessage( + text: String, + error: Boolean, + ) { labelMsg.text = text labelMsg.textFill = Color.color(if (error) 1.0 else 0.0, 0.0, 0.0) labelMsg.isVisible = true diff --git a/ide-plp/src/main/kotlin/it/unibo/tuprolog/ui/gui/GraphvizRenderer.kt b/ide-plp/src/main/kotlin/it/unibo/tuprolog/ui/gui/GraphvizRenderer.kt index 1365849c6..60f68daaa 100644 --- a/ide-plp/src/main/kotlin/it/unibo/tuprolog/ui/gui/GraphvizRenderer.kt +++ b/ide-plp/src/main/kotlin/it/unibo/tuprolog/ui/gui/GraphvizRenderer.kt @@ -12,31 +12,34 @@ import java.util.concurrent.CompletableFuture import java.util.concurrent.Future object GraphvizRenderer { - private var available: Future = CompletableFuture.completedFuture(false) @Suppress("TooGenericExceptionCaught", "SwallowedException") fun initialize() { - available = CompletableFuture.supplyAsync { - try { - val outputStream = ByteArrayOutputStream() - val sampleBDD = BinaryDecisionDiagram.terminalOf(true) - Graphviz - .fromString(sampleBDD.toDotString()) - .render(Format.PNG) - .toOutputStream(outputStream) - true - } catch (e: Exception) { - false + available = + CompletableFuture.supplyAsync { + try { + val outputStream = ByteArrayOutputStream() + val sampleBDD = BinaryDecisionDiagram.terminalOf(true) + Graphviz + .fromString(sampleBDD.toDotString()) + .render(Format.PNG) + .toOutputStream(outputStream) + true + } catch (e: Exception) { + false + } } - } } val isAvailable: Boolean get() = if (available.isDone) available.get() else false val isReady: Boolean get() = available.isDone - fun renderAsPNG(graph: String, imageOutputStream: OutputStream) { + fun renderAsPNG( + graph: String, + imageOutputStream: OutputStream, + ) { if (!isAvailable) { throw UnsupportedOperationException("Graphviz renderer is not available") } diff --git a/ide-plp/src/main/kotlin/it/unibo/tuprolog/ui/gui/PLPIDEApplication.kt b/ide-plp/src/main/kotlin/it/unibo/tuprolog/ui/gui/PLPIDEApplication.kt index 79d5d0861..f56329e8a 100644 --- a/ide-plp/src/main/kotlin/it/unibo/tuprolog/ui/gui/PLPIDEApplication.kt +++ b/ide-plp/src/main/kotlin/it/unibo/tuprolog/ui/gui/PLPIDEApplication.kt @@ -34,11 +34,12 @@ class PLPIDEApplication : Application() { TuPrologIDEBuilder( stage, title = "tuProlog IDE for Probabilistic Logic Programming", - customTabs = listOf( - CustomTab( - customSolutionsTab - ) { this.configureModel(it, solutionsListView, customSolutionsTab) } - ) + customTabs = + listOf( + CustomTab( + customSolutionsTab, + ) { this.configureModel(it, solutionsListView, customSolutionsTab) }, + ), ).show() } catch (e: Throwable) { e.printStackTrace() @@ -53,7 +54,7 @@ class PLPIDEApplication : Application() { private fun configureModel( model: TuPrologIDEModel, listView: ListView, - listTab: Tab + listTab: Tab, ) { // Hook events to the custom solutions tab model.onReset.subscribe { listView.items.clear() } @@ -76,7 +77,7 @@ class PLPIDEApplication : Application() { stdIn = it.standardInput, stdOut = it.standardOutput, stdErr = it.standardError, - warnings = it.warnings + warnings = it.warnings, ) } } diff --git a/ide-plp/src/main/kotlin/it/unibo/tuprolog/ui/gui/PLPSolutionView.kt b/ide-plp/src/main/kotlin/it/unibo/tuprolog/ui/gui/PLPSolutionView.kt index 3afc6f5bd..1914b8f1e 100644 --- a/ide-plp/src/main/kotlin/it/unibo/tuprolog/ui/gui/PLPSolutionView.kt +++ b/ide-plp/src/main/kotlin/it/unibo/tuprolog/ui/gui/PLPSolutionView.kt @@ -24,7 +24,6 @@ import javafx.scene.shape.Circle import java.io.IOException sealed class PLPSolutionView(private val solution: S) : VBox() { - companion object { private const val FXML = "PLPSolutionView.fxml" @@ -39,7 +38,7 @@ sealed class PLPSolutionView(private val solution: S) : VBox() solution.whenIs( yes = { YesViewPLP(it) }, no = { NoViewPLP(it) }, - halt = { HaltViewPLP(it) } + halt = { HaltViewPLP(it) }, ) } diff --git a/ide/build.gradle.kts b/ide/build.gradle.kts index dc68bd31c..95f542926 100644 --- a/ide/build.gradle.kts +++ b/ide/build.gradle.kts @@ -1,11 +1,14 @@ +import io.github.gciatto.kt.mpp.jar.javaFxFatJars + plugins { - id(libs.plugins.shadowJar.get().pluginId) id(libs.plugins.ktMpp.mavenPublish.get().pluginId) + id(libs.plugins.ktMpp.fatJar.get().pluginId) } -val arguments: String? by project - -val supportedPlatforms by extra { listOf("win", "linux", "mac", "mac-aarch64") } +multiPlatformHelper { + javaFxFatJars() + fatJarEntryPoint.set("it.unibo.tuprolog.ui.gui.Main") +} dependencies { api(project(":io-lib")) @@ -14,34 +17,26 @@ dependencies { api(project(":solve-classic")) api(libs.richtextFx) for (jfxModule in listOf(libs.javafx.base, libs.javafx.controls, libs.javafx.fxml, libs.javafx.graphics)) { - for (platform in supportedPlatforms) { - val dependency = jfxModule.get().let { - "${it.module.group}:${it.module.name}:${it.versionConstraint.requiredVersion}" - } + for (platform in multiPlatformHelper.fatJarPlatforms) { + val dependency = + jfxModule.get().let { + "${it.module.group}:${it.module.name}:${it.versionConstraint.requiredVersion}" + } api("$dependency:$platform") } } testImplementation(kotlin("test-junit")) } -val entryPoint = "it.unibo.tuprolog.ui.gui.Main" - tasks.create("run") { group = "application" - mainClass.set(entryPoint) + mainClass.set(multiPlatformHelper.fatJarEntryPoint) dependsOn("jvmMainClasses") sourceSets.getByName("main") { classpath = runtimeClasspath } standardInput = System.`in` -} - -shadowJar(entryPoint) - -for (platform in supportedPlatforms) { - if ("mac" in platform) { - shadowJar(entryPoint, platform, excludedPlatforms = supportedPlatforms - setOf(platform, "linux")) - } else { - shadowJar(entryPoint, platform) + project.findProperty("arguments")?.let { + args = it.toString().split("\\s+".toRegex()).filterNot(String::isBlank) } } diff --git a/ide/gradle.properties b/ide/gradle.properties index b265984dc..94aa89750 100644 --- a/ide/gradle.properties +++ b/ide/gradle.properties @@ -1,2 +1,3 @@ projectDescription=Customisable, JavaFX-based GUI for logic solvers projectLongName=2P-Kt, IDE Module +fatJarEntryPoint=it.unibo.tuprolog.ui.gui.Main diff --git a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/AssignmentView.kt b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/AssignmentView.kt index cd81cf335..6a1964ad6 100644 --- a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/AssignmentView.kt +++ b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/AssignmentView.kt @@ -14,9 +14,8 @@ import java.io.IOException class AssignmentView( variable: Var, value: Term, - formatter: TermFormatter = TermFormatter.prettyExpressions() + formatter: TermFormatter = TermFormatter.prettyExpressions(), ) : HBox() { - companion object { private const val FXML = "AssignmentView.fxml" } diff --git a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/FileTabView.kt b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/FileTabView.kt index 7bdca67bb..45edf34c3 100644 --- a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/FileTabView.kt +++ b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/FileTabView.kt @@ -19,9 +19,8 @@ class FileTabView( file: File, private val model: TuPrologIDEModel, private val ideController: TuPrologIDEController, - initialText: String = "" + initialText: String = "", ) : Tab() { - companion object { private const val FXML = "FileTabView.fxml" private const val MIN_FONT_SIZE = 13 diff --git a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/ListCellView.kt b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/ListCellView.kt index 961624ab1..58c4a2a7f 100644 --- a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/ListCellView.kt +++ b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/ListCellView.kt @@ -4,12 +4,16 @@ import javafx.scene.Node import javafx.scene.control.ListCell class ListCellView(private val viewGenerator: (T) -> Node) : ListCell() { - override fun updateItem(item: T?, empty: Boolean) { + override fun updateItem( + item: T?, + empty: Boolean, + ) { super.updateItem(item, empty) - graphic = if (empty || item == null) { - null - } else { - viewGenerator(item) - } + graphic = + if (empty || item == null) { + null + } else { + viewGenerator(item) + } } } diff --git a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/RegexExtensions.kt b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/RegexExtensions.kt index 9bb976ac8..d7d81c4f4 100644 --- a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/RegexExtensions.kt +++ b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/RegexExtensions.kt @@ -1,19 +1,14 @@ package it.unibo.tuprolog.ui.gui -infix fun Regex.or(other: Regex): Regex = - anyOf(this, other) +infix fun Regex.or(other: Regex): Regex = anyOf(this, other) -infix fun Regex.and(other: Regex): Regex = - Regex(pattern + other.pattern) +infix fun Regex.and(other: Regex): Regex = Regex(pattern + other.pattern) -fun anyOf(vararg regexps: Regex): Regex = - anyOf(sequenceOf(*regexps)) +fun anyOf(vararg regexps: Regex): Regex = anyOf(sequenceOf(*regexps)) -fun anyOf(regexps: Iterable): Regex = - anyOf(regexps.asSequence()) +fun anyOf(regexps: Iterable): Regex = anyOf(regexps.asSequence()) -fun anyOf(regexps: Sequence): Regex = - regexps.map { it.pattern }.joinToString("|").toRegex() +fun anyOf(regexps: Sequence): Regex = regexps.map { it.pattern }.joinToString("|").toRegex() fun Regex.asGroup(name: String? = null): Regex = if (name == null) { @@ -22,11 +17,8 @@ fun Regex.asGroup(name: String? = null): Regex = "(?<$name>$pattern)" }.toRegex() -fun wordOf(pattern: String): Regex = - wordify(pattern).toRegex() +fun wordOf(pattern: String): Regex = wordify(pattern).toRegex() -fun wordify(pattern: String): String = - "(^|\\b)($pattern)(\\b|$)" +fun wordify(pattern: String): String = "(^|\\b)($pattern)(\\b|$)" -fun Regex.asWord(): Regex = - wordOf(pattern) +fun Regex.asWord(): Regex = wordOf(pattern) diff --git a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/SolutionView.kt b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/SolutionView.kt index e0f3edfa3..a8827b14d 100644 --- a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/SolutionView.kt +++ b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/SolutionView.kt @@ -17,7 +17,6 @@ import javafx.scene.shape.Circle import java.io.IOException sealed class SolutionView(protected val solution: S) : VBox() { - companion object { private const val FXML = "SolutionView.fxml" @@ -32,7 +31,7 @@ sealed class SolutionView(protected val solution: S) : VBox() { solution.whenIs( yes = { YesView(it) }, no = { NoView(it) }, - halt = { HaltView(it) } + halt = { HaltView(it) }, ) } diff --git a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/SolverEvent.kt b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/SolverEvent.kt index ff6b23b77..8624fd898 100644 --- a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/SolverEvent.kt +++ b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/SolverEvent.kt @@ -18,7 +18,7 @@ data class SolverEvent( override val staticKb: Theory, override val dynamicKb: Theory, override val inputChannels: InputStore, - override val outputChannels: OutputStore + override val outputChannels: OutputStore, ) : ExecutionContextAware { constructor(event: T, other: ExecutionContextAware) : this( @@ -30,6 +30,6 @@ data class SolverEvent( libraries = other.libraries, operators = other.operators, outputChannels = other.outputChannels, - staticKb = other.staticKb.toImmutableTheory() + staticKb = other.staticKb.toImmutableTheory(), ) } diff --git a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/SyntaxColoring.kt b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/SyntaxColoring.kt index 5043f1167..a32d82d58 100644 --- a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/SyntaxColoring.kt +++ b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/SyntaxColoring.kt @@ -17,9 +17,8 @@ class SyntaxColoring( private val codeArea: CodeArea, delay: Duration = DEFAULT_UPDATE_DELAY, operators: OperatorSet = OperatorSet.DEFAULT, - private val executor: ExecutorService = ForkJoinPool.commonPool() + private val executor: ExecutorService = ForkJoinPool.commonPool(), ) { - @Volatile var delay: Duration = delay @Synchronized get @@ -42,11 +41,12 @@ class SyntaxColoring( } private fun computeHighlightingAsync(): Task>> { - val task: Task>> = object : Task>>() { - override fun call(): StyleSpans> { - return computeHighlighting(codeArea.text) + val task: Task>> = + object : Task>>() { + override fun call(): StyleSpans> { + return computeHighlighting(codeArea.text) + } } - } executor.execute(task) return task } @@ -70,21 +70,22 @@ class SyntaxColoring( @Synchronized fun activate() { if (subscription == null) { - subscription = codeArea.multiPlainChanges() - .successionEnds(delay) - .supplyTask { computeHighlightingAsync() } - .awaitLatest(codeArea.multiPlainChanges()) - .filterMap { - when { - it.isSuccess -> { - Optional.of(it.get()) + subscription = + codeArea.multiPlainChanges() + .successionEnds(delay) + .supplyTask { computeHighlightingAsync() } + .awaitLatest(codeArea.multiPlainChanges()) + .filterMap { + when { + it.isSuccess -> { + Optional.of(it.get()) + } + else -> { + it.failure.printStackTrace() + Optional.empty() + } } - else -> { - it.failure.printStackTrace() - Optional.empty() - } - } - }.subscribe { applyHighlighting(it) } + }.subscribe { applyHighlighting(it) } } else { error("Syntax coloring is already active") } @@ -102,9 +103,10 @@ class SyntaxColoring( } } - private val patternCache: Cached = Cached.of { - pattern(this.operators) - } + private val patternCache: Cached = + Cached.of { + pattern(this.operators) + } private fun computeHighlighting(text: String): StyleSpans> { val matches = patternCache.value.findAll(text) @@ -127,7 +129,6 @@ class SyntaxColoring( } companion object { - private val DEFAULT_UPDATE_DELAY = Duration.ofMillis(100) private fun keywords(operators: OperatorSet): Regex = @@ -184,14 +185,15 @@ class SyntaxColoring( private val CHAR_PATTERN = Regex("0'(\\\\[abfnrtv'`\"]|.)") - private val NUMBER_PATTERN = anyOf( - FLOAT_PATTERN, - INTEGER_PATTERN, - HEX_PATTERN, - BIN_PATTERN, - OCT_PATTERN, - CHAR_PATTERN - ).asWord() + private val NUMBER_PATTERN = + anyOf( + FLOAT_PATTERN, + INTEGER_PATTERN, + HEX_PATTERN, + BIN_PATTERN, + OCT_PATTERN, + CHAR_PATTERN, + ).asWord() private const val KEYWORD = "KEYWORD" private const val PAREN = "PAREN" @@ -205,34 +207,36 @@ class SyntaxColoring( private const val ATOM = "ATOM" private const val FULLSTOP = "FULLSTOP" - private fun pattern(operators: OperatorSet) = anyOf( - COMMENT_PATTERN.asGroup(COMMENT), - keywords(operators).asGroup(KEYWORD), - PAREN_PATTERN.asGroup(PAREN), - BRACE_PATTERN.asGroup(BRACE), - BRACKET_PATTERN.asGroup(BRACKET), - FUNCTOR_PATTERN.asGroup(FUNCTOR), - ATOM_PATTERN.asGroup(ATOM), - VARIABLE_PATTERN.asGroup(VARIABLE), - NUMBER_PATTERN.asGroup(NUMBER), - STRING_PATTERN.asGroup(STRING), - FULLSTOP_PATTERN.asGroup(FULLSTOP) - ) + private fun pattern(operators: OperatorSet) = + anyOf( + COMMENT_PATTERN.asGroup(COMMENT), + keywords(operators).asGroup(KEYWORD), + PAREN_PATTERN.asGroup(PAREN), + BRACE_PATTERN.asGroup(BRACE), + BRACKET_PATTERN.asGroup(BRACKET), + FUNCTOR_PATTERN.asGroup(FUNCTOR), + ATOM_PATTERN.asGroup(ATOM), + VARIABLE_PATTERN.asGroup(VARIABLE), + NUMBER_PATTERN.asGroup(NUMBER), + STRING_PATTERN.asGroup(STRING), + FULLSTOP_PATTERN.asGroup(FULLSTOP), + ) private val MatchResult.styleClass: String - get() = when { - groups[KEYWORD] != null -> KEYWORD.lowercase() - groups[PAREN] != null -> PAREN.lowercase() - groups[NUMBER] != null -> NUMBER.lowercase() - groups[BRACE] != null -> BRACE.lowercase() - groups[BRACKET] != null -> BRACKET.lowercase() - groups[STRING] != null -> STRING.lowercase() - groups[COMMENT] != null -> COMMENT.lowercase() - groups[VARIABLE] != null -> VARIABLE.lowercase() - groups[ATOM] != null -> ATOM.lowercase() - groups[FUNCTOR] != null -> FUNCTOR.lowercase() - groups[FULLSTOP] != null -> FULLSTOP.lowercase() - else -> "" - } + get() = + when { + groups[KEYWORD] != null -> KEYWORD.lowercase() + groups[PAREN] != null -> PAREN.lowercase() + groups[NUMBER] != null -> NUMBER.lowercase() + groups[BRACE] != null -> BRACE.lowercase() + groups[BRACKET] != null -> BRACKET.lowercase() + groups[STRING] != null -> STRING.lowercase() + groups[COMMENT] != null -> COMMENT.lowercase() + groups[VARIABLE] != null -> VARIABLE.lowercase() + groups[ATOM] != null -> ATOM.lowercase() + groups[FUNCTOR] != null -> FUNCTOR.lowercase() + groups[FULLSTOP] != null -> FULLSTOP.lowercase() + else -> "" + } } } diff --git a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/SyntaxException.kt b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/SyntaxException.kt index 1caefd0fc..9e3cd37be 100644 --- a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/SyntaxException.kt +++ b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/SyntaxException.kt @@ -9,17 +9,18 @@ internal sealed class SyntaxException(override val cause: ParseException) : TuPr class InTheorySyntaxError(val file: File, cause: ParseException) : SyntaxException(cause) { override val message: String get() { - val errorDetector = SyntaxError.errorDetector( - cause.input?.toString() ?: file.readText(), - cause.line, - cause.column, - cause.message - ) + val errorDetector = + SyntaxError.errorDetector( + cause.input?.toString() ?: file.readText(), + cause.line, + cause.column, + cause.message, + ) return """ |Syntax error at ${cause.line}:${cause.column} of ${file.name}, while parsing clause ${cause.clauseIndex} | | ${errorDetector.replace("\n", "\n| ")} - """.trimMargin() + """.trimMargin() } } @@ -34,7 +35,7 @@ internal sealed class SyntaxException(override val cause: ParseException) : TuPr |Syntax error in query, near column ${cause.column} | | ${errorDetector.replace("\n", "\n| ")} - """.trimMargin() + """.trimMargin() } } diff --git a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/TuPrologIDEBuilder.kt b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/TuPrologIDEBuilder.kt index 118f61e67..201a07751 100644 --- a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/TuPrologIDEBuilder.kt +++ b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/TuPrologIDEBuilder.kt @@ -27,14 +27,17 @@ data class TuPrologIDEBuilder( var onAbout: () -> Unit = { showAboutDialog(title, Info.VERSION) }, var stylesheets: List = listOf(JAVA_KEYWORDS_LIGHT, LIGHT_CODE_AREA), var customLibraries: List = emptyList(), - var customTabs: List = emptyList() + var customTabs: List = emptyList(), ) { - companion object { private const val DEFAULT_ICON_SCALE_RATIO: Double = 0.3 @JvmStatic - fun showConfirmationDialog(title: String, header: String, content: String): Boolean = + fun showConfirmationDialog( + title: String, + header: String, + content: String, + ): Boolean = Alert(Alert.AlertType.CONFIRMATION).also { it.title = title it.headerText = header @@ -46,7 +49,7 @@ data class TuPrologIDEBuilder( showConfirmationDialog( "Close $what", "Confirmation", - "Do you really want close the $what?" + "Do you really want close the $what?", ) @JvmStatic @@ -55,22 +58,24 @@ data class TuPrologIDEBuilder( version: String = Info.VERSION, image: Image = TUPROLOG_LOGO, width: Double = TUPROLOG_LOGO.width * DEFAULT_ICON_SCALE_RATIO, - height: Double = TUPROLOG_LOGO.height * DEFAULT_ICON_SCALE_RATIO - ): Optional = Alert(Alert.AlertType.INFORMATION).also { - it.title = "About" - it.headerText = "$what v$version" - it.dialogPane.graphic = ImageView(image).also { img -> - img.fitWidth = width - img.fitHeight = height - } - it.contentText = - """ + height: Double = TUPROLOG_LOGO.height * DEFAULT_ICON_SCALE_RATIO, + ): Optional = + Alert(Alert.AlertType.INFORMATION).also { + it.title = "About" + it.headerText = "$what v$version" + it.dialogPane.graphic = + ImageView(image).also { img -> + img.fitWidth = width + img.fitHeight = height + } + it.contentText = + """ |Running on: | - 2P-Kt v${Info.VERSION} | - JVM v${System.getProperty("java.version")} | - JavaFX v${System.getProperty("javafx.runtime.version")} - """.trimMargin() - }.showAndWait() + """.trimMargin() + }.showAndWait() } fun title(title: String) = apply { this.title = title } @@ -85,24 +90,23 @@ data class TuPrologIDEBuilder( fun stylesheet(stylesheet: String) = apply { this.stylesheets += stylesheet } - fun customLibraries(customLibraries: Iterable) = - apply { this.customLibraries = customLibraries.toList() } + fun customLibraries(customLibraries: Iterable) = apply { this.customLibraries = customLibraries.toList() } - fun customLibrary(customLibrary: Library) = - apply { this.customLibraries += customLibrary } + fun customLibrary(customLibrary: Library) = apply { this.customLibraries += customLibrary } - fun customTabs(customTabs: Iterable) = - apply { this.customTabs = customTabs.toList() } + fun customTabs(customTabs: Iterable) = apply { this.customTabs = customTabs.toList() } - fun customTab(customTab: CustomTab) = - apply { this.customTabs += customTab } + fun customTab(customTab: CustomTab) = apply { this.customTabs += customTab } - fun customTab(tab: Tab, modelConfigurator: ModelConfigurator) = - customTab(CustomTab(tab, modelConfigurator)) + fun customTab( + tab: Tab, + modelConfigurator: ModelConfigurator, + ) = customTab(CustomTab(tab, modelConfigurator)) - fun customTab(tab: Tab) = customTab(tab) { - /* do nothing */ - } + fun customTab(tab: Tab) = + customTab(tab) { + // do nothing + } fun show() { val loader = FXMLLoader(javaClass.getResource("TuPrologIDEView.fxml")) diff --git a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/TuPrologIDEController.kt b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/TuPrologIDEController.kt index ebc822e84..e62e94951 100644 --- a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/TuPrologIDEController.kt +++ b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/TuPrologIDEController.kt @@ -50,9 +50,8 @@ import kotlin.math.pow import kotlin.math.round import kotlin.system.exitProcess -@Suppress("UNUSED_PARAMETER", "unused", "VarCouldBeVal", "TooManyFunctions") +@Suppress("UNUSED_PARAMETER", "unused", "VarCouldBeVal", "TooManyFunctions", "LargeClass") class TuPrologIDEController : Initializable { - companion object { private const val DAYS_PER_YEAR = 365 } @@ -244,12 +243,14 @@ class TuPrologIDEController : Initializable { private val currentFileTab: FileTabView? get() = model.currentFile?.let { tabForFile(it) } - private fun tabForFile(file: File): FileTabView? = - fileTabs.firstOrNull { it.file == file } + private fun tabForFile(file: File): FileTabView? = fileTabs.firstOrNull { it.file == file } @Suppress("NoNameShadowing") @FXML - override fun initialize(location: URL, resources: ResourceBundle?) { + override fun initialize( + location: URL, + resources: ResourceBundle?, + ) { model.onResolutionStarted.subscribe(this::onResolutionStarted) model.onResolutionOver.subscribe(this::onResolutionOver) model.onNewQuery.subscribe(this::onNewQuery) @@ -305,9 +306,10 @@ class TuPrologIDEController : Initializable { } private fun onTimeoutSliderMoved(value: Number) { - model.solveOptions = model.solveOptions.setTimeout( - round(10.0.pow(value.toDouble())).toLong() - ) + model.solveOptions = + model.solveOptions.setTimeout( + round(10.0.pow(value.toDouble())).toLong(), + ) } private fun onSolveOptionsChanged(newSolveOptions: SolveOptions) { @@ -332,41 +334,45 @@ class TuPrologIDEController : Initializable { hours.pretty("h"), minutes.pretty("m"), seconds.pretty("s"), - milliseconds.pretty("ms") + milliseconds.pretty("ms"), ).filterNotNull().joinToString() } - private fun Long.pretty(unit: String): String? = - if (this == 0L) null else "$this$unit" + private fun Long.pretty(unit: String): String? = if (this == 0L) null else "$this$unit" private fun Int.pretty(unit: String): String? = toLong().pretty(unit) - private fun onNewSolver(e: SolverEvent) = onUiThread { - updateContextSensitiveView(e) - } + private fun onNewSolver(e: SolverEvent) = + onUiThread { + updateContextSensitiveView(e) + } - private fun onNewStaticKb(e: SolverEvent) = onUiThread { - updateContextSensitiveView(e) - } + private fun onNewStaticKb(e: SolverEvent) = + onUiThread { + updateContextSensitiveView(e) + } - private fun onFileLoaded(e: Pair) = onUiThread { - tabsFiles.tabs.add(FileTabView(e.first, model, this, e.second)) - handleSomeOpenFiles() - } + private fun onFileLoaded(e: Pair) = + onUiThread { + tabsFiles.tabs.add(FileTabView(e.first, model, this, e.second)) + handleSomeOpenFiles() + } - private fun onFileClosed(e: File) = onUiThread { - fileTabs.firstOrNull { it.file == e }?.let { - tabsFiles.tabs -= it - handleNoMoreOpenFiles() + private fun onFileClosed(e: File) = + onUiThread { + fileTabs.firstOrNull { it.file == e }?.let { + tabsFiles.tabs -= it + handleNoMoreOpenFiles() + } } - } - private fun onFileSelected(e: File) = onUiThread { - fileTabs.firstOrNull { it.file == e }?.let { - it.updateSyntaxColoring() - tabsFiles.selectionModel.select(it) + private fun onFileSelected(e: File) = + onUiThread { + fileTabs.firstOrNull { it.file == e }?.let { + it.updateSyntaxColoring() + tabsFiles.selectionModel.select(it) + } } - } private fun handleNoMoreOpenFiles() { if (fileTabs.none()) { @@ -387,10 +393,11 @@ class TuPrologIDEController : Initializable { } } - private fun onStdoutPrinted(output: String) = onUiThread { - txaStdout.text += output - tabStdout.showNotification() - } + private fun onStdoutPrinted(output: String) = + onUiThread { + txaStdout.text += output + tabStdout.showNotification() + } private fun Tab.showNotification() { if (!isSelected && !text.endsWith("*")) { @@ -447,102 +454,114 @@ class TuPrologIDEController : Initializable { lastEvent = event } - private fun updatingContextSensitiveView(event: SolverEvent<*>, action: () -> Unit) { + private fun updatingContextSensitiveView( + event: SolverEvent<*>, + action: () -> Unit, + ) { action() updateContextSensitiveView(event) } - private fun onStderrPrinted(output: String) = onUiThread { - txaStderr.text += output - tabStderr.showNotification() - } + private fun onStderrPrinted(output: String) = + onUiThread { + txaStderr.text += output + tabStderr.showNotification() + } - private fun onWarning(warning: Warning) = onUiThread { - lsvWarnings.items.add(warning) - lsvWarnings.scrollTo(warning) - tabWarnings.showNotification() - } + private fun onWarning(warning: Warning) = + onUiThread { + lsvWarnings.items.add(warning) + lsvWarnings.scrollTo(warning) + tabWarnings.showNotification() + } - private fun onError(exception: Exception) = onUiThread { - val dialog = Alert(Alert.AlertType.ERROR) - dialog.title = exception::class.java.simpleName - when (exception) { - is SyntaxException.InTheorySyntaxError -> { - dialog.headerText = "Syntax error in ${exception.file.name}" - dialog.dialogPane.content = exception.message.toMonospacedText() - } - is SyntaxException.InQuerySyntaxError -> { - dialog.headerText = "Syntax error in query" - dialog.dialogPane.content = exception.message.toMonospacedText() - } - else -> { - dialog.headerText = "Error" - dialog.dialogPane.content = exception.message?.replaceFirstChar { - if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() - }?.toMonospacedText() + private fun onError(exception: Exception) = + onUiThread { + val dialog = Alert(Alert.AlertType.ERROR) + dialog.title = exception::class.java.simpleName + when (exception) { + is SyntaxException.InTheorySyntaxError -> { + dialog.headerText = "Syntax error in ${exception.file.name}" + dialog.dialogPane.content = exception.message.toMonospacedText() + } + is SyntaxException.InQuerySyntaxError -> { + dialog.headerText = "Syntax error in query" + dialog.dialogPane.content = exception.message.toMonospacedText() + } + else -> { + dialog.headerText = "Error" + dialog.dialogPane.content = + exception.message?.replaceFirstChar { + if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() + }?.toMonospacedText() + } } + dialog.dialogPane.minHeight = Region.USE_PREF_SIZE + dialog.dialogPane.minWidth = Region.USE_PREF_SIZE + dialog.showAndWait() } - dialog.dialogPane.minHeight = Region.USE_PREF_SIZE - dialog.dialogPane.minWidth = Region.USE_PREF_SIZE - dialog.showAndWait() - } private fun String?.toMonospacedText(): Node { if (this == null) return Text() return Text(this).also { it.style = "-fx-font-family: monospaced" } } - private fun onNewSolution(e: SolverEvent) = onUiThread { - updatingContextSensitiveView(e) { - lsvSolutions.items.add(e.event) - lsvSolutions.scrollTo(e.event) - tabSolutions.showNotification() + private fun onNewSolution(e: SolverEvent) = + onUiThread { + updatingContextSensitiveView(e) { + lsvSolutions.items.add(e.event) + lsvSolutions.scrollTo(e.event) + tabSolutions.showNotification() + } } - } - private fun onNewQuery(e: SolverEvent) = onUiThread { - updatingContextSensitiveView(e) { - cleanUpAfterResolution() - btnStop.isDisable = false - txaStdin.isDisable = true - btnNext.text = "Next" - btnNextAll.text = "All next" + private fun onNewQuery(e: SolverEvent) = + onUiThread { + updatingContextSensitiveView(e) { + cleanUpAfterResolution() + btnStop.isDisable = false + txaStdin.isDisable = true + btnNext.text = "Next" + btnNextAll.text = "All next" + } } - } - private fun onQueryOver(e: SolverEvent) = onUiThread { - updatingContextSensitiveView(e) { - lblStatus.text = "Idle" - btnStop.isDisable = true - txaStdin.isDisable = false - btnNext.text = "Solve" - btnNextAll.text = "Solve all" + private fun onQueryOver(e: SolverEvent) = + onUiThread { + updatingContextSensitiveView(e) { + lblStatus.text = "Idle" + btnStop.isDisable = true + txaStdin.isDisable = false + btnNext.text = "Solve" + btnNextAll.text = "Solve all" + } } - } - private fun onResolutionStarted(e: SolverEvent) = onUiThread { - updatingContextSensitiveView(e) { - btnNext.isDisable = true - btnNextAll.isDisable = true - btnStop.isDisable = true - btnReset.isDisable = true - prbResolution.isVisible = true - txfQuery.isDisable = true - lblStatus.text = "Solving..." + private fun onResolutionStarted(e: SolverEvent) = + onUiThread { + updatingContextSensitiveView(e) { + btnNext.isDisable = true + btnNextAll.isDisable = true + btnStop.isDisable = true + btnReset.isDisable = true + prbResolution.isVisible = true + txfQuery.isDisable = true + lblStatus.text = "Solving..." + } } - } - private fun onResolutionOver(e: SolverEvent) = onUiThread { - updatingContextSensitiveView(e) { - btnNext.isDisable = false - btnNextAll.isDisable = false - prbResolution.isVisible = false - btnStop.isDisable = false - btnReset.isDisable = false - txfQuery.isDisable = false - lblStatus.text = "Solution ${e.event}" + private fun onResolutionOver(e: SolverEvent) = + onUiThread { + updatingContextSensitiveView(e) { + btnNext.isDisable = false + btnNextAll.isDisable = false + prbResolution.isVisible = false + btnStop.isDisable = false + btnReset.isDisable = false + txfQuery.isDisable = false + lblStatus.text = "Solution ${e.event}" + } } - } @FXML fun onKeyTypedOnCurrentFile(e: KeyEvent) { @@ -665,7 +684,7 @@ class TuPrologIDEController : Initializable { fileChooser.extensionFilters.addAll( FileChooser.ExtensionFilter("Prolog file", "*.pl", "*.2p"), FileChooser.ExtensionFilter("Text file", "*.txt"), - FileChooser.ExtensionFilter("Any file", "*") + FileChooser.ExtensionFilter("Any file", "*"), ) fileChooser.initialDirectory = File(System.getProperty("user.home")) fileChooser.title = "Open file..." @@ -704,7 +723,7 @@ class TuPrologIDEController : Initializable { fileChooser.extensionFilters.addAll( FileChooser.ExtensionFilter("Prolog file", "*.pl"), FileChooser.ExtensionFilter("Text file", "*.txt"), - FileChooser.ExtensionFilter("2P file", "*.2p") + FileChooser.ExtensionFilter("2P file", "*.2p"), ) fileChooser.initialDirectory = File(System.getProperty("user.home")) fileChooser.title = "Save file as..." diff --git a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/TuPrologIDEModel.kt b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/TuPrologIDEModel.kt index f357f2212..9de666f0f 100644 --- a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/TuPrologIDEModel.kt +++ b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/TuPrologIDEModel.kt @@ -13,13 +13,14 @@ import java.util.concurrent.ForkJoinPool @Suppress("TooManyFunctions") interface TuPrologIDEModel { - companion object { fun of(executor: ExecutorService = ForkJoinPool.commonPool()): TuPrologIDEModel = TuPrologIDEModelImpl(executor) } enum class State { - IDLE, COMPUTING, SOLUTION + IDLE, + COMPUTING, + SOLUTION, } var solveOptions: SolveOptions @@ -44,9 +45,15 @@ interface TuPrologIDEModel { fun getFile(file: File): String - fun setFile(file: File, theory: String) + fun setFile( + file: File, + theory: String, + ) - fun renameFile(file: File, newFile: File) + fun renameFile( + file: File, + newFile: File, + ) fun setCurrentFile(theory: String) diff --git a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/TuPrologIDEModelImpl.kt b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/TuPrologIDEModelImpl.kt index 28555b253..54f375aa2 100644 --- a/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/TuPrologIDEModelImpl.kt +++ b/ide/src/main/kotlin/it/unibo/tuprolog/ui/gui/TuPrologIDEModelImpl.kt @@ -28,9 +28,8 @@ import java.util.concurrent.ExecutorService @Suppress("UnsafeCallOnNullableType", "TooManyFunctions") internal class TuPrologIDEModelImpl( override val executor: ExecutorService, - var customizer: ((MutableSolver) -> MutableSolver)? = { it } + var customizer: ((MutableSolver) -> MutableSolver)? = { it }, ) : TuPrologIDEModel { - companion object { const val DEFAULT_TIMEOUT: Long = 5000 } @@ -101,7 +100,10 @@ internal class TuPrologIDEModelImpl( return files[file]!!.text } - override fun setFile(file: File, theory: String) { + override fun setFile( + file: File, + theory: String, + ) { if (file in files) { files[file]?.text(theory) } else { @@ -109,7 +111,10 @@ internal class TuPrologIDEModelImpl( } } - override fun renameFile(file: File, newFile: File) { + override fun renameFile( + file: File, + newFile: File, + ) { files[newFile] = files[file]!! files -= file } @@ -140,7 +145,11 @@ internal class TuPrologIDEModelImpl( this.solver.regenerate() } - private inline fun ensuringStateIs(state: State, vararg states: State, action: () -> T): T { + private inline fun ensuringStateIs( + state: State, + vararg states: State, + action: () -> T, + ): T { val admissibleStates = EnumSet.of(state, *states) if (this.state in admissibleStates) { return action() @@ -149,22 +158,24 @@ internal class TuPrologIDEModelImpl( } } - private val solver = Cached.of { - var newSolver = Solver.prolog.newBuilder() - .runtime(Runtime.of(OOPLib, IOLib)) - .flag(TrackVariables) { ON } - .standardInput(InputChannel.of(stdin)) - .standardOutput(OutputChannel.of { onStdoutPrinted.push(it) }) - .standardError(OutputChannel.of { onStderrPrinted.push(it) }) - .warnings(OutputChannel.of { onWarning.push(it) }) - .buildMutable() - if (this.customizer != null) { - newSolver = this.customizer!!(newSolver) - } - newSolver.also { - onNewSolver.push(SolverEvent(Unit, it)) + private val solver = + Cached.of { + var newSolver = + Solver.prolog.newBuilder() + .runtime(Runtime.of(OOPLib, IOLib)) + .flag(TrackVariables) { ON } + .standardInput(InputChannel.of(stdin)) + .standardOutput(OutputChannel.of { onStdoutPrinted.push(it) }) + .standardError(OutputChannel.of { onStderrPrinted.push(it) }) + .warnings(OutputChannel.of { onWarning.push(it) }) + .buildMutable() + if (this.customizer != null) { + newSolver = this.customizer!!(newSolver) + } + newSolver.also { + onNewSolver.push(SolverEvent(Unit, it)) + } } - } override fun closeFile(file: File) { files -= file @@ -241,14 +252,15 @@ internal class TuPrologIDEModelImpl( solver: MutableSolver, file: File, content: FileContent?, - onlyIfChanged: Boolean + onlyIfChanged: Boolean, ) { if (onlyIfChanged && content?.changed == true) { return } try { - val theory = content?.text()?.parseAsTheory(solver.operators) - ?: Theory.empty(solver.unificator) + val theory = + content?.text()?.parseAsTheory(solver.operators) + ?: Theory.empty(solver.unificator) solver.resetDynamicKb() solver.loadStaticKb(theory) onNewStaticKb.push(SolverEvent(Unit, solver)) @@ -264,12 +276,13 @@ internal class TuPrologIDEModelImpl( val sol = solutions!!.next() onResolutionOver.push(SolverEvent(solutionCount, solver.value)) onNewSolution.push(SolverEvent(sol, solver.value)) - state = if (!sol.isYes || !solutions!!.hasNext()) { - onQueryOver.push(SolverEvent(sol.query, solver.value)) - State.IDLE - } else { - State.SOLUTION - } + state = + if (!sol.isYes || !solutions!!.hasNext()) { + onQueryOver.push(SolverEvent(sol.query, solver.value)) + State.IDLE + } else { + State.SOLUTION + } } } diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/IOLib.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/IOLib.kt index add666802..b4a68d0e9 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/IOLib.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/IOLib.kt @@ -56,52 +56,53 @@ object IOLib : AbstractLibrary() { get() = "prolog.io" override val primitives: Map - get() = listOf( - AtEndOfStream0, - AtEndOfStream1, - CharConversion, - Close1, - Close2, - Consult, - CurrentCharConversion, - CurrentInput, - CurrentOutput, - FlushOutput, - GetByte1, - GetByte2, - GetChar1, - GetChar2, - GetCode1, - GetCode2, - Nl1, - Open3, - Open4, - PeekByte1, - PeekByte2, - PeekChar1, - PeekChar2, - PeekCode1, - PeekCode2, - PutByte1, - PutByte2, - PutChar1, - PutChar2, - PutCode1, - PutCode2, - Read1, - Read2, - ReadTerm2, - ReadTerm3, - SetInput, - SetOutput, - SetTheory, - StreamProperty, - Write2, - WriteCanonical1, - WriteCanonical2, - WriteEq1, - WriteEq2, - WriteTerm2, - WriteTerm3 - ).map { it.descriptionPair }.toMapEnsuringNoDuplicates() + get() = + listOf( + AtEndOfStream0, + AtEndOfStream1, + CharConversion, + Close1, + Close2, + Consult, + CurrentCharConversion, + CurrentInput, + CurrentOutput, + FlushOutput, + GetByte1, + GetByte2, + GetChar1, + GetChar2, + GetCode1, + GetCode2, + Nl1, + Open3, + Open4, + PeekByte1, + PeekByte2, + PeekChar1, + PeekChar2, + PeekCode1, + PeekCode2, + PutByte1, + PutByte2, + PutChar1, + PutChar2, + PutCode1, + PutCode2, + Read1, + Read2, + ReadTerm2, + ReadTerm3, + SetInput, + SetOutput, + SetTheory, + StreamProperty, + Write2, + WriteCanonical1, + WriteCanonical2, + WriteEq1, + WriteEq2, + WriteTerm2, + WriteTerm3, + ).map { it.descriptionPair }.toMapEnsuringNoDuplicates() } diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/IOMode.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/IOMode.kt index b431d9497..89784199a 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/IOMode.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/IOMode.kt @@ -3,7 +3,10 @@ package it.unibo.tuprolog.solve.libs.io import it.unibo.tuprolog.core.Atom enum class IOMode { - READ, WRITE, APPEND; + READ, + WRITE, + APPEND, + ; companion object { val atomValues = values().asSequence().map { it.name.lowercase() }.map(Atom.Companion::of).toSet() diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/Url.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/Url.kt index 411afbcc8..46a322103 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/Url.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/Url.kt @@ -27,8 +27,7 @@ interface Url { fun readAsByteArray(): ByteArray @JsName("resolve") - fun resolve(child: String): Url = - remote(protocol, host, port, "$path/$child", query) + fun resolve(child: String): Url = remote(protocol, host, port, "$path/$child", query) @JsName("div") operator fun div(child: String): Url = resolve(child) @@ -42,16 +41,30 @@ interface Url { get() = protocol.startsWith("http") companion object { - private fun T?.str(transformation: (T) -> String = { it.toString() }): String = if (this == null) "" else transformation(this) internal fun Int.ensureValidPort(): Int = - if (this < 0) throw IllegalArgumentException("Invalid port: $this") else this + if (this < 0) { + throw IllegalArgumentException( + "Invalid port: $this", + ) + } else { + this + } internal enum class UrlField { PROTOCOL, UNIT, HOST, PORT, PATH, QUERY, ANCHOR } - private fun urlRegex(protocol: String? = null, unit: String? = null, host: String? = null, port: String? = null, path: String? = null, query: String? = null, anchor: String? = null): Regex { + @Suppress("ktlint:standard:max-line-length") + private fun urlRegex( + protocol: String? = null, + unit: String? = null, + host: String? = null, + port: String? = null, + path: String? = null, + query: String? = null, + anchor: String? = null, + ): Regex { val protocolGroup = """(${protocol.str { "?<$it>" }}[\w]+)""" val unitGroup = @@ -84,37 +97,55 @@ interface Url { @JvmStatic @JsName("file") - fun file(path: String): Url = - fileUrl(path) + fun file(path: String): Url = fileUrl(path) @JvmStatic @JsName("remote") - fun remote(protocol: String, host: String = "", port: Int? = null, path: String = "", query: String? = null): Url = - remoteUrl(protocol, host, port, path, query) + fun remote( + protocol: String, + host: String = "", + port: Int? = null, + path: String = "", + query: String? = null, + ): Url = remoteUrl(protocol, host, port, path, query) @JvmStatic @JsName("http") - fun http(host: String = "", port: Int? = null, path: String = "", query: String? = null): Url = - remote("http", host, port, path, query) + fun http( + host: String = "", + port: Int? = null, + path: String = "", + query: String? = null, + ): Url = remote("http", host, port, path, query) @JvmStatic @JsName("https") - fun https(host: String = "", port: Int? = null, path: String = "", query: String? = null): Url = - remote("https", host, port, path, query) + fun https( + host: String = "", + port: Int? = null, + path: String = "", + query: String? = null, + ): Url = remote("https", host, port, path, query) @JvmStatic @JsName("of") - fun of(string: String): Url = try { - parseUrl(string) - } catch (e: InvalidUrlException) { + fun of(string: String): Url = try { - parseUrl("file://$string") - } catch (_: InvalidUrlException) { - throw e + parseUrl(string) + } catch (e: InvalidUrlException) { + try { + parseUrl("file://$string") + } catch (_: InvalidUrlException) { + throw e + } } - } - internal fun toString(protocol: String, host: String = "", port: Int? = null, path: String = "", query: String? = null): String = - "$protocol://$host${port?.ensureValidPort().str { ":$it" }}$path${query.str { "?$it" }}" + internal fun toString( + protocol: String, + host: String = "", + port: Int? = null, + path: String = "", + query: String? = null, + ): String = "$protocol://$host${port?.ensureValidPort().str { ":$it" }}$path${query.str { "?$it" }}" } } diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/UrlUtils.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/UrlUtils.kt index 7ac70c8f3..f67bfdec0 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/UrlUtils.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/UrlUtils.kt @@ -8,7 +8,13 @@ import kotlin.jvm.JvmName expect fun fileUrl(path: String): Url -expect fun remoteUrl(protocol: String, host: String = "", port: Int? = null, path: String = "", query: String? = null): Url +expect fun remoteUrl( + protocol: String, + host: String = "", + port: Int? = null, + path: String = "", + query: String? = null, +): Url expect fun parseUrl(string: String): Url diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/exceptions/InvalidUrlException.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/exceptions/InvalidUrlException.kt index fcb2f63fa..df4814c41 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/exceptions/InvalidUrlException.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/exceptions/InvalidUrlException.kt @@ -16,7 +16,7 @@ class InvalidUrlException : TuPrologException { context: ExecutionContext, signature: Signature, culprit: Term, - index: Int + index: Int, ): LogicError { return TypeError.forArgument(context, signature, TypeError.Expected.URL, culprit, index) } diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/CharConversion.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/CharConversion.kt index 108a682d3..ec9dad727 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/CharConversion.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/CharConversion.kt @@ -6,7 +6,10 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object CharConversion : BinaryRelation.NonBacktrackable("char_conversion") { - override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response { return notSupported() } } diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/Close2.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/Close2.kt index 09999ce89..cb06c2a86 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/Close2.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/Close2.kt @@ -6,7 +6,10 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object Close2 : BinaryRelation.NonBacktrackable("close") { - override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response { return notSupported() } } diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/CurrentCharConversion.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/CurrentCharConversion.kt index b72a7419b..2bd0088ae 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/CurrentCharConversion.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/CurrentCharConversion.kt @@ -6,7 +6,10 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object CurrentCharConversion : BinaryRelation.NonBacktrackable("current_char_conversion") { - override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response { return notSupported() } } diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/GetByte2.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/GetByte2.kt index 22b7d762d..925ed16d5 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/GetByte2.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/GetByte2.kt @@ -6,7 +6,10 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object GetByte2 : BinaryRelation.NonBacktrackable("get_byte") { - override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response { return notSupported() } } diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/GetChar2.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/GetChar2.kt index 13340d1ec..2e956f103 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/GetChar2.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/GetChar2.kt @@ -9,7 +9,10 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object GetChar2 : BinaryRelation.NonBacktrackable("get_char") { - override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response { val channel = ensuringArgumentIsInputChannel(0) ensuringArgumentIsVarOrChar(1) return readCharAndReply(channel, second) diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/GetCode2.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/GetCode2.kt index 624dde6db..695f7cfba 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/GetCode2.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/GetCode2.kt @@ -9,7 +9,10 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object GetCode2 : BinaryRelation.NonBacktrackable("get_code") { - override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response { val channel = ensuringArgumentIsInputChannel(0) ensuringArgumentIsVarOrCharCode(0) return readCodeAndReply(channel, first) diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/IOPrimitiveUtils.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/IOPrimitiveUtils.kt index a9f0b9244..74cf50ace 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/IOPrimitiveUtils.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/IOPrimitiveUtils.kt @@ -53,7 +53,6 @@ import it.unibo.tuprolog.unify.Unificator import kotlin.collections.List as KtList object IOPrimitiveUtils { - private val INPUT_STREAM_TERM_PATTERN by lazy { InputChannel.streamTerm() } private val OUTPUT_STREAM_TERM_PATTERN by lazy { OutputChannel.streamTerm() } private val PROPERTY_TYPE_PATTERN by lazy { Struct.of("type", Var.anonymous()) } @@ -73,64 +72,77 @@ object IOPrimitiveUtils { private val INFO_SINGLETONS_PATTERN by lazy { singletons() } private val validPropertiesPattern: Sequence - get() = sequenceOf( - PROPERTY_INPUT, - PROPERTY_OUTPUT, - PROPERTY_ALIAS_PATTERN, - PROPERTY_TYPE_PATTERN, - PROPERTY_EOF_ACTION_PATTERN, - PROPERTY_REPOSITION_PATTERN - ) + get() = + sequenceOf( + PROPERTY_INPUT, + PROPERTY_OUTPUT, + PROPERTY_ALIAS_PATTERN, + PROPERTY_TYPE_PATTERN, + PROPERTY_EOF_ACTION_PATTERN, + PROPERTY_REPOSITION_PATTERN, + ) private val validOptionsPattern: Sequence - get() = sequenceOf(this::quoted, this::ignoreOps, this::numberVars) - .flatMap { sequenceOf(true, false).map(it) } + get() = + sequenceOf(this::quoted, this::ignoreOps, this::numberVars) + .flatMap { sequenceOf(true, false).map(it) } private val validInfoPattern: Sequence - get() = sequenceOf( - INFO_VARIABLES_PATTERN, - INFO_VARIABLE_NAMES_PATTERN, - INFO_SINGLETONS_PATTERN - ) + get() = + sequenceOf( + INFO_VARIABLES_PATTERN, + INFO_VARIABLE_NAMES_PATTERN, + INFO_SINGLETONS_PATTERN, + ) private val supportedPropertiesPattern: Sequence - get() = sequenceOf( - PROPERTY_INPUT, - PROPERTY_OUTPUT, - PROPERTY_ALIAS_PATTERN, - PROPERTY_TYPE_TEXT, - PROPERTY_EOF_ACTION_EOF_CODE, - PROPERTY_REPOSITION_FALSE - ) + get() = + sequenceOf( + PROPERTY_INPUT, + PROPERTY_OUTPUT, + PROPERTY_ALIAS_PATTERN, + PROPERTY_TYPE_TEXT, + PROPERTY_EOF_ACTION_EOF_CODE, + PROPERTY_REPOSITION_FALSE, + ) - private fun alias(alias: String? = null) = - Struct.of("alias", alias?.let { Atom.of(it) } ?: Var.anonymous()) + private fun alias(alias: String? = null) = Struct.of("alias", alias?.let { Atom.of(it) } ?: Var.anonymous()) - private fun quoted(value: Boolean? = null) = - Struct.of("quoted", value?.let { Truth.of(it) } ?: Var.anonymous()) + private fun quoted(value: Boolean? = null) = Struct.of("quoted", value?.let { Truth.of(it) } ?: Var.anonymous()) private fun ignoreOps(value: Boolean? = null) = - Struct.of("ignore_ops", value?.let { Truth.of(it) } ?: Var.anonymous()) + Struct.of( + "ignore_ops", + value?.let { Truth.of(it) } ?: Var.anonymous(), + ) private fun numberVars(value: Boolean? = null) = - Struct.of("numbervars", value?.let { Truth.of(it) } ?: Var.anonymous()) + Struct.of( + "numbervars", + value?.let { Truth.of(it) } ?: Var.anonymous(), + ) private fun variables(variables: KtList? = null) = - Struct.of("variables", variables?.let { List.of(it) } ?: Var.anonymous()) - - private fun vn(functor: String, vNames: KtList>? = null) = Struct.of( - functor, - vNames?.map { (a, v) -> Struct.of("=", a, v) } - ?.let { List.of(it) } - ?: Var.anonymous() + "variables", + variables?.let { + List.of(it) + } ?: Var.anonymous(), ) - private fun variableNames(vNames: KtList>? = null) = - vn("variable_names", vNames) + private fun vn( + functor: String, + vNames: KtList>? = null, + ) = Struct.of( + functor, + vNames?.map { (a, v) -> Struct.of("=", a, v) } + ?.let { List.of(it) } + ?: Var.anonymous(), + ) - private fun singletons(vNames: KtList>? = null) = - vn("singletons", vNames) + private fun variableNames(vNames: KtList>? = null) = vn("variable_names", vNames) + + private fun singletons(vNames: KtList>? = null) = vn("singletons", vNames) @Suppress("UNCHECKED_CAST") fun Solve.Request.propertiesOf(channel: Channel): Sequence = @@ -142,7 +154,7 @@ object IOPrimitiveUtils { context.inputChannels .aliasesOf(channel as InputChannel) .filterNot { it == ChannelStore.CURRENT } - .map(::alias) + .map(::alias), ) } is OutputChannel<*> -> { @@ -151,7 +163,7 @@ object IOPrimitiveUtils { context.outputChannels .aliasesOf(channel as OutputChannel) .filterNot { it == ChannelStore.CURRENT } - .map(::alias) + .map(::alias), ) } } @@ -220,7 +232,10 @@ object IOPrimitiveUtils { } } - private fun KtList.getOption(unificator: Unificator, pattern: Term): Boolean = + private fun KtList.getOption( + unificator: Unificator, + pattern: Term, + ): Boolean = asSequence() .filterIsInstance() .filter { unificator.match(it, pattern) } @@ -229,7 +244,11 @@ object IOPrimitiveUtils { .map { it.isTrue } .firstOrNull() ?: false - private fun KtList.getInfo(unificator: Unificator, pattern: Term, value: Term): Substitution = + private fun KtList.getInfo( + unificator: Unificator, + pattern: Term, + value: Term, + ): Substitution = asSequence().filterIsInstance() .firstOrNull { unificator.match(it, pattern) } ?.let { unificator.mgu(it, value) } @@ -239,16 +258,18 @@ object IOPrimitiveUtils { fun Solve.Request.ensuringArgumentIsFormatter(index: Int): TermFormatter { ensuringArgumentIsValidOptionList(index) val optionList = (arguments[index] as List).toList() - val funcFormat = if (optionList.getOption(context.unificator, OPTION_QUOTED_PATTERN)) { - QUOTED_IF_NECESSARY - } else { - LITERAL - } - val opFormat = if (optionList.getOption(context.unificator, OPTION_IGNORE_OPS_PATTERN)) { - IGNORE_OPERATORS - } else { - EXPRESSIONS - } + val funcFormat = + if (optionList.getOption(context.unificator, OPTION_QUOTED_PATTERN)) { + QUOTED_IF_NECESSARY + } else { + LITERAL + } + val opFormat = + if (optionList.getOption(context.unificator, OPTION_IGNORE_OPS_PATTERN)) { + IGNORE_OPERATORS + } else { + EXPRESSIONS + } val numberVars = optionList.getOption(context.unificator, OPTION_NUMBER_VARS_PATTERN) return TermFormatter.of(UNDERSCORE, opFormat, funcFormat, numberVars, context.operators) } @@ -296,18 +317,19 @@ object IOPrimitiveUtils { val term = arguments[index] when (term) { is Var -> return null - is Struct -> when { - match(term, OUTPUT_STREAM_TERM_PATTERN) -> { - return context.outputChannels.findByTerm(term) - .firstOrNull() - ?: throw ExistenceError.forStream(context, term) + is Struct -> + when { + match(term, OUTPUT_STREAM_TERM_PATTERN) -> { + return context.outputChannels.findByTerm(term) + .firstOrNull() + ?: throw ExistenceError.forStream(context, term) + } + match(term, INPUT_STREAM_TERM_PATTERN) -> { + return context.inputChannels.findByTerm(term) + .firstOrNull() + ?: throw ExistenceError.forStream(context, term) + } } - match(term, INPUT_STREAM_TERM_PATTERN) -> { - return context.inputChannels.findByTerm(term) - .firstOrNull() - ?: throw ExistenceError.forStream(context, term) - } - } } throw DomainError.forArgument(context, signature, STREAM_OR_ALIAS, term, index) } @@ -315,11 +337,12 @@ object IOPrimitiveUtils { fun Solve.Request.ensuringArgumentIsVarOrChar(index: Int): Solve.Request { return when (val arg = arguments[index]) { is Var -> this - is Atom -> when { - arg.value == "end_of_file" -> this - arg.value.length == 1 -> this - else -> throw TypeError.forArgument(context, signature, TypeError.Expected.IN_CHARACTER, arg, index) - } + is Atom -> + when { + arg.value == "end_of_file" -> this + arg.value.length == 1 -> this + else -> throw TypeError.forArgument(context, signature, TypeError.Expected.IN_CHARACTER, arg, index) + } else -> throw TypeError.forArgument(context, signature, TypeError.Expected.IN_CHARACTER, arg, index) } } @@ -377,7 +400,7 @@ object IOPrimitiveUtils { fun Solve.Request.writeTermAndReply( channel: OutputChannel, term: Term, - formatter: TermFormatter + formatter: TermFormatter, ): Solve.Response { return try { channel.write(term.format(formatter)) @@ -389,7 +412,7 @@ object IOPrimitiveUtils { fun Solve.Request.writeCodeAndReply( channel: OutputChannel, - arg: Integer + arg: Integer, ): Solve.Response { return try { channel.write("${arg.intValue.toChar()}") @@ -399,7 +422,10 @@ object IOPrimitiveUtils { } } - fun Solve.Request.writeCharAndReply(channel: OutputChannel, arg: Atom): Solve.Response { + fun Solve.Request.writeCharAndReply( + channel: OutputChannel, + arg: Atom, + ): Solve.Response { return try { channel.write(arg.value) replySuccess() @@ -408,7 +434,10 @@ object IOPrimitiveUtils { } } - fun Solve.Request.peekCodeAndReply(channel: InputChannel, arg: Term): Solve.Response { + fun Solve.Request.peekCodeAndReply( + channel: InputChannel, + arg: Term, + ): Solve.Response { return try { val code = channel.peek()?.get(0)?.code ?: -1 replyWith(mgu(arg, Integer.of(code))) @@ -417,7 +446,10 @@ object IOPrimitiveUtils { } } - fun Solve.Request.peekCharAndReply(channel: InputChannel, arg: Term): Solve.Response { + fun Solve.Request.peekCharAndReply( + channel: InputChannel, + arg: Term, + ): Solve.Response { return try { val char = channel.peek() ?: "end_of_file" replyWith(mgu(arg, Atom.of(char))) @@ -426,7 +458,10 @@ object IOPrimitiveUtils { } } - fun Solve.Request.readCodeAndReply(channel: InputChannel, arg: Term): Solve.Response { + fun Solve.Request.readCodeAndReply( + channel: InputChannel, + arg: Term, + ): Solve.Response { return try { val code = channel.read()?.get(0)?.code ?: -1 replyWith(mgu(arg, Integer.of(code))) @@ -435,7 +470,10 @@ object IOPrimitiveUtils { } } - fun Solve.Request.readCharAndReply(channel: InputChannel, arg: Term): Solve.Response { + fun Solve.Request.readCharAndReply( + channel: InputChannel, + arg: Term, + ): Solve.Response { return try { val char = channel.read() ?: "end_of_file" replyWith(mgu(arg, Atom.of(char))) @@ -445,14 +483,14 @@ object IOPrimitiveUtils { } private val Term.singletons: Set - get() = variables.groupBy { it } - .asSequence() - .filter { it.value.size == 1 } - .map { it.key } - .toSet() + get() = + variables.groupBy { it } + .asSequence() + .filter { it.value.size == 1 } + .map { it.key } + .toSet() - private fun Iterable.toAssignments(): KtList> = - asSequence().toAssignments() + private fun Iterable.toAssignments(): KtList> = asSequence().toAssignments() private fun Sequence.toAssignments(): KtList> = groupBy { Atom.of(it.name) } @@ -462,15 +500,16 @@ object IOPrimitiveUtils { fun Solve.Request.readTermAndReply( channel: InputChannel, arg: Term, - lastIsInfoList: Boolean = false + lastIsInfoList: Boolean = false, ): Solve.Response { try { val termsChannel = channel.asTermChannel(context.operators) - val infoList = if (lastIsInfoList) { - ensuringArgumentIsValidInfoList(arguments.lastIndex) - } else { - emptyList() - } + val infoList = + if (lastIsInfoList) { + ensuringArgumentIsValidInfoList(arguments.lastIndex) + } else { + emptyList() + } if (!termsChannel.available) return replyFail() return when (val read = termsChannel.read()) { null -> replyFail() @@ -478,12 +517,13 @@ object IOPrimitiveUtils { val variables = variables(read.variables.toList()) val variableNames = variableNames(read.variables.toAssignments()) val singletons = singletons(read.singletons.toAssignments()) - val info = infoList?.let { - val u = context.unificator - it.getInfo(u, INFO_SINGLETONS_PATTERN, singletons) + - it.getInfo(u, INFO_VARIABLES_PATTERN, variables) + - it.getInfo(u, INFO_VARIABLE_NAMES_PATTERN, variableNames) - } ?: mgu(arguments.last(), List.of(variables, variableNames, singletons)) + val info = + infoList?.let { + val u = context.unificator + it.getInfo(u, INFO_SINGLETONS_PATTERN, singletons) + + it.getInfo(u, INFO_VARIABLES_PATTERN, variables) + + it.getInfo(u, INFO_VARIABLE_NAMES_PATTERN, variableNames) + } ?: mgu(arguments.last(), List.of(variables, variableNames, singletons)) replyWith(mgu(arg, read) + info) } } @@ -495,7 +535,7 @@ object IOPrimitiveUtils { channel.streamTerm.toString(), e.line, e.column, - e.message ?: "" + e.message ?: "", ) } } @@ -507,15 +547,16 @@ object IOPrimitiveUtils { val url = ensuringArgumentIsUrl(0) val mode = ensuringArgumentIsIOMode(1) ensuringArgumentIsVariable(2) - val options = if (arguments.size >= 4) { - ensuringArgumentIsList(3) - (arguments[3] as List).toSequence() - .map { ensureTermIsValidProperty(it) } - .map { ensureTermIsSupportedProperty(it) } - .toSet() - } else { - emptySet() - } + val options = + if (arguments.size >= 4) { + ensuringArgumentIsList(3) + (arguments[3] as List).toSequence() + .map { ensureTermIsValidProperty(it) } + .map { ensureTermIsSupportedProperty(it) } + .toSet() + } else { + emptySet() + } val alias = options.firstOrNull { match(it, PROPERTY_ALIAS_PATTERN) }?.alias return when (mode) { IOMode.READ -> replyOpeningStream(url.openInputChannel(), third, alias) @@ -527,7 +568,7 @@ object IOPrimitiveUtils { private fun Solve.Request.replyOpeningStream( channel: OutputChannel, third: Term, - alias: String? = null + alias: String? = null, ): Solve.Response { val streamTerm = channel.streamTerm return replyWith(mgu(third, streamTerm)) { @@ -538,7 +579,7 @@ object IOPrimitiveUtils { private fun Solve.Request.replyOpeningStream( channel: InputChannel, third: Term, - alias: String? = null + alias: String? = null, ): Solve.Response { val streamTerm = channel.streamTerm return replyWith(mgu(third, streamTerm)) { diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/Open3.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/Open3.kt index 6013d9327..dd3624b7f 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/Open3.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/Open3.kt @@ -8,5 +8,9 @@ import it.unibo.tuprolog.solve.primitive.Solve.Response import it.unibo.tuprolog.solve.primitive.TernaryRelation object Open3 : TernaryRelation.NonBacktrackable("open") { - override fun Request.computeOne(first: Term, second: Term, third: Term): Response = open(third) + override fun Request.computeOne( + first: Term, + second: Term, + third: Term, + ): Response = open(third) } diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/Open4.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/Open4.kt index 873bdd80d..2b3a96800 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/Open4.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/Open4.kt @@ -11,6 +11,6 @@ object Open4 : QuaternaryRelation.NonBacktrackable("open") { first: Term, second: Term, third: Term, - fourth: Term + fourth: Term, ): Solve.Response = open(third) } diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PeekByte2.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PeekByte2.kt index 5772c0ec8..6547e8930 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PeekByte2.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PeekByte2.kt @@ -6,7 +6,10 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object PeekByte2 : BinaryRelation.NonBacktrackable("peek_byte") { - override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response { return notSupported() } } diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PeekChar2.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PeekChar2.kt index 0a2f8fc83..5714c5e9e 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PeekChar2.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PeekChar2.kt @@ -9,7 +9,10 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object PeekChar2 : BinaryRelation.NonBacktrackable("peek_char") { - override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response { val channel = ensuringArgumentIsInputChannel(0) ensuringArgumentIsVarOrChar(1) return peekCharAndReply(channel, second) diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PeekCode2.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PeekCode2.kt index a0d96474b..0ccf42c42 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PeekCode2.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PeekCode2.kt @@ -9,7 +9,10 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object PeekCode2 : BinaryRelation.NonBacktrackable("peek_code") { - override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response { val channel = ensuringArgumentIsInputChannel(0) ensuringArgumentIsVarOrCharCode(0) return peekCodeAndReply(channel, first) diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PutByte2.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PutByte2.kt index 8181c5437..6b459fe83 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PutByte2.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PutByte2.kt @@ -6,7 +6,10 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object PutByte2 : BinaryRelation.NonBacktrackable("put_byte") { - override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response { return notSupported() } } diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PutChar2.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PutChar2.kt index 1225eb6dc..5c1e91567 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PutChar2.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PutChar2.kt @@ -9,7 +9,10 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object PutChar2 : BinaryRelation.NonBacktrackable("put_char") { - override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response { val channel = ensuringArgumentIsOutputChannel(0) ensuringArgumentIsChar(1) return writeCharAndReply(channel, first as Atom) diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PutCode2.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PutCode2.kt index 6b4f77934..0f0e74b3c 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PutCode2.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/PutCode2.kt @@ -9,7 +9,10 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object PutCode2 : BinaryRelation.NonBacktrackable("put_code") { - override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response { val channel = ensuringArgumentIsOutputChannel(0) ensuringArgumentIsCharCode(1) return writeCodeAndReply(channel, first as Integer) diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/Read2.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/Read2.kt index cc8fc226e..18e60d154 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/Read2.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/Read2.kt @@ -8,7 +8,10 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object Read2 : BinaryRelation.NonBacktrackable("read") { - override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response { val channel = ensuringArgumentIsInputChannel(0) return readTermAndReply(channel, second) } diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/ReadTerm2.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/ReadTerm2.kt index 4d4468081..2c4f600a9 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/ReadTerm2.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/ReadTerm2.kt @@ -8,6 +8,8 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object ReadTerm2 : BinaryRelation.NonBacktrackable("read_term") { - override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response = - readTermAndReply(currentInputChannel, first, lastIsInfoList = true) + override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response = readTermAndReply(currentInputChannel, first, lastIsInfoList = true) } diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/ReadTerm3.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/ReadTerm3.kt index 1bfa3cdbb..33e7e83d0 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/ReadTerm3.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/ReadTerm3.kt @@ -8,7 +8,11 @@ import it.unibo.tuprolog.solve.primitive.Solve import it.unibo.tuprolog.solve.primitive.TernaryRelation object ReadTerm3 : TernaryRelation.NonBacktrackable("read_term") { - override fun Solve.Request.computeOne(first: Term, second: Term, third: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + third: Term, + ): Solve.Response { val channel = ensuringArgumentIsInputChannel(0) return readTermAndReply(channel, second, lastIsInfoList = true) } diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/SetTheory.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/SetTheory.kt index 774b05858..f37a669dd 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/SetTheory.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/SetTheory.kt @@ -17,13 +17,17 @@ object SetTheory : UnaryPredicate.NonBacktrackable("set_theory return setTheory(first.castTo().value, append = false) } - fun Solve.Request.setTheory(text: String, append: Boolean = true): Solve.Response { + fun Solve.Request.setTheory( + text: String, + append: Boolean = true, + ): Solve.Response { try { val theory = ClausesParser.withOperators(context.operators).parseTheory(text) - val solver = context.createMutableSolver( - staticKb = Theory.empty(context.unificator), - dynamicKb = MutableTheory.empty(context.unificator) - ) + val solver = + context.createMutableSolver( + staticKb = Theory.empty(context.unificator), + dynamicKb = MutableTheory.empty(context.unificator), + ) solver.loadStaticKb(theory) return replySuccess { if (append) { @@ -43,7 +47,9 @@ object SetTheory : UnaryPredicate.NonBacktrackable("set_theory e.clauseIndex, e.line, e.column, - e.message?.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() } ?: "" + e.message + ?.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() } + ?: "", ) } } diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/StreamProperty.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/StreamProperty.kt index fbf41353d..eed5fd632 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/StreamProperty.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/StreamProperty.kt @@ -9,7 +9,10 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object StreamProperty : BinaryRelation("stream_property") { - override fun Solve.Request.computeAll(first: Term, second: Term): Sequence { + override fun Solve.Request.computeAll( + first: Term, + second: Term, + ): Sequence { ensuringArgumentIsVarOrStream(0) ensuringArgumentIsStreamProperty(1) return sequenceOf(context.inputChannels, context.outputChannels) diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/Write2.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/Write2.kt index d8ad479ec..b0fbacc1a 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/Write2.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/Write2.kt @@ -9,7 +9,10 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object Write2 : BinaryRelation.NonBacktrackable("write") { - override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response { val channel = ensuringArgumentIsOutputChannel(0) return writeTermAndReply(channel, second, TermFormatter.default(context.operators)) } diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/WriteCanonical2.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/WriteCanonical2.kt index f6b2ab6ef..5d24b9251 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/WriteCanonical2.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/WriteCanonical2.kt @@ -9,7 +9,10 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object WriteCanonical2 : BinaryRelation.NonBacktrackable("write_canonical") { - override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response { val channel = ensuringArgumentIsOutputChannel(0) return writeTermAndReply(channel, second, TermFormatter.canonical()) } diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/WriteEq2.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/WriteEq2.kt index ce40debf9..c5d682cb1 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/WriteEq2.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/WriteEq2.kt @@ -9,7 +9,10 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object WriteEq2 : BinaryRelation.NonBacktrackable("writeq") { - override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response { val channel = ensuringArgumentIsOutputChannel(0) return writeTermAndReply(channel, second, TermFormatter.readable()) } diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/WriteTerm2.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/WriteTerm2.kt index e015134f7..d7b3cb4b6 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/WriteTerm2.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/WriteTerm2.kt @@ -9,7 +9,10 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object WriteTerm2 : BinaryRelation.NonBacktrackable("write_term") { - override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response { val formatter = ensuringArgumentIsFormatter(1) return writeTermAndReply(currentOutputChannel, first, formatter) } diff --git a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/WriteTerm3.kt b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/WriteTerm3.kt index 7b997ffc1..6981eb36d 100644 --- a/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/WriteTerm3.kt +++ b/io-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/io/primitives/WriteTerm3.kt @@ -9,7 +9,11 @@ import it.unibo.tuprolog.solve.primitive.Solve import it.unibo.tuprolog.solve.primitive.TernaryRelation object WriteTerm3 : TernaryRelation.NonBacktrackable("write_term") { - override fun Solve.Request.computeOne(first: Term, second: Term, third: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + third: Term, + ): Solve.Response { val channel = ensuringArgumentIsOutputChannel(0) val formatter = ensuringArgumentIsFormatter(1) return writeTermAndReply(channel, first, formatter) diff --git a/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/ExampleTheories.kt b/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/ExampleTheories.kt index a384f4b52..6fd1d80bf 100644 --- a/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/ExampleTheories.kt +++ b/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/ExampleTheories.kt @@ -3,26 +3,26 @@ package it.unibo.tuprolog.solve.libs.io import it.unibo.tuprolog.dsl.theory.logicProgramming object ExampleTheories { - - val PARENTS = logicProgramming { - theoryOf( - fact { "male"("james1") }, - fact { "male"("charles1") }, - fact { "male"("charles2") }, - fact { "male"("james2") }, - fact { "male"("george1") }, - fact { "female"("catherine") }, - fact { "female"("elizabeth") }, - fact { "female"("sophia") }, - fact { "parent"("charles1", "james1") }, - fact { "parent"("elizabeth", "james1") }, - fact { "parent"("charles2", "charles1") }, - fact { "parent"("catherine", "charles1") }, - fact { "parent"("james2", "charles1") }, - fact { "parent"("sophia", "elizabeth") }, - fact { "parent"("george1", "sophia") }, - rule { "mother"(X, Y) `if` ("female"(X) and "parent"(X, Y)) }, - rule { "father"(X, Y) `if` ("male"(X) and "parent"(X, Y)) } - ) - } + val PARENTS = + logicProgramming { + theoryOf( + fact { "male"("james1") }, + fact { "male"("charles1") }, + fact { "male"("charles2") }, + fact { "male"("james2") }, + fact { "male"("george1") }, + fact { "female"("catherine") }, + fact { "female"("elizabeth") }, + fact { "female"("sophia") }, + fact { "parent"("charles1", "james1") }, + fact { "parent"("elizabeth", "james1") }, + fact { "parent"("charles2", "charles1") }, + fact { "parent"("catherine", "charles1") }, + fact { "parent"("james2", "charles1") }, + fact { "parent"("sophia", "elizabeth") }, + fact { "parent"("george1", "sophia") }, + rule { "mother"(X, Y) `if` ("female"(X) and "parent"(X, Y)) }, + rule { "father"(X, Y) `if` ("male"(X) and "parent"(X, Y)) }, + ) + } } diff --git a/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/ExampleUrls.kt b/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/ExampleUrls.kt index ed15c8007..7e194f201 100644 --- a/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/ExampleUrls.kt +++ b/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/ExampleUrls.kt @@ -1,9 +1,9 @@ package it.unibo.tuprolog.solve.libs.io object ExampleUrls { - private const val baseUrl = "http://localhost:8080" + private const val BASE_URL = "http://localhost:8080" - const val PARENTS = "$baseUrl/parents.pl" + const val PARENTS = "$BASE_URL/parents.pl" - const val WRONG_PARENTS = "$baseUrl/parents-wrong.pl" + const val WRONG_PARENTS = "$BASE_URL/parents-wrong.pl" } diff --git a/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/StringUtils.kt b/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/StringUtils.kt index c8b1c5eb8..2a10cf640 100644 --- a/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/StringUtils.kt +++ b/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/StringUtils.kt @@ -8,5 +8,7 @@ internal fun String.trimAndCorrectLineTermination(lineTerminator: String = "\n") return trim().replace(TERMINATOR, lineTerminator) } -fun assertSameLines(expected: String, actual: String) = - assertEquals(expected.trimAndCorrectLineTermination(), actual.trimAndCorrectLineTermination()) +fun assertSameLines( + expected: String, + actual: String, +) = assertEquals(expected.trimAndCorrectLineTermination(), actual.trimAndCorrectLineTermination()) diff --git a/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestClassicInclude.kt b/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestClassicInclude.kt index a1a707937..a11487335 100644 --- a/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestClassicInclude.kt +++ b/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestClassicInclude.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.library.Runtime import kotlin.test.Test class TestClassicInclude : TestInclude, SolverFactory by ClassicSolverFactory { - private val prototype = TestInclude.prototype(this) override val defaultRuntime: Runtime diff --git a/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestConsult.kt b/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestConsult.kt index 3c8a2b41c..603591554 100644 --- a/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestConsult.kt +++ b/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestConsult.kt @@ -4,10 +4,8 @@ import it.unibo.tuprolog.solve.SolverFactory import it.unibo.tuprolog.solve.SolverTest interface TestConsult : SolverTest { - companion object { - fun prototype(solverFactory: SolverFactory): TestConsult = - TestConsultImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestConsult = TestConsultImpl(solverFactory) } fun testApi() diff --git a/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestConsultImpl.kt b/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestConsultImpl.kt index 3bd997e1f..58bbee817 100644 --- a/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestConsultImpl.kt +++ b/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestConsultImpl.kt @@ -12,14 +12,14 @@ import kotlin.test.assertEquals import kotlin.test.assertTrue class TestConsultImpl(private val solverFactory: SolverFactory) : TestConsult { - private fun testConsultCorrectTheory(url: Url) { logicProgramming { val canaryTheory = theoryOf(factOf("canary")) - val solver = solverFactory.solverWithDefaultBuiltins( - otherLibraries = Runtime.of(IOLib), - staticKb = canaryTheory - ) + val solver = + solverFactory.solverWithDefaultBuiltins( + otherLibraries = Runtime.of(IOLib), + staticKb = canaryTheory, + ) assertEquals(canaryTheory, solver.staticKb) val query = consult(url.toString()) val solutions = solver.solve(query).toList() @@ -37,10 +37,11 @@ class TestConsultImpl(private val solverFactory: SolverFactory) : TestConsult { private fun testConsultWrongTheory(url: Url) { logicProgramming { val canaryTheory = theoryOf(factOf("canary")) - val solver = solverFactory.solverWithDefaultBuiltins( - otherLibraries = Runtime.of(IOLib), - staticKb = canaryTheory - ) + val solver = + solverFactory.solverWithDefaultBuiltins( + otherLibraries = Runtime.of(IOLib), + staticKb = canaryTheory, + ) assertEquals(canaryTheory, solver.staticKb) val query = consult(url.toString()) val solutions = solver.solve(query).toList() @@ -62,10 +63,11 @@ class TestConsultImpl(private val solverFactory: SolverFactory) : TestConsult { private fun testConsultMissingTheory(url: Url) { logicProgramming { val canaryTheory = theoryOf(factOf("canary")) - val solver = solverFactory.solverWithDefaultBuiltins( - otherLibraries = Runtime.of(IOLib), - staticKb = canaryTheory - ) + val solver = + solverFactory.solverWithDefaultBuiltins( + otherLibraries = Runtime.of(IOLib), + staticKb = canaryTheory, + ) assertEquals(canaryTheory, solver.staticKb) val query = consult(url.toString()) val solutions = solver.solve(query).toList() @@ -85,9 +87,10 @@ class TestConsultImpl(private val solverFactory: SolverFactory) : TestConsult { } override fun testApi() { - val solver = solverFactory.solverWithDefaultBuiltins( - otherLibraries = Runtime.of(IOLib) - ) + val solver = + solverFactory.solverWithDefaultBuiltins( + otherLibraries = Runtime.of(IOLib), + ) assertEquals(IOLib, solver.libraries[IOLib.alias]) solver.assertHasPredicateInAPI(Consult) } diff --git a/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestInclude.kt b/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestInclude.kt index 1bd2ca374..9a0b45b38 100644 --- a/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestInclude.kt +++ b/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestInclude.kt @@ -4,10 +4,8 @@ import it.unibo.tuprolog.solve.SolverFactory import it.unibo.tuprolog.solve.SolverTest interface TestInclude : SolverTest { - companion object { - fun prototype(solverFactory: SolverFactory): TestInclude = - TestIncludeImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestInclude = TestIncludeImpl(solverFactory) } fun testLocalInclude() diff --git a/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestIncludeImpl.kt b/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestIncludeImpl.kt index ed594a298..83272e81c 100644 --- a/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestIncludeImpl.kt +++ b/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestIncludeImpl.kt @@ -9,13 +9,12 @@ import kotlin.test.assertEquals import kotlin.test.assertTrue class TestIncludeImpl(private val solverFactory: SolverFactory) : TestInclude { - private fun theoryWithLocalInclude(loadGoal: String) = logicProgramming { val parentsPath = findResource("Parents.pl") theoryOf( directive { loadGoal(parentsPath.toString()) }, - fact { "someFact" } + fact { "someFact" }, ) } @@ -46,7 +45,7 @@ class TestIncludeImpl(private val solverFactory: SolverFactory) : TestInclude { logicProgramming { theoryOf( directive { loadGoal(ExampleUrls.PARENTS) }, - fact { "someFact" } + fact { "someFact" }, ) } @@ -77,7 +76,7 @@ class TestIncludeImpl(private val solverFactory: SolverFactory) : TestInclude { logicProgramming { theoryOf( directive { loadGoal("/path/to/missing.pl") }, - fact { "someFact" } + fact { "someFact" }, ) } diff --git a/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestStreamsInclude.kt b/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestStreamsInclude.kt index 7d26b1c1b..086ea340a 100644 --- a/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestStreamsInclude.kt +++ b/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestStreamsInclude.kt @@ -8,7 +8,6 @@ import kotlin.test.Test @Ignore class TestStreamsInclude : TestInclude, SolverFactory by StreamsSolverFactory { - private val prototype = TestInclude.prototype(this) override val defaultRuntime: Runtime diff --git a/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestUrl.kt b/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestUrl.kt index fbc3f9faa..57a6930a6 100644 --- a/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestUrl.kt +++ b/io-lib/src/commonTest/kotlin/it/unibo/tuprolog/solve/libs/io/TestUrl.kt @@ -9,7 +9,6 @@ import kotlin.test.assertTrue import kotlin.test.fail class TestUrl { - @Test fun testCreation1() { val urlString = "http://www.example.com:80/" @@ -51,7 +50,7 @@ class TestUrl { assertSameLines( ExampleFiles.WRONG_PARENTS, - text + text, ) } @@ -63,7 +62,7 @@ class TestUrl { assertSameLines( ExampleFiles.PARENTS, - text + text, ) val parsed = ClausesParser.withDefaultOperators().parseTheory(text) @@ -118,12 +117,12 @@ class TestUrl { var url = findResource("Parents.pl") assertSameLines( ExampleFiles.PARENTS, - url.readAsText() + url.readAsText(), ) url = findResource("WrongParents.pl") assertSameLines( ExampleFiles.WRONG_PARENTS, - url.readAsText() + url.readAsText(), ) } diff --git a/io-lib/src/jsMain/kotlin/it/unibo/tuprolog/solve/libs/io/ChannelUtilsJs.kt b/io-lib/src/jsMain/kotlin/it/unibo/tuprolog/solve/libs/io/ChannelUtilsJs.kt index 23f426877..3d12c139a 100644 --- a/io-lib/src/jsMain/kotlin/it/unibo/tuprolog/solve/libs/io/ChannelUtilsJs.kt +++ b/io-lib/src/jsMain/kotlin/it/unibo/tuprolog/solve/libs/io/ChannelUtilsJs.kt @@ -5,5 +5,5 @@ import it.unibo.tuprolog.core.operators.OperatorSet import it.unibo.tuprolog.solve.channel.InputChannel actual fun InputChannel.asTermChannel(operators: OperatorSet): InputChannel { - throw IllegalStateException("Reading terms is still not supported for JS") + TODO("reading terms is still not supported for JS") } diff --git a/io-lib/src/jsMain/kotlin/it/unibo/tuprolog/solve/libs/io/FileSystem.kt b/io-lib/src/jsMain/kotlin/it/unibo/tuprolog/solve/libs/io/FileSystem.kt index 259570521..de3557009 100644 --- a/io-lib/src/jsMain/kotlin/it/unibo/tuprolog/solve/libs/io/FileSystem.kt +++ b/io-lib/src/jsMain/kotlin/it/unibo/tuprolog/solve/libs/io/FileSystem.kt @@ -1,3 +1,5 @@ +@file:Suppress("TooManyFunctions", "TooGenericExceptionCaught") + package it.unibo.tuprolog.solve.libs.io import it.unibo.tuprolog.Info @@ -23,7 +25,10 @@ private val REQUEST: dynamic by lazy { js("require('sync-request')") } -internal fun fetch(url: String, encoding: String? = null): T { +internal fun fetch( + url: String, + encoding: String? = null, +): T { try { val response = REQUEST("GET", url, js("{}")) // js("{ cache: 'file' }")) return response.getBody(encoding).unsafeCast() @@ -32,17 +37,13 @@ internal fun fetch(url: String, encoding: String? = null): T { } } -private fun toByteArray(obj: dynamic): ByteArray = - ByteArray(obj.length) { obj[it] } +private fun toByteArray(obj: dynamic): ByteArray = ByteArray(obj.length) { obj[it] } -private fun Uint8Array.toByteArray(): ByteArray = - ByteArray(length) { this[it] } +private fun Uint8Array.toByteArray(): ByteArray = ByteArray(length) { this[it] } -private fun ArrayBuffer.toUInt8Array(): Uint8Array = - Uint8Array(this) +private fun ArrayBuffer.toUInt8Array(): Uint8Array = Uint8Array(this) -internal fun ArrayBuffer.toByteArray(): ByteArray = - toUInt8Array().toByteArray() +internal fun ArrayBuffer.toByteArray(): ByteArray = toUInt8Array().toByteArray() private fun browserReadText(path: String): String = js("window").localStorage.getItem(path).unsafeCast() diff --git a/io-lib/src/jsMain/kotlin/it/unibo/tuprolog/solve/libs/io/UrlUtilsJs.kt b/io-lib/src/jsMain/kotlin/it/unibo/tuprolog/solve/libs/io/UrlUtilsJs.kt index 93124a513..a34a75f7d 100644 --- a/io-lib/src/jsMain/kotlin/it/unibo/tuprolog/solve/libs/io/UrlUtilsJs.kt +++ b/io-lib/src/jsMain/kotlin/it/unibo/tuprolog/solve/libs/io/UrlUtilsJs.kt @@ -8,11 +8,15 @@ actual fun parseUrl(string: String): Url = JsUrl(string) actual fun fileUrl(path: String): Url = JsUrl(protocol = "file", path = path) -actual fun remoteUrl(protocol: String, host: String, port: Int?, path: String, query: String?): Url = - JsUrl(protocol, host, port, path, query) +actual fun remoteUrl( + protocol: String, + host: String, + port: Int?, + path: String, + query: String?, +): Url = JsUrl(protocol, host, port, path, query) -actual fun Url.openInputChannel(): InputChannel = - InputChannel.of(readAsText()) +actual fun Url.openInputChannel(): InputChannel = InputChannel.of(readAsText()) actual fun Url.openOutputChannel(append: Boolean): OutputChannel { throw IOException("Writing not supported for ${toString()}") diff --git a/io-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/io/ChannelUtilsJvm.kt b/io-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/io/ChannelUtilsJvm.kt index c413618b8..5188f0469 100644 --- a/io-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/io/ChannelUtilsJvm.kt +++ b/io-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/io/ChannelUtilsJvm.kt @@ -9,10 +9,11 @@ import java.util.WeakHashMap private val cache = WeakHashMap, InputChannel>() +@Suppress("UnsafeCallOnNullableType") @Synchronized actual fun InputChannel.asTermChannel(operators: OperatorSet): InputChannel { if (this !is ReaderChannel) { - throw IllegalStateException("Channel $streamTerm does not supporting reading terms, as it is of type ${this::class.simpleName}") + error("Channel $streamTerm does not supporting reading terms, as it is of type ${this::class.simpleName}") } return if (cache.containsKey(this)) { cache[this]!! diff --git a/io-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/io/JvmUrl.kt b/io-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/io/JvmUrl.kt index 0a88627d4..f0fafa71c 100644 --- a/io-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/io/JvmUrl.kt +++ b/io-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/io/JvmUrl.kt @@ -9,7 +9,6 @@ import java.net.URL import kotlin.streams.asSequence data class JvmUrl(val url: URL) : Url { - constructor(string: String) : this(string.toUrl()) constructor(protocol: String, host: String = "", port: Int? = null, path: String = "", query: String? = null) : diff --git a/io-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/io/UrlUtilsJvm.kt b/io-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/io/UrlUtilsJvm.kt index c5e990d3c..999970396 100644 --- a/io-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/io/UrlUtilsJvm.kt +++ b/io-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/io/UrlUtilsJvm.kt @@ -17,15 +17,21 @@ actual fun parseUrl(string: String): Url = JvmUrl(string) actual fun fileUrl(path: String): Url = JvmUrl(protocol = "file", path = path) -actual fun remoteUrl(protocol: String, host: String, port: Int?, path: String, query: String?): Url = - JvmUrl(protocol, host, port, path, query) +actual fun remoteUrl( + protocol: String, + host: String, + port: Int?, + path: String, + query: String?, +): Url = JvmUrl(protocol, host, port, path, query) fun URL.toUrl(): Url = parseUrl(toExternalForm()) -fun Url.toURL(): URL = when (this) { - is JvmUrl -> url - else -> toString().toUrl() -} +fun Url.toURL(): URL = + when (this) { + is JvmUrl -> url + else -> toString().toUrl() + } internal fun String.toUrl(): URL = try { diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/NullRef.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/NullRef.kt index e063569d7..3030e1403 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/NullRef.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/NullRef.kt @@ -6,9 +6,15 @@ interface NullRef : ObjectRef { override val `object`: Any get() = throw NullPointerException() - override fun invoke(objectConverter: TermToObjectConverter, methodName: String, arguments: List): Result = - throw NullPointerException() + override fun invoke( + objectConverter: TermToObjectConverter, + methodName: String, + arguments: List, + ): Result = throw NullPointerException() - override fun assign(objectConverter: TermToObjectConverter, propertyName: String, value: Term): Boolean = - throw NullPointerException() + override fun assign( + objectConverter: TermToObjectConverter, + propertyName: String, + value: Term, + ): Boolean = throw NullPointerException() } diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/OOPLib.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/OOPLib.kt index 73bcc6143..d45869907 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/OOPLib.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/OOPLib.kt @@ -35,69 +35,71 @@ import org.gciatto.kt.math.BigDecimal import org.gciatto.kt.math.BigInteger object OOPLib : AbstractLibrary() { - override val alias: String get() = "prolog.oop" override val primitives: Map - get() = listOf>( - ArrayItems, - Assign, - Cast, - Type, - InvokeMethod, - InvokeStrict, - ListItems, - NewObject3, - NullRef, - ObjectRef, - Ref, - Register, - SetItems, - TypeRef, - Unregister - ).map { it.descriptionPair }.toMap() + get() = + listOf>( + ArrayItems, + Assign, + Cast, + Type, + InvokeMethod, + InvokeStrict, + ListItems, + NewObject3, + NullRef, + ObjectRef, + Ref, + Register, + SetItems, + TypeRef, + Unregister, + ).map { it.descriptionPair }.toMap() override val clauses: List - get() = listOf( - ColonEquals.Cast, - ColonEquals.Invocation, - ColonEquals.Assignment, - Dot, - FluentReduce.Recursive, - FluentReduce.Couple, - FluentReduce.Trivial, - NewObject2, - PropertyReduce.Recursive, - PropertyReduce.Base, - Alias.forType("string", String::class), - Alias.forType("array", Array::class), - Alias.forType("list", List::class), - Alias.forType("arraylist", ArrayList::class), - Alias.forType("map", Map::class), - Alias.forType("hashmap", LinkedHashMap::class), - Alias.forType("int", Int::class), - Alias.forType("integer", Int::class), - Alias.forType("double", Double::class), - Alias.forType("float", Float::class), - Alias.forType("long", Long::class), - Alias.forType("short", Short::class), - Alias.forType("byte", Byte::class), - Alias.forType("char", Char::class), - Alias.forType("bool", Boolean::class), - Alias.forType("boolean", Boolean::class), - Alias.forType("any", Any::class), - Alias.forType("nothing", Nothing::class), - Alias.forType("big_integer", BigInteger::class), - Alias.forType("big_decimal", BigDecimal::class), - *platformSpecificAliases - ).map { it.implementation } + get() = + listOf( + ColonEquals.Cast, + ColonEquals.Invocation, + ColonEquals.Assignment, + Dot, + FluentReduce.Recursive, + FluentReduce.Couple, + FluentReduce.Trivial, + NewObject2, + PropertyReduce.Recursive, + PropertyReduce.Base, + Alias.forType("string", String::class), + Alias.forType("array", Array::class), + Alias.forType("list", List::class), + Alias.forType("arraylist", ArrayList::class), + Alias.forType("map", Map::class), + Alias.forType("hashmap", LinkedHashMap::class), + Alias.forType("int", Int::class), + Alias.forType("integer", Int::class), + Alias.forType("double", Double::class), + Alias.forType("float", Float::class), + Alias.forType("long", Long::class), + Alias.forType("short", Short::class), + Alias.forType("byte", Byte::class), + Alias.forType("char", Char::class), + Alias.forType("bool", Boolean::class), + Alias.forType("boolean", Boolean::class), + Alias.forType("any", Any::class), + Alias.forType("nothing", Nothing::class), + Alias.forType("big_integer", BigInteger::class), + Alias.forType("big_decimal", BigDecimal::class), + *platformSpecificAliases, + ).map { it.implementation } override val operators: OperatorSet - get() = OperatorSet( - Operator(".", XFY, 800), - Operator(":=", XFX, 850), - Operator("as", XFX, 200), - Operator("$", FX, 100) - ) + get() = + OperatorSet( + Operator(".", XFY, 800), + Operator(":=", XFX, 850), + Operator("as", XFX, 200), + Operator("$", FX, 100), + ) } diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/ObjectRef.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/ObjectRef.kt index aa4404fe4..fbfe1c0cc 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/ObjectRef.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/ObjectRef.kt @@ -7,6 +7,7 @@ import kotlin.jvm.JvmStatic import kotlin.reflect.KClass interface ObjectRef : Ref { + @Suppress("ktlint:standard:property-naming") val `object`: Any companion object { @@ -17,8 +18,10 @@ interface ObjectRef : Ref { else -> nameOf(any::class, any.identifier) } - private fun nameOf(type: KClass<*>, identifier: String): String = - "" + private fun nameOf( + type: KClass<*>, + identifier: String, + ): String = "" @JvmStatic fun of(any: Any?): ObjectRef = diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/OverloadSelector.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/OverloadSelector.kt index ebbc53bf0..871fc2450 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/OverloadSelector.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/OverloadSelector.kt @@ -11,9 +11,15 @@ interface OverloadSelector { val termToObjectConverter: TermToObjectConverter - fun findMethod(name: String, arguments: List): KCallable<*> + fun findMethod( + name: String, + arguments: List, + ): KCallable<*> - fun findProperty(name: String, value: Term): KMutableProperty<*> + fun findProperty( + name: String, + value: Term, + ): KMutableProperty<*> fun findConstructor(arguments: List): KCallable<*> @@ -21,7 +27,7 @@ interface OverloadSelector { @JvmStatic fun of( type: KClass<*>, - termToObjectConverter: TermToObjectConverter = TermToObjectConverter.default + termToObjectConverter: TermToObjectConverter = TermToObjectConverter.default, ): OverloadSelector = overloadSelector(type, termToObjectConverter) } } diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/Ref.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/Ref.kt index 2c042253b..3cdc893b8 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/Ref.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/Ref.kt @@ -4,31 +4,58 @@ import it.unibo.tuprolog.core.Atom import it.unibo.tuprolog.core.Term interface Ref : Atom { - fun invoke(objectConverter: TermToObjectConverter, methodName: String, vararg arguments: Term): Result = - invoke(objectConverter, methodName, listOf(*arguments)) - - fun invoke(objectConverter: TermToObjectConverter, methodName: String, arguments: List): Result - - fun invoke(objectConverter: TermToObjectConverter, methodName: String, arguments: Iterable): Result = - invoke(objectConverter, methodName, arguments.toList()) - - fun invoke(objectConverter: TermToObjectConverter, methodName: String, arguments: Sequence): Result = - invoke(objectConverter, methodName, arguments.toList()) - - fun invoke(methodName: String, vararg arguments: Term): Result = - invoke(TermToObjectConverter.default, methodName, listOf(*arguments)) - - fun invoke(methodName: String, arguments: List): Result = - invoke(TermToObjectConverter.default, methodName, arguments) - - fun invoke(methodName: String, arguments: Iterable): Result = - invoke(TermToObjectConverter.default, methodName, arguments.toList()) - - fun invoke(methodName: String, arguments: Sequence): Result = - invoke(TermToObjectConverter.default, methodName, arguments.toList()) - - fun assign(objectConverter: TermToObjectConverter, propertyName: String, value: Term): Boolean - - fun assign(propertyName: String, value: Term): Boolean = - assign(TermToObjectConverter.default, propertyName, value) + fun invoke( + objectConverter: TermToObjectConverter, + methodName: String, + vararg arguments: Term, + ): Result = invoke(objectConverter, methodName, listOf(*arguments)) + + fun invoke( + objectConverter: TermToObjectConverter, + methodName: String, + arguments: List, + ): Result + + fun invoke( + objectConverter: TermToObjectConverter, + methodName: String, + arguments: Iterable, + ): Result = invoke(objectConverter, methodName, arguments.toList()) + + fun invoke( + objectConverter: TermToObjectConverter, + methodName: String, + arguments: Sequence, + ): Result = invoke(objectConverter, methodName, arguments.toList()) + + fun invoke( + methodName: String, + vararg arguments: Term, + ): Result = invoke(TermToObjectConverter.default, methodName, listOf(*arguments)) + + fun invoke( + methodName: String, + arguments: List, + ): Result = invoke(TermToObjectConverter.default, methodName, arguments) + + fun invoke( + methodName: String, + arguments: Iterable, + ): Result = invoke(TermToObjectConverter.default, methodName, arguments.toList()) + + fun invoke( + methodName: String, + arguments: Sequence, + ): Result = invoke(TermToObjectConverter.default, methodName, arguments.toList()) + + fun assign( + objectConverter: TermToObjectConverter, + propertyName: String, + value: Term, + ): Boolean + + fun assign( + propertyName: String, + value: Term, + ): Boolean = assign(TermToObjectConverter.default, propertyName, value) } diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/Result.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/Result.kt index 26ea470de..cb474f5e6 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/Result.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/Result.kt @@ -4,7 +4,6 @@ import it.unibo.tuprolog.core.Term import it.unibo.tuprolog.core.TermConvertible sealed class Result { - abstract fun toTerm(): Term? abstract fun asObjectRef(): ObjectRef? @@ -20,7 +19,6 @@ sealed class Result { } data class Value(val value: Any?) : Result(), TermConvertible { - private val termValue by lazy { ObjectToTermConverter.default.convert(value) } diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TermToObjectConverter.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TermToObjectConverter.kt index 42bdb1d82..0a82cada9 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TermToObjectConverter.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TermToObjectConverter.kt @@ -7,24 +7,29 @@ import kotlin.jvm.JvmStatic import kotlin.reflect.KClass interface TermToObjectConverter { - fun convertInto(type: KClass<*>, term: Term): Any? + fun convertInto( + type: KClass<*>, + term: Term, + ): Any? fun possibleConversions(term: Term): Sequence fun admissibleTypes(term: Term): Set> - fun priorityOfConversion(type: KClass<*>, term: Term): Int? + fun priorityOfConversion( + type: KClass<*>, + term: Term, + ): Int? fun mostAdequateType(term: Term): KClass<*> - fun convert(term: Term): Any? = - convertInto(mostAdequateType(term), term) + fun convert(term: Term): Any? = convertInto(mostAdequateType(term), term) companion object { @JvmStatic fun of( typeFactory: TypeFactory = TypeFactory.default, - dealiaser: (Struct) -> Ref? = { null } + dealiaser: (Struct) -> Ref? = { null }, ): TermToObjectConverter = TermToObjectConverterImpl(typeFactory, dealiaser) @JvmStatic diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TypeFactory.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TypeFactory.kt index 2192bf4f0..3787b8edf 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TypeFactory.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TypeFactory.kt @@ -13,6 +13,5 @@ interface TypeFactory { fun typeFromName(typeName: String): KClass<*>? - fun typeRefFromName(typeName: String): TypeRef? = - Optional.of(typeFromName(typeName)).map { TypeRef.of(it) }.value + fun typeRefFromName(typeName: String): TypeRef? = Optional.of(typeFromName(typeName)).map { TypeRef.of(it) }.value } diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TypeRef.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TypeRef.kt index 460b10e42..59a6ab223 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TypeRef.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TypeRef.kt @@ -8,28 +8,33 @@ import kotlin.reflect.KClass interface TypeRef : Ref { val type: KClass<*> - fun create(objectConverter: TermToObjectConverter, vararg arguments: Term): Result = - create(objectConverter, listOf(*arguments)) + fun create( + objectConverter: TermToObjectConverter, + vararg arguments: Term, + ): Result = create(objectConverter, listOf(*arguments)) - fun create(objectConverter: TermToObjectConverter, arguments: List): Result + fun create( + objectConverter: TermToObjectConverter, + arguments: List, + ): Result - fun create(objectConverter: TermToObjectConverter, arguments: Iterable): Result = - create(objectConverter, arguments.toList()) + fun create( + objectConverter: TermToObjectConverter, + arguments: Iterable, + ): Result = create(objectConverter, arguments.toList()) - fun create(objectConverter: TermToObjectConverter, arguments: Sequence): Result = - create(objectConverter, arguments.toList()) + fun create( + objectConverter: TermToObjectConverter, + arguments: Sequence, + ): Result = create(objectConverter, arguments.toList()) - fun create(vararg arguments: Term): Result = - create(TermToObjectConverter.default, listOf(*arguments)) + fun create(vararg arguments: Term): Result = create(TermToObjectConverter.default, listOf(*arguments)) - fun create(arguments: List): Result = - create(TermToObjectConverter.default, arguments) + fun create(arguments: List): Result = create(TermToObjectConverter.default, arguments) - fun create(arguments: Iterable): Result = - create(TermToObjectConverter.default, arguments.toList()) + fun create(arguments: Iterable): Result = create(TermToObjectConverter.default, arguments.toList()) - fun create(arguments: Sequence): Result = - create(TermToObjectConverter.default, arguments.toList()) + fun create(arguments: Sequence): Result = create(TermToObjectConverter.default, arguments.toList()) companion object { @JvmStatic diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TypeUtils.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TypeUtils.kt index 4719a6764..8dc130f65 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TypeUtils.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TypeUtils.kt @@ -11,17 +11,18 @@ import kotlin.reflect.KClass import kotlin.reflect.KFunction import kotlin.reflect.KMutableProperty -private val PRIMITIVE_TYPES = setOf( - Long::class, - Int::class, - Short::class, - Byte::class, - Char::class, - Double::class, - Float::class -) - -internal const val id = "[a-zA-Z_][a-zA-Z0-9_]*" +private val PRIMITIVE_TYPES = + setOf( + Long::class, + Int::class, + Short::class, + Byte::class, + Char::class, + Double::class, + Float::class, + ) + +internal const val ID = "[a-zA-Z_][a-zA-Z0-9_]*" expect val Any.identifier: String @@ -33,7 +34,10 @@ expect val KClass<*>.companionObjectType: Optional> expect fun kClassFromName(qualifiedName: String): Optional> -internal expect fun KCallable<*>.catchingPlatformSpecificException(instance: Any?, action: () -> T): T +internal expect fun KCallable<*>.catchingPlatformSpecificException( + instance: Any?, + action: () -> T, +): T expect fun KClass<*>.allSupertypes(strict: Boolean): Sequence> @@ -45,33 +49,46 @@ expect val KClass<*>.name: String expect fun KCallable<*>.pretty(): String -expect fun KCallable.invoke(instance: Any?, vararg args: Any?): T +expect fun KCallable.invoke( + instance: Any?, + vararg args: Any?, +): T expect val KMutableProperty.setterMethod: KFunction -internal expect fun overloadSelector(type: KClass<*>, termToObjectConverter: TermToObjectConverter): OverloadSelector +internal expect fun overloadSelector( + type: KClass<*>, + termToObjectConverter: TermToObjectConverter, +): OverloadSelector val KClass<*>.isPrimitiveType: Boolean get() = this in PRIMITIVE_TYPES -infix fun KClass<*>.isSupertypeOf(other: KClass<*>): Boolean = - isSupertypeOf(other, false) +infix fun KClass<*>.isSupertypeOf(other: KClass<*>): Boolean = isSupertypeOf(other, false) -fun KClass<*>.isSupertypeOf(other: KClass<*>, strict: Boolean): Boolean = - other.allSupertypes(strict).any { it == this } +fun KClass<*>.isSupertypeOf( + other: KClass<*>, + strict: Boolean, +): Boolean = other.allSupertypes(strict).any { it == this } fun KClass<*>.superTypeDistance(other: KClass<*>): Int? = - other.allSupertypes(false).indexed().firstOrNull { (_, it) -> it == this }?.index + other.allSupertypes( + false, + ).indexed().firstOrNull { (_, it) -> it == this }?.index -infix fun KClass<*>.isSubtypeOf(other: KClass<*>): Boolean = - isSubtypeOf(other, false) +infix fun KClass<*>.isSubtypeOf(other: KClass<*>): Boolean = isSubtypeOf(other, false) -fun KClass<*>.isSubtypeOf(other: KClass<*>, strict: Boolean): Boolean = - other.isSupertypeOf(this, strict) +fun KClass<*>.isSubtypeOf( + other: KClass<*>, + strict: Boolean, +): Boolean = other.isSupertypeOf(this, strict) fun KClass<*>.subTypeDistance(other: KClass<*>): Int? = other.superTypeDistance(this) -internal fun Any.invoke(objectConverter: TermToObjectConverter, methodName: String, arguments: List): Result = - this::class.invoke(objectConverter, methodName, arguments, this) +internal fun Any.invoke( + objectConverter: TermToObjectConverter, + methodName: String, + arguments: List, +): Result = this::class.invoke(objectConverter, methodName, arguments, this) private fun KCallable<*>.ensureArgumentsListIsOfSize(actualArguments: List): List> { return formalParameterTypes.also { formalArgumentsTypes -> @@ -92,7 +109,7 @@ internal fun KClass<*>.invoke( objectConverter: TermToObjectConverter, methodName: String, arguments: List, - instance: Any? + instance: Any?, ): Result { val methodRef = OverloadSelector.of(this, objectConverter).findMethod(methodName, arguments) return methodRef.callWithPrologArguments(objectConverter, arguments, instance) @@ -101,26 +118,30 @@ internal fun KClass<*>.invoke( private fun KCallable<*>.callWithPrologArguments( converter: TermToObjectConverter, arguments: List, - instance: Any? = null + instance: Any? = null, ): Result { val formalArgumentsTypes = ensureArgumentsListIsOfSize(arguments) - val args = arguments.mapIndexed { i, it -> - converter.convertInto(formalArgumentsTypes[i], it) - }.toTypedArray() + val args = + arguments.mapIndexed { i, it -> + converter.convertInto(formalArgumentsTypes[i], it) + }.toTypedArray() return catchingPlatformSpecificException(instance) { val result = invoke(instance, *args) Result.Value(result) } } -internal fun Any.assign(objectConverter: TermToObjectConverter, propertyName: String, value: Term): Result = - this::class.assign(objectConverter, propertyName, value, this) +internal fun Any.assign( + objectConverter: TermToObjectConverter, + propertyName: String, + value: Term, +): Result = this::class.assign(objectConverter, propertyName, value, this) internal fun KClass<*>.assign( objectConverter: TermToObjectConverter, propertyName: String, value: Term, - instance: Any? + instance: Any?, ): Result { val setterRef = OverloadSelector.of(this, objectConverter).findProperty(propertyName, value).setterMethod return setterRef.callWithPrologArguments(objectConverter, listOf(value), instance) @@ -128,7 +149,7 @@ internal fun KClass<*>.assign( internal fun KClass<*>.create( objectConverter: TermToObjectConverter, - arguments: List + arguments: List, ): Result { val constructorRef = OverloadSelector.of(this, objectConverter).findConstructor(arguments) return constructorRef.callWithPrologArguments(objectConverter, arguments) diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/ConstructorInvocationException.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/ConstructorInvocationException.kt index 99a5026be..9870b9da6 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/ConstructorInvocationException.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/ConstructorInvocationException.kt @@ -12,20 +12,20 @@ import kotlin.reflect.KClass @Suppress("MemberVisibilityCanBePrivate") class ConstructorInvocationException( val type: KClass<*>, - val admissibleTypes: List>> + val admissibleTypes: List>>, ) : OopException( - "There is no constructor on type ${type.fullName} which accepts " + - "[${admissibleTypes.pretty()}] as formal arguments" -) { + "There is no constructor on type ${type.fullName} which accepts " + + "[${admissibleTypes.pretty()}] as formal arguments", + ) { override fun toLogicError( context: ExecutionContext, - signature: Signature + signature: Signature, ): LogicError { return ExistenceError.of( context, ExistenceError.ObjectType.OOP_CONSTRUCTOR, culprit, - message ?: "" + message ?: "", ) } diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/MalformedAliasException.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/MalformedAliasException.kt index 7782ddab2..de14afdf5 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/MalformedAliasException.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/MalformedAliasException.kt @@ -13,24 +13,23 @@ import it.unibo.tuprolog.solve.libs.oop.primitives.DEALIASING_TEMPLATE @Suppress("MemberVisibilityCanBePrivate") class MalformedAliasException( - val dealiasingExpression: Struct + val dealiasingExpression: Struct, ) : OopException( - "This is not a dealiasing expression `$dealiasingExpression` in the form ${ - DEALIASING_TEMPLATE.format( - prettyExpressions() - ) - }" -) { - + "This is not a dealiasing expression `$dealiasingExpression` in the form ${ + DEALIASING_TEMPLATE.format( + prettyExpressions(), + ) + }", + ) { override fun toLogicError( context: ExecutionContext, - signature: Signature + signature: Signature, ): LogicError { return TypeError.of( context, DEALIASING_EXPRESSION, culprit, - "Error in ${signature.toIndicator()}: ${message?.replaceFirstChar { it.lowercase() }}" + "Error in ${signature.toIndicator()}: ${message?.replaceFirstChar { it.lowercase() }}", ) } diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/MethodInvocationException.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/MethodInvocationException.kt index 27e6014bf..36aac3b6b 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/MethodInvocationException.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/MethodInvocationException.kt @@ -13,20 +13,20 @@ import kotlin.reflect.KClass class MethodInvocationException( val type: KClass<*>, val missingMethodName: String, - val admissibleTypes: List>> + val admissibleTypes: List>>, ) : OopException( - "There is no method on type ${type.fullName} which is named `$missingMethodName` and accepts " + - "[${admissibleTypes.pretty()}] as formal arguments" -) { + "There is no method on type ${type.fullName} which is named `$missingMethodName` and accepts " + + "[${admissibleTypes.pretty()}] as formal arguments", + ) { override fun toLogicError( context: ExecutionContext, - signature: Signature + signature: Signature, ): LogicError { return ExistenceError.of( context, ExistenceError.ObjectType.OOP_METHOD, culprit, - message ?: "" + message ?: "", ) } diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/NoSuchAnAliasException.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/NoSuchAnAliasException.kt index bff706088..249446ad3 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/NoSuchAnAliasException.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/NoSuchAnAliasException.kt @@ -11,11 +11,10 @@ import it.unibo.tuprolog.unify.Unificator.Companion.matches @Suppress("MemberVisibilityCanBePrivate") class NoSuchAnAliasException( - val dealiasingExpression: Struct + val dealiasingExpression: Struct, ) : OopException( - "There exists no reference whose alias is `${dealiasingExpression[0]}`" -) { - + "There exists no reference whose alias is `${dealiasingExpression[0]}`", + ) { init { require(dealiasingExpression matches DEALIASING_TEMPLATE) require(dealiasingExpression[0] is Struct) @@ -25,13 +24,13 @@ class NoSuchAnAliasException( override fun toLogicError( context: ExecutionContext, - signature: Signature + signature: Signature, ): LogicError { return ExistenceError.of( context, ExistenceError.ObjectType.OOP_ALIAS, culprit, - message ?: "" + message ?: "", ) } diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/OopException.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/OopException.kt index 2b7b149bd..0ec01378d 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/OopException.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/OopException.kt @@ -10,13 +10,15 @@ import kotlin.jvm.JvmOverloads import kotlin.reflect.KClass abstract class OopException : TuPrologException { - @JvmOverloads constructor(message: String? = null, cause: Throwable? = null) : super(message, cause) constructor(cause: Throwable?) : super(cause) - abstract fun toLogicError(context: ExecutionContext, signature: Signature): LogicError + abstract fun toLogicError( + context: ExecutionContext, + signature: Signature, + ): LogicError protected abstract val culprit: Term diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/OopRuntimeException.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/OopRuntimeException.kt index 6852bfd7f..8fcb498c9 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/OopRuntimeException.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/OopRuntimeException.kt @@ -13,13 +13,15 @@ import kotlin.reflect.KCallable class OopRuntimeException( private val callable: KCallable<*>, private val receiver: Any?, - inner: Throwable + inner: Throwable, ) : OopException( - inner.message ?: "Unhandled exception of type ${inner::class.fullName} while executing OOP code", - cause = inner -) { - override fun toLogicError(context: ExecutionContext, signature: Signature): LogicError = - SystemError.forUncaughtException(context, this) + inner.message ?: "Unhandled exception of type ${inner::class.fullName} while executing OOP code", + cause = inner, + ) { + override fun toLogicError( + context: ExecutionContext, + signature: Signature, + ): LogicError = SystemError.forUncaughtException(context, this) override val message: String get() = super.message!! @@ -28,11 +30,12 @@ class OopRuntimeException( get() = super.cause!! override val culprit: Term - get() = Atom.of( - if (receiver == null) { - callable.pretty() - } else { - "${receiver::class.fullName}::${callable.pretty()}" - } - ) + get() = + Atom.of( + if (receiver == null) { + callable.pretty() + } else { + "${receiver::class.fullName}::${callable.pretty()}" + }, + ) } diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/PropertyAssignmentException.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/PropertyAssignmentException.kt index 0894ae13d..fcd7c75c8 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/PropertyAssignmentException.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/PropertyAssignmentException.kt @@ -13,21 +13,20 @@ import kotlin.reflect.KClass class PropertyAssignmentException( val type: KClass<*>, val missingPropertyName: String, - val admissibleTypes: Set> + val admissibleTypes: Set>, ) : OopException( - "There is no property on type ${type.fullName} which is named `$missingPropertyName` and can be " + - "assigned to a value of type ${admissibleTypes.pretty()}" -) { - + "There is no property on type ${type.fullName} which is named `$missingPropertyName` and can be " + + "assigned to a value of type ${admissibleTypes.pretty()}", + ) { override fun toLogicError( context: ExecutionContext, - signature: Signature + signature: Signature, ): LogicError { return ExistenceError.of( context, ExistenceError.ObjectType.OOP_PROPERTY, culprit, - message ?: "" + message ?: "", ) } diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/RuntimePermissionException.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/RuntimePermissionException.kt index 47c976636..2c9378842 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/RuntimePermissionException.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/RuntimePermissionException.kt @@ -14,35 +14,36 @@ import kotlin.reflect.KCallable class RuntimePermissionException( val callable: KCallable<*>, val receiver: Any?, - cause: Throwable? = null + cause: Throwable? = null, ) : OopException( - "Invoking method ${callable.pretty()}" + if (receiver != null) { - " on object `$receiver` of type `${receiver::class.fullName} " - } else { - " " - } + "is not permitted", - cause -) { - + "Invoking method ${callable.pretty()}" + + if (receiver != null) { + " on object `$receiver` of type `${receiver::class.fullName} " + } else { + " " + } + "is not permitted", + cause, + ) { override fun toLogicError( context: ExecutionContext, - signature: Signature + signature: Signature, ): LogicError { return PermissionError.of( context, signature, PermissionError.Operation.INVOKE, PermissionError.Permission.OOP_METHOD, - culprit + culprit, ) } override val culprit: Term - get() = Atom.of( - if (receiver == null) { - callable.pretty() - } else { - "${receiver::class.fullName}::${callable.pretty()}" - } - ) + get() = + Atom.of( + if (receiver == null) { + callable.pretty() + } else { + "${receiver::class.fullName}::${callable.pretty()}" + }, + ) } diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/TermToObjectConversionException.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/TermToObjectConversionException.kt index e7f4fa789..fc7f45d5e 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/TermToObjectConversionException.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/exceptions/TermToObjectConversionException.kt @@ -11,20 +11,23 @@ import kotlin.reflect.KClass @Suppress("MemberVisibilityCanBePrivate") class TermToObjectConversionException( val term: Term, - val targetType: KClass<*>? = null + val targetType: KClass<*>? = null, ) : OopException( - targetType?.let { - "Term `$term` cannot be converted into an object of type ${targetType.fullName}" - } ?: "Term `$term` cannot be converted into an object" -) { + targetType?.let { + "Term `$term` cannot be converted into an object of type ${targetType.fullName}" + } ?: "Term `$term` cannot be converted into an object", + ) { constructor(term: Term) : this(term, null) - override fun toLogicError(context: ExecutionContext, signature: Signature): LogicError { + override fun toLogicError( + context: ExecutionContext, + signature: Signature, + ): LogicError { return RepresentationError.of( context, signature, RepresentationError.Limit.OOP_OBJECT, - this + this, ) } diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/NullRefImpl.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/NullRefImpl.kt index b19ab697a..a0101cdbc 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/NullRefImpl.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/NullRefImpl.kt @@ -26,9 +26,15 @@ internal object NullRefImpl : NullRef, Atom by Atom.of(ObjectRef.nameOf(null)) { override fun apply(substitution: Substitution): Term = this - override fun apply(substitution: Substitution, vararg substitutions: Substitution): Term = this - - override fun get(substitution: Substitution, vararg substitutions: Substitution): Term = this + override fun apply( + substitution: Substitution, + vararg substitutions: Substitution, + ): Term = this + + override fun get( + substitution: Substitution, + vararg substitutions: Substitution, + ): Term = this override fun accept(visitor: TermVisitor): T = visitor.visitAtom(this) } diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/ObjectRefImpl.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/ObjectRefImpl.kt index b7629ba51..616952bbb 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/ObjectRefImpl.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/ObjectRefImpl.kt @@ -20,10 +20,17 @@ internal class ObjectRefImpl(override val `object`: Any) : ObjectRef, Atom by At override fun asConstant(): Constant = this - override fun invoke(objectConverter: TermToObjectConverter, methodName: String, arguments: List): Result = - `object`.invoke(objectConverter, methodName, arguments) - - override fun assign(objectConverter: TermToObjectConverter, propertyName: String, value: Term): Boolean { + override fun invoke( + objectConverter: TermToObjectConverter, + methodName: String, + arguments: List, + ): Result = `object`.invoke(objectConverter, methodName, arguments) + + override fun assign( + objectConverter: TermToObjectConverter, + propertyName: String, + value: Term, + ): Boolean { `object`.assign(objectConverter, propertyName, value) return true } @@ -38,9 +45,15 @@ internal class ObjectRefImpl(override val `object`: Any) : ObjectRef, Atom by At override fun apply(substitution: Substitution): Term = this - override fun apply(substitution: Substitution, vararg substitutions: Substitution): Term = this + override fun apply( + substitution: Substitution, + vararg substitutions: Substitution, + ): Term = this - override fun get(substitution: Substitution, vararg substitutions: Substitution): Term = this + override fun get( + substitution: Substitution, + vararg substitutions: Substitution, + ): Term = this override fun accept(visitor: TermVisitor): T = visitor.visitAtom(this) } diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/ObjectToTermConverterImpl.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/ObjectToTermConverterImpl.kt index 16416dc80..85f498924 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/ObjectToTermConverterImpl.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/ObjectToTermConverterImpl.kt @@ -10,7 +10,6 @@ import it.unibo.tuprolog.solve.libs.oop.ObjectToTermConverter import it.unibo.tuprolog.utils.NumberTypeTester internal class ObjectToTermConverterImpl : ObjectToTermConverter { - private val numberTypeTester = NumberTypeTester() override fun convert(source: Any?): Term { @@ -18,10 +17,11 @@ internal class ObjectToTermConverterImpl : ObjectToTermConverter { when (source) { null -> ObjectRef.NULL is String -> Atom.of(source) - is Number -> when { - source.isInteger -> Integer.of(source.toInteger()) - else -> Real.of(source.toDecimal()) - } + is Number -> + when { + source.isInteger -> Integer.of(source.toInteger()) + else -> Real.of(source.toDecimal()) + } is Char -> Atom.of(charArrayOf(source).concatToString()) is Boolean -> Truth.of(source) else -> ObjectRef.of(source) diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/TermToObjectConverterImpl.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/TermToObjectConverterImpl.kt index 29b4ee9bb..a14f2c9bb 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/TermToObjectConverterImpl.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/TermToObjectConverterImpl.kt @@ -27,10 +27,12 @@ import kotlin.reflect.KClass internal class TermToObjectConverterImpl( private val typeFactory: TypeFactory, - private val dealiaser: (Struct) -> Ref? + private val dealiaser: (Struct) -> Ref?, ) : TermToObjectConverter { - - override fun convertInto(type: KClass<*>, term: Term): Any? { + override fun convertInto( + type: KClass<*>, + term: Term, + ): Any? { return when (term) { is NullRef, is Var -> { if (type.isPrimitiveType) { @@ -46,46 +48,51 @@ internal class TermToObjectConverterImpl( throw TermToObjectConversionException(term, type) } } - is Truth -> when { - Boolean::class isSubtypeOf type -> term.isTrue - String::class isSubtypeOf type -> term.value - else -> throw TermToObjectConversionException(term, type) - } - is Atom -> when { - String::class isSubtypeOf type -> term.value - Char::class isSubtypeOf type -> { - if (term.value.length == 1) { - term.value[0] - } else { - throw TermToObjectConversionException(term, type) + is Truth -> + when { + Boolean::class isSubtypeOf type -> term.isTrue + String::class isSubtypeOf type -> term.value + else -> throw TermToObjectConversionException(term, type) + } + is Atom -> + when { + String::class isSubtypeOf type -> term.value + Char::class isSubtypeOf type -> { + if (term.value.length == 1) { + term.value[0] + } else { + throw TermToObjectConversionException(term, type) + } } + else -> throw TermToObjectConversionException(term, type) + } + is Real -> + when { + BigDecimal::class isSubtypeOf type -> term.decimalValue + Double::class isSubtypeOf type -> term.decimalValue.toDouble() + Float::class isSubtypeOf type -> term.decimalValue.toFloat() + else -> throw TermToObjectConversionException(term, type) + } + is Integer -> + when { + BigInteger::class isSubtypeOf type -> term.intValue + Long::class isSubtypeOf type -> term.intValue.toLongExact() + Int::class isSubtypeOf type -> term.intValue.toIntExact() + Short::class isSubtypeOf type -> term.intValue.toShortExact() + Byte::class isSubtypeOf type -> term.intValue.toByteExact() + BigDecimal::class isSubtypeOf type -> term.decimalValue + Double::class isSubtypeOf type -> term.decimalValue.toDouble() + Float::class isSubtypeOf type -> term.decimalValue.toFloat() + else -> throw TermToObjectConversionException(term, type) } - else -> throw TermToObjectConversionException(term, type) - } - is Real -> when { - BigDecimal::class isSubtypeOf type -> term.decimalValue - Double::class isSubtypeOf type -> term.decimalValue.toDouble() - Float::class isSubtypeOf type -> term.decimalValue.toFloat() - else -> throw TermToObjectConversionException(term, type) - } - is Integer -> when { - BigInteger::class isSubtypeOf type -> term.intValue - Long::class isSubtypeOf type -> term.intValue.toLongExact() - Int::class isSubtypeOf type -> term.intValue.toIntExact() - Short::class isSubtypeOf type -> term.intValue.toShortExact() - Byte::class isSubtypeOf type -> term.intValue.toByteExact() - BigDecimal::class isSubtypeOf type -> term.decimalValue - Double::class isSubtypeOf type -> term.decimalValue.toDouble() - Float::class isSubtypeOf type -> term.decimalValue.toFloat() - else -> throw TermToObjectConversionException(term, type) - } is Struct -> when { term matches CAST_TEMPLATE -> explicitConversion(term, term[0], term[1]) - term matches DEALIASING_TEMPLATE -> when (val ref = dealiaser(term)) { - is ObjectRef -> convertInto(type, ref) - else -> throw TermToObjectConversionException(term) - } + term matches DEALIASING_TEMPLATE -> + when (val ref = dealiaser(term)) { + is ObjectRef -> convertInto(type, ref) + else -> throw TermToObjectConversionException(term) + } else -> throw TermToObjectConversionException(term) }.also { if (it != null && !(it::class isSubtypeOf type)) { @@ -96,7 +103,11 @@ internal class TermToObjectConverterImpl( } } - private fun explicitConversion(castExpression: Struct, term: Term, type: Term): Any? { + private fun explicitConversion( + castExpression: Struct, + term: Term, + type: Term, + ): Any? { val targetType = getType(castExpression, type) try { return convertInto(targetType, term) @@ -107,28 +118,38 @@ internal class TermToObjectConverterImpl( } } - private fun getType(castExpression: Struct, typeTerm: Term): KClass<*> = + private fun getType( + castExpression: Struct, + typeTerm: Term, + ): KClass<*> = when (typeTerm) { is TypeRef -> typeTerm.type is Atom -> { typeFactory.typeFromName(typeTerm.value) ?: throw TermToObjectConversionException(castExpression) } - is Struct -> when { - typeTerm matches DEALIASING_TEMPLATE -> when (val ref = dealiaser(typeTerm)) { - is TypeRef -> ref.type + is Struct -> + when { + typeTerm matches DEALIASING_TEMPLATE -> + when (val ref = dealiaser(typeTerm)) { + is TypeRef -> ref.type + else -> throw TermToObjectConversionException(castExpression) + } else -> throw TermToObjectConversionException(castExpression) } - else -> throw TermToObjectConversionException(castExpression) - } else -> throw TermToObjectConversionException(castExpression) } override fun possibleConversions(term: Term): Sequence = - admissibleTypes(term).asSequence().map { convertInto(it, term) } + admissibleTypes(term).asSequence().map { + convertInto(it, term) + } override fun mostAdequateType(term: Term): KClass<*> = admissibleTypesByPriority(term).first() - override fun priorityOfConversion(type: KClass<*>, term: Term): Int? = + override fun priorityOfConversion( + type: KClass<*>, + term: Term, + ): Int? = admissibleTypes(term).asSequence() .map { type.subTypeDistance(it) } .indexed() @@ -172,14 +193,16 @@ internal class TermToObjectConverterImpl( } admissible } - is Struct -> when { - term matches CAST_TEMPLATE -> sequenceOf(getType(term, term[1])) - term matches DEALIASING_TEMPLATE -> when (val ref = dealiaser(term)) { - is ObjectRef -> admissibleTypesByPriority(ref) + is Struct -> + when { + term matches CAST_TEMPLATE -> sequenceOf(getType(term, term[1])) + term matches DEALIASING_TEMPLATE -> + when (val ref = dealiaser(term)) { + is ObjectRef -> admissibleTypesByPriority(ref) + else -> throw TermToObjectConversionException(term) + } else -> throw TermToObjectConversionException(term) } - else -> throw TermToObjectConversionException(term) - } else -> throw TermToObjectConversionException(term) } } diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/TypeRefImpl.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/TypeRefImpl.kt index 4dd940ae3..3a5f98e2a 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/TypeRefImpl.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/TypeRefImpl.kt @@ -23,11 +23,18 @@ internal class TypeRefImpl(override val type: KClass<*>) : TypeRef, Atom by Atom private fun nameOf(type: KClass<*>): String = "" } - override fun create(objectConverter: TermToObjectConverter, arguments: List): Result { + override fun create( + objectConverter: TermToObjectConverter, + arguments: List, + ): Result { return type.create(objectConverter, arguments) } - override fun invoke(objectConverter: TermToObjectConverter, methodName: String, arguments: List): Result = + override fun invoke( + objectConverter: TermToObjectConverter, + methodName: String, + arguments: List, + ): Result = when (val companionObjectRef = type.companionObjectRef) { is Optional.Some -> companionObjectRef.value.invoke(objectConverter, methodName, arguments) else -> type.invoke(objectConverter, methodName, arguments, null) @@ -48,13 +55,23 @@ internal class TypeRefImpl(override val type: KClass<*>) : TypeRef, Atom by Atom override fun apply(substitution: Substitution): Term = this - override fun apply(substitution: Substitution, vararg substitutions: Substitution): Term = this + override fun apply( + substitution: Substitution, + vararg substitutions: Substitution, + ): Term = this - override fun get(substitution: Substitution, vararg substitutions: Substitution): Term = this + override fun get( + substitution: Substitution, + vararg substitutions: Substitution, + ): Term = this override fun accept(visitor: TermVisitor): T = visitor.visitAtom(this) - override fun assign(objectConverter: TermToObjectConverter, propertyName: String, value: Term): Boolean { + override fun assign( + objectConverter: TermToObjectConverter, + propertyName: String, + value: Term, + ): Boolean { when (val companionObjectRef = type.companionObjectRef) { is Optional.Some -> companionObjectRef.value.assign(objectConverter, propertyName, value) else -> type.assign(objectConverter, propertyName, value, null) diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/AbstractInvoke.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/AbstractInvoke.kt index 1f401caf4..b404bf9dd 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/AbstractInvoke.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/AbstractInvoke.kt @@ -10,11 +10,10 @@ import it.unibo.tuprolog.solve.primitive.Solve import it.unibo.tuprolog.solve.primitive.TernaryRelation abstract class AbstractInvoke(suffix: String) : TernaryRelation.Functional("invoke_$suffix") { - override fun Solve.Request.computeOneSubstitution( first: Term, second: Term, - third: Term + third: Term, ): Substitution { ensuringArgumentIsStruct(0) ensuringArgumentIsStruct(1) @@ -35,7 +34,11 @@ abstract class AbstractInvoke(suffix: String) : TernaryRelation.Functional.actuallyInvoke(ref: Ref, method: Struct, resultTerm: Term): Substitution { + private fun Solve.Request.actuallyInvoke( + ref: Ref, + method: Struct, + resultTerm: Term, + ): Substitution { return when (val result = ref.invoke(termToObjectConverter, method.functor, method.args)) { is Result.Value -> mgu(resultTerm, result.getInvocationResult()) else -> Substitution.failed() diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/AbstractIterableItems.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/AbstractIterableItems.kt index 0f6f658c5..4c2da8745 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/AbstractIterableItems.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/AbstractIterableItems.kt @@ -14,14 +14,16 @@ import kotlin.reflect.KClass abstract class AbstractIterableItems(iterable: String, private val target: KClass) : BinaryRelation.Functional("${iterable}_items") { - protected abstract fun Sequence.toIterable(): T protected abstract val Any?.isIterable: Boolean protected abstract val T.items: Sequence - override fun Solve.Request.computeOneSubstitution(first: Term, second: Term): Substitution = + override fun Solve.Request.computeOneSubstitution( + first: Term, + second: Term, + ): Substitution = when { first is Var && second is Var -> ensuringAllArgumentsAreInstantiated().let { Substitution.failed() } @@ -35,9 +37,10 @@ abstract class AbstractIterableItems(iterable: String, private val targ val obj = first.`object` if (obj.isIterable) { @Suppress("UNCHECKED_CAST") - val items = (obj as T).items.map { - ObjectToTermConverter.default.convert(it) - } + val items = + (obj as T).items.map { + ObjectToTermConverter.default.convert(it) + } mgu(second, List.of(items)) } else { Substitution.failed() diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/Assign.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/Assign.kt index bedf5438a..f7dd8fdc1 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/Assign.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/Assign.kt @@ -9,26 +9,27 @@ import it.unibo.tuprolog.solve.primitive.Solve import it.unibo.tuprolog.solve.primitive.TernaryRelation object Assign : TernaryRelation.Predicative("assign") { - override fun Solve.Request.compute( first: Term, second: Term, - third: Term + third: Term, ): Boolean { ensuringArgumentIsAtom(0) ensuringArgumentIsAtom(1) return catchingOopExceptions { - val ref = when (first) { - is Ref -> first - else -> findRefFromAlias(first as Atom) - } + val ref = + when (first) { + is Ref -> first + else -> findRefFromAlias(first as Atom) + } - val value = if (match(third, DEALIASING_TEMPLATE)) { - findRefFromAlias(third as Struct) - } else { - third - } + val value = + if (match(third, DEALIASING_TEMPLATE)) { + findRefFromAlias(third as Struct) + } else { + third + } ref.assign(termToObjectConverter, (second as Atom).value, value) } diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/Cast.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/Cast.kt index 0422f1efe..2ff3677f9 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/Cast.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/Cast.kt @@ -15,7 +15,11 @@ import it.unibo.tuprolog.solve.primitive.TernaryRelation import kotlin.reflect.KClass object Cast : TernaryRelation("cast") { - override fun Request.computeAll(first: Term, second: Term, third: Term): Sequence = + override fun Request.computeAll( + first: Term, + second: Term, + third: Term, + ): Sequence = catchingOopExceptions { when (second) { is Struct -> { @@ -42,7 +46,11 @@ object Cast : TernaryRelation("cast") { } } - private fun Request.cast(term: Term, type: KClass<*>?, result: Term): Substitution = + private fun Request.cast( + term: Term, + type: KClass<*>?, + result: Term, + ): Substitution = if (type == null) { Substitution.failed() } else { diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/NewObject3.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/NewObject3.kt index 873a7477a..17d2fa713 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/NewObject3.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/NewObject3.kt @@ -8,11 +8,10 @@ import it.unibo.tuprolog.solve.primitive.Solve import it.unibo.tuprolog.solve.primitive.TernaryRelation object NewObject3 : TernaryRelation.Functional("new_object") { - override fun Solve.Request.computeOneSubstitution( first: Term, second: Term, - third: Term + third: Term, ): Substitution { ensuringArgumentIsStruct(0) ensuringArgumentIsList(1) diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/PrimitiveExtensions.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/PrimitiveExtensions.kt index 4f9a92bef..581f61146 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/PrimitiveExtensions.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/PrimitiveExtensions.kt @@ -54,7 +54,7 @@ fun Solve.Request.ensuringArgumentIsObjectRef(index: I signature, TypeError.Expected.OBJECT_REFERENCE, arg, - index + index, ) else -> this } @@ -69,7 +69,7 @@ fun Solve.Request.ensuringArgumentIsTypeRef(index: Int signature, TypeError.Expected.TYPE_REFERENCE, arg, - index + index, ) else -> this } @@ -96,13 +96,14 @@ fun Solve.Request.getArgumentAsTypeRef(index: Int): Ty } private fun Solve.Request.findRefFromAliasOrNull(alias: Struct): Ref? { - val actualAlias = if (isDealiasingExpression(alias)) { - alias[0] as Struct - } else { - throw MalformedAliasException(alias) - } + val actualAlias = + if (isDealiasingExpression(alias)) { + alias[0] as Struct + } else { + throw MalformedAliasException(alias) + } - @Suppress("LocalVariableName") + @Suppress("LocalVariableName", "ktlint:standard:property-naming") val ActualRef = Var.of("ActualRef") return solve(Struct.of(Alias.FUNCTOR, actualAlias, ActualRef)) .filterIsInstance() diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/Register.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/Register.kt index 168ae56f8..ebeb334ee 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/Register.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/Register.kt @@ -10,7 +10,10 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object Register : BinaryRelation.NonBacktrackable("register") { - override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response { ensuringAllArgumentsAreInstantiated() ensuringArgumentIsRef(0) ensuringArgumentIsStruct(1) diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/Type.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/Type.kt index d40f18494..3e04b6d9e 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/Type.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/primitives/Type.kt @@ -12,31 +12,31 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object Type : BinaryRelation.Functional("type") { - private val typeFactory = TypeFactory.default override fun Solve.Request.computeOneSubstitution( first: Term, - second: Term - ): Substitution = catchingOopExceptions { - when { - first is Var && second is Var -> { - ensuringArgumentIsInstantiated(0) - Substitution.failed() - } - first is Var -> { - ensuringArgumentIsAtom(1) - ensuringArgumentIsTypeRef(1) - mgu(first, Atom.of((second as TypeRef).type.name)) - } - second is Var -> { - ensuringArgumentIsAtom(0) - typeFactory.typeRefFromName((first as Atom).value)?.let { mgu(it, second) } ?: Substitution.failed() - } - else -> { - ensuringArgumentIsAtom(0) - Substitution.failed() + second: Term, + ): Substitution = + catchingOopExceptions { + when { + first is Var && second is Var -> { + ensuringArgumentIsInstantiated(0) + Substitution.failed() + } + first is Var -> { + ensuringArgumentIsAtom(1) + ensuringArgumentIsTypeRef(1) + mgu(first, Atom.of((second as TypeRef).type.name)) + } + second is Var -> { + ensuringArgumentIsAtom(0) + typeFactory.typeRefFromName((first as Atom).value)?.let { mgu(it, second) } ?: Substitution.failed() + } + else -> { + ensuringArgumentIsAtom(0) + Substitution.failed() + } } } - } } diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/Alias.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/Alias.kt index 93194478f..d2e2fba15 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/Alias.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/Alias.kt @@ -13,13 +13,21 @@ import it.unibo.tuprolog.solve.rule.RuleWrapper import kotlin.reflect.KClass class Alias private constructor(val alias: Struct, val ref: Ref) : RuleWrapper(FUNCTOR, 2) { - companion object { - fun forObject(alias: String, `object`: Any?) = Alias(Atom.of(alias), ObjectRef.of(`object`)) - - fun forType(alias: String, type: KClass<*>) = Alias(Atom.of(alias), TypeRef.of(type)) - - fun of(alias: Struct, ref: Ref) = Alias(alias, ref) + fun forObject( + alias: String, + `object`: Any?, + ) = Alias(Atom.of(alias), ObjectRef.of(`object`)) + + fun forType( + alias: String, + type: KClass<*>, + ) = Alias(Atom.of(alias), TypeRef.of(type)) + + fun of( + alias: Struct, + ref: Ref, + ) = Alias(alias, ref) const val FUNCTOR = OOP.ALIAS_FUNCTOR } diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/ColonEquals.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/ColonEquals.kt index 2298fecd0..fdfc2505d 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/ColonEquals.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/ColonEquals.kt @@ -18,9 +18,7 @@ import it.unibo.tuprolog.solve.libs.oop.primitives.Cast as CastPrimitive * ``` */ sealed class ColonEquals : RuleWrapper(CALL_OPERATOR, 2) { - object Cast : ColonEquals() { - private val R by variables private val X by variables private val Y by variables @@ -30,16 +28,16 @@ sealed class ColonEquals : RuleWrapper(CALL_OPERATOR, 2) { get() = ktListOf(R, structOf(CAST_OPERATOR, X, T)) override val Scope.body: Term - get() = tupleOf( - structOf(Var.functor, R), - atomOf("!"), - structOf(FluentReduce.FUNCTOR, X, Y), - structOf(CastPrimitive.functor, Y, T, R) - ) + get() = + tupleOf( + structOf(Var.functor, R), + atomOf("!"), + structOf(FluentReduce.FUNCTOR, X, Y), + structOf(CastPrimitive.functor, Y, T, R), + ) } object Invocation : ColonEquals() { - private val R by variables private val M by variables @@ -47,11 +45,12 @@ sealed class ColonEquals : RuleWrapper(CALL_OPERATOR, 2) { get() = kotlin.collections.listOf(R, M) override val Scope.body: Term - get() = tupleOf( - structOf(Var.functor, R), - atomOf("!"), - structOf(FluentReduce.FUNCTOR, M, R) - ) + get() = + tupleOf( + structOf(Var.functor, R), + atomOf("!"), + structOf(FluentReduce.FUNCTOR, M, R), + ) } object Assignment : ColonEquals() { @@ -64,9 +63,10 @@ sealed class ColonEquals : RuleWrapper(CALL_OPERATOR, 2) { get() = kotlin.collections.listOf(C, V) override val Scope.body: Term - get() = tupleOf( - structOf(PropertyReduce.FUNCTOR, C, R, P), - structOf(Assign.functor, R, P, V) - ) + get() = + tupleOf( + structOf(PropertyReduce.FUNCTOR, C, R, P), + structOf(Assign.functor, R, P, V), + ) } } diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/Dot.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/Dot.kt index b3ff1f61d..890d510db 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/Dot.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/Dot.kt @@ -13,15 +13,15 @@ import it.unibo.tuprolog.solve.rule.RuleWrapper * */ object Dot : RuleWrapper(ACCESS_OPERATOR, 2) { - private val Method by variables private val Ref by variables override val Scope.head: List - get() = kotlin.collections.listOf( - Ref, - Method - ) + get() = + kotlin.collections.listOf( + Ref, + Method, + ) override val Scope.body: Term get() = structOf(FluentReduce.FUNCTOR, consOf(Ref, Method), `_`) diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/FluentReduce.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/FluentReduce.kt index 64357a72f..c8cffe5dc 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/FluentReduce.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/FluentReduce.kt @@ -27,28 +27,28 @@ sealed class FluentReduce : RuleWrapper(FUNCTOR, ARITY) { get() = atomOf("!") object Recursive : FluentReduce() { - private val P by variables private val M by variables private val P1 by variables private val X by variables override val Scope.head: List - get() = kotlin.collections.listOf( - listFrom(P, M, last = X), - R - ) + get() = + kotlin.collections.listOf( + listFrom(P, M, last = X), + R, + ) override val Scope.body: Term - get() = tupleOf( - atomOf("!"), - structOf(InvokeMethod.functor, P, M, P1), - structOf(FUNCTOR, consOf(P1, X), R) - ) + get() = + tupleOf( + atomOf("!"), + structOf(InvokeMethod.functor, P, M, P1), + structOf(FUNCTOR, consOf(P1, X), R), + ) } object Couple : FluentReduce() { - private val P by variables private val M by variables @@ -56,10 +56,11 @@ sealed class FluentReduce : RuleWrapper(FUNCTOR, ARITY) { get() = kotlin.collections.listOf(consOf(P, M), R) override val Scope.body: Term - get() = tupleOf( - atomOf("!"), - structOf(InvokeMethod.functor, P, M, R) - ) + get() = + tupleOf( + atomOf("!"), + structOf(InvokeMethod.functor, P, M, R), + ) } // object Base : FluentReduce() { diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/NewObject2.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/NewObject2.kt index bd9f096b7..aaf79889b 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/NewObject2.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/NewObject2.kt @@ -7,7 +7,6 @@ import it.unibo.tuprolog.solve.libs.oop.primitives.NewObject3 import it.unibo.tuprolog.solve.rule.RuleWrapper object NewObject2 : RuleWrapper(NewObject3.functor, 2) { - private val Type by variables private val Instance by variables diff --git a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/PropertyReduce.kt b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/PropertyReduce.kt index f68f17525..b32f7318c 100644 --- a/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/PropertyReduce.kt +++ b/oop-lib/src/commonMain/kotlin/it/unibo/tuprolog/solve/libs/oop/rules/PropertyReduce.kt @@ -26,7 +26,6 @@ sealed class PropertyReduce : RuleWrapper(FUNCTOR, ARITY) { get() = atomOf("!") object Recursive : PropertyReduce() { - private val B1 by variables private val C by variables private val O by variables @@ -36,11 +35,12 @@ sealed class PropertyReduce : RuleWrapper(FUNCTOR, ARITY) { get() = kotlin.collections.listOf(listFrom(A, B, last = C), O, P) override val Scope.body: Term - get() = tupleOf( - atomOf("!"), - structOf(InvokeMethod.functor, A, B, B1), - structOf(FUNCTOR, consOf(B1, C), O, P) - ) + get() = + tupleOf( + atomOf("!"), + structOf(InvokeMethod.functor, A, B, B1), + structOf(FUNCTOR, consOf(B1, C), O, P), + ) } object Base : PropertyReduce() { diff --git a/oop-lib/src/jsMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TypeUtilsJs.kt b/oop-lib/src/jsMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TypeUtilsJs.kt index e59d9aafe..06021dda3 100644 --- a/oop-lib/src/jsMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TypeUtilsJs.kt +++ b/oop-lib/src/jsMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TypeUtilsJs.kt @@ -8,6 +8,8 @@ import kotlin.reflect.KMutableProperty private val TODO_EXCEPTION = NotImplementedError("OOP-Prolog integration is still not supported on JS") +private const val HEX_RADIX = 16 + actual val KClass<*>.companionObjectRef: Optional get() = Optional.none() @@ -35,17 +37,17 @@ actual fun kClassFromName(qualifiedName: String): Optional> { } } -private val classNamePattern = "^($id):($id(\\.$id)*)$".toRegex() +private val classNamePattern = "^($ID):($ID(\\.$ID)*)$".toRegex() actual val CLASS_NAME_PATTERN: Regex get() = classNamePattern actual val Any.identifier: String - get() = identifier.hashCode().toString(16) + get() = identifier.hashCode().toString(HEX_RADIX) internal actual fun KCallable<*>.catchingPlatformSpecificException( instance: Any?, - action: () -> T + action: () -> T, ): T = action() actual fun KClass<*>.allSupertypes(strict: Boolean): Sequence> = throw TODO_EXCEPTION @@ -61,10 +63,15 @@ actual val KClass<*>.name: String actual fun KCallable<*>.pretty(): String = throw TODO_EXCEPTION -actual fun KCallable.invoke(instance: Any?, vararg args: Any?): T = throw TODO_EXCEPTION +actual fun KCallable.invoke( + instance: Any?, + vararg args: Any?, +): T = throw TODO_EXCEPTION actual val KMutableProperty.setterMethod: KFunction get() = throw TODO_EXCEPTION -actual fun overloadSelector(type: KClass<*>, termToObjectConverter: TermToObjectConverter): OverloadSelector = - throw TODO_EXCEPTION +actual fun overloadSelector( + type: KClass<*>, + termToObjectConverter: TermToObjectConverter, +): OverloadSelector = throw TODO_EXCEPTION diff --git a/oop-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/oop/Aliases.kt b/oop-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/oop/Aliases.kt index 05a78df6c..0179af3e6 100644 --- a/oop-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/oop/Aliases.kt +++ b/oop-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/oop/Aliases.kt @@ -3,10 +3,11 @@ package it.unibo.tuprolog.solve.libs.oop import it.unibo.tuprolog.solve.libs.oop.rules.Alias internal actual val platformSpecificAliases: Array - get() = arrayOf( - Alias.forType("system", System::class), - Alias.forType("math", Math::class), - Alias.forObject("stdout", System.out), - Alias.forObject("stderr", System.err), - Alias.forObject("stdin", System.`in`) - ) + get() = + arrayOf( + Alias.forType("system", System::class), + Alias.forType("math", Math::class), + Alias.forObject("stdout", System.out), + Alias.forObject("stderr", System.err), + Alias.forObject("stdin", System.`in`), + ) diff --git a/oop-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/oop/KotlinToJavaTypeMap.kt b/oop-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/oop/KotlinToJavaTypeMap.kt index 00d8a5d4e..cdd24d17e 100644 --- a/oop-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/oop/KotlinToJavaTypeMap.kt +++ b/oop-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/oop/KotlinToJavaTypeMap.kt @@ -3,36 +3,39 @@ package it.unibo.tuprolog.solve.libs.oop import java.util.TreeMap import kotlin.reflect.KClass -private val map = TreeMap>().also { tree -> - listOf( - Any::class, - String::class, - CharSequence::class, - Throwable::class, - Cloneable::class, - Number::class, - Comparable::class, - Enum::class, - Annotation::class, - Iterable::class, - Iterator::class, - Collection::class, - List::class, - Set::class, - ListIterator::class, - Map::class, - Map.Entry::class, - Boolean::class, - Char::class, - Byte::class, - Short::class, - Int::class, - Float::class, - Long::class, - Double::class, - Nothing::class - ).forEach { tree[it.qualifiedName!!] = it } -} +private val map = + TreeMap>().also { tree -> + listOf( + Any::class, + String::class, + CharSequence::class, + Throwable::class, + Cloneable::class, + Number::class, + Comparable::class, + Enum::class, + Annotation::class, + Iterable::class, + Iterator::class, + Collection::class, + List::class, + Set::class, + ListIterator::class, + Map::class, + Map.Entry::class, + Boolean::class, + Char::class, + Byte::class, + Short::class, + Int::class, + Float::class, + Long::class, + Double::class, + Nothing::class, + ).map { (it.qualifiedName ?: error("Reflection issue with $it")) to it }.forEach { (name, klass) -> + tree[name] = klass + } + } internal object KotlinToJavaTypeMap : Map> by map { override fun toString(): String = map.toString() diff --git a/oop-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TypeUtilsJvm.kt b/oop-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TypeUtilsJvm.kt index 32c6f4f1b..36eafb921 100644 --- a/oop-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TypeUtilsJvm.kt +++ b/oop-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/oop/TypeUtilsJvm.kt @@ -1,3 +1,5 @@ +@file:Suppress("TooManyFunctions") + package it.unibo.tuprolog.solve.libs.oop import it.unibo.tuprolog.solve.libs.oop.exceptions.OopRuntimeException @@ -23,16 +25,20 @@ actual val KClass<*>.companionObjectRef: Optional get() = Optional.of(objectInstance ?: companionObjectInstance) actual val KClass<*>.companionObjectType: Optional> - get() = Optional.of( - if (objectInstance != null) { - this - } else { - companionObject - } - ) + get() = + Optional.of( + if (objectInstance != null) { + this + } else { + companionObject + }, + ) -private val classCache = Cache.simpleLru>>(32) +private const val DEFAULT_CACHE_SIZE = 32 +private val classCache = Cache.simpleLru>>(DEFAULT_CACHE_SIZE) + +@Suppress("ReturnCount") actual fun kClassFromName(qualifiedName: String): Optional> { require(CLASS_NAME_PATTERN.matches(qualifiedName)) { "`$qualifiedName` must match ${CLASS_NAME_PATTERN.pattern} while it doesn't" @@ -40,6 +46,7 @@ actual fun kClassFromName(qualifiedName: String): Optional> { return classCache.getOrSet(qualifiedName) { kClassFromNameImpl(qualifiedName) } } +@Suppress("ReturnCount") private fun kClassFromNameImpl(qualifiedName: String): Optional> { val kotlinKlass = KotlinToJavaTypeMap[qualifiedName] return if (kotlinKlass != null) { @@ -57,11 +64,15 @@ private fun kClassFromNameImpl(qualifiedName: String): Optional> { } } -private fun String.replaceAt(index: Int, char: Char): String { - if (index < 0 || index >= length) throw IndexOutOfBoundsException() +private fun String.replaceAt( + index: Int, + char: Char, +): String { + if (index < 0 || index >= length) throw IndexOutOfBoundsException("Index out of bounds: $index") return substring(0, index) + char + substring(index + 1) } +@Suppress("SwallowedException") private fun javaClassForName(qualifiedName: String): Class<*>? = try { Class.forName(qualifiedName) @@ -69,26 +80,28 @@ private fun javaClassForName(qualifiedName: String): Class<*>? = null } -private val classNamePattern = "^$id(\\.$id(\\$$id)*)*$".toRegex() +private val classNamePattern = "^$ID(\\.$ID(\\$$ID)*)*$".toRegex() actual val CLASS_NAME_PATTERN: Regex get() = classNamePattern +@Suppress("MagicNumber") actual val Any.identifier: String get() = System.identityHashCode(this).toString(16) internal actual fun KCallable<*>.catchingPlatformSpecificException( instance: Any?, - action: () -> T -): T = try { - action() -} catch (e: IllegalCallableAccessException) { - throw RuntimePermissionException(this, instance, e) -} catch (e: InvocationTargetException) { - throw OopRuntimeException(this, instance, e.targetException ?: e.cause ?: e) -} catch (e: IllegalArgumentException) { - throw OopRuntimeException(this, instance, e.cause ?: e) -} + action: () -> T, +): T = + try { + action() + } catch (e: IllegalCallableAccessException) { + throw RuntimePermissionException(this, instance, e) + } catch (e: InvocationTargetException) { + throw OopRuntimeException(this, instance, e.targetException ?: e.cause ?: e) + } catch (e: IllegalArgumentException) { + throw OopRuntimeException(this, instance, e.cause ?: e) + } actual fun KClass<*>.allSupertypes(strict: Boolean): Sequence> = supertypes.asSequence() @@ -99,18 +112,18 @@ actual fun KClass<*>.allSupertypes(strict: Boolean): Sequence> = .let { if (strict) it else sequenceOf(this) + it } actual val KCallable<*>.formalParameterTypes: List> - get() = parameters.filterNot { it.kind == KParameter.Kind.INSTANCE }.map { - it.type.classifier as? KClass<*> ?: Any::class - } + get() = + parameters.filterNot { it.kind == KParameter.Kind.INSTANCE }.map { + it.type.classifier as? KClass<*> ?: Any::class + } actual val KClass<*>.fullName: String - get() = qualifiedName!! + get() = qualifiedName ?: error("Reflection issue: cannot get qualified name of $this") actual val KClass<*>.name: String - get() = simpleName!! + get() = simpleName ?: error("Reflection issue: cannot get name of $this") -actual fun KCallable<*>.pretty(): String = - "$name(${parameters.map { it.pretty() }}): ${returnType.classifier.pretty()}" +actual fun KCallable<*>.pretty(): String = "$name(${parameters.map { it.pretty() }}): ${returnType.classifier.pretty()}" private fun KClassifier?.pretty(): String = if (this is KClass<*>) { @@ -127,7 +140,10 @@ private fun KParameter.pretty(): String = } @Suppress("UNCHECKED_CAST") -actual fun KCallable.invoke(instance: Any?, vararg args: Any?): T = +actual fun KCallable.invoke( + instance: Any?, + vararg args: Any?, +): T = when (this) { is KProperty0 -> get() is KProperty1<*, T> -> { @@ -150,5 +166,7 @@ actual fun KCallable.invoke(instance: Any?, vararg args: Any?): T = actual val KMutableProperty.setterMethod: KFunction get() = setter -actual fun overloadSelector(type: KClass<*>, termToObjectConverter: TermToObjectConverter): OverloadSelector = - OverloadSelectorImpl(type, termToObjectConverter) +actual fun overloadSelector( + type: KClass<*>, + termToObjectConverter: TermToObjectConverter, +): OverloadSelector = OverloadSelectorImpl(type, termToObjectConverter) diff --git a/oop-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/KotlinTypesHacks.kt b/oop-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/KotlinTypesHacks.kt index 63e890241..bbff1a2bb 100644 --- a/oop-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/KotlinTypesHacks.kt +++ b/oop-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/KotlinTypesHacks.kt @@ -6,9 +6,7 @@ import kotlin.reflect.KCallable import kotlin.reflect.KClass internal object KotlinTypesHacks { - private data class CallableId(val type: KClass<*>, val name: String) : Comparable { - private val stringRepresentation = "${type.fullName}::$name" override fun compareTo(other: CallableId): Int = stringRepresentation.compareTo(other.stringRepresentation) @@ -16,57 +14,61 @@ internal object KotlinTypesHacks { override fun toString(): String = stringRepresentation } - private val typeCallableMap = TreeMap>().also { - it[CallableId(Int.Companion::class, "MAX_VALUE")] = Int.Companion::MAX_VALUE - it[CallableId(Int.Companion::class, "MIN_VALUE")] = Int.Companion::MIN_VALUE - it[CallableId(Int.Companion::class, "SIZE_BITS")] = Int.Companion::SIZE_BITS - it[CallableId(Int.Companion::class, "SIZE_BYTES")] = Int.Companion::SIZE_BYTES + private val typeCallableMap = + TreeMap>().also { + it[CallableId(Int.Companion::class, "MAX_VALUE")] = Int.Companion::MAX_VALUE + it[CallableId(Int.Companion::class, "MIN_VALUE")] = Int.Companion::MIN_VALUE + it[CallableId(Int.Companion::class, "SIZE_BITS")] = Int.Companion::SIZE_BITS + it[CallableId(Int.Companion::class, "SIZE_BYTES")] = Int.Companion::SIZE_BYTES - it[CallableId(Short.Companion::class, "MAX_VALUE")] = Short.Companion::MAX_VALUE - it[CallableId(Short.Companion::class, "MIN_VALUE")] = Short.Companion::MIN_VALUE - it[CallableId(Short.Companion::class, "SIZE_BITS")] = Short.Companion::SIZE_BITS - it[CallableId(Short.Companion::class, "SIZE_BYTES")] = Short.Companion::SIZE_BYTES + it[CallableId(Short.Companion::class, "MAX_VALUE")] = Short.Companion::MAX_VALUE + it[CallableId(Short.Companion::class, "MIN_VALUE")] = Short.Companion::MIN_VALUE + it[CallableId(Short.Companion::class, "SIZE_BITS")] = Short.Companion::SIZE_BITS + it[CallableId(Short.Companion::class, "SIZE_BYTES")] = Short.Companion::SIZE_BYTES - it[CallableId(Long.Companion::class, "MAX_VALUE")] = Long.Companion::MAX_VALUE - it[CallableId(Long.Companion::class, "MIN_VALUE")] = Long.Companion::MIN_VALUE - it[CallableId(Long.Companion::class, "SIZE_BITS")] = Long.Companion::SIZE_BITS - it[CallableId(Long.Companion::class, "SIZE_BYTES")] = Long.Companion::SIZE_BYTES + it[CallableId(Long.Companion::class, "MAX_VALUE")] = Long.Companion::MAX_VALUE + it[CallableId(Long.Companion::class, "MIN_VALUE")] = Long.Companion::MIN_VALUE + it[CallableId(Long.Companion::class, "SIZE_BITS")] = Long.Companion::SIZE_BITS + it[CallableId(Long.Companion::class, "SIZE_BYTES")] = Long.Companion::SIZE_BYTES - it[CallableId(Byte.Companion::class, "MAX_VALUE")] = Byte.Companion::MAX_VALUE - it[CallableId(Byte.Companion::class, "MIN_VALUE")] = Byte.Companion::MIN_VALUE - it[CallableId(Byte.Companion::class, "SIZE_BITS")] = Byte.Companion::SIZE_BITS - it[CallableId(Byte.Companion::class, "SIZE_BYTES")] = Byte.Companion::SIZE_BYTES + it[CallableId(Byte.Companion::class, "MAX_VALUE")] = Byte.Companion::MAX_VALUE + it[CallableId(Byte.Companion::class, "MIN_VALUE")] = Byte.Companion::MIN_VALUE + it[CallableId(Byte.Companion::class, "SIZE_BITS")] = Byte.Companion::SIZE_BITS + it[CallableId(Byte.Companion::class, "SIZE_BYTES")] = Byte.Companion::SIZE_BYTES - it[CallableId(Char.Companion::class, "MAX_VALUE")] = Char.Companion::MAX_VALUE - it[CallableId(Char.Companion::class, "MIN_VALUE")] = Char.Companion::MIN_VALUE - it[CallableId(Char.Companion::class, "SIZE_BITS")] = Char.Companion::SIZE_BITS - it[CallableId(Char.Companion::class, "SIZE_BYTES")] = Char.Companion::SIZE_BYTES - it[CallableId(Char.Companion::class, "MIN_HIGH_SURROGATE")] = Char.Companion::MIN_HIGH_SURROGATE - it[CallableId(Char.Companion::class, "MIN_LOW_SURROGATE")] = Char.Companion::MIN_LOW_SURROGATE - it[CallableId(Char.Companion::class, "MIN_SURROGATE")] = Char.Companion::MIN_SURROGATE - it[CallableId(Char.Companion::class, "MAX_HIGH_SURROGATE")] = Char.Companion::MAX_HIGH_SURROGATE - it[CallableId(Char.Companion::class, "MAX_LOW_SURROGATE")] = Char.Companion::MAX_LOW_SURROGATE - it[CallableId(Char.Companion::class, "MAX_SURROGATE")] = Char.Companion::MAX_SURROGATE + it[CallableId(Char.Companion::class, "MAX_VALUE")] = Char.Companion::MAX_VALUE + it[CallableId(Char.Companion::class, "MIN_VALUE")] = Char.Companion::MIN_VALUE + it[CallableId(Char.Companion::class, "SIZE_BITS")] = Char.Companion::SIZE_BITS + it[CallableId(Char.Companion::class, "SIZE_BYTES")] = Char.Companion::SIZE_BYTES + it[CallableId(Char.Companion::class, "MIN_HIGH_SURROGATE")] = Char.Companion::MIN_HIGH_SURROGATE + it[CallableId(Char.Companion::class, "MIN_LOW_SURROGATE")] = Char.Companion::MIN_LOW_SURROGATE + it[CallableId(Char.Companion::class, "MIN_SURROGATE")] = Char.Companion::MIN_SURROGATE + it[CallableId(Char.Companion::class, "MAX_HIGH_SURROGATE")] = Char.Companion::MAX_HIGH_SURROGATE + it[CallableId(Char.Companion::class, "MAX_LOW_SURROGATE")] = Char.Companion::MAX_LOW_SURROGATE + it[CallableId(Char.Companion::class, "MAX_SURROGATE")] = Char.Companion::MAX_SURROGATE - it[CallableId(Double.Companion::class, "MAX_VALUE")] = Double.Companion::MAX_VALUE - it[CallableId(Double.Companion::class, "MIN_VALUE")] = Double.Companion::MIN_VALUE - it[CallableId(Double.Companion::class, "SIZE_BITS")] = Double.Companion::SIZE_BITS - it[CallableId(Double.Companion::class, "SIZE_BYTES")] = Double.Companion::SIZE_BYTES - it[CallableId(Double.Companion::class, "NEGATIVE_INFINITY")] = Double.Companion::NEGATIVE_INFINITY - it[CallableId(Double.Companion::class, "NaN")] = Double.Companion::NaN - it[CallableId(Double.Companion::class, "POSITIVE_INFINITY")] = Double.Companion::POSITIVE_INFINITY + it[CallableId(Double.Companion::class, "MAX_VALUE")] = Double.Companion::MAX_VALUE + it[CallableId(Double.Companion::class, "MIN_VALUE")] = Double.Companion::MIN_VALUE + it[CallableId(Double.Companion::class, "SIZE_BITS")] = Double.Companion::SIZE_BITS + it[CallableId(Double.Companion::class, "SIZE_BYTES")] = Double.Companion::SIZE_BYTES + it[CallableId(Double.Companion::class, "NEGATIVE_INFINITY")] = Double.Companion::NEGATIVE_INFINITY + it[CallableId(Double.Companion::class, "NaN")] = Double.Companion::NaN + it[CallableId(Double.Companion::class, "POSITIVE_INFINITY")] = Double.Companion::POSITIVE_INFINITY - it[CallableId(Float.Companion::class, "MAX_VALUE")] = Float.Companion::MAX_VALUE - it[CallableId(Float.Companion::class, "MIN_VALUE")] = Float.Companion::MIN_VALUE - it[CallableId(Float.Companion::class, "SIZE_BITS")] = Float.Companion::SIZE_BITS - it[CallableId(Float.Companion::class, "SIZE_BYTES")] = Float.Companion::SIZE_BYTES - it[CallableId(Float.Companion::class, "NEGATIVE_INFINITY")] = Float.Companion::NEGATIVE_INFINITY - it[CallableId(Float.Companion::class, "NaN")] = Float.Companion::NaN - it[CallableId(Float.Companion::class, "POSITIVE_INFINITY")] = Float.Companion::POSITIVE_INFINITY + it[CallableId(Float.Companion::class, "MAX_VALUE")] = Float.Companion::MAX_VALUE + it[CallableId(Float.Companion::class, "MIN_VALUE")] = Float.Companion::MIN_VALUE + it[CallableId(Float.Companion::class, "SIZE_BITS")] = Float.Companion::SIZE_BITS + it[CallableId(Float.Companion::class, "SIZE_BYTES")] = Float.Companion::SIZE_BYTES + it[CallableId(Float.Companion::class, "NEGATIVE_INFINITY")] = Float.Companion::NEGATIVE_INFINITY + it[CallableId(Float.Companion::class, "NaN")] = Float.Companion::NaN + it[CallableId(Float.Companion::class, "POSITIVE_INFINITY")] = Float.Companion::POSITIVE_INFINITY - it[CallableId(String.Companion::class, "CASE_INSENSITIVE_ORDER")] = String.Companion::CASE_INSENSITIVE_ORDER - } + it[CallableId(String.Companion::class, "CASE_INSENSITIVE_ORDER")] = String.Companion::CASE_INSENSITIVE_ORDER + } - operator fun get(type: KClass<*>, name: String, args: List): KCallable<*>? = - if (args.isNotEmpty()) null else typeCallableMap[CallableId(type, name)] + operator fun get( + type: KClass<*>, + name: String, + args: List, + ): KCallable<*>? = if (args.isNotEmpty()) null else typeCallableMap[CallableId(type, name)] } diff --git a/oop-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/OverloadSelectorImpl.kt b/oop-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/OverloadSelectorImpl.kt index 1122b6cf0..bf035902c 100644 --- a/oop-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/OverloadSelectorImpl.kt +++ b/oop-lib/src/jvmMain/kotlin/it/unibo/tuprolog/solve/libs/oop/impl/OverloadSelectorImpl.kt @@ -16,10 +16,13 @@ import kotlin.reflect.KVisibility internal class OverloadSelectorImpl( override val type: KClass<*>, - override val termToObjectConverter: TermToObjectConverter + override val termToObjectConverter: TermToObjectConverter, ) : OverloadSelector { - - override fun findMethod(name: String, arguments: List): KCallable<*> { + @Suppress("SwallowedException") + override fun findMethod( + name: String, + arguments: List, + ): KCallable<*> { KotlinTypesHacks[type, name, arguments]?.let { return it } return try { type.members @@ -28,17 +31,30 @@ internal class OverloadSelectorImpl( .map { it to it.instanceParameters.score(arguments) } .minByOrNull { (_, score) -> score ?: Int.MAX_VALUE } ?.first - ?: throw MethodInvocationException(type, name, arguments.map { termToObjectConverter.admissibleTypes(it) }) + ?: throw MethodInvocationException( + type, name, + arguments.map { + termToObjectConverter.admissibleTypes(it) + }, + ) } catch (e: IllegalStateException) { type.allSupertypes(strict = true) .firstOrNull() ?.let { OverloadSelector.of(it, termToObjectConverter) } ?.findMethod(name, arguments) - ?: throw MethodInvocationException(type, name, arguments.map { termToObjectConverter.admissibleTypes(it) }) + ?: throw MethodInvocationException( + type, name, + arguments.map { + termToObjectConverter.admissibleTypes(it) + }, + ) } } - override fun findProperty(name: String, value: Term): KMutableProperty<*> { + override fun findProperty( + name: String, + value: Term, + ): KMutableProperty<*> { return type.members .filter { it.name == name } .filter { it.visibility == KVisibility.PUBLIC } @@ -61,6 +77,7 @@ internal class OverloadSelectorImpl( ?: throw ConstructorInvocationException(type, arguments.map { termToObjectConverter.admissibleTypes(it) }) } + @Suppress("ReturnCount") private fun List.score(arguments: List): Int? { if (size != arguments.size) return null var score = 0 diff --git a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/A.kt b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/A.kt index 26433dd42..99a388056 100644 --- a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/A.kt +++ b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/A.kt @@ -1,7 +1,6 @@ package it.unibo.tuprolog.solve.libs.oop sealed class A(open val z: String) { - data class B(val x: Int, override val z: String) : A(z) data class C(val y: Long, override val z: String) : A(z) diff --git a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/ConstructorOverloadDetector.kt b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/ConstructorOverloadDetector.kt index ceb9fb33b..dc4c3c263 100644 --- a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/ConstructorOverloadDetector.kt +++ b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/ConstructorOverloadDetector.kt @@ -5,7 +5,6 @@ import org.gciatto.kt.math.BigInteger import kotlin.reflect.KClass class ConstructorOverloadDetector { - val args: Pair> constructor(x: Any) { diff --git a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/Conversions.kt b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/Conversions.kt index 54ed4c555..165b7467f 100644 --- a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/Conversions.kt +++ b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/Conversions.kt @@ -12,19 +12,20 @@ import org.gciatto.kt.math.BigInteger import kotlin.reflect.KClass internal object Conversions { - val bestCases = listOf( - TestDatum(Atom.of("a"), String::class, "a"), - TestDatum(Integer.ONE, BigInteger::class, BigInteger.ONE), - TestDatum(Real.ONE, BigDecimal::class, BigDecimal.ONE), - TestDatum(Truth.TRUE, Boolean::class, true), - TestDatum(Truth.FAIL, Boolean::class, false), - TestDatum(Truth.FALSE, Boolean::class, false), - TestDatum(Var.anonymous(), Any::class, null), - TestDatum(Var.of("X"), Any::class, null), - TestDatum(A.B(1, "a"), Any::class), - TestDatum(A.C(2, "b"), Any::class), - TestDatum(null, Any::class) - ) + val bestCases = + listOf( + TestDatum(Atom.of("a"), String::class, "a"), + TestDatum(Integer.ONE, BigInteger::class, BigInteger.ONE), + TestDatum(Real.ONE, BigDecimal::class, BigDecimal.ONE), + TestDatum(Truth.TRUE, Boolean::class, true), + TestDatum(Truth.FAIL, Boolean::class, false), + TestDatum(Truth.FALSE, Boolean::class, false), + TestDatum(Var.anonymous(), Any::class, null), + TestDatum(Var.of("X"), Any::class, null), + TestDatum(A.B(1, "a"), Any::class), + TestDatum(A.C(2, "b"), Any::class), + TestDatum(null, Any::class), + ) private val higherThanMaxLong = BigInteger.of(Long.MAX_VALUE) + BigInteger.ONE private val lowerThanMinLong = BigInteger.of(Long.MIN_VALUE) - BigInteger.ONE @@ -38,72 +39,234 @@ internal object Conversions { private val higherThanMaxByte = BigInteger.of(Byte.MAX_VALUE.toInt()) + BigInteger.ONE private val lowerThanMinByte = BigInteger.of(Byte.MIN_VALUE.toInt()) - BigInteger.ONE - val explicitCases = listOf( - TestDatum(Atom.of("a"), String::class, "a"), - TestDatum(Atom.of("a"), Char::class, 'a'), - TestDatum(Integer.ONE, BigInteger::class, BigInteger.ONE), - TestDatum(Integer.ONE, BigDecimal::class, BigDecimal.ONE), - TestDatum(Integer.ONE, Int::class, 1), - TestDatum(Integer.ONE, Short::class, 1.toShort()), - TestDatum(Integer.ONE, Long::class, 1.toLong()), - TestDatum(Integer.ONE, Byte::class, 1.toByte()), - TestDatum(Integer.ONE, Double::class, 1.0), - TestDatum(Integer.ONE, Float::class, 1.0f), - TestDatum(Real.ONE, BigDecimal::class, BigDecimal.ONE), - TestDatum(Real.ONE, Float::class, 1.0f), - TestDatum(Real.ONE, Double::class, 1.0), - TestDatum(Truth.TRUE, Boolean::class, true), - TestDatum(Truth.TRUE, String::class, "true"), - TestDatum(Truth.FAIL, Boolean::class, false), - TestDatum(Truth.FAIL, String::class, "fail"), - TestDatum(Truth.FALSE, Boolean::class, false), - TestDatum(Truth.FALSE, String::class, "false"), - TestDatum(Var.anonymous(), Any::class, null), - TestDatum(Var.of("X"), Any::class, null), - TestDatum(A.B(1, "a"), Any::class), - TestDatum(A.C(2, "b"), Any::class), - TestDatum(null, Any::class) - ) + val explicitCases = + listOf( + TestDatum(Atom.of("a"), String::class, "a"), + TestDatum(Atom.of("a"), Char::class, 'a'), + TestDatum(Integer.ONE, BigInteger::class, BigInteger.ONE), + TestDatum(Integer.ONE, BigDecimal::class, BigDecimal.ONE), + TestDatum(Integer.ONE, Int::class, 1), + TestDatum(Integer.ONE, Short::class, 1.toShort()), + TestDatum(Integer.ONE, Long::class, 1.toLong()), + TestDatum(Integer.ONE, Byte::class, 1.toByte()), + TestDatum(Integer.ONE, Double::class, 1.0), + TestDatum(Integer.ONE, Float::class, 1.0f), + TestDatum(Real.ONE, BigDecimal::class, BigDecimal.ONE), + TestDatum(Real.ONE, Float::class, 1.0f), + TestDatum(Real.ONE, Double::class, 1.0), + TestDatum(Truth.TRUE, Boolean::class, true), + TestDatum(Truth.TRUE, String::class, "true"), + TestDatum(Truth.FAIL, Boolean::class, false), + TestDatum(Truth.FAIL, String::class, "fail"), + TestDatum(Truth.FALSE, Boolean::class, false), + TestDatum(Truth.FALSE, String::class, "false"), + TestDatum(Var.anonymous(), Any::class, null), + TestDatum(Var.of("X"), Any::class, null), + TestDatum(A.B(1, "a"), Any::class), + TestDatum(A.C(2, "b"), Any::class), + TestDatum(null, Any::class), + ) - private fun Term.product(vararg types: KClass<*>, datum: (Term, KClass<*>) -> TestDatum): List = - sequenceOf(this).product(sequenceOf(*types)).map { (t, k) -> datum(t, k) }.toList() + private fun Term.product( + vararg types: KClass<*>, + datum: (Term, KClass<*>) -> TestDatum, + ): List = sequenceOf(this).product(sequenceOf(*types)).map { (t, k) -> datum(t, k) }.toList() - val cornerCases: List = - Var.of("X").product(String::class, Char::class, BigInteger::class, BigDecimal::class, Int::class, Short::class, Long::class, Byte::class, Double::class, Float::class) { t, k -> - TestDatum.failed(t, k) - } + Var.anonymous().product(String::class, Char::class, BigInteger::class, BigDecimal::class, Int::class, Short::class, Long::class, Byte::class, Double::class, Float::class) { t, k -> - TestDatum.failed(t, k) - } + ObjectRef.of(A.B(1, "a")).product(String::class, Char::class, BigInteger::class, BigDecimal::class, Int::class, Short::class, Long::class, Byte::class, Double::class, Float::class) { t, k -> - TestDatum.failed(t, k) - } + ObjectRef.of(A.C(2, "b")).product(String::class, Char::class, BigInteger::class, BigDecimal::class, Int::class, Short::class, Long::class, Byte::class, Double::class, Float::class) { t, k -> - TestDatum.failed(t, k) - } + Truth.TRUE.product(Char::class, BigInteger::class, BigDecimal::class, Int::class, Short::class, Long::class, Byte::class, Double::class, Float::class) { t, k -> - TestDatum.failed(t, k) - } + Truth.FAIL.product(Char::class, BigInteger::class, BigDecimal::class, Int::class, Short::class, Long::class, Byte::class, Double::class, Float::class) { t, k -> - TestDatum.failed(t, k) - } + Truth.FALSE.product(Char::class, BigInteger::class, BigDecimal::class, Int::class, Short::class, Long::class, Byte::class, Double::class, Float::class) { t, k -> - TestDatum.failed(t, k) - } + Atom.of("a").product(BigInteger::class, BigDecimal::class, Int::class, Short::class, Long::class, Byte::class, Double::class, Float::class, Boolean::class) { t, k -> - TestDatum.failed(t, k) - } + Atom.of("ab").product(Char::class, BigInteger::class, BigDecimal::class, Int::class, Short::class, Long::class, Byte::class, Double::class, Float::class, Boolean::class) { t, k -> - TestDatum.failed(t, k) - } + Integer.of(higherThanMaxLong).product(String::class, Char::class, Int::class, Short::class, Long::class, Byte::class, Boolean::class) { t, k -> - TestDatum.failed(t, k) - } + Integer.of(lowerThanMinLong).product(String::class, Char::class, Int::class, Short::class, Long::class, Byte::class, Boolean::class) { t, k -> - TestDatum.failed(t, k) - } + Integer.of(higherThanMaxInt).product(String::class, Char::class, Int::class, Short::class, Byte::class, Boolean::class) { t, k -> - TestDatum.failed(t, k) - } + Integer.of(lowerThanMinInt).product(String::class, Char::class, Int::class, Short::class, Byte::class, Boolean::class) { t, k -> - TestDatum.failed(t, k) - } + Integer.of(higherThanMaxShort).product(String::class, Char::class, Short::class, Byte::class, Boolean::class) { t, k -> - TestDatum.failed(t, k) - } + Integer.of(lowerThanMinShort).product(String::class, Char::class, Short::class, Byte::class, Boolean::class) { t, k -> - TestDatum.failed(t, k) - } + Integer.of(higherThanMaxByte).product(String::class, Char::class, Byte::class, Boolean::class) { t, k -> - TestDatum.failed(t, k) - } + Integer.of(lowerThanMinByte).product(String::class, Char::class, Byte::class, Boolean::class) { t, k -> - TestDatum.failed(t, k) - } + Integer.of(0).product(String::class, Char::class, Boolean::class) { t, k -> - TestDatum.failed(t, k) - } + private fun MutableList.cornerCase( + term: Term, + vararg types: KClass<*>, + ) { + addAll(term.product(*types, datum = TestDatum::failed)) + } + + @Suppress("ktlint:standard:multiline-expression-wrapping") + val cornerCases: List = buildList { + cornerCase( + Var.of("X"), + String::class, + Char::class, + BigInteger::class, + BigDecimal::class, + Int::class, + Short::class, + Long::class, + Byte::class, + Double::class, + Float::class, + ) + cornerCase( + Var.anonymous(), + String::class, + Char::class, + BigInteger::class, + BigDecimal::class, + Int::class, + Short::class, + Long::class, + Byte::class, + Double::class, + Float::class, + ) + cornerCase( + ObjectRef.of(A.B(1, "a")), + String::class, + Char::class, + BigInteger::class, + BigDecimal::class, + Int::class, + Short::class, + Long::class, + Byte::class, + Double::class, + Float::class, + ) + cornerCase( + ObjectRef.of(A.C(2, "b")), + String::class, + Char::class, + BigInteger::class, + BigDecimal::class, + Int::class, + Short::class, + Long::class, + Byte::class, + Double::class, + Float::class, + ) + cornerCase( + Truth.TRUE, + Char::class, + BigInteger::class, + BigDecimal::class, + Int::class, + Short::class, + Long::class, + Byte::class, + Double::class, + Float::class, + ) + cornerCase( + Truth.FAIL, + Char::class, + BigInteger::class, + BigDecimal::class, + Int::class, + Short::class, + Long::class, + Byte::class, + Double::class, + Float::class, + ) + cornerCase( + Truth.FALSE, + Char::class, + BigInteger::class, + BigDecimal::class, + Int::class, + Short::class, + Long::class, + Byte::class, + Double::class, + Float::class, + ) + cornerCase( + Atom.of("a"), + BigInteger::class, + BigDecimal::class, + Int::class, + Short::class, + Long::class, + Byte::class, + Double::class, + Float::class, + Boolean::class, + ) + cornerCase( + Atom.of("ab"), + Char::class, + BigInteger::class, + BigDecimal::class, + Int::class, + Short::class, + Long::class, + Byte::class, + Double::class, + Float::class, + Boolean::class, + ) + cornerCase( + Integer.of(higherThanMaxLong), + String::class, + Char::class, + Int::class, + Short::class, + Long::class, + Byte::class, + Boolean::class, + ) + cornerCase( + Integer.of(lowerThanMinLong), + String::class, + Char::class, + Int::class, + Short::class, + Long::class, + Byte::class, + Boolean::class, + ) + cornerCase( + Integer.of(higherThanMaxInt), + String::class, + Char::class, + Int::class, + Short::class, + Byte::class, + Boolean::class, + ) + cornerCase( + Integer.of(lowerThanMinInt), + String::class, + Char::class, + Int::class, + Short::class, + Byte::class, + Boolean::class, + ) + cornerCase( + Integer.of(higherThanMaxShort), + String::class, + Char::class, + Short::class, + Byte::class, + Boolean::class, + ) + cornerCase( + Integer.of(lowerThanMinShort), + String::class, + Char::class, + Short::class, + Byte::class, + Boolean::class, + ) + cornerCase( + Integer.of(higherThanMaxByte), + String::class, + Char::class, + Byte::class, + Boolean::class, + ) + cornerCase( + Integer.of(lowerThanMinByte), + String::class, + Char::class, + Byte::class, + Boolean::class, + ) + cornerCase( + Integer.of(0), + String::class, + Char::class, + Boolean::class, + ) + } } diff --git a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/OverloadDetector.kt b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/OverloadDetector.kt index f139e9d47..75e3a0846 100644 --- a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/OverloadDetector.kt +++ b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/OverloadDetector.kt @@ -9,16 +9,27 @@ interface OverloadDetector { val size: Int fun call(x: Any): String + fun call(x: String): String + fun call(x: Boolean): String + fun call(x: Char): String + fun call(x: Byte): String + fun call(x: Short): String + fun call(x: Int): String + fun call(x: Float): String + fun call(x: Long): String + fun call(x: Double): String + fun call(x: BigInteger): String + fun call(x: BigDecimal): String fun toList(): List diff --git a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestAlias.kt b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestAlias.kt index 3a3740103..1cb178546 100644 --- a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestAlias.kt +++ b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestAlias.kt @@ -5,8 +5,7 @@ import it.unibo.tuprolog.solve.SolverTest interface TestAlias : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestAlias = - TestAliasImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestAlias = TestAliasImpl(solverFactory) } fun testDefaultAliases() diff --git a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestAliasImpl.kt b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestAliasImpl.kt index f7465d428..4dd4473dd 100644 --- a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestAliasImpl.kt +++ b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestAliasImpl.kt @@ -23,13 +23,13 @@ import kotlin.reflect.KClass import kotlin.test.assertTrue class TestAliasImpl(private val solverFactory: SolverFactory) : TestAlias { - private fun aliasesByObject(obj: Any?): List { - val ref = when (obj) { - is KClass<*> -> TypeRef.of(obj) - null -> ObjectRef.NULL - else -> ObjectRef.of(obj) - } + val ref = + when (obj) { + is KClass<*> -> TypeRef.of(obj) + null -> ObjectRef.NULL + else -> ObjectRef.of(obj) + } return OOPLib.clauses.asSequence() .filterIsInstance() .filter { it.head matches Struct.of(Alias.FUNCTOR, Var.anonymous(), ref) } @@ -39,32 +39,40 @@ class TestAliasImpl(private val solverFactory: SolverFactory) : TestAlias { .toList() } - private fun assertAliasIsPresent(solver: Solver, alias: String, type: KClass<*>) { + private fun assertAliasIsPresent( + solver: Solver, + alias: String, + type: KClass<*>, + ) { logicProgramming { val query1 = Alias.FUNCTOR(alias, T) assertSolutionEquals( ktListOf(query1.yes(T to TypeRef.of(type))), - solver.solveList(query1) + solver.solveList(query1), ) val query2 = Alias.FUNCTOR(A, TypeRef.of(type)) assertSolutionEquals( aliasesByObject(type).map { query2.yes(A to it) }, - solver.solveList(query2) + solver.solveList(query2), ) } } - private fun assertAliasIsPresent(solver: Solver, alias: String, obj: Any?) { + private fun assertAliasIsPresent( + solver: Solver, + alias: String, + obj: Any?, + ) { logicProgramming { val query1 = Alias.FUNCTOR(alias, T) assertSolutionEquals( ktListOf(query1.yes(T to ObjectRef.of(obj))), - solver.solveList(query1) + solver.solveList(query1), ) val query2 = Alias.FUNCTOR(A, ObjectRef.of(obj)) assertSolutionEquals( aliasesByObject(obj).map { query2.yes(A to it) }, - solver.solveList(query2) + solver.solveList(query2), ) } } @@ -104,33 +112,34 @@ class TestAliasImpl(private val solverFactory: SolverFactory) : TestAlias { val query = Alias.FUNCTOR(A, T) val solutions = solver.solveList(query) - val expected = ktListOf( - query.yes(A to "string", T to TypeRef.of(String::class)), - query.yes(A to "array", T to TypeRef.of(Array::class)), - query.yes(A to "list", T to TypeRef.of(List::class)), - query.yes(A to "arraylist", T to TypeRef.of(ArrayList::class)), - query.yes(A to "map", T to TypeRef.of(Map::class)), - query.yes(A to "hashmap", T to TypeRef.of(LinkedHashMap::class)), - query.yes(A to "int", T to TypeRef.of(Int::class)), - query.yes(A to "integer", T to TypeRef.of(Int::class)), - query.yes(A to "double", T to TypeRef.of(Double::class)), - query.yes(A to "float", T to TypeRef.of(Float::class)), - query.yes(A to "long", T to TypeRef.of(Long::class)), - query.yes(A to "short", T to TypeRef.of(Short::class)), - query.yes(A to "byte", T to TypeRef.of(Byte::class)), - query.yes(A to "char", T to TypeRef.of(Char::class)), - query.yes(A to "bool", T to TypeRef.of(Boolean::class)), - query.yes(A to "boolean", T to TypeRef.of(Boolean::class)), - query.yes(A to "any", T to TypeRef.of(Any::class)), - query.yes(A to "nothing", T to TypeRef.of(Nothing::class)), - query.yes(A to "big_integer", T to TypeRef.of(BigInteger::class)), - query.yes(A to "big_decimal", T to TypeRef.of(BigDecimal::class)), - query.yes(A to "system", T to TypeRef.of(System::class)), - query.yes(A to "math", T to TypeRef.of(Math::class)), - query.yes(A to "stdout", T to ObjectRef.of(System.out)), - query.yes(A to "stderr", T to ObjectRef.of(System.err)), - query.yes(A to "stdin", T to ObjectRef.of(System.`in`)) - ) + val expected = + ktListOf( + query.yes(A to "string", T to TypeRef.of(String::class)), + query.yes(A to "array", T to TypeRef.of(Array::class)), + query.yes(A to "list", T to TypeRef.of(List::class)), + query.yes(A to "arraylist", T to TypeRef.of(ArrayList::class)), + query.yes(A to "map", T to TypeRef.of(Map::class)), + query.yes(A to "hashmap", T to TypeRef.of(LinkedHashMap::class)), + query.yes(A to "int", T to TypeRef.of(Int::class)), + query.yes(A to "integer", T to TypeRef.of(Int::class)), + query.yes(A to "double", T to TypeRef.of(Double::class)), + query.yes(A to "float", T to TypeRef.of(Float::class)), + query.yes(A to "long", T to TypeRef.of(Long::class)), + query.yes(A to "short", T to TypeRef.of(Short::class)), + query.yes(A to "byte", T to TypeRef.of(Byte::class)), + query.yes(A to "char", T to TypeRef.of(Char::class)), + query.yes(A to "bool", T to TypeRef.of(Boolean::class)), + query.yes(A to "boolean", T to TypeRef.of(Boolean::class)), + query.yes(A to "any", T to TypeRef.of(Any::class)), + query.yes(A to "nothing", T to TypeRef.of(Nothing::class)), + query.yes(A to "big_integer", T to TypeRef.of(BigInteger::class)), + query.yes(A to "big_decimal", T to TypeRef.of(BigDecimal::class)), + query.yes(A to "system", T to TypeRef.of(System::class)), + query.yes(A to "math", T to TypeRef.of(Math::class)), + query.yes(A to "stdout", T to ObjectRef.of(System.out)), + query.yes(A to "stderr", T to ObjectRef.of(System.err)), + query.yes(A to "stdin", T to ObjectRef.of(System.`in`)), + ) assertSolutionEquals(expected, solutions) } } @@ -148,7 +157,7 @@ class TestAliasImpl(private val solverFactory: SolverFactory) : TestAlias { val registerQuery1 = Register.functor(bInstanceAlias.ref, bInstanceAlias.alias) assertSolutionEquals( ktListOf(registerQuery1.yes()), - solver.solveList(registerQuery1) + solver.solveList(registerQuery1), ) assertTrue { bInstanceAlias.implementation in solver.staticKb } assertTrue { solver.dynamicKb.size == 0L } @@ -156,13 +165,13 @@ class TestAliasImpl(private val solverFactory: SolverFactory) : TestAlias { val aliasQuery1 = bInstanceAlias.implementation.head assertSolutionEquals( ktListOf(aliasQuery1.yes()), - solver.solveList(aliasQuery1) + solver.solveList(aliasQuery1), ) val registerQuery2 = Register.functor(bTypeAlias.ref, bTypeAlias.alias) assertSolutionEquals( ktListOf(registerQuery2.yes()), - solver.solveList(registerQuery2) + solver.solveList(registerQuery2), ) assertTrue { bTypeAlias.implementation in solver.staticKb } assertTrue { solver.dynamicKb.size == 0L } @@ -170,7 +179,7 @@ class TestAliasImpl(private val solverFactory: SolverFactory) : TestAlias { val aliasQuery2 = bTypeAlias.implementation.head assertSolutionEquals( ktListOf(aliasQuery2.yes()), - solver.solveList(aliasQuery2) + solver.solveList(aliasQuery2), ) } } @@ -186,10 +195,10 @@ class TestAliasImpl(private val solverFactory: SolverFactory) : TestAlias { DummyInstances.executionContext, Register.signature, X, - 0 - ) + 0, + ), ), - solver.solveOnce(query) + solver.solveOnce(query), ) query = Register.functor(ObjectRef.NULL, A) @@ -199,10 +208,10 @@ class TestAliasImpl(private val solverFactory: SolverFactory) : TestAlias { DummyInstances.executionContext, Register.signature, A, - 1 - ) + 1, + ), ), - solver.solveOnce(query) + solver.solveOnce(query), ) query = Register.functor(3, "alias") @@ -213,10 +222,10 @@ class TestAliasImpl(private val solverFactory: SolverFactory) : TestAlias { Register.signature, TypeError.Expected.REFERENCE, intOf(3), - 0 - ) + 0, + ), ), - solver.solveOnce(query) + solver.solveOnce(query), ) query = Register.functor(ObjectRef.NULL, 3) @@ -227,10 +236,10 @@ class TestAliasImpl(private val solverFactory: SolverFactory) : TestAlias { Register.signature, TypeError.Expected.CALLABLE, intOf(3), - 1 - ) + 1, + ), ), - solver.solveOnce(query) + solver.solveOnce(query), ) } } diff --git a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestClassicAlias.kt b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestClassicAlias.kt index cd08f33a8..ff0e0b6a1 100644 --- a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestClassicAlias.kt +++ b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestClassicAlias.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.classic.ClassicSolverFactory import org.junit.Test class TestClassicAlias : TestAlias, SolverFactory by ClassicSolverFactory { - private val prototype = TestAlias.prototype(this) @Test diff --git a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestClassicCreation.kt b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestClassicCreation.kt index 753d3c352..89b5632c0 100644 --- a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestClassicCreation.kt +++ b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestClassicCreation.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.classic.ClassicSolverFactory import org.junit.Test class TestClassicCreation : TestCreation, SolverFactory by ClassicSolverFactory { - private val prototype = TestCreation.prototype(this) @Test diff --git a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestClassicMethodInvocation.kt b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestClassicMethodInvocation.kt index 96b74ec98..6be2a6371 100644 --- a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestClassicMethodInvocation.kt +++ b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestClassicMethodInvocation.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.classic.ClassicSolverFactory import org.junit.Test class TestClassicMethodInvocation : TestMethodInvocation, SolverFactory by ClassicSolverFactory { - private val prototype = TestMethodInvocation.prototype(this) @Test diff --git a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestClassicStrictInvocation.kt b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestClassicStrictInvocation.kt index 5dc1aaccf..09302bcf6 100644 --- a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestClassicStrictInvocation.kt +++ b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestClassicStrictInvocation.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.classic.ClassicSolverFactory import org.junit.Test class TestClassicStrictInvocation : TestStrictInvocation, SolverFactory by ClassicSolverFactory { - private val prototype = TestStrictInvocation.prototype(this) @Test diff --git a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestCreation.kt b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestCreation.kt index 7a0fe0eac..9ed659d04 100644 --- a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestCreation.kt +++ b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestCreation.kt @@ -7,7 +7,10 @@ interface TestCreation : SolverTest { companion object { fun prototype(solverFactory: SolverFactory): TestCreation = TestCreationImpl(solverFactory) } + fun mostProperConstructorIsSelectedWhenInstantiatingTypeRef() + fun constructorCanBeSelectedViaExplicitCastWhenInstantiatingTypeRef() + fun constructorSelectionMayFailWhenInstantiatingTypeRef() } diff --git a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestCreationImpl.kt b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestCreationImpl.kt index 1787abe31..80707f3c7 100644 --- a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestCreationImpl.kt +++ b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestCreationImpl.kt @@ -21,7 +21,7 @@ class TestCreationImpl(protected val solverFactory: SolverFactory) : TestCreatio private fun testConstructorInvocation( cases: List, detectorType: KClass<*> = ConstructorOverloadDetector::class, - case2Term: (TestDatum) -> Term + case2Term: (TestDatum) -> Term, ) = logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins(otherLibraries = Runtime.of(OOPLib)) for (case in cases) { @@ -29,24 +29,26 @@ class TestCreationImpl(protected val solverFactory: SolverFactory) : TestCreatio val solutions = solver.solveList(query) assertTrue(solutions.size == 1) when (val solution = solutions.single()) { - is Solution.Halt -> when (val exception = solution.exception) { - is SystemError -> { - assertTrue(exception.cause is OopRuntimeException) - assertTrue(exception.cause?.cause is NullPointerException) + is Solution.Halt -> + when (val exception = solution.exception) { + is SystemError -> { + assertTrue(exception.cause is OopRuntimeException) + assertTrue(exception.cause?.cause is NullPointerException) + } + is RepresentationError -> { + assertTrue(exception.cause is TermToObjectConversionException) + } + else -> fail("Unexpected exception: $exception") } - is RepresentationError -> { - assertTrue(exception.cause is TermToObjectConversionException) - } - else -> fail("Unexpected exception: $exception") - } - is Solution.Yes -> solver.solveOnce(query).substitution[X]?.let { - assertTrue(it is ObjectRef) - assertEquals(detectorType, it.`object`::class) - assertEquals?>( - case.converted to case.type, - (it.`object` as? ConstructorOverloadDetector)?.args - ) - } ?: fail("Missing variable assignment in $solution: $X") + is Solution.Yes -> + solver.solveOnce(query).substitution[X]?.let { + assertTrue(it is ObjectRef) + assertEquals(detectorType, it.`object`::class) + assertEquals?>( + case.converted to case.type, + (it.`object` as? ConstructorOverloadDetector)?.args, + ) + } ?: fail("Missing variable assignment in $solution: $X") else -> fail("Unexpected solution: $solution") } } diff --git a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestDatum.kt b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestDatum.kt index f9c903a45..a69a2afa0 100644 --- a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestDatum.kt +++ b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestDatum.kt @@ -17,7 +17,10 @@ internal data class TestDatum(val term: Term, val type: KClass<*>, val converted get() = converted == null || exception != null companion object { - fun failed(term: Term, type: KClass<*>): TestDatum { + fun failed( + term: Term, + type: KClass<*>, + ): TestDatum { return TestDatum(term, type, TermToObjectConversionException(term, type)) } } diff --git a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestInvocation.kt b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestInvocation.kt index 78641e61c..c2287d470 100644 --- a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestInvocation.kt +++ b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestInvocation.kt @@ -4,9 +4,14 @@ import it.unibo.tuprolog.solve.SolverTest interface TestInvocation : SolverTest { fun mostProperOverloadIsSelectedWhenInvokingObjectRefMethod() + fun overloadCanBeSelectedViaExplicitCastWhenInvokingObjectRefMethod() + fun overloadSelectionMayFailWhenInvokingObjectRefMethod() + fun mostProperOverloadIsSelectedWhenInvokingTypeRefMethod() + fun overloadCanBeSelectedViaExplicitCastWhenInvokingTypeRefMethod() + fun overloadSelectionMayFailWhenInvokingTypeRefMethod() } diff --git a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestInvocationImpl.kt b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestInvocationImpl.kt index aef41a35b..fe0a68130 100644 --- a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestInvocationImpl.kt +++ b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestInvocationImpl.kt @@ -20,7 +20,6 @@ import kotlin.test.assertTrue import kotlin.test.fail abstract class TestInvocationImpl(protected val solverFactory: SolverFactory) : TestInvocation { - internal abstract fun caseToResult(case: TestDatum): Term protected abstract val invoke: String @@ -29,7 +28,7 @@ abstract class TestInvocationImpl(protected val solverFactory: SolverFactory) : cases: List, detectorCreator: () -> OverloadDetector = OverloadDetector.Companion::create, refCreator: (OverloadDetector) -> Ref = ObjectRef.Companion::of, - case2Term: (TestDatum) -> Term + case2Term: (TestDatum) -> Term, ) = logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins(otherLibraries = Runtime.of(OOPLib)) val obj = detectorCreator() @@ -39,35 +38,36 @@ abstract class TestInvocationImpl(protected val solverFactory: SolverFactory) : val solutions = solver.solveList(query) assertTrue(solutions.size == 1) when (val solution = solutions.single()) { - is Solution.Halt -> when (val exception = solution.exception) { - is SystemError -> { - assertTrue(exception.cause is OopRuntimeException) - assertTrue(exception.cause?.cause is NullPointerException) - } - is RepresentationError -> { - assertTrue(exception.cause is TermToObjectConversionException) + is Solution.Halt -> + when (val exception = solution.exception) { + is SystemError -> { + assertTrue(exception.cause is OopRuntimeException) + assertTrue(exception.cause?.cause is NullPointerException) + } + is RepresentationError -> { + assertTrue(exception.cause is TermToObjectConversionException) + } + else -> fail("Unexpected exception: $exception") } - else -> fail("Unexpected exception: $exception") - } is Solution.Yes -> { assertSolutionEquals( query.yes(R to caseToResult(case)), - solution + solution, ) } else -> fail("Unexpected solution: $solution") } } var query = InvokeMethod.functor(ref, "size", R) - val expectedSize = cases.size - cases.filter { it.isFailed }.count() + val expectedSize = cases.size - cases.count { it.isFailed } assertSolutionEquals( query.yes(R to Integer.of(expectedSize)), - solver.solveOnce(query) + solver.solveOnce(query), ) query = InvokeMethod.functor(ref, "toList", R) assertEquals( obj.toList(), - solver.solveOnce(query).asYes()?.substitution?.get(R)?.let { it as ObjectRef }?.`object` + solver.solveOnce(query).asYes()?.substitution?.get(R)?.let { it as ObjectRef }?.`object`, ) assertEquals(cases.filterNot { it.isFailed }.map { it.converted!! }, obj.toList()) assertEquals(cases.filterNot { it.isFailed }.map { it.converted!! to it.type }, obj.recordings) @@ -93,7 +93,7 @@ abstract class TestInvocationImpl(protected val solverFactory: SolverFactory) : testMethodInvocation( Conversions.bestCases, detectorCreator = OverloadDetectorObject::refresh, - refCreator = { TypeRef.of(OverloadDetectorObject::class) } + refCreator = { TypeRef.of(OverloadDetectorObject::class) }, ) { it.term } } @@ -101,7 +101,7 @@ abstract class TestInvocationImpl(protected val solverFactory: SolverFactory) : testMethodInvocation( Conversions.explicitCases, detectorCreator = OverloadDetectorObject::refresh, - refCreator = { TypeRef.of(OverloadDetectorObject::class) } + refCreator = { TypeRef.of(OverloadDetectorObject::class) }, ) { Struct.of(OOP.CAST_OPERATOR, it.term, Atom.of(it.type.fullName)) } @@ -111,7 +111,7 @@ abstract class TestInvocationImpl(protected val solverFactory: SolverFactory) : testMethodInvocation( Conversions.cornerCases, detectorCreator = OverloadDetectorObject::refresh, - refCreator = { TypeRef.of(OverloadDetectorObject::class) } + refCreator = { TypeRef.of(OverloadDetectorObject::class) }, ) { Struct.of(OOP.CAST_OPERATOR, it.term, Atom.of(it.type.fullName)) } diff --git a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestKotlinReflectionWorkaroundsAreStillNecessary.kt b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestKotlinReflectionWorkaroundsAreStillNecessary.kt index 9d1309970..7e2b08a1b 100644 --- a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestKotlinReflectionWorkaroundsAreStillNecessary.kt +++ b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestKotlinReflectionWorkaroundsAreStillNecessary.kt @@ -9,7 +9,7 @@ import kotlin.test.fail @Ignore class TestKotlinReflectionWorkaroundsAreStillNecessary { - + @Suppress("PrintStackTrace") private inline fun assertExceptionIsThrown(action: () -> Unit) { try { action() @@ -25,9 +25,10 @@ class TestKotlinReflectionWorkaroundsAreStillNecessary { } private val KClass<*>.instanceMembersWithNoArg - get() = members.asSequence() - .filter { it.parameters.size == 1 && it.parameters[0].kind == KParameter.Kind.INSTANCE } - .filterNot { it.name in setOf("hashCode", "toString") } + get() = + members.asSequence() + .filter { it.parameters.size == 1 && it.parameters[0].kind == KParameter.Kind.INSTANCE } + .filterNot { it.name in setOf("hashCode", "toString") } @Test fun testIntInstanceMethods() { diff --git a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestKotlinTypeRefs.kt b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestKotlinTypeRefs.kt index 4201cd631..cc248ac31 100644 --- a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestKotlinTypeRefs.kt +++ b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestKotlinTypeRefs.kt @@ -4,8 +4,11 @@ import org.junit.Test import kotlin.test.assertEquals class TestKotlinTypeRefs { - - private fun assertPropertyReturns(typeRef: TypeRef, property: String, expected: Any?) { + private fun assertPropertyReturns( + typeRef: TypeRef, + property: String, + expected: Any?, + ) { val result = typeRef.invoke(property) assertEquals(expected, result.asValue()?.value) } diff --git a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestMethodInvocationImpl.kt b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestMethodInvocationImpl.kt index 014f26f73..2de78cd23 100644 --- a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestMethodInvocationImpl.kt +++ b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestMethodInvocationImpl.kt @@ -7,5 +7,6 @@ import it.unibo.tuprolog.solve.libs.oop.primitives.InvokeMethod class TestMethodInvocationImpl(solverFactory: SolverFactory) : TestInvocationImpl(solverFactory), TestMethodInvocation { override fun caseToResult(case: TestDatum): Term = Atom.of(case.type.name) + override val invoke: String get() = InvokeMethod.functor } diff --git a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestRefs.kt b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestRefs.kt index 46c97ecc4..89d128e0f 100644 --- a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestRefs.kt +++ b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestRefs.kt @@ -15,12 +15,12 @@ import kotlin.test.assertFalse import kotlin.test.assertTrue class TestRefs { - + @Suppress("SwallowedException") private fun testMethodInvocation( cases: List, detectorCreator: () -> OverloadDetector = OverloadDetector.Companion::create, refCreator: (OverloadDetector) -> Ref = ObjectRef.Companion::of, - case2Term: (TestDatum) -> Term + case2Term: (TestDatum) -> Term, ) { val obj = detectorCreator() val ref = refCreator(obj) @@ -39,7 +39,7 @@ class TestRefs { } } var result = ref.invoke("size") - val expectedSize = cases.size - cases.filter { it.isFailed }.count() + val expectedSize = cases.size - cases.count { it.isFailed } assertEquals(Integer.of(expectedSize), result.toTerm()) result = ref.invoke("toList") val list = result.asObjectRef()?.`object` as List<*> @@ -47,10 +47,11 @@ class TestRefs { assertEquals(cases.filterNot { it.isFailed }.map { it.converted!! to it.type }, obj.recordings) } + @Suppress("SwallowedException") private fun testConstructorInvocation( cases: List, detectorType: KClass<*> = ConstructorOverloadDetector::class, - case2Term: (TestDatum) -> Term + case2Term: (TestDatum) -> Term, ) { val ref = TypeRef.of(detectorType) for (case in cases) { @@ -94,7 +95,7 @@ class TestRefs { testMethodInvocation( Conversions.bestCases, detectorCreator = OverloadDetectorObject::refresh, - refCreator = { TypeRef.of(OverloadDetectorObject::class) } + refCreator = { TypeRef.of(OverloadDetectorObject::class) }, ) { it.term } } @@ -103,7 +104,7 @@ class TestRefs { testMethodInvocation( Conversions.explicitCases, detectorCreator = OverloadDetectorObject::refresh, - refCreator = { TypeRef.of(OverloadDetectorObject::class) } + refCreator = { TypeRef.of(OverloadDetectorObject::class) }, ) { Struct.of(CAST_OPERATOR, it.term, Atom.of(it.type.fullName)) } @@ -114,7 +115,7 @@ class TestRefs { testMethodInvocation( Conversions.cornerCases, detectorCreator = OverloadDetectorObject::refresh, - refCreator = { TypeRef.of(OverloadDetectorObject::class) } + refCreator = { TypeRef.of(OverloadDetectorObject::class) }, ) { Struct.of(CAST_OPERATOR, it.term, Atom.of(it.type.fullName)) } diff --git a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestStrictInvocationImpl.kt b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestStrictInvocationImpl.kt index 0e7e5f39c..020e4bfdd 100644 --- a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestStrictInvocationImpl.kt +++ b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestStrictInvocationImpl.kt @@ -6,5 +6,6 @@ import it.unibo.tuprolog.solve.libs.oop.primitives.InvokeStrict class TestStrictInvocationImpl(solverFactory: SolverFactory) : TestInvocationImpl(solverFactory), TestStrictInvocation { override fun caseToResult(case: TestDatum): Term = ObjectRef.of(case.type.name) + override val invoke: String get() = InvokeStrict.functor } diff --git a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestTypesRetrieval.kt b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestTypesRetrieval.kt index cff4eaf21..a55d9a75d 100644 --- a/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestTypesRetrieval.kt +++ b/oop-lib/src/jvmTest/kotlin/it/unibo/tuprolog/solve/libs/oop/TestTypesRetrieval.kt @@ -1,23 +1,36 @@ +@file:Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") + package it.unibo.tuprolog.solve.libs.oop import org.junit.Test import kotlin.reflect.KClass import kotlin.test.assertEquals import kotlin.test.assertNull +import java.lang.annotation.Annotation as JavaAnnotation +import kotlin.Annotation as KtAnnotation class TestTypesRetrieval { - - private fun assertFactoryRetrievesTypeCorrectly(factory: TypeFactory, type: KClass<*>) { + private fun assertFactoryRetrievesTypeCorrectly( + factory: TypeFactory, + type: KClass<*>, + ) { assertEquals(type, factory.typeFromName(type.fullName)) assertEquals(TypeRef.of(type), factory.typeRefFromName(type.fullName)) } - private fun assertFactoryRetrievesKotlinTypeFromJavaName(factory: TypeFactory, kType: KClass<*>, jType: Class<*>) { + private fun assertFactoryRetrievesKotlinTypeFromJavaName( + factory: TypeFactory, + kType: KClass<*>, + jType: Class<*>, + ) { assertEquals(kType, factory.typeFromName(jType.name)) assertEquals(TypeRef.of(kType), factory.typeRefFromName(jType.name)) } - private fun assertFactoryRetrievesNoType(factory: TypeFactory, typeName: String) { + private fun assertFactoryRetrievesNoType( + factory: TypeFactory, + typeName: String, + ) { assertNull(factory.typeFromName(typeName)) assertNull(factory.typeRefFromName(typeName)) } @@ -59,7 +72,7 @@ class TestTypesRetrieval { assertFactoryRetrievesTypeCorrectly(factory, Number::class) assertFactoryRetrievesTypeCorrectly(factory, Comparable::class) assertFactoryRetrievesTypeCorrectly(factory, Enum::class) - assertFactoryRetrievesTypeCorrectly(factory, Annotation::class) + assertFactoryRetrievesTypeCorrectly(factory, KtAnnotation::class) assertFactoryRetrievesTypeCorrectly(factory, Iterable::class) assertFactoryRetrievesTypeCorrectly(factory, Iterator::class) assertFactoryRetrievesTypeCorrectly(factory, Collection::class) @@ -90,7 +103,7 @@ class TestTypesRetrieval { assertFactoryRetrievesNoType(factory, Number::class.fullName + "1") assertFactoryRetrievesNoType(factory, Comparable::class.fullName + "1") assertFactoryRetrievesNoType(factory, Enum::class.fullName + "1") - assertFactoryRetrievesNoType(factory, Annotation::class.fullName + "1") + assertFactoryRetrievesNoType(factory, KtAnnotation::class.fullName + "1") assertFactoryRetrievesNoType(factory, Iterable::class.fullName + "1") assertFactoryRetrievesNoType(factory, Iterator::class.fullName + "1") assertFactoryRetrievesNoType(factory, Collection::class.fullName + "1") @@ -121,7 +134,7 @@ class TestTypesRetrieval { assertFactoryRetrievesKotlinTypeFromJavaName(factory, Number::class, java.lang.Number::class.java) assertFactoryRetrievesKotlinTypeFromJavaName(factory, Comparable::class, java.lang.Comparable::class.java) assertFactoryRetrievesKotlinTypeFromJavaName(factory, Enum::class, java.lang.Enum::class.java) - assertFactoryRetrievesKotlinTypeFromJavaName(factory, Annotation::class, java.lang.annotation.Annotation::class.java) + assertFactoryRetrievesKotlinTypeFromJavaName(factory, KtAnnotation::class, JavaAnnotation::class.java) assertFactoryRetrievesKotlinTypeFromJavaName(factory, Iterable::class, java.lang.Iterable::class.java) assertFactoryRetrievesKotlinTypeFromJavaName(factory, Iterator::class, java.util.Iterator::class.java) assertFactoryRetrievesKotlinTypeFromJavaName(factory, Collection::class, java.util.Collection::class.java) diff --git a/parser-core/src/commonMain/kotlin/it/unibo/tuprolog/core/parsing/InvalidTermTypeException.kt b/parser-core/src/commonMain/kotlin/it/unibo/tuprolog/core/parsing/InvalidTermTypeException.kt index f3ce7970c..21021b29a 100644 --- a/parser-core/src/commonMain/kotlin/it/unibo/tuprolog/core/parsing/InvalidTermTypeException.kt +++ b/parser-core/src/commonMain/kotlin/it/unibo/tuprolog/core/parsing/InvalidTermTypeException.kt @@ -11,5 +11,5 @@ class InvalidTermTypeException( line: Int = 1, column: Int = 1, message: String? = "Expected ${type.simpleName}, got: $offendingSymbol", - throwable: Throwable? = null + throwable: Throwable? = null, ) : ParseException(input, offendingSymbol, line, column, message, throwable) diff --git a/parser-core/src/commonMain/kotlin/it/unibo/tuprolog/core/parsing/ParseException.kt b/parser-core/src/commonMain/kotlin/it/unibo/tuprolog/core/parsing/ParseException.kt index edcb15d1a..2a8f2fe68 100644 --- a/parser-core/src/commonMain/kotlin/it/unibo/tuprolog/core/parsing/ParseException.kt +++ b/parser-core/src/commonMain/kotlin/it/unibo/tuprolog/core/parsing/ParseException.kt @@ -9,9 +9,8 @@ open class ParseException( @JsName("line") var line: Int, @JsName("column") var column: Int, message: String?, - throwable: Throwable? + throwable: Throwable?, ) : TuPrologException(message, throwable) { - @JsName("clauseIndex") var clauseIndex = -1 diff --git a/parser-core/src/commonMain/kotlin/it/unibo/tuprolog/core/parsing/ParsinUtils.kt b/parser-core/src/commonMain/kotlin/it/unibo/tuprolog/core/parsing/ParsinUtils.kt new file mode 100644 index 000000000..b3ac8cb0c --- /dev/null +++ b/parser-core/src/commonMain/kotlin/it/unibo/tuprolog/core/parsing/ParsinUtils.kt @@ -0,0 +1,16 @@ +package it.unibo.tuprolog.core.parsing + +import it.unibo.tuprolog.core.Atom +import it.unibo.tuprolog.core.Numeric +import it.unibo.tuprolog.core.Struct +import it.unibo.tuprolog.core.Term + +internal val Term.isOpDirective: Boolean + get() { + return this is Struct && + arity == 3 && + functor == "op" && + this.isGround && + this[0] is Numeric && + this[1] is Atom + } diff --git a/parser-core/src/commonMain/kotlin/it/unibo/tuprolog/core/parsing/TermParser.kt b/parser-core/src/commonMain/kotlin/it/unibo/tuprolog/core/parsing/TermParser.kt index 9b164992b..94ed80366 100644 --- a/parser-core/src/commonMain/kotlin/it/unibo/tuprolog/core/parsing/TermParser.kt +++ b/parser-core/src/commonMain/kotlin/it/unibo/tuprolog/core/parsing/TermParser.kt @@ -20,7 +20,6 @@ import kotlin.jvm.JvmOverloads import kotlin.jvm.JvmStatic interface TermParser { - @JsName("scope") val scope: Scope @@ -28,99 +27,112 @@ interface TermParser { val defaultOperatorSet: OperatorSet @JsName("parseTermWithOperators") - fun parseTerm(input: String, operators: OperatorSet): Term + fun parseTerm( + input: String, + operators: OperatorSet, + ): Term @JsName("parseTerm") - fun parseTerm(input: String): Term = - parseTerm(input, defaultOperatorSet) + fun parseTerm(input: String): Term = parseTerm(input, defaultOperatorSet) @JsName("parseStructWithOperators") - fun parseStruct(input: String, operators: OperatorSet): Struct = - parseAs(input, operators) + fun parseStruct( + input: String, + operators: OperatorSet, + ): Struct = parseAs(input, operators) @JsName("parseStruct") - fun parseStruct(input: String): Struct = - parseStruct(input, defaultOperatorSet) + fun parseStruct(input: String): Struct = parseStruct(input, defaultOperatorSet) @JsName("parseConstantWithOperators") - fun parseConstant(input: String, operators: OperatorSet): Constant = - parseAs(input, operators) + fun parseConstant( + input: String, + operators: OperatorSet, + ): Constant = parseAs(input, operators) @JsName("parseConstant") - fun parseConstant(input: String): Constant = - parseConstant(input, defaultOperatorSet) + fun parseConstant(input: String): Constant = parseConstant(input, defaultOperatorSet) @JsName("parseVarWithOperators") - fun parseVar(input: String, operators: OperatorSet): Var = - parseAs(input, operators) + fun parseVar( + input: String, + operators: OperatorSet, + ): Var = parseAs(input, operators) @JsName("parseVar") - fun parseVar(input: String): Var = - parseVar(input, defaultOperatorSet) + fun parseVar(input: String): Var = parseVar(input, defaultOperatorSet) @JsName("parseAtomWithOperators") - fun parseAtom(input: String, operators: OperatorSet): Atom = - parseAs(input, operators) + fun parseAtom( + input: String, + operators: OperatorSet, + ): Atom = parseAs(input, operators) @JsName("parseAtom") - fun parseAtom(input: String): Atom = - parseAtom(input, defaultOperatorSet) + fun parseAtom(input: String): Atom = parseAtom(input, defaultOperatorSet) @JsName("parseNumericWithOperators") - fun parseNumeric(input: String, operators: OperatorSet): Numeric = - parseAs(input, operators) + fun parseNumeric( + input: String, + operators: OperatorSet, + ): Numeric = parseAs(input, operators) @JsName("parseNumeric") - fun parseNumeric(input: String): Numeric = - parseNumeric(input, defaultOperatorSet) + fun parseNumeric(input: String): Numeric = parseNumeric(input, defaultOperatorSet) @JsName("parseIntegerWithOperators") - fun parseInteger(input: String, operators: OperatorSet): Integer = - parseAs(input, operators) + fun parseInteger( + input: String, + operators: OperatorSet, + ): Integer = parseAs(input, operators) @JsName("parseInteger") - fun parseInteger(input: String): Integer = - parseInteger(input, defaultOperatorSet) + fun parseInteger(input: String): Integer = parseInteger(input, defaultOperatorSet) @JsName("parseRealWithOperators") - fun parseReal(input: String, operators: OperatorSet): Real = - parseAs(input, operators) + fun parseReal( + input: String, + operators: OperatorSet, + ): Real = parseAs(input, operators) @JsName("parseReal") - fun parseReal(input: String): Real = - parseReal(input, defaultOperatorSet) + fun parseReal(input: String): Real = parseReal(input, defaultOperatorSet) @JsName("parseClauseWithOperators") - fun parseClause(input: String, operators: OperatorSet): Clause = - parseAs(input, operators) + fun parseClause( + input: String, + operators: OperatorSet, + ): Clause = parseAs(input, operators) @JsName("parseClause") - fun parseClause(input: String): Clause = - parseClause(input, defaultOperatorSet) + fun parseClause(input: String): Clause = parseClause(input, defaultOperatorSet) @JsName("parseRuleWithOperators") - fun parseRule(input: String, operators: OperatorSet): Rule = - parseAs(input, operators) + fun parseRule( + input: String, + operators: OperatorSet, + ): Rule = parseAs(input, operators) @JsName("parseRule") - fun parseRule(input: String): Rule = - parseRule(input, defaultOperatorSet) + fun parseRule(input: String): Rule = parseRule(input, defaultOperatorSet) @JsName("parseFactWithOperators") - fun parseFact(input: String, operators: OperatorSet): Fact = - parseAs(input, operators) + fun parseFact( + input: String, + operators: OperatorSet, + ): Fact = parseAs(input, operators) @JsName("parseFact") - fun parseFact(input: String): Fact = - parseFact(input, defaultOperatorSet) + fun parseFact(input: String): Fact = parseFact(input, defaultOperatorSet) @JsName("parseDirectiveWithOperators") - fun parseDirective(input: String, operators: OperatorSet): Directive = - parseAs(input, operators) + fun parseDirective( + input: String, + operators: OperatorSet, + ): Directive = parseAs(input, operators) @JsName("parseDirective") - fun parseDirective(input: String): Directive = - parseDirective(input, defaultOperatorSet) + fun parseDirective(input: String): Directive = parseDirective(input, defaultOperatorSet) companion object { @JvmStatic @@ -141,18 +153,24 @@ interface TermParser { @JvmStatic @JsName("withOperatorSet") @JvmOverloads - fun withOperators(operators: OperatorSet, scope: Scope = Scope.empty()) = - termParserWithOperators(operators, scope) + fun withOperators( + operators: OperatorSet, + scope: Scope = Scope.empty(), + ) = termParserWithOperators(operators, scope) @JvmStatic @JsName("withOperators") @JvmOverloads - fun withOperators(vararg operators: Operator, scope: Scope = Scope.empty()) = - withOperators(OperatorSet(*operators), scope) - - private inline fun TermParser.parseAs(input: String, operators: OperatorSet) = - parseTerm(input, operators).let { - it as? T ?: throw InvalidTermTypeException(input, it, T::class) - } + fun withOperators( + vararg operators: Operator, + scope: Scope = Scope.empty(), + ) = withOperators(OperatorSet(*operators), scope) + + private inline fun TermParser.parseAs( + input: String, + operators: OperatorSet, + ) = parseTerm(input, operators).let { + it as? T ?: throw InvalidTermTypeException(input, it, T::class) + } } } diff --git a/parser-core/src/commonMain/kotlin/it/unibo/tuprolog/core/parsing/TermParserExtensions.kt b/parser-core/src/commonMain/kotlin/it/unibo/tuprolog/core/parsing/TermParserExtensions.kt index 8ebed0a5a..fecd14b71 100644 --- a/parser-core/src/commonMain/kotlin/it/unibo/tuprolog/core/parsing/TermParserExtensions.kt +++ b/parser-core/src/commonMain/kotlin/it/unibo/tuprolog/core/parsing/TermParserExtensions.kt @@ -19,13 +19,20 @@ import it.unibo.tuprolog.core.operators.OperatorSet import kotlin.js.JsName import kotlin.jvm.JvmName -internal expect fun termParserWithOperators(operators: OperatorSet, scope: Scope = Scope.empty()): TermParser +internal expect fun termParserWithOperators( + operators: OperatorSet, + scope: Scope = Scope.empty(), +): TermParser private val defaultParser: TermParser get() = TermParser.withDefaultOperators() @JsName("termToClause") -fun Term.toClause(source: Any? = null, line: Int = 0, column: Int = 0): Clause = +fun Term.toClause( + source: Any? = null, + line: Int = 0, + column: Int = 0, +): Clause = when (this) { is Clause -> this is Struct -> Fact.of(this) @@ -33,193 +40,181 @@ fun Term.toClause(source: Any? = null, line: Int = 0, column: Int = 0): Clause = } @JsName("parseTermWithOperators") -fun Term.Companion.parse(input: String, operators: OperatorSet): Term = - defaultParser.parseTerm(input, operators) +fun Term.Companion.parse( + input: String, + operators: OperatorSet, +): Term = defaultParser.parseTerm(input, operators) @JsName("parseTerm") -fun Term.Companion.parse(input: String): Term = - defaultParser.parseTerm(input) +fun Term.Companion.parse(input: String): Term = defaultParser.parseTerm(input) @JsName("parseStringAsTermWithOperators") -fun String.parseAsTerm(operators: OperatorSet): Term = - defaultParser.parseTerm(this, operators) +fun String.parseAsTerm(operators: OperatorSet): Term = defaultParser.parseTerm(this, operators) @JsName("parseStringAsTerm") -fun String.parseAsTerm(): Term = - defaultParser.parseTerm(this) +fun String.parseAsTerm(): Term = defaultParser.parseTerm(this) @JsName("parseStructWithOperators") -fun Struct.Companion.parse(input: String, operators: OperatorSet): Struct = - defaultParser.parseStruct(input, operators) +fun Struct.Companion.parse( + input: String, + operators: OperatorSet, +): Struct = defaultParser.parseStruct(input, operators) @JsName("parseStruct") -fun Struct.Companion.parse(input: String): Struct = - defaultParser.parseStruct(input) +fun Struct.Companion.parse(input: String): Struct = defaultParser.parseStruct(input) @JsName("parseStringAsStructWithOperators") -fun String.parseAsStruct(operators: OperatorSet): Struct = - defaultParser.parseStruct(this, operators) +fun String.parseAsStruct(operators: OperatorSet): Struct = defaultParser.parseStruct(this, operators) @JsName("parseStringAsStruct") -fun String.parseAsStruct(): Struct = - defaultParser.parseStruct(this) +fun String.parseAsStruct(): Struct = defaultParser.parseStruct(this) @JsName("parseConstantWithOperators") -fun Constant.Companion.parse(input: String, operators: OperatorSet): Constant = - defaultParser.parseConstant(input, operators) +fun Constant.Companion.parse( + input: String, + operators: OperatorSet, +): Constant = defaultParser.parseConstant(input, operators) @JsName("parseConstant") -fun Constant.Companion.parse(input: String): Constant = - defaultParser.parseConstant(input) +fun Constant.Companion.parse(input: String): Constant = defaultParser.parseConstant(input) @JsName("parseStringAsConstantWithOperators") -fun String.parseAsConstant(operators: OperatorSet): Constant = - defaultParser.parseConstant(this, operators) +fun String.parseAsConstant(operators: OperatorSet): Constant = defaultParser.parseConstant(this, operators) @JsName("parseStringAsConstant") -fun String.parseAsConstant(): Constant = - defaultParser.parseConstant(this) +fun String.parseAsConstant(): Constant = defaultParser.parseConstant(this) @JsName("parseVarWithOperators") -fun Var.Companion.parse(input: String, operators: OperatorSet): Var = - defaultParser.parseVar(input, operators) +fun Var.Companion.parse( + input: String, + operators: OperatorSet, +): Var = defaultParser.parseVar(input, operators) @JsName("parseVar") -fun Var.Companion.parse(input: String): Var = - defaultParser.parseVar(input) +fun Var.Companion.parse(input: String): Var = defaultParser.parseVar(input) @JsName("parseStringAsVarWithOperators") -fun String.parseAsVar(operators: OperatorSet): Var = - defaultParser.parseVar(this, operators) +fun String.parseAsVar(operators: OperatorSet): Var = defaultParser.parseVar(this, operators) @JsName("parseStringAs") -fun String.parseAsVar(): Var = - defaultParser.parseVar(this) +fun String.parseAsVar(): Var = defaultParser.parseVar(this) @JsName("parseAtomWithOperators") -fun Atom.Companion.parse(input: String, operators: OperatorSet): Atom = - defaultParser.parseAtom(input, operators) +fun Atom.Companion.parse( + input: String, + operators: OperatorSet, +): Atom = defaultParser.parseAtom(input, operators) @JsName("parseAtom") -fun Atom.Companion.parse(input: String): Atom = - defaultParser.parseAtom(input) +fun Atom.Companion.parse(input: String): Atom = defaultParser.parseAtom(input) @JsName("parseStringAsAtomWithOperators") -fun String.parseAsAtom(operators: OperatorSet): Atom = - defaultParser.parseAtom(this, operators) +fun String.parseAsAtom(operators: OperatorSet): Atom = defaultParser.parseAtom(this, operators) @JsName("parseStringAsAtom") -fun String.parseAsAtom(): Atom = - defaultParser.parseAtom(this) +fun String.parseAsAtom(): Atom = defaultParser.parseAtom(this) @JsName("parseNumericWithOperators") -fun Numeric.Companion.parse(input: String, operators: OperatorSet): Numeric = - defaultParser.parseNumeric(input, operators) +fun Numeric.Companion.parse( + input: String, + operators: OperatorSet, +): Numeric = defaultParser.parseNumeric(input, operators) @JsName("parseNumeric") -fun Numeric.Companion.parse(input: String): Numeric = - defaultParser.parseNumeric(input) +fun Numeric.Companion.parse(input: String): Numeric = defaultParser.parseNumeric(input) @JsName("parseStringAsNumericWithOperators") -fun String.parseAsNumeric(operators: OperatorSet): Numeric = - defaultParser.parseNumeric(this, operators) +fun String.parseAsNumeric(operators: OperatorSet): Numeric = defaultParser.parseNumeric(this, operators) @JsName("parseStringAsNumeric") -fun String.parseAsNumeric(): Numeric = - defaultParser.parseNumeric(this) +fun String.parseAsNumeric(): Numeric = defaultParser.parseNumeric(this) @JsName("parseIntegerWithOperators") -fun Integer.Companion.parse(input: String, operators: OperatorSet): Integer = - defaultParser.parseInteger(input, operators) +fun Integer.Companion.parse( + input: String, + operators: OperatorSet, +): Integer = defaultParser.parseInteger(input, operators) @JsName("parseInteger") -fun Integer.Companion.parse(input: String): Integer = - defaultParser.parseInteger(input) +fun Integer.Companion.parse(input: String): Integer = defaultParser.parseInteger(input) @JsName("parseStringAsIntegerWithOperators") -fun String.parseAsInteger(operators: OperatorSet): Integer = - defaultParser.parseInteger(this, operators) +fun String.parseAsInteger(operators: OperatorSet): Integer = defaultParser.parseInteger(this, operators) @JsName("parseStringAsInteger") -fun String.parseAsInteger(): Integer = - defaultParser.parseInteger(this) +fun String.parseAsInteger(): Integer = defaultParser.parseInteger(this) @JsName("parseRealWithOperators") -fun Real.Companion.parse(input: String, operators: OperatorSet): Real = - defaultParser.parseReal(input, operators) +fun Real.Companion.parse( + input: String, + operators: OperatorSet, +): Real = defaultParser.parseReal(input, operators) @JsName("parseReal") -fun Real.Companion.parse(input: String): Real = - defaultParser.parseReal(input) +fun Real.Companion.parse(input: String): Real = defaultParser.parseReal(input) @JsName("parseStringAsRealWithOperators") -fun String.parseAsReal(operators: OperatorSet): Real = - defaultParser.parseReal(this, operators) +fun String.parseAsReal(operators: OperatorSet): Real = defaultParser.parseReal(this, operators) @JsName("parseStringAsReal") -fun String.parseAsReal(): Real = - defaultParser.parseReal(this) +fun String.parseAsReal(): Real = defaultParser.parseReal(this) @JsName("parseClauseWithOperators") -fun Clause.Companion.parse(input: String, operators: OperatorSet): Clause = - defaultParser.parseClause(input, operators) +fun Clause.Companion.parse( + input: String, + operators: OperatorSet, +): Clause = defaultParser.parseClause(input, operators) @JsName("parseClause") -fun Clause.Companion.parse(input: String): Clause = - defaultParser.parseClause(input) +fun Clause.Companion.parse(input: String): Clause = defaultParser.parseClause(input) @JsName("parseStringAsClauseWithOperators") -fun String.parseAsClause(operators: OperatorSet): Clause = - defaultParser.parseClause(this, operators) +fun String.parseAsClause(operators: OperatorSet): Clause = defaultParser.parseClause(this, operators) @JsName("parseStringAsClause") -fun String.parseAsClause(): Clause = - defaultParser.parseClause(this) +fun String.parseAsClause(): Clause = defaultParser.parseClause(this) @JsName("parseRuleWithOperators") -fun Rule.Companion.parse(input: String, operators: OperatorSet): Rule = - defaultParser.parseRule(input, operators) +fun Rule.Companion.parse( + input: String, + operators: OperatorSet, +): Rule = defaultParser.parseRule(input, operators) @JsName("parseRule") -fun Rule.Companion.parse(input: String): Rule = - defaultParser.parseRule(input) +fun Rule.Companion.parse(input: String): Rule = defaultParser.parseRule(input) @JsName("parseStringAsRuleWithOperators") -fun String.parseAsRule(operators: OperatorSet): Rule = - defaultParser.parseRule(this, operators) +fun String.parseAsRule(operators: OperatorSet): Rule = defaultParser.parseRule(this, operators) @JsName("parseStringAsRule") -fun String.parseAsRule(): Rule = - defaultParser.parseRule(this) +fun String.parseAsRule(): Rule = defaultParser.parseRule(this) @JsName("parseFactWithOperators") -fun Fact.Companion.parse(input: String, operators: OperatorSet): Fact = - defaultParser.parseFact(input, operators) +fun Fact.Companion.parse( + input: String, + operators: OperatorSet, +): Fact = defaultParser.parseFact(input, operators) @JsName("parseFact") -fun Fact.Companion.parse(input: String): Fact = - defaultParser.parseFact(input) +fun Fact.Companion.parse(input: String): Fact = defaultParser.parseFact(input) @JsName("parseStringAsFactWithOperators") -fun String.parseAsFact(operators: OperatorSet): Fact = - defaultParser.parseFact(this, operators) +fun String.parseAsFact(operators: OperatorSet): Fact = defaultParser.parseFact(this, operators) @JsName("parseStringAsFact") -fun String.parseAsFact(): Fact = - defaultParser.parseFact(this) +fun String.parseAsFact(): Fact = defaultParser.parseFact(this) @JsName("parseDirectiveWithOperators") -fun Directive.Companion.parse(input: String, operators: OperatorSet): Directive = - defaultParser.parseDirective(input, operators) +fun Directive.Companion.parse( + input: String, + operators: OperatorSet, +): Directive = defaultParser.parseDirective(input, operators) @JsName("parseDirective") -fun Directive.Companion.parse(input: String): Directive = - defaultParser.parseDirective(input) +fun Directive.Companion.parse(input: String): Directive = defaultParser.parseDirective(input) @JsName("parseStringAsDirectiveWithOperators") -fun String.parseAsDirective(operators: OperatorSet): Directive = - defaultParser.parseDirective(this, operators) +fun String.parseAsDirective(operators: OperatorSet): Directive = defaultParser.parseDirective(this, operators) @JsName("parseStringAsDirective") -fun String.parseAsDirective(): Directive = - defaultParser.parseDirective(this) +fun String.parseAsDirective(): Directive = defaultParser.parseDirective(this) diff --git a/parser-core/src/commonTest/kotlin/it/unibo/tuprolog/core/parsing/test/AssertionUtils.kt b/parser-core/src/commonTest/kotlin/it/unibo/tuprolog/core/parsing/test/AssertionUtils.kt index 7a4c08655..40168574b 100644 --- a/parser-core/src/commonTest/kotlin/it/unibo/tuprolog/core/parsing/test/AssertionUtils.kt +++ b/parser-core/src/commonTest/kotlin/it/unibo/tuprolog/core/parsing/test/AssertionUtils.kt @@ -9,19 +9,22 @@ import it.unibo.tuprolog.dsl.unify.LogicProgrammingScopeWithUnification import kotlin.test.assertEquals /** Asserts terms are equal taking into account differences in complete variables names */ -fun assertTermsAreEqual(expected: Term, actual: Term) { +fun assertTermsAreEqual( + expected: Term, + actual: Term, +) { assertEquals(expected.isGround, actual.isGround) if (expected.isGround) { assertEquals( expected, actual, message = - """Comparing: + """Comparing: | actual: $actual | type: ${actual::class} | expected: $expected | type: ${expected::class} - """.trimMargin() + """.trimMargin(), ) } else { when { @@ -41,19 +44,23 @@ fun assertTermsAreEqual(expected: Term, actual: Term) { } assertEquals( expected.variables.toSet().size, - actual.variables.toSet().size + actual.variables.toSet().size, ) } } fun TermParser.assertTermIsCorrectlyParsed( stringToBeParsed: String, - expectedGenerator: LogicProgrammingScopeWithUnification.() -> Term + expectedGenerator: LogicProgrammingScopeWithUnification.() -> Term, ) { assertTermIsCorrectlyParsed(stringToBeParsed, LogicProgrammingScopeWithUnification.of().expectedGenerator()) } -fun TermParser.assertTermIsCorrectlyParsed(stringToBeParsed: String, expected: Term, loggingOn: Boolean = false) { +fun TermParser.assertTermIsCorrectlyParsed( + stringToBeParsed: String, + expected: Term, + loggingOn: Boolean = false, +) { if (loggingOn) println("Parsing:\n\t$stringToBeParsed") val actual = parseTerm(stringToBeParsed) diff --git a/parser-core/src/commonTest/kotlin/it/unibo/tuprolog/core/parsing/test/DoubleChecksOnEqualities.kt b/parser-core/src/commonTest/kotlin/it/unibo/tuprolog/core/parsing/test/DoubleChecksOnEqualities.kt index 5a98a611a..c95138fbc 100644 --- a/parser-core/src/commonTest/kotlin/it/unibo/tuprolog/core/parsing/test/DoubleChecksOnEqualities.kt +++ b/parser-core/src/commonTest/kotlin/it/unibo/tuprolog/core/parsing/test/DoubleChecksOnEqualities.kt @@ -10,14 +10,13 @@ import kotlin.test.Test import kotlin.test.assertEquals class DoubleChecksOnEqualities { - @Test fun testNumsAreEquals1() { assertEquals( Integer.of(1), logicProgramming { 1.toTerm() - } + }, ) } @@ -27,7 +26,7 @@ class DoubleChecksOnEqualities { Real.of("3.100000000000000088817841970012523233890533447265625"), logicProgramming { numOf(3.1) - } + }, ) } @@ -37,7 +36,7 @@ class DoubleChecksOnEqualities { Integer.of(1), logicProgramming { numOf(1) - } + }, ) } @@ -47,7 +46,7 @@ class DoubleChecksOnEqualities { Integer.of(1), logicProgramming { numOf(1L) - } + }, ) } @@ -57,7 +56,7 @@ class DoubleChecksOnEqualities { Integer.of(1), logicProgramming { numOf(BigInteger.ONE) - } + }, ) } @@ -67,7 +66,7 @@ class DoubleChecksOnEqualities { Integer.of(1), logicProgramming { numOf(BigInteger.TEN / BigInteger.TEN) - } + }, ) } @@ -77,7 +76,7 @@ class DoubleChecksOnEqualities { Cons.singleton(Integer.of(1)), logicProgramming { listOf(1) - } + }, ) } @@ -87,7 +86,7 @@ class DoubleChecksOnEqualities { Cons.singleton(Integer.of(1)), logicProgramming { listOf(numOf(1)) - } + }, ) } @@ -97,7 +96,7 @@ class DoubleChecksOnEqualities { Cons.singleton(Integer.of(1)), logicProgramming { consOf(1, emptyList) - } + }, ) } @@ -107,7 +106,7 @@ class DoubleChecksOnEqualities { Cons.singleton(Integer.of(1)), logicProgramming { consOf(numOf(1), emptyList) - } + }, ) } @@ -117,7 +116,7 @@ class DoubleChecksOnEqualities { Cons.singleton(Integer.of(1)), logicProgramming { consOf(Integer.of(1), emptyList) - } + }, ) } @@ -127,7 +126,7 @@ class DoubleChecksOnEqualities { Struct.of("+", Integer.of(1), Integer.of(2)), logicProgramming { 1.toTerm() + 2 - } + }, ) } } diff --git a/parser-core/src/commonTest/kotlin/it/unibo/tuprolog/core/parsing/test/ParsingExamples.kt b/parser-core/src/commonTest/kotlin/it/unibo/tuprolog/core/parsing/test/ParsingExamples.kt index 7348c3877..5a6e3eb53 100644 --- a/parser-core/src/commonTest/kotlin/it/unibo/tuprolog/core/parsing/test/ParsingExamples.kt +++ b/parser-core/src/commonTest/kotlin/it/unibo/tuprolog/core/parsing/test/ParsingExamples.kt @@ -6,227 +6,268 @@ import org.gciatto.kt.math.BigDecimal import org.gciatto.kt.math.BigInteger object ParsingExamples { - val canonicalTerms: Sequence> = sequenceOf( - "f(X)" to logicProgramming { "f"("X") }, - "f(X, y)" to logicProgramming { "f"("X", "y") }, - "g(X, y, 3)" to logicProgramming { "g"("X", "y", 3) }, - "[]" to logicProgramming { emptyList }, - "[ ]" to logicProgramming { emptyList }, - "[1]" to logicProgramming { listOf(1) }, - "[1 | X]" to logicProgramming { consOf(1, "X") }, - "[1, a | X]" to logicProgramming { consOf(1, consOf("a", "X")) }, - "[a, 2, X]" to logicProgramming { listOf("a", 2, "X") }, - "{}" to logicProgramming { emptyBlock }, - "{ }" to logicProgramming { emptyBlock }, - "{ 1 }" to logicProgramming { blockOf(1) }, - "{ 1, a }" to logicProgramming { blockOf(1, "a") }, - "{ 1, a, X }" to logicProgramming { blockOf(1, "a", "X") }, - "abc" to logicProgramming { atomOf("abc") }, - "Abc" to logicProgramming { varOf("Abc") }, - "'abc'" to logicProgramming { atomOf("abc") }, - "'Abc'" to logicProgramming { atomOf("Abc") }, - "'Abc d'" to logicProgramming { atomOf("Abc d") }, - "'1'" to logicProgramming { atomOf("1") }, - "'1.2'" to logicProgramming { atomOf("1.2") }, - "\"abc\"" to logicProgramming { atomOf("abc") }, - "\"Abc\"" to logicProgramming { atomOf("Abc") }, - "\"Abc d\"" to logicProgramming { atomOf("Abc d") }, - "\"1\"" to logicProgramming { atomOf("1") }, - "\"1.2\"" to logicProgramming { atomOf("1.2") }, - "1" to logicProgramming { numOf(1) }, - "1.2" to logicProgramming { numOf("1.2") }, - "-1" to logicProgramming { numOf(-1) }, - "-1.2" to logicProgramming { numOf("-1.2") }, - "${BigInteger.of("".padEnd(17, 'F'), 16)}" to logicProgramming { numOf(BigInteger.of("295147905179352825855")) }, - "0xFF" to logicProgramming { numOf(255) }, - "0XFF" to logicProgramming { numOf(255) }, - "-0xFF" to logicProgramming { numOf(-255) }, - "-0XFF" to logicProgramming { numOf(-255) }, - "0b111" to logicProgramming { numOf(7) }, - "0B111" to logicProgramming { numOf(7) }, - "-0b111" to logicProgramming { numOf(-7) }, - "-0B111" to logicProgramming { numOf(-7) }, - "0o11" to logicProgramming { numOf(9) }, - "0O11" to logicProgramming { numOf(9) }, - "-0o11" to logicProgramming { numOf(-9) }, - "-0O11" to logicProgramming { numOf(-9) }, - "0O11" to logicProgramming { numOf(9) }, - "0'a" to logicProgramming { numOf(97) }, - "-0'a" to logicProgramming { numOf(-97) }, - "${BigDecimal.PI}" to logicProgramming { numOf(BigDecimal.PI) }, - "(+)" to logicProgramming { atomOf("+") }, - "(-)" to logicProgramming { atomOf("-") }, - "$" to logicProgramming { atomOf("$") }, - "+(1)" to logicProgramming { structOf("+", 1) }, - "-(1)" to logicProgramming { structOf("-", 1) }, - "$(1)" to logicProgramming { structOf("$", 1) }, - "+(1, 2)" to logicProgramming { structOf("+", 1, 2) }, - "-(1, 2)" to logicProgramming { structOf("-", 1, 2) }, - "$(1, 2)" to logicProgramming { structOf("$", 1, 2) }, - "'+'(1)" to logicProgramming { structOf("+", 1) }, - "'-'(1)" to logicProgramming { structOf("-", 1) }, - "'$'(1)" to logicProgramming { structOf("$", 1) }, - "'+'(1, 2)" to logicProgramming { structOf("+", 1, 2) }, - "'-'(1, 2)" to logicProgramming { structOf("-", 1, 2) }, - "'$'(1, 2)" to logicProgramming { structOf("$", 1, 2) }, - "'F'(1, 2)" to logicProgramming { structOf("F", 1, 2) }, - "'true'(3)" to logicProgramming { structOf("true", 3) }, - "'false'(4)" to logicProgramming { structOf("false", 4) }, - "'fail'(5)" to logicProgramming { structOf("fail", 5) }, - "true(0)" to logicProgramming { structOf("true", 0) }, - "false(1)" to logicProgramming { structOf("false", 1) }, - "fail(2)" to logicProgramming { structOf("fail", 2) } - ) + @Suppress("ktlint:standard:multiline-expression-wrapping") + val canonicalTerms: Sequence> = + sequenceOf( + "f(X)" to logicProgramming { "f"("X") }, + "f(X, y)" to logicProgramming { "f"("X", "y") }, + "g(X, y, 3)" to logicProgramming { "g"("X", "y", 3) }, + "[]" to logicProgramming { emptyList }, + "[ ]" to logicProgramming { emptyList }, + "[1]" to logicProgramming { listOf(1) }, + "[1 | X]" to logicProgramming { consOf(1, "X") }, + "[1, a | X]" to logicProgramming { consOf(1, consOf("a", "X")) }, + "[a, 2, X]" to logicProgramming { listOf("a", 2, "X") }, + "{}" to logicProgramming { emptyBlock }, + "{ }" to logicProgramming { emptyBlock }, + "{ 1 }" to logicProgramming { blockOf(1) }, + "{ 1, a }" to logicProgramming { blockOf(1, "a") }, + "{ 1, a, X }" to logicProgramming { blockOf(1, "a", "X") }, + "abc" to logicProgramming { atomOf("abc") }, + "Abc" to logicProgramming { varOf("Abc") }, + "'abc'" to logicProgramming { atomOf("abc") }, + "'Abc'" to logicProgramming { atomOf("Abc") }, + "'Abc d'" to logicProgramming { atomOf("Abc d") }, + "'1'" to logicProgramming { atomOf("1") }, + "'1.2'" to logicProgramming { atomOf("1.2") }, + "\"abc\"" to logicProgramming { atomOf("abc") }, + "\"Abc\"" to logicProgramming { atomOf("Abc") }, + "\"Abc d\"" to logicProgramming { atomOf("Abc d") }, + "\"1\"" to logicProgramming { atomOf("1") }, + "\"1.2\"" to logicProgramming { atomOf("1.2") }, + "1" to logicProgramming { numOf(1) }, + "1.2" to logicProgramming { numOf("1.2") }, + "-1" to logicProgramming { numOf(-1) }, + "-1.2" to logicProgramming { numOf("-1.2") }, + "${BigInteger.of("".padEnd(17, 'F'), 16)}" to logicProgramming { + numOf(BigInteger.of("295147905179352825855")) + }, + "0xFF" to logicProgramming { numOf(255) }, + "0XFF" to logicProgramming { numOf(255) }, + "-0xFF" to logicProgramming { numOf(-255) }, + "-0XFF" to logicProgramming { numOf(-255) }, + "0b111" to logicProgramming { numOf(7) }, + "0B111" to logicProgramming { numOf(7) }, + "-0b111" to logicProgramming { numOf(-7) }, + "-0B111" to logicProgramming { numOf(-7) }, + "0o11" to logicProgramming { numOf(9) }, + "0O11" to logicProgramming { numOf(9) }, + "-0o11" to logicProgramming { numOf(-9) }, + "-0O11" to logicProgramming { numOf(-9) }, + "0O11" to logicProgramming { numOf(9) }, + "0'a" to logicProgramming { numOf(97) }, + "-0'a" to logicProgramming { numOf(-97) }, + "${BigDecimal.PI}" to logicProgramming { numOf(BigDecimal.PI) }, + "(+)" to logicProgramming { atomOf("+") }, + "(-)" to logicProgramming { atomOf("-") }, + "$" to logicProgramming { atomOf("$") }, + "+(1)" to logicProgramming { structOf("+", 1) }, + "-(1)" to logicProgramming { structOf("-", 1) }, + "$(1)" to logicProgramming { structOf("$", 1) }, + "+(1, 2)" to logicProgramming { structOf("+", 1, 2) }, + "-(1, 2)" to logicProgramming { structOf("-", 1, 2) }, + "$(1, 2)" to logicProgramming { structOf("$", 1, 2) }, + "'+'(1)" to logicProgramming { structOf("+", 1) }, + "'-'(1)" to logicProgramming { structOf("-", 1) }, + "'$'(1)" to logicProgramming { structOf("$", 1) }, + "'+'(1, 2)" to logicProgramming { structOf("+", 1, 2) }, + "'-'(1, 2)" to logicProgramming { structOf("-", 1, 2) }, + "'$'(1, 2)" to logicProgramming { structOf("$", 1, 2) }, + "'F'(1, 2)" to logicProgramming { structOf("F", 1, 2) }, + "'true'(3)" to logicProgramming { structOf("true", 3) }, + "'false'(4)" to logicProgramming { structOf("false", 4) }, + "'fail'(5)" to logicProgramming { structOf("fail", 5) }, + "true(0)" to logicProgramming { structOf("true", 0) }, + "false(1)" to logicProgramming { structOf("false", 1) }, + "fail(2)" to logicProgramming { structOf("fail", 2) }, + ) - val expressions: Sequence> = sequenceOf( - "g(X, y, f(3, a))" to logicProgramming { "g"("X", "y", "f"(3, "a")) }, - "g(X, y, (3, a))" to logicProgramming { "g"("X", "y", 3 and "a") }, - "1 + 2" to logicProgramming { - 1.toTerm() + 2 - }, - "3 + 4 * 5 - 1" to logicProgramming { - (3.toTerm() + (4.toTerm() * 5)).toTerm() - 1 - }, - "A; _" to logicProgramming { - "A" or `_` - }, - "a; B :- 1" to logicProgramming { - "a" or "B" impliedBy 1 - }, - "a :- 1; '2'" to logicProgramming { - "a" impliedBy (1 or "2") - }, - "a; B :- 1, 3.1; '2'" to logicProgramming { - "a" or "B" impliedBy - (1 and 3.1 or "2") - }, - "a, c(D); B :- 1, 3.1; '2'" to logicProgramming { - "a" and "c"("D") or "B" impliedBy - (1 and 3.1 or "2") - }, - "a; B, c(D) :- 1, \"4\"; '2', 3.1" to logicProgramming { - "a" or ("B" and "c"("D")) impliedBy - (1 and "4" or ("2" and 3.1)) - }, - "a, c(D); B, e(_f, [g]) :- 1; '2', 3.1" to logicProgramming { - ("a" and "c"("D") or ("B" and "e"("_f", listOf("g")))) impliedBy - (1 or ("2" and 3.1)) - }, - "a, 3 -> 5; 5.3, 1 -> 6 :- a; b, c" to logicProgramming { - (("a" and 3) then 5) or ((5.3 and 1) then 6) impliedBy - ("a" or ("b" and "c")) - }, - "first_step(X, [X])" to logicProgramming { - "first_step"("X", listOf("X")) - }, - "sec_step(X,[_|L]) :- first_step(X,L)" to logicProgramming { - "sec_step"("X", consOf(`_`, "L")) impliedBy - ("first_step"("X", "L")) - }, - "last_but_one(X,[X,_])" to logicProgramming { - "last_but_one"("X", listOf("X", `_`)) - }, - "last_but_one(X,[_,Y|Ys]) :- last_but_one(X,[Y|Ys])" to logicProgramming { - "last_but_one"("X", consOf(`_`, consOf("Y", "Ys"))) impliedBy - "last_but_one"("X", consOf("Y", "Ys")) - }, - "element_at(X,[_|L],K) :- K > 1, K1 is K - 1, element_at(X,L,K1)" to logicProgramming { - "element_at"("X", consOf(`_`, "L"), "K") impliedBy - (("K" greaterThan 1) and (("K1" `is` ("K" - 1)) and ("element_at"("X", "L", "K1")))) - }, - "my_length([],0)" to logicProgramming { - "my_length"(emptyList, 0) - }, - "my_length([_|L],N) :- my_length(L,N1), N is N1 + 1" to logicProgramming { - "my_length"(consOf(`_`, "L"), "N") impliedBy - ("my_length"("L", "N1") and (("N" `is` ("N1".toTerm() + 1)))) - }, - "my_reverse(L1,L2) :- my_rev(L1,L2,[])" to logicProgramming { - "my_reverse"("L1", "L2") impliedBy - "my_rev"("L1", "L2", emptyList) - }, - "my_rev([],L2,L2) :- !" to logicProgramming { - "my_rev"(emptyList, "L2", "L2") impliedBy "!" - }, - "my_rev([X|Xs],L2,Acc) :- my_rev(Xs,L2,[X|Acc])" to logicProgramming { - "my_rev"(consOf("X", "Xs"), "L2", "Acc") impliedBy - "my_rev"("Xs", "L2", consOf("X", "Acc")) - }, - "is_palindrome(L) :- reverse(L,L)" to logicProgramming { - "is_palindrome"("L") impliedBy - "reverse"("L", "L") - }, - "my_flatten(X,[X]) :- \\+ is_list(X)" to logicProgramming { - "my_flatten"("X", listOf("X")) impliedBy - "\\+"("is_list"("X")) - }, - "my_flatten([],[])" to logicProgramming { - "my_flatten"(emptyList, emptyList) - }, - "my_flatten([X|Xs],Zs) :- my_flatten(X,Y), my_flatten(Xs,Ys), append(Y,Ys,Zs)" to logicProgramming { - "my_flatten"(consOf("X", "Xs"), "Zs") impliedBy - ("my_flatten"("X", "Y") and ("my_flatten"("Xs", "Ys") and "append"("Y", "Ys", "Zs"))) - }, - "compress([X,Y|Ys],[X|Zs]) :- X \\= Y, compress([Y|Ys],Zs)" to logicProgramming { - "compress"(consOf("X", consOf("Y", "Ys")), consOf("X", "Zs")) impliedBy - ("\\="("X", "Y") and "compress"(consOf("Y", "Ys"), "Zs")) - }, - "count(X,[],[],N,[N,X]) :- N > 1" to logicProgramming { - "count"("X", emptyList, emptyList, "N", consOf("N", "X")) impliedBy - ("N" greaterThan 1) - }, - "count(X,[Y|Ys],[Y|Ys],1,X) :- X \\= Y" to logicProgramming { - "count"("X", consOf("Y", "Ys"), consOf("Y", "Ys"), 1, "X") impliedBy - ("\\="("X", "Y")) - }, - "count(X,[Y|Ys],[Y|Ys],N,[N,X]) :- N > 1, X \\= Y" to logicProgramming { - "count"("X", consOf("Y", "Ys"), consOf("Y", "Ys"), "N", consOf("N", "X")) impliedBy - (("N" greaterThan 1) and ("\\="("X", "Y"))) - }, - "count(X,[X|Xs],Ys,K,T) :- K1 is K + 1, count(X,Xs,Ys,K1,T)" to logicProgramming { - "count"("X", consOf("X", "Xs"), "Ys", "K", "T") impliedBy - (("K1" `is` ("K".toTerm() + 1)) and ("count"("X", "Xs", "Ys", "K1", "T"))) - }, - "map_upper_bound(XMax, YMax) :- map_size(XSize, YSize), XMax is XSize - 1, YMax is YSize - 1" to logicProgramming { - "map_upper_bound"("XMax", "YMax") impliedBy - ("map_size"("XSize", "YSize") and (("XMax" `is` ("XSize" - 1)) and ("YMax" `is` ("YSize" - 1)))) - }, - "in_map(X, Y) :- X >= 0, Y >= 0, map_size(XSize, YSize), X < XSize, Y < YSize" to logicProgramming { - "in_map"("X", "Y") impliedBy - (("X" greaterThanOrEqualsTo 0) and (("Y" greaterThanOrEqualsTo 0) and ("map_size"("XSize", "YSize") and (("X" lowerThan ("XSize")) and ("Y" lowerThan "YSize"))))) - }, - "tile(wall, X, Y) :- \\+ in_map(X, Y)" to logicProgramming { - "tile"("wall", "X", "Y") impliedBy - ("\\+"("in_map"("X", "Y"))) - }, - "draw_char(X, Y) :- tty_size(_, XSize), X >= XSize, NY is Y + 1, draw_char(0, NY)" to logicProgramming { - "draw_char"("X", "Y") impliedBy - ("tty_size"(`_`, "XSize") and (("X" greaterThanOrEqualsTo "XSize") and (("NY" `is` ("Y".toTerm() + 1)) and ("draw_char"(0, "NY"))))) - }, - "Y < YMsgs -> write(' ') ; display_offset(XOff, YOff), XMap is X + XOff, YMap is Y + YOff, get_character(XMap, YMap, C), format('~s', [C])" to logicProgramming { - (("Y" lowerThan "YMsgs") then "write"(" ")) or - ( - "display_offset"("XOff", "YOff") and ( - ("XMap" `is` ("X".toTerm() + "XOff")) and ( - ("YMap" `is` ("Y".toTerm() + "YOff")) and - ("get_character"("XMap", "YMap", "C") and ("format"("~s", listOf("C")))) + @Suppress("ktlint:standard:max-line-length") + val expressions: Sequence> = + sequenceOf( + "g(X, y, f(3, a))" to logicProgramming { "g"("X", "y", "f"(3, "a")) }, + "g(X, y, (3, a))" to logicProgramming { "g"("X", "y", 3 and "a") }, + "1 + 2" to + logicProgramming { + 1.toTerm() + 2 + }, + "3 + 4 * 5 - 1" to + logicProgramming { + (3.toTerm() + (4.toTerm() * 5)).toTerm() - 1 + }, + "A; _" to + logicProgramming { + "A" or `_` + }, + "a; B :- 1" to + logicProgramming { + "a" or "B" impliedBy 1 + }, + "a :- 1; '2'" to + logicProgramming { + "a" impliedBy (1 or "2") + }, + "a; B :- 1, 3.1; '2'" to + logicProgramming { + "a" or "B" impliedBy + (1 and 3.1 or "2") + }, + "a, c(D); B :- 1, 3.1; '2'" to + logicProgramming { + "a" and "c"("D") or "B" impliedBy + (1 and 3.1 or "2") + }, + "a; B, c(D) :- 1, \"4\"; '2', 3.1" to + logicProgramming { + "a" or ("B" and "c"("D")) impliedBy + (1 and "4" or ("2" and 3.1)) + }, + "a, c(D); B, e(_f, [g]) :- 1; '2', 3.1" to + logicProgramming { + ("a" and "c"("D") or ("B" and "e"("_f", listOf("g")))) impliedBy + (1 or ("2" and 3.1)) + }, + "a, 3 -> 5; 5.3, 1 -> 6 :- a; b, c" to + logicProgramming { + (("a" and 3) then 5) or ((5.3 and 1) then 6) impliedBy + ("a" or ("b" and "c")) + }, + "first_step(X, [X])" to + logicProgramming { + "first_step"("X", listOf("X")) + }, + "sec_step(X,[_|L]) :- first_step(X,L)" to + logicProgramming { + "sec_step"("X", consOf(`_`, "L")) impliedBy + ("first_step"("X", "L")) + }, + "last_but_one(X,[X,_])" to + logicProgramming { + "last_but_one"("X", listOf("X", `_`)) + }, + "last_but_one(X,[_,Y|Ys]) :- last_but_one(X,[Y|Ys])" to + logicProgramming { + "last_but_one"("X", consOf(`_`, consOf("Y", "Ys"))) impliedBy + "last_but_one"("X", consOf("Y", "Ys")) + }, + "element_at(X,[_|L],K) :- K > 1, K1 is K - 1, element_at(X,L,K1)" to + logicProgramming { + "element_at"("X", consOf(`_`, "L"), "K") impliedBy + (("K" greaterThan 1) and (("K1" `is` ("K" - 1)) and ("element_at"("X", "L", "K1")))) + }, + "my_length([],0)" to + logicProgramming { + "my_length"(emptyList, 0) + }, + "my_length([_|L],N) :- my_length(L,N1), N is N1 + 1" to + logicProgramming { + "my_length"(consOf(`_`, "L"), "N") impliedBy + ("my_length"("L", "N1") and (("N" `is` ("N1".toTerm() + 1)))) + }, + "my_reverse(L1,L2) :- my_rev(L1,L2,[])" to + logicProgramming { + "my_reverse"("L1", "L2") impliedBy + "my_rev"("L1", "L2", emptyList) + }, + "my_rev([],L2,L2) :- !" to + logicProgramming { + "my_rev"(emptyList, "L2", "L2") impliedBy "!" + }, + "my_rev([X|Xs],L2,Acc) :- my_rev(Xs,L2,[X|Acc])" to + logicProgramming { + "my_rev"(consOf("X", "Xs"), "L2", "Acc") impliedBy + "my_rev"("Xs", "L2", consOf("X", "Acc")) + }, + "is_palindrome(L) :- reverse(L,L)" to + logicProgramming { + "is_palindrome"("L") impliedBy + "reverse"("L", "L") + }, + "my_flatten(X,[X]) :- \\+ is_list(X)" to + logicProgramming { + "my_flatten"("X", listOf("X")) impliedBy + "\\+"("is_list"("X")) + }, + "my_flatten([],[])" to + logicProgramming { + "my_flatten"(emptyList, emptyList) + }, + "my_flatten([X|Xs],Zs) :- my_flatten(X,Y), my_flatten(Xs,Ys), append(Y,Ys,Zs)" to + logicProgramming { + "my_flatten"(consOf("X", "Xs"), "Zs") impliedBy + ("my_flatten"("X", "Y") and ("my_flatten"("Xs", "Ys") and "append"("Y", "Ys", "Zs"))) + }, + "compress([X,Y|Ys],[X|Zs]) :- X \\= Y, compress([Y|Ys],Zs)" to + logicProgramming { + "compress"(consOf("X", consOf("Y", "Ys")), consOf("X", "Zs")) impliedBy + ("\\="("X", "Y") and "compress"(consOf("Y", "Ys"), "Zs")) + }, + "count(X,[],[],N,[N,X]) :- N > 1" to + logicProgramming { + "count"("X", emptyList, emptyList, "N", consOf("N", "X")) impliedBy + ("N" greaterThan 1) + }, + "count(X,[Y|Ys],[Y|Ys],1,X) :- X \\= Y" to + logicProgramming { + "count"("X", consOf("Y", "Ys"), consOf("Y", "Ys"), 1, "X") impliedBy + ("\\="("X", "Y")) + }, + "count(X,[Y|Ys],[Y|Ys],N,[N,X]) :- N > 1, X \\= Y" to + logicProgramming { + "count"("X", consOf("Y", "Ys"), consOf("Y", "Ys"), "N", consOf("N", "X")) impliedBy + (("N" greaterThan 1) and ("\\="("X", "Y"))) + }, + "count(X,[X|Xs],Ys,K,T) :- K1 is K + 1, count(X,Xs,Ys,K1,T)" to + logicProgramming { + "count"("X", consOf("X", "Xs"), "Ys", "K", "T") impliedBy + (("K1" `is` ("K".toTerm() + 1)) and ("count"("X", "Xs", "Ys", "K1", "T"))) + }, + "map_upper_bound(XMax, YMax) :- map_size(XSize, YSize), XMax is XSize - 1, YMax is YSize - 1" to + logicProgramming { + "map_upper_bound"("XMax", "YMax") impliedBy + ("map_size"("XSize", "YSize") and (("XMax" `is` ("XSize" - 1)) and ("YMax" `is` ("YSize" - 1)))) + }, + "in_map(X, Y) :- X >= 0, Y >= 0, map_size(XSize, YSize), X < XSize, Y < YSize" to + logicProgramming { + "in_map"("X", "Y") impliedBy + (("X" greaterThanOrEqualsTo 0) and (("Y" greaterThanOrEqualsTo 0) and ("map_size"("XSize", "YSize") and (("X" lowerThan ("XSize")) and ("Y" lowerThan "YSize"))))) + }, + "tile(wall, X, Y) :- \\+ in_map(X, Y)" to + logicProgramming { + "tile"("wall", "X", "Y") impliedBy + ("\\+"("in_map"("X", "Y"))) + }, + "draw_char(X, Y) :- tty_size(_, XSize), X >= XSize, NY is Y + 1, draw_char(0, NY)" to + logicProgramming { + "draw_char"("X", "Y") impliedBy + ("tty_size"(`_`, "XSize") and (("X" greaterThanOrEqualsTo "XSize") and (("NY" `is` ("Y".toTerm() + 1)) and ("draw_char"(0, "NY"))))) + }, + "Y < YMsgs -> write(' ') ; display_offset(XOff, YOff), XMap is X + XOff, YMap is Y + YOff, get_character(XMap, YMap, C), format('~s', [C])" to + logicProgramming { + (("Y" lowerThan "YMsgs") then "write"(" ")) or + ( + "display_offset"("XOff", "YOff") and ( + ("XMap" `is` ("X".toTerm() + "XOff")) and ( + ("YMap" `is` ("Y".toTerm() + "YOff")) and + ("get_character"("XMap", "YMap", "C") and ("format"("~s", listOf("C")))) + ) ) ) - ) - }, - "display_offset(X, Y) :- player(XPos, YPos), tty_size(YSize, XSize), message_lines(YMsgs), X is XPos - floor(XSize / 2), Y is YPos - floor((YSize - YMsgs) / 2)" to logicProgramming { - "display_offset"("X", "Y") impliedBy - ( - "player"("XPos", "YPos") and ( - "tty_size"("YSize", "XSize")and ( - "message_lines"("YMsgs") and ( - ("X" `is` ("XPos" - "floor"("XSize" / 2))) and (("Y" `is` ("YPos" - "floor"(("YSize" - "YMsgs") / 2)))) + }, + "display_offset(X, Y) :- player(XPos, YPos), tty_size(YSize, XSize), message_lines(YMsgs), X is XPos - floor(XSize / 2), Y is YPos - floor((YSize - YMsgs) / 2)" to + logicProgramming { + "display_offset"("X", "Y") impliedBy + ( + "player"("XPos", "YPos") and ( + "tty_size"("YSize", "XSize")and ( + "message_lines"("YMsgs") and ( + ("X" `is` ("XPos" - "floor"("XSize" / 2))) and (("Y" `is` ("YPos" - "floor"(("YSize" - "YMsgs") / 2)))) + ) ) ) ) - ) - } - ) + }, + ) val all = canonicalTerms + expressions } diff --git a/parser-core/src/commonTest/kotlin/it/unibo/tuprolog/core/parsing/test/TermParserTest.kt b/parser-core/src/commonTest/kotlin/it/unibo/tuprolog/core/parsing/test/TermParserTest.kt index 57e348dea..582139ca6 100644 --- a/parser-core/src/commonTest/kotlin/it/unibo/tuprolog/core/parsing/test/TermParserTest.kt +++ b/parser-core/src/commonTest/kotlin/it/unibo/tuprolog/core/parsing/test/TermParserTest.kt @@ -4,7 +4,6 @@ import it.unibo.tuprolog.core.parsing.TermParser import kotlin.test.Test class TermParserTest { - @Test fun testParsingWithCanonicalTerms() { val parser = TermParser.withNoOperator() diff --git a/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/Conversions.kt b/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/Conversions.kt index fc57f6811..c7bf8ad41 100644 --- a/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/Conversions.kt +++ b/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/Conversions.kt @@ -2,8 +2,6 @@ package it.unibo.tuprolog.core.parsing import it.unibo.tuprolog.core.operators.Specifier -fun String.toSpecifier(): Specifier = - Specifier.valueOf(uppercase()) +fun String.toSpecifier(): Specifier = Specifier.valueOf(uppercase()) -fun Specifier.toAssociativity(): String = - toString() +fun Specifier.toAssociativity(): String = toString() diff --git a/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/DynamicOpListener.kt b/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/DynamicOpListener.kt index 3dab80a74..16bb215a5 100644 --- a/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/DynamicOpListener.kt +++ b/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/DynamicOpListener.kt @@ -14,11 +14,11 @@ import kotlin.math.max import kotlin.math.min import it.unibo.tuprolog.core.List as LogicList +@Suppress("CyclomaticComplexMethod", "NestedBlockDepth", "MagicNumber") class DynamicOpListener private constructor( private val parser: PrologParser, - private val operatorDefinedCallback: PrologParser?.(Operator) -> Unit + private val operatorDefinedCallback: PrologParser?.(Operator) -> Unit, ) : PrologParserListener() { - override fun exitClause(ctx: ClauseContext) { val expr = ctx.expression() if (ctx.exception != null) { @@ -27,8 +27,8 @@ class DynamicOpListener private constructor( if (expr._op != null && ":-" == expr._op?.symbol?.text && expr.associativity in Associativity.PREFIX) { val directive = ctx.accept(PrologVisitor()) as Directive val op = directive.body - if (op is Struct && op.arity == 3 && op.functor == "op" && op[0] is Numeric && op[1] is Atom && op.isGround) { - val priority = min(1200, max(0, (op[0] as Numeric).intValue.toInt())) + if (op.isOpDirective) { + val priority = min(1200, max(0, ((op as Struct)[0] as Numeric).intValue.toInt())) val specifier = Specifier.fromTerm(op[1]) when (val operator = op[2]) { is Atom -> { @@ -56,7 +56,10 @@ class DynamicOpListener private constructor( return DynamicOpListener(parser) { } } - fun of(parser: PrologParser, operatorDefinedCallback: PrologParser?.(Operator) -> Unit): DynamicOpListener { + fun of( + parser: PrologParser, + operatorDefinedCallback: PrologParser?.(Operator) -> Unit, + ): DynamicOpListener { return DynamicOpListener(parser, operatorDefinedCallback) } } diff --git a/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/ParseExceptionExt.kt b/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/ParseExceptionExt.kt index 7ef0cbd03..4906c3e9d 100644 --- a/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/ParseExceptionExt.kt +++ b/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/ParseExceptionExt.kt @@ -2,14 +2,25 @@ package it.unibo.tuprolog.core.parsing import it.unibo.tuprolog.parser.Token -fun parseException(input: Any?, token: Token, message: String?, throwable: Throwable?) = - ParseException(input, token.text, token.line, token.column, message, throwable) +fun parseException( + input: Any?, + token: Token, + message: String?, + throwable: Throwable?, +) = ParseException(input, token.text, token.line, token.column, message, throwable) -fun parseException(token: Token, message: String?, throwable: Throwable?) = - ParseException(null, token.text, token.line, token.column, message, throwable) +fun parseException( + token: Token, + message: String?, + throwable: Throwable?, +) = ParseException(null, token.text, token.line, token.column, message, throwable) -fun parseException(token: Token, message: String?) = - ParseException(null, token.text, token.line, token.column, message, null) +fun parseException( + token: Token, + message: String?, +) = ParseException(null, token.text, token.line, token.column, message, null) -fun parseException(token: Token, throwable: Throwable?) = - ParseException(null, token.text, token.line, token.column, "", throwable) +fun parseException( + token: Token, + throwable: Throwable?, +) = ParseException(null, token.text, token.line, token.column, "", throwable) diff --git a/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/PrologParserFactory.kt b/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/PrologParserFactory.kt index d3b273285..be78eddb8 100644 --- a/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/PrologParserFactory.kt +++ b/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/PrologParserFactory.kt @@ -16,8 +16,8 @@ import it.unibo.tuprolog.parser.Token import it.unibo.tuprolog.parser.isParseCancellationException import it.unibo.tuprolog.parser.isRecognitionException +@Suppress("TooManyFunctions") object PrologParserFactory { - private fun newErrorListener(whileParsing: Any): dynamic { return object { private fun symbolToString(obj: dynamic): String { @@ -35,7 +35,7 @@ object PrologParserFactory { line: Int, column: Int, msg: String, - e: RecognitionException + e: RecognitionException, ) { if (recognizer is PrologParser) { recognizer.removeParseListeners() @@ -46,21 +46,27 @@ object PrologParserFactory { line, column + 1, msg, - e + e, ) } } } - fun parseExpression(string: String): SingletonExpressionContext = - parseExpression(string, OperatorSet.EMPTY) + fun parseExpression(string: String): SingletonExpressionContext = parseExpression(string, OperatorSet.EMPTY) - fun parseExpression(string: String, withOperators: OperatorSet): SingletonExpressionContext { + fun parseExpression( + string: String, + withOperators: OperatorSet, + ): SingletonExpressionContext { val parser = createParser(string, withOperators) return parseExpression(parser, string) } - private fun parseExpression(parserAndErrorStrategy: Pair, source: String): SingletonExpressionContext { + @Suppress("InstanceOfCheckForException", "SwallowedException") + private fun parseExpression( + parserAndErrorStrategy: Pair, + source: String, + ): SingletonExpressionContext { var mark = -1 var index = -1 val parser = parserAndErrorStrategy.first @@ -92,21 +98,25 @@ object PrologParserFactory { fun parseExpressionWithStandardOperators(string: String): SingletonExpressionContext = parseExpression(string, OperatorSet.DEFAULT) - fun parseClauses(source: String, withOperators: OperatorSet): Sequence { + fun parseClauses( + source: String, + withOperators: OperatorSet, + ): Sequence { val parser = createParser(source, withOperators) return parseClauses(parser, source) } - fun parseClauses(source: String): Sequence = - parseClauses(source, OperatorSet.EMPTY) + fun parseClauses(source: String): Sequence = parseClauses(source, OperatorSet.EMPTY) fun parseClausesWithStandardOperators(source: String): Sequence = parseClauses(source, OperatorSet.DEFAULT) - fun createParser(string: String): Pair = - createParser(string, OperatorSet.DEFAULT) + fun createParser(string: String): Pair = createParser(string, OperatorSet.DEFAULT) - fun createParser(source: String, operators: OperatorSet): Pair { + fun createParser( + source: String, + operators: OperatorSet, + ): Pair { val stream = InputStream(source) val lexer = PrologLexer(stream) lexer.removeErrorListeners() @@ -119,7 +129,10 @@ object PrologParserFactory { return addOperators(parser, operators) to originalErrorStrategy } - fun addOperators(prologParser: PrologParser, operators: OperatorSet): PrologParser { + fun addOperators( + prologParser: PrologParser, + operators: OperatorSet, + ): PrologParser { operators.forEach { prologParser.addOperator(it.functor, it.specifier.toAssociativity(), it.priority) } @@ -127,7 +140,11 @@ object PrologParserFactory { return prologParser } - private fun parseClause(parserAndErrorStrategy: Pair, source: Any): OptClauseContext { + @Suppress("InstanceOfCheckForException", "SwallowedException") + private fun parseClause( + parserAndErrorStrategy: Pair, + source: Any, + ): OptClauseContext { var mark = -1 var index = -1 val parser = parserAndErrorStrategy.first @@ -156,7 +173,10 @@ object PrologParserFactory { } } - private fun parseClauses(parser: Pair, source: Any): Sequence { + private fun parseClauses( + parser: Pair, + source: Any, + ): Sequence { return generateSequence(0) { it + 1 } .map { try { diff --git a/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/PrologVisitor.kt b/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/PrologVisitor.kt index ebbc50e9d..9e3f65eaf 100644 --- a/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/PrologVisitor.kt +++ b/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/PrologVisitor.kt @@ -30,13 +30,11 @@ import it.unibo.tuprolog.parser.TermContext import it.unibo.tuprolog.parser.VariableContext import org.gciatto.kt.math.BigInteger +@Suppress("TooManyFunctions") class PrologVisitor(private val scope: Scope = Scope.empty()) : PrologParserVisitor() { + override fun visitSingletonTerm(ctx: SingletonTermContext): Term = visitTerm(ctx.term()) - override fun visitSingletonTerm(ctx: SingletonTermContext): Term = - visitTerm(ctx.term()) - - override fun visitSingletonExpression(ctx: SingletonExpressionContext): Term = - visitExpression(ctx.expression()) + override fun visitSingletonExpression(ctx: SingletonExpressionContext): Term = visitExpression(ctx.expression()) override fun visitClause(ctx: ClauseContext): Term = ctx.expression().accept(this).toClause(null, ctx.start!!.line, ctx.start!!.column) @@ -48,9 +46,11 @@ class PrologVisitor(private val scope: Scope = Scope.empty()) : PrologParserVisi INFIX.contains(ctx.associativity) -> visitInfixExpression(ctx) POSTFIX.contains(ctx.associativity) -> visitPostfixExpression(ctx) PREFIX.contains(ctx.associativity) -> visitPrefixExpression(ctx) - else -> throw IllegalArgumentException("Associativity unknown: ${ctx.associativity} INFIX=$INFIX PREFIX=$PREFIX POSTFIX=$POSTFIX") + else -> throw IllegalArgumentException( + "Associativity unknown: ${ctx.associativity} INFIX=$INFIX PREFIX=$PREFIX POSTFIX=$POSTFIX", + ) }, - flatten(ctx.outers.asList()) + flatten(ctx.outers.asList()), ) } @@ -80,7 +80,7 @@ class PrologVisitor(private val scope: Scope = Scope.empty()) : PrologParserVisi } catch (notAFloating: NumberFormatException) { throw parseException( ctx.value, - "Invalid real number format: " + ctx.value.text + "Invalid real number format: " + ctx.value.text, ) } } @@ -93,17 +93,16 @@ class PrologVisitor(private val scope: Scope = Scope.empty()) : PrologParserVisi } override fun visitStructure(ctx: StructureContext): Term { - if (ctx.isList) { - return scope.listOf() + return if (ctx.isList) { + scope.listOf() } else if (ctx.isBlock) { - return scope.blockOf() - } - return if (ctx.arity == 0) { + scope.blockOf() + } else if (ctx.arity == 0) { scope.atomOf(ctx.functor.text) } else { scope.structOf( ctx.functor.text, - ctx.args.asSequence().map(this::visitExpression) + ctx.args.asSequence().map(this::visitExpression), ) } } @@ -125,6 +124,7 @@ class PrologVisitor(private val scope: Scope = Scope.empty()) : PrologParserVisi } } + @Suppress("MagicNumber") private fun parseInteger(ctx: IntegerContext): BigInteger { val str = ctx.value.text val base: Int @@ -147,7 +147,7 @@ class PrologVisitor(private val scope: Scope = Scope.empty()) : PrologParserVisi if (clean.length != 1) { throw parseException( ctx.value, - "Invalid character literal: " + ctx.value.text + "Invalid character literal: " + ctx.value.text, ) } return with(BigInteger.of(clean[0].code)) { @@ -174,10 +174,13 @@ class PrologVisitor(private val scope: Scope = Scope.empty()) : PrologParserVisi ctx.left?.accept(this)!!, ctx.operators.map { it.symbol.text - } + }, ) - private fun postfix(term: Term, ops: List): Term { + private fun postfix( + term: Term, + ops: List, + ): Term { val operator = ops.iterator() var result: Term = scope.structOf(operator.next(), term) while (operator.hasNext()) { @@ -191,10 +194,13 @@ class PrologVisitor(private val scope: Scope = Scope.empty()) : PrologParserVisi ctx.right[0].accept(this), ctx.operators.map { it.symbol.text - } + }, ) - private fun prefix(term: Term, ops: List): Term { + private fun prefix( + term: Term, + ops: List, + ): Term { var i = ops.size - 1 var result: Term = scope.structOf(ops[i--], term) while (i >= 0) { @@ -209,7 +215,7 @@ class PrologVisitor(private val scope: Scope = Scope.empty()) : PrologParserVisi XFY -> visitInfixRightAssociativeExpression(ctx) YFX -> visitInfixLeftAssociativeExpression(ctx) XFX -> visitInfixNonAssociativeExpression(ctx) - else -> throw IllegalStateException() + else -> error("Non-infix associativity ${ctx.associativity} in infix expression") } } @@ -219,28 +225,38 @@ class PrologVisitor(private val scope: Scope = Scope.empty()) : PrologParserVisi return infixNonAssociative(operands, operators) } - private fun infixNonAssociative(terms: List, ops: List): Term { + private fun infixNonAssociative( + terms: List, + ops: List, + ): Term { return scope.structOf(ops[0], terms[0], terms[1]) } - private fun handleOuters(expression: Term, outers: List): Term { + private fun handleOuters( + expression: Term, + outers: List, + ): Term { var result = expression for (o in outers) { val operands = listOf(result) + o.right.map { it.accept(this) } val operators = o.operators.map { it.symbol.text } - result = when (o.associativity) { - XFY -> infixRight(operands, operators) - XF, YF -> postfix(result, operators) - XFX -> infixNonAssociative(operands, operators) - YFX -> infixLeft(operands, operators) - FX, FY -> prefix(result, operators) - else -> throw IllegalStateException() - } + result = + when (val associativity = o.associativity) { + XFY -> infixRight(operands, operators) + XF, YF -> postfix(result, operators) + XFX -> infixNonAssociative(operands, operators) + YFX -> infixLeft(operands, operators) + FX, FY -> prefix(result, operators) + else -> error("Invalid associativity: $associativity") + } } return result } - private fun infixRight(terms: List, ops: List): Term { + private fun infixRight( + terms: List, + ops: List, + ): Term { var i = terms.size - 1 var j = ops.size - 1 var result: Term = scope.structOf(ops[j--], terms[i - 1], terms[i]) @@ -252,7 +268,10 @@ class PrologVisitor(private val scope: Scope = Scope.empty()) : PrologParserVisi return result } - private fun infixLeft(terms: List, ops: List): Term { + private fun infixLeft( + terms: List, + ops: List, + ): Term { var i = 0 var j = 0 var result: Term = scope.structOf(ops[j++], terms[i++], terms[i++]) @@ -266,8 +285,7 @@ class PrologVisitor(private val scope: Scope = Scope.empty()) : PrologParserVisi private fun listOfOperands(ctx: ExpressionContext): List = (listOf(ctx.left) + ctx.right.toList()).map { it!!.accept(this) } - private fun listOfOperators(ctx: ExpressionContext): List = - ctx.operators.map { it.symbol.text } + private fun listOfOperators(ctx: ExpressionContext): List = ctx.operators.map { it.symbol.text } private fun visitInfixRightAssociativeExpression(ctx: ExpressionContext): Term = infixRight(listOfOperands(ctx), listOfOperators(ctx)) @@ -280,6 +298,5 @@ class PrologVisitor(private val scope: Scope = Scope.empty()) : PrologParserVisi sequenceOf(it) + flatten(it.outers.asSequence()) } - private fun flatten(outers: List): List = - flatten(outers.asSequence()).toList() + private fun flatten(outers: List): List = flatten(outers.asSequence()).toList() } diff --git a/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/TermParserExtensions.kt b/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/TermParserExtensions.kt index 8cddf081a..74ea67a20 100644 --- a/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/TermParserExtensions.kt +++ b/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/TermParserExtensions.kt @@ -3,5 +3,7 @@ package it.unibo.tuprolog.core.parsing import it.unibo.tuprolog.core.Scope import it.unibo.tuprolog.core.operators.OperatorSet -actual fun termParserWithOperators(operators: OperatorSet, scope: Scope): TermParser = - TermParserImpl(scope, operators) +actual fun termParserWithOperators( + operators: OperatorSet, + scope: Scope, +): TermParser = TermParserImpl(scope, operators) diff --git a/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/TermParserImpl.kt b/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/TermParserImpl.kt index 9fda07b88..8785b4c8b 100644 --- a/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/TermParserImpl.kt +++ b/parser-core/src/jsMain/kotlin/it/unibo/tuprolog/core/parsing/TermParserImpl.kt @@ -6,8 +6,10 @@ import it.unibo.tuprolog.core.operators.OperatorSet class TermParserImpl( override val scope: Scope, - override val defaultOperatorSet: OperatorSet + override val defaultOperatorSet: OperatorSet, ) : TermParser { - override fun parseTerm(input: String, operators: OperatorSet): Term = - PrologParserFactory.parseExpression(input, operators).accept(PrologVisitor(scope)) + override fun parseTerm( + input: String, + operators: OperatorSet, + ): Term = PrologParserFactory.parseExpression(input, operators).accept(PrologVisitor(scope)) } diff --git a/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/DynamicOpListener.kt b/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/DynamicOpListener.kt index b6bc15870..238f4aa6c 100644 --- a/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/DynamicOpListener.kt +++ b/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/DynamicOpListener.kt @@ -16,11 +16,11 @@ import it.unibo.tuprolog.core.List as LogicList class DynamicOpListener private constructor( parser: PrologParser, - private val operatorDefinedCallback: PrologParser?.(Operator) -> Unit + private val operatorDefinedCallback: PrologParser?.(Operator) -> Unit, ) : PrologParserBaseListener() { - private val parser: WeakReference = WeakReference(parser) + @Suppress("NestedBlockDepth") override fun exitClause(ctx: PrologParser.ClauseContext) { val expr: PrologParser.ExpressionContext = ctx.expression() if (ctx.exception != null) { @@ -29,14 +29,15 @@ class DynamicOpListener private constructor( if (expr.op != null && ":-" == expr.op.symbol.text && expr.associativity in Associativity.PREFIX) { val directive = ctx.accept(PrologExpressionVisitor()) as Directive val op = directive.body - if (op is Struct && op.arity == 3 && op.functor == "op" && op[0] is Numeric && op[1] is Atom && op.isGround) { - val priority = min( - PrologParser.TOP, - max( - PrologParser.BOTTOM, - (op[0] as Numeric).intValue.toInt() + if (op.isOpDirective) { + val priority = + min( + PrologParser.TOP, + max( + PrologParser.BOTTOM, + ((op as Struct)[0] as Numeric).intValue.toInt(), + ), ) - ) val specifier = Specifier.fromTerm(op[1]) when (val operator = op[2]) { is Atom -> { @@ -64,7 +65,10 @@ class DynamicOpListener private constructor( return DynamicOpListener(parser) { } } - fun of(parser: PrologParser, operatorDefinedCallback: PrologParser?.(Operator) -> Unit): DynamicOpListener { + fun of( + parser: PrologParser, + operatorDefinedCallback: PrologParser?.(Operator) -> Unit, + ): DynamicOpListener { return DynamicOpListener(parser, operatorDefinedCallback) } } diff --git a/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/Echo.kt b/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/Echo.kt index 40773ba17..225fc8861 100644 --- a/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/Echo.kt +++ b/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/Echo.kt @@ -10,8 +10,8 @@ fun main() { while (true) { print("> ") - val line = readLine() - val term = parser.parseTerm(line!!) + val line = readlnOrNull() ?: break + val term = parser.parseTerm(line) println(term.format(TermFormatter.prettyExpressions())) } } diff --git a/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/ParseExceptionExt.kt b/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/ParseExceptionExt.kt index e4e0c632a..e7aabf280 100644 --- a/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/ParseExceptionExt.kt +++ b/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/ParseExceptionExt.kt @@ -2,14 +2,25 @@ package it.unibo.tuprolog.core.parsing import org.antlr.v4.runtime.Token -fun parseException(input: Any?, token: Token, message: String?, throwable: Throwable?) = - ParseException(input, token.text, token.line, token.charPositionInLine, message, throwable) +fun parseException( + input: Any?, + token: Token, + message: String?, + throwable: Throwable?, +) = ParseException(input, token.text, token.line, token.charPositionInLine, message, throwable) -fun parseException(token: Token, message: String?, throwable: Throwable?) = - ParseException(null, token.text, token.line, token.charPositionInLine, message, throwable) +fun parseException( + token: Token, + message: String?, + throwable: Throwable?, +) = ParseException(null, token.text, token.line, token.charPositionInLine, message, throwable) -fun parseException(token: Token, message: String?) = - ParseException(null, token.text, token.line, token.charPositionInLine, message, null) +fun parseException( + token: Token, + message: String?, +) = ParseException(null, token.text, token.line, token.charPositionInLine, message, null) -fun parseException(token: Token, throwable: Throwable?) = - ParseException(null, token.text, token.line, token.charPositionInLine, "", throwable) +fun parseException( + token: Token, + throwable: Throwable?, +) = ParseException(null, token.text, token.line, token.charPositionInLine, "", throwable) diff --git a/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/PrologExpressionVisitor.kt b/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/PrologExpressionVisitor.kt index 584267006..82484a2d8 100644 --- a/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/PrologExpressionVisitor.kt +++ b/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/PrologExpressionVisitor.kt @@ -17,10 +17,9 @@ import it.unibo.tuprolog.parser.dynamic.Associativity.YF import it.unibo.tuprolog.parser.dynamic.Associativity.YFX import org.gciatto.kt.math.BigInteger +@Suppress("TooManyFunctions") class PrologExpressionVisitor(private val scope: Scope = Scope.empty()) : PrologParserBaseVisitor() { - - override fun visitSingletonTerm(ctx: PrologParser.SingletonTermContext): Term = - visitTerm(ctx.term()) + override fun visitSingletonTerm(ctx: PrologParser.SingletonTermContext): Term = visitTerm(ctx.term()) override fun visitSingletonExpression(ctx: PrologParser.SingletonExpressionContext): Term = visitExpression(ctx.expression()) @@ -36,9 +35,9 @@ class PrologExpressionVisitor(private val scope: Scope = Scope.empty()) : Prolog POSTFIX.contains(ctx.associativity) -> visitPostfixExpression(ctx) PREFIX.contains(ctx.associativity) -> visitPrefixExpression(ctx) ctx.exception != null -> throw ctx.exception - else -> throw IllegalArgumentException() // use kotlin's IllegalArgumentException + else -> error("Unknown expression type: $ctx") }, - flatten(ctx.outers) + flatten(ctx.outers), ) } @@ -70,17 +69,16 @@ class PrologExpressionVisitor(private val scope: Scope = Scope.empty()) : Prolog } override fun visitStructure(ctx: PrologParser.StructureContext): Term { - if (ctx.isList) { - return scope.listOf() + return if (ctx.isList) { + scope.listOf() } else if (ctx.isBlock) { - return scope.blockOf() - } - return if (ctx.arity == 0) { + scope.blockOf() + } else if (ctx.arity == 0) { scope.atomOf(ctx.functor.text) } else { scope.structOf( ctx.functor.text, - ctx.args.asSequence().map(this::visitExpression) + ctx.args.asSequence().map(this::visitExpression), ) } } @@ -102,7 +100,7 @@ class PrologExpressionVisitor(private val scope: Scope = Scope.empty()) : Prolog } } - @Suppress("NullableBooleanElvis", "UNNECESSARY_SAFE_CALL") + @Suppress("NullableBooleanElvis", "MagicNumber") private fun parseInteger(ctx: PrologParser.IntegerContext): BigInteger { val str = ctx.value.text val base: Int @@ -129,7 +127,7 @@ class PrologExpressionVisitor(private val scope: Scope = Scope.empty()) : Prolog ctx.value.line, ctx.value.charPositionInLine, "Invalid character literal: " + ctx.text, - null + null, ) } return with(BigInteger.of(clean[0].code)) { @@ -156,10 +154,13 @@ class PrologExpressionVisitor(private val scope: Scope = Scope.empty()) : Prolog ctx.left.accept(this), ctx.operators.map { it.symbol.text - } + }, ) - private fun postfix(term: Term, ops: List): Term { + private fun postfix( + term: Term, + ops: List, + ): Term { val operator = ops.iterator() var result: Term = scope.structOf(operator.next(), term) while (operator.hasNext()) { @@ -173,10 +174,13 @@ class PrologExpressionVisitor(private val scope: Scope = Scope.empty()) : Prolog ctx.right[0].accept(this), ctx.operators.map { it.symbol.text - } + }, ) - private fun prefix(term: Term, ops: List): Term { + private fun prefix( + term: Term, + ops: List, + ): Term { var i = ops.size - 1 var result: Term = scope.structOf(ops[i--], term) while (i >= 0) { @@ -191,7 +195,7 @@ class PrologExpressionVisitor(private val scope: Scope = Scope.empty()) : Prolog XFY -> visitInfixRightAssociativeExpression(ctx) YFX -> visitInfixLeftAssociativeExpression(ctx) XFX -> visitInfixNonAssociativeExpression(ctx) - else -> throw IllegalStateException() + else -> error("Expected infix associativity, got ${ctx.associativity} instead") } } @@ -201,27 +205,37 @@ class PrologExpressionVisitor(private val scope: Scope = Scope.empty()) : Prolog return infixNonAssociative(operands, operators) } - private fun infixNonAssociative(terms: List, ops: List): Term { + private fun infixNonAssociative( + terms: List, + ops: List, + ): Term { return scope.structOf(ops[0], terms[0], terms[1]) } - private fun handleOuters(expression: Term, outers: List): Term { + private fun handleOuters( + expression: Term, + outers: List, + ): Term { var result = expression for (o in outers) { val operands = listOf(result) + o.right.map { it.accept(this) } val operators = o.operators.map { it.symbol.text } - result = when (o.associativity!!) { - XFY -> infixRight(operands, operators) - XF, YF -> postfix(result, operators) - XFX -> infixNonAssociative(operands, operators) - YFX -> infixLeft(operands, operators) - FX, FY -> prefix(result, operators) - } + result = + when (o.associativity!!) { + XFY -> infixRight(operands, operators) + XF, YF -> postfix(result, operators) + XFX -> infixNonAssociative(operands, operators) + YFX -> infixLeft(operands, operators) + FX, FY -> prefix(result, operators) + } } return result } - private fun infixRight(terms: List, ops: List): Term { + private fun infixRight( + terms: List, + ops: List, + ): Term { var i = terms.size - 1 var j = ops.size - 1 var result: Term = scope.structOf(ops[j--], terms[i - 1], terms[i]) @@ -233,7 +247,10 @@ class PrologExpressionVisitor(private val scope: Scope = Scope.empty()) : Prolog return result } - private fun infixLeft(terms: List, ops: List): Term { + private fun infixLeft( + terms: List, + ops: List, + ): Term { var i = 0 var j = 0 var result: Term = scope.structOf(ops[j++], terms[i++], terms[i++]) diff --git a/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/PrologParserFactory.kt b/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/PrologParserFactory.kt index df55654ab..20638300d 100644 --- a/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/PrologParserFactory.kt +++ b/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/PrologParserFactory.kt @@ -20,8 +20,8 @@ import org.antlr.v4.runtime.misc.ParseCancellationException import java.io.InputStream import java.io.Reader +@Suppress("TooManyFunctions") object PrologParserFactory { - private fun newErrorListener(whileParsing: Any): ANTLRErrorListener { return object : BaseErrorListener() { private fun symbolToString(obj: Any): String { @@ -38,7 +38,7 @@ object PrologParserFactory { line: Int, charPositionInLine: Int, msg: String, - e: RecognitionException? + e: RecognitionException?, ) { if (recognizer is PrologParser) { recognizer.removeParseListeners() @@ -49,95 +49,140 @@ object PrologParserFactory { line, charPositionInLine + 1, msg, - e + e, ) } } } - fun parseSingletonExpr(string: String, withOperators: OperatorSet): PrologParser.SingletonExpressionContext { + fun parseSingletonExpr( + string: String, + withOperators: OperatorSet, + ): PrologParser.SingletonExpressionContext { val parser = createParser(string, withOperators) return parseSingletonExpr(parser, string) } - fun parseSingletonExpr(string: Reader, withOperators: OperatorSet): PrologParser.SingletonExpressionContext { + fun parseSingletonExpr( + string: Reader, + withOperators: OperatorSet, + ): PrologParser.SingletonExpressionContext { val parser = createParser(string, withOperators) return parseSingletonExpr(parser, string) } - fun parseSingletonExpr(string: InputStream, withOperators: OperatorSet): PrologParser.SingletonExpressionContext { + fun parseSingletonExpr( + string: InputStream, + withOperators: OperatorSet, + ): PrologParser.SingletonExpressionContext { val parser = createParser(string, withOperators) return parseSingletonExpr(parser, string) } - fun parseSingletonTerm(string: String, withOperators: OperatorSet): PrologParser.SingletonTermContext { + fun parseSingletonTerm( + string: String, + withOperators: OperatorSet, + ): PrologParser.SingletonTermContext { val parser = createParser(string, withOperators) return parseSingletonTerm(parser, string) } - fun parseSingletonTerm(string: Reader, withOperators: OperatorSet): PrologParser.SingletonTermContext { + fun parseSingletonTerm( + string: Reader, + withOperators: OperatorSet, + ): PrologParser.SingletonTermContext { val parser = createParser(string, withOperators) return parseSingletonTerm(parser, string) } - fun parseSingletonTerm(string: InputStream, withOperators: OperatorSet): PrologParser.SingletonTermContext { + fun parseSingletonTerm( + string: InputStream, + withOperators: OperatorSet, + ): PrologParser.SingletonTermContext { val parser = createParser(string, withOperators) return parseSingletonTerm(parser, string) } - private fun parseSingletonExpr(parser: PrologParser, source: Any): PrologParser.SingletonExpressionContext { + private fun parseSingletonExpr( + parser: PrologParser, + source: Any, + ): PrologParser.SingletonExpressionContext { return parseSingle(parser, source) { singletonExpression() } } - fun parseClauses(source: String, withOperators: OperatorSet): Sequence { + fun parseClauses( + source: String, + withOperators: OperatorSet, + ): Sequence { val parser = createParser(source, withOperators) return parseClauses(parser, source) } - fun parseClauses(source: Reader, withOperators: OperatorSet): Sequence { + fun parseClauses( + source: Reader, + withOperators: OperatorSet, + ): Sequence { val parser = createParser(source, withOperators) return parseClauses(parser, source) } - fun parseClauses(source: InputStream, withOperators: OperatorSet): Sequence { + fun parseClauses( + source: InputStream, + withOperators: OperatorSet, + ): Sequence { val parser = createParser(source, withOperators) return parseClauses(parser, source) } - fun parseExpressions(source: String, withOperators: OperatorSet): Sequence { + fun parseExpressions( + source: String, + withOperators: OperatorSet, + ): Sequence { val parser = createParser(source, withOperators) return parseExpressions(parser, source) } - fun parseExpressions(source: Reader, withOperators: OperatorSet): Sequence { + fun parseExpressions( + source: Reader, + withOperators: OperatorSet, + ): Sequence { val parser = createParser(source, withOperators) return parseExpressions(parser, source) } - fun parseExpressions(source: InputStream, withOperators: OperatorSet): Sequence { + fun parseExpressions( + source: InputStream, + withOperators: OperatorSet, + ): Sequence { val parser = createParser(source, withOperators) return parseExpressions(parser, source) } - private fun createParser(string: String): PrologParser = - createParser(string, CharStreams::fromString) + private fun createParser(string: String): PrologParser = createParser(string, CharStreams::fromString) - private fun createParser(source: Reader): PrologParser = - createParser(source, CharStreams::fromReader) + private fun createParser(source: Reader): PrologParser = createParser(source, CharStreams::fromReader) - private fun createParser(source: InputStream): PrologParser = - createParser(source, CharStreams::fromStream) + private fun createParser(source: InputStream): PrologParser = createParser(source, CharStreams::fromStream) - private fun createParser(source: String, operators: OperatorSet): PrologParser = - addOperators(createParser(source), operators) + private fun createParser( + source: String, + operators: OperatorSet, + ): PrologParser = addOperators(createParser(source), operators) - private fun createParser(source: Reader, operators: OperatorSet): PrologParser = - addOperators(createParser(source), operators) + private fun createParser( + source: Reader, + operators: OperatorSet, + ): PrologParser = addOperators(createParser(source), operators) - private fun createParser(source: InputStream, operators: OperatorSet): PrologParser = - addOperators(createParser(source), operators) + private fun createParser( + source: InputStream, + operators: OperatorSet, + ): PrologParser = addOperators(createParser(source), operators) - private fun addOperators(prologParser: PrologParser, operators: OperatorSet): PrologParser { + private fun addOperators( + prologParser: PrologParser, + operators: OperatorSet, + ): PrologParser { operators.forEach { prologParser.addOperator(it.functor, it.specifier.toAssociativity(), it.priority) } @@ -145,7 +190,10 @@ object PrologParserFactory { return prologParser } - private fun createParser(source: T, charListGenerator: (T) -> CharStream): PrologParser { + private fun createParser( + source: T, + charListGenerator: (T) -> CharStream, + ): PrologParser { val stream: CharStream = charListGenerator(source) val lexer = PrologLexer(stream) lexer.removeErrorListeners() @@ -157,7 +205,12 @@ object PrologParserFactory { return parser } - private fun parseSingle(parser: PrologParser, source: Any, rule: PrologParser.() -> T): T { + @Suppress("SwallowedException") + private fun parseSingle( + parser: PrologParser, + source: Any, + rule: PrologParser.() -> T, + ): T { return try { parser.rule() } catch (ex: ParseCancellationException) { @@ -179,11 +232,19 @@ object PrologParserFactory { } } - private fun parseSingletonTerm(parser: PrologParser, source: Any): PrologParser.SingletonTermContext { + private fun parseSingletonTerm( + parser: PrologParser, + source: Any, + ): PrologParser.SingletonTermContext { return parseSingle(parser, source) { singletonTerm() } } - private fun parseNext(parser: PrologParser, input: Any, rule: PrologParser.() -> T): T { + @Suppress("SwallowedException", "ThrowsCount") + private fun parseNext( + parser: PrologParser, + input: Any, + rule: PrologParser.() -> T, + ): T { var mark = -1 var index = -1 return try { @@ -215,11 +276,17 @@ object PrologParserFactory { } } - private fun parseNextClause(parser: PrologParser, input: Any): PrologParser.OptClauseContext { + private fun parseNextClause( + parser: PrologParser, + input: Any, + ): PrologParser.OptClauseContext { return parseNext(parser, input) { optClause() } } - private fun parseClauses(parser: PrologParser, source: Any): Sequence { + private fun parseClauses( + parser: PrologParser, + source: Any, + ): Sequence { return generateSequence(0) { it + 1 } .map { try { @@ -233,11 +300,17 @@ object PrologParserFactory { .filterNotNull() } - private fun parseNextExpression(parser: PrologParser, input: Any): PrologParser.OptExpressionContext { + private fun parseNextExpression( + parser: PrologParser, + input: Any, + ): PrologParser.OptExpressionContext { return parseNext(parser, input) { optExpression() } } - private fun parseExpressions(parser: PrologParser, source: Any): Sequence { + private fun parseExpressions( + parser: PrologParser, + source: Any, + ): Sequence { return generateSequence(0) { it + 1 } .map { try { diff --git a/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/TermParserExtensions.kt b/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/TermParserExtensions.kt index 8cddf081a..74ea67a20 100644 --- a/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/TermParserExtensions.kt +++ b/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/TermParserExtensions.kt @@ -3,5 +3,7 @@ package it.unibo.tuprolog.core.parsing import it.unibo.tuprolog.core.Scope import it.unibo.tuprolog.core.operators.OperatorSet -actual fun termParserWithOperators(operators: OperatorSet, scope: Scope): TermParser = - TermParserImpl(scope, operators) +actual fun termParserWithOperators( + operators: OperatorSet, + scope: Scope, +): TermParser = TermParserImpl(scope, operators) diff --git a/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/TermParserImpl.kt b/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/TermParserImpl.kt index 334148b06..cc2b9d08b 100644 --- a/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/TermParserImpl.kt +++ b/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/TermParserImpl.kt @@ -6,8 +6,10 @@ import it.unibo.tuprolog.core.operators.OperatorSet class TermParserImpl( override val scope: Scope, - override val defaultOperatorSet: OperatorSet + override val defaultOperatorSet: OperatorSet, ) : TermParser { - override fun parseTerm(input: String, operators: OperatorSet): Term = - PrologParserFactory.parseSingletonExpr(input, operators).accept(PrologExpressionVisitor(scope)) + override fun parseTerm( + input: String, + operators: OperatorSet, + ): Term = PrologParserFactory.parseSingletonExpr(input, operators).accept(PrologExpressionVisitor(scope)) } diff --git a/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/TermReader.kt b/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/TermReader.kt index 443118bac..e2c111549 100644 --- a/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/TermReader.kt +++ b/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/TermReader.kt @@ -13,50 +13,66 @@ interface TermReader { val defaultOperatorSet: OperatorSet - fun readTerm(reader: Reader, operators: OperatorSet): Term? + fun readTerm( + reader: Reader, + operators: OperatorSet, + ): Term? fun readTerm(reader: Reader): Term? = readTerm(reader, defaultOperatorSet) - fun readTerm(inputStream: InputStream, operators: OperatorSet): Term? + fun readTerm( + inputStream: InputStream, + operators: OperatorSet, + ): Term? fun readTerm(inputStream: InputStream): Term? = readTerm(inputStream, defaultOperatorSet) - fun readTerms(reader: Reader, operators: OperatorSet): Sequence + fun readTerms( + reader: Reader, + operators: OperatorSet, + ): Sequence fun readTerms(reader: Reader): Sequence = readTerms(reader, defaultOperatorSet) - fun readTerms(inputStream: InputStream, operators: OperatorSet): Sequence + fun readTerms( + inputStream: InputStream, + operators: OperatorSet, + ): Sequence fun readTerms(inputStream: InputStream): Sequence = readTerms(inputStream, defaultOperatorSet) - fun readTerms(string: String, operators: OperatorSet): Sequence = readTerms(StringReader(string), operators) + fun readTerms( + string: String, + operators: OperatorSet, + ): Sequence = readTerms(StringReader(string), operators) fun readTerms(string: String): Sequence = readTerms(string, defaultOperatorSet) companion object { @JvmStatic @JvmOverloads - fun withNoOperator(scope: Scope = Scope.empty()): TermReader = - withOperators(OperatorSet.EMPTY, scope) + fun withNoOperator(scope: Scope = Scope.empty()): TermReader = withOperators(OperatorSet.EMPTY, scope) @JvmStatic @JvmOverloads - fun withStandardOperators(scope: Scope = Scope.empty()): TermReader = - withOperators(OperatorSet.STANDARD, scope) + fun withStandardOperators(scope: Scope = Scope.empty()): TermReader = withOperators(OperatorSet.STANDARD, scope) @JvmStatic @JvmOverloads - fun withDefaultOperators(scope: Scope = Scope.empty()): TermReader = - withOperators(OperatorSet.DEFAULT, scope) + fun withDefaultOperators(scope: Scope = Scope.empty()): TermReader = withOperators(OperatorSet.DEFAULT, scope) @JvmStatic @JvmOverloads - fun withOperators(operators: OperatorSet, scope: Scope = Scope.empty()): TermReader = - TermReaderImpl(scope, operators) + fun withOperators( + operators: OperatorSet, + scope: Scope = Scope.empty(), + ): TermReader = TermReaderImpl(scope, operators) @JvmStatic @JvmOverloads - fun withOperators(vararg operators: Operator, scope: Scope = Scope.empty()): TermReader = - withOperators(OperatorSet(*operators), scope) + fun withOperators( + vararg operators: Operator, + scope: Scope = Scope.empty(), + ): TermReader = withOperators(OperatorSet(*operators), scope) } } diff --git a/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/TermReaderImpl.kt b/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/TermReaderImpl.kt index 6f6b7b23f..1cbde579f 100644 --- a/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/TermReaderImpl.kt +++ b/parser-core/src/jvmMain/kotlin/it/unibo/tuprolog/core/parsing/TermReaderImpl.kt @@ -8,17 +8,31 @@ import java.io.Reader class TermReaderImpl( override val scope: Scope, - override val defaultOperatorSet: OperatorSet + override val defaultOperatorSet: OperatorSet, ) : TermReader { - override fun readTerm(reader: Reader, operators: OperatorSet): Term? = - readTerms(reader, operators).firstOrNull() + override fun readTerm( + reader: Reader, + operators: OperatorSet, + ): Term? = readTerms(reader, operators).firstOrNull() - override fun readTerm(inputStream: InputStream, operators: OperatorSet): Term? = - readTerms(inputStream, operators).firstOrNull() + override fun readTerm( + inputStream: InputStream, + operators: OperatorSet, + ): Term? = readTerms(inputStream, operators).firstOrNull() - override fun readTerms(reader: Reader, operators: OperatorSet): Sequence = - PrologParserFactory.parseExpressions(reader, operators).map { it.accept(PrologExpressionVisitor(scope)) } + override fun readTerms( + reader: Reader, + operators: OperatorSet, + ): Sequence = + PrologParserFactory.parseExpressions(reader, operators).map { + it.accept(PrologExpressionVisitor(scope)) + } - override fun readTerms(inputStream: InputStream, operators: OperatorSet): Sequence = - PrologParserFactory.parseExpressions(inputStream, operators).map { it.accept(PrologExpressionVisitor(scope)) } + override fun readTerms( + inputStream: InputStream, + operators: OperatorSet, + ): Sequence = + PrologParserFactory.parseExpressions(inputStream, operators).map { + it.accept(PrologExpressionVisitor(scope)) + } } diff --git a/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/Antlr4.kt b/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/Antlr4.kt index 93cc6515f..217be15c7 100644 --- a/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/Antlr4.kt +++ b/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/Antlr4.kt @@ -1,6 +1,6 @@ @file:JsModule("antlr4") @file:JsNonModule -@file:Suppress("TooManyFunctions", "FunctionNaming", "UnusedPrivateProperty") +@file:Suppress("TooManyFunctions", "FunctionNaming", "UnusedPrivateProperty", "ktlint:standard:function-naming") package it.unibo.tuprolog.parser @@ -39,7 +39,6 @@ open external class Token { * @see https://github.com/antlr/antlr4/blob/master/runtime/JavaScript/src/antlr4/Token.js */ external class CommonToken(source: dynamic, type: Int, channel: Int, start: Int, stop: Int) : Token { - fun clone(): CommonToken override fun toString(): String @@ -60,13 +59,23 @@ external class InputStream(input: dynamic, decodeToUnicodeCodePoints: Boolean) { val size: Int fun reset() + fun consume() + fun LA(offset: Int): Int + fun LT(offset: Int): Int + fun mark(): Int + fun release() + fun seek(index: Int) - fun getText(start: Int, stop: Int): String + + fun getText( + start: Int, + stop: Int, + ): String override fun toString(): String } @@ -86,17 +95,32 @@ open external class BufferedTokenStream(tokenSource: dynamic) : TokenStream { val fetchedEOF: Boolean fun mark(): Int + fun release(marker: Int) + fun reset() + fun seek(index: Int) + operator fun get(index: Int): Token + fun consume() + fun sync(index: Int): Boolean + fun fetch(n: Int): Int - fun getTokens(start: Int, stop: Int) + + fun getTokens( + start: Int, + stop: Int, + ) + fun LA(offset: Int): Int + open fun LB(offset: Int): Int + open fun LT(offset: Int): Int + fun fill() } @@ -107,7 +131,9 @@ external class CommonTokenStream(lexer: dynamic, channel: Int) : BufferedTokenSt constructor(lexer: dynamic) override fun LB(offset: Int): Int + override fun LT(offset: Int): Int + fun getNumberOfChannelTokens(): Int val channel: Int diff --git a/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/Antlr4Error.kt b/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/Antlr4Error.kt index 4cb1f7a98..5d2ae88c6 100644 --- a/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/Antlr4Error.kt +++ b/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/Antlr4Error.kt @@ -6,10 +6,15 @@ package it.unibo.tuprolog.parser abstract external class ErrorStrategy { fun reset(recognizer: dynamic) + fun recoverInline(recognizer: dynamic) + fun recover(recognizer: dynamic) + fun sync(recognizer: dynamic) + fun inErrorRecoveryMode(recognizer: dynamic) + fun reportError(recognizer: dynamic) } @@ -29,7 +34,7 @@ abstract external class ErrorListener { line: Int, column: Int, msg: String, - e: dynamic + e: dynamic, ) } @@ -40,7 +45,7 @@ open external class ConsoleErrorListener : ErrorListener { line: Int, column: Int, msg: String, - e: dynamic + e: dynamic, ) } @@ -56,7 +61,7 @@ external class DiagnosticErrorListener : ErrorListener { line: Int, column: Int, msg: String, - e: dynamic + e: dynamic, ) } diff --git a/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/Antlr4Extensions.kt b/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/Antlr4Extensions.kt index 932a24e0f..101bcdeb8 100644 --- a/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/Antlr4Extensions.kt +++ b/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/Antlr4Extensions.kt @@ -4,11 +4,8 @@ fun Token.getNameAccordingTo(lexer: dynamic): String { return lexer.symbolicNames[this.type] as String } -fun jsClassName(obj: dynamic): String? = - obj?.__proto__?.constructor?.name as String? +fun jsClassName(obj: dynamic): String? = obj?.__proto__?.constructor?.name as String? -fun isParseCancellationException(obj: dynamic): Boolean = - jsClassName(obj) == "ParseCancellationException" +fun isParseCancellationException(obj: dynamic): Boolean = jsClassName(obj) == "ParseCancellationException" -fun isRecognitionException(obj: dynamic): Boolean = - jsClassName(obj) == "RecognitionException" +fun isRecognitionException(obj: dynamic): Boolean = jsClassName(obj) == "RecognitionException" diff --git a/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/PredictionMode.kt b/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/PredictionMode.kt index 37e0fcb88..c4180dc33 100644 --- a/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/PredictionMode.kt +++ b/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/PredictionMode.kt @@ -1,5 +1,6 @@ @file:JsModule("antlr4/src/antlr4/atn") @file:JsNonModule + package it.unibo.tuprolog.parser /** diff --git a/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/PrologLexer.kt b/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/PrologLexer.kt index 0d749973d..afc50877a 100644 --- a/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/PrologLexer.kt +++ b/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/PrologLexer.kt @@ -5,15 +5,23 @@ package it.unibo.tuprolog.parser @Suppress("UnusedPrivateProperty") external class PrologLexer(input: dynamic) { - fun addOperators(vararg operators: String) + fun getOperators(): Array + fun isOperator(string: String): Boolean + fun unquote(string: String): String - fun escape(string: String, stringType: StringType): String + + fun escape( + string: String, + stringType: Int, + ): String + fun getAllTokens(): Array fun addErrorListener(listener: dynamic) + fun removeErrorListeners() companion object { diff --git a/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/PrologParser.kt b/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/PrologParser.kt index ee7f19ef6..992c21378 100644 --- a/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/PrologParser.kt +++ b/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/PrologParser.kt @@ -1,6 +1,6 @@ @file:JsModule("@tuprolog/parser-utils") @file:JsNonModule -@file:Suppress("VariableNaming", "TooManyFunctions", "UnusedPrivateProperty") +@file:Suppress("VariableNaming", "TooManyFunctions", "UnusedPrivateProperty", "ktlint:standard:property-naming") package it.unibo.tuprolog.parser @@ -60,27 +60,51 @@ external class PrologParser(input: TokenStream) { fun reset() fun addParseListener(listener: PrologParserListener) + fun addErrorListener(listener: dynamic) + fun removeErrorListeners() fun isOperator(operator: String): Boolean + fun getTokenStream(): CommonTokenStream - fun addOperator(functor: String, associativity: String, priority: Int) + + fun addOperator( + functor: String, + associativity: String, + priority: Int, + ) + fun singletonTerm(): SingletonTermContext + fun singletonExpression(): SingletonExpressionContext + fun theory(): TheoryContext + fun optClause(): OptClauseContext + fun clause(): ClauseContext + fun expression(): ExpressionContext + fun outer(): OuterContext + fun op(): OpContext + fun term(): TermContext + fun number(): NumberContext + fun integer(): IntegerContext + fun real(): RealContext + fun variable(): VariableContext + fun structure(): StructureContext + fun list(): ListContext + fun set(): BlockContext } @@ -121,8 +145,11 @@ external class ExpressionContext : ParserRuleContext { val outers: Array fun term(): TermContext + fun op(): OpContext + fun expression(): ExpressionContext + fun outer(): OuterContext } @@ -140,7 +167,9 @@ external class OuterContext : ParserRuleContext { val outers: Array fun op(): OpContext + fun expression(): ExpressionContext + fun outer(): OuterContext } @@ -159,17 +188,24 @@ external class TermContext : ParserRuleContext { val isBlock: Boolean fun variable(): VariableContext + fun structure(): StructureContext + fun list(): ListContext + fun set(): BlockContext + fun number(): NumberContext + fun expression(): ExpressionContext } external class NumberContext : ParserRuleContext { val isInt: Boolean val isReal: Boolean + fun integer(): IntegerContext + fun real(): RealContext } diff --git a/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/PrologParserListener.kt b/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/PrologParserListener.kt index 1e83e0847..1e69d31ef 100644 --- a/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/PrologParserListener.kt +++ b/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/PrologParserListener.kt @@ -5,37 +5,67 @@ package it.unibo.tuprolog.parser @Suppress("TooManyFunctions") open external class PrologParserListener { - open fun enterSingletonTerm(ctx: SingletonTermContext) + open fun exitSingletonTerm(ctx: SingletonTermContext) + open fun enterSingletonExpression(ctx: SingletonExpressionContext) + open fun exitSingletonExpression(ctx: SingletonExpressionContext) + open fun enterTheory(ctx: TheoryContext) + open fun exitTheory(ctx: TheoryContext) + open fun enterOptClause(ctx: OptClauseContext) + open fun exitOptClause(ctx: OptClauseContext) + open fun enterClause(ctx: ClauseContext) + open fun exitClause(ctx: ClauseContext) + open fun enterExpression(ctx: ExpressionContext) + open fun exitExpression(ctx: ExpressionContext) + open fun enterOuter(ctx: OuterContext) + open fun exitOuter(ctx: OuterContext) + open fun enterOp(ctx: OpContext) + open fun exitOp(ctx: OpContext) + open fun enterTerm(ctx: TermContext) + open fun exitTerm(ctx: TermContext) + open fun enterNumber(ctx: NumberContext) + open fun exitNumber(ctx: NumberContext) + open fun enterInteger(ctx: IntegerContext) + open fun exitInteger(ctx: IntegerContext) + open fun enterReal(ctx: RealContext) + open fun exitReal(ctx: RealContext) + open fun enterVariable(ctx: VariableContext) + open fun exitVariable(ctx: VariableContext) + open fun enterStructure(ctx: StructureContext) + open fun exitStructure(ctx: StructureContext) + open fun enterList(ctx: ListContext) + open fun exitList(ctx: ListContext) + open fun enterBlock(ctx: BlockContext) + open fun exitBlock(ctx: BlockContext) } diff --git a/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/PrologParserVisitor.kt b/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/PrologParserVisitor.kt index 7cfa59b5d..0a33fc5ec 100644 --- a/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/PrologParserVisitor.kt +++ b/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/PrologParserVisitor.kt @@ -5,21 +5,35 @@ package it.unibo.tuprolog.parser @Suppress("TooManyFunctions") open external class PrologParserVisitor { - open fun visitSingletonTerm(ctx: SingletonTermContext): T + open fun visitSingletonExpression(ctx: SingletonExpressionContext): T + open fun visitTheory(ctx: TheoryContext): T + open fun visitOptClause(ctx: OptClauseContext): T + open fun visitClause(ctx: ClauseContext): T + open fun visitExpression(ctx: ExpressionContext): T + open fun visitOuter(ctx: OuterContext): T + open fun visitOp(ctx: OpContext): T + open fun visitTerm(ctx: TermContext): T + open fun visitNumber(ctx: NumberContext): T + open fun visitInteger(ctx: IntegerContext): T + open fun visitReal(ctx: RealContext): T + open fun visitVariable(ctx: VariableContext): T + open fun visitStructure(ctx: StructureContext): T + open fun visitList(ctx: ListContext): T + open fun visitBlock(ctx: BlockContext): T } diff --git a/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/StringType.kt b/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/StringType.kt index 760b73365..f7708ea0b 100644 --- a/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/StringType.kt +++ b/parser-js/src/main/kotlin/it/unibo/tuprolog/parser/StringType.kt @@ -3,7 +3,7 @@ package it.unibo.tuprolog.parser -external enum class StringType { - SINGLE_QUOTED, - DOUBLE_QUOTED +external object StringType { + val SINGLE_QUOTED: Int + val DOUBLE_QUOTED: Int } diff --git a/parser-js/src/test/kotlin/it/unibo/tuprolog/parser/TestAntlrImport.kt b/parser-js/src/test/kotlin/it/unibo/tuprolog/parser/TestAntlrImport.kt index ee088cf62..f02083c4e 100644 --- a/parser-js/src/test/kotlin/it/unibo/tuprolog/parser/TestAntlrImport.kt +++ b/parser-js/src/test/kotlin/it/unibo/tuprolog/parser/TestAntlrImport.kt @@ -3,7 +3,6 @@ package it.unibo.tuprolog.parser import kotlin.test.Test class TestAntlrImport { - @Test fun antlr4() { js("require('antlr4')") diff --git a/parser-js/src/test/kotlin/it/unibo/tuprolog/parser/TestLexerKt.kt b/parser-js/src/test/kotlin/it/unibo/tuprolog/parser/TestLexerKt.kt index c4419b78c..48e0cd62b 100644 --- a/parser-js/src/test/kotlin/it/unibo/tuprolog/parser/TestLexerKt.kt +++ b/parser-js/src/test/kotlin/it/unibo/tuprolog/parser/TestLexerKt.kt @@ -4,7 +4,6 @@ import kotlin.test.Test import kotlin.test.assertEquals class TestLexerKt { - private inline val loggingOn get() = false @Test diff --git a/parser-js/src/test/kotlin/it/unibo/tuprolog/parser/TestPrologLexer.kt b/parser-js/src/test/kotlin/it/unibo/tuprolog/parser/TestPrologLexer.kt index 234e45025..bff80ff26 100644 --- a/parser-js/src/test/kotlin/it/unibo/tuprolog/parser/TestPrologLexer.kt +++ b/parser-js/src/test/kotlin/it/unibo/tuprolog/parser/TestPrologLexer.kt @@ -17,19 +17,20 @@ class TestPrologLexer { PrologLexer.channelNames.forEachIndexed { index, channel -> assertEquals(channelNames[index], channel) } - val ruleNames = arrayOf( - "INTEGER", "HEX", "OCT", "BINARY", "SIGN", - "FLOAT", "CHAR", "BOOL", "LPAR", "RPAR", - "LSQUARE", "RSQUARE", "EMPTY_LIST", - "LBRACE", "RBRACE", "EMPTY_SET", "VARIABLE", - "SQ_STRING", "DQ_STRING", "COMMA", "PIPE", - "CUT", "FULL_STOP", "FullStopTerminator", - "WHITE_SPACES", "COMMENT", "LINE_COMMENT", - "OPERATOR", "ATOM", "Symbols", "Escapable", - "DoubleSQ", "DoubleDQ", "OpSymbol", - "Atom", "Ws", "OctDigit", "BinDigit", - "HexDigit", "Digit", "Zero" - ) + val ruleNames = + arrayOf( + "INTEGER", "HEX", "OCT", "BINARY", "SIGN", + "FLOAT", "CHAR", "BOOL", "LPAR", "RPAR", + "LSQUARE", "RSQUARE", "EMPTY_LIST", + "LBRACE", "RBRACE", "EMPTY_SET", "VARIABLE", + "SQ_STRING", "DQ_STRING", "COMMA", "PIPE", + "CUT", "FULL_STOP", "FullStopTerminator", + "WHITE_SPACES", "COMMENT", "LINE_COMMENT", + "OPERATOR", "ATOM", "Symbols", "Escapable", + "DoubleSQ", "DoubleDQ", "OpSymbol", + "Atom", "Ws", "OctDigit", "BinDigit", + "HexDigit", "Digit", "Zero", + ) PrologLexer.ruleNames.forEachIndexed { index, rule -> assertEquals(ruleNames[index], rule) } diff --git a/parser-js/src/test/kotlin/it/unibo/tuprolog/parser/TestPrologParser.kt b/parser-js/src/test/kotlin/it/unibo/tuprolog/parser/TestPrologParser.kt index 6baa0375c..dead017ed 100644 --- a/parser-js/src/test/kotlin/it/unibo/tuprolog/parser/TestPrologParser.kt +++ b/parser-js/src/test/kotlin/it/unibo/tuprolog/parser/TestPrologParser.kt @@ -5,7 +5,6 @@ import kotlin.test.assertEquals import kotlin.test.assertTrue class TestPrologParser { - private fun sequenceOfInputStreamFromStrings(vararg strings: String): Sequence { val res = mutableListOf() strings.forEach { @@ -57,7 +56,7 @@ class TestPrologParser { !sc.isBlock && !sc.isTruth && sc.functor.text == "a" && - sc.functor.type == PrologLexer.ATOM + sc.functor.type == PrologLexer.ATOM, ) } @@ -72,7 +71,7 @@ class TestPrologParser { s.arity == s.args.count() && s.arity == 0 && s.isString && !s.isList && !s.isTruth && s.functor.text == "a" && - (s.functor.type == PrologLexer.DQ_STRING || s.functor.type == PrologLexer.SQ_STRING) + (s.functor.type == PrologLexer.DQ_STRING || s.functor.type == PrologLexer.SQ_STRING), ) } } @@ -87,7 +86,7 @@ class TestPrologParser { s.arity == s.args.count() && s.isTruth && !s.isList && !s.isString && s.functor.text == "true" && - s.functor.type == PrologLexer.BOOL + s.functor.type == PrologLexer.BOOL, ) } @@ -101,7 +100,7 @@ class TestPrologParser { s.arity == s.args.count() && s.isTruth && !s.isList && !s.isString && s.functor.text == "fail" && - s.functor.type == PrologLexer.BOOL + s.functor.type == PrologLexer.BOOL, ) } @@ -116,7 +115,7 @@ class TestPrologParser { s.arity == s.args.count() && s.arity == 0 && s.isList && !s.isTruth && !s.isString && - s.functor.type == PrologLexer.EMPTY_LIST + s.functor.type == PrologLexer.EMPTY_LIST, ) } } @@ -131,7 +130,7 @@ class TestPrologParser { assertTrue( !v.isAnonymous && v.value.text.contains("A") && - v.value.type == PrologLexer.VARIABLE + v.value.type == PrologLexer.VARIABLE, ) } } @@ -147,7 +146,7 @@ class TestPrologParser { assertTrue( l.length == l.items.count() && l.length == 1 && - !l.hasTail && l.tail == null + !l.hasTail && l.tail == null, ) val expr = l.items[0] assertTrue(expr.isTerm && expr.left != null && expr.operators.count() == 0 && expr.right.count() == 0) diff --git a/parser-jvm/build.gradle.kts b/parser-jvm/build.gradle.kts index abb0a4edf..9803c257d 100644 --- a/parser-jvm/build.gradle.kts +++ b/parser-jvm/build.gradle.kts @@ -24,7 +24,8 @@ configurations { tasks.generateGrammarSource { maxHeapSize = "64m" arguments = arguments + listOf("-visitor", "-long-messages") - outputDirectory = File("${project.buildDir}/generated-src/antlr/main/it/unibo/tuprolog/parser") + val buildDir = project.layout.buildDirectory.get().asFile + outputDirectory = buildDir.resolve("generated-src/antlr/main/it/unibo/tuprolog/parser") tasks.compileKotlin.orNull?.dependsOn(this) tasks.findByName("sourcesJar")?.dependsOn(this) } diff --git a/parser-jvm/src/main/kotlin/it/unibo/tuprolog/parser/ParsingException.kt b/parser-jvm/src/main/kotlin/it/unibo/tuprolog/parser/ParsingException.kt index bac11c91a..b5dc9c1ad 100644 --- a/parser-jvm/src/main/kotlin/it/unibo/tuprolog/parser/ParsingException.kt +++ b/parser-jvm/src/main/kotlin/it/unibo/tuprolog/parser/ParsingException.kt @@ -6,9 +6,8 @@ class ParsingException( val line: Int, val column: Int, message: String?, - throwable: Throwable? + throwable: Throwable?, ) : RuntimeException(message, throwable) { - override fun toString(): String { return "ParsingException{" + "message='" + message?.replace("\\n", "\\\\n") + '\'' + diff --git a/parser-jvm/src/main/kotlin/it/unibo/tuprolog/parser/dynamic/Associativity.kt b/parser-jvm/src/main/kotlin/it/unibo/tuprolog/parser/dynamic/Associativity.kt index 5f688de91..7b2bedf6b 100644 --- a/parser-jvm/src/main/kotlin/it/unibo/tuprolog/parser/dynamic/Associativity.kt +++ b/parser-jvm/src/main/kotlin/it/unibo/tuprolog/parser/dynamic/Associativity.kt @@ -3,10 +3,16 @@ package it.unibo.tuprolog.parser.dynamic import java.util.EnumSet enum class Associativity { - XF, YF, XFX, XFY, YFX, FX, FY; + XF, + YF, + XFX, + XFY, + YFX, + FX, + FY, + ; companion object { - @JvmStatic fun values(i: Int): Associativity { return values()[i] @@ -28,10 +34,12 @@ enum class Associativity { val POSTFIX: EnumSet = EnumSet.of(YF, XF) @JvmField - var NON_PREFIX: EnumSet = EnumSet.complementOf(PREFIX) + val NON_PREFIX: EnumSet = EnumSet.complementOf(PREFIX) @JvmStatic fun isAssociativity(value: String?): Boolean = - values().asSequence().any { it.name.equals(value, ignoreCase = true) } + values().asSequence().any { + it.name.equals(value, ignoreCase = true) + } } } diff --git a/parser-jvm/src/main/kotlin/it/unibo/tuprolog/parser/dynamic/StringType.kt b/parser-jvm/src/main/kotlin/it/unibo/tuprolog/parser/dynamic/StringType.kt index c35791936..c402ed159 100644 --- a/parser-jvm/src/main/kotlin/it/unibo/tuprolog/parser/dynamic/StringType.kt +++ b/parser-jvm/src/main/kotlin/it/unibo/tuprolog/parser/dynamic/StringType.kt @@ -1,5 +1,6 @@ package it.unibo.tuprolog.parser.dynamic enum class StringType { - SINGLE_QUOTED, DOUBLE_QUOTED + SINGLE_QUOTED, + DOUBLE_QUOTED, } diff --git a/parser-jvm/src/test/kotlin/it/unibo/tuprolog/parser/PrologParserTest.kt b/parser-jvm/src/test/kotlin/it/unibo/tuprolog/parser/PrologParserTest.kt index dcf86d3b0..890c00c98 100644 --- a/parser-jvm/src/test/kotlin/it/unibo/tuprolog/parser/PrologParserTest.kt +++ b/parser-jvm/src/test/kotlin/it/unibo/tuprolog/parser/PrologParserTest.kt @@ -12,9 +12,7 @@ import kotlin.test.assertEquals import kotlin.test.assertTrue class PrologParserTest { - companion object { - private fun lexerForString(input: String): PrologLexer { return PrologLexer(CharStreams.fromString(input)) } @@ -53,11 +51,11 @@ class PrologParserTest { line: Int, charPositionInLine: Int, msg: String, - e: RecognitionException + e: RecognitionException, ) { throw e } - } + }, ) return parser.singletonTerm() } @@ -85,9 +83,9 @@ class PrologParserTest { return PrologParser( tokenStreamFromLexer( lexerForString( - string - ) - ) + string, + ), + ), ) } } @@ -124,7 +122,7 @@ class PrologParserTest { !sc.isBlock && !sc.isTruth && sc.functor.text == "a" && - sc.functor.type == PrologLexer.ATOM + sc.functor.type == PrologLexer.ATOM, ) } @@ -138,7 +136,7 @@ class PrologParserTest { s.arity == s.args.count() && s.arity == 0 && s.isString && !s.isBlock && !s.isList && !s.isTruth && s.functor.text == "a" && - (s.functor.type == PrologLexer.DQ_STRING || s.functor.type == PrologLexer.SQ_STRING) + (s.functor.type == PrologLexer.DQ_STRING || s.functor.type == PrologLexer.SQ_STRING), ) } } @@ -152,7 +150,7 @@ class PrologParserTest { s.arity == s.args.count() && s.isTruth && !s.isList && !s.isString && s.functor.text == "true" && - s.functor.type == PrologLexer.BOOL + s.functor.type == PrologLexer.BOOL, ) } @@ -165,7 +163,7 @@ class PrologParserTest { s.arity == s.args.count() && s.isTruth && !s.isList && !s.isString && s.functor.text == "fail" && - s.functor.type == PrologLexer.BOOL + s.functor.type == PrologLexer.BOOL, ) } @@ -178,7 +176,7 @@ class PrologParserTest { s.arity == s.args.count() && s.isTruth && !s.isList && !s.isString && s.functor.text == "false" && - s.functor.type == PrologLexer.BOOL + s.functor.type == PrologLexer.BOOL, ) } @@ -192,7 +190,7 @@ class PrologParserTest { s.arity == s.args.count() && s.arity == 0 && s.isList && !s.isTruth && !s.isString && - s.functor.type == PrologLexer.EMPTY_LIST + s.functor.type == PrologLexer.EMPTY_LIST, ) } } @@ -206,7 +204,7 @@ class PrologParserTest { assertTrue( !v.isAnonymous && v.value.text.contains("A") && - v.value.type == PrologLexer.VARIABLE + v.value.type == PrologLexer.VARIABLE, ) } } @@ -221,7 +219,7 @@ class PrologParserTest { assertTrue( l.length == l.items.count() && l.length == 1 && - !l.hasTail && l.tail == null + !l.hasTail && l.tail == null, ) val expr = l.items[0] assertTrue(expr.isTerm && expr.left != null && expr.operators.isEmpty() && expr.right.isEmpty()) diff --git a/parser-theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesParser.kt b/parser-theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesParser.kt index 3189ae61b..d6e8ae2eb 100644 --- a/parser-theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesParser.kt +++ b/parser-theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesParser.kt @@ -13,33 +13,44 @@ interface ClausesParser { val defaultOperatorSet: OperatorSet @JsName("parseTheoryWithOperators") - fun parseTheory(input: String, operators: OperatorSet, unificator: Unificator): Theory = - Theory.indexedOf(unificator, parseClausesLazily(input, operators)) + fun parseTheory( + input: String, + operators: OperatorSet, + unificator: Unificator, + ): Theory = Theory.indexedOf(unificator, parseClausesLazily(input, operators)) @JsName("parseTheoryWithOperatorsAndDefaultUnificator") - fun parseTheory(input: String, operators: OperatorSet): Theory = parseTheory(input, operators, Unificator.default) + fun parseTheory( + input: String, + operators: OperatorSet, + ): Theory = parseTheory(input, operators, Unificator.default) @JsName("parseTheory") - fun parseTheory(input: String, unificator: Unificator): Theory = - parseTheory(input, defaultOperatorSet, unificator) + fun parseTheory( + input: String, + unificator: Unificator, + ): Theory = parseTheory(input, defaultOperatorSet, unificator) @JsName("parseTheoryWithDefaultUnificator") fun parseTheory(input: String): Theory = parseTheory(input, Unificator.default) @JsName("parseClausesLazilyWithOperators") - fun parseClausesLazily(input: String, operators: OperatorSet): Sequence + fun parseClausesLazily( + input: String, + operators: OperatorSet, + ): Sequence @JsName("parseClausesLazily") - fun parseClausesLazily(input: String): Sequence = - parseClausesLazily(input, defaultOperatorSet) + fun parseClausesLazily(input: String): Sequence = parseClausesLazily(input, defaultOperatorSet) @JsName("parseClausesWithOperators") - fun parseClauses(input: String, operators: OperatorSet): List = - parseClausesLazily(input, operators).toList() + fun parseClauses( + input: String, + operators: OperatorSet, + ): List = parseClausesLazily(input, operators).toList() @JsName("parseClauses") - fun parseClauses(input: String): List = - parseClauses(input, defaultOperatorSet) + fun parseClauses(input: String): List = parseClauses(input, defaultOperatorSet) companion object { @JvmStatic diff --git a/parser-theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesParserExtensions.kt b/parser-theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesParserExtensions.kt index 539728e74..6b06ef72d 100644 --- a/parser-theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesParserExtensions.kt +++ b/parser-theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesParserExtensions.kt @@ -13,33 +13,29 @@ internal expect fun clausesParserWithOperators(operators: OperatorSet): ClausesP private val defaultParser = ClausesParser.withDefaultOperators() @JsName("parseTheoryWithOperators") -fun Theory.Companion.parse(input: String, operators: OperatorSet): Theory = - defaultParser.parseTheory(input, operators) +fun Theory.Companion.parse( + input: String, + operators: OperatorSet, +): Theory = defaultParser.parseTheory(input, operators) @JsName("parseTheory") -fun Theory.Companion.parse(input: String): Theory = - defaultParser.parseTheory(input) +fun Theory.Companion.parse(input: String): Theory = defaultParser.parseTheory(input) @JsName("parseAsTheoryWithOperators") -fun String.parseAsTheory(operators: OperatorSet): Theory = - defaultParser.parseTheory(this, operators) +fun String.parseAsTheory(operators: OperatorSet): Theory = defaultParser.parseTheory(this, operators) @JsName("parseAsTheory") -fun String.parseAsTheory(): Theory = - defaultParser.parseTheory(this) +fun String.parseAsTheory(): Theory = defaultParser.parseTheory(this) @JsName("parseAsClausesWithOperators") -fun String.parseAsClauses(operators: OperatorSet): List = - defaultParser.parseClauses(this, operators) +fun String.parseAsClauses(operators: OperatorSet): List = defaultParser.parseClauses(this, operators) @JsName("parseAsClauses") -fun String.parseAsClauses(): List = - defaultParser.parseClauses(this) +fun String.parseAsClauses(): List = defaultParser.parseClauses(this) @JsName("parseAsClausesLazilyWithOperators") fun String.parseAsClausesLazily(operators: OperatorSet): Sequence = defaultParser.parseClausesLazily(this, operators) @JsName("parseAsClausesLazily") -fun String.parseAsClausesLazily(): Sequence = - defaultParser.parseClausesLazily(this) +fun String.parseAsClausesLazily(): Sequence = defaultParser.parseClausesLazily(this) diff --git a/parser-theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/parsing/TestClausesParser.kt b/parser-theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/parsing/TestClausesParser.kt index ed4c326ba..a2ee28a5b 100644 --- a/parser-theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/parsing/TestClausesParser.kt +++ b/parser-theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/parsing/TestClausesParser.kt @@ -12,24 +12,30 @@ import kotlin.test.assertTrue import kotlin.test.fail class TestClausesParser { - companion object { - fun assertMatch(expected: Term, actual: Term) { + fun assertMatch( + expected: Term, + actual: Term, + ) { assertTrue("Term `$actual` does not unify with `$expected`") { Unificator.default.match(expected, actual) } } - fun assertMatch(expected: Term, actual: LogicProgrammingScopeWithTheories.() -> Term) { + fun assertMatch( + expected: Term, + actual: LogicProgrammingScopeWithTheories.() -> Term, + ) { assertMatch(expected, LogicProgrammingScopeWithTheories.of().actual()) } } @Test fun testTheoryParsing() { - val db = with(ClausesParser.withStandardOperators()) { - parseTheory("f(1).\nf(2).\n:- f(X), g(X).\nf(X) :- g(X).") - } + val db = + with(ClausesParser.withStandardOperators()) { + parseTheory("f(1).\nf(2).\n:- f(X), g(X).\nf(X) :- g(X).") + } val rules = db.rules.toList() val directives = db.directives.toList() @@ -71,9 +77,10 @@ class TestClausesParser { |1 :: 2 :: nil. """.trimMargin() - val th = with(ClausesParser.withStandardOperators()) { - parseTheory(input) - } + val th = + with(ClausesParser.withStandardOperators()) { + parseTheory(input) + } assertMatch(th.elementAt(0)) { directive { "op"(900, "xfy", "::") } @@ -103,9 +110,10 @@ class TestClausesParser { |1 ++ 2 -- 3 ++ 4. """.trimMargin() - val th = with(ClausesParser.withStandardOperators()) { - parseTheory(input) - } + val th = + with(ClausesParser.withStandardOperators()) { + parseTheory(input) + } assertMatch(th.elementAt(0)) { directive { "op"(900, "yfx", listOf("++", "--")) } diff --git a/parser-theory/src/jsMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesParserImpl.kt b/parser-theory/src/jsMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesParserImpl.kt index 90c06c9ff..ed9b855e9 100644 --- a/parser-theory/src/jsMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesParserImpl.kt +++ b/parser-theory/src/jsMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesParserImpl.kt @@ -8,8 +8,10 @@ import it.unibo.tuprolog.core.parsing.PrologVisitor import it.unibo.tuprolog.core.parsing.toClause class ClausesParserImpl(override val defaultOperatorSet: OperatorSet) : ClausesParser { - - override fun parseClausesLazily(input: String, operators: OperatorSet): Sequence { + override fun parseClausesLazily( + input: String, + operators: OperatorSet, + ): Sequence { return PrologParserFactory.parseClauses(input, operators) .asSequence() .map { it.accept(PrologVisitor()) } diff --git a/parser-theory/src/jvmMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesParserImpl.kt b/parser-theory/src/jvmMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesParserImpl.kt index b0b9a5bde..bffd9d7f6 100644 --- a/parser-theory/src/jvmMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesParserImpl.kt +++ b/parser-theory/src/jvmMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesParserImpl.kt @@ -7,7 +7,10 @@ import it.unibo.tuprolog.core.parsing.PrologParserFactory import it.unibo.tuprolog.core.parsing.toClause internal class ClausesParserImpl(override val defaultOperatorSet: OperatorSet) : ClausesParser { - override fun parseClausesLazily(input: String, operators: OperatorSet): Sequence { + override fun parseClausesLazily( + input: String, + operators: OperatorSet, + ): Sequence { return PrologParserFactory.parseClauses(input, operators) .asSequence() .map { it.accept(PrologExpressionVisitor()) } diff --git a/parser-theory/src/jvmMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesReader.kt b/parser-theory/src/jvmMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesReader.kt index 61c6d43d7..f81acaa6a 100644 --- a/parser-theory/src/jvmMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesReader.kt +++ b/parser-theory/src/jvmMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesReader.kt @@ -10,33 +10,48 @@ import java.io.InputStream import java.io.Reader import kotlin.jvm.JvmStatic +@Suppress("TooManyFunctions") interface ClausesReader { val defaultOperatorSet: OperatorSet - fun readTheory(inputStream: InputStream, operators: OperatorSet): Theory = - Theory.of(Unificator.default, readClausesLazily(inputStream, operators)) + fun readTheory( + inputStream: InputStream, + operators: OperatorSet, + ): Theory = Theory.of(Unificator.default, readClausesLazily(inputStream, operators)) - fun readTheory(reader: Reader, operators: OperatorSet): Theory = - Theory.of(Unificator.default, readClausesLazily(reader, operators)) + fun readTheory( + reader: Reader, + operators: OperatorSet, + ): Theory = Theory.of(Unificator.default, readClausesLazily(reader, operators)) fun readTheory(inputStream: InputStream): Theory = readTheory(inputStream, defaultOperatorSet) fun readTheory(reader: Reader): Theory = readTheory(reader, defaultOperatorSet) - fun readClausesLazily(inputStream: InputStream, operators: OperatorSet): Sequence + fun readClausesLazily( + inputStream: InputStream, + operators: OperatorSet, + ): Sequence - fun readClausesLazily(reader: Reader, operators: OperatorSet): Sequence + fun readClausesLazily( + reader: Reader, + operators: OperatorSet, + ): Sequence fun readClausesLazily(inputStream: InputStream): Sequence = readClausesLazily(inputStream, defaultOperatorSet) fun readClausesLazily(reader: Reader): Sequence = readClausesLazily(reader, defaultOperatorSet) - fun readClauses(inputStream: InputStream, operators: OperatorSet): List = - readClausesLazily(inputStream, operators).toList() + fun readClauses( + inputStream: InputStream, + operators: OperatorSet, + ): List = readClausesLazily(inputStream, operators).toList() - fun readClauses(reader: Reader, operators: OperatorSet): List = - readClausesLazily(reader).toList() + fun readClauses( + reader: Reader, + operators: OperatorSet, + ): List = readClausesLazily(reader).toList() fun readClauses(inputStream: InputStream): List = readClauses(inputStream, defaultOperatorSet) diff --git a/parser-theory/src/jvmMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesReaderImpl.kt b/parser-theory/src/jvmMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesReaderImpl.kt index 8df56653b..0cbe018cb 100644 --- a/parser-theory/src/jvmMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesReaderImpl.kt +++ b/parser-theory/src/jvmMain/kotlin/it/unibo/tuprolog/theory/parsing/ClausesReaderImpl.kt @@ -8,13 +8,19 @@ import java.io.InputStream import java.io.Reader internal class ClausesReaderImpl(override val defaultOperatorSet: OperatorSet) : ClausesReader { - override fun readClausesLazily(inputStream: InputStream, operators: OperatorSet): Sequence = + override fun readClausesLazily( + inputStream: InputStream, + operators: OperatorSet, + ): Sequence = PrologParserFactory.parseClauses(inputStream, operators) .asSequence() .map { it.accept(PrologExpressionVisitor()) } .map { it.toClause() } - override fun readClausesLazily(reader: Reader, operators: OperatorSet): Sequence = + override fun readClausesLazily( + reader: Reader, + operators: OperatorSet, + ): Sequence = PrologParserFactory.parseClauses(reader, operators) .asSequence() .map { it.accept(PrologExpressionVisitor()) } diff --git a/repl/build.gradle.kts b/repl/build.gradle.kts index 13a80fdfa..f09f663a1 100644 --- a/repl/build.gradle.kts +++ b/repl/build.gradle.kts @@ -1,6 +1,6 @@ plugins { id(libs.plugins.ktMpp.mavenPublish.get().pluginId) - id(libs.plugins.shadowJar.get().pluginId) + id(libs.plugins.ktMpp.fatJar.get().pluginId) } kotlin { @@ -18,24 +18,17 @@ kotlin { } } -val arguments: String? by project - -val mainKlass = "it.unibo.tuprolog.ui.repl.Main" - -shadowJar(entryPoint = mainKlass) - tasks.create("run", JavaExec::class.java) { group = "application" dependsOn("jvmMainClasses") - classpath = files( - kotlin.jvm().compilations.getByName("main").output, - kotlin.jvm().compilations.getByName("main").compileDependencyFiles - ) + classpath = + files( + kotlin.jvm().compilations.getByName("main").output, + kotlin.jvm().compilations.getByName("main").compileDependencyFiles, + ) standardInput = System.`in` - mainClass.set(mainKlass) - arguments.let { - if (it != null) { - args = it.split("\\s+".toRegex()).filterNot { a -> a.isBlank() } - } + mainClass.set(multiPlatformHelper.fatJarEntryPoint) + project.findProperty("arguments")?.let { + args = it.toString().split("\\s+".toRegex()).filterNot(String::isBlank) } } diff --git a/repl/gradle.properties b/repl/gradle.properties index 65a1562ac..3c9496436 100644 --- a/repl/gradle.properties +++ b/repl/gradle.properties @@ -1,2 +1,3 @@ projectDescription=Customisable, command-line interface for logic solvers projectLongName=2P-Kt, REPL Module +fatJarEntryPoint=it.unibo.tuprolog.ui.repl.Main diff --git a/repl/src/commonMain/kotlin/it/unibo/tuprolog/ui/repl/AbstractTuPrologCommand.kt b/repl/src/commonMain/kotlin/it/unibo/tuprolog/ui/repl/AbstractTuPrologCommand.kt index 5596aec2f..e35a51f81 100644 --- a/repl/src/commonMain/kotlin/it/unibo/tuprolog/ui/repl/AbstractTuPrologCommand.kt +++ b/repl/src/commonMain/kotlin/it/unibo/tuprolog/ui/repl/AbstractTuPrologCommand.kt @@ -20,20 +20,23 @@ abstract class AbstractTuPrologCommand( autoCompleteEnvvar: String? = "", allowMultipleSubcommands: Boolean = false, treatUnknownOptionsAsArgs: Boolean = false, - hidden: Boolean = false + hidden: Boolean = false, ) : CliktCommand( - help, - epilog, - name, - invokeWithoutSubcommand, - printHelpOnEmptyArgs, - helpTags, - autoCompleteEnvvar, - allowMultipleSubcommands, - treatUnknownOptionsAsArgs, - hidden -) { - private fun printSolution(sol: Solution, operatorSet: OperatorSet) { + help, + epilog, + name, + invokeWithoutSubcommand, + printHelpOnEmptyArgs, + helpTags, + autoCompleteEnvvar, + allowMultipleSubcommands, + treatUnknownOptionsAsArgs, + hidden, + ) { + private fun printSolution( + sol: Solution, + operatorSet: OperatorSet, + ) { when (sol) { is Solution.Yes -> { printYesSolution(sol, operatorSet) @@ -47,11 +50,17 @@ abstract class AbstractTuPrologCommand( } } - private fun printYesSolution(sol: Solution.Yes, operatorSet: OperatorSet) { + private fun printYesSolution( + sol: Solution.Yes, + operatorSet: OperatorSet, + ) { echo(sol.format(SolutionFormatter.withOperators(operatorSet))) } - private fun printHaltSolution(sol: Solution.Halt, operatorSet: OperatorSet) { + private fun printHaltSolution( + sol: Solution.Halt, + operatorSet: OperatorSet, + ) { when (val ex = sol.exception) { is HaltException -> { echo("# goodbye.") @@ -96,11 +105,17 @@ abstract class AbstractTuPrologCommand( } @Suppress("UNUSED_PARAMETER") - private fun printNoSolution(sol: Solution.No, operatorSet: OperatorSet) { + private fun printNoSolution( + sol: Solution.No, + operatorSet: OperatorSet, + ) { echo(sol.format(SolutionFormatter.withOperators(operatorSet))) } - protected fun printSolutions(solutions: Iterator, operatorSet: OperatorSet) { + protected fun printSolutions( + solutions: Iterator, + operatorSet: OperatorSet, + ) { var first = true while (solutions.hasNext()) { if (!first) { @@ -114,7 +129,11 @@ abstract class AbstractTuPrologCommand( printEndOfSolutions() } - protected fun printNumSolutions(solutions: Iterator, maxSolutions: Int, operatorSet: OperatorSet) { + protected fun printNumSolutions( + solutions: Iterator, + maxSolutions: Int, + operatorSet: OperatorSet, + ) { var i = 0 while (i < maxSolutions && solutions.hasNext()) { i++ diff --git a/repl/src/commonMain/kotlin/it/unibo/tuprolog/ui/repl/TuPrologCmd.kt b/repl/src/commonMain/kotlin/it/unibo/tuprolog/ui/repl/TuPrologCmd.kt index 0fab62a4d..5f93bfb72 100644 --- a/repl/src/commonMain/kotlin/it/unibo/tuprolog/ui/repl/TuPrologCmd.kt +++ b/repl/src/commonMain/kotlin/it/unibo/tuprolog/ui/repl/TuPrologCmd.kt @@ -27,9 +27,8 @@ class TuPrologCmd(vararg additionalLibraries: Library) : AbstractTuPrologCommand invokeWithoutSubcommand = true, allowMultipleSubcommands = true, name = "java -jar 2p-repl.jar", - help = "Start a Prolog Read-Eval-Print loop" + help = "Start a Prolog Read-Eval-Print loop", ) { - companion object { const val DEFAULT_TIMEOUT: Int = 1000 // 1 s } @@ -42,12 +41,12 @@ class TuPrologCmd(vararg additionalLibraries: Library) : AbstractTuPrologCommand private val timeout by option( "-t", "--timeout", - help = "Maximum amount of time for computing a solution (default: $DEFAULT_TIMEOUT ms)" + help = "Maximum amount of time for computing a solution (default: $DEFAULT_TIMEOUT ms)", ).int().default(DEFAULT_TIMEOUT) private val oop by option( "--oop", - help = "Loads the OOP library" + help = "Loads the OOP library", ).flag(default = false) override fun run() { @@ -77,7 +76,7 @@ class TuPrologCmd(vararg additionalLibraries: Library) : AbstractTuPrologCommand |# Column : ${e.column} |# Clause : ${e.clauseIndex} """.trimMargin(), - err = true + err = true, ) } } @@ -113,18 +112,20 @@ class TuPrologCmd(vararg additionalLibraries: Library) : AbstractTuPrologCommand fun getSolver(): Solver { echo("# 2P-Kt version ${Info.VERSION}") val theory: Theory = this.loadTheory() - val outputChannel = OutputChannel.of { w -> - echo("# ${w.message}", err = true) - val sep = "\n at " - val formatter = TermFormatter.Companion.prettyExpressions(w.context.operators) - val stacktrace = w.logicStackTrace.joinToString(sep) { it.format(formatter) } - echo("# at $stacktrace", err = true) - } - val libraries = if (oop) { - Runtime.of(IOLib, OOPLib, *additionalLibraries) - } else { - Runtime.of(IOLib, *additionalLibraries) - } + val outputChannel = + OutputChannel.of { w -> + echo("# ${w.message}", err = true) + val sep = "\n at " + val formatter = TermFormatter.Companion.prettyExpressions(w.context.operators) + val stacktrace = w.logicStackTrace.joinToString(sep) { it.format(formatter) } + echo("# at $stacktrace", err = true) + } + val libraries = + if (oop) { + Runtime.of(IOLib, OOPLib, *additionalLibraries) + } else { + Runtime.of(IOLib, *additionalLibraries) + } return Solver.prolog.newBuilder() .runtime(libraries) .staticKb(theory) diff --git a/repl/src/commonMain/kotlin/it/unibo/tuprolog/ui/repl/TuPrologSolveQuery.kt b/repl/src/commonMain/kotlin/it/unibo/tuprolog/ui/repl/TuPrologSolveQuery.kt index a456eb07a..1a02464b8 100644 --- a/repl/src/commonMain/kotlin/it/unibo/tuprolog/ui/repl/TuPrologSolveQuery.kt +++ b/repl/src/commonMain/kotlin/it/unibo/tuprolog/ui/repl/TuPrologSolveQuery.kt @@ -12,9 +12,8 @@ import it.unibo.tuprolog.solve.TimeDuration class TuPrologSolveQuery : AbstractTuPrologCommand( help = "Compute a particular query and then terminate", - name = "solve" + name = "solve", ) { - private val query: String by argument() private val maxSolutions: Int by option("-n", "--numberOfSolutions", help = "Number of solution to calculate").int() .default(0) diff --git a/serialize-core/src/commonMain/kotlin/it/unibo/tuprolog/serialize/MimeType.kt b/serialize-core/src/commonMain/kotlin/it/unibo/tuprolog/serialize/MimeType.kt index a4c40d294..363c673cc 100644 --- a/serialize-core/src/commonMain/kotlin/it/unibo/tuprolog/serialize/MimeType.kt +++ b/serialize-core/src/commonMain/kotlin/it/unibo/tuprolog/serialize/MimeType.kt @@ -6,9 +6,8 @@ sealed class MimeType( @JsName("type") val type: String, @JsName("subType") - val subType: String + val subType: String, ) { - object Json : MimeType("application", "json") object Yaml : MimeType("application", "yaml") diff --git a/serialize-core/src/commonMain/kotlin/it/unibo/tuprolog/serialize/Objectifier.kt b/serialize-core/src/commonMain/kotlin/it/unibo/tuprolog/serialize/Objectifier.kt index ea507ae29..25ccb0ef9 100644 --- a/serialize-core/src/commonMain/kotlin/it/unibo/tuprolog/serialize/Objectifier.kt +++ b/serialize-core/src/commonMain/kotlin/it/unibo/tuprolog/serialize/Objectifier.kt @@ -7,13 +7,11 @@ interface Objectifier { fun objectify(value: T): Any @JsName("objectifyMany") - fun objectifyMany(vararg values: T): Any = - objectifyMany(listOf(*values)) + fun objectifyMany(vararg values: T): Any = objectifyMany(listOf(*values)) @JsName("objectifyManyIterable") fun objectifyMany(values: Iterable): Any @JsName("objectifyManySequence") - fun objectifyMany(values: Sequence): Any = - objectifyMany(values.asIterable()) + fun objectifyMany(values: Sequence): Any = objectifyMany(values.asIterable()) } diff --git a/serialize-core/src/commonMain/kotlin/it/unibo/tuprolog/serialize/ObjectsUtils.kt b/serialize-core/src/commonMain/kotlin/it/unibo/tuprolog/serialize/ObjectsUtils.kt index 23188d228..2bac01a06 100644 --- a/serialize-core/src/commonMain/kotlin/it/unibo/tuprolog/serialize/ObjectsUtils.kt +++ b/serialize-core/src/commonMain/kotlin/it/unibo/tuprolog/serialize/ObjectsUtils.kt @@ -1,7 +1,13 @@ package it.unibo.tuprolog.serialize expect object ObjectsUtils { - fun parseAsObject(string: String, mimeType: MimeType): Any + fun parseAsObject( + string: String, + mimeType: MimeType, + ): Any - fun deeplyEqual(obj1: Any?, obj2: Any?): Boolean + fun deeplyEqual( + obj1: Any?, + obj2: Any?, + ): Boolean } diff --git a/serialize-core/src/commonMain/kotlin/it/unibo/tuprolog/serialize/Serializer.kt b/serialize-core/src/commonMain/kotlin/it/unibo/tuprolog/serialize/Serializer.kt index f796c011b..1ad4263bd 100644 --- a/serialize-core/src/commonMain/kotlin/it/unibo/tuprolog/serialize/Serializer.kt +++ b/serialize-core/src/commonMain/kotlin/it/unibo/tuprolog/serialize/Serializer.kt @@ -10,13 +10,11 @@ interface Serializer { fun serialize(value: T): String @JsName("serializeMany") - fun serializeMany(vararg values: T): String = - serializeMany(listOf(*values)) + fun serializeMany(vararg values: T): String = serializeMany(listOf(*values)) @JsName("serializeManyIterable") fun serializeMany(values: Iterable): String @JsName("serializeManySequence") - fun serializeMany(values: Sequence): String = - serializeMany(values.asIterable()) + fun serializeMany(values: Sequence): String = serializeMany(values.asIterable()) } diff --git a/serialize-core/src/commonMain/kotlin/it/unibo/tuprolog/serialize/TermSerializer.kt b/serialize-core/src/commonMain/kotlin/it/unibo/tuprolog/serialize/TermSerializer.kt index e2a7a73bf..e6cd85e2c 100644 --- a/serialize-core/src/commonMain/kotlin/it/unibo/tuprolog/serialize/TermSerializer.kt +++ b/serialize-core/src/commonMain/kotlin/it/unibo/tuprolog/serialize/TermSerializer.kt @@ -5,7 +5,6 @@ import kotlin.js.JsName import kotlin.jvm.JvmStatic interface TermSerializer : Serializer { - companion object { @JvmStatic @JsName("of") diff --git a/serialize-core/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestTermDeserializer.kt b/serialize-core/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestTermDeserializer.kt index 6eef0f663..618ee8a3e 100644 --- a/serialize-core/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestTermDeserializer.kt +++ b/serialize-core/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestTermDeserializer.kt @@ -9,7 +9,9 @@ class TestTermDeserializer { val deserializer: TermDeserializer = TermDeserializer.of(MimeType.Json) assertEquals(MimeType.Json, deserializer.mimeType) - deserializer.assertTermDeserializationWorks("{\"fun\":\"member\",\"args\":[{\"var\":\"H\"},{\"list\":[{\"var\":\"H\"}],\"tail\":{\"var\":\"_\"}}]}") { + deserializer.assertTermDeserializationWorks( + "{\"fun\":\"member\",\"args\":[{\"var\":\"H\"},{\"list\":[{\"var\":\"H\"}],\"tail\":{\"var\":\"_\"}}]}", + ) { structOf("member", varOf("H"), consOf(varOf("H"), anonymous())) } } @@ -28,7 +30,7 @@ class TestTermDeserializer { | - var: H | tail: | var: _ - """.trimMargin() + """.trimMargin(), ) { structOf("member", varOf("H"), consOf(varOf("H"), anonymous())) } @@ -141,12 +143,14 @@ class TestTermDeserializer { structOf("f", atomOf("hello"), numOf(2)) } - deserializer.assertTermDeserializationWorks("{\"fun\":\"f\",\"args\":[\"prova 2\",{\"real\":3.0},{\"list\":[\"qua ci va una lista\",true]}]}") { + deserializer.assertTermDeserializationWorks( + "{\"fun\":\"f\",\"args\":[\"prova 2\",{\"real\":3.0},{\"list\":[\"qua ci va una lista\",true]}]}", + ) { structOf( "f", atomOf("prova 2"), realOf(3.0), - listOf(atomOf("qua ci va una lista"), truthOf(true)) + listOf(atomOf("qua ci va una lista"), truthOf(true)), ) } } @@ -181,7 +185,7 @@ class TestTermDeserializer { "f", atomOf("prova 2"), realOf(3.0), - listOf(atomOf("qua ci va una lista"), truthOf(true)) + listOf(atomOf("qua ci va una lista"), truthOf(true)), ) } } diff --git a/serialize-core/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestTermSerializer.kt b/serialize-core/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestTermSerializer.kt index 55f2c2924..69a700bbc 100644 --- a/serialize-core/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestTermSerializer.kt +++ b/serialize-core/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestTermSerializer.kt @@ -4,7 +4,6 @@ import kotlin.test.Test import kotlin.test.assertEquals class TestTermSerializer { - @Test fun testAtomSerializationInJSON() { val serializer: TermSerializer = TermSerializer.of(MimeType.Json) @@ -80,7 +79,9 @@ class TestTermSerializer { val serializer: TermSerializer = TermSerializer.of(MimeType.Json) assertEquals(MimeType.Json, serializer.mimeType) - serializer.assertTermSerializationWorks("{\"fun\":\"member\",\"args\":[{\"var\":\"H\"},{\"list\":[{\"var\":\"H\"}],\"tail\":{\"var\":\"_\"}}]}") { + serializer.assertTermSerializationWorks( + "{\"fun\":\"member\",\"args\":[{\"var\":\"H\"},{\"list\":[{\"var\":\"H\"}],\"tail\":{\"var\":\"_\"}}]}", + ) { structOf("member", varOf("H"), consOf(varOf("H"), anonymous())) } } @@ -126,7 +127,7 @@ class TestTermSerializer { | - var: H | tail: | var: _ - """.trimMargin() + """.trimMargin(), ) { structOf("member", varOf("H"), consOf(varOf("H"), anonymous())) } diff --git a/serialize-core/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestUtils.kt b/serialize-core/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestUtils.kt index 32725b44f..96495d580 100644 --- a/serialize-core/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestUtils.kt +++ b/serialize-core/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestUtils.kt @@ -8,7 +8,10 @@ import it.unibo.tuprolog.serialize.ObjectsUtils.parseAsObject /** * Utility assertion method aimed at checking if a serializer correctly works */ -fun Serializer.assertSerializationWorks(expected: String, actual: T) { +fun Serializer.assertSerializationWorks( + expected: String, + actual: T, +) { val expectedObj = parseAsObject(expected, mimeType) val actualObj = TermObjectifier.default.objectify(actual) kotlin.test.assertTrue( @@ -18,7 +21,7 @@ fun Serializer.assertSerializationWorks(expected: String, actual: |got instead: | $actualObj | - """.trimMargin() + """.trimMargin(), ) { deeplyEqual(expectedObj, actualObj) } } @@ -36,14 +39,20 @@ fun Serializer.assertSerializationWorks(expected: String, actual: * * @see Scope https://pika-lab.gitlab.io/tuprolog/2p-in-kotlin/kotlindoc/it/unibo/tuprolog/core/scope/ */ -fun Serializer.assertTermSerializationWorks(expected: String, actualGenerator: Scope.() -> Term) { +fun Serializer.assertTermSerializationWorks( + expected: String, + actualGenerator: Scope.() -> Term, +) { assertSerializationWorks(expected, Scope.empty().actualGenerator()) } /** * Utility assertion method aimed at checking if a deserializer correctly works */ -fun Deserializer.assertDeserializationWorks(expected: T, actual: String) { +fun Deserializer.assertDeserializationWorks( + expected: T, + actual: String, +) { val deserialized = deserialize(actual) kotlin.test.assertTrue( """ @@ -52,7 +61,7 @@ fun Deserializer.assertDeserializationWorks(expected: T, actual: S |got: | $deserialized | - """.trimMargin() + """.trimMargin(), ) { expected.equals(deserialized, false) } } @@ -70,6 +79,9 @@ fun Deserializer.assertDeserializationWorks(expected: T, actual: S * * @see Scope https://pika-lab.gitlab.io/tuprolog/2p-in-kotlin/kotlindoc/it/unibo/tuprolog/core/scope/ */ -fun Deserializer.assertTermDeserializationWorks(actual: String, expectedGenerator: Scope.() -> Term) { +fun Deserializer.assertTermDeserializationWorks( + actual: String, + expectedGenerator: Scope.() -> Term, +) { assertDeserializationWorks(Scope.empty().expectedGenerator(), actual) } diff --git a/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTermDeobjectifier.kt b/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTermDeobjectifier.kt index 42a95dbd2..dd9de81e0 100644 --- a/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTermDeobjectifier.kt +++ b/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTermDeobjectifier.kt @@ -5,9 +5,8 @@ import it.unibo.tuprolog.core.Struct import it.unibo.tuprolog.core.Term import it.unibo.tuprolog.core.Var -@Suppress("USELESS_CAST") +@Suppress("USELESS_CAST", "TooManyFunctions") internal class JsTermDeobjectifier : TermDeobjectifier { - private val scope: Scope = Scope.empty() override fun deobjectify(`object`: Any): Term { @@ -80,7 +79,7 @@ internal class JsTermDeobjectifier : TermDeobjectifier { items.map { deobjectify(it ?: throw DeobjectificationException(value)) }, - last = if (last != null) deobjectify(last) else scope.emptyList + last = if (last != null) deobjectify(last) else scope.emptyList, ) } @@ -89,19 +88,23 @@ internal class JsTermDeobjectifier : TermDeobjectifier { return scope.tupleOf( items.map { deobjectify(it ?: throw DeobjectificationException(value)) - } + }, ) } - private fun deobjectifyBlock(value: dynamic, name: String = "block"): Term { + private fun deobjectifyBlock( + value: dynamic, + name: String = "block", + ): Term { val items = value[name] as? Array<*> ?: throw DeobjectificationException(value) return scope.blockOf( items.map { deobjectify(it ?: throw DeobjectificationException(value)) - } + }, ) } + @Suppress("UseCheckOrError", "ThrowsCount") private fun deobjectifyStructure(value: dynamic): Term { val name = value["fun"] as? String ?: throw DeobjectificationException(value) val args = value["args"] as? Array<*> ?: throw DeobjectificationException(value) @@ -109,7 +112,7 @@ internal class JsTermDeobjectifier : TermDeobjectifier { name, args.map { deobjectify(it ?: throw DeobjectificationException(value)) - } + }, ) } diff --git a/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTermDeserializer.kt b/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTermDeserializer.kt index b219e6eb1..6c0830cda 100644 --- a/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTermDeserializer.kt +++ b/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTermDeserializer.kt @@ -3,11 +3,9 @@ package it.unibo.tuprolog.serialize import it.unibo.tuprolog.core.Term internal class JsTermDeserializer(override val mimeType: MimeType) : TermDeserializer { - override fun deserialize(string: String): Term = - JsTermDeobjectifier().deobjectify(parse(string)) + override fun deserialize(string: String): Term = JsTermDeobjectifier().deobjectify(parse(string)) - override fun deserializeMany(string: String): Iterable = - JsTermDeobjectifier().deobjectifyMany(parse(string)) + override fun deserializeMany(string: String): Iterable = JsTermDeobjectifier().deobjectifyMany(parse(string)) private fun parse(string: String): Any = when (mimeType) { diff --git a/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTermObjectifier.kt b/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTermObjectifier.kt index 8cee1ecb1..f1fd9378c 100644 --- a/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTermObjectifier.kt +++ b/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTermObjectifier.kt @@ -18,9 +18,10 @@ import it.unibo.tuprolog.core.Truth import it.unibo.tuprolog.core.Tuple import it.unibo.tuprolog.core.Var +@Suppress("TooManyFunctions") internal class JsTermObjectifier : TermObjectifier { override fun defaultValue(term: Term): Any { - throw IllegalStateException() + error("Cannot convert to object: $term") } override fun objectifyMany(values: Iterable): Any { @@ -29,7 +30,7 @@ internal class JsTermObjectifier : TermObjectifier { override fun visitVar(term: Var): dynamic = jsObject( - "var" to term.name + "var" to term.name, ) override fun visitTruth(term: Truth): Any = @@ -43,84 +44,82 @@ internal class JsTermObjectifier : TermObjectifier { override fun visitStruct(term: Struct): Any = jsObject( "fun" to term.functor, - "args" to term.args.map { it.accept(this) } + "args" to term.args.map { it.accept(this) }, ) - override fun visitAtom(term: Atom): String = - term.value + override fun visitAtom(term: Atom): String = term.value + @Suppress("SwallowedException") override fun visitInteger(term: Integer): dynamic = try { term.value.toIntExact() } catch (e: ArithmeticException) { jsObject( - "integer" to term.value.toString() + "integer" to term.value.toString(), ) } override fun visitReal(term: Real): Any = jsObject( - "real" to term.value.toString().let { - if ("." !in it) { - "$it.0" - } else { - it - } - } + "real" to + term.value.toString().let { + if ("." !in it) { + "$it.0" + } else { + it + } + }, ) override fun visitBlock(term: Block): Any = jsObject( - "block" to term.toList().map { it.accept(this) } + "block" to term.toList().map { it.accept(this) }, ) - override fun visitEmptyBlock(term: EmptyBlock): Any = - visitBlock(term) + override fun visitEmptyBlock(term: EmptyBlock): Any = visitBlock(term) override fun visitList(term: List): Any { val listed = term.toList() return if (term.isWellFormed) { jsObject( - "list" to listed.map { it.accept(this) }.toTypedArray() + "list" to listed.map { it.accept(this) }.toTypedArray(), ) } else { jsObject( "list" to listed.subList(0, listed.lastIndex).map { it.accept(this) }.toTypedArray(), - "tail" to listed[listed.lastIndex].accept(this) + "tail" to listed[listed.lastIndex].accept(this), ) } } - override fun visitCons(term: Cons): Any = - visitList(term) + override fun visitCons(term: Cons): Any = visitList(term) - override fun visitEmptyList(term: EmptyList): Any = - visitList(term) + override fun visitEmptyList(term: EmptyList): Any = visitList(term) override fun visitTuple(term: Tuple): Any = jsObject( - "tuple" to term.toList().map { it.accept(this) } + "tuple" to term.toList().map { it.accept(this) }, ) override fun visitIndicator(term: Indicator): Any = jsObject( "name" to term.nameTerm.accept(this), - "arity" to term.arityTerm.accept(this) + "arity" to term.arityTerm.accept(this), ) override fun visitRule(term: Rule): Any = jsObject( "head" to term.head.accept(this), - "body" to term.body.accept(this) + "body" to term.body.accept(this), ) override fun visitFact(term: Fact): Any = jsObject( - "head" to term.head.accept(this) + "head" to term.head.accept(this), ) override fun visitDirective(term: Directive): Any = jsObject( - "body" to term.body.accept(this) + "body" to term.body.accept(this), ) } diff --git a/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTermSerializer.kt b/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTermSerializer.kt index 30f592e2e..6237bea9d 100644 --- a/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTermSerializer.kt +++ b/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTermSerializer.kt @@ -3,14 +3,11 @@ package it.unibo.tuprolog.serialize import it.unibo.tuprolog.core.Term internal class JsTermSerializer(override val mimeType: MimeType) : TermSerializer { - private val objectifier = JsTermObjectifier() - override fun serialize(value: Term): String = - stringify(objectifier.objectify(value)) + override fun serialize(value: Term): String = stringify(objectifier.objectify(value)) - override fun serializeMany(values: Iterable): String = - stringify(objectifier.objectifyMany(values)) + override fun serializeMany(values: Iterable): String = stringify(objectifier.objectifyMany(values)) private fun stringify(objectified: Any): String = when (mimeType) { diff --git a/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsUtils.kt b/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsUtils.kt index 59c6fa580..181220daa 100644 --- a/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsUtils.kt +++ b/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsUtils.kt @@ -6,7 +6,10 @@ internal fun jsObject(config: dynamic.() -> Unit): Any { return obj } -internal fun jsObject(vararg properties: Pair, config: dynamic.() -> Unit = {}): Any { +internal fun jsObject( + vararg properties: Pair, + config: dynamic.() -> Unit = {}, +): Any { return jsObject { for ((k, v) in properties) { this[k] = v @@ -15,7 +18,10 @@ internal fun jsObject(vararg properties: Pair, config: dynamic. } } -internal fun jsObject(properties: Iterable>, config: dynamic.() -> Unit = {}): Any { +internal fun jsObject( + properties: Iterable>, + config: dynamic.() -> Unit = {}, +): Any { return jsObject { for ((k, v) in properties) { this[k] = v @@ -24,5 +30,7 @@ internal fun jsObject(properties: Iterable>, config: dynam } } -internal fun hasProperty(obj: dynamic, name: String): Boolean = - obj[name] != undefined +internal fun hasProperty( + obj: dynamic, + name: String, +): Boolean = obj[name] != undefined diff --git a/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/ObjectsUtils.kt b/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/ObjectsUtils.kt index be58362e9..6bf9e1f0f 100644 --- a/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/ObjectsUtils.kt +++ b/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/ObjectsUtils.kt @@ -1,8 +1,10 @@ package it.unibo.tuprolog.serialize actual object ObjectsUtils { - - actual fun parseAsObject(string: String, mimeType: MimeType): Any { + actual fun parseAsObject( + string: String, + mimeType: MimeType, + ): Any { return when (mimeType) { is MimeType.Xml -> throw NotImplementedError() is MimeType.Yaml -> YAML.parse(string) @@ -10,7 +12,10 @@ actual object ObjectsUtils { } as Any } - actual fun deeplyEqual(obj1: Any?, obj2: Any?): Boolean { + actual fun deeplyEqual( + obj1: Any?, + obj2: Any?, + ): Boolean { return JSON.stringify(obj1) == JSON.stringify(obj2) } } diff --git a/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/YAML.kt b/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/YAML.kt index f60cd60ca..1a79ccfa8 100644 --- a/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/YAML.kt +++ b/serialize-core/src/jsMain/kotlin/it/unibo/tuprolog/serialize/YAML.kt @@ -2,10 +2,19 @@ package it.unibo.tuprolog.serialize @JsModule("yaml") @JsNonModule +@Suppress("UnusedParameter") external object YAML { - fun stringify(value: dynamic, options: dynamic): String + fun stringify( + value: dynamic, + options: dynamic, + ): String + fun stringify(value: dynamic): String - fun parse(string: String, options: dynamic): dynamic + fun parse( + string: String, + options: dynamic, + ): dynamic + fun parse(string: String): dynamic } diff --git a/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTermDeobjectifier.kt b/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTermDeobjectifier.kt index c97558c9c..cf6d4759c 100644 --- a/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTermDeobjectifier.kt +++ b/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTermDeobjectifier.kt @@ -9,8 +9,8 @@ import java.math.BigDecimal import java.math.BigInteger import it.unibo.tuprolog.core.Integer as LogicInteger +@Suppress("TooManyFunctions") internal class JvmTermDeobjectifier : TermDeobjectifier { - private val scope: Scope = Scope.empty() override fun deobjectify(`object`: Any): Term { @@ -62,12 +62,10 @@ internal class JvmTermDeobjectifier : TermDeobjectifier { } private fun deobjectifyClause(value: Map<*, *>): Term { - val head = value["head"]?.let { - deobjectify(it) as? Struct ?: throw DeobjectificationException(value) - } + val head = value["head"]?.let { deobjectify(it) as? Struct } ?: throw DeobjectificationException(value) val body = value["body"]?.let { deobjectify(it) } return if (body == null) { - scope.factOf(head!!) + scope.factOf(head) } else { scope.clauseOf(head, body) } @@ -80,7 +78,7 @@ internal class JvmTermDeobjectifier : TermDeobjectifier { items.map { deobjectify(it ?: throw DeobjectificationException(value)) }, - last = last?.let { deobjectify(it) } ?: scope.emptyList + last = last?.let { deobjectify(it) } ?: scope.emptyList, ) } @@ -89,19 +87,23 @@ internal class JvmTermDeobjectifier : TermDeobjectifier { return scope.tupleOf( items.map { deobjectify(it ?: throw DeobjectificationException(value)) - } + }, ) } - private fun deobjectifyBlock(value: Map<*, *>, name: String = "block"): Term { + private fun deobjectifyBlock( + value: Map<*, *>, + name: String = "block", + ): Term { val items = value[name] as? List<*> ?: throw DeobjectificationException(value) return scope.blockOf( items.map { deobjectify(it ?: throw DeobjectificationException(value)) - } + }, ) } + @Suppress("ThrowsCount") private fun deobjectifyStructure(value: Map<*, *>): Term { val name = value["fun"] as? String ?: throw DeobjectificationException(value) val args = value["args"] as? List<*> ?: throw DeobjectificationException(value) @@ -109,7 +111,7 @@ internal class JvmTermDeobjectifier : TermDeobjectifier { name, args.map { deobjectify(it ?: throw DeobjectificationException(value)) - } + }, ) } diff --git a/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTermDeserializer.kt b/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTermDeserializer.kt index 63e1cc79d..8ea759590 100644 --- a/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTermDeserializer.kt +++ b/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTermDeserializer.kt @@ -4,16 +4,15 @@ import it.unibo.tuprolog.core.Term import java.io.Reader internal class JvmTermDeserializer(override val mimeType: MimeType) : ReadingTermDeserializer { - private val mapper = mimeType.objectMapper override fun deserialize(reader: Reader): Term = JvmTermDeobjectifier().deobjectify( - mapper.readValue(reader, java.lang.Object::class.java) + mapper.readValue(reader, java.lang.Object::class.java), ) override fun deserializeMany(reader: Reader): Iterable = JvmTermDeobjectifier().deobjectifyMany( - mapper.readValue(reader, java.lang.Object::class.java) + mapper.readValue(reader, java.lang.Object::class.java), ) } diff --git a/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTermObjectifier.kt b/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTermObjectifier.kt index b2c7dd767..bb3e7a4aa 100644 --- a/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTermObjectifier.kt +++ b/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTermObjectifier.kt @@ -18,9 +18,10 @@ import it.unibo.tuprolog.core.Truth import it.unibo.tuprolog.core.Tuple import it.unibo.tuprolog.core.Var +@Suppress("TooManyFunctions") internal class JvmTermObjectifier : TermObjectifier { override fun defaultValue(term: Term): Any { - throw IllegalStateException() + error("Cannot objectify term: $term") } override fun objectifyMany(values: Iterable): Any { @@ -29,7 +30,7 @@ internal class JvmTermObjectifier : TermObjectifier { override fun visitVar(term: Var): Map = mapOf( - "var" to term.name + "var" to term.name, ) override fun visitTruth(term: Truth): Any = @@ -43,78 +44,75 @@ internal class JvmTermObjectifier : TermObjectifier { override fun visitStruct(term: Struct): Map = mapOf( "fun" to term.functor, - "args" to term.args.map { it.accept(this) } + "args" to term.args.map { it.accept(this) }, ) - override fun visitAtom(term: Atom): String = - term.value + override fun visitAtom(term: Atom): String = term.value + @Suppress("SwallowedException") override fun visitInteger(term: Integer): Any = try { term.value.toLongExact() } catch (e: ArithmeticException) { mapOf( - "integer" to term.value.toString() + "integer" to term.value.toString(), ) } override fun visitReal(term: Real): Any = mapOf( - "real" to term.value.toString() + "real" to term.value.toString(), ) override fun visitBlock(term: Block): Map = mapOf( - "block" to term.toList().map { it.accept(this) } + "block" to term.toList().map { it.accept(this) }, ) - override fun visitEmptyBlock(term: EmptyBlock): Map = - visitBlock(term) + override fun visitEmptyBlock(term: EmptyBlock): Map = visitBlock(term) override fun visitList(term: List): Map { val listed = term.toList() return if (term.isWellFormed) { mapOf( - "list" to listed.map { it.accept(this) } + "list" to listed.map { it.accept(this) }, ) } else { mapOf( "list" to listed.subList(0, listed.lastIndex).map { it.accept(this) }, - "tail" to listed[listed.lastIndex].accept(this) + "tail" to listed[listed.lastIndex].accept(this), ) } } - override fun visitCons(term: Cons): Map = - visitList(term) + override fun visitCons(term: Cons): Map = visitList(term) - override fun visitEmptyList(term: EmptyList): Map = - visitList(term) + override fun visitEmptyList(term: EmptyList): Map = visitList(term) override fun visitTuple(term: Tuple): Map = mapOf( - "tuple" to term.toList().map { it.accept(this) } + "tuple" to term.toList().map { it.accept(this) }, ) override fun visitIndicator(term: Indicator): Map = mapOf( "name" to term.nameTerm.accept(this), - "arity" to term.arityTerm.accept(this) + "arity" to term.arityTerm.accept(this), ) override fun visitRule(term: Rule): Map = mapOf( "head" to term.head.accept(this), - "body" to term.body.accept(this) + "body" to term.body.accept(this), ) override fun visitFact(term: Fact): Map = mapOf( - "head" to term.head.accept(this) + "head" to term.head.accept(this), ) override fun visitDirective(term: Directive): Map = mapOf( - "body" to term.body.accept(this) + "body" to term.body.accept(this), ) } diff --git a/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTermSerializer.kt b/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTermSerializer.kt index ca0c9062f..e0aabda66 100644 --- a/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTermSerializer.kt +++ b/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTermSerializer.kt @@ -4,15 +4,20 @@ import it.unibo.tuprolog.core.Term import java.io.Writer internal class JvmTermSerializer(override val mimeType: MimeType) : WritingTermSerializer { - private val mapper = mimeType.objectMapper private val objectifier = JvmTermObjectifier() - override fun serialize(writer: Writer, value: Term) { + override fun serialize( + writer: Writer, + value: Term, + ) { mapper.writeValue(writer, objectifier.objectify(value)) } - override fun serializeMany(writer: Writer, values: Iterable) { + override fun serializeMany( + writer: Writer, + values: Iterable, + ) { mapper.writeValue(writer, objectifier.objectifyMany(values)) } } diff --git a/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/MimeTypeExtensions.kt b/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/MimeTypeExtensions.kt index 073c7d12a..32ea39b46 100644 --- a/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/MimeTypeExtensions.kt +++ b/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/MimeTypeExtensions.kt @@ -6,11 +6,12 @@ import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.dataformat.xml.XmlMapper import com.fasterxml.jackson.dataformat.yaml.YAMLMapper -private val objectMappers = mapOf( - MimeType.Json to ObjectMapper(), - MimeType.Yaml to YAMLMapper(), - MimeType.Xml to XmlMapper() -) +private val objectMappers = + mapOf( + MimeType.Json to ObjectMapper(), + MimeType.Yaml to YAMLMapper(), + MimeType.Xml to XmlMapper(), + ) val MimeType.objectMapper: ObjectMapper get() = objectMappers[this] ?: throw NotImplementedError("MIME type not supported: $this") diff --git a/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/ObjectsUtils.kt b/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/ObjectsUtils.kt index e98a4ee5d..d1fda9e22 100644 --- a/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/ObjectsUtils.kt +++ b/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/ObjectsUtils.kt @@ -1,24 +1,33 @@ package it.unibo.tuprolog.serialize actual object ObjectsUtils { - actual fun parseAsObject(string: String, mimeType: MimeType): Any { + actual fun parseAsObject( + string: String, + mimeType: MimeType, + ): Any { return mimeType.objectMapper.readValue(string, java.lang.Object::class.java) } - actual fun deeplyEqual(obj1: Any?, obj2: Any?): Boolean { + actual fun deeplyEqual( + obj1: Any?, + obj2: Any?, + ): Boolean { return when { obj1 is Number && obj2 is Number -> obj1.toString() == obj2.toString() - obj1 is List<*> && obj2 is List<*> -> when { - obj1.size != obj2.size -> false - else -> obj1.asSequence().zip(obj2.asSequence()).all { - deeplyEqual(it.first, it.second) + obj1 is List<*> && obj2 is List<*> -> + when { + obj1.size != obj2.size -> false + else -> + obj1.asSequence().zip(obj2.asSequence()).all { + deeplyEqual(it.first, it.second) + } + } + obj1 is Map<*, *> && obj2 is Map<*, *> -> + when { + obj1.size != obj2.size -> false + obj1.keys != obj2.keys -> false + else -> obj1.keys.all { deeplyEqual(obj1[it], obj2[it]) } } - } - obj1 is Map<*, *> && obj2 is Map<*, *> -> when { - obj1.size != obj2.size -> false - obj1.keys != obj2.keys -> false - else -> obj1.keys.all { deeplyEqual(obj1[it], obj2[it]) } - } else -> obj1 == obj2 } } diff --git a/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/WritingSerializer.kt b/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/WritingSerializer.kt index f585ee9da..f8c6557bc 100644 --- a/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/WritingSerializer.kt +++ b/serialize-core/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/WritingSerializer.kt @@ -4,7 +4,10 @@ import java.io.StringWriter import java.io.Writer interface WritingSerializer : Serializer { - fun serialize(writer: Writer, value: T) + fun serialize( + writer: Writer, + value: T, + ) override fun serialize(value: T): String = StringWriter().use { @@ -12,10 +15,15 @@ interface WritingSerializer : Serializer { it.toString() } - fun serializeMany(writer: Writer, vararg values: T) = - serializeMany(writer, listOf(*values)) + fun serializeMany( + writer: Writer, + vararg values: T, + ) = serializeMany(writer, listOf(*values)) - fun serializeMany(writer: Writer, values: Iterable) + fun serializeMany( + writer: Writer, + values: Iterable, + ) override fun serializeMany(values: Iterable): String = StringWriter().use { @@ -23,6 +31,8 @@ interface WritingSerializer : Serializer { it.toString() } - fun serializeMany(writer: Writer, values: Sequence) = - serializeMany(writer, values.asIterable()) + fun serializeMany( + writer: Writer, + values: Sequence, + ) = serializeMany(writer, values.asIterable()) } diff --git a/serialize-theory/build.gradle.kts b/serialize-theory/build.gradle.kts index 83e504751..47d9254dc 100644 --- a/serialize-theory/build.gradle.kts +++ b/serialize-theory/build.gradle.kts @@ -35,10 +35,11 @@ listOf("yaml", "json").forEach { tasks.create("print${it.capitalized()}", JavaExec::class.java) { group = "application" dependsOn("jvmTestClasses") - classpath = files( - kotlin.jvm().compilations.getByName("test").output, - kotlin.jvm().compilations.getByName("test").compileDependencyFiles - ) + classpath = + files( + kotlin.jvm().compilations.getByName("test").output, + kotlin.jvm().compilations.getByName("test").compileDependencyFiles, + ) standardInput = System.`in` mainClass.set("${it.uppercase(Locale.getDefault())}PrinterKt") } diff --git a/serialize-theory/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestTheoryDeserialization.kt b/serialize-theory/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestTheoryDeserialization.kt index 980d50729..de02bc02c 100644 --- a/serialize-theory/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestTheoryDeserialization.kt +++ b/serialize-theory/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestTheoryDeserialization.kt @@ -3,14 +3,17 @@ package it.unibo.tuprolog.serialize import kotlin.test.Test class TestTheoryDeserialization { - @Test fun testTheorySerializationJSON() { - TheoryDeserializer.of(MimeType.Json).assertDeserializationWorks(Instances.commonRules, Instances.commonRulesInJSON) + TheoryDeserializer.of( + MimeType.Json, + ).assertDeserializationWorks(Instances.commonRules, Instances.commonRulesInJSON) } @Test fun testTheorySerializationYAML() { - TheoryDeserializer.of(MimeType.Yaml).assertDeserializationWorks(Instances.commonRules, Instances.commonRulesInYAML) + TheoryDeserializer.of( + MimeType.Yaml, + ).assertDeserializationWorks(Instances.commonRules, Instances.commonRulesInYAML) } } diff --git a/serialize-theory/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestTheorySerialization.kt b/serialize-theory/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestTheorySerialization.kt index 5347f1490..403fa1081 100644 --- a/serialize-theory/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestTheorySerialization.kt +++ b/serialize-theory/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestTheorySerialization.kt @@ -3,7 +3,6 @@ package it.unibo.tuprolog.serialize import kotlin.test.Test class TestTheorySerialization { - @Test fun testTheorySerializationJSON() { TheorySerializer.of(MimeType.Json).assertSerializationWorks(Instances.commonRulesInJSON, Instances.commonRules) diff --git a/serialize-theory/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestUtils.kt b/serialize-theory/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestUtils.kt index 29efe8ee7..8696abc0e 100644 --- a/serialize-theory/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestUtils.kt +++ b/serialize-theory/src/commonTest/kotlin/it/unibo/tuprolog/serialize/TestUtils.kt @@ -6,7 +6,10 @@ import it.unibo.tuprolog.serialize.ObjectsUtils.parseAsObject import it.unibo.tuprolog.theory.Theory import it.unibo.tuprolog.utils.itemWiseEquals -fun Serializer.assertSerializationWorks(expected: String, actual: T) { +fun Serializer.assertSerializationWorks( + expected: String, + actual: T, +) { val expectedObj = parseAsObject(expected, mimeType) val actualObj = TheoryObjectifier.default.objectify(actual) kotlin.test.assertTrue( @@ -16,15 +19,21 @@ fun Serializer.assertSerializationWorks(expected: String, actual |got instead: | $actualObj | - """.trimMargin() + """.trimMargin(), ) { deeplyEqual(expectedObj, actualObj) } } -fun Serializer.assertTermSerializationWorks(expected: String, actualGenerator: Scope.() -> Theory) { +fun Serializer.assertTermSerializationWorks( + expected: String, + actualGenerator: Scope.() -> Theory, +) { assertSerializationWorks(expected, Scope.empty().actualGenerator()) } -fun Deserializer.assertDeserializationWorks(expected: T, actual: String) { +fun Deserializer.assertDeserializationWorks( + expected: T, + actual: String, +) { val deserialized = deserialize(actual) kotlin.test.assertTrue( """ @@ -33,15 +42,21 @@ fun Deserializer.assertDeserializationWorks(expected: T, actual: |got: | $deserialized | - """.trimMargin() + """.trimMargin(), ) { representationsAreEqual(expected, deserialized) } } -fun Deserializer.assertTermDeserializationWorks(actual: String, expectedGenerator: Scope.() -> Theory) { +fun Deserializer.assertTermDeserializationWorks( + actual: String, + expectedGenerator: Scope.() -> Theory, +) { assertDeserializationWorks(Scope.empty().expectedGenerator(), actual) } -private fun representationsAreEqual(t1: Theory, t2: Theory): Boolean { +private fun representationsAreEqual( + t1: Theory, + t2: Theory, +): Boolean { return itemWiseEquals(t1, t2) { x, y -> x.equals(y, false) } diff --git a/serialize-theory/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTheoryDeobjectifier.kt b/serialize-theory/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTheoryDeobjectifier.kt index 6fbab6680..9e1801157 100644 --- a/serialize-theory/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTheoryDeobjectifier.kt +++ b/serialize-theory/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTheoryDeobjectifier.kt @@ -8,7 +8,7 @@ internal class JsTheoryDeobjectifier : TheoryDeobjectifier { return Theory.of( TermDeobjectifier.default.deobjectifyMany(`object`) .asSequence() - .map { it as Clause } + .map { it as Clause }, ) } diff --git a/serialize-theory/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTheoryDeserializer.kt b/serialize-theory/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTheoryDeserializer.kt index 12dcca165..b72e6a0bb 100644 --- a/serialize-theory/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTheoryDeserializer.kt +++ b/serialize-theory/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTheoryDeserializer.kt @@ -3,8 +3,7 @@ package it.unibo.tuprolog.serialize import it.unibo.tuprolog.theory.Theory internal class JsTheoryDeserializer(override val mimeType: MimeType) : TheoryDeserializer { - override fun deserialize(string: String): Theory = - JsTheoryDeobjectifier().deobjectify(parse(string)) + override fun deserialize(string: String): Theory = JsTheoryDeobjectifier().deobjectify(parse(string)) override fun deserializeMany(string: String): Iterable = JsTheoryDeobjectifier().deobjectifyMany(parse(string)) diff --git a/serialize-theory/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTheorySerializer.kt b/serialize-theory/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTheorySerializer.kt index 82dfeaf0f..13ffb7a2f 100644 --- a/serialize-theory/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTheorySerializer.kt +++ b/serialize-theory/src/jsMain/kotlin/it/unibo/tuprolog/serialize/JsTheorySerializer.kt @@ -3,14 +3,11 @@ package it.unibo.tuprolog.serialize import it.unibo.tuprolog.theory.Theory internal class JsTheorySerializer(override val mimeType: MimeType) : TheorySerializer { - private val objectifier = JsTheoryObjectifier() - override fun serialize(value: Theory): String = - stringify(objectifier.objectify(value)) + override fun serialize(value: Theory): String = stringify(objectifier.objectify(value)) - override fun serializeMany(values: Iterable): String = - stringify(objectifier.objectifyMany(values)) + override fun serializeMany(values: Iterable): String = stringify(objectifier.objectifyMany(values)) private fun stringify(objectified: Any): String = when (mimeType) { diff --git a/serialize-theory/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTheoryDeobjectifier.kt b/serialize-theory/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTheoryDeobjectifier.kt index e74e25dd2..c88dca17b 100644 --- a/serialize-theory/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTheoryDeobjectifier.kt +++ b/serialize-theory/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTheoryDeobjectifier.kt @@ -10,7 +10,7 @@ internal class JvmTheoryDeobjectifier : TheoryDeobjectifier { Unificator.default, TermDeobjectifier.default.deobjectifyMany(`object`) .asSequence() - .map { it as Clause } + .map { it as Clause }, ) } diff --git a/serialize-theory/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTheoryDeserializer.kt b/serialize-theory/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTheoryDeserializer.kt index cb1493954..7aba5056f 100644 --- a/serialize-theory/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTheoryDeserializer.kt +++ b/serialize-theory/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTheoryDeserializer.kt @@ -4,16 +4,15 @@ import it.unibo.tuprolog.theory.Theory import java.io.Reader internal class JvmTheoryDeserializer(override val mimeType: MimeType) : ReadingTheoryDeserializer { - private val mapper = mimeType.objectMapper override fun deserialize(reader: Reader): Theory = JvmTheoryDeobjectifier().deobjectify( - mapper.readValue(reader, java.lang.Object::class.java) + mapper.readValue(reader, java.lang.Object::class.java), ) override fun deserializeMany(reader: Reader): Iterable = JvmTheoryDeobjectifier().deobjectifyMany( - mapper.readValue(reader, java.lang.Object::class.java) + mapper.readValue(reader, java.lang.Object::class.java), ) } diff --git a/serialize-theory/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTheoryObjectifier.kt b/serialize-theory/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTheoryObjectifier.kt index 3e9529567..b086b7e55 100644 --- a/serialize-theory/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTheoryObjectifier.kt +++ b/serialize-theory/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTheoryObjectifier.kt @@ -3,7 +3,6 @@ package it.unibo.tuprolog.serialize import it.unibo.tuprolog.theory.Theory internal class JvmTheoryObjectifier : TheoryObjectifier { - private val objectifier = TermObjectifier.default override fun objectify(value: Theory): Any { diff --git a/serialize-theory/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTheorySerializer.kt b/serialize-theory/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTheorySerializer.kt index 5b8ecee19..1e88dec27 100644 --- a/serialize-theory/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTheorySerializer.kt +++ b/serialize-theory/src/jvmMain/kotlin/it/unibo/tuprolog/serialize/JvmTheorySerializer.kt @@ -4,15 +4,20 @@ import it.unibo.tuprolog.theory.Theory import java.io.Writer internal class JvmTheorySerializer(override val mimeType: MimeType) : WritingTheorySerializer { - private val mapper = mimeType.objectMapper private val objectifier = JvmTheoryObjectifier() - override fun serialize(writer: Writer, value: Theory) { + override fun serialize( + writer: Writer, + value: Theory, + ) { mapper.writeValue(writer, objectifier.objectify(value)) } - override fun serializeMany(writer: Writer, values: Iterable) { + override fun serializeMany( + writer: Writer, + values: Iterable, + ) { mapper.writeValue(writer, objectifier.objectifyMany(values)) } } diff --git a/settings.gradle.kts b/settings.gradle.kts index 2cd884ee5..48e8d1d30 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -18,8 +18,10 @@ plugins { id("org.gradle.toolchains.foojay-resolver-convention") version "0.7.0" } -fun tag(format: String, vararg properties: String): String = - format.format(*properties.map { System.getProperty(it) ?: error("Missing property $it") }.toTypedArray()) +fun tag( + format: String, + vararg properties: String, +): String = format.format(*properties.map { System.getProperty(it) ?: error("Missing property $it") }.toTypedArray()) val ci = !System.getenv("CI").isNullOrBlank() val ciTag = if (ci) "CI" else "Local" diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/AbstractClassicSolver.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/AbstractClassicSolver.kt index 8c4d4de1d..b742232d1 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/AbstractClassicSolver.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/AbstractClassicSolver.kt @@ -29,18 +29,17 @@ abstract class AbstractClassicSolver( initialDynamicKb: Theory = MutableTheory.empty(unificator), inputChannels: InputStore = InputStore.fromStandard(), outputChannels: OutputStore = OutputStore.fromStandard(), - trustKb: Boolean = false + trustKb: Boolean = false, ) : AbstractSolver( - unificator, - libraries, - flags, - initialStaticKb, - initialDynamicKb, - inputChannels, - outputChannels, - trustKb -) { - + unificator, + libraries, + flags, + initialStaticKb, + initialDynamicKb, + inputChannels, + outputChannels, + trustKb, + ) { override lateinit var currentContext: ClassicExecutionContext constructor( @@ -53,7 +52,7 @@ abstract class AbstractClassicSolver( stdOut: OutputChannel = OutputChannel.stdOut(), stdErr: OutputChannel = OutputChannel.stdErr(), warnings: OutputChannel = OutputChannel.warn(), - trustKb: Boolean = false + trustKb: Boolean = false, ) : this( unificator, libraries, @@ -62,7 +61,7 @@ abstract class AbstractClassicSolver( dynamicKb, InputStore.fromStandard(stdIn), OutputStore.fromStandard(stdOut, stdErr, warnings), - trustKb + trustKb, ) final override fun initializeContext( @@ -74,7 +73,7 @@ abstract class AbstractClassicSolver( operators: OperatorSet, inputChannels: InputStore, outputChannels: OutputStore, - trustKb: Boolean + trustKb: Boolean, ) = ClassicExecutionContext( unificator = unificator, libraries = libraries, @@ -84,34 +83,42 @@ abstract class AbstractClassicSolver( operators = getAllOperators(libraries).toOperatorSet(), inputChannels = inputChannels, outputChannels = outputChannels, - startTime = 0 + startTime = 0, ) - final override fun solveImpl(goal: Struct, options: SolveOptions): Sequence { - currentContext = ClassicExecutionContext( - unificator = unificator, - query = goal, - libraries = libraries, - flags = flags, - staticKb = staticKb.toImmutableTheory(), - dynamicKb = dynamicKb.toMutableTheory(), - operators = operators, - inputChannels = inputChannels, - outputChannels = outputChannels, - customData = currentContext.customData, - startTime = currentTimeInstant(), - maxDuration = options.timeout - ) + final override fun solveImpl( + goal: Struct, + options: SolveOptions, + ): Sequence { + currentContext = + ClassicExecutionContext( + unificator = unificator, + query = goal, + libraries = libraries, + flags = flags, + staticKb = staticKb.toImmutableTheory(), + dynamicKb = dynamicKb.toMutableTheory(), + operators = operators, + inputChannels = inputChannels, + outputChannels = outputChannels, + customData = currentContext.customData, + startTime = currentTimeInstant(), + maxDuration = options.timeout, + ) return solutionIterator(StateInit(currentContext), this::updateCurrentContextAfterStateTransition).asSequence() } protected abstract fun solutionIterator( initialState: State, - onStateTransition: (State, State, Long) -> Unit + onStateTransition: (State, State, Long) -> Unit, ): SolutionIterator @Suppress("UNUSED_PARAMETER") - private fun updateCurrentContextAfterStateTransition(source: State, destination: State, index: Long) { + private fun updateCurrentContextAfterStateTransition( + source: State, + destination: State, + index: Long, + ) { require(destination.context.step == index) currentContext = destination.context } @@ -125,7 +132,7 @@ abstract class AbstractClassicSolver( stdIn: InputChannel, stdOut: OutputChannel, stdErr: OutputChannel, - warnings: OutputChannel + warnings: OutputChannel, ): AbstractClassicSolver abstract override fun clone(): AbstractClassicSolver diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/ChoicePointContext.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/ChoicePointContext.kt index f805b3bcb..cb1bdd366 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/ChoicePointContext.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/ChoicePointContext.kt @@ -9,10 +9,9 @@ sealed class ChoicePointContext( open val alternatives: Cursor, open val executionContext: ClassicExecutionContext?, open val parent: ChoicePointContext?, - open val depth: Int = 0 + open val depth: Int = 0, ) { - -// This assertion fails on JS since depth is undefined + // This assertion fails on JS since depth is undefined // init { // require((depth == 0 && parent == null) || (depth > 0 && parent != null)) { // """Violated initial constraint for claass ChoicePointContext: (depth == 0 && parent == null) || (depth > 0 && parent != null) @@ -29,14 +28,15 @@ sealed class ChoicePointContext( get() = pathToRoot.any { it.alternatives.hasNext } val pathToRoot: Sequence - get() = sequence { - var curr: ChoicePointContext? = this@ChoicePointContext - while (curr != null) { - @Suppress("UNNECESSARY_NOT_NULL_ASSERTION") - yield(curr!!) - curr = curr.parent + get() = + sequence { + var curr: ChoicePointContext? = this@ChoicePointContext + while (curr != null) { + @Suppress("UNNECESSARY_NOT_NULL_ASSERTION") + yield(curr!!) + curr = curr.parent + } } - } val executionContextDepth: Int? get() = executionContext?.depth @@ -44,16 +44,17 @@ sealed class ChoicePointContext( val executionContextProcedure: Struct? get() = executionContext?.procedure - override fun toString(): String = "$typeName(" + - "alternatives=$alternatives, " + - if (executionContext === null) { - "executionContext=$executionContext, " - } else { - "executionContextDepth=$executionContextDepth, " - "executionContextProcedure=$executionContextProcedure, " - } + - "depth=$depth" + - ")" + override fun toString(): String = + "$typeName(" + + "alternatives=$alternatives, " + + if (executionContext === null) { + "executionContext=$executionContext, " + } else { + "executionContextDepth=$executionContextDepth, " + "executionContextProcedure=$executionContextProcedure, " + } + + "depth=$depth" + + ")" protected abstract val typeName: String @@ -63,9 +64,8 @@ sealed class ChoicePointContext( override val alternatives: Cursor, override val executionContext: ClassicExecutionContext?, override val parent: ChoicePointContext?, - override val depth: Int + override val depth: Int, ) : ChoicePointContext(alternatives, executionContext, parent, depth) { - override fun toString(): String { return super.toString() } @@ -74,24 +74,26 @@ sealed class ChoicePointContext( get() = "Primitives" override fun backtrack(context: ClassicExecutionContext): ClassicExecutionContext { - val tempContext = executionContext!!.copy( - primitives = alternatives, - step = context.step + 1, - startTime = context.startTime, - flags = context.flags, - dynamicKb = context.dynamicKb, - staticKb = context.staticKb, - operators = context.operators, - inputChannels = context.inputChannels, - outputChannels = context.outputChannels, - libraries = context.libraries, - customData = context.customData.discardEphemeral() - ) - - val nextChoicePointContext = copy( - alternatives = alternatives.next, - executionContext = tempContext - ) + val tempContext = + executionContext!!.copy( + primitives = alternatives, + step = context.step + 1, + startTime = context.startTime, + flags = context.flags, + dynamicKb = context.dynamicKb, + staticKb = context.staticKb, + operators = context.operators, + inputChannels = context.inputChannels, + outputChannels = context.outputChannels, + libraries = context.libraries, + customData = context.customData.discardEphemeral(), + ) + + val nextChoicePointContext = + copy( + alternatives = alternatives.next, + executionContext = tempContext, + ) return tempContext.copy(choicePoints = nextChoicePointContext) } @@ -101,9 +103,8 @@ sealed class ChoicePointContext( override val alternatives: Cursor, override val executionContext: ClassicExecutionContext?, override val parent: ChoicePointContext?, - override val depth: Int + override val depth: Int, ) : ChoicePointContext(alternatives, executionContext, parent, depth) { - override fun toString(): String { return super.toString() } @@ -112,24 +113,26 @@ sealed class ChoicePointContext( get() = "Rules" override fun backtrack(context: ClassicExecutionContext): ClassicExecutionContext { - val tempContext = executionContext!!.copy( - rules = alternatives, - step = context.step + 1, - startTime = context.startTime, - flags = context.flags, - dynamicKb = context.dynamicKb, - staticKb = context.staticKb, - operators = context.operators, - inputChannels = context.inputChannels, - outputChannels = context.outputChannels, - libraries = context.libraries, - customData = context.customData.discardEphemeral() - ) - - val nextChoicePointContext = copy( - alternatives = alternatives.next, - executionContext = tempContext - ) + val tempContext = + executionContext!!.copy( + rules = alternatives, + step = context.step + 1, + startTime = context.startTime, + flags = context.flags, + dynamicKb = context.dynamicKb, + staticKb = context.staticKb, + operators = context.operators, + inputChannels = context.inputChannels, + outputChannels = context.outputChannels, + libraries = context.libraries, + customData = context.customData.discardEphemeral(), + ) + + val nextChoicePointContext = + copy( + alternatives = alternatives.next, + executionContext = tempContext, + ) return tempContext.copy(choicePoints = nextChoicePointContext) } @@ -140,10 +143,10 @@ fun ChoicePointContext?.nextDepth(): Int = if (this == null) 0 else this.depth + fun ChoicePointContext?.appendPrimitives( alternatives: Cursor, - executionContext: ClassicExecutionContext? = null + executionContext: ClassicExecutionContext? = null, ): ChoicePointContext = ChoicePointContext.Primitives(alternatives, executionContext, this, nextDepth()) fun ChoicePointContext?.appendRules( alternatives: Cursor, - executionContext: ClassicExecutionContext? = null + executionContext: ClassicExecutionContext? = null, ): ChoicePointContext = ChoicePointContext.Rules(alternatives, executionContext, this, nextDepth()) diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/ClassicExecutionContext.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/ClassicExecutionContext.kt index 695da1069..3f90d1058 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/ClassicExecutionContext.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/ClassicExecutionContext.kt @@ -51,7 +51,7 @@ data class ClassicExecutionContext( val parent: ClassicExecutionContext? = null, val depth: Int = 0, val step: Long = 0, - val relevantVariables: KtSet = emptySet() + val relevantVariables: KtSet = emptySet(), ) : ExecutionContext { init { require((depth == 0 && parent == null) || (depth > 0 && parent != null)) @@ -69,13 +69,14 @@ data class ClassicExecutionContext( val isActivationRecord: Boolean get() = parent == null || depth - parent.depth >= 1 - val pathToRoot: Sequence = sequence { - var current: ClassicExecutionContext? = this@ClassicExecutionContext - while (current != null) { - yield(current) - current = current.parent + val pathToRoot: Sequence = + sequence { + var current: ClassicExecutionContext? = this@ClassicExecutionContext + while (current != null) { + yield(current) + current = current.parent + } } - } val currentGoal: Term? by lazy { if (goals.isOver) null else goals.current?.apply(substitution) @@ -90,8 +91,7 @@ data class ClassicExecutionContext( .cached() } - fun isVariableInteresting(variable: Var) = - variable in interestingVariables + fun isVariableInteresting(variable: Var) = variable in interestingVariables override val logicStackTrace: KtList by lazy { pathToRoot.filter { it.isActivationRecord } @@ -106,8 +106,18 @@ data class ClassicExecutionContext( staticKb: Theory, dynamicKb: Theory, inputChannels: InputStore, - outputChannels: OutputStore - ): Solver = ClassicSolver(unificator, libraries, flags, staticKb, dynamicKb, inputChannels, outputChannels, trustKb = true) + outputChannels: OutputStore, + ): Solver = + ClassicSolver( + unificator, + libraries, + flags, + staticKb, + dynamicKb, + inputChannels, + outputChannels, + trustKb = true, + ) override fun createMutableSolver( unificator: Unificator, @@ -116,9 +126,18 @@ data class ClassicExecutionContext( staticKb: Theory, dynamicKb: Theory, inputChannels: InputStore, - outputChannels: OutputStore + outputChannels: OutputStore, ): MutableSolver = - MutableClassicSolver(unificator, libraries, flags, staticKb, dynamicKb, inputChannels, outputChannels, trustKb = true) + MutableClassicSolver( + unificator, + libraries, + flags, + staticKb, + dynamicKb, + inputChannels, + outputChannels, + trustKb = true, + ) override fun update( unificator: Unificator, @@ -129,7 +148,7 @@ data class ClassicExecutionContext( operators: OperatorSet, inputChannels: InputStore, outputChannels: OutputStore, - customData: CustomDataStore + customData: CustomDataStore, ): ClassicExecutionContext { return copy( unificator = unificator, @@ -140,7 +159,7 @@ data class ClassicExecutionContext( operators = operators, inputChannels = inputChannels, outputChannels = outputChannels, - customData = customData + customData = customData, ) } diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/ClassicSolver.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/ClassicSolver.kt index 887680c42..5489a8690 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/ClassicSolver.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/ClassicSolver.kt @@ -13,7 +13,6 @@ import it.unibo.tuprolog.theory.Theory import it.unibo.tuprolog.unify.Unificator internal open class ClassicSolver : AbstractClassicSolver { - constructor( unificator: Unificator = Unificator.default, libraries: Runtime = Runtime.empty(), @@ -22,7 +21,7 @@ internal open class ClassicSolver : AbstractClassicSolver { initialDynamicKb: Theory = MutableTheory.empty(unificator), inputChannels: InputStore = InputStore.fromStandard(), outputChannels: OutputStore = OutputStore.fromStandard(), - trustKb: Boolean = false + trustKb: Boolean = false, ) : super(unificator, libraries, flags, initialStaticKb, initialDynamicKb, inputChannels, outputChannels, trustKb) constructor( @@ -35,12 +34,12 @@ internal open class ClassicSolver : AbstractClassicSolver { stdOut: OutputChannel = OutputChannel.stdOut(), stdErr: OutputChannel = OutputChannel.stdErr(), warnings: OutputChannel = OutputChannel.warn(), - trustKb: Boolean = false + trustKb: Boolean = false, ) : super(unificator, libraries, flags, staticKb, dynamicKb, stdIn, stdOut, stdErr, warnings, trustKb) override fun solutionIterator( initialState: State, - onStateTransition: (State, State, Long) -> Unit + onStateTransition: (State, State, Long) -> Unit, ) = SolutionIterator.of(initialState, onStateTransition) override fun copy( @@ -52,7 +51,7 @@ internal open class ClassicSolver : AbstractClassicSolver { stdIn: InputChannel, stdOut: OutputChannel, stdErr: OutputChannel, - warnings: OutputChannel + warnings: OutputChannel, ) = ClassicSolver(unificator, libraries, flags, staticKb, dynamicKb, stdIn, stdOut, stdErr, warnings) override fun clone(): ClassicSolver = copy() diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/ClassicSolverFactory.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/ClassicSolverFactory.kt index 434cc2340..c77a36a12 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/ClassicSolverFactory.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/ClassicSolverFactory.kt @@ -19,7 +19,6 @@ import kotlin.js.JsExport @Suppress("NON_EXPORTABLE_TYPE") @JsExport object ClassicSolverFactory : SolverFactory { - override val defaultBuiltins: Library get() = DefaultBuiltins @@ -30,7 +29,7 @@ object ClassicSolverFactory : SolverFactory { staticKb: Theory, dynamicKb: Theory, inputs: InputStore, - outputs: OutputStore + outputs: OutputStore, ): Solver = ClassicSolver(unificator, libraries, flags, staticKb, dynamicKb, inputs, outputs) override fun solverOf( @@ -42,7 +41,7 @@ object ClassicSolverFactory : SolverFactory { stdIn: InputChannel, stdOut: OutputChannel, stdErr: OutputChannel, - warnings: OutputChannel + warnings: OutputChannel, ): Solver = ClassicSolver(unificator, libraries, flags, staticKb, dynamicKb, stdIn, stdOut, stdErr, warnings) override fun mutableSolverOf( @@ -54,8 +53,9 @@ object ClassicSolverFactory : SolverFactory { stdIn: InputChannel, stdOut: OutputChannel, stdErr: OutputChannel, - warnings: OutputChannel - ): MutableSolver = MutableClassicSolver(unificator, libraries, flags, staticKb, dynamicKb, stdIn, stdOut, stdErr, warnings) + warnings: OutputChannel, + ): MutableSolver = + MutableClassicSolver(unificator, libraries, flags, staticKb, dynamicKb, stdIn, stdOut, stdErr, warnings) override fun mutableSolverOf( unificator: Unificator, @@ -64,6 +64,6 @@ object ClassicSolverFactory : SolverFactory { staticKb: Theory, dynamicKb: Theory, inputs: InputStore, - outputs: OutputStore + outputs: OutputStore, ): MutableSolver = MutableClassicSolver(unificator, libraries, flags, staticKb, dynamicKb, inputs, outputs) } diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/MutableClassicSolver.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/MutableClassicSolver.kt index e4c227fea..7d1b9f599 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/MutableClassicSolver.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/MutableClassicSolver.kt @@ -21,7 +21,6 @@ import it.unibo.tuprolog.theory.Theory import it.unibo.tuprolog.unify.Unificator internal class MutableClassicSolver : ClassicSolver, MutableSolver { - constructor( unificator: Unificator = Unificator.default, libraries: Runtime = Runtime.empty(), @@ -30,7 +29,7 @@ internal class MutableClassicSolver : ClassicSolver, MutableSolver { dynamicKb: Theory = MutableTheory.empty(unificator), inputChannels: InputStore = InputStore.fromStandard(), outputChannels: OutputStore = OutputStore.fromStandard(), - trustKb: Boolean = false + trustKb: Boolean = false, ) : super(unificator, libraries, flags, staticKb, dynamicKb, inputChannels, outputChannels, trustKb) constructor( @@ -43,7 +42,7 @@ internal class MutableClassicSolver : ClassicSolver, MutableSolver { stdOut: OutputChannel = OutputChannel.stdOut(), stdErr: OutputChannel = OutputChannel.stdErr(), warnings: OutputChannel = OutputChannel.warn(), - trustKb: Boolean = false + trustKb: Boolean = false, ) : super(unificator, libraries, flags, staticKb, dynamicKb, stdIn, stdOut, stdErr, warnings, trustKb) override fun loadLibrary(library: Library) { @@ -51,7 +50,7 @@ internal class MutableClassicSolver : ClassicSolver, MutableSolver { val newRuntime = libraries + library copy( libraries = newRuntime, - operators = operators + getAllOperators(newRuntime).toOperatorSet() + operators = operators + getAllOperators(newRuntime).toOperatorSet(), ) } } @@ -61,7 +60,7 @@ internal class MutableClassicSolver : ClassicSolver, MutableSolver { val newRuntime = libraries + library copy( libraries = newRuntime, - operators = getAllOperators(newRuntime, staticKb, dynamicKb).toOperatorSet() + operators = getAllOperators(newRuntime, staticKb, dynamicKb).toOperatorSet(), ) } } @@ -70,7 +69,7 @@ internal class MutableClassicSolver : ClassicSolver, MutableSolver { updateContext { copy( libraries = libraries, - operators = getAllOperators(libraries, staticKb, dynamicKb).toOperatorSet() + operators = getAllOperators(libraries, staticKb, dynamicKb).toOperatorSet(), ) } } @@ -78,7 +77,7 @@ internal class MutableClassicSolver : ClassicSolver, MutableSolver { override fun loadStaticKb(theory: Theory) { initializeKb( staticKb = theory, - appendStatic = false + appendStatic = false, ) } @@ -90,7 +89,7 @@ internal class MutableClassicSolver : ClassicSolver, MutableSolver { updateContext { copy( staticKb = Theory.empty(unificator), - operators = getAllOperators(libraries, dynamicKb).toOperatorSet() + operators = getAllOperators(libraries, dynamicKb).toOperatorSet(), ) } } @@ -98,7 +97,7 @@ internal class MutableClassicSolver : ClassicSolver, MutableSolver { override fun loadDynamicKb(theory: Theory) { initializeKb( dynamicKb = theory, - appendDynamic = false + appendDynamic = false, ) } @@ -110,7 +109,7 @@ internal class MutableClassicSolver : ClassicSolver, MutableSolver { updateContext { copy( dynamicKb = MutableTheory.empty(unificator), - operators = getAllOperators(libraries, staticKb).toOperatorSet() + operators = getAllOperators(libraries, staticKb).toOperatorSet(), ) } } @@ -119,7 +118,7 @@ internal class MutableClassicSolver : ClassicSolver, MutableSolver { updateContext { copy( dynamicKb = dynamicKb.assertA(clause), - operators = operators + listOf(clause).getAllOperators().toOperatorSet() + operators = operators + listOf(clause).getAllOperators().toOperatorSet(), ) } } @@ -134,7 +133,7 @@ internal class MutableClassicSolver : ClassicSolver, MutableSolver { updateContext { copy( dynamicKb = dynamicKb.assertZ(clause), - operators = operators + listOf(clause).getAllOperators().toOperatorSet() + operators = operators + listOf(clause).getAllOperators().toOperatorSet(), ) } } @@ -150,7 +149,7 @@ internal class MutableClassicSolver : ClassicSolver, MutableSolver { updateContext { copy( dynamicKb = result.theory.toMutableTheory(), - operators = operators - listOf(clause).getAllOperators().toOperatorSet() + operators = operators - listOf(clause).getAllOperators().toOperatorSet(), ) } return result @@ -169,7 +168,7 @@ internal class MutableClassicSolver : ClassicSolver, MutableSolver { updateContext { copy( dynamicKb = result.theory.toMutableTheory(), - operators = operators - result.theory.getAllOperators().toOperatorSet() + operators = operators - result.theory.getAllOperators().toOperatorSet(), ) } return result @@ -183,7 +182,10 @@ internal class MutableClassicSolver : ClassicSolver, MutableSolver { return result } - override fun setFlag(name: String, value: Term) { + override fun setFlag( + name: String, + value: Term, + ) { updateContext { copy(flags = flags.set(name, value)) } @@ -234,7 +236,7 @@ internal class MutableClassicSolver : ClassicSolver, MutableSolver { stdIn: InputChannel, stdOut: OutputChannel, stdErr: OutputChannel, - warnings: OutputChannel + warnings: OutputChannel, ) = MutableClassicSolver(unificator, libraries, flags, staticKb, dynamicKb, stdIn, stdOut, stdErr, warnings) override fun clone(): MutableClassicSolver = copy() diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/MutableSolutionIterator.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/MutableSolutionIterator.kt index e4e6a9c95..a733a42da 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/MutableSolutionIterator.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/MutableSolutionIterator.kt @@ -8,7 +8,11 @@ import kotlin.jvm.JvmStatic interface MutableSolutionIterator : SolutionIterator { @JsName("hijackStateTransition") - fun hijackStateTransition(source: State, destination: State, index: Long): State + fun hijackStateTransition( + source: State, + destination: State, + index: Long, + ): State companion object { @JsName("of") @@ -17,7 +21,7 @@ interface MutableSolutionIterator : SolutionIterator { fun of( initialState: State, hijackStateTransitionCallback: (State, State, Long) -> State = { _, dest, _ -> dest }, - onStateTransitionCallback: (State, State, Long) -> Unit = { _, _, _ -> } + onStateTransitionCallback: (State, State, Long) -> Unit = { _, _, _ -> }, ): SolutionIterator { return HijackableSolutionIterator(initialState, hijackStateTransitionCallback, onStateTransitionCallback) } diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/SolutionIterator.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/SolutionIterator.kt index fd6e07ab2..e05f7a83a 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/SolutionIterator.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/SolutionIterator.kt @@ -18,14 +18,18 @@ interface SolutionIterator : Iterator { override fun next(): Solution @JsName("onStateTransition") - fun onStateTransition(source: State, destination: State, index: Long) + fun onStateTransition( + source: State, + destination: State, + index: Long, + ) companion object { @JsName("of") @JvmStatic fun of( initialState: State, - onStateTransition: (State, State, Long) -> Unit = { _, _, _ -> } + onStateTransition: (State, State, Long) -> Unit = { _, _, _ -> }, ): SolutionIterator = SimpleSolutionIterator(initialState, onStateTransition) } } diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/AbstractEndState.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/AbstractEndState.kt index c5c486078..0bcfa4a26 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/AbstractEndState.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/AbstractEndState.kt @@ -5,7 +5,7 @@ import it.unibo.tuprolog.solve.classic.ClassicExecutionContext abstract class AbstractEndState( override val solution: Solution, - override val context: ClassicExecutionContext + override val context: ClassicExecutionContext, ) : EndState, AbstractState(context) { override fun computeNext(): State = throw NoSuchElementException() } diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/AbstractState.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/AbstractState.kt index 23117bab3..4906dcae1 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/AbstractState.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/AbstractState.kt @@ -8,7 +8,6 @@ import it.unibo.tuprolog.solve.currentTimeInstant import it.unibo.tuprolog.solve.exception.TimeOutException abstract class AbstractState(override val context: ClassicExecutionContext) : State { - protected val executionTime: TimeInstant by lazy { currentTime() } @@ -21,9 +20,9 @@ abstract class AbstractState(override val context: ClassicExecutionContext) : St StateHalt( TimeOutException( exceededDuration = context.maxDuration, - context = context + context = context, ), - context.copy(step = nextStep()) + context.copy(step = nextStep()), ) } else { computeNext() @@ -41,5 +40,7 @@ abstract class AbstractState(override val context: ClassicExecutionContext) : St protected fun previousDepth(): Int = context.depth - 1 protected fun ClassicExecutionContext.skipThrow(): ExecutionContext = - pathToRoot.first { it.procedure?.functor != Throw.functor } + pathToRoot.first { + it.procedure?.functor != Throw.functor + } } diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/EndState.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/EndState.kt index 96faba981..b53438741 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/EndState.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/EndState.kt @@ -4,7 +4,6 @@ import it.unibo.tuprolog.solve.Solution import kotlin.js.JsName interface EndState : State { - @JsName("solution") val solution: Solution diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/State.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/State.kt index f84dc9ef6..bac5437d9 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/State.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/State.kt @@ -4,7 +4,6 @@ import it.unibo.tuprolog.solve.classic.ClassicExecutionContext import kotlin.js.JsName interface State { - @JsName("isEndState") val isEndState: Boolean get() = false diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateBacktracking.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateBacktracking.kt index c48bc7110..28e9ab522 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateBacktracking.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateBacktracking.kt @@ -9,7 +9,7 @@ data class StateBacktracking(override val context: ClassicExecutionContext) : Ab return if (choicePoints.let { it === null || !it.hasOpenAlternatives }) { StateEnd( solution = Solution.no(context.query), - context = context.copy(step = nextStep()) + context = context.copy(step = nextStep()), ) } else { val choicePointContext = choicePoints!!.pathToRoot.first { it.alternatives.hasNext } diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateEnd.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateEnd.kt index edf70cf9f..864108eb1 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateEnd.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateEnd.kt @@ -5,9 +5,8 @@ import it.unibo.tuprolog.solve.classic.ClassicExecutionContext data class StateEnd( override val solution: Solution, - override val context: ClassicExecutionContext + override val context: ClassicExecutionContext, ) : AbstractEndState(solution, context) { - override val isTimeout: Boolean get() = false diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateException.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateException.kt index c453d77ec..ecc82740b 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateException.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateException.kt @@ -15,11 +15,9 @@ import it.unibo.tuprolog.utils.plus data class StateException( override val exception: ResolutionException, - override val context: ClassicExecutionContext + override val context: ClassicExecutionContext, ) : ExceptionalState, AbstractState(context) { - - private fun Struct.isCatch(): Boolean = - arity == 3 && functor == Catch.functor + private fun Struct.isCatch(): Boolean = arity == 3 && functor == Catch.functor private fun LogicError.getExceptionContent(): Term { return when (this) { @@ -35,18 +33,24 @@ data class StateException( } private val finalState: EndState - get() = StateHalt( - exception.toPublicException(), - context.copy(step = nextStep()) - ) + get() = + StateHalt( + exception.toPublicException(), + context.copy(step = nextStep()), + ) private val handleExceptionInParentContext: StateException - get() = StateException( - exception, - context.parent!!.copy(step = nextStep()) - ) + get() = + StateException( + exception, + context.parent!!.copy(step = nextStep()), + ) - private fun handleStruct(unificator: Unificator, catchGoal: Struct, error: LogicError): State = + private fun handleStruct( + unificator: Unificator, + catchGoal: Struct, + error: LogicError, + ): State = when { catchGoal.isCatch() -> { val catcher = unificator.mgu(catchGoal[1], error.getExceptionContent()) @@ -56,28 +60,31 @@ data class StateException( else -> handleExceptionInParentContext } - private fun handleCatch(catchGoal: Struct, catcher: Substitution) = - when { - catcher.isSuccess -> { - val newSubstitution = (context.substitution + catcher).filter { (it, _) -> + private fun handleCatch( + catchGoal: Struct, + catcher: Substitution, + ) = when { + catcher.isSuccess -> { + val newSubstitution = + (context.substitution + catcher).filter { (it, _) -> context.isVariableInteresting(it) } - val subGoals = catchGoal[2][newSubstitution] - val newGoals = subGoals.toGoals() + context.goals.next + val subGoals = catchGoal[2][newSubstitution] + val newGoals = subGoals.toGoals() + context.goals.next - StateGoalSelection( - context.copy( - goals = newGoals, - rules = Cursor.empty(), - primitives = Cursor.empty(), - substitution = newSubstitution.castToUnifier(), - step = nextStep() - ) - ) - } - context.isRoot -> finalState - else -> handleExceptionInParentContext + StateGoalSelection( + context.copy( + goals = newGoals, + rules = Cursor.empty(), + primitives = Cursor.empty(), + substitution = newSubstitution.castToUnifier(), + step = nextStep(), + ), + ) } + context.isRoot -> finalState + else -> handleExceptionInParentContext + } override fun computeNext(): State { return when (exception) { @@ -94,5 +101,8 @@ data class StateException( } override fun clone(context: ClassicExecutionContext): StateException = - copy(exception = exception, context = context) + copy( + exception = exception, + context = context, + ) } diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateGoalSelection.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateGoalSelection.kt index 3ab7fd36d..d4337c52d 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateGoalSelection.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateGoalSelection.kt @@ -5,12 +5,13 @@ import it.unibo.tuprolog.solve.classic.ClassicExecutionContext import it.unibo.tuprolog.solve.flags.TrackVariables data class StateGoalSelection(override val context: ClassicExecutionContext) : AbstractState(context) { + @Suppress("ktlint:standard:discouraged-comment-location") override fun computeNext(): State { return if (context.goals.isOver) { if (context.isRoot) { StateEnd( Solution.yes(context.query, context.substitution), - context.copy(step = nextStep()) + context.copy(step = nextStep()), ) } else { StateGoalSelection( @@ -29,21 +30,21 @@ data class StateGoalSelection(override val context: ClassicExecutionContext) : A inputChannels = context.inputChannels, outputChannels = context.outputChannels, libraries = context.libraries, - customData = context.customData + customData = context.customData, ) - } + }, ) } } else if (context.flags[TrackVariables] == TrackVariables.ON) { StatePrimitiveSelection( context.copy( step = nextStep(), - relevantVariables = context.relevantVariables + context.goals.current!!.variables.toSet() - ) + relevantVariables = context.relevantVariables + context.goals.current!!.variables.toSet(), + ), ) } else { StatePrimitiveSelection( - context.copy(step = nextStep()) + context.copy(step = nextStep()), ) } } diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateHalt.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateHalt.kt index f30ece010..234eda390 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateHalt.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateHalt.kt @@ -6,7 +6,7 @@ import it.unibo.tuprolog.solve.exception.ResolutionException data class StateHalt( override val exception: ResolutionException, - override val context: ClassicExecutionContext + override val context: ClassicExecutionContext, ) : ExceptionalState, AbstractEndState(Solution.halt(context.query, exception), context) { override fun clone(context: ClassicExecutionContext): StateHalt = copy(exception = exception, context = context) } diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateInit.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateInit.kt index 1d8ee85df..3994af4f8 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateInit.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateInit.kt @@ -17,8 +17,8 @@ data class StateInit(override val context: ClassicExecutionContext) : AbstractSt depth = 0, step = 1, customData = context.customData.preservePersistent(), - relevantVariables = emptySet() - ).appendRulesAndChoicePoints(Cursor.empty()) + relevantVariables = emptySet(), + ).appendRulesAndChoicePoints(Cursor.empty()), ) } diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StatePrimitiveExecution.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StatePrimitiveExecution.kt index dda9d7e40..1f09f1a6f 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StatePrimitiveExecution.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StatePrimitiveExecution.kt @@ -7,11 +7,10 @@ import it.unibo.tuprolog.solve.exception.ResolutionException import it.unibo.tuprolog.utils.Cursor data class StatePrimitiveExecution(override val context: ClassicExecutionContext) : AbstractState(context) { - private fun ClassicExecutionContext.copyFromCurrentPrimitive( goals: Cursor? = null, procedureFromAncestor: Int = 0, - substitution: Substitution? = null + substitution: Substitution? = null, ): ClassicExecutionContext { val ctx = primitives.current?.let { apply(it.sideEffects) } ?: this return ctx.copy( @@ -19,36 +18,41 @@ data class StatePrimitiveExecution(override val context: ClassicExecutionContext procedure = pathToRoot.drop(procedureFromAncestor).map { it.procedure }.first(), primitives = Cursor.empty(), substitution = (substitution ?: this.substitution) as Substitution.Unifier, - step = nextStep() + step = nextStep(), ) } - override fun computeNext(): State = try { - context.primitives.current?.solution?.whenIs( - yes = { - StateGoalSelection( - context.copyFromCurrentPrimitive( - goals = context.goals.next, - procedureFromAncestor = 1, - substitution = context.unificator.merge( - context.substitution, - it.substitution, - occurCheckEnabled = false - ) + override fun computeNext(): State = + try { + context.primitives.current?.solution?.whenIs( + yes = { + StateGoalSelection( + context.copyFromCurrentPrimitive( + goals = context.goals.next, + procedureFromAncestor = 1, + substitution = + context.unificator.merge( + context.substitution, + it.substitution, + occurCheckEnabled = false, + ), + ), ) - ) - }, - no = { - StateBacktracking(context.parent!!.copyFromCurrentPrimitive()) - }, - halt = { - StateException(it.exception.updateLastContext(context.skipThrow()), context.copyFromCurrentPrimitive()) - }, - otherwise = { throw IllegalStateException("This should never happen") } - ) ?: StateBacktracking(context.copyFromCurrentPrimitive()) - } catch (exception: ResolutionException) { - StateException(exception.updateLastContext(context.skipThrow()), context.copy(step = nextStep())) - } + }, + no = { + StateBacktracking(context.parent!!.copyFromCurrentPrimitive()) + }, + halt = { + StateException( + it.exception.updateLastContext(context.skipThrow()), + context.copyFromCurrentPrimitive(), + ) + }, + otherwise = { throw IllegalStateException("This should never happen") }, + ) ?: StateBacktracking(context.copyFromCurrentPrimitive()) + } catch (exception: ResolutionException) { + StateException(exception.updateLastContext(context.skipThrow()), context.copy(step = nextStep())) + } override fun clone(context: ClassicExecutionContext): StatePrimitiveExecution = copy(context = context) } diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StatePrimitiveSelection.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StatePrimitiveSelection.kt index 4f019f124..e16f2ca75 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StatePrimitiveSelection.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StatePrimitiveSelection.kt @@ -9,11 +9,10 @@ import it.unibo.tuprolog.solve.extractSignature import it.unibo.tuprolog.utils.cursor data class StatePrimitiveSelection(override val context: ClassicExecutionContext) : AbstractState(context) { - private fun exceptionalState(exception: ResolutionException): StateException { return StateException( exception, - context.copy(step = nextStep()) + context.copy(step = nextStep()), ) } @@ -26,8 +25,8 @@ data class StatePrimitiveSelection(override val context: ClassicExecutionContext InstantiationError.forGoal( context = context, procedure = context.procedure!!.extractSignature(), - variable = goal.castToVar() - ) + variable = goal.castToVar(), + ), ) } goal.isStruct -> { @@ -38,8 +37,9 @@ data class StatePrimitiveSelection(override val context: ClassicExecutionContext val childContext = createChild() try { val request = childContext.toRequest(goalStruct, signature, executionTime) - val primitive = libraries.primitives[signature] - ?: error("Inconsistent behaviour of Library.contains and Library.get") + val primitive = + libraries.primitives[signature] + ?: error("Inconsistent behaviour of Library.contains and Library.get") val primitiveExecutions = primitive.solve(request).cursor() StatePrimitiveExecution(childContext.appendPrimitivesAndChoicePoints(primitiveExecutions)) } catch (exception: ResolutionException) { @@ -55,8 +55,8 @@ data class StatePrimitiveSelection(override val context: ClassicExecutionContext context = context, procedure = context.procedure?.extractSignature() ?: Signature("?-", 1), expectedType = TypeError.Expected.CALLABLE, - culprit = goal - ) + culprit = goal, + ), ) } } diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateRuleExecution.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateRuleExecution.kt index 73d69cb5a..899e275b0 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateRuleExecution.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateRuleExecution.kt @@ -20,8 +20,8 @@ data class StateRuleExecution(override val context: ClassicExecutionContext) : A goals = subGoals.toGoals(), rules = Cursor.empty(), substitution = newSubstitution, - step = nextStep() - ) + step = nextStep(), + ), ) } else -> failureState diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateRuleSelection.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateRuleSelection.kt index 3d87cd23f..2ddb6e674 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateRuleSelection.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/StateRuleSelection.kt @@ -22,15 +22,15 @@ import it.unibo.tuprolog.utils.buffered import it.unibo.tuprolog.utils.cursor data class StateRuleSelection(override val context: ClassicExecutionContext) : AbstractState(context) { - companion object { private val catchSignature = Catch.signature - private val transparentToCut = setOf( - Signature(",", 2), - Signature(";", 2), - Signature("->", 2) - ) + private val transparentToCut = + setOf( + Signature(",", 2), + Signature(";", 2), + Signature("->", 2), + ) private sealed class CutLimit { abstract val depthToCut: Int @@ -57,26 +57,31 @@ data class StateRuleSelection(override val context: ClassicExecutionContext) : A private fun exceptionalState(exception: ResolutionException): StateException = StateException(exception, context.copy(step = nextStep())) - private fun missingProcedure(ruleSources: Sequence, missing: Signature): State = + private fun missingProcedure( + ruleSources: Sequence, + missing: Signature, + ): State = when (val unknown = context.flags[Unknown]) { Unknown.FAIL -> failureState else -> { if (ruleSources.none { missing.toIndicator() in it }) { when (unknown) { - Unknown.ERROR -> exceptionalState( - ExistenceError.forProcedure( - context = context, - procedure = missing - ) - ) - Unknown.WARNING -> failureState.also { - context.warnings.write( - MissingPredicate( + Unknown.ERROR -> + exceptionalState( + ExistenceError.forProcedure( context = context, - signature = missing - ) + procedure = missing, + ), ) - } + Unknown.WARNING -> + failureState.also { + context.warnings.write( + MissingPredicate( + context = context, + signature = missing, + ), + ) + } else -> failureState } } else { @@ -86,18 +91,20 @@ data class StateRuleSelection(override val context: ClassicExecutionContext) : A } private val ignoreState: StateGoalSelection - get() = StateGoalSelection( - context.copy(goals = context.goals.next, step = nextStep()) - ) + get() = + StateGoalSelection( + context.copy(goals = context.goals.next, step = nextStep()), + ) private fun Term.isCut(): Boolean = this.isAtom && this.castToAtom().value == "!" private fun ClassicExecutionContext.computeCutLimit(magicCut: Boolean = false): CutLimit { - val cutLimit = if (magicCut) { - this.pathToRoot.firstOrNull() - } else { - this.pathToRoot.firstOrNull { it.procedure?.extractSignature() !in transparentToCut } - } + val cutLimit = + if (magicCut) { + this.pathToRoot.firstOrNull() + } else { + this.pathToRoot.firstOrNull { it.procedure?.extractSignature() !in transparentToCut } + } return if (cutLimit == null) { CutLimit.None } else { @@ -105,7 +112,10 @@ data class StateRuleSelection(override val context: ClassicExecutionContext) : A } } - private fun cutCanBeSkipped(cutLimit: CutLimit, executionContext: ClassicExecutionContext): Boolean = + private fun cutCanBeSkipped( + cutLimit: CutLimit, + executionContext: ClassicExecutionContext, + ): Boolean = cutLimit.isNone || cutLimit.depthToCut > executionContext.depth || cutLimit.depthToCut == executionContext.depth && @@ -120,9 +130,10 @@ data class StateRuleSelection(override val context: ClassicExecutionContext) : A this } else -> { - val cutCandidates = pathToRoot.filter { - it.executionContext!!.procedure == cutLimit.procedure - } + val cutCandidates = + pathToRoot.filter { + it.executionContext!!.procedure == cutLimit.procedure + } if (cutCandidates.any()) { cutCandidates.firstOrNull { it.executionContext!!.depth <= cutLimit.depthToCut @@ -134,11 +145,13 @@ data class StateRuleSelection(override val context: ClassicExecutionContext) : A } private val ClassicExecutionContext.isTailRecursive: Boolean - get() = goals.next.isOver && flags[LastCallOptimization] == ON && currentGoal!!.let { currentGoal -> - currentGoal.asStruct()?.extractSignature()?.let { - it == procedure?.extractSignature() && it != catchSignature - } ?: false - } + get() = + goals.next.isOver && flags[LastCallOptimization] == ON && + currentGoal!!.let { currentGoal -> + currentGoal.asStruct()?.extractSignature()?.let { + it == procedure?.extractSignature() && it != catchSignature + } ?: false + } override fun computeNext(): State { val currentGoal = context.currentGoal!! @@ -148,54 +161,56 @@ data class StateRuleSelection(override val context: ClassicExecutionContext) : A InstantiationError.forGoal( context = context, procedure = context.procedure!!.extractSignature(), - variable = currentGoal.castToVar() - ) + variable = currentGoal.castToVar(), + ), ) } - currentGoal.isStruct -> with(context) { - val currentGoalStruct = currentGoal.castToStruct() - val ruleSources = sequenceOf(libraries.asTheory(unificator), staticKb, dynamicKb) - - when { - currentGoalStruct.isTruth -> { - if (currentGoalStruct.isTrue) { - ignoreState - } else { - failureState + currentGoal.isStruct -> + with(context) { + val currentGoalStruct = currentGoal.castToStruct() + val ruleSources = sequenceOf(libraries.asTheory(unificator), staticKb, dynamicKb) + + when { + currentGoalStruct.isTruth -> { + if (currentGoalStruct.isTrue) { + ignoreState + } else { + failureState + } } - } - currentGoalStruct.isCut() -> { - val cutLimit = computeCutLimit(currentGoalStruct is MagicCut) - ignoreState.let { - it.copy( - context = it.context.copy( - choicePoints = it.context.choicePoints.performCut(cutLimit) + currentGoalStruct.isCut() -> { + val cutLimit = computeCutLimit(currentGoalStruct is MagicCut) + ignoreState.let { + it.copy( + context = + it.context.copy( + choicePoints = it.context.choicePoints.performCut(cutLimit), + ), ) - ) + } } - } - ruleSources.any { currentGoalStruct in it } -> { - val rules = ruleSources.flatMap { it.selectClauses(currentGoalStruct) }.cursor() - if (context.isTailRecursive) { - StateRuleExecution(context.replaceWithChildAppendingRulesAndChoicePoints(rules)) - } else { - StateRuleExecution(context.createChildAppendingRulesAndChoicePoints(rules)) + ruleSources.any { currentGoalStruct in it } -> { + val rules = ruleSources.flatMap { it.selectClauses(currentGoalStruct) }.cursor() + if (context.isTailRecursive) { + StateRuleExecution(context.replaceWithChildAppendingRulesAndChoicePoints(rules)) + } else { + StateRuleExecution(context.createChildAppendingRulesAndChoicePoints(rules)) + } } - } - else -> missingProcedure(ruleSources, currentGoalStruct.extractSignature()) + else -> missingProcedure(ruleSources, currentGoalStruct.extractSignature()) + } } - } else -> { exceptionalState( TypeError.forGoal( context = context, procedure = context.procedure!!.extractSignature(), expectedType = TypeError.Expected.CALLABLE, - culprit = currentGoal - ) + culprit = currentGoal, + ), ) } } diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/Utils.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/Utils.kt index 466c2bff2..45b4130f9 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/Utils.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/fsm/Utils.kt @@ -16,11 +16,13 @@ import it.unibo.tuprolog.utils.Cursor import it.unibo.tuprolog.utils.cursor import kotlin.jvm.JvmName -fun Sequence.toRulesCursor(): Cursor = - ensureRules().cursor() +fun Sequence.toRulesCursor(): Cursor = ensureRules().cursor() fun Sequence.ensureRules(): Sequence = - map { require(it.isRule); it.castToRule() } + map { + require(it.isRule) + it.castToRule() + } fun Term.unfoldGoals(): Sequence = when { @@ -45,7 +47,7 @@ fun ClassicExecutionContext.createChild(inferProcedureFromGoals: Boolean = true) parent = this, depth = depth + 1, step = step + 1, - relevantVariables = emptySet() + relevantVariables = emptySet(), ) } @@ -56,35 +58,37 @@ fun ClassicExecutionContext.replaceWithChild(inferProcedureFromGoals: Boolean = goals = currentGoal.toGoals(), procedure = if (inferProcedureFromGoals) currentGoal else procedure, depth = depth + 1, - step = step + 1 + step = step + 1, ) } fun ClassicExecutionContext.appendRulesAndChoicePoints(rules: Cursor): ClassicExecutionContext { - val newChoicePointContext = if (rules.hasNext) { - choicePoints.appendRules(rules.next, this) - } else { - choicePoints.appendRules(Cursor.empty(), this) - } + val newChoicePointContext = + if (rules.hasNext) { + choicePoints.appendRules(rules.next, this) + } else { + choicePoints.appendRules(Cursor.empty(), this) + } return copy(rules = rules, choicePoints = newChoicePointContext) } fun ClassicExecutionContext.appendPrimitivesAndChoicePoints( - primitiveExecutions: Cursor + primitiveExecutions: Cursor, ): ClassicExecutionContext { - val newChoicePointContext = if (primitiveExecutions.hasNext) { - choicePoints.appendPrimitives(primitiveExecutions.next, this) - } else { - choicePoints.appendPrimitives(Cursor.empty(), this) - } + val newChoicePointContext = + if (primitiveExecutions.hasNext) { + choicePoints.appendPrimitives(primitiveExecutions.next, this) + } else { + choicePoints.appendPrimitives(Cursor.empty(), this) + } return copy(primitives = primitiveExecutions, choicePoints = newChoicePointContext) } fun ClassicExecutionContext.createChildAppendingRulesAndChoicePoints( rules: Cursor, - inferProcedureFromGoals: Boolean = true + inferProcedureFromGoals: Boolean = true, ): ClassicExecutionContext { val tempExecutionContext = createChild(inferProcedureFromGoals) return tempExecutionContext.appendRulesAndChoicePoints(rules) @@ -92,7 +96,7 @@ fun ClassicExecutionContext.createChildAppendingRulesAndChoicePoints( fun ClassicExecutionContext.replaceWithChildAppendingRulesAndChoicePoints( rules: Cursor, - inferProcedureFromGoals: Boolean = true + inferProcedureFromGoals: Boolean = true, ): ClassicExecutionContext { val tempExecutionContext = replaceWithChild(inferProcedureFromGoals) return tempExecutionContext.appendRulesAndChoicePoints(rules) @@ -100,7 +104,7 @@ fun ClassicExecutionContext.replaceWithChildAppendingRulesAndChoicePoints( fun ClassicExecutionContext.createChildAppendingPrimitivesAndChoicePoints( primitiveExecutions: Cursor, - inferProcedureFromGoals: Boolean = true + inferProcedureFromGoals: Boolean = true, ): ClassicExecutionContext { val tempExecutionContext = createChild(inferProcedureFromGoals) return tempExecutionContext.appendPrimitivesAndChoicePoints(primitiveExecutions) @@ -109,5 +113,5 @@ fun ClassicExecutionContext.createChildAppendingPrimitivesAndChoicePoints( fun ClassicExecutionContext.toRequest( goal: Struct, signature: Signature, - startTime: TimeInstant + startTime: TimeInstant, ) = Solve.Request(signature, goal.args, this, startTime) diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/impl/AbstractSolutionIterator.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/impl/AbstractSolutionIterator.kt index cc07a38b2..cc39cae95 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/impl/AbstractSolutionIterator.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/impl/AbstractSolutionIterator.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.classic.SolutionIterator import it.unibo.tuprolog.solve.classic.fsm.State internal abstract class AbstractSolutionIterator(state: State) : SolutionIterator { - final override var state: State = state private set @@ -23,5 +22,8 @@ internal abstract class AbstractSolutionIterator(state: State) : SolutionIterato return state.castToEndState().solution.cleanUp() } - protected abstract fun computeNextState(state: State, step: Long): State + protected abstract fun computeNextState( + state: State, + step: Long, + ): State } diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/impl/HijackableSolutionIterator.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/impl/HijackableSolutionIterator.kt index 9628f07b4..c9e89a13b 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/impl/HijackableSolutionIterator.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/impl/HijackableSolutionIterator.kt @@ -6,13 +6,22 @@ import it.unibo.tuprolog.solve.classic.fsm.State internal class HijackableSolutionIterator( state: State, private val hijackStateTransitionCallback: (State, State, Long) -> State, - private val onStateTransitionCallback: (State, State, Long) -> Unit + private val onStateTransitionCallback: (State, State, Long) -> Unit, ) : AbstractSolutionIterator(state), MutableSolutionIterator { - override fun computeNextState(state: State, step: Long): State = hijackStateTransition(state, state.next(), step) + override fun computeNextState( + state: State, + step: Long, + ): State = hijackStateTransition(state, state.next(), step) - override fun hijackStateTransition(source: State, destination: State, index: Long): State = - hijackStateTransitionCallback(source, destination, index) + override fun hijackStateTransition( + source: State, + destination: State, + index: Long, + ): State = hijackStateTransitionCallback(source, destination, index) - override fun onStateTransition(source: State, destination: State, index: Long) = - onStateTransitionCallback(source, destination, index) + override fun onStateTransition( + source: State, + destination: State, + index: Long, + ) = onStateTransitionCallback(source, destination, index) } diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/impl/SimpleSolutionIterator.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/impl/SimpleSolutionIterator.kt index 843619e23..81c45334a 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/impl/SimpleSolutionIterator.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/impl/SimpleSolutionIterator.kt @@ -4,10 +4,16 @@ import it.unibo.tuprolog.solve.classic.fsm.State internal class SimpleSolutionIterator( state: State, - private val onStateTransitionCallback: (State, State, Long) -> Unit + private val onStateTransitionCallback: (State, State, Long) -> Unit, ) : AbstractSolutionIterator(state) { - override fun computeNextState(state: State, step: Long): State = state.next() + override fun computeNextState( + state: State, + step: Long, + ): State = state.next() - override fun onStateTransition(source: State, destination: State, index: Long) = - onStateTransitionCallback(source, destination, index) + override fun onStateTransition( + source: State, + destination: State, + index: Long, + ) = onStateTransitionCallback(source, destination, index) } diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/stdlib/DefaultBuiltins.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/stdlib/DefaultBuiltins.kt index 7744e7964..299c072d4 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/stdlib/DefaultBuiltins.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/stdlib/DefaultBuiltins.kt @@ -12,19 +12,20 @@ import it.unibo.tuprolog.solve.rule.RuleWrapper import it.unibo.tuprolog.solve.stdlib.CommonBuiltins object DefaultBuiltins : ExtensionLibrary(CommonBuiltins) { - override val additionalPrimitives: Iterable> - get() = listOf( - Throw - ) + get() = + listOf( + Throw, + ) override val additionalRules: Iterable> - get() = listOf( - Catch, - Call, - Comma, - Cut, - NegationAsFailure.Fail, - NegationAsFailure.Success - ) + get() = + listOf( + Catch, + Call, + Comma, + Cut, + NegationAsFailure.Fail, + NegationAsFailure.Success, + ) } diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/stdlib/primitive/Throw.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/stdlib/primitive/Throw.kt index 8389f0191..fab3d5d33 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/stdlib/primitive/Throw.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/stdlib/primitive/Throw.kt @@ -10,13 +10,16 @@ import it.unibo.tuprolog.solve.primitive.Solve import it.unibo.tuprolog.solve.primitive.UnaryPredicate object Throw : UnaryPredicate("throw") { - private fun handleError(context: ExecutionContext, error: Term): ResolutionException = + private fun handleError( + context: ExecutionContext, + error: Term, + ): ResolutionException = when { error is Struct && error.functor == "error" && error.arity in 1..2 -> { LogicError.of( context = context, type = error[0] as Struct, - extraData = if (error.arity > 1) error[1] else null + extraData = if (error.arity > 1) error[1] else null, ) } else -> MessageError.of(error, context) @@ -25,7 +28,7 @@ object Throw : UnaryPredicate("throw") { override fun Solve.Request.computeAll(first: Term): Sequence { return sequenceOf( ensuringAllArgumentsAreInstantiated() - .replyException(handleError(context, arguments[0])) + .replyException(handleError(context, arguments[0])), ) } } diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/stdlib/rule/Call.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/stdlib/rule/Call.kt index fe4e00b14..4c6c82870 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/stdlib/rule/Call.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/stdlib/rule/Call.kt @@ -12,8 +12,9 @@ object Call : RuleWrapper("call", 1) { get() = ktListOf(varOf("G")) override val Scope.body: Term - get() = tupleOf( - structOf(EnsureExecutable.functor, varOf("G")), - varOf("G") - ) + get() = + tupleOf( + structOf(EnsureExecutable.functor, varOf("G")), + varOf("G"), + ) } diff --git a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/stdlib/rule/NegationAsFailure.kt b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/stdlib/rule/NegationAsFailure.kt index b7a28cf2f..dcb1ea9d0 100644 --- a/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/stdlib/rule/NegationAsFailure.kt +++ b/solve-classic/src/commonMain/kotlin/it/unibo/tuprolog/solve/classic/stdlib/rule/NegationAsFailure.kt @@ -9,22 +9,23 @@ import it.unibo.tuprolog.solve.stdlib.primitive.EnsureExecutable import kotlin.collections.List as KtList sealed class NegationAsFailure : RuleWrapper(FUNCTOR, ARITY) { - override val Scope.head: KtList - get() = ktListOf( - varOf("X") - ) + get() = + ktListOf( + varOf("X"), + ) abstract override val Scope.body: Term object Fail : NegationAsFailure() { override val Scope.body: Term - get() = tupleOf( - structOf(EnsureExecutable.functor, varOf("X")), - structOf(Call.functor, varOf("X")), - MagicCut, - truthOf(false) - ) + get() = + tupleOf( + structOf(EnsureExecutable.functor, varOf("X")), + structOf(Call.functor, varOf("X")), + MagicCut, + truthOf(false), + ) } object Success : NegationAsFailure() { diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveClassicTest.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveClassicTest.kt index 9b6614860..6dfc28f8a 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveClassicTest.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveClassicTest.kt @@ -4,8 +4,9 @@ import kotlin.jvm.JvmField object SolveClassicTest { @JvmField - val expectations = Expectations( - prologShouldWork = true, - classicShouldWork = true - ) + val expectations = + Expectations( + prologShouldWork = true, + classicShouldWork = true, + ) } diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestClassicStaticFactory.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestClassicStaticFactory.kt index cdd7c1f29..d1ecc90e2 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestClassicStaticFactory.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestClassicStaticFactory.kt @@ -3,9 +3,10 @@ package it.unibo.tuprolog.solve import kotlin.test.Test class TestClassicStaticFactory : TestStaticFactory { - private val prototype = TestStaticFactory.prototype( - SolveClassicTest.expectations - ) + private val prototype = + TestStaticFactory.prototype( + SolveClassicTest.expectations, + ) @Test override fun testStaticSolverFactoryForClassic() { diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicAnd.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicAnd.kt index 77acef0f4..988b97cb4 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicAnd.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicAnd.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.TestAnd import kotlin.test.Test class TestClassicAnd : TestAnd, SolverFactory by ClassicSolverFactory { - private val prototype = TestAnd.prototype(this) @Test diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicArg.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicArg.kt index 5b9645d2a..1bc71f548 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicArg.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicArg.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.TestArg import kotlin.test.Test class TestClassicArg : TestArg, SolverFactory by ClassicSolverFactory { - private val prototype = TestArg.prototype(this) @Test diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicAtom.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicAtom.kt index 32595b5b6..7c5389a4a 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicAtom.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicAtom.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.TestAtom import kotlin.test.Test class TestClassicAtom : TestAtom, SolverFactory by ClassicSolverFactory { - private val prototype = TestAtom.prototype(this) @Test diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicAtomic.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicAtomic.kt index 0ec1cc31b..bc31e2159 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicAtomic.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicAtomic.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.TestAtomic import kotlin.test.Test class TestClassicAtomic : TestAtomic, SolverFactory by ClassicSolverFactory { - private val prototype = TestAtomic.prototype(this) @Test diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicCustomData.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicCustomData.kt index bcb20c4af..ae2071083 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicCustomData.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicCustomData.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.TestCustomData import kotlin.test.Test class TestClassicCustomData : TestCustomData, SolverFactory by ClassicSolverFactory { - val prototype = TestCustomData.prototype(this) @Test diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicCut.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicCut.kt index 66c787dbb..0917f2d90 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicCut.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicCut.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.TestCut import kotlin.test.Test class TestClassicCut : TestCut, SolverFactory by ClassicSolverFactory { - private val prototype = TestCut.prototype(this) @Test diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicDirectives.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicDirectives.kt index c26aa8118..2bdfb2921 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicDirectives.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicDirectives.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.TestDirectives import kotlin.test.Test class TestClassicDirectives : TestDirectives, SolverFactory by ClassicSolverFactory { - private val prototype = TestDirectives.prototype(this) @Test diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicFindAll.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicFindAll.kt index 9dbeb1b8e..cdd77fa22 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicFindAll.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicFindAll.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.TestFindAll import kotlin.test.Test class TestClassicFindAll : TestFindAll, SolverFactory by ClassicSolverFactory { - private val prototype = TestFindAll.prototype(this, Signature("ensure_executable", 1)) override val errorSignature: Signature diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicFlags.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicFlags.kt index acf2c424c..35c5fa851 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicFlags.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicFlags.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.TestFlags import kotlin.test.Test class TestClassicFlags : TestFlags, SolverFactory by ClassicSolverFactory { - private val prototype = TestFlags.prototype(this) @Test diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicInteger.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicInteger.kt index df0ff7cbb..9291c2e72 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicInteger.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicInteger.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.TestInteger import kotlin.test.Test class TestClassicInteger : TestInteger, SolverFactory by ClassicSolverFactory { - private val prototype = TestInteger.prototype(this) @Test diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicNonVar.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicNonVar.kt index bf45e45a6..f2fce0638 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicNonVar.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicNonVar.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.TestNonVar import kotlin.test.Test class TestClassicNonVar : TestNonVar, SolverFactory by ClassicSolverFactory { - private val prototype = TestNonVar.prototype(this) @Test diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicNotUnify.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicNotUnify.kt index 75dcf13cb..629b54828 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicNotUnify.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicNotUnify.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.TestNotUnify import kotlin.test.Test class TestClassicNotUnify : TestNotUnify, SolverFactory by ClassicSolverFactory { - private val prototype = TestNotUnify.prototype(this) @Test diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicNumber.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicNumber.kt index 8a747329e..f3df8f226 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicNumber.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicNumber.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.TestNumber import kotlin.test.Test class TestClassicNumber : TestNumber, SolverFactory by ClassicSolverFactory { - private val prototype = TestNumber.prototype(this) @Test diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicOr.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicOr.kt index 1ecff60e8..51d36ce18 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicOr.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicOr.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.TestOr import kotlin.test.Test class TestClassicOr : TestOr, SolverFactory by ClassicSolverFactory { - private val prototype = TestOr.prototype(this) @Test diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicSetOf.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicSetOf.kt index 482a335d6..55f6a771e 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicSetOf.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicSetOf.kt @@ -18,8 +18,8 @@ class TestClassicSetOf : TestSetOf, SolverFactory by ClassicSolverFactory { } @Test - override fun testSetOfNoSorted() { - prototype.testSetOfNoSorted() + override fun testSetOfSorted() { + prototype.testSetOfSorted() } @Test diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicSolutionPresentation.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicSolutionPresentation.kt index 5abde4578..4a919e155 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicSolutionPresentation.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicSolutionPresentation.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.TestSolutionPresentation import kotlin.test.Test class TestClassicSolutionPresentation : TestSolutionPresentation, SolverFactory by ClassicSolverFactory { - val prototype = TestSolutionPresentation.prototype(this) @Test diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicSolver.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicSolver.kt index b78665588..8e20db898 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicSolver.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicSolver.kt @@ -6,10 +6,10 @@ import it.unibo.tuprolog.solve.TestSolver import kotlin.test.Test class TestClassicSolver : TestSolver, SolverFactory by ClassicSolverFactory { - - private val prototype = Signature("ensure_executable", 1).let { - TestSolver.prototype(this, it, it, it) - } + private val prototype = + Signature("ensure_executable", 1).let { + TestSolver.prototype(this, it, it, it) + } override val callErrorSignature: Signature get() = prototype.callErrorSignature diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicSolverConstruction.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicSolverConstruction.kt index 7f0a19c88..c2e9595ed 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicSolverConstruction.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicSolverConstruction.kt @@ -8,7 +8,6 @@ import kotlin.test.Test class TestClassicSolverConstruction : TestSolverConstruction, SolverFactory by ClassicSolverFactory { - private val prototype = TestSolverConstruction.prototype(this, DefaultBuiltins) @Test diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicSubstitutions.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicSubstitutions.kt index 52e7004b7..75e49a446 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicSubstitutions.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicSubstitutions.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.TestSubstitutions import kotlin.test.Test class TestClassicSubstitutions : TestSubstitutions, SolverFactory by ClassicSolverFactory { - private val prototype = TestSubstitutions.prototype(this) @Test diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicTerm.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicTerm.kt index 930329395..5685bfffe 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicTerm.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicTerm.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.TestTerm import kotlin.test.Test class TestClassicTerm : TestTerm, SolverFactory by ClassicSolverFactory { - private val prototype = TestTerm.prototype(this) @Test diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicTimeout.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicTimeout.kt index 75547dea3..289f0c770 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicTimeout.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicTimeout.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.TestTimeout import kotlin.test.Test class TestClassicTimeout : TestTimeout, SolverFactory by ClassicSolverFactory { - private val prototype = TestTimeout.prototype(this) @Test diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicUnify.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicUnify.kt index 4fc7f56f1..1d479bfb7 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicUnify.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestClassicUnify.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.TestUnify import kotlin.test.Test class TestClassicUnify : TestUnify, SolverFactory by ClassicSolverFactory { - private val prototype = TestUnify.prototype(this) @Test diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestStateMachinePreservesUnificator.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestStateMachinePreservesUnificator.kt index fb434cc8d..97acd9c8d 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestStateMachinePreservesUnificator.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestStateMachinePreservesUnificator.kt @@ -23,27 +23,29 @@ class TestStateMachinePreservesUnificator { private class DebuggableClassicSolver(staticKb: Theory) : AbstractClassicSolver( unificator = CustomUnificator, staticKb = staticKb, - libraries = Runtime.of(DefaultBuiltins) + libraries = Runtime.of(DefaultBuiltins), ) { override fun solutionIterator( initialState: State, - onStateTransition: (State, State, Long) -> Unit - ): SolutionIterator = SolutionIterator.of(initialState) { src, dst, i -> - println(src) - if (dst.isEndState && dst.context.choicePoints == null) { - println(dst) + onStateTransition: (State, State, Long) -> Unit, + ): SolutionIterator = + SolutionIterator.of(initialState) { src, dst, i -> + println(src) + if (dst.isEndState && dst.context.choicePoints == null) { + println(dst) + } + for (state in listOf(src, dst)) { + assertSame( + expected = state.context.unificator, + actual = CustomUnificator, + message = + "Unificator is unexpectedly reset after $i steps while transitioning from\n" + + " source=$src\n" + + " destination=$dst", + ) + } + onStateTransition(src, dst, i) } - for (state in listOf(src, dst)) { - assertSame( - expected = state.context.unificator, - actual = CustomUnificator, - message = "Unificator is unexpectedly reset after $i steps while transitioning from\n" + - " source=$src\n" + - " destination=$dst" - ) - } - onStateTransition(src, dst, i) - } override fun copy( unificator: Unificator, @@ -54,37 +56,38 @@ class TestStateMachinePreservesUnificator { stdIn: InputChannel, stdOut: OutputChannel, stdErr: OutputChannel, - warnings: OutputChannel + warnings: OutputChannel, ): AbstractClassicSolver = TODO() override fun clone(): AbstractClassicSolver = TODO() } - private val theoryInvolvingAllStates = logicProgramming { - theoryOf( - rule { - "countUpTo"(X, X, Z).impliedBy( - Z `is` (X + Y) - ) - }, - rule { - "countUpTo"(X, Y, Z).impliedBy( - write(X), - nl, - X lowerThan Y, - W `is` (X + 1), - "countUpTo"(W, Y, Z) - ) - }, - rule { - "count"(X).impliedBy( - X greaterThan 0, - catch("countUpTo"(0, X, `_`), E, write(E) and nl and fail) - ) - }, - rule { "count"(X).impliedBy(write(X), nl) } - ) - } + private val theoryInvolvingAllStates = + logicProgramming { + theoryOf( + rule { + "countUpTo"(X, X, Z).impliedBy( + Z `is` (X + Y), + ) + }, + rule { + "countUpTo"(X, Y, Z).impliedBy( + write(X), + nl, + X lowerThan Y, + W `is` (X + 1), + "countUpTo"(W, Y, Z), + ) + }, + rule { + "count"(X).impliedBy( + X greaterThan 0, + catch("countUpTo"(0, X, `_`), E, write(E) and nl and fail), + ) + }, + rule { "count"(X).impliedBy(write(X), nl) }, + ) + } @Test fun testUnificatorIsPreserved() { @@ -93,7 +96,7 @@ class TestStateMachinePreservesUnificator { val goal = Struct.of("count", Integer.of(4)) assertEquals( listOf(goal.yes()), - solver.solveList(goal) + solver.solveList(goal), ) } } diff --git a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestSubstitutionMerging.kt b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestSubstitutionMerging.kt index 1818da662..4ce849628 100644 --- a/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestSubstitutionMerging.kt +++ b/solve-classic/src/commonTest/kotlin/it/unibo/tuprolog/solve/classic/TestSubstitutionMerging.kt @@ -15,31 +15,38 @@ import it.unibo.tuprolog.solve.yes import kotlin.test.Test class TestSubstitutionMerging { - private val theory = logicProgramming { - theoryOf( - rule { "a"(X) impliedBy "b"(X) }, - rule { "b"(Y) impliedBy "c"(Y) }, - rule { "c"(Z) impliedBy "primitive"(Z) } - ) - } + private val theory = + logicProgramming { + theoryOf( + rule { "a"(X) impliedBy "b"(X) }, + rule { "b"(Y) impliedBy "c"(Y) }, + rule { "c"(Z) impliedBy "primitive"(Z) }, + ) + } - private val primitive = object : UnaryPredicate("primitive") { - override fun Solve.Request.computeAll(first: Term): Sequence = sequence { - val allVariables = context.substitution.let { it.keys.toSet() + it.values.filterIsInstance().toSet() } - for (x in allVariables.sortedBy { it.name }) { - yield(replySuccess(Substitution.unifier(x to Atom.of(x.name)))) - } + @Suppress("ktlint:standard:multiline-expression-wrapping") + private val primitive = + object : UnaryPredicate("primitive") { + override fun Solve.Request.computeAll(first: Term): Sequence = + sequence { + val allVariables = context.substitution.let { + it.keys.toSet() + it.values.filterIsInstance().toSet() + } + for (x in allVariables.sortedBy { it.name }) { + yield(replySuccess(Substitution.unifier(x to Atom.of(x.name)))) + } + } } - } @Test fun testSubstitutionsAreCorrectlyMergedAfterPrimitives() { logicProgramming { - val solver = ClassicSolverFactory.newBuilder() - .staticKb(theory) - .noBuiltins() - .runtime(libraryOf("test", primitive).toRuntime()) - .build() + val solver = + ClassicSolverFactory.newBuilder() + .staticKb(theory) + .noBuiltins() + .runtime(libraryOf("test", primitive).toRuntime()) + .build() val goal = "a"(A) @@ -49,9 +56,9 @@ class TestSubstitutionMerging { goal.yes(A to atomOf("A")), goal.yes(A to atomOf("X")), goal.yes(A to atomOf("Y")), - goal.yes(A to atomOf("Z")) + goal.yes(A to atomOf("Z")), ), - solutions + solutions, ) } } diff --git a/solve-concurrent/gradle.properties b/solve-concurrent/gradle.properties index 1fcdc3a90..3e2da8a8c 100644 --- a/solve-concurrent/gradle.properties +++ b/solve-concurrent/gradle.properties @@ -3,5 +3,5 @@ Kotlin coroutines projectLongName=2P-Kt, Solver-Concurrent Module jvmStackSize=512M jvmMaxHeapSize=2G -ktCompilerArgs=-opt-in=kotlin.RequiresOptIn +ktCompilerArgs=-opt-in=kotlin.RequiresOptIn;-Xexpect-actual-classes ktCompilerArgsJvm=-Xjvm-default=all \ No newline at end of file diff --git a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/AtomicInt.kt b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/AtomicInt.kt index bc690d07e..1be5f6a96 100644 --- a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/AtomicInt.kt +++ b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/AtomicInt.kt @@ -20,7 +20,6 @@ interface AtomicInt { fun decAndGet(delta: Int = 1): Int companion object { - @JsName("zero") @JvmStatic fun zero(): AtomicInt = atomicInt(0) diff --git a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/ConcurrentExecutionContext.kt b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/ConcurrentExecutionContext.kt index 51a82340d..296523302 100644 --- a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/ConcurrentExecutionContext.kt +++ b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/ConcurrentExecutionContext.kt @@ -46,7 +46,7 @@ data class ConcurrentExecutionContext( override val maxDuration: TimeDuration = TimeDuration.MAX_VALUE, val parent: ConcurrentExecutionContext? = null, val depth: Int = 0, - val step: Long = 0 + val step: Long = 0, ) : ExecutionContext { init { require((depth == 0 && parent == null) || (depth > 0 && parent != null)) @@ -59,13 +59,14 @@ data class ConcurrentExecutionContext( val isActivationRecord: Boolean get() = parent == null || depth - parent.depth >= 1 - val pathToRoot: Sequence = sequence { - var current: ConcurrentExecutionContext? = this@ConcurrentExecutionContext - while (current != null) { - yield(current) - current = current.parent + val pathToRoot: Sequence = + sequence { + var current: ConcurrentExecutionContext? = this@ConcurrentExecutionContext + while (current != null) { + yield(current) + current = current.parent + } } - } val currentGoal: Term? get() = if (goals.isOver) null else goals.current @@ -91,17 +92,18 @@ data class ConcurrentExecutionContext( staticKb: Theory, dynamicKb: Theory, inputChannels: InputStore, - outputChannels: OutputStore - ): ConcurrentSolver = ConcurrentSolverImpl( - unificator, - libraries, - flags, - staticKb, - dynamicKb, - inputChannels, - outputChannels, - trustKb = true - ) + outputChannels: OutputStore, + ): ConcurrentSolver = + ConcurrentSolverImpl( + unificator, + libraries, + flags, + staticKb, + dynamicKb, + inputChannels, + outputChannels, + trustKb = true, + ) override fun createMutableSolver( unificator: Unificator, @@ -110,16 +112,17 @@ data class ConcurrentExecutionContext( staticKb: Theory, dynamicKb: Theory, inputChannels: InputStore, - outputChannels: OutputStore - ): MutableSolver = MutableConcurrentSolver( - unificator, - libraries, - flags, - staticKb, - dynamicKb, - inputChannels, - outputChannels - ) + outputChannels: OutputStore, + ): MutableSolver = + MutableConcurrentSolver( + unificator, + libraries, + flags, + staticKb, + dynamicKb, + inputChannels, + outputChannels, + ) override fun update( unificator: Unificator, @@ -130,7 +133,7 @@ data class ConcurrentExecutionContext( operators: OperatorSet, inputChannels: InputStore, outputChannels: OutputStore, - customData: CustomDataStore + customData: CustomDataStore, ): ConcurrentExecutionContext { return copy( unificator = unificator, @@ -141,7 +144,7 @@ data class ConcurrentExecutionContext( operators = operators, inputChannels = inputChannels, outputChannels = outputChannels, - customData = customData + customData = customData, ) } diff --git a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/ConcurrentResolutionHandle.kt b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/ConcurrentResolutionHandle.kt index 0ec4b62b9..42bf60fe7 100644 --- a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/ConcurrentResolutionHandle.kt +++ b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/ConcurrentResolutionHandle.kt @@ -11,9 +11,8 @@ import kotlinx.coroutines.channels.SendChannel data class ConcurrentResolutionHandle( val solveOptions: SolveOptions, val solutionChannel: SendChannel, - val solutionCounter: AtomicInt = AtomicInt.zero() + val solutionCounter: AtomicInt = AtomicInt.zero(), ) { - @OptIn(ExperimentalCoroutinesApi::class) fun terminateResolution(resolutionScope: CoroutineScope) { if (!solutionChannel.isClosedForSend) { @@ -26,7 +25,7 @@ data class ConcurrentResolutionHandle( @OptIn(ExperimentalCoroutinesApi::class) suspend fun publishSolutionAndTerminateResolutionIfNeed( solution: Solution, - resolutionScope: CoroutineScope + resolutionScope: CoroutineScope, ): Boolean { if (solutionChannel.isClosedForSend) return false solutionChannel.send(solution) diff --git a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/ConcurrentSolver.kt b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/ConcurrentSolver.kt index 6d5c2170c..ad3d1053a 100644 --- a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/ConcurrentSolver.kt +++ b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/ConcurrentSolver.kt @@ -15,9 +15,11 @@ import kotlinx.coroutines.channels.ReceiveChannel import kotlin.js.JsName interface ConcurrentSolver : Solver { - @JsName("solveConcurrently") - fun solveConcurrently(goal: Struct, options: SolveOptions): ReceiveChannel + fun solveConcurrently( + goal: Struct, + options: SolveOptions, + ): ReceiveChannel override fun copy( unificator: Unificator, @@ -28,7 +30,7 @@ interface ConcurrentSolver : Solver { stdIn: InputChannel, stdOut: OutputChannel, stdErr: OutputChannel, - warnings: OutputChannel + warnings: OutputChannel, ): ConcurrentSolver override fun clone(): ConcurrentSolver diff --git a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/ConcurrentSolverFactory.kt b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/ConcurrentSolverFactory.kt index d41a7d4af..75cfe9d5c 100644 --- a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/ConcurrentSolverFactory.kt +++ b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/ConcurrentSolverFactory.kt @@ -26,7 +26,7 @@ object ConcurrentSolverFactory : SolverFactory { staticKb: Theory, dynamicKb: Theory, inputs: InputStore, - outputs: OutputStore + outputs: OutputStore, ): Solver = ConcurrentSolverImpl(unificator, libraries, flags, staticKb, dynamicKb, inputs, outputs) override fun solverOf( @@ -38,7 +38,7 @@ object ConcurrentSolverFactory : SolverFactory { stdIn: InputChannel, stdOut: OutputChannel, stdErr: OutputChannel, - warnings: OutputChannel + warnings: OutputChannel, ): Solver = ConcurrentSolverImpl(unificator, libraries, flags, staticKb, dynamicKb, stdIn, stdOut, stdErr, warnings) override fun mutableSolverOf( @@ -50,8 +50,9 @@ object ConcurrentSolverFactory : SolverFactory { stdIn: InputChannel, stdOut: OutputChannel, stdErr: OutputChannel, - warnings: OutputChannel - ): MutableSolver = MutableConcurrentSolver(unificator, libraries, flags, staticKb, dynamicKb, stdIn, stdOut, stdErr, warnings) + warnings: OutputChannel, + ): MutableSolver = + MutableConcurrentSolver(unificator, libraries, flags, staticKb, dynamicKb, stdIn, stdOut, stdErr, warnings) override fun mutableSolverOf( unificator: Unificator, @@ -60,6 +61,6 @@ object ConcurrentSolverFactory : SolverFactory { staticKb: Theory, dynamicKb: Theory, inputs: InputStore, - outputs: OutputStore + outputs: OutputStore, ): MutableSolver = MutableConcurrentSolver(unificator, libraries, flags, staticKb, dynamicKb, inputs, outputs) } diff --git a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/ConcurrentSolverImpl.kt b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/ConcurrentSolverImpl.kt index 5fb1a50e9..e235442f2 100644 --- a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/ConcurrentSolverImpl.kt +++ b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/ConcurrentSolverImpl.kt @@ -28,7 +28,7 @@ import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.yield -import kotlin.jvm.Volatile +import kotlin.concurrent.Volatile import kotlinx.coroutines.channels.Channel as KtChannel internal open class ConcurrentSolverImpl( @@ -39,18 +39,17 @@ internal open class ConcurrentSolverImpl( initialDynamicKb: Theory = MutableTheory.empty(unificator), inputChannels: InputStore = InputStore.fromStandard(), outputChannels: OutputStore = OutputStore.fromStandard(), - trustKb: Boolean = false + trustKb: Boolean = false, ) : ConcurrentSolver, AbstractSolver( - unificator, - libraries, - flags, - initialStaticKb, - initialDynamicKb, - inputChannels, - outputChannels, - trustKb -) { - + unificator, + libraries, + flags, + initialStaticKb, + initialDynamicKb, + inputChannels, + outputChannels, + trustKb, + ) { constructor( unificator: Unificator, libraries: Runtime = Runtime.empty(), @@ -61,7 +60,7 @@ internal open class ConcurrentSolverImpl( stdOut: OutputChannel = OutputChannel.stdOut(), stdErr: OutputChannel = OutputChannel.stdErr(), warnings: OutputChannel = OutputChannel.warn(), - trustKb: Boolean = false + trustKb: Boolean = false, ) : this( unificator, libraries, @@ -70,13 +69,16 @@ internal open class ConcurrentSolverImpl( dynamicKb, InputStore.fromStandard(stdIn), OutputStore.fromStandard(stdOut, stdErr, warnings), - trustKb + trustKb, ) @Volatile override lateinit var currentContext: ConcurrentExecutionContext - private fun CoroutineScope.handleAsyncStateTransition(state: State, handle: ConcurrentResolutionHandle): Job = + private fun CoroutineScope.handleAsyncStateTransition( + state: State, + handle: ConcurrentResolutionHandle, + ): Job = launch { if (state is EndState) { handle.publishSolutionAndTerminateResolutionIfNeed(state.solution, this) @@ -88,47 +90,58 @@ internal open class ConcurrentSolverImpl( } } - private fun Sequence.ensureAtMostOneNegative(): Sequence = sequence { - var lastNegative: Solution.No? = null - val i = iterator() - while (i.hasNext()) { - when (val it = i.next()) { - is Solution.No -> { - lastNegative = it - } - else -> { - yield(it) + private fun Sequence.ensureAtMostOneNegative(): Sequence = + sequence { + var lastNegative: Solution.No? = null + val i = iterator() + while (i.hasNext()) { + when (val it = i.next()) { + is Solution.No -> { + lastNegative = it + } + else -> { + yield(it) + } } } + lastNegative?.let { yield(it) } } - lastNegative?.let { yield(it) } - } - private suspend fun startAsyncResolution(initialState: State, handle: ConcurrentResolutionHandle) = coroutineScope { + private suspend fun startAsyncResolution( + initialState: State, + handle: ConcurrentResolutionHandle, + ) = coroutineScope { handleAsyncStateTransition(initialState, handle).join() handle.closeSolutionChannelWithNoSolutionIfNeeded(initialState.context.query) } - private fun initialState(goal: Struct, options: SolveOptions): State { - currentContext = ConcurrentExecutionContext( - goals = goal.toGoals(), - step = 1, - query = goal, - libraries = libraries, - flags = flags, - staticKb = staticKb.toImmutableTheory(), - dynamicKb = dynamicKb.toMutableTheory(), - operators = operators, - inputChannels = inputChannels, - outputChannels = outputChannels, - customData = currentContext.customData, - maxDuration = options.timeout, - startTime = currentTimeInstant() - ) + private fun initialState( + goal: Struct, + options: SolveOptions, + ): State { + currentContext = + ConcurrentExecutionContext( + goals = goal.toGoals(), + step = 1, + query = goal, + libraries = libraries, + flags = flags, + staticKb = staticKb.toImmutableTheory(), + dynamicKb = dynamicKb.toMutableTheory(), + operators = operators, + inputChannels = inputChannels, + outputChannels = outputChannels, + customData = currentContext.customData, + maxDuration = options.timeout, + startTime = currentTimeInstant(), + ) return StateGoalSelection(currentContext) } - override fun solveConcurrently(goal: Struct, options: SolveOptions): ReceiveChannel { + override fun solveConcurrently( + goal: Struct, + options: SolveOptions, + ): ReceiveChannel { val channel = KtChannel(KtChannel.UNLIMITED) val initialState = initialState(goal, options) val handle = ConcurrentResolutionHandle(options, channel) @@ -139,7 +152,10 @@ internal open class ConcurrentSolverImpl( return channel } - override fun solveImpl(goal: Struct, options: SolveOptions): Sequence { + override fun solveImpl( + goal: Struct, + options: SolveOptions, + ): Sequence { return solveConcurrently(goal, options).toSequence().ensureAtMostOneNegative() } @@ -152,7 +168,7 @@ internal open class ConcurrentSolverImpl( stdIn: InputChannel, stdOut: OutputChannel, stdErr: OutputChannel, - warnings: OutputChannel + warnings: OutputChannel, ) = ConcurrentSolverImpl(unificator, libraries, flags, staticKb, dynamicKb, stdIn, stdOut, stdErr, warnings) override fun clone(): ConcurrentSolverImpl = copy() @@ -166,16 +182,17 @@ internal open class ConcurrentSolverImpl( operators: OperatorSet, inputChannels: InputStore, outputChannels: OutputStore, - trustKb: Boolean - ): ConcurrentExecutionContext = ConcurrentExecutionContext( - unificator = unificator, - libraries = libraries, - flags = flags, - staticKb = if (trustKb) staticKb.toImmutableTheory() else Theory.empty(unificator), - dynamicKb = if (trustKb) dynamicKb.toMutableTheory() else MutableTheory.empty(unificator), - operators = getAllOperators(libraries).toOperatorSet(), - inputChannels = inputChannels, - outputChannels = outputChannels, - startTime = 0L - ) + trustKb: Boolean, + ): ConcurrentExecutionContext = + ConcurrentExecutionContext( + unificator = unificator, + libraries = libraries, + flags = flags, + staticKb = if (trustKb) staticKb.toImmutableTheory() else Theory.empty(unificator), + dynamicKb = if (trustKb) dynamicKb.toMutableTheory() else MutableTheory.empty(unificator), + operators = getAllOperators(libraries).toOperatorSet(), + inputChannels = inputChannels, + outputChannels = outputChannels, + startTime = 0L, + ) } diff --git a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/MutableConcurrentSolver.kt b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/MutableConcurrentSolver.kt index d054c87a4..5f9246cc0 100644 --- a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/MutableConcurrentSolver.kt +++ b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/MutableConcurrentSolver.kt @@ -21,7 +21,6 @@ import it.unibo.tuprolog.theory.Theory import it.unibo.tuprolog.unify.Unificator internal class MutableConcurrentSolver : ConcurrentSolverImpl, MutableSolver { - constructor( unificator: Unificator = Unificator.default, libraries: Runtime = Runtime.empty(), @@ -30,7 +29,7 @@ internal class MutableConcurrentSolver : ConcurrentSolverImpl, MutableSolver { dynamicKb: Theory = MutableTheory.empty(unificator), inputChannels: InputStore = InputStore.fromStandard(), outputChannels: OutputStore = OutputStore.fromStandard(), - trustKb: Boolean = false + trustKb: Boolean = false, ) : super(unificator, libraries, flags, staticKb, dynamicKb, inputChannels, outputChannels, trustKb) constructor( @@ -43,7 +42,7 @@ internal class MutableConcurrentSolver : ConcurrentSolverImpl, MutableSolver { stdOut: OutputChannel = OutputChannel.stdOut(), stdErr: OutputChannel = OutputChannel.stdErr(), warnings: OutputChannel = OutputChannel.warn(), - trustKb: Boolean = false + trustKb: Boolean = false, ) : super(unificator, libraries, flags, staticKb, dynamicKb, stdIn, stdOut, stdErr, warnings, trustKb) override fun loadLibrary(library: Library) { @@ -51,7 +50,7 @@ internal class MutableConcurrentSolver : ConcurrentSolverImpl, MutableSolver { val newLibraries = libraries + library copy( libraries = newLibraries, - operators = operators + getAllOperators(newLibraries).toOperatorSet() + operators = operators + getAllOperators(newLibraries).toOperatorSet(), ) } } @@ -61,7 +60,7 @@ internal class MutableConcurrentSolver : ConcurrentSolverImpl, MutableSolver { val newLibraries = libraries + library copy( libraries = newLibraries, - operators = getAllOperators(newLibraries, staticKb, dynamicKb).toOperatorSet() + operators = getAllOperators(newLibraries, staticKb, dynamicKb).toOperatorSet(), ) } } @@ -70,7 +69,7 @@ internal class MutableConcurrentSolver : ConcurrentSolverImpl, MutableSolver { updateContext { copy( libraries = libraries, - operators = getAllOperators(libraries, staticKb, dynamicKb).toOperatorSet() + operators = getAllOperators(libraries, staticKb, dynamicKb).toOperatorSet(), ) } } @@ -78,7 +77,7 @@ internal class MutableConcurrentSolver : ConcurrentSolverImpl, MutableSolver { override fun loadStaticKb(theory: Theory) { initializeKb( staticKb = theory, - appendStatic = false + appendStatic = false, ) } @@ -90,7 +89,7 @@ internal class MutableConcurrentSolver : ConcurrentSolverImpl, MutableSolver { updateContext { copy( staticKb = Theory.empty(unificator), - operators = getAllOperators(libraries, dynamicKb).toOperatorSet() + operators = getAllOperators(libraries, dynamicKb).toOperatorSet(), ) } } @@ -98,7 +97,7 @@ internal class MutableConcurrentSolver : ConcurrentSolverImpl, MutableSolver { override fun loadDynamicKb(theory: Theory) { initializeKb( dynamicKb = theory, - appendDynamic = false + appendDynamic = false, ) } @@ -110,7 +109,7 @@ internal class MutableConcurrentSolver : ConcurrentSolverImpl, MutableSolver { updateContext { copy( dynamicKb = MutableTheory.empty(unificator), - operators = getAllOperators(libraries, staticKb).toOperatorSet() + operators = getAllOperators(libraries, staticKb).toOperatorSet(), ) } } @@ -119,7 +118,7 @@ internal class MutableConcurrentSolver : ConcurrentSolverImpl, MutableSolver { updateContext { copy( dynamicKb = dynamicKb.assertA(clause), - operators = operators + listOf(clause).getAllOperators().toOperatorSet() + operators = operators + listOf(clause).getAllOperators().toOperatorSet(), ) } } @@ -134,7 +133,7 @@ internal class MutableConcurrentSolver : ConcurrentSolverImpl, MutableSolver { updateContext { copy( dynamicKb = dynamicKb.assertZ(clause), - operators = operators + listOf(clause).getAllOperators().toOperatorSet() + operators = operators + listOf(clause).getAllOperators().toOperatorSet(), ) } } @@ -150,7 +149,7 @@ internal class MutableConcurrentSolver : ConcurrentSolverImpl, MutableSolver { updateContext { copy( dynamicKb = result.theory.toMutableTheory(), - operators = operators - listOf(clause).getAllOperators().toOperatorSet() + operators = operators - listOf(clause).getAllOperators().toOperatorSet(), ) } return result @@ -169,7 +168,7 @@ internal class MutableConcurrentSolver : ConcurrentSolverImpl, MutableSolver { updateContext { copy( dynamicKb = result.theory.toMutableTheory(), - operators = operators - result.theory.getAllOperators().toOperatorSet() + operators = operators - result.theory.getAllOperators().toOperatorSet(), ) } return result @@ -183,7 +182,10 @@ internal class MutableConcurrentSolver : ConcurrentSolverImpl, MutableSolver { return result } - override fun setFlag(name: String, value: Term) { + override fun setFlag( + name: String, + value: Term, + ) { updateContext { copy(flags = flags.set(name, value)) } @@ -234,7 +236,7 @@ internal class MutableConcurrentSolver : ConcurrentSolverImpl, MutableSolver { stdIn: InputChannel, stdOut: OutputChannel, stdErr: OutputChannel, - warnings: OutputChannel + warnings: OutputChannel, ) = MutableConcurrentSolver(unificator, libraries, flags, staticKb, dynamicKb, stdIn, stdOut, stdErr, warnings) override fun clone(): MutableConcurrentSolver = copy() diff --git a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/AbstractState.kt b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/AbstractState.kt index 369706fdf..c0f0c1d29 100644 --- a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/AbstractState.kt +++ b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/AbstractState.kt @@ -8,7 +8,6 @@ import it.unibo.tuprolog.solve.currentTimeInstant import it.unibo.tuprolog.solve.exception.TimeOutException abstract class AbstractState(override val context: ConcurrentExecutionContext) : State { - protected val executionTime: TimeInstant by lazy { currentTime() } @@ -22,10 +21,10 @@ abstract class AbstractState(override val context: ConcurrentExecutionContext) : StateHalt( TimeOutException( exceededDuration = context.maxDuration, - context = context + context = context, ), - context.copy(step = nextStep()) - ) + context.copy(step = nextStep()), + ), ) } else { computeNext() @@ -39,5 +38,7 @@ abstract class AbstractState(override val context: ConcurrentExecutionContext) : protected fun nextStep(): Long = context.step + 1 protected fun ConcurrentExecutionContext.skipThrow(): ExecutionContext = - pathToRoot.first { it.procedure?.functor != Throw.functor } + pathToRoot.first { + it.procedure?.functor != Throw.functor + } } diff --git a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/EndState.kt b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/EndState.kt index 0b90918fc..63d12e308 100644 --- a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/EndState.kt +++ b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/EndState.kt @@ -4,7 +4,6 @@ import it.unibo.tuprolog.solve.Solution import kotlin.js.JsName interface EndState : State { - override val isEndState: Boolean get() = true diff --git a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/State.kt b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/State.kt index b07812170..afae36917 100644 --- a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/State.kt +++ b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/State.kt @@ -4,7 +4,6 @@ import it.unibo.tuprolog.solve.concurrent.ConcurrentExecutionContext import kotlin.js.JsName interface State { - @JsName("isEndState") val isEndState: Boolean get() = false diff --git a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StateException.kt b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StateException.kt index aa3fcc313..e66e76b70 100644 --- a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StateException.kt +++ b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StateException.kt @@ -14,11 +14,9 @@ import it.unibo.tuprolog.utils.plus data class StateException( override val exception: ResolutionException, - override val context: ConcurrentExecutionContext + override val context: ConcurrentExecutionContext, ) : AbstractState(context), ExceptionalState { - - private fun Struct.isCatch(): Boolean = - arity == 3 && functor == Catch.functor + private fun Struct.isCatch(): Boolean = arity == 3 && functor == Catch.functor private fun LogicError.getExceptionContent(): Term { return when (this) { @@ -34,18 +32,24 @@ data class StateException( } private val finalState: EndState - get() = StateHalt( - exception.toPublicException(), - context.copy(step = nextStep()) - ) + get() = + StateHalt( + exception.toPublicException(), + context.copy(step = nextStep()), + ) private val handleExceptionInParentContext: StateException - get() = StateException( - exception, - context.parent!!.copy(step = nextStep()) - ) + get() = + StateException( + exception, + context.parent!!.copy(step = nextStep()), + ) - private fun handleStruct(unificator: Unificator, catchGoal: Struct, error: LogicError): State = + private fun handleStruct( + unificator: Unificator, + catchGoal: Struct, + error: LogicError, + ): State = when { catchGoal.isCatch() -> { val catcher = unificator.mgu(catchGoal[1], error.getExceptionContent()) @@ -55,27 +59,29 @@ data class StateException( else -> handleExceptionInParentContext } - private fun handleCatch(catchGoal: Struct, catcher: Substitution) = - when { - catcher.isSuccess -> { - val newSubstitution = - (context.substitution + catcher).filter(context.interestingVariables) - val subGoals = catchGoal[2][newSubstitution] - val newGoals = subGoals.toGoals() + context.goals.next + private fun handleCatch( + catchGoal: Struct, + catcher: Substitution, + ) = when { + catcher.isSuccess -> { + val newSubstitution = + (context.substitution + catcher).filter(context.interestingVariables) + val subGoals = catchGoal[2][newSubstitution] + val newGoals = subGoals.toGoals() + context.goals.next - StateGoalSelection( - context.copy( - goals = newGoals, - rule = null, - primitive = null, - substitution = newSubstitution.castToUnifier(), - step = nextStep() - ) - ) - } - context.isRoot -> finalState - else -> handleExceptionInParentContext + StateGoalSelection( + context.copy( + goals = newGoals, + rule = null, + primitive = null, + substitution = newSubstitution.castToUnifier(), + step = nextStep(), + ), + ) } + context.isRoot -> finalState + else -> handleExceptionInParentContext + } override fun computeNext(): Iterable { return listOf( @@ -89,10 +95,13 @@ data class StateException( } } else -> finalState - } + }, ) } override fun clone(context: ConcurrentExecutionContext): StateException = - copy(exception = exception, context = context) + copy( + exception = exception, + context = context, + ) } diff --git a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StateGoalSelection.kt b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StateGoalSelection.kt index 8510462a8..d127c3e05 100644 --- a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StateGoalSelection.kt +++ b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StateGoalSelection.kt @@ -4,13 +4,14 @@ import it.unibo.tuprolog.solve.Solution import it.unibo.tuprolog.solve.concurrent.ConcurrentExecutionContext data class StateGoalSelection(override val context: ConcurrentExecutionContext) : AbstractState(context) { + @Suppress("ktlint:standard:discouraged-comment-location") override fun computeNext(): Iterable { return listOf( if (context.goals.isOver) { if (context.isRoot) { StateEnd( Solution.yes(context.query, context.substitution), - context.copy(step = nextStep()) + context.copy(step = nextStep()), ) } else { StateGoalSelection( @@ -28,15 +29,15 @@ data class StateGoalSelection(override val context: ConcurrentExecutionContext) inputChannels = context.inputChannels, outputChannels = context.outputChannels, libraries = context.libraries, - customData = context.customData + customData = context.customData, ) - } + }, ) } } else { val goalsWithSubstitution = context.goals.map { it[context.substitution] } StatePrimitiveSelection(context.copy(goals = goalsWithSubstitution, step = nextStep())) - } + }, ) } diff --git a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StateHalt.kt b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StateHalt.kt index 38a5adab3..514f669fd 100644 --- a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StateHalt.kt +++ b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StateHalt.kt @@ -6,9 +6,8 @@ import it.unibo.tuprolog.solve.exception.ResolutionException data class StateHalt( override val exception: ResolutionException, - override val context: ConcurrentExecutionContext + override val context: ConcurrentExecutionContext, ) : AbstractState(context), ExceptionalState, EndState { - override val solution: Solution = Solution.halt(context.query, exception) override fun next(): Iterable = super.next() diff --git a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StatePrimitiveExecution.kt b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StatePrimitiveExecution.kt index 4c2d3645e..b54b5d9d8 100644 --- a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StatePrimitiveExecution.kt +++ b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StatePrimitiveExecution.kt @@ -8,16 +8,16 @@ import it.unibo.tuprolog.solve.exception.ResolutionException import it.unibo.tuprolog.utils.Cursor data class StatePrimitiveExecution(override val context: ConcurrentExecutionContext) : AbstractState(context) { - - private fun failureState(context: ConcurrentExecutionContext = this.context): EndState = StateEnd( - solution = Solution.no(context.query), - context = context.copy(step = nextStep()) - ) + private fun failureState(context: ConcurrentExecutionContext = this.context): EndState = + StateEnd( + solution = Solution.no(context.query), + context = context.copy(step = nextStep()), + ) private fun ConcurrentExecutionContext.copyFromCurrentPrimitive( goals: Cursor? = null, procedureFromAncestor: Int = 0, - substitution: Substitution? = null + substitution: Substitution? = null, ): ConcurrentExecutionContext { val ctx = primitive?.let { apply(it.sideEffects) } ?: this return ctx.copy( @@ -25,34 +25,38 @@ data class StatePrimitiveExecution(override val context: ConcurrentExecutionCont procedure = pathToRoot.drop(procedureFromAncestor).map { it.procedure }.first(), primitive = null, substitution = (substitution ?: this.substitution) as Substitution.Unifier, - step = nextStep() + step = nextStep(), ) } - override fun computeNext(): Iterable = listOf( - try { - context.primitive?.solution?.whenIs( - yes = { - StateGoalSelection( - context.copyFromCurrentPrimitive( - goals = context.goals.next, - procedureFromAncestor = 1, - substitution = (context.substitution + it.substitution) + override fun computeNext(): Iterable = + listOf( + try { + context.primitive?.solution?.whenIs( + yes = { + StateGoalSelection( + context.copyFromCurrentPrimitive( + goals = context.goals.next, + procedureFromAncestor = 1, + substitution = (context.substitution + it.substitution), + ), ) - ) - }, - no = { - failureState(context.parent!!.copyFromCurrentPrimitive()) - }, - halt = { - StateException(it.exception.updateLastContext(context.skipThrow()), context.copyFromCurrentPrimitive()) - }, - otherwise = { throw IllegalStateException("This should never happen") } - ) ?: failureState(context.parent!!.copyFromCurrentPrimitive()) - } catch (exception: ResolutionException) { - StateException(exception.updateLastContext(context.skipThrow()), context.copy(step = nextStep())) - } - ) + }, + no = { + failureState(context.parent!!.copyFromCurrentPrimitive()) + }, + halt = { + StateException( + it.exception.updateLastContext(context.skipThrow()), + context.copyFromCurrentPrimitive(), + ) + }, + otherwise = { throw IllegalStateException("This should never happen") }, + ) ?: failureState(context.parent!!.copyFromCurrentPrimitive()) + } catch (exception: ResolutionException) { + StateException(exception.updateLastContext(context.skipThrow()), context.copy(step = nextStep())) + }, + ) override fun clone(context: ConcurrentExecutionContext): StatePrimitiveExecution = copy(context = context) } diff --git a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StatePrimitiveSelection.kt b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StatePrimitiveSelection.kt index cfe2e728f..04196bd70 100644 --- a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StatePrimitiveSelection.kt +++ b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StatePrimitiveSelection.kt @@ -8,13 +8,12 @@ import it.unibo.tuprolog.solve.exception.error.TypeError import it.unibo.tuprolog.solve.extractSignature data class StatePrimitiveSelection(override val context: ConcurrentExecutionContext) : AbstractState(context) { - private fun exceptionalState(exception: ResolutionException): Iterable { return listOf( StateException( exception, - context.copy(step = nextStep()) - ) + context.copy(step = nextStep()), + ), ) } @@ -27,8 +26,8 @@ data class StatePrimitiveSelection(override val context: ConcurrentExecutionCont InstantiationError.forGoal( context = context, procedure = context.procedure!!.extractSignature(), - variable = goal.castToVar() - ) + variable = goal.castToVar(), + ), ) } goal.isStruct -> { @@ -39,8 +38,9 @@ data class StatePrimitiveSelection(override val context: ConcurrentExecutionCont val childContext = createChild() try { val request = childContext.toRequest(goalStruct, signature, executionTime) - val primitive = libraries.primitives[signature] - ?: error("Inconsistent behaviour of Library.contains and Library.get") + val primitive = + libraries.primitives[signature] + ?: error("Inconsistent behaviour of Library.contains and Library.get") primitive.solve(request) .map { StatePrimitiveExecution(childContext.copy(primitive = it)) } .asIterable() @@ -57,8 +57,8 @@ data class StatePrimitiveSelection(override val context: ConcurrentExecutionCont context = context, procedure = context.procedure?.extractSignature() ?: Signature("?-", 1), expectedType = TypeError.Expected.CALLABLE, - culprit = goal - ) + culprit = goal, + ), ) } } diff --git a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StateRuleExecution.kt b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StateRuleExecution.kt index 694e74967..d794294c8 100644 --- a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StateRuleExecution.kt +++ b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StateRuleExecution.kt @@ -5,12 +5,12 @@ import it.unibo.tuprolog.solve.Solution import it.unibo.tuprolog.solve.concurrent.ConcurrentExecutionContext data class StateRuleExecution(override val context: ConcurrentExecutionContext) : AbstractState(context) { - private val failureState: EndState - get() = StateEnd( - solution = Solution.no(context.query), - context = context.copy(step = nextStep()) - ) + get() = + StateEnd( + solution = Solution.no(context.query), + context = context.copy(step = nextStep()), + ) override fun computeNext(): Iterable { val substitution = with(context) { unificator.mgu(currentGoal!!, rule!!.head) } @@ -24,12 +24,12 @@ data class StateRuleExecution(override val context: ConcurrentExecutionContext) goals = subGoals.toGoals(), rule = null, substitution = newSubstitution, - step = nextStep() - ) + step = nextStep(), + ), ) } else -> failureState - } + }, ) } diff --git a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StateRuleSelection.kt b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StateRuleSelection.kt index 6ef669412..10f483cc9 100644 --- a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StateRuleSelection.kt +++ b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/StateRuleSelection.kt @@ -19,7 +19,6 @@ import it.unibo.tuprolog.theory.Theory import it.unibo.tuprolog.utils.buffered data class StateRuleSelection(override val context: ConcurrentExecutionContext) : AbstractState(context) { - companion object { private val catchSignature = Catch.signature } @@ -27,26 +26,31 @@ data class StateRuleSelection(override val context: ConcurrentExecutionContext) private fun exceptionalState(exception: ResolutionException): StateException = StateException(exception, context.copy(step = nextStep())) - private fun missingProcedure(ruleSources: Sequence, missing: Signature): State = + private fun missingProcedure( + ruleSources: Sequence, + missing: Signature, + ): State = when (val unknown = context.flags[Unknown]) { Unknown.FAIL -> failureState else -> { if (ruleSources.none { missing.toIndicator() in it }) { when (unknown) { - Unknown.ERROR -> exceptionalState( - ExistenceError.forProcedure( - context = context, - procedure = missing - ) - ) - Unknown.WARNING -> failureState.also { - context.warnings.write( - MissingPredicate( + Unknown.ERROR -> + exceptionalState( + ExistenceError.forProcedure( context = context, - signature = missing - ) + procedure = missing, + ), ) - } + Unknown.WARNING -> + failureState.also { + context.warnings.write( + MissingPredicate( + context = context, + signature = missing, + ), + ) + } else -> failureState } } else { @@ -59,10 +63,11 @@ data class StateRuleSelection(override val context: ConcurrentExecutionContext) get() = StateGoalSelection(context.copy(goals = context.goals.next, step = nextStep())) private val failureState: EndState - get() = StateEnd( - solution = Solution.no(context.query), - context = context.copy(step = nextStep()) - ) + get() = + StateEnd( + solution = Solution.no(context.query), + context = context.copy(step = nextStep()), + ) override fun computeNext(): Iterable { val currentGoal = context.currentGoal!! @@ -73,55 +78,59 @@ data class StateRuleSelection(override val context: ConcurrentExecutionContext) InstantiationError.forGoal( context = context, procedure = context.procedure!!.extractSignature(), - variable = currentGoal.castToVar() - ) - ) + variable = currentGoal.castToVar(), + ), + ), ) - currentGoal.isStruct -> with(context) { - val currentGoalStruct = currentGoal.castToStruct() - val ruleSources = sequenceOf(libraries.asTheory(context.unificator), staticKb, dynamicKb) - when { - currentGoalStruct.isTruth -> { - listOf( - if (currentGoalStruct.isTrue) { - ignoreState - } else { - failureState - } - ) - } - ruleSources.any { currentGoalStruct in it } -> { - val rules = ruleSources.flatMap { it.selectClauses(currentGoalStruct) } - rules.map { - if (context.isTailRecursive) { - StateRuleExecution(context.replaceWithChildAppendingRules(it)) - } else { - StateRuleExecution(context.createChildAppendingRules(it)) - } - }.asIterable() + currentGoal.isStruct -> + with(context) { + val currentGoalStruct = currentGoal.castToStruct() + val ruleSources = sequenceOf(libraries.asTheory(context.unificator), staticKb, dynamicKb) + when { + currentGoalStruct.isTruth -> { + listOf( + if (currentGoalStruct.isTrue) { + ignoreState + } else { + failureState + }, + ) + } + ruleSources.any { currentGoalStruct in it } -> { + val rules = ruleSources.flatMap { it.selectClauses(currentGoalStruct) } + rules.map { + if (context.isTailRecursive) { + StateRuleExecution(context.replaceWithChildAppendingRules(it)) + } else { + StateRuleExecution(context.createChildAppendingRules(it)) + } + }.asIterable() + } + else -> listOf(missingProcedure(ruleSources, currentGoalStruct.extractSignature())) } - else -> listOf(missingProcedure(ruleSources, currentGoalStruct.extractSignature())) } - } - else -> listOf( - exceptionalState( - TypeError.forGoal( - context = context, - procedure = context.procedure!!.extractSignature(), - expectedType = TypeError.Expected.CALLABLE, - culprit = currentGoal - ) + else -> + listOf( + exceptionalState( + TypeError.forGoal( + context = context, + procedure = context.procedure!!.extractSignature(), + expectedType = TypeError.Expected.CALLABLE, + culprit = currentGoal, + ), + ), ) - ) } } private val ConcurrentExecutionContext.isTailRecursive: Boolean - get() = goals.next.isOver && flags[LastCallOptimization] == ON && goals.current!!.let { currentGoal -> - currentGoal.asStruct()?.extractSignature()?.let { - it == procedure?.extractSignature() && it != catchSignature - } ?: false - } + get() = + goals.next.isOver && flags[LastCallOptimization] == ON && + goals.current!!.let { currentGoal -> + currentGoal.asStruct()?.extractSignature()?.let { + it == procedure?.extractSignature() && it != catchSignature + } ?: false + } private fun Theory.selectClauses(term: Struct): Sequence = get(term).map { it.freshCopy() }.ensureRules().let { diff --git a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/Utils.kt b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/Utils.kt index 97448442e..e5b3102fa 100644 --- a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/Utils.kt +++ b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/fsm/Utils.kt @@ -15,7 +15,10 @@ import it.unibo.tuprolog.utils.cursor import kotlin.jvm.JvmName fun Sequence.ensureRules(): Sequence = - map { require(it.isRule); it.castToRule() } + map { + require(it.isRule) + it.castToRule() + } fun Term.unfoldGoals(): Sequence = when { @@ -39,7 +42,7 @@ fun ConcurrentExecutionContext.createChild(inferProcedureFromGoals: Boolean = tr procedure = if (inferProcedureFromGoals) currentGoal else procedure, parent = this, depth = depth + 1, - step = step + 1 + step = step + 1, ) } @@ -50,13 +53,13 @@ fun ConcurrentExecutionContext.replaceWithChild(inferProcedureFromGoals: Boolean goals = currentGoal.toGoals(), procedure = if (inferProcedureFromGoals) currentGoal else procedure, depth = depth + 1, - step = step + 1 + step = step + 1, ) } fun ConcurrentExecutionContext.createChildAppendingRules( rule: Rule, - inferProcedureFromGoals: Boolean = true + inferProcedureFromGoals: Boolean = true, ): ConcurrentExecutionContext { val tempExecutionContext = createChild(inferProcedureFromGoals) return tempExecutionContext.copy(rule = rule) @@ -64,7 +67,7 @@ fun ConcurrentExecutionContext.createChildAppendingRules( fun ConcurrentExecutionContext.replaceWithChildAppendingRules( rule: Rule, - inferProcedureFromGoals: Boolean = true + inferProcedureFromGoals: Boolean = true, ): ConcurrentExecutionContext { val tempExecutionContext = replaceWithChild(inferProcedureFromGoals) return tempExecutionContext.copy(rule = rule) @@ -73,5 +76,5 @@ fun ConcurrentExecutionContext.replaceWithChildAppendingRules( fun ConcurrentExecutionContext.toRequest( goal: Struct, signature: Signature, - startTime: TimeInstant + startTime: TimeInstant, ) = Solve.Request(signature, goal.args, this, startTime) diff --git a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/stdlib/DefaultBuiltins.kt b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/stdlib/DefaultBuiltins.kt index 9673cc67a..90e674e31 100644 --- a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/stdlib/DefaultBuiltins.kt +++ b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/stdlib/DefaultBuiltins.kt @@ -77,89 +77,93 @@ import it.unibo.tuprolog.solve.stdlib.primitive.Var import it.unibo.tuprolog.solve.stdlib.primitive.Write object DefaultBuiltins : ExtensionLibrary(CommonBuiltins) { + @Suppress("ktlint:standard:discouraged-comment-location") override val additionalRules: Iterable> - get() = listOf( - Catch, - Call, - Comma, - Cut, // convert into primitive in case smarter behavirour is needed - NegationAsFailure.Fail, - NegationAsFailure.Success - ) + get() = + listOf( + Catch, + Call, + Comma, + Cut, // convert into primitive in case smarter behavirour is needed + NegationAsFailure.Fail, + NegationAsFailure.Success, + ) + @Suppress("ktlint:standard:discouraged-comment-location") override val primitives: Map - get() = listOf( - // Abolish, - Arg, - ArithmeticEqual, - ArithmeticGreaterThan, - ArithmeticGreaterThanOrEqualTo, - ArithmeticLowerThan, - ArithmeticLowerThanOrEqualTo, - ArithmeticNotEqual, - // Assert, - // AssertA, - // AssertZ, - Atom, - AtomChars, - AtomCodes, - AtomConcat, - Atomic, - AtomLength, - Between, - BagOf, - Callable, - CharCode, - Clause, - Compound, - CopyTerm, - CurrentOp, - CurrentFlag, - EnsureExecutable, - FindAll, - Float, - Functor, - GetDurable, - GetEphemeral, - GetPersistent, - Ground, - Halt, - Halt1, - Integer, - Is, - Naf, // TODO remove rule for \+ from default builtins - Natural, - NewLine, - NonVar, - NotUnifiableWith, - Number, - NumberChars, - NumberCodes, - Op, - Or, // TODO removes rule for -> and ; from default builtins - Repeat, - // Retract, - // RetractAll, - Reverse, - SetDurable, - SetEphemeral, - SetOf, - SetPersistent, - SetFlag, - // Sleep, - SubAtom, - TermGreaterThan, - TermGreaterThanOrEqualTo, - TermIdentical, - TermLowerThan, - TermLowerThanOrEqualTo, - TermNotIdentical, - TermNotSame, - TermSame, - Throw, // Specific impl - UnifiesWith, - Univ, - Var, - Write - ).map { it.descriptionPair }.toMap() + get() = + listOf( + // Abolish, + Arg, + ArithmeticEqual, + ArithmeticGreaterThan, + ArithmeticGreaterThanOrEqualTo, + ArithmeticLowerThan, + ArithmeticLowerThanOrEqualTo, + ArithmeticNotEqual, + // Assert, + // AssertA, + // AssertZ, + Atom, + AtomChars, + AtomCodes, + AtomConcat, + Atomic, + AtomLength, + Between, + BagOf, + Callable, + CharCode, + Clause, + Compound, + CopyTerm, + CurrentOp, + CurrentFlag, + EnsureExecutable, + FindAll, + Float, + Functor, + GetDurable, + GetEphemeral, + GetPersistent, + Ground, + Halt, + Halt1, + Integer, + Is, + Naf, // TODO remove rule for \+ from default builtins + Natural, + NewLine, + NonVar, + NotUnifiableWith, + Number, + NumberChars, + NumberCodes, + Op, + Or, // TODO removes rule for -> and ; from default builtins + Repeat, + // Retract, + // RetractAll, + Reverse, + SetDurable, + SetEphemeral, + SetOf, + SetPersistent, + SetFlag, + // Sleep, + SubAtom, + TermGreaterThan, + TermGreaterThanOrEqualTo, + TermIdentical, + TermLowerThan, + TermLowerThanOrEqualTo, + TermNotIdentical, + TermNotSame, + TermSame, + Throw, // Specific impl + UnifiesWith, + Univ, + Var, + Write, + ).map { it.descriptionPair }.toMap() } diff --git a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/stdlib/primitive/Or.kt b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/stdlib/primitive/Or.kt index 1f041cf7a..99b7f0685 100644 --- a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/stdlib/primitive/Or.kt +++ b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/stdlib/primitive/Or.kt @@ -14,7 +14,7 @@ import it.unibo.tuprolog.solve.stdlib.rule.Arrow object Or : BinaryRelation(";") { override fun Solve.Request.computeAll( first: Term, - second: Term + second: Term, ): Sequence { ensuringArgumentIsCallable(0) ensuringArgumentIsCallable(1) @@ -41,7 +41,7 @@ object Or : BinaryRelation(";") { private fun Solve.Request.mapSolution( solution: Solution, - conditionSubstitution: Substitution = Substitution.empty() + conditionSubstitution: Substitution = Substitution.empty(), ): Solve.Response { return when (solution) { is Solution.Yes -> { diff --git a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/stdlib/primitive/Throw.kt b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/stdlib/primitive/Throw.kt index 107121252..7b599d8b8 100644 --- a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/stdlib/primitive/Throw.kt +++ b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/stdlib/primitive/Throw.kt @@ -10,13 +10,16 @@ import it.unibo.tuprolog.solve.primitive.Solve import it.unibo.tuprolog.solve.primitive.UnaryPredicate object Throw : UnaryPredicate("throw") { - private fun handleError(context: ExecutionContext, error: Term): ResolutionException = + private fun handleError( + context: ExecutionContext, + error: Term, + ): ResolutionException = when { error is Struct && error.functor == "error" && error.arity in 1..2 -> { LogicError.of( context = context, type = error[0] as Struct, - extraData = if (error.arity > 1) error[1] else null + extraData = if (error.arity > 1) error[1] else null, ) } else -> MessageError.of(error, context) @@ -24,7 +27,7 @@ object Throw : UnaryPredicate("throw") { override fun Solve.Request.computeAll(first: Term): Sequence { return sequenceOf( - ensuringAllArgumentsAreInstantiated().replyException(handleError(context, arguments[0])) + ensuringAllArgumentsAreInstantiated().replyException(handleError(context, arguments[0])), ) } } diff --git a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/stdlib/rule/Call.kt b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/stdlib/rule/Call.kt index 71146df6f..0130b953d 100644 --- a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/stdlib/rule/Call.kt +++ b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/stdlib/rule/Call.kt @@ -11,8 +11,9 @@ object Call : RuleWrapper("call", 1) { get() = ktListOf(varOf("G")) override val Scope.body: Term - get() = tupleOf( - structOf(EnsureExecutable.functor, varOf("G")), - varOf("G") - ) + get() = + tupleOf( + structOf(EnsureExecutable.functor, varOf("G")), + varOf("G"), + ) } diff --git a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/stdlib/rule/NegationAsFailure.kt b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/stdlib/rule/NegationAsFailure.kt index 052639323..63c558439 100644 --- a/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/stdlib/rule/NegationAsFailure.kt +++ b/solve-concurrent/src/commonMain/kotlin/it/unibo/tuprolog/solve/concurrent/stdlib/rule/NegationAsFailure.kt @@ -8,22 +8,23 @@ import it.unibo.tuprolog.solve.stdlib.magic.MagicCut import it.unibo.tuprolog.solve.stdlib.primitive.EnsureExecutable sealed class NegationAsFailure : RuleWrapper(FUNCTOR, ARITY) { - override val Scope.head: List - get() = ktListOf( - varOf("X") - ) + get() = + ktListOf( + varOf("X"), + ) abstract override val Scope.body: Term object Fail : NegationAsFailure() { override val Scope.body: Term - get() = tupleOf( - structOf(EnsureExecutable.functor, varOf("X")), - structOf(Call.functor, varOf("X")), - MagicCut, - truthOf(false) - ) + get() = + tupleOf( + structOf(EnsureExecutable.functor, varOf("X")), + structOf(Call.functor, varOf("X")), + MagicCut, + truthOf(false), + ) } object Success : NegationAsFailure() { diff --git a/solve-concurrent/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveConcurrentTest.kt b/solve-concurrent/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveConcurrentTest.kt index 798b792f4..a54cf115e 100644 --- a/solve-concurrent/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveConcurrentTest.kt +++ b/solve-concurrent/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveConcurrentTest.kt @@ -4,7 +4,8 @@ import kotlin.jvm.JvmField object SolveConcurrentTest { @JvmField - val expectations = Expectations( - concurrentShouldWork = true - ) + val expectations = + Expectations( + concurrentShouldWork = true, + ) } diff --git a/solve-concurrent/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestConcurrentStaticFactory.kt b/solve-concurrent/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestConcurrentStaticFactory.kt index b07b14b1c..914d3569a 100644 --- a/solve-concurrent/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestConcurrentStaticFactory.kt +++ b/solve-concurrent/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestConcurrentStaticFactory.kt @@ -3,9 +3,10 @@ package it.unibo.tuprolog.solve import kotlin.test.Test class TestConcurrentStaticFactory : TestStaticFactory { - private val prototype = TestStaticFactory.prototype( - SolveConcurrentTest.expectations - ) + private val prototype = + TestStaticFactory.prototype( + SolveConcurrentTest.expectations, + ) @Test override fun testStaticSolverFactoryForClassic() { diff --git a/solve-concurrent/src/commonTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestClassicSolverConstruction.kt b/solve-concurrent/src/commonTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestClassicSolverConstruction.kt index d2ff4f878..f883b6329 100644 --- a/solve-concurrent/src/commonTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestClassicSolverConstruction.kt +++ b/solve-concurrent/src/commonTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestClassicSolverConstruction.kt @@ -8,11 +8,11 @@ import kotlin.test.Test class TestClassicSolverConstruction : TestSolverConstruction, SolverFactory by ConcurrentSolverFactory { - - private val prototype = TestSolverConstruction.prototype( - this, - DefaultBuiltins - ) + private val prototype = + TestSolverConstruction.prototype( + this, + DefaultBuiltins, + ) @Test override fun testCreatingEmptySolver() { diff --git a/solve-concurrent/src/jsMain/kotlin/it/unibo/tuprolog/solve/concurrent/AtomicIntJs.kt b/solve-concurrent/src/jsMain/kotlin/it/unibo/tuprolog/solve/concurrent/AtomicIntJs.kt index 223fbdcb3..855f519a3 100644 --- a/solve-concurrent/src/jsMain/kotlin/it/unibo/tuprolog/solve/concurrent/AtomicIntJs.kt +++ b/solve-concurrent/src/jsMain/kotlin/it/unibo/tuprolog/solve/concurrent/AtomicIntJs.kt @@ -1,7 +1,6 @@ package it.unibo.tuprolog.solve.concurrent class AtomicIntJs(override var value: Int) : AtomicInt { - override fun plusAssign(delta: Int) { value += delta } diff --git a/solve-concurrent/src/jvmMain/kotlin/it/unibo/tuprolog/solve/concurrent/AtomicIntJvm.kt b/solve-concurrent/src/jvmMain/kotlin/it/unibo/tuprolog/solve/concurrent/AtomicIntJvm.kt index 2ec7a8102..f5350749d 100644 --- a/solve-concurrent/src/jvmMain/kotlin/it/unibo/tuprolog/solve/concurrent/AtomicIntJvm.kt +++ b/solve-concurrent/src/jvmMain/kotlin/it/unibo/tuprolog/solve/concurrent/AtomicIntJvm.kt @@ -3,7 +3,6 @@ package it.unibo.tuprolog.solve.concurrent import java.util.concurrent.atomic.AtomicInteger class AtomicIntJvm private constructor(private val atomicValue: AtomicInteger) : AtomicInt { - constructor(value: Int) : this(AtomicInteger(value)) override var value: Int @@ -18,11 +17,9 @@ class AtomicIntJvm private constructor(private val atomicValue: AtomicInteger) : this += (-delta) } - override fun incAndGet(delta: Int): Int = - atomicValue.addAndGet(delta) + override fun incAndGet(delta: Int): Int = atomicValue.addAndGet(delta) - override fun decAndGet(delta: Int): Int = - atomicValue.addAndGet(-delta) + override fun decAndGet(delta: Int): Int = atomicValue.addAndGet(-delta) override fun equals(other: Any?): Boolean { if (this === other) return true diff --git a/solve-concurrent/src/jvmMain/kotlin/it/unibo/tuprolog/solve/concurrent/CoroutinesUtilsJvm.kt b/solve-concurrent/src/jvmMain/kotlin/it/unibo/tuprolog/solve/concurrent/CoroutinesUtilsJvm.kt index 566ecba79..6aa1b6332 100644 --- a/solve-concurrent/src/jvmMain/kotlin/it/unibo/tuprolog/solve/concurrent/CoroutinesUtilsJvm.kt +++ b/solve-concurrent/src/jvmMain/kotlin/it/unibo/tuprolog/solve/concurrent/CoroutinesUtilsJvm.kt @@ -1,7 +1,6 @@ package it.unibo.tuprolog.solve.concurrent import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.channels.ReceiveChannel @@ -10,7 +9,7 @@ import java.util.concurrent.Executors import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.TimeUnit -@OptIn(ExperimentalCoroutinesApi::class) +@Suppress("TooGenericExceptionCaught") actual fun ReceiveChannel.toSequence(coroutineScope: CoroutineScope): Sequence { val queue = LinkedBlockingQueue() coroutineScope.launch { @@ -45,11 +44,11 @@ private val executionContext = Executors.newCachedThreadPool() internal actual val backgroundScope: CoroutineScope = CoroutineScope(SupervisorJob() + backgroundExecutionContext.asCoroutineDispatcher()) -actual fun createScope(): CoroutineScope = - CoroutineScope(SupervisorJob() + executionContext.asCoroutineDispatcher()) +actual fun createScope(): CoroutineScope = CoroutineScope(SupervisorJob() + executionContext.asCoroutineDispatcher()) -// todo need checks, computation never ends with shorter timeout of executionContext.awaitTermination +@Suppress("MagicNumber") actual fun closeExecution() { + // TODO need checks, computation never ends with shorter timeout of executionContext.awaitTermination executionContext.awaitTermination(30, TimeUnit.SECONDS) executionContext.shutdown() backgroundExecutionContext.awaitTermination(2, TimeUnit.SECONDS) diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestChannelToSequence.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestChannelToSequence.kt index a4a1206c1..da7e3c205 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestChannelToSequence.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestChannelToSequence.kt @@ -8,56 +8,58 @@ import kotlin.test.assertEquals import kotlin.test.assertTrue class TestChannelToSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test - fun testEmptyChannel() = multiRunConcurrentTest { - val channel: Channel = Channel() - val emptySeq = channel.toSequence(this) - assertTrue(channel.close()) - assertTrue(emptySeq.none()) - assertTrue(channel.isClosedForReceive) - assertTrue(channel.isClosedForSend) - } + fun testEmptyChannel() = + multiRunConcurrentTest { + val channel: Channel = Channel() + val emptySeq = channel.toSequence(this) + assertTrue(channel.close()) + assertTrue(emptySeq.none()) + assertTrue(channel.isClosedForReceive) + assertTrue(channel.isClosedForSend) + } @OptIn(ExperimentalCoroutinesApi::class) @Test - fun testEarlyClose() = multiRunConcurrentTest { - val channel: Channel = Channel() - channel.close() - val seq = channel.toSequence(this) - assertTrue(seq.count() == 0) - assertTrue(channel.isClosedForReceive) - assertTrue(channel.isClosedForSend) - } + fun testEarlyClose() = + multiRunConcurrentTest { + val channel: Channel = Channel() + channel.close() + val seq = channel.toSequence(this) + assertTrue(seq.count() == 0) + assertTrue(channel.isClosedForReceive) + assertTrue(channel.isClosedForSend) + } @OptIn(ExperimentalCoroutinesApi::class) @Test - fun testConcurrentSend() = multiRunConcurrentTest { - val channel: Channel = Channel() - launch { - channel.send("a") - channel.send("b") - channel.send("c") - channel.close() + fun testConcurrentSend() = + multiRunConcurrentTest { + val channel: Channel = Channel() + launch { + channel.send("a") + channel.send("b") + channel.send("c") + channel.close() + } + val set = channel.toSequence(this).toSet() + assertEquals(setOf("a", "b", "c"), set) + assertTrue(channel.isClosedForReceive) + assertTrue(channel.isClosedForSend) } - val set = channel.toSequence(this).toSet() - assertEquals(setOf("a", "b", "c"), set) - assertTrue(channel.isClosedForReceive) - assertTrue(channel.isClosedForSend) - } - @OptIn(ExperimentalCoroutinesApi::class) @Test - fun testChannelToSequence() = multiRunConcurrentTest { - val times = 100 - val channel: Channel = Channel(Channel.UNLIMITED) - launch { - for (c in 0 until times) - channel.send("$c") - channel.close() + fun testChannelToSequenceWorks() = + multiRunConcurrentTest { + val times = 100 + val channel: Channel = Channel(Channel.UNLIMITED) + launch { + for (c in 0 until times) + channel.send("$c") + channel.close() + } + val seq = channel.toSequence(this) + seq.forEachIndexed { index, s -> assertEquals("$index", s) } } - val seq = channel.toSequence(this) - seq.forEachIndexed { index, s -> assertEquals("$index", s) } - } } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAnd.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAnd.kt index 523c7fd32..7598a0d6a 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAnd.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAnd.kt @@ -12,7 +12,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentAnd : FromSequence, SolverFactory { - fun testTermIsFreeVariable() { logicProgramming { val solver = solverWithDefaultBuiltins() @@ -48,20 +47,22 @@ interface TestConcurrentAnd : FromSequence, SolverFa fun testNoFooIsCallable() { logicProgramming { - val solver = solverWithDefaultBuiltins( - flags = FlagStore.of(Unknown to Unknown.ERROR) - ) + val solver = + solverWithDefaultBuiltins( + flags = FlagStore.of(Unknown to Unknown.ERROR), + ) val query = "nofoo"("X") and call("X") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - ExistenceError.forProcedure( - DummyInstances.executionContext, - Signature("nofoo", 1) - ) + val expected = + fromSequence( + query.halt( + ExistenceError.forProcedure( + DummyInstances.executionContext, + Signature("nofoo", 1), + ), + ), ) - ) expected.assertingEquals(solutions) } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAndImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAndImpl.kt index ed18d5f60..aea7b0abd 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAndImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAndImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentAndImpl : TestConcurrentAnd, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testTermIsFreeVariable() = multiRunConcurrentTest { super.testTermIsFreeVariable() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentArg.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentArg.kt index 16737ff58..815fca091 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentArg.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentArg.kt @@ -12,7 +12,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentArg : FromSequence, SolverFactory { - fun testArgFromFoo() { logicProgramming { val solver = solverWithDefaultBuiltins() @@ -127,16 +126,17 @@ interface TestConcurrentArg : FromSequence, SolverFa val query = arg(1, "X", "a") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - Signature("arg", 3), - varOf("X"), - index = 1 - ) + val expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + Signature("arg", 3), + varOf("X"), + index = 1, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -148,17 +148,18 @@ interface TestConcurrentArg : FromSequence, SolverFa val query = arg(0, "atom", "A") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("arg", 3), - TypeError.Expected.COMPOUND, - atomOf("atom"), - index = 1 - ) + val expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("arg", 3), + TypeError.Expected.COMPOUND, + atomOf("atom"), + index = 1, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -170,17 +171,18 @@ interface TestConcurrentArg : FromSequence, SolverFa val query = arg(0, 3, "A") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("arg", 3), - TypeError.Expected.COMPOUND, - numOf(3), - index = 1 - ) + val expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("arg", 3), + TypeError.Expected.COMPOUND, + numOf(3), + index = 1, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -192,17 +194,18 @@ interface TestConcurrentArg : FromSequence, SolverFa val query = arg(intOf(-3), "foo"("a", "b"), "A") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - DomainError.forArgument( - DummyInstances.executionContext, - Signature("arg", 3), - DomainError.Expected.NOT_LESS_THAN_ZERO, - numOf(-3), - index = 0 - ) + val expected = + fromSequence( + query.halt( + DomainError.forArgument( + DummyInstances.executionContext, + Signature("arg", 3), + DomainError.Expected.NOT_LESS_THAN_ZERO, + numOf(-3), + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -214,17 +217,18 @@ interface TestConcurrentArg : FromSequence, SolverFa val query = arg("a", "foo"("a", "b"), "X") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("arg", 3), - TypeError.Expected.INTEGER, - atomOf("a"), - index = 0 - ) + val expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("arg", 3), + TypeError.Expected.INTEGER, + atomOf("a"), + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentArgImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentArgImpl.kt index a1bcb242d..326935057 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentArgImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentArgImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentArgImpl : TestConcurrentArg, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testArgFromFoo() = multiRunConcurrentTest { super.testArgFromFoo() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentArith.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentArith.kt index b99efff19..8241e06fc 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentArith.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentArith.kt @@ -11,7 +11,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentArith : FromSequence, SolverFactory { - fun testArithDiff() { logicProgramming { val solver = solverWithDefaultBuiltins() @@ -36,32 +35,34 @@ interface TestConcurrentArith : FromSequence, Solver query = N arithNeq 5 solutions = fromSequence(solver.solve(query, mediumDuration)) - expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - Signature("=\\=", 2), - N, - index = 0 - ) + expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + Signature("=\\=", 2), + N, + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) query = "floot"(1) arithNeq 5 solutions = fromSequence(solver.solve(query, mediumDuration)) - expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("=\\=", 2), - TypeError.Expected.EVALUABLE, - "floot"(1), - index = 0 - ) + expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("=\\=", 2), + TypeError.Expected.EVALUABLE, + "floot"(1), + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -91,32 +92,34 @@ interface TestConcurrentArith : FromSequence, Solver query = N arithEq 5 solutions = fromSequence(solver.solve(query, mediumDuration)) - expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - Signature("=:=", 2), - N, - index = 0 - ) + expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + Signature("=:=", 2), + N, + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) query = "floot"(1) arithEq 5 solutions = fromSequence(solver.solve(query, mediumDuration)) - expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("=:=", 2), - TypeError.Expected.EVALUABLE, - "floot"(1), - index = 0 - ) + expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("=:=", 2), + TypeError.Expected.EVALUABLE, + "floot"(1), + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) @@ -152,32 +155,34 @@ interface TestConcurrentArith : FromSequence, Solver query = X greaterThan 5 solutions = fromSequence(solver.solve(query, mediumDuration)) - expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - Signature(">", 2), - X, - index = 0 - ) + expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + Signature(">", 2), + X, + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) query = (2 + "floot"(1)) greaterThan 5 solutions = fromSequence(solver.solve(query, mediumDuration)) - expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature(">", 2), - TypeError.Expected.EVALUABLE, - "floot"(1), - index = 0 - ) + expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature(">", 2), + TypeError.Expected.EVALUABLE, + "floot"(1), + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -207,32 +212,34 @@ interface TestConcurrentArith : FromSequence, Solver query = X greaterThanOrEqualsTo 5 solutions = fromSequence(solver.solve(query, mediumDuration)) - expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - Signature(">=", 2), - X, - index = 0 - ) + expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + Signature(">=", 2), + X, + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) query = (2 + "floot"(1)) greaterThanOrEqualsTo 5 solutions = fromSequence(solver.solve(query, mediumDuration)) - expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature(">=", 2), - TypeError.Expected.EVALUABLE, - "floot"(1), - index = 0 - ) + expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature(">=", 2), + TypeError.Expected.EVALUABLE, + "floot"(1), + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -262,32 +269,34 @@ interface TestConcurrentArith : FromSequence, Solver query = X lowerThan 5 solutions = fromSequence(solver.solve(query, mediumDuration)) - expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - Signature("<", 2), - X, - index = 0 - ) + expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + Signature("<", 2), + X, + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) query = (2 + "floot"(1)) lowerThan 5 solutions = fromSequence(solver.solve(query, mediumDuration)) - expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("<", 2), - TypeError.Expected.EVALUABLE, - "floot"(1), - index = 0 - ) + expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("<", 2), + TypeError.Expected.EVALUABLE, + "floot"(1), + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -317,32 +326,34 @@ interface TestConcurrentArith : FromSequence, Solver query = X lowerThanOrEqualsTo 5 solutions = fromSequence(solver.solve(query, mediumDuration)) - expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - Signature("=<", 2), - X, - index = 0 - ) + expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + Signature("=<", 2), + X, + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) query = (2 + "floot"(1)) lowerThanOrEqualsTo 5 solutions = fromSequence(solver.solve(query, mediumDuration)) - expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("=<", 2), - TypeError.Expected.EVALUABLE, - "floot"(1), - index = 0 - ) + expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("=<", 2), + TypeError.Expected.EVALUABLE, + "floot"(1), + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentArithImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentArithImpl.kt index 4a2109200..6d77f90bc 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentArithImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentArithImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentArithImpl : TestConcurrentArith, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testArithDiff() = multiRunConcurrentTest { super.testArithDiff() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtom.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtom.kt index 3133c5560..27dcebbe6 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtom.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtom.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentAtom : FromSequence, SolverFactory { - fun testAtomAtom() { logicProgramming { val solver = solverWithDefaultBuiltins() diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomChars.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomChars.kt index 3f8054719..20abe17be 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomChars.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomChars.kt @@ -11,7 +11,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentAtomChars : FromSequence, SolverFactory { - fun atomCharsTestFirstIsVar() { logicProgramming { val solver = solverWithDefaultBuiltins() @@ -84,16 +83,17 @@ interface TestConcurrentAtomChars : FromSequence, So val query = atom_chars("A", "L") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - Signature("atom_chars", 2), - varOf("A"), - index = 0 - ) + val expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + Signature("atom_chars", 2), + varOf("A"), + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -105,17 +105,18 @@ interface TestConcurrentAtomChars : FromSequence, So val query = atom_chars("A", "iso") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("atom_chars", 2), - TypeError.Expected.LIST, - atomOf("iso"), - index = 1 - ) + val expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("atom_chars", 2), + TypeError.Expected.LIST, + atomOf("iso"), + index = 1, + ), + ), ) - ) expected.assertingEquals(solutions) } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomCharsImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomCharsImpl.kt index 5c27939fa..ceb6488b4 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomCharsImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomCharsImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentAtomCharsImpl : TestConcurrentAtomChars, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun atomCharsTestFirstIsVar() = multiRunConcurrentTest { super.atomCharsTestFirstIsVar() } @@ -35,7 +34,8 @@ class TestConcurrentAtomCharsImpl : @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun atomCharsTestIstantationErrorCheck() = multiRunConcurrentTest { super.atomCharsTestIstantationErrorCheck() } + override fun atomCharsTestIstantationErrorCheck() = + multiRunConcurrentTest { super.atomCharsTestIstantationErrorCheck() } @OptIn(ExperimentalCoroutinesApi::class) @Test diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomCodes.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomCodes.kt index 8ccd75083..66848801a 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomCodes.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomCodes.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentAtomCodes : FromSequence, SolverFactory { - fun testAtomCodesSecondIsVar1() { logicProgramming { val solver = solverWithDefaultBuiltins() diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomCodesImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomCodesImpl.kt index 642f684c3..559e76890 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomCodesImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomCodesImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentAtomCodesImpl : TestConcurrentAtomCodes, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testAtomCodesSecondIsVar1() = multiRunConcurrentTest { super.testAtomCodesSecondIsVar1() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomConcat.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomConcat.kt index 49e52d225..c71b4d5a4 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomConcat.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomConcat.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentAtomConcat : FromSequence, SolverFactory { - fun testAtomConcatThirdIsVar() { logicProgramming { val solver = solverWithDefaultBuiltins() diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomConcatImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomConcatImpl.kt index 0dee41b2d..64cdd07be 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomConcatImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomConcatImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentAtomConcatImpl : TestConcurrentAtomConcat, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testAtomConcatThirdIsVar() = multiRunConcurrentTest { super.testAtomConcatThirdIsVar() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomImpl.kt index 3c917140f..1b3352ecd 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentAtomImpl : TestConcurrentAtom, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testAtomAtom() = multiRunConcurrentTest { super.testAtomAtom() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomLength.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomLength.kt index a86fe2784..3c0427eb7 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomLength.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomLength.kt @@ -10,7 +10,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentAtomLength : FromSequence, SolverFactory { - fun testAtomLengthNoVar() { logicProgramming { val solver = solverWithDefaultBuiltins() @@ -41,17 +40,18 @@ interface TestConcurrentAtomLength : FromSequence, S val query = char_code("X", "a") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("char_code", 2), - TypeError.Expected.INTEGER, - atomOf("a"), - index = 1 - ) + val expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("char_code", 2), + TypeError.Expected.INTEGER, + atomOf("a"), + index = 1, + ), + ), ) - ) expected.assertingEquals(solutions) } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomLengthImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomLengthImpl.kt index 49d8c5c19..08d7cc864 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomLengthImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomLengthImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentAtomLengthImpl : TestConcurrentAtomLength, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testAtomLengthNoVar() = multiRunConcurrentTest { super.testAtomLengthNoVar() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomic.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomic.kt index 952899331..9ce57c619 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomic.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomic.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentAtomic : FromSequence, SolverFactory { - fun testAtomicAtom() { logicProgramming { val solver = solverWithDefaultBuiltins() diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomicImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomicImpl.kt index c48f0c307..d402c8389 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomicImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentAtomicImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentAtomicImpl : TestConcurrentAtomic, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testAtomicAtom() = multiRunConcurrentTest { super.testAtomicAtom() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentBagOf.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentBagOf.kt index 2f62348dd..9bcc49146 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentBagOf.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentBagOf.kt @@ -11,7 +11,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentBagOf : FromSequence, SolverFactory { - fun testBagXInDifferentValues() { logicProgramming { val solver = solverWithDefaultBuiltins() @@ -78,16 +77,17 @@ interface TestConcurrentBagOf : FromSequence, Solver val query = bagof("X", "G", "S") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - Signature("bagof", 3), - varOf("G"), - index = 1 - ) + val expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + Signature("bagof", 3), + varOf("G"), + index = 1, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -99,17 +99,18 @@ interface TestConcurrentBagOf : FromSequence, Solver val query = bagof("X", 1, "S") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("bagof", 3), - TypeError.Expected.CALLABLE, - numOf(1), - index = 1 - ) + val expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("bagof", 3), + TypeError.Expected.CALLABLE, + numOf(1), + index = 1, + ), + ), ) - ) expected.assertingEquals(solutions) } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentBagOfImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentBagOfImpl.kt index f107ba3df..737321dba 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentBagOfImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentBagOfImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentBagOfImpl : TestConcurrentBagOf, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testBagXInDifferentValues() = multiRunConcurrentTest { super.testBagXInDifferentValues() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentBigList.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentBigList.kt index 65faab1b5..3b516dd44 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentBigList.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentBigList.kt @@ -8,35 +8,36 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentBigList : FromSequence, SolverFactory { - override val shortDuration: TimeDuration get() = 4000 fun testBigListGeneration() { logicProgramming { - val theory = theoryOf( - fact { "biglist"(0, listOf(0)) }, - rule { - "biglist"(N, consOf(N, X)).impliedBy( - N greaterThan 0, - M `is` (N - 1), - "biglist"(M, X) - ) - } - ) + val theory = + theoryOf( + fact { "biglist"(0, listOf(0)) }, + rule { + "biglist"(N, consOf(N, X)).impliedBy( + N greaterThan 0, + M `is` (N - 1), + "biglist"(M, X), + ) + }, + ) val solver = solverWithDefaultBuiltins(staticKb = theory) val query = "biglist"(BigListOptions.SIZE, L) val solutions = fromSequence(solver.solve(query, longDuration)) - val expected = fromSequence( - sequenceOf( - query.yes( - L to listOf((0..BigListOptions.SIZE).reversed().map { Integer.of(it) }) + val expected = + fromSequence( + sequenceOf( + query.yes( + L to listOf((0..BigListOptions.SIZE).reversed().map { Integer.of(it) }), + ), + query.no(), ), - query.no() ) - ) expected.assertingEquals(solutions) } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentBigListImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentBigListImpl.kt index 6435695c9..49c0db86a 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentBigListImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentBigListImpl.kt @@ -9,7 +9,6 @@ class TestConcurrentBigListImpl : TestConcurrentBigList, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - override val shortDuration: TimeDuration get() = 6000 diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCall.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCall.kt index 687759f9e..9ac2b881d 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCall.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCall.kt @@ -11,7 +11,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentCall : FromSequence, SolverFactory { - val errorSignature: Signature fun testCallCut() { @@ -68,15 +67,16 @@ interface TestConcurrentCall : FromSequence, SolverF val query = call(write(3) and "X") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - InstantiationError.forGoal( - DummyInstances.executionContext, - errorSignature, - varOf("X") - ) + val expected = + fromSequence( + query.halt( + InstantiationError.forGoal( + DummyInstances.executionContext, + errorSignature, + varOf("X"), + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -88,16 +88,17 @@ interface TestConcurrentCall : FromSequence, SolverF val query = call(write(3) and call(1)) val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forGoal( - DummyInstances.executionContext, - errorSignature, - TypeError.Expected.CALLABLE, - numOf(1) - ) + val expected = + fromSequence( + query.halt( + TypeError.forGoal( + DummyInstances.executionContext, + errorSignature, + TypeError.Expected.CALLABLE, + numOf(1), + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -109,15 +110,16 @@ interface TestConcurrentCall : FromSequence, SolverF val query = call("X") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - InstantiationError.forGoal( - DummyInstances.executionContext, - errorSignature, - varOf("X") - ) + val expected = + fromSequence( + query.halt( + InstantiationError.forGoal( + DummyInstances.executionContext, + errorSignature, + varOf("X"), + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -129,16 +131,17 @@ interface TestConcurrentCall : FromSequence, SolverF val query = call(1) val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forGoal( - DummyInstances.executionContext, - errorSignature, - TypeError.Expected.CALLABLE, - numOf(1) - ) + val expected = + fromSequence( + query.halt( + TypeError.forGoal( + DummyInstances.executionContext, + errorSignature, + TypeError.Expected.CALLABLE, + numOf(1), + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -150,16 +153,18 @@ interface TestConcurrentCall : FromSequence, SolverF val query = call(fail and 1) val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forGoal( - DummyInstances.executionContext, - errorSignature, - TypeError.Expected.CALLABLE, - fail and 1 // solver returns 1 - ) + val expected = + fromSequence( + query.halt( + TypeError.forGoal( + DummyInstances.executionContext, + errorSignature, + TypeError.Expected.CALLABLE, + // solver returns 1 + fail and 1, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -171,16 +176,18 @@ interface TestConcurrentCall : FromSequence, SolverF val query = call(write(3) and 1) val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forGoal( - DummyInstances.executionContext, - errorSignature, - TypeError.Expected.CALLABLE, - write(3) and 1 // solver returns 1 - ) + val expected = + fromSequence( + query.halt( + TypeError.forGoal( + DummyInstances.executionContext, + errorSignature, + TypeError.Expected.CALLABLE, + // solver returns 1 + write(3) and 1, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -192,16 +199,18 @@ interface TestConcurrentCall : FromSequence, SolverF val query = call(1 or true) val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forGoal( - DummyInstances.executionContext, - errorSignature, - TypeError.Expected.CALLABLE, - (1 or true) // solver returns 1 - ) + val expected = + fromSequence( + query.halt( + TypeError.forGoal( + DummyInstances.executionContext, + errorSignature, + TypeError.Expected.CALLABLE, + // solver returns 1 + (1 or true), + ), + ), ) - ) expected.assertingEquals(solutions) } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCallImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCallImpl.kt index 5108b4616..db903c47e 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCallImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCallImpl.kt @@ -9,7 +9,6 @@ class TestConcurrentCallImpl : TestConcurrentCall, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - override val errorSignature: Signature = Signature("ensure_executable", 1) @OptIn(ExperimentalCoroutinesApi::class) diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCatchAndThrow.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCatchAndThrow.kt index 23119fc46..dbfba9cbf 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCatchAndThrow.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCatchAndThrow.kt @@ -8,21 +8,21 @@ import it.unibo.tuprolog.solve.halt import it.unibo.tuprolog.solve.no interface TestConcurrentCatchAndThrow : FromSequence, SolverFactory { - fun testCatchThrow() { logicProgramming { val solver = solverWithDefaultBuiltins() val query = (catch(true, C, write("something")) and `throw`("blabla")) val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - SystemError.forUncaughtException( - DummyInstances.executionContext, - atomOf("blabla") - ) + val expected = + fromSequence( + query.halt( + SystemError.forUncaughtException( + DummyInstances.executionContext, + atomOf("blabla"), + ), + ), ) - ) expected.assertingEquals(solutions) } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCatchAndThrowImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCatchAndThrowImpl.kt index 38409e2de..a70d34281 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCatchAndThrowImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCatchAndThrowImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentCatchAndThrowImpl : TestConcurrentCatchAndThrow, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testCatchThrow() = multiRunConcurrentTest { super.testCatchThrow() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCharCode.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCharCode.kt index 8ebce18db..46c82105d 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCharCode.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCharCode.kt @@ -10,7 +10,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentCharCode : FromSequence, SolverFactory { - fun testCharCodeSecondIsVar() { logicProgramming { val solver = solverWithDefaultBuiltins() @@ -38,16 +37,17 @@ interface TestConcurrentCharCode : FromSequence, Sol val solver = solverWithDefaultBuiltins() val query = atom_length("X", 4) val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - Signature("atom_length", 2), - varOf("X"), - index = 0 - ) + val expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + Signature("atom_length", 2), + varOf("X"), + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCharCodeImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCharCodeImpl.kt index 51d8c8b84..f990f7b1e 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCharCodeImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCharCodeImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentCharCodeImpl : TestConcurrentCharCode, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testCharCodeSecondIsVar() = multiRunConcurrentTest { super.testCharCodeSecondIsVar() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentClause.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentClause.kt index 785112d10..973ce327f 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentClause.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentClause.kt @@ -12,7 +12,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentClause : FromSequence, SolverFactory { - fun testClauseXBody() { logicProgramming { val solver = solverWithDefaultBuiltins() @@ -31,16 +30,17 @@ interface TestConcurrentClause : FromSequence, Solve val query = clause(`_`, "B") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - Signature("clause", 2), - `_`, - index = 0 - ) + val expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + Signature("clause", 2), + `_`, + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) @@ -66,17 +66,18 @@ interface TestConcurrentClause : FromSequence, Solve val query = clause(4, "B") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("clause", 2), - TypeError.Expected.CALLABLE, - numOf(4), - index = 0 - ) + val expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("clause", 2), + TypeError.Expected.CALLABLE, + numOf(4), + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) @@ -103,17 +104,18 @@ interface TestConcurrentClause : FromSequence, Solve val query = clause("f"(`_`), 5) val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("clause", 2), - TypeError.Expected.CALLABLE, - numOf(5), - index = 1 - ) + val expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("clause", 2), + TypeError.Expected.CALLABLE, + numOf(5), + index = 1, + ), + ), ) - ) expected.assertingEquals(solutions) @@ -140,17 +142,18 @@ interface TestConcurrentClause : FromSequence, Solve val query = clause(atom(`_`), "Body") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - PermissionError.of( - DummyInstances.executionContext, - Signature("clause", 2), - PermissionError.Operation.ACCESS, - PermissionError.Permission.PRIVATE_PROCEDURE, - "atom" / 1 - ) + val expected = + fromSequence( + query.halt( + PermissionError.of( + DummyInstances.executionContext, + Signature("clause", 2), + PermissionError.Operation.ACCESS, + PermissionError.Permission.PRIVATE_PROCEDURE, + "atom" / 1, + ), + ), ) - ) expected.assertingEquals(solutions) @@ -173,11 +176,13 @@ interface TestConcurrentClause : FromSequence, Solve fun testClauseVariables() { logicProgramming { - val solver = solverWithDefaultBuiltins( - staticKb = theoryOf( - rule { "f"(X) impliedBy "g"(X) } + val solver = + solverWithDefaultBuiltins( + staticKb = + theoryOf( + rule { "f"(X) impliedBy "g"(X) }, + ), ) - ) var query = clause("f"(A), B) var solutions = fromSequence(solver.solve(query, mediumDuration)) diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentClauseImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentClauseImpl.kt index aa09a8719..b28251d22 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentClauseImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentClauseImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentClauseImpl : TestConcurrentClause, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testClauseXBody() = multiRunConcurrentTest { super.testClauseXBody() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCompound.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCompound.kt index a5d9ee14d..ca011ac43 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCompound.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCompound.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentCompound : FromSequence, SolverFactory { - fun testCompoundDec() { logicProgramming { val solver = solverWithDefaultBuiltins() diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCompoundImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCompoundImpl.kt index f95520fd0..dac1e4684 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCompoundImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCompoundImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentCompoundImpl : TestConcurrentCompound, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testCompoundDec() = multiRunConcurrentTest { super.testCompoundDec() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCopyTerm.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCopyTerm.kt index 25d08d658..e10e509d7 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCopyTerm.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCopyTerm.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentCopyTerm : FromSequence, SolverFactory { - fun testCopyXNum() { logicProgramming { val solver = solverWithDefaultBuiltins() diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCopyTermImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCopyTermImpl.kt index 98bf71cbe..eecbabfe4 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCopyTermImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCopyTermImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentCopyTermImpl : TestConcurrentCopyTerm, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testCopyXNum() = multiRunConcurrentTest { super.testCopyXNum() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCustomData.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCustomData.kt index f5a44543d..5a2f6228c 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCustomData.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCustomData.kt @@ -13,7 +13,6 @@ import it.unibo.tuprolog.solve.stdlib.primitive.SetPersistent import it.unibo.tuprolog.solve.yes interface TestConcurrentCustomData : FromSequence, SolverFactory { - fun testApi() { val solver = solverWithDefaultBuiltins() diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCustomDataImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCustomDataImpl.kt index e937da277..6715625e5 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCustomDataImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentCustomDataImpl.kt @@ -9,7 +9,6 @@ class TestConcurrentCustomDataImpl : TestConcurrentCustomData, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testApi() = multiRunConcurrentTest { super.testApi() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFail.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFail.kt index 485d4a340..7bab59c66 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFail.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFail.kt @@ -11,7 +11,6 @@ import it.unibo.tuprolog.solve.halt import it.unibo.tuprolog.solve.no interface TestConcurrentFail : FromSequence, SolverFactory { - fun testFail() { logicProgramming { val solver = solverWithDefaultBuiltins() @@ -26,20 +25,22 @@ interface TestConcurrentFail : FromSequence, SolverF fun testUndefPred() { // streams solver: `No(query=undef_pred)` instead of undef_pred/0 logicProgramming { - val solver = solverWithDefaultBuiltins( - flags = FlagStore.of(Unknown to Unknown.ERROR) - ) + val solver = + solverWithDefaultBuiltins( + flags = FlagStore.of(Unknown to Unknown.ERROR), + ) val query = atomOf("undef_pred") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - ExistenceError.forProcedure( - DummyInstances.executionContext, - Signature("undef_pred", 0) - ) + val expected = + fromSequence( + query.halt( + ExistenceError.forProcedure( + DummyInstances.executionContext, + Signature("undef_pred", 0), + ), + ), ) - ) expected.assertingEquals(solutions) } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFailImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFailImpl.kt index 3e9ece9e1..a723bb985 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFailImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFailImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentFailImpl : TestConcurrentFail, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testFail() = multiRunConcurrentTest { super.testFail() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFindAll.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFindAll.kt index d5fe765a8..fa6335680 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFindAll.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFindAll.kt @@ -11,7 +11,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentFindAll : FromSequence, SolverFactory { - val errorSignature: Signature fun testFindXInDiffValues() { @@ -92,16 +91,17 @@ interface TestConcurrentFindAll : FromSequence, Solv val query = findall("X", "Goal", "S") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - Signature("findall", 3), - varOf("Goal"), - index = 1 - ) + val expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + Signature("findall", 3), + varOf("Goal"), + index = 1, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -113,17 +113,18 @@ interface TestConcurrentFindAll : FromSequence, Solv val query = findall("X", 4, "S") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("findall", 3), - TypeError.Expected.CALLABLE, - numOf(4), - index = 1 - ) + val expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("findall", 3), + TypeError.Expected.CALLABLE, + numOf(4), + index = 1, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -135,16 +136,17 @@ interface TestConcurrentFindAll : FromSequence, Solv val query = findall("X", call(1), "S") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forGoal( - DummyInstances.executionContext, - errorSignature, - TypeError.Expected.CALLABLE, - numOf(1) - ) + val expected = + fromSequence( + query.halt( + TypeError.forGoal( + DummyInstances.executionContext, + errorSignature, + TypeError.Expected.CALLABLE, + numOf(1), + ), + ), ) - ) expected.assertingEquals(solutions) } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFindAllImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFindAllImpl.kt index 180f0349b..33d7c66b8 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFindAllImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFindAllImpl.kt @@ -10,7 +10,6 @@ class TestConcurrentFindAllImpl : TestConcurrentFindAll, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - override val errorSignature: Signature = Signature("ensure_executable", 1) @OptIn(ExperimentalCoroutinesApi::class) diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFlags.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFlags.kt index ab1ed80da..518aa4be1 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFlags.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFlags.kt @@ -23,7 +23,6 @@ import kotlin.test.assertFalse import kotlin.test.assertTrue interface TestConcurrentFlags : FromSequence, SolverFactory { - fun defaultLastCallOptimizationIsOn() { logicProgramming { val solver = solverWithDefaultBuiltins() @@ -81,33 +80,35 @@ interface TestConcurrentFlags : FromSequence, Solver for (term in ktListOf(5, "f"("x"), 2.3).map { it.toTerm() }) { var query = current_flag(term, `_`) var solutions2 = fromSequence(solver.solveOnce(query, shortDuration)) - var expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - CurrentFlag.signature, - TypeError.Expected.ATOM, - term, - 0 - ) + var expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + CurrentFlag.signature, + TypeError.Expected.ATOM, + term, + 0, + ), + ), ) - ) expected.assertingEquals(solutions2) query = set_flag(term, "value") solutions2 = fromSequence(solver.solveOnce(query, shortDuration)) - expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - SetFlag.signature, - TypeError.Expected.ATOM, - term, - 0 - ) + expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + SetFlag.signature, + TypeError.Expected.ATOM, + term, + 0, + ), + ), ) - ) expected.assertingEquals(solutions2) } @@ -157,10 +158,11 @@ interface TestConcurrentFlags : FromSequence, Solver val query = current_flag(F, X) - val selectedFlags = solver.solve(query, shortDuration) - .filterIsInstance() - .map { it.substitution[F]!! to it.substitution[X]!! } - .toMap() + val selectedFlags = + solver.solve(query, shortDuration) + .filterIsInstance() + .map { it.substitution[F]!! to it.substitution[X]!! } + .toMap() assertEquals(defaultFlags, selectedFlags) } @@ -172,16 +174,17 @@ interface TestConcurrentFlags : FromSequence, Solver val query = set_flag(F, "value") val solutions = fromSequence(solver.solveList(query, shortDuration)) - val expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - SetFlag.signature, - F, - index = 0 - ) + val expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + SetFlag.signature, + F, + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -196,17 +199,18 @@ interface TestConcurrentFlags : FromSequence, Solver assertFalse { LastCallOptimization.admissibleValues.contains(truthOf(true)) } val solutions = fromSequence(solver.solveList(query, shortDuration)) - val expected = fromSequence( - query.halt( - DomainError.forFlagValues( - DummyInstances.executionContext, - SetFlag.signature, - LastCallOptimization.admissibleValues.asIterable(), - truthOf(true), - index = 1 - ) + val expected = + fromSequence( + query.halt( + DomainError.forFlagValues( + DummyInstances.executionContext, + SetFlag.signature, + LastCallOptimization.admissibleValues.asIterable(), + truthOf(true), + index = 1, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -218,17 +222,18 @@ interface TestConcurrentFlags : FromSequence, Solver val query = set_flag(MaxArity.name, 10) val solutions = fromSequence(solver.solveList(query, shortDuration)) - val expected = fromSequence( - query.halt( - PermissionError.of( - DummyInstances.executionContext, - SetFlag.signature, - PermissionError.Operation.MODIFY, - PermissionError.Permission.FLAG, - atomOf(MaxArity.name) - ) + val expected = + fromSequence( + query.halt( + PermissionError.of( + DummyInstances.executionContext, + SetFlag.signature, + PermissionError.Operation.MODIFY, + PermissionError.Permission.FLAG, + atomOf(MaxArity.name), + ), + ), ) - ) expected.assertingEquals(solutions) } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFlagsImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFlagsImpl.kt index 7869ba3dd..013af70c6 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFlagsImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFlagsImpl.kt @@ -9,7 +9,6 @@ class TestConcurrentFlagsImpl : TestConcurrentFlags, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun defaultLastCallOptimizationIsOn() = multiRunConcurrentTest { super.defaultLastCallOptimizationIsOn() } @@ -33,8 +32,12 @@ class TestConcurrentFlagsImpl : @OptIn(ExperimentalCoroutinesApi::class) @Test - @Ignore // todo handle set flag side effect - override fun settingMissingFlagsSucceeds() = multiRunConcurrentTest { super.settingMissingFlagsSucceeds() } + @Ignore + override fun settingMissingFlagsSucceeds() = + multiRunConcurrentTest { + // todo handle set flag side effect + super.settingMissingFlagsSucceeds() + } @OptIn(ExperimentalCoroutinesApi::class) @Test diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFloat.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFloat.kt index 6d060fbe5..b7ebd6fa1 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFloat.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFloat.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentFloat : FromSequence, SolverFactory { - fun testFloatDec() { logicProgramming { val solver = solverWithDefaultBuiltins() diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFloatImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFloatImpl.kt index f329a89bb..d55c3456b 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFloatImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFloatImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentFloatImpl : TestConcurrentFloat, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testFloatDec() = multiRunConcurrentTest { super.testFloatDec() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFunctor.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFunctor.kt index 2b54a12e2..434875619 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFunctor.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFunctor.kt @@ -13,7 +13,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentFunctor : FromSequence, SolverFactory { - fun testFunArity() { logicProgramming { val solver = solverWithDefaultBuiltins() @@ -140,16 +139,17 @@ interface TestConcurrentFunctor : FromSequence, Solv val query = functor("X", "Y", 3) val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - Signature("functor", 3), - varOf("Y"), - 1 - ) + val expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + Signature("functor", 3), + varOf("Y"), + 1, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -161,16 +161,17 @@ interface TestConcurrentFunctor : FromSequence, Solv val query = functor("X", "foo", "N") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - Signature("functor", 3), - varOf("N"), - index = 2 - ) + val expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + Signature("functor", 3), + varOf("N"), + index = 2, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -182,17 +183,18 @@ interface TestConcurrentFunctor : FromSequence, Solv val query = functor("X", "foo", "a") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("functor", 3), - TypeError.Expected.INTEGER, - atomOf("a"), - index = 2 - ) + val expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("functor", 3), + TypeError.Expected.INTEGER, + atomOf("a"), + index = 2, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -204,17 +206,18 @@ interface TestConcurrentFunctor : FromSequence, Solv val query = functor("F", 1.5, 1) val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("functor", 3), - TypeError.Expected.ATOM, - numOf(1.5), - index = 1 - ) + val expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("functor", 3), + TypeError.Expected.ATOM, + numOf(1.5), + index = 1, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -226,17 +229,18 @@ interface TestConcurrentFunctor : FromSequence, Solv val query = functor("F", "foo"("a"), 1) val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("functor", 3), - TypeError.Expected.ATOMIC, - "foo"("a"), - index = 1 - ) + val expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("functor", 3), + TypeError.Expected.ATOMIC, + "foo"("a"), + index = 1, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -246,19 +250,21 @@ interface TestConcurrentFunctor : FromSequence, Solv logicProgramming { val solver = solverWithDefaultBuiltins() - val query = current_flag("max_arity", A) and ( - (X `is` (A + 1)) and functor(T, "foo", X) + val query = + current_flag("max_arity", A) and ( + (X `is` (A + 1)) and functor(T, "foo", X) ) val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - RepresentationError.of( - DummyInstances.executionContext, - Signature("functor", 3), - RepresentationError.Limit.MAX_ARITY - ) + val expected = + fromSequence( + query.halt( + RepresentationError.of( + DummyInstances.executionContext, + Signature("functor", 3), + RepresentationError.Limit.MAX_ARITY, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -270,17 +276,18 @@ interface TestConcurrentFunctor : FromSequence, Solv val query = functor("T", "foo", intOf(-1)) val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - DomainError.forArgument( - DummyInstances.executionContext, - Signature("functor", 3), - DomainError.Expected.NOT_LESS_THAN_ZERO, - intOf(-1), - index = 2 - ) + val expected = + fromSequence( + query.halt( + DomainError.forArgument( + DummyInstances.executionContext, + Signature("functor", 3), + DomainError.Expected.NOT_LESS_THAN_ZERO, + intOf(-1), + index = 2, + ), + ), ) - ) expected.assertingEquals(solutions) } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFunctorImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFunctorImpl.kt index d670cfe2a..d26b68db3 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFunctorImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentFunctorImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentFunctorImpl : TestConcurrentFunctor, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testFunArity() = multiRunConcurrentTest { super.testFunArity() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIfThen.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIfThen.kt index bf9dedd4a..da787d1b3 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIfThen.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIfThen.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentIfThen : FromSequence, SolverFactory { - fun testIfThenTrue() { logicProgramming { val solver = solverWithDefaultBuiltins() @@ -73,12 +72,13 @@ interface TestConcurrentIfThen : FromSequence, Solve val query = "->"(true, ("X" eq 1) or ("X" eq 2)) val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - sequenceOf( - query.yes("X" to 1), - query.yes("X" to 2) + val expected = + fromSequence( + sequenceOf( + query.yes("X" to 1), + query.yes("X" to 2), + ), ) - ) expected.assertingEquals(solutions) } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIfThenElse.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIfThenElse.kt index 29f6da8f3..b0f8e7be6 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIfThenElse.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIfThenElse.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentIfThenElse : FromSequence, SolverFactory { - fun testIfTrueElseFail() { logicProgramming { val solver = solverWithDefaultBuiltins() @@ -85,12 +84,13 @@ interface TestConcurrentIfThenElse : FromSequence, S val query = ";"("->"(true, ("X" eq 1) or ("X" eq 2)), true) val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - sequenceOf( - query.yes("X" to 1), - query.yes("X" to 2) + val expected = + fromSequence( + sequenceOf( + query.yes("X" to 1), + query.yes("X" to 2), + ), ) - ) expected.assertingEquals(solutions) } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIfThenElseImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIfThenElseImpl.kt index 65d79e53d..4419d13ec 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIfThenElseImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIfThenElseImpl.kt @@ -9,7 +9,6 @@ class TestConcurrentIfThenElseImpl : TestConcurrentIfThenElse, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testIfTrueElseFail() = multiRunConcurrentTest { super.testIfTrueElseFail() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIfThenImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIfThenImpl.kt index d419e23cd..be49c00a1 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIfThenImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIfThenImpl.kt @@ -9,7 +9,6 @@ class TestConcurrentIfThenImpl : TestConcurrentIfThen, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testIfThenTrue() = multiRunConcurrentTest { super.testIfThenTrue() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentInteger.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentInteger.kt index 29fe1a71b..d6d7f1351 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentInteger.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentInteger.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentInteger : FromSequence, SolverFactory { - fun testIntPositiveNum() { logicProgramming { val solver = solverWithDefaultBuiltins() diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIntegerImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIntegerImpl.kt index 507ac562e..3b3f940d4 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIntegerImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIntegerImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentIntegerImpl : TestConcurrentInteger, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testIntPositiveNum() = multiRunConcurrentTest { super.testIntPositiveNum() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIs.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIs.kt index 11111b433..237d3e1b0 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIs.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIs.kt @@ -11,7 +11,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentIs : FromSequence, SolverFactory { - fun testIsResult() { logicProgramming { val solver = solverWithDefaultBuiltins() @@ -54,16 +53,17 @@ interface TestConcurrentIs : FromSequence, SolverFac val query = intOf(77) `is` "N" val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - Signature("is", 2), - varOf("N"), - index = 1 - ) + val expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + Signature("is", 2), + varOf("N"), + index = 1, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -75,17 +75,18 @@ interface TestConcurrentIs : FromSequence, SolverFac val query = intOf(77) `is` "foo" val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("is", 2), - TypeError.Expected.EVALUABLE, - atomOf("foo"), - index = 1 - ) + val expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("is", 2), + TypeError.Expected.EVALUABLE, + atomOf("foo"), + index = 1, + ), + ), ) - ) expected.assertingEquals(solutions) } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIsImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIsImpl.kt index 1d65ae085..647a68d5d 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIsImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentIsImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentIsImpl : TestConcurrentIs, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testIsResult() = multiRunConcurrentTest { super.testIsResult() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNonVar.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNonVar.kt index 9117af350..d028e34bb 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNonVar.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNonVar.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentNonVar : FromSequence, SolverFactory { - fun testNonVarNumber() { logicProgramming { val solver = solverWithDefaultBuiltins() diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNonVarImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNonVarImpl.kt index 3300662a1..d0a6cafd9 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNonVarImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNonVarImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentNonVarImpl : TestConcurrentNonVar, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testNonVarNumber() = multiRunConcurrentTest { super.testNonVarNumber() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNotProvable.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNotProvable.kt index aac3f8587..a4259d00d 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNotProvable.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNotProvable.kt @@ -11,7 +11,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentNotProvable : FromSequence, SolverFactory { - val errorSignature: Signature fun testNPTrue() { @@ -56,12 +55,13 @@ interface TestConcurrentNotProvable : FromSequence, val query = ((("X" eq 1) or ("X" eq 2)) and "not"(("!" and fail))) val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - sequenceOf( - query.yes("X" to 1), - query.yes("X" to 2) + val expected = + fromSequence( + sequenceOf( + query.yes("X" to 1), + query.yes("X" to 2), + ), ) - ) expected.assertingEquals(solutions) } @@ -85,16 +85,17 @@ interface TestConcurrentNotProvable : FromSequence, val query = "not"(3) val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forGoal( - DummyInstances.executionContext, - errorSignature, - TypeError.Expected.CALLABLE, - numOf(3) - ) + val expected = + fromSequence( + query.halt( + TypeError.forGoal( + DummyInstances.executionContext, + errorSignature, + TypeError.Expected.CALLABLE, + numOf(3), + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -106,15 +107,16 @@ interface TestConcurrentNotProvable : FromSequence, val query = "not"("X") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - InstantiationError.forGoal( - DummyInstances.executionContext, - errorSignature, - varOf("X") - ) + val expected = + fromSequence( + query.halt( + InstantiationError.forGoal( + DummyInstances.executionContext, + errorSignature, + varOf("X"), + ), + ), ) - ) expected.assertingEquals(solutions) } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNotProvableImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNotProvableImpl.kt index 2ff363afb..0cd67a08e 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNotProvableImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNotProvableImpl.kt @@ -9,7 +9,6 @@ class TestConcurrentNotProvableImpl : TestConcurrentNotProvable, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - override val errorSignature: Signature = Signature("ensure_executable", 1) @OptIn(ExperimentalCoroutinesApi::class) diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNotUnify.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNotUnify.kt index 051851494..b6f51293d 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNotUnify.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNotUnify.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentNotUnify : FromSequence, SolverFactory { - fun testNumberNotUnify() { logicProgramming { val solver = solverWithDefaultBuiltins() diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNotUnifyImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNotUnifyImpl.kt index 23ba3385a..a1c9fee10 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNotUnifyImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNotUnifyImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentNotUnifyImpl : TestConcurrentNotUnify, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testNumberNotUnify() = multiRunConcurrentTest { super.testNumberNotUnify() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumber.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumber.kt index 6b331abbf..bf74259c9 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumber.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumber.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentNumber : FromSequence, SolverFactory { - fun testBasicNum() { logicProgramming { val solver = solverWithDefaultBuiltins() diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumberChars.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumberChars.kt index c32d55d4a..51fca052a 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumberChars.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumberChars.kt @@ -9,7 +9,6 @@ import it.unibo.tuprolog.solve.halt import it.unibo.tuprolog.solve.yes interface TestConcurrentNumberChars : FromSequence, SolverFactory { - fun testNumberCharsListIsVar() { logicProgramming { val solver = solverWithDefaultBuiltins() @@ -100,16 +99,17 @@ interface TestConcurrentNumberChars : FromSequence, val query = number_chars("X", "L") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - Signature("number_chars", 2), - varOf("X"), - index = 0 - ) + val expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + Signature("number_chars", 2), + varOf("X"), + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumberCharsImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumberCharsImpl.kt index 7ffd21e1e..bad7cf57b 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumberCharsImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumberCharsImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentNumberCharsImpl : TestConcurrentNumberChars, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testNumberCharsListIsVar() = multiRunConcurrentTest { super.testNumberCharsListIsVar() } @@ -39,5 +38,6 @@ class TestConcurrentNumberCharsImpl : @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testNumberCharsInstantiationError() = multiRunConcurrentTest { super.testNumberCharsInstantiationError() } + override fun testNumberCharsInstantiationError() = + multiRunConcurrentTest { super.testNumberCharsInstantiationError() } } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumberCodes.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumberCodes.kt index 20607ab9e..83f78ea2d 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumberCodes.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumberCodes.kt @@ -9,7 +9,6 @@ import it.unibo.tuprolog.solve.halt import it.unibo.tuprolog.solve.yes interface TestConcurrentNumberCodes : FromSequence, SolverFactory { - fun testNumberCodesListIsVar() { logicProgramming { val solver = solverWithDefaultBuiltins() @@ -88,17 +87,18 @@ interface TestConcurrentNumberCodes : FromSequence, val query = number_codes("a", "L") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("number_codes", 2), - TypeError.Expected.NUMBER, - atomOf("a"), - index = 0 - ) + val expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("number_codes", 2), + TypeError.Expected.NUMBER, + atomOf("a"), + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumberCodesImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumberCodesImpl.kt index c5c304608..3713c2a08 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumberCodesImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumberCodesImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentNumberCodesImpl : TestConcurrentNumberCodes, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testNumberCodesListIsVar() = multiRunConcurrentTest { super.testNumberCodesListIsVar() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumberImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumberImpl.kt index 3a9a56236..1d8bb78aa 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumberImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentNumberImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentNumberImpl : TestConcurrentNumber, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testBasicNum() = multiRunConcurrentTest { super.testBasicNum() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentOr.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentOr.kt index 819e0f3c5..8259226a3 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentOr.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentOr.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentOr : FromSequence, SolverFactory { - fun testTrueOrFalse() { logicProgramming { val solver = solverWithDefaultBuiltins() @@ -61,12 +60,13 @@ interface TestConcurrentOr : FromSequence, SolverFac val query = ("X" eq 1) or ("X" eq 2) val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - sequenceOf( - query.yes("X" to 1), - query.yes("X" to 2) + val expected = + fromSequence( + sequenceOf( + query.yes("X" to 1), + query.yes("X" to 2), + ), ) - ) expected.assertingEquals(solutions) } } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentOrImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentOrImpl.kt index ffaf0b4c5..061b1b937 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentOrImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentOrImpl.kt @@ -9,7 +9,6 @@ class TestConcurrentOrImpl : TestConcurrentOr, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testTrueOrFalse() = multiRunConcurrentTest { super.testTrueOrFalse() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentRepeat.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentRepeat.kt index 09e14b873..941c385a6 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentRepeat.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentRepeat.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.SolverFactory import it.unibo.tuprolog.solve.no interface TestConcurrentRepeat : FromSequence, SolverFactory { - fun testRepeat() { logicProgramming { val solver = solverWithDefaultBuiltins() diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentRepeatImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentRepeatImpl.kt index 1d69e362d..51b34e85b 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentRepeatImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentRepeatImpl.kt @@ -9,7 +9,6 @@ class TestConcurrentRepeatImpl : TestConcurrentRepeat, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // does not terminate when concurrent diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSetOf.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSetOf.kt index 74e9c96e7..534e2bfae 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSetOf.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSetOf.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentSetOf : FromSequence, SolverFactory { - fun testSetOfBasic() { logicProgramming { val solver = solverWithDefaultBuiltins() diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSetOfImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSetOfImpl.kt index e04928823..eaada2fd5 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSetOfImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSetOfImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentSetOfImpl : TestConcurrentSetOf, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testSetOfBasic() = multiRunConcurrentTest { super.testSetOfBasic() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSolutionPresentation.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSolutionPresentation.kt index fed8e2a9a..7da9d33b5 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSolutionPresentation.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSolutionPresentation.kt @@ -8,12 +8,12 @@ import kotlin.test.assertEquals import kotlin.test.assertTrue interface TestConcurrentSolutionPresentation : FromSequence, SolverFactory { - fun testSolutionWithDandlingVars() { logicProgramming { - val theory = theoryOf( - fact { "append"("seq"(X), X) } - ) + val theory = + theoryOf( + fact { "append"("seq"(X), X) }, + ) val solver = solverOf(staticKb = theory) val query = "append"(A, B) val sol = solver.solveOnce(query) diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSolutionPresentationImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSolutionPresentationImpl.kt index 34f83d69c..7f436257c 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSolutionPresentationImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSolutionPresentationImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentSolutionPresentationImpl : TestConcurrentSolutionPresentation, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testSolutionWithDandlingVars() = multiRunConcurrentTest { super.testSolutionWithDandlingVars() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSolver.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSolver.kt index 9f71ff793..cc3b63032 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSolver.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSolver.kt @@ -58,71 +58,79 @@ import it.unibo.tuprolog.solve.yes import kotlin.test.assertEquals import kotlin.test.assertTrue +@Suppress("LongMethod", "LargeClass", "CyclomaticComplexMethod") interface TestConcurrentSolver : FromSequence, SolverFactory { - val callErrorSignature: Signature val nafErrorSignature: Signature val notErrorSignature: Signature fun testUnknownFlag2() { logicProgramming { - val theory = theoryOf( - rule { - "ancestor"(X, Y) `if` "parent"(X, Y) - }, - rule { - "ancestor"(X, Y) `if` ("parent"(X, Z) and "ancestor"(Z, Y)) - }, - fact { "parent"("abraham", "isaac") }, - fact { "parent"("isaac", "jacob") }, - fact { "parent"("jacob", "joseph") } - ) + val theory = + theoryOf( + rule { + "ancestor"(X, Y) `if` "parent"(X, Y) + }, + rule { + "ancestor"(X, Y) `if` ("parent"(X, Z) and "ancestor"(Z, Y)) + }, + fact { "parent"("abraham", "isaac") }, + fact { "parent"("isaac", "jacob") }, + fact { "parent"("jacob", "joseph") }, + ) val observedWarnings = mutableListOf() - var solver = solverWithDefaultBuiltins( - staticKb = theory, - flags = FlagStore.of(Unknown to Unknown.WARNING), - warnings = OutputChannel.of { - observedWarnings.add(it) - } - ) + var solver = + solverWithDefaultBuiltins( + staticKb = theory, + flags = FlagStore.of(Unknown to Unknown.WARNING), + warnings = + OutputChannel.of { + observedWarnings.add(it) + }, + ) val query = "ancestor"("abraham", X) var solutions = fromSequence(solver.solve(query)) - val expected = fromSequence( - sequenceOf( - query.yes(X to "isaac"), - query.yes(X to "jacob"), - query.yes(X to "joseph"), - query.no() + val expected = + fromSequence( + sequenceOf( + query.yes(X to "isaac"), + query.yes(X to "jacob"), + query.yes(X to "joseph"), + query.no(), + ), ) - ) expected.assertingEquals(solutions) assertEquals(mutableListOf(), observedWarnings) - solver = solverWithDefaultBuiltins( - staticKb = theory, - flags = FlagStore.of(Unknown to Unknown.ERROR), - warnings = OutputChannel.of { - observedWarnings.add(it) - } - ) + solver = + solverWithDefaultBuiltins( + staticKb = theory, + flags = FlagStore.of(Unknown to Unknown.ERROR), + warnings = + OutputChannel.of { + observedWarnings.add(it) + }, + ) solutions = fromSequence(solver.solve(query)) expected.assertingEquals(solutions) assertEquals(mutableListOf(), observedWarnings) - solver = solverWithDefaultBuiltins( - staticKb = theory, - flags = FlagStore.of(Unknown to Unknown.FAIL), - warnings = OutputChannel.of { - observedWarnings.add(it) - } - ) + solver = + solverWithDefaultBuiltins( + staticKb = theory, + flags = FlagStore.of(Unknown to Unknown.FAIL), + warnings = + OutputChannel.of { + observedWarnings.add(it) + }, + ) solutions = fromSequence(solver.solve(query)) expected.assertingEquals(solutions) @@ -136,32 +144,37 @@ interface TestConcurrentSolver : FromSequence, Solve val observedWarnings = mutableListOf() - var solver = solverWithDefaultBuiltins( - flags = FlagStore.of(Unknown to Unknown.ERROR), - warnings = OutputChannel.of { - observedWarnings.add(it) - } - ) + var solver = + solverWithDefaultBuiltins( + flags = FlagStore.of(Unknown to Unknown.ERROR), + warnings = + OutputChannel.of { + observedWarnings.add(it) + }, + ) var solutions = fromSequence(solver.solve(query)) - var expected = fromSequence( - query.halt( - ExistenceError.forProcedure( - DummyInstances.executionContext, - query.extractSignature() - ) + var expected = + fromSequence( + query.halt( + ExistenceError.forProcedure( + DummyInstances.executionContext, + query.extractSignature(), + ), + ), ) - ) expected.assertingEquals(solutions) assertTrue { observedWarnings.isEmpty() } - solver = solverWithDefaultBuiltins( - flags = FlagStore.of(Unknown to Unknown.WARNING), - warnings = OutputChannel.of { - observedWarnings.add(it) - } - ) + solver = + solverWithDefaultBuiltins( + flags = FlagStore.of(Unknown to Unknown.WARNING), + warnings = + OutputChannel.of { + observedWarnings.add(it) + }, + ) solutions = fromSequence(solver.solve(query)) expected = fromSequence(query.no()) @@ -171,12 +184,14 @@ interface TestConcurrentSolver : FromSequence, Solve assertTrue { observedWarnings[0] is MissingPredicate } assertEquals(query.extractSignature(), (observedWarnings[0] as MissingPredicate).signature) - solver = solverWithDefaultBuiltins( - flags = FlagStore.of(Unknown to Unknown.FAIL), - warnings = OutputChannel.of { - observedWarnings.add(it) - } - ) + solver = + solverWithDefaultBuiltins( + flags = FlagStore.of(Unknown to Unknown.FAIL), + warnings = + OutputChannel.of { + observedWarnings.add(it) + }, + ) solutions = fromSequence(solver.solve(query)) expected = fromSequence(query.no()) @@ -278,15 +293,19 @@ interface TestConcurrentSolver : FromSequence, Solve } } - private fun testAssert(suffix: String, inverse: Boolean) { + private fun testAssert( + suffix: String, + inverse: Boolean, + ) { logicProgramming { val solver = solverWithDefaultBuiltins() val assertX = "assert$suffix" - val query = assertX("f"(1)) and - assertX("f"(2)) and - assertX("f"(3)) and - "f"(X) + val query = + assertX("f"(1)) and + assertX("f"(2)) and + assertX("f"(3)) and + "f"(X) val solutions = solver.solve(query, mediumDuration).toList() val ints = if (inverse) (3 downTo 1) else (1..3) @@ -320,14 +339,15 @@ interface TestConcurrentSolver : FromSequence, Solve solver.standardOutput.addListener { outputs += it!! } - val terms = ktListOf( - atomOf("atom"), - atomOf("a string"), - varOf("A_Var"), - numOf(1), - numOf(2.1), - "f"("x") - ) + val terms = + ktListOf( + atomOf("atom"), + atomOf("a string"), + varOf("A_Var"), + numOf(1), + numOf(2.1), + "f"("x"), + ) val query = tupleOf(terms.map { write(it) }.append(nl)) @@ -338,7 +358,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertEquals( terms.map { it.format(TermFormatter.default()) }.append("\n"), - outputs + outputs, ) } } @@ -364,20 +384,22 @@ interface TestConcurrentSolver : FromSequence, Solve assertEquals( ktListOf("a", "b", "c", "d", "\n", "e"), - outputs + outputs, ) } } fun testFindAll() { logicProgramming { - val solver = solverWithDefaultBuiltins( - staticKb = theoryOf( - fact { "a"(1) }, - fact { "a"(2) }, - fact { "a"(3) } + val solver = + solverWithDefaultBuiltins( + staticKb = + theoryOf( + fact { "a"(1) }, + fact { "a"(2) }, + fact { "a"(3) }, + ), ) - ) var query = findall(N, "a"(N), L) @@ -394,16 +416,17 @@ interface TestConcurrentSolver : FromSequence, Solve query = findall(`_`, G, `_`) solutions = fromSequence(solver.solve(query, mediumDuration)) - expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - Signature("findall", 3), - variable = G, - index = 1 - ) + expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + Signature("findall", 3), + variable = G, + index = 1, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -411,35 +434,39 @@ interface TestConcurrentSolver : FromSequence, Solve fun testSideEffectsPersistentAfterBacktracking1() { logicProgramming { - val solver = solverWithDefaultBuiltins( - dynamicKb = theoryOf( - fact { "f"(1) }, - fact { "f"(2) }, - fact { "f"(3) } - ), - staticKb = theoryOf( - clause { "getf"(F) `if` findall(X, "f"(X), F) }, - clause { "getg"(G) `if` findall(X, "g"(X), G) }, - clause { - "ftog"(F, G) `if` ( - retract("f"(X)) and - assert("g"(X)) and - "getf"(F) and - "getg"(G) - ) - } + val solver = + solverWithDefaultBuiltins( + dynamicKb = + theoryOf( + fact { "f"(1) }, + fact { "f"(2) }, + fact { "f"(3) }, + ), + staticKb = + theoryOf( + clause { "getf"(F) `if` findall(X, "f"(X), F) }, + clause { "getg"(G) `if` findall(X, "g"(X), G) }, + clause { + "ftog"(F, G) `if` ( + retract("f"(X)) and + assert("g"(X)) and + "getf"(F) and + "getg"(G) + ) + }, + ), ) - ) val query = "ftog"(X, Y) val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - sequenceOf( - query.yes(X to listOf(2, 3), Y to listOf(1)), - query.yes(X to listOf(3), Y to listOf(1, 2)), - query.yes(X to emptyList, Y to listOf(1, 2, 3)) + val expected = + fromSequence( + sequenceOf( + query.yes(X to listOf(2, 3), Y to listOf(1)), + query.yes(X to listOf(3), Y to listOf(1, 2)), + query.yes(X to emptyList, Y to listOf(1, 2, 3)), + ), ) - ) expected.assertingEquals(solutions) } @@ -450,8 +477,8 @@ interface TestConcurrentSolver : FromSequence, Solve logicProgramming { val solver = solverWithDefaultBuiltins() val query = truthOf(true) - var solutions = fromSequence(solver.solve(query, mediumDuration)) - var expected = fromSequence(query.yes()) + val solutions = fromSequence(solver.solve(query, mediumDuration)) + val expected = fromSequence(query.yes()) expected.assertingEquals(solutions) } @@ -460,44 +487,48 @@ interface TestConcurrentSolver : FromSequence, Solve /** Test with [lessThan500MsGoalToSolution] */ fun testTimeout1() { assertConcurrentSolverSolutionsCorrect( - solver = solverWithDefaultBuiltins( - staticKb = TimeRelatedTheories.timeRelatedTheory - ), + solver = + solverWithDefaultBuiltins( + staticKb = TimeRelatedTheories.timeRelatedTheory, + ), goalToSolutions = lessThan500MsGoalToSolution, - maxDuration = 400L + maxDuration = 400L, ) } /** Test with [slightlyMoreThan500MsGoalToSolution] */ fun testTimeout2() { assertConcurrentSolverSolutionsCorrect( - solver = solverWithDefaultBuiltins( - staticKb = TimeRelatedTheories.timeRelatedTheory - ), + solver = + solverWithDefaultBuiltins( + staticKb = TimeRelatedTheories.timeRelatedTheory, + ), goalToSolutions = slightlyMoreThan500MsGoalToSolution, - maxDuration = 599L + maxDuration = 599L, ) } /** Test with [slightlyMoreThan600MsGoalToSolution] */ fun testTimeout3() { assertConcurrentSolverSolutionsCorrect( - solver = solverWithDefaultBuiltins( - staticKb = TimeRelatedTheories.timeRelatedTheory - ), + solver = + solverWithDefaultBuiltins( + staticKb = TimeRelatedTheories.timeRelatedTheory, + ), goalToSolutions = slightlyMoreThan600MsGoalToSolution, - maxDuration = 699L + maxDuration = 699L, ) } /** Test with [slightlyMoreThan700MsGoalToSolution] */ fun testTimeout4() { assertConcurrentSolverSolutionsCorrect( - solver = solverWithDefaultBuiltins( - staticKb = TimeRelatedTheories.timeRelatedTheory - ), + solver = + solverWithDefaultBuiltins( + staticKb = TimeRelatedTheories.timeRelatedTheory, + ), goalToSolutions = slightlyMoreThan700MsGoalToSolution, - maxDuration = 799L + maxDuration = 799L, ) } @@ -506,7 +537,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solver = solverWithDefaultBuiltins(staticKb = CustomTheories.ifThenTheory1), goalToSolutions = ifThen1ToSolution, - maxDuration = mediumDuration + maxDuration = mediumDuration, ) } @@ -515,7 +546,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solver = solverWithDefaultBuiltins(staticKb = CustomTheories.ifThenTheory1), goalToSolutions = ifThenElse1ToSolution, - maxDuration = mediumDuration + maxDuration = mediumDuration, ) } @@ -524,7 +555,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solver = solverWithDefaultBuiltins(staticKb = CustomTheories.ifThenTheory2), goalToSolutions = ifThenElse2ToSolution, - maxDuration = mediumDuration + maxDuration = mediumDuration, ) } @@ -533,7 +564,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solver = solverWithDefaultBuiltins(staticKb = CustomTheories.ifThenTheory2), goalToSolutions = ifThen2ToSolution, - maxDuration = mediumDuration + maxDuration = mediumDuration, ) } @@ -542,7 +573,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(staticKb = TestingClauseTheories.simpleFactTheory), simpleFactTheoryNotableGoalToSolutions, - mediumDuration + mediumDuration, ) } @@ -551,7 +582,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(staticKb = TestingClauseTheories.simpleCutTheory), simpleCutTheoryNotableGoalToSolutions, - mediumDuration + mediumDuration, ) } @@ -560,7 +591,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(staticKb = TestingClauseTheories.simpleCutAndConjunctionTheory), simpleCutAndConjunctionTheoryNotableGoalToSolutions, - mediumDuration + mediumDuration, ) } @@ -569,7 +600,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(staticKb = TestingClauseTheories.cutConjunctionAndBacktrackingTheory), cutConjunctionAndBacktrackingTheoryNotableGoalToSolutions, - mediumDuration + mediumDuration, ) } @@ -578,7 +609,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(staticKb = TestingClauseTheories.infiniteComputationTheory), infiniteComputationTheoryNotableGoalToSolution, - shortDuration + shortDuration, ) } @@ -587,7 +618,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(staticKb = PrologStandardExampleTheories.prologStandardExampleTheory), prologStandardExampleTheoryNotableGoalToSolution, - mediumDuration + mediumDuration, ) } @@ -596,7 +627,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(staticKb = PrologStandardExampleTheories.prologStandardExampleWithCutTheory), prologStandardExampleWithCutTheoryNotableGoalToSolution, - mediumDuration + mediumDuration, ) } @@ -605,7 +636,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(staticKb = TestingClauseTheories.customReverseListTheory), customReverseListTheoryNotableGoalToSolution, - mediumDuration + mediumDuration, ) } @@ -614,7 +645,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(staticKb = PrologStandardExampleTheories.conjunctionStandardExampleTheory), conjunctionStandardExampleTheoryNotableGoalToSolution, - mediumDuration + mediumDuration, ) } @@ -625,14 +656,13 @@ interface TestConcurrentSolver : FromSequence, Solve TestingClauseTheories.allPrologTestingTheoriesToRespectiveGoalsAndSolutions( callErrorSignature, nafErrorSignature, - notErrorSignature + notErrorSignature, ) .mapValues { (_, listOfGoalToSolutions) -> listOfGoalToSolutions.flatMap { (goal, expectedSolutions) -> ktListOf( (goal and true).run { to(expectedSolutions.changeQueriesTo(this)) }, (true and goal).run { to(expectedSolutions.changeQueriesTo(this)) }, - (goal and false).run { when { expectedSolutions.any { it is Solution.Halt } -> @@ -640,8 +670,7 @@ interface TestConcurrentSolver : FromSequence, Solve else -> hasSolutions({ no() }) } }, - - (false and goal).hasSolutions({ no() }) + (false and goal).hasSolutions({ no() }), ) } } @@ -651,7 +680,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(staticKb = database), goalToSolutions, - mediumDuration + mediumDuration, ) } } @@ -662,13 +691,13 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(staticKb = PrologStandardExampleTheories.callStandardExampleTheory), callStandardExampleTheoryGoalsToSolution(callErrorSignature), - mediumDuration + mediumDuration, ) assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(), callTestingGoalsToSolutions(callErrorSignature), - mediumDuration + mediumDuration, ) } @@ -678,7 +707,7 @@ interface TestConcurrentSolver : FromSequence, Solve TestingClauseTheories.allPrologTestingTheoriesToRespectiveGoalsAndSolutions( callErrorSignature, nafErrorSignature, - notErrorSignature + notErrorSignature, ) .mapValues { (_, listOfGoalToSolutions) -> listOfGoalToSolutions.map { (goal, expectedSolutions) -> @@ -688,39 +717,42 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(staticKb = database), goalToSolutions, - mediumDuration + mediumDuration, ) } } } - /** Call primitive testing with [catchTestingGoalsToSolutions] and [catchAndThrowTheoryExampleNotableGoalToSolution] */ + /** + * Call primitive testing with [catchTestingGoalsToSolutions] and [catchAndThrowTheoryExampleNotableGoalToSolution] + * */ fun testCatchPrimitive() { assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(staticKb = PrologStandardExampleTheories.catchAndThrowTheoryExample), catchAndThrowTheoryExampleNotableGoalToSolution, - mediumDuration + mediumDuration, ) assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(), catchTestingGoalsToSolutions, - mediumDuration + mediumDuration, ) } /** A test in which all testing goals are called through the Catch primitive */ fun testCatchPrimitiveTransparency() { logicProgramming { - fun Struct.containsHaltPrimitive(): Boolean = when (functor) { - "halt" -> true - else -> argsSequence.filterIsInstance().any { it.containsHaltPrimitive() } - } + fun Struct.containsHaltPrimitive(): Boolean = + when (functor) { + "halt" -> true + else -> argsSequence.filterIsInstance().any { it.containsHaltPrimitive() } + } TestingClauseTheories.allPrologTestingTheoriesToRespectiveGoalsAndSolutions( callErrorSignature, nafErrorSignature, - notErrorSignature + notErrorSignature, ) .mapValues { (_, listOfGoalToSolutions) -> listOfGoalToSolutions.flatMap { (goal, expectedSolutions) -> @@ -737,14 +769,14 @@ interface TestConcurrentSolver : FromSequence, Solve }, `catch`(goal, "notUnifyingCatcher", false).run { to(expectedSolutions.changeQueriesTo(this)) - } + }, ) } }.forEach { (database, goalToSolutions) -> assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(staticKb = database), goalToSolutions, - mediumDuration + mediumDuration, ) } } @@ -755,7 +787,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(), haltTestingGoalsToSolutions, - mediumDuration + mediumDuration, ) } @@ -764,7 +796,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(staticKb = PrologStandardExampleTheories.notStandardExampleTheory), notStandardExampleTheoryNotableGoalToSolution(nafErrorSignature, notErrorSignature), - mediumDuration + mediumDuration, ) } @@ -774,7 +806,7 @@ interface TestConcurrentSolver : FromSequence, Solve TestingClauseTheories.allPrologTestingTheoriesToRespectiveGoalsAndSolutions( callErrorSignature, nafErrorSignature, - notErrorSignature + notErrorSignature, ) .mapValues { (_, listOfGoalToSolutions) -> listOfGoalToSolutions.flatMap { (goal, expectedSolutions) -> @@ -806,14 +838,14 @@ interface TestConcurrentSolver : FromSequence, Solve expectedSolutions.first() is Solution.No -> hasSolutions({ no() }) else -> to(expectedSolutions.changeQueriesTo(this)) } - } + }, ) } }.forEach { (database, goalToSolutions) -> assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(staticKb = database), goalToSolutions, - mediumDuration + mediumDuration, ) } } @@ -824,7 +856,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(staticKb = PrologStandardExampleTheories.ifThenStandardExampleTheory), ifThenStandardExampleTheoryNotableGoalToSolution, - mediumDuration + mediumDuration, ) } @@ -833,7 +865,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(), ifThenElseStandardExampleNotableGoalToSolution, - mediumDuration + mediumDuration, ) } @@ -842,7 +874,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(staticKb = TestingClauseTheories.customRangeListGeneratorTheory), customRangeListGeneratorTheoryNotableGoalToSolution, - mediumDuration + mediumDuration, ) } @@ -860,16 +892,18 @@ interface TestConcurrentSolver : FromSequence, Solve fun testBasicBacktracking1() { logicProgramming { - val solver = solverWithDefaultBuiltins( - staticKb = theory( - { "a"(X) impliedBy ("b"(X) and "c"(X)) }, - { "b"(1) }, - { "b"(2) impliedBy cut }, - { "b"(3) }, - { "c"(2) }, - { "c"(3) } + val solver = + solverWithDefaultBuiltins( + staticKb = + theory( + { "a"(X) impliedBy ("b"(X) and "c"(X)) }, + { "b"(1) }, + { "b"(2) impliedBy cut }, + { "b"(3) }, + { "c"(2) }, + { "c"(3) }, + ), ) - ) val query = "a"(N) val solutions = fromSequence(solver.solve(query, mediumDuration)) val expected = fromSequence(query.yes(N to 2)) @@ -880,15 +914,17 @@ interface TestConcurrentSolver : FromSequence, Solve fun testBasicBacktracking2() { logicProgramming { - val solver = solverWithDefaultBuiltins( - staticKb = theory( - { "a"(X) impliedBy ("c"(X) and "b"(X)) }, - { "b"(2) impliedBy cut }, - { "b"(3) }, - { "c"(3) }, - { "c"(2) } + val solver = + solverWithDefaultBuiltins( + staticKb = + theory( + { "a"(X) impliedBy ("c"(X) and "b"(X)) }, + { "b"(2) impliedBy cut }, + { "b"(3) }, + { "c"(3) }, + { "c"(2) }, + ), ) - ) val query = "a"(N) val solutions = fromSequence(solver.solve(query, mediumDuration)) val expected = fromSequence(sequenceOf(query.yes(N to 3), query.yes(N to 2))) @@ -899,15 +935,17 @@ interface TestConcurrentSolver : FromSequence, Solve fun testBasicBacktracking3() { logicProgramming { - val solver = solverWithDefaultBuiltins( - staticKb = theory( - { "a"(X) impliedBy (("b"(X) and cut) and "c"(X)) }, - { "b"(2) }, - { "b"(3) }, - { "c"(2) }, - { "c"(3) } + val solver = + solverWithDefaultBuiltins( + staticKb = + theory( + { "a"(X) impliedBy (("b"(X) and cut) and "c"(X)) }, + { "b"(2) }, + { "b"(3) }, + { "c"(2) }, + { "c"(3) }, + ), ) - ) val query = "a"(N) val solutions = fromSequence(solver.solve(query, mediumDuration)) val expected = fromSequence(query.yes(N to 2)) @@ -918,15 +956,17 @@ interface TestConcurrentSolver : FromSequence, Solve fun testBasicBacktracking4() { logicProgramming { - val solver = solverWithDefaultBuiltins( - staticKb = theory( - { "a"(X) impliedBy ("b"(X) and (cut and "c"(X))) }, - { "b"(2) }, - { "b"(3) }, - { "c"(2) }, - { "c"(3) } + val solver = + solverWithDefaultBuiltins( + staticKb = + theory( + { "a"(X) impliedBy ("b"(X) and (cut and "c"(X))) }, + { "b"(2) }, + { "b"(3) }, + { "c"(2) }, + { "c"(3) }, + ), ) - ) val query = "a"(N) val solutions = fromSequence(solver.solve(query, mediumDuration)) val expected = fromSequence(query.yes(N to 2)) @@ -937,13 +977,15 @@ interface TestConcurrentSolver : FromSequence, Solve fun testConjunction() { logicProgramming { - val solver = solverWithDefaultBuiltins( - staticKb = theory( - { "a" impliedBy ("b" and "c") }, - { "b" }, - { "c" } + val solver = + solverWithDefaultBuiltins( + staticKb = + theory( + { "a" impliedBy ("b" and "c") }, + { "b" }, + { "c" }, + ), ) - ) val query = atomOf("a") val solutions = fromSequence(solver.solve(query, mediumDuration)) val expected = fromSequence(query.yes()) @@ -954,15 +996,17 @@ interface TestConcurrentSolver : FromSequence, Solve fun testConjunctionOfConjunctions() { logicProgramming { - val solver = solverWithDefaultBuiltins( - staticKb = theory( - { "a" impliedBy (tupleOf("b", "c") and tupleOf("d", "e")) }, - { "b" }, - { "c" }, - { "d" }, - { "e" } + val solver = + solverWithDefaultBuiltins( + staticKb = + theory( + { "a" impliedBy (tupleOf("b", "c") and tupleOf("d", "e")) }, + { "b" }, + { "c" }, + { "d" }, + { "e" }, + ), ) - ) val query = atomOf("a") val solutions = fromSequence(solver.solve(query, mediumDuration)) val expected = fromSequence(query.yes()) @@ -973,13 +1017,15 @@ interface TestConcurrentSolver : FromSequence, Solve fun testConjunctionWithUnification() { logicProgramming { - val solver = solverWithDefaultBuiltins( - staticKb = theory( - { "a"(X) impliedBy ("b"(X) and "c"(X)) }, - { "b"(1) }, - { "c"(1) } + val solver = + solverWithDefaultBuiltins( + staticKb = + theory( + { "a"(X) impliedBy ("b"(X) and "c"(X)) }, + { "b"(1) }, + { "c"(1) }, + ), ) - ) val query = "a"(N) val solutions = fromSequence(solver.solve(query, mediumDuration)) val expected = fromSequence(query.yes(N to 1)) @@ -990,13 +1036,15 @@ interface TestConcurrentSolver : FromSequence, Solve fun testDisjunction() { logicProgramming { - val solver = solverWithDefaultBuiltins( - staticKb = theory( - { "a" impliedBy ("b" or "c") }, - { "b" }, - { "c" } + val solver = + solverWithDefaultBuiltins( + staticKb = + theory( + { "a" impliedBy ("b" or "c") }, + { "b" }, + { "c" }, + ), ) - ) val query = atomOf("a") val solutions = fromSequence(solver.solve(query, mediumDuration)) val expected = fromSequence(sequenceOf(query.yes(), query.yes())) @@ -1007,13 +1055,15 @@ interface TestConcurrentSolver : FromSequence, Solve fun testDisjunctionWithUnification() { logicProgramming { - val solver = solverWithDefaultBuiltins( - staticKb = theory( - { "a"(X) impliedBy ("b"(X) or "c"(X)) }, - { "b"(1) }, - { "c"(2) } + val solver = + solverWithDefaultBuiltins( + staticKb = + theory( + { "a"(X) impliedBy ("b"(X) or "c"(X)) }, + { "b"(1) }, + { "c"(2) }, + ), ) - ) val query = "a"(N) val solutions = fromSequence(solver.solve(query, mediumDuration)) val expected = fromSequence(sequenceOf(query.yes(N to 1), query.yes(N to 2))) @@ -1044,21 +1094,23 @@ interface TestConcurrentSolver : FromSequence, Solve assertEquals( ktListOf( factOf(structOf("f", numOf(1))), - ruleOf(structOf("f", numOf(2)), atomOf("false")) + ruleOf(structOf("f", numOf(2)), atomOf("false")), ), - solver.dynamicKb.toList() + solver.dynamicKb.toList(), ) } } fun testRetract() { logicProgramming { - val solver = solverWithDefaultBuiltins( - dynamicKb = theoryOf( - factOf(structOf("f", numOf(1))), - ruleOf(structOf("f", numOf(2)), atomOf("false")) + val solver = + solverWithDefaultBuiltins( + dynamicKb = + theoryOf( + factOf(structOf("f", numOf(1))), + ruleOf(structOf("f", numOf(2)), atomOf("false")), + ), ) - ) val query = retract("f"(X)) // retract(f(X)) @@ -1069,7 +1121,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertEquals( ktListOf(), - solver.dynamicKb.toList() + solver.dynamicKb.toList(), ) assertEquals(0L, solver.dynamicKb.size) } @@ -1125,33 +1177,35 @@ interface TestConcurrentSolver : FromSequence, Solve query = functor(X, Y, 2) solutions = fromSequence(solver.solve(query, mediumDuration)) - expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - Signature("functor", 3), - variable = Y, - index = 1 - ) + expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + Signature("functor", 3), + variable = Y, + index = 1, + ), + ), ) - ) expected.assertingEquals(solutions) query = functor(X, "a", "2") solutions = fromSequence(solver.solve(query, mediumDuration)) - expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("functor", 3), - TypeError.Expected.INTEGER, - atomOf("2"), - 2 - ) + expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("functor", 3), + TypeError.Expected.INTEGER, + atomOf("2"), + 2, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -1178,33 +1232,35 @@ interface TestConcurrentSolver : FromSequence, Solve query = X univ Y solutions = fromSequence(solver.solve(query, mediumDuration)) - expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - Signature("=..", 2), - variable = X, - index = 0 - ) + expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + Signature("=..", 2), + variable = X, + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) query = "a"("b", "c") univ "a" solutions = fromSequence(solver.solve(query, mediumDuration)) - expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("=..", 2), - TypeError.Expected.LIST, - atomOf("a"), - 1 - ) + expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("=..", 2), + TypeError.Expected.LIST, + atomOf("a"), + 1, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -1212,12 +1268,14 @@ interface TestConcurrentSolver : FromSequence, Solve fun testRetractAll() { logicProgramming { - val solver = solverWithDefaultBuiltins( - dynamicKb = theoryOf( - factOf(structOf("f", numOf(1))), - ruleOf(structOf("f", numOf(2)), atomOf("false")) + val solver = + solverWithDefaultBuiltins( + dynamicKb = + theoryOf( + factOf(structOf("f", numOf(1))), + ruleOf(structOf("f", numOf(2)), atomOf("false")), + ), ) - ) var query = retractall("f"(X)) @@ -1228,7 +1286,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertEquals( ktListOf(), - solver.dynamicKb.toList() + solver.dynamicKb.toList(), ) assertEquals(0L, solver.dynamicKb.size) @@ -1269,17 +1327,18 @@ interface TestConcurrentSolver : FromSequence, Solve query = append(X, Y, listOf(1, 2, 3, 4, 5, 6)) solutions = fromSequence(solver.solve(query, mediumDuration)) - expected = fromSequence( - sequenceOf( - query.yes(X to emptyList, Y to listOf(1, 2, 3, 4, 5, 6)), - query.yes(X to listOf(1), Y to listOf(2, 3, 4, 5, 6)), - query.yes(X to listOf(1, 2), Y to listOf(3, 4, 5, 6)), - query.yes(X to listOf(1, 2, 3), Y to listOf(4, 5, 6)), - query.yes(X to listOf(1, 2, 3, 4), Y to listOf(5, 6)), - query.yes(X to listOf(1, 2, 3, 4, 5), Y to listOf(6)), - query.yes(X to listOf(1, 2, 3, 4, 5, 6), Y to emptyList) + expected = + fromSequence( + sequenceOf( + query.yes(X to emptyList, Y to listOf(1, 2, 3, 4, 5, 6)), + query.yes(X to listOf(1), Y to listOf(2, 3, 4, 5, 6)), + query.yes(X to listOf(1, 2), Y to listOf(3, 4, 5, 6)), + query.yes(X to listOf(1, 2, 3), Y to listOf(4, 5, 6)), + query.yes(X to listOf(1, 2, 3, 4), Y to listOf(5, 6)), + query.yes(X to listOf(1, 2, 3, 4, 5), Y to listOf(6)), + query.yes(X to listOf(1, 2, 3, 4, 5, 6), Y to emptyList), + ), ) - ) expected.assertingEquals(solutions) } @@ -1289,7 +1348,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(), TestingTermOperators.greaterThanTesting, - mediumDuration + mediumDuration, ) } @@ -1297,7 +1356,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(), TestingTermOperators.greaterThanOrEqualTesting, - mediumDuration + mediumDuration, ) } @@ -1305,7 +1364,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(), TestingTermOperators.equalTesting, - mediumDuration + mediumDuration, ) } @@ -1313,7 +1372,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(), TestingTermOperators.notEqualTesting, - mediumDuration + mediumDuration, ) } @@ -1321,7 +1380,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(), TestingTermOperators.lowerThanTesting, - mediumDuration + mediumDuration, ) } @@ -1329,7 +1388,7 @@ interface TestConcurrentSolver : FromSequence, Solve assertConcurrentSolverSolutionsCorrect( solverWithDefaultBuiltins(), TestingTermOperators.lowerThanOrEqualTesting, - mediumDuration + mediumDuration, ) } } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSolverImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSolverImpl.kt index a3044d127..99f077f6b 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSolverImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSolverImpl.kt @@ -10,7 +10,6 @@ class TestConcurrentSolverImpl : TestConcurrentSolver, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - override val callErrorSignature: Signature = Signature("ensure_executable", 1) override val nafErrorSignature: Signature = Signature("ensure_executable", 1) override val notErrorSignature: Signature = Signature("ensure_executable", 1) @@ -21,412 +20,474 @@ class TestConcurrentSolverImpl : @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testUnknownFlag1() = multiRunConcurrentTest { - super.testUnknownFlag1() - } + override fun testUnknownFlag1() = + multiRunConcurrentTest { + super.testUnknownFlag1() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // Side effects need to be implemented - override fun testSideEffectsPersistentAfterBacktracking1() = multiRunConcurrentTest { - super.testSideEffectsPersistentAfterBacktracking1() - } + override fun testSideEffectsPersistentAfterBacktracking1() = + multiRunConcurrentTest { + super.testSideEffectsPersistentAfterBacktracking1() + } @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testFindAll() = multiRunConcurrentTest { - super.testFindAll() - } + override fun testFindAll() = + multiRunConcurrentTest { + super.testFindAll() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // Assert need to be implemented - override fun testAssert() = multiRunConcurrentTest { - super.testAssert() - } + override fun testAssert() = + multiRunConcurrentTest { + super.testAssert() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // Assert need to be implemented - override fun testAssertZ() = multiRunConcurrentTest { - super.testAssertZ() - } + override fun testAssertZ() = + multiRunConcurrentTest { + super.testAssertZ() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // Assert need to be implemented - override fun testAssertA() = multiRunConcurrentTest { - super.testAssertA() - } + override fun testAssertA() = + multiRunConcurrentTest { + super.testAssertA() + } @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testWrite() = multiRunConcurrentTest { - super.testWrite() - } + override fun testWrite() = + multiRunConcurrentTest { + super.testWrite() + } @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testStandardOutput() = multiRunConcurrentTest { - super.testStandardOutput() - } + override fun testStandardOutput() = + multiRunConcurrentTest { + super.testStandardOutput() + } @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testTrue() = multiRunConcurrentTest { - super.testTrue() - } + override fun testTrue() = + multiRunConcurrentTest { + super.testTrue() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // Cut need to be implemented - override fun testIfThen1() = multiRunConcurrentTest { - super.testIfThen1() - } + override fun testIfThen1() = + multiRunConcurrentTest { + super.testIfThen1() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // Cut need to be implemented - override fun testIfThen2() = multiRunConcurrentTest { - super.testIfThen2() - } + override fun testIfThen2() = + multiRunConcurrentTest { + super.testIfThen2() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // Cut need to be implemented - override fun testIfThenElse1() = multiRunConcurrentTest { - super.testIfThenElse1() - } + override fun testIfThenElse1() = + multiRunConcurrentTest { + super.testIfThenElse1() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // Cut need to be implemented - override fun testIfThenElse2() = multiRunConcurrentTest { - super.testIfThenElse2() - } + override fun testIfThenElse2() = + multiRunConcurrentTest { + super.testIfThenElse2() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // unhandled sleep - override fun testTimeout1() = multiRunConcurrentTest { - super.testTimeout1() - } + override fun testTimeout1() = + multiRunConcurrentTest { + super.testTimeout1() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // unhandled sleep - override fun testTimeout2() = multiRunConcurrentTest { - super.testTimeout2() - } + override fun testTimeout2() = + multiRunConcurrentTest { + super.testTimeout2() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // unhandled sleep - override fun testTimeout3() = multiRunConcurrentTest { - super.testTimeout3() - } + override fun testTimeout3() = + multiRunConcurrentTest { + super.testTimeout3() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // unhandled sleep - override fun testTimeout4() = multiRunConcurrentTest { - super.testTimeout4() - } + override fun testTimeout4() = + multiRunConcurrentTest { + super.testTimeout4() + } @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testUnification() = multiRunConcurrentTest { - super.testUnification() - } + override fun testUnification() = + multiRunConcurrentTest { + super.testUnification() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // Cut need to be implemented - override fun testSimpleCutAlternatives() = multiRunConcurrentTest { - super.testSimpleCutAlternatives() - } + override fun testSimpleCutAlternatives() = + multiRunConcurrentTest { + super.testSimpleCutAlternatives() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // Cut need to be implemented - override fun testCutAndConjunction() = multiRunConcurrentTest { - super.testCutAndConjunction() - } + override fun testCutAndConjunction() = + multiRunConcurrentTest { + super.testCutAndConjunction() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // Cut need to be implemented - override fun testCutConjunctionAndBacktracking() = multiRunConcurrentTest { - super.testCutConjunctionAndBacktracking() - } + override fun testCutConjunctionAndBacktracking() = + multiRunConcurrentTest { + super.testCutConjunctionAndBacktracking() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // timeout need to be implemented, does not terminate - override fun testMaxDurationParameterAndTimeOutException() = multiRunConcurrentTest { - super.testMaxDurationParameterAndTimeOutException() - } + override fun testMaxDurationParameterAndTimeOutException() = + multiRunConcurrentTest { + super.testMaxDurationParameterAndTimeOutException() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // if is nondeterministic - override fun testPrologStandardSearchTreeExample() = multiRunConcurrentTest { - super.testPrologStandardSearchTreeExample() - } + override fun testPrologStandardSearchTreeExample() = + multiRunConcurrentTest { + super.testPrologStandardSearchTreeExample() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // Cut need to be implemented - override fun testPrologStandardSearchTreeWithCutExample() = multiRunConcurrentTest { - super.testPrologStandardSearchTreeWithCutExample() - } + override fun testPrologStandardSearchTreeWithCutExample() = + multiRunConcurrentTest { + super.testPrologStandardSearchTreeWithCutExample() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // Cut need to be implemented - override fun testBacktrackingWithCustomReverseListImplementation() = multiRunConcurrentTest { - super.testBacktrackingWithCustomReverseListImplementation() - } + override fun testBacktrackingWithCustomReverseListImplementation() = + multiRunConcurrentTest { + super.testBacktrackingWithCustomReverseListImplementation() + } @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testWithPrologStandardConjunctionExamples() = multiRunConcurrentTest { - super.testWithPrologStandardConjunctionExamples() - } + override fun testWithPrologStandardConjunctionExamples() = + multiRunConcurrentTest { + super.testWithPrologStandardConjunctionExamples() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // Cut need to be implemented - override fun testConjunctionProperties() = multiRunConcurrentTest { - super.testConjunctionProperties() - } + override fun testConjunctionProperties() = + multiRunConcurrentTest { + super.testConjunctionProperties() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // Cut need to be implemented - override fun testCallPrimitive() = multiRunConcurrentTest { - super.testCallPrimitive() - } + override fun testCallPrimitive() = + multiRunConcurrentTest { + super.testCallPrimitive() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // Cut need to be implemented - override fun testCallPrimitiveTransparency() = multiRunConcurrentTest { - super.testCallPrimitiveTransparency() - } + override fun testCallPrimitiveTransparency() = + multiRunConcurrentTest { + super.testCallPrimitiveTransparency() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // same solution count does not match (probably correct) - override fun testCatchPrimitive() = multiRunConcurrentTest { - super.testCatchPrimitive() - } + override fun testCatchPrimitive() = + multiRunConcurrentTest { + super.testCatchPrimitive() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // solutions do not match (probably correct) - override fun testCatchPrimitiveTransparency() = multiRunConcurrentTest { - super.testCatchPrimitiveTransparency() - } + override fun testCatchPrimitiveTransparency() = + multiRunConcurrentTest { + super.testCatchPrimitiveTransparency() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // todo check needed, solutions appear equals but tests fail - override fun testHaltPrimitive() = multiRunConcurrentTest { - super.testHaltPrimitive() - } + override fun testHaltPrimitive() = + multiRunConcurrentTest { + super.testHaltPrimitive() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // todo check needed, solution is not halt but unknown cause - override fun testNotPrimitive() = multiRunConcurrentTest { - super.testNotPrimitive() - } + override fun testNotPrimitive() = + multiRunConcurrentTest { + super.testNotPrimitive() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // todo check needed, solutions do not match - override fun testNotModularity() = multiRunConcurrentTest { - super.testNotModularity() - } + override fun testNotModularity() = + multiRunConcurrentTest { + super.testNotModularity() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // Arrow need to be implemented - override fun testIfThenRule() = multiRunConcurrentTest { - super.testIfThenRule() - } + override fun testIfThenRule() = + multiRunConcurrentTest { + super.testIfThenRule() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // Arrow need to be implemented - override fun testIfThenElseRule() = multiRunConcurrentTest { - super.testIfThenElseRule() - } + override fun testIfThenElseRule() = + multiRunConcurrentTest { + super.testIfThenElseRule() + } @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testNumbersRangeListGeneration() = multiRunConcurrentTest { - super.testNumbersRangeListGeneration() - } + override fun testNumbersRangeListGeneration() = + multiRunConcurrentTest { + super.testNumbersRangeListGeneration() + } @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testConjunction() = multiRunConcurrentTest { - super.testConjunction() - } + override fun testConjunction() = + multiRunConcurrentTest { + super.testConjunction() + } @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testConjunctionWithUnification() = multiRunConcurrentTest { - super.testConjunctionWithUnification() - } + override fun testConjunctionWithUnification() = + multiRunConcurrentTest { + super.testConjunctionWithUnification() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // some API need to be implemented (abolish, assert, etc.) - override fun testBuiltinApi() = multiRunConcurrentTest { - super.testBuiltinApi() - } + override fun testBuiltinApi() = + multiRunConcurrentTest { + super.testBuiltinApi() + } @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testDisjunction() = multiRunConcurrentTest { - super.testDisjunction() - } + override fun testDisjunction() = + multiRunConcurrentTest { + super.testDisjunction() + } @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testFailure() = multiRunConcurrentTest { - super.testFailure() - } + override fun testFailure() = + multiRunConcurrentTest { + super.testFailure() + } @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testDisjunctionWithUnification() = multiRunConcurrentTest { - super.testDisjunctionWithUnification() - } + override fun testDisjunctionWithUnification() = + multiRunConcurrentTest { + super.testDisjunctionWithUnification() + } @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testConjunctionOfConjunctions() = multiRunConcurrentTest { - super.testConjunctionOfConjunctions() - } + override fun testConjunctionOfConjunctions() = + multiRunConcurrentTest { + super.testConjunctionOfConjunctions() + } @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testMember() = multiRunConcurrentTest { - super.testMember() - } + override fun testMember() = + multiRunConcurrentTest { + super.testMember() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // backtracking is not present in concurrent solver, probably useless test - override fun testBasicBacktracking1() = multiRunConcurrentTest { - super.testBasicBacktracking1() - } + override fun testBasicBacktracking1() = + multiRunConcurrentTest { + super.testBasicBacktracking1() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // backtracking is not present in concurrent solver, probably useless test - override fun testBasicBacktracking2() = multiRunConcurrentTest { - super.testBasicBacktracking2() - } + override fun testBasicBacktracking2() = + multiRunConcurrentTest { + super.testBasicBacktracking2() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // backtracking is not present in concurrent solver, probably useless test - override fun testBasicBacktracking3() = multiRunConcurrentTest { - super.testBasicBacktracking3() - } + override fun testBasicBacktracking3() = + multiRunConcurrentTest { + super.testBasicBacktracking3() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // backtracking is not present in concurrent solver, probably useless test - override fun testBasicBacktracking4() = multiRunConcurrentTest { - super.testBasicBacktracking4() - } + override fun testBasicBacktracking4() = + multiRunConcurrentTest { + super.testBasicBacktracking4() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // Assert need to be implemented - override fun testAssertRules() = multiRunConcurrentTest { - super.testAssertRules() - } + override fun testAssertRules() = + multiRunConcurrentTest { + super.testAssertRules() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // Retract need to be implemented - override fun testRetract() = multiRunConcurrentTest { - super.testRetract() - } + override fun testRetract() = + multiRunConcurrentTest { + super.testRetract() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // todo check needed, more solutions than expected - override fun testNatural() = multiRunConcurrentTest { - super.testNatural() - } + override fun testNatural() = + multiRunConcurrentTest { + super.testNatural() + } @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testFunctor() = multiRunConcurrentTest { - super.testFunctor() - } + override fun testFunctor() = + multiRunConcurrentTest { + super.testFunctor() + } @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testUniv() = multiRunConcurrentTest { - super.testUniv() - } + override fun testUniv() = + multiRunConcurrentTest { + super.testUniv() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // Retract need to be implemented - override fun testRetractAll() = multiRunConcurrentTest { - super.testRetractAll() - } + override fun testRetractAll() = + multiRunConcurrentTest { + super.testRetractAll() + } @OptIn(ExperimentalCoroutinesApi::class) @Test @Ignore // Append need to be implemented - override fun testAppend() = multiRunConcurrentTest { - super.testAppend() - } + override fun testAppend() = + multiRunConcurrentTest { + super.testAppend() + } @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testTermGreaterThan() = multiRunConcurrentTest { - super.testTermGreaterThan() - } + override fun testTermGreaterThan() = + multiRunConcurrentTest { + super.testTermGreaterThan() + } @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testTermSame() = multiRunConcurrentTest { - super.testTermSame() - } + override fun testTermSame() = + multiRunConcurrentTest { + super.testTermSame() + } @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testTermLowerThan() = multiRunConcurrentTest { - super.testTermLowerThan() - } + override fun testTermLowerThan() = + multiRunConcurrentTest { + super.testTermLowerThan() + } @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testTermGreaterThanOrEqual() = multiRunConcurrentTest { - super.testTermGreaterThanOrEqual() - } + override fun testTermGreaterThanOrEqual() = + multiRunConcurrentTest { + super.testTermGreaterThanOrEqual() + } @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testTermLowerThanOrEqual() = multiRunConcurrentTest { - super.testTermLowerThanOrEqual() - } + override fun testTermLowerThanOrEqual() = + multiRunConcurrentTest { + super.testTermLowerThanOrEqual() + } @OptIn(ExperimentalCoroutinesApi::class) @Test - override fun testTermNotSame() = multiRunConcurrentTest { - super.testTermNotSame() - } + override fun testTermNotSame() = + multiRunConcurrentTest { + super.testTermNotSame() + } } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentStackTrace.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentStackTrace.kt index 361c717d5..fa6cc9ecf 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentStackTrace.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentStackTrace.kt @@ -14,14 +14,14 @@ import it.unibo.tuprolog.solve.halt import it.unibo.tuprolog.theory.Theory import kotlin.test.assertEquals +@Suppress("LocalVariableName", "ktlint:standard:property-naming", "VariableNaming") interface TestConcurrentStackTrace : FromSequence, SolverFactory { - private fun threeLayersTheory(errorExpression: LogicProgrammingScope.() -> Struct): Theory = logicProgramming { theoryOf( rule { "foo"(X) impliedBy "bar"(X) }, rule { "bar"(X) impliedBy "baz"(X) }, - rule { "baz"(X) impliedBy errorExpression() } + rule { "baz"(X) impliedBy errorExpression() }, ) } @@ -33,22 +33,23 @@ interface TestConcurrentStackTrace : FromSequence, S val query = "foo"(X) val solution = solver.solveOnce(query) val solutions = fromSequence(solution) - val expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - Signature("+", 2), - Y, - index = 0 - ) + val expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + Signature("+", 2), + Y, + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) assertEquals( ktListOf("is" / 2, "baz" / 1, "bar" / 1, "foo" / 1, "?-" / 1), - (solution as Solution.Halt).exception.logicStackTrace.map { it.indicator } + (solution as Solution.Halt).exception.logicStackTrace.map { it.indicator }, ) } } @@ -61,22 +62,23 @@ interface TestConcurrentStackTrace : FromSequence, S val query = findall(X, "foo"(X), L) val solution = solver.solveOnce(query) val solutions = fromSequence(solution) - val expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - Signature("+", 2), - Y, - index = 0 - ) + val expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + Signature("+", 2), + Y, + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) assertEquals( ktListOf("is" / 2, "baz" / 1, "bar" / 1, "foo" / 1, "findall" / 3, "?-" / 1), - (solution as Solution.Halt).exception.logicStackTrace.map { it.indicator } + (solution as Solution.Halt).exception.logicStackTrace.map { it.indicator }, ) } } @@ -89,22 +91,23 @@ interface TestConcurrentStackTrace : FromSequence, S val query = findall(X, bagof(Z, "foo"(Z), X), L) val solution = solver.solveOnce(query) val solutions = fromSequence(solution) - val expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - Signature("+", 2), - Y, - index = 0 - ) + val expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + Signature("+", 2), + Y, + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) assertEquals( ktListOf("is" / 2, "baz" / 1, "bar" / 1, "foo" / 1, "bagof" / 3, "findall" / 3, "?-" / 1), - (solution as Solution.Halt).exception.logicStackTrace.map { it.indicator } + (solution as Solution.Halt).exception.logicStackTrace.map { it.indicator }, ) } } @@ -116,22 +119,23 @@ interface TestConcurrentStackTrace : FromSequence, S val query = findall(X, bagof(Z, "foo"(Z), X), L) val solution = solver.solveOnce(query) val solutions = fromSequence(solution) - val expected = fromSequence( - query.halt( - SystemError.forUncaughtError( - MessageError( - context = DummyInstances.executionContext, - extraData = atomOf("x") - ) - ) + val expected = + fromSequence( + query.halt( + SystemError.forUncaughtError( + MessageError( + context = DummyInstances.executionContext, + extraData = atomOf("x"), + ), + ), + ), ) - ) expected.assertingEquals(solutions) assertEquals( ktListOf("baz" / 1, "bar" / 1, "foo" / 1, "bagof" / 3, "findall" / 3, "?-" / 1), - (solution as Solution.Halt).exception.logicStackTrace.map { it.indicator } + (solution as Solution.Halt).exception.logicStackTrace.map { it.indicator }, ) } } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentStackTraceImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentStackTraceImpl.kt index ff047cff0..3942fc59e 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentStackTraceImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentStackTraceImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentStackTraceImpl : TestConcurrentStackTrace, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testSimpleStackTrace() = multiRunConcurrentTest { super.testSimpleStackTrace() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSubAtom.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSubAtom.kt index c4df9c267..8be095522 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSubAtom.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSubAtom.kt @@ -12,7 +12,6 @@ import it.unibo.tuprolog.solve.halt import it.unibo.tuprolog.solve.yes interface TestConcurrentSubAtom : FromSequence, SolverFactory { - fun testSubAtomSubIsVar() { logicProgramming { val solver = solverWithDefaultBuiltins() @@ -43,12 +42,13 @@ interface TestConcurrentSubAtom : FromSequence, Solv val query = sub_atom("abracadabra", intOf(3), "L", intOf(3), "S") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - sequenceOf( - query.yes("S" to atomOf("acada")), - query.yes("L" to 5) + val expected = + fromSequence( + sequenceOf( + query.yes("S" to atomOf("acada")), + query.yes("L" to 5), + ), ) - ) expected.assertingEquals(solutions) } @@ -60,12 +60,13 @@ interface TestConcurrentSubAtom : FromSequence, Solv val query = sub_atom("banana", intOf(3), intOf(2), "T", "S") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - sequenceOf( - query.yes("S" to atomOf("an")), - query.yes("T" to 1) + val expected = + fromSequence( + sequenceOf( + query.yes("S" to atomOf("an")), + query.yes("T" to 1), + ), ) - ) expected.assertingEquals(solutions) } @@ -77,16 +78,17 @@ interface TestConcurrentSubAtom : FromSequence, Solv val query = sub_atom("Banana", intOf(3), intOf(2), "Y", "S") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - InstantiationError.forArgument( - DummyInstances.executionContext, - Signature("sub_atom", 5), - varOf("Banana"), - index = 0 - ) + val expected = + fromSequence( + query.halt( + InstantiationError.forArgument( + DummyInstances.executionContext, + Signature("sub_atom", 5), + varOf("Banana"), + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -98,17 +100,18 @@ interface TestConcurrentSubAtom : FromSequence, Solv val query = sub_atom(5, 2, 2, "_", "S") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("sub_atom", 5), - TypeError.Expected.ATOM, - Integer.of("5"), - index = 0 - ) + val expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("sub_atom", 5), + TypeError.Expected.ATOM, + Integer.of("5"), + index = 0, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -121,17 +124,18 @@ interface TestConcurrentSubAtom : FromSequence, Solv val query = sub_atom("banana", 4, 2, "_", 2) val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("sub_atom", 5), - TypeError.Expected.ATOM, - Integer.of("2"), - index = 4 - ) + val expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("sub_atom", 5), + TypeError.Expected.ATOM, + Integer.of("2"), + index = 4, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -144,17 +148,18 @@ interface TestConcurrentSubAtom : FromSequence, Solv val query = sub_atom("banana", "a", 2, "_", "S") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("sub_atom", 5), - TypeError.Expected.INTEGER, - Atom.of("a"), - index = 1 - ) + val expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("sub_atom", 5), + TypeError.Expected.INTEGER, + Atom.of("a"), + index = 1, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -166,17 +171,18 @@ interface TestConcurrentSubAtom : FromSequence, Solv val query = sub_atom("banana", 4, "n", "_", "S") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("sub_atom", 5), - TypeError.Expected.INTEGER, - Atom.of("n"), - index = 2 - ) + val expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("sub_atom", 5), + TypeError.Expected.INTEGER, + Atom.of("n"), + index = 2, + ), + ), ) - ) expected.assertingEquals(solutions) } @@ -188,17 +194,18 @@ interface TestConcurrentSubAtom : FromSequence, Solv val query = sub_atom("banana", 4, 2, "m", "S") val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.halt( - TypeError.forArgument( - DummyInstances.executionContext, - Signature("sub_atom", 5), - TypeError.Expected.INTEGER, - Atom.of("m"), - index = 3 - ) + val expected = + fromSequence( + query.halt( + TypeError.forArgument( + DummyInstances.executionContext, + Signature("sub_atom", 5), + TypeError.Expected.INTEGER, + Atom.of("m"), + index = 3, + ), + ), ) - ) expected.assertingEquals(solutions) } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSubAtomImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSubAtomImpl.kt index 8ebfcdc9d..847654dc9 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSubAtomImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentSubAtomImpl.kt @@ -9,7 +9,6 @@ class TestConcurrentSubAtomImpl : TestConcurrentSubAtom, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testSubAtomSubIsVar() = multiRunConcurrentTest { super.testSubAtomSubIsVar() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentTerm.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentTerm.kt index 6c45fa5e9..91c2a6270 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentTerm.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentTerm.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentTerm : FromSequence, SolverFactory { - fun testTermDiff() { logicProgramming { val solver = solverWithDefaultBuiltins() diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentTermImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentTermImpl.kt index 582e3dd08..d69c36d45 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentTermImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentTermImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentTermImpl : TestConcurrentTerm, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testTermDiff() = multiRunConcurrentTest { super.testTermDiff() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentTrue.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentTrue.kt index a94b1fb6b..716559f5a 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentTrue.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentTrue.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.SolverFactory import it.unibo.tuprolog.solve.yes interface TestConcurrentTrue : FromSequence, SolverFactory { - fun testTrue() { logicProgramming { val solver = solverWithDefaultBuiltins() diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentTrueImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentTrueImpl.kt index 2a058b452..21e608dd5 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentTrueImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentTrueImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentTrueImpl : TestConcurrentTrue, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testTrue() = multiRunConcurrentTest { super.testTrue() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentUnify.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentUnify.kt index a6796f54c..30af1deb5 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentUnify.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentUnify.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.no import it.unibo.tuprolog.solve.yes interface TestConcurrentUnify : FromSequence, SolverFactory { - fun testNumberUnify() { logicProgramming { val solver = solverWithDefaultBuiltins() @@ -133,13 +132,14 @@ interface TestConcurrentUnify : FromSequence, Solver val query = ("f"("A", "B", "C")) eq ("f"("g"("B", "B"), "g"("C", "C"), "g"("D", "D"))) val solutions = fromSequence(solver.solve(query, mediumDuration)) - val expected = fromSequence( - query.yes( - "A" to "g"("g"("g"("D", "D"), "g"("D", "D")), "g"("g"("D", "D"), "g"("D", "D"))), - "B" to "g"("g"("D", "D"), "g"("D", "D")), - "C" to "g"("D", "D") + val expected = + fromSequence( + query.yes( + "A" to "g"("g"("g"("D", "D"), "g"("D", "D")), "g"("g"("D", "D"), "g"("D", "D"))), + "B" to "g"("g"("D", "D"), "g"("D", "D")), + "C" to "g"("D", "D"), + ), ) - ) expected.assertingEquals(solutions) } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentUnifyImpl.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentUnifyImpl.kt index f93703354..950fe2a81 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentUnifyImpl.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentUnifyImpl.kt @@ -8,7 +8,6 @@ class TestConcurrentUnifyImpl : TestConcurrentUnify, SolverFactory by ConcurrentSolverFactory, FromSequence by ConcurrentFromSequence { - @OptIn(ExperimentalCoroutinesApi::class) @Test override fun testNumberUnify() = multiRunConcurrentTest { super.testNumberUnify() } diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentUtils.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentUtils.kt index 7958c96a0..5658c670c 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentUtils.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestConcurrentUtils.kt @@ -30,7 +30,7 @@ private inline val loggingOn get() = false fun multiRunConcurrentTest( times: Int = 5, coroutineContext: CoroutineContext = Dispatchers.Default, - block: suspend CoroutineScope.() -> Unit + block: suspend CoroutineScope.() -> Unit, ) = (0 until times).forEach { _ -> runBlocking(coroutineContext) { block() } } interface WithAssertingEquals { @@ -39,7 +39,9 @@ interface WithAssertingEquals { interface FromSequence : SolverTest { fun fromSequence(sequence: Sequence): T + fun fromSequence(solutions: Iterable): T = fromSequence(solutions.asSequence()) + fun fromSequence(solution: Solution): T = fromSequence(sequenceOf(solution)) } @@ -48,11 +50,10 @@ object ConcurrentFromSequence : FromSequence { } class KeySolution(val solution: Solution) { - + @Suppress("ReturnCount") private fun ResolutionException.similar(other: Any?): Boolean { if (this === other) return true if (other == null || this::class != other::class) return false - return if (this is LogicError && other is LogicError) { errorStruct.equals(other.errorStruct, false) && message == other.message } else { @@ -61,16 +62,18 @@ class KeySolution(val solution: Solution) { } private val ResolutionException.hash: Int - get() = if (this is LogicError) { - 31 * errorStruct.hashCode() + message.hashCode() - } else { - hashCode() - } + get() = + if (this is LogicError) { + 31 * errorStruct.hashCode() + message.hashCode() + } else { + hashCode() + } private val Substitution.Unifier.hash: Int - get() = entries.fold(0) { base, entry -> - base + entry.value.hash - } + get() = + entries.fold(0) { base, entry -> + base + entry.value.hash + } private val Term.hash: Int get() { @@ -91,10 +94,10 @@ class KeySolution(val solution: Solution) { return hashCode } + @Suppress("ReturnCount") private fun List.similar(other: List): Boolean { if (this === other) return true if (size != other.size) return false - return all { other.any { otherIt -> otherIt.similar(it) @@ -117,26 +120,27 @@ class KeySolution(val solution: Solution) { return args.similar(other.args) } - private fun Term.similar(other: Term): Boolean = when { - isTuple -> { - other.asTuple()?.similar(castToTuple()) ?: false - } - isCons -> { - other.asCons()?.similar(castToCons()) ?: false - } - isVar -> { - other.asVar()?.equals(castToVar(), false) ?: false - } - isStruct -> { - other.asStruct()?.similar(castToStruct()) ?: false + private fun Term.similar(other: Term): Boolean = + when { + isTuple -> { + other.asTuple()?.similar(castToTuple()) ?: false + } + isCons -> { + other.asCons()?.similar(castToCons()) ?: false + } + isVar -> { + other.asVar()?.equals(castToVar(), false) ?: false + } + isStruct -> { + other.asStruct()?.similar(castToStruct()) ?: false + } + else -> this == other } - else -> this == other - } + @Suppress("ReturnCount") private fun Substitution.Unifier.similar(other: Any?): Boolean { if (this === other) return true if (other == null || this::class != other::class) return false - other as Substitution.Unifier if (isSuccess != other.isSuccess) return false if (this.size != other.size) return false @@ -151,26 +155,29 @@ class KeySolution(val solution: Solution) { other as KeySolution val queryEqual = solution.query == other.solution.query - val substitutionEqual = solution.substitution.whenIs( - { it.similar(other.solution.substitution) }, - { it == other.solution.substitution }, - { it == other.solution.substitution } - ) - val exceptionEqual = if (solution is Solution.Halt && other.solution is Solution.Halt) { - solution.exception.similar(other.solution.exception) - } else { - true - } + val substitutionEqual = + solution.substitution.whenIs( + { it.similar(other.solution.substitution) }, + { it == other.solution.substitution }, + { it == other.solution.substitution }, + ) + val exceptionEqual = + if (solution is Solution.Halt && other.solution is Solution.Halt) { + solution.exception.similar(other.solution.exception) + } else { + true + } return queryEqual && substitutionEqual && exceptionEqual } override fun hashCode(): Int { var result = solution.query.hashCode() - result = 31 * result + solution.substitution.whenIs( - { it.hash }, - { it.hashCode() }, - { it.hashCode() } - ) + result = 31 * result + + solution.substitution.whenIs( + { it.hash }, + { it.hashCode() }, + { it.hashCode() }, + ) if (solution is Solution.Halt) { result = 31 * result + solution.exception.hash } @@ -183,17 +190,18 @@ class KeySolution(val solution: Solution) { fun Solution.key(): KeySolution = KeySolution(this) class MultiSet(private val solutionOccurrences: Map = mapOf()) : WithAssertingEquals { - constructor(solutions: Iterable) : this(solutions.asSequence()) constructor(solutions: Sequence) : this( - solutions.map { it.key() }.groupBy { it }.mapValues { it.value.size } + solutions.map { it.key() }.groupBy { it }.mapValues { it.value.size }, ) constructor(vararg solutions: Solution) : this(solutions.asIterable()) fun add(solution: Solution): MultiSet = - MultiSet(solutionOccurrences + (solution.key() to (solutionOccurrences[solution.key()] ?: 1))) + MultiSet( + solutionOccurrences + (solution.key() to (solutionOccurrences[solution.key()] ?: 1)), + ) override fun assertingEquals(other: Any?) { if (this === other) { @@ -207,27 +215,28 @@ class MultiSet(private val solutionOccurrences: Map = mapOf()) val failMsg = "Expected solutions: ${printSolutions()} \nActual solutions: ${actual.printSolutions()}" assertEquals( - solutionOccurrences.entries.filter { !it.key.solution.isNo }.size, - actual.solutionOccurrences.entries.filter { !it.key.solution.isNo }.size, - "Expected MultiSet size did not match actual MultiSet size.\n$failMsg" + solutionOccurrences.entries.count { !it.key.solution.isNo }, + actual.solutionOccurrences.entries.count { !it.key.solution.isNo }, + "Expected MultiSet size did not match actual MultiSet size.\n$failMsg", ) solutionOccurrences.forEach { (key, value) -> val foundValue: Int? = actual.solutionOccurrences[key]?.let { if (key.solution.isNo) 1 else it } assertNotNull( foundValue, - "Expected solution not found in actual. Missing expected solution: $key\n$failMsg" + "Expected solution not found in actual. Missing expected solution: $key\n$failMsg", ) assertEquals( value, foundValue, - "Expected solution count ($value) did not match actual solution count ($foundValue).\n$failMsg" + "Expected solution count ($value) did not match actual solution count ($foundValue).\n$failMsg", ) } } - private fun printSolutions(): String = solutionOccurrences.entries.fold("") { base, kv -> - "${base}Solution:${kv.key} Times:${kv.value}\n" - } + private fun printSolutions(): String = + solutionOccurrences.entries.fold("") { base, kv -> + "${base}Solution:${kv.key} Times:${kv.value}\n" + } override fun equals(other: Any?): Boolean { if (this === other) return true @@ -249,7 +258,7 @@ class MultiSet(private val solutionOccurrences: Map = mapOf()) fun assertConcurrentSolverSolutionsCorrect( solver: Solver, goalToSolutions: List>>, - maxDuration: TimeDuration + maxDuration: TimeDuration, ) { goalToSolutions.forEach { (goal, solutionList) -> if (loggingOn) solver.logKBs() @@ -262,7 +271,10 @@ fun assertConcurrentSolverSolutionsCorrect( } } -fun logGoalAndSolutions(goal: Struct, solutions: T) { +fun logGoalAndSolutions( + goal: Struct, + solutions: T, +) { println("?- $goal.") println(solutions.toString()) // todo replace with better print println("".padEnd(80, '-')) diff --git a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestMultiSet.kt b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestMultiSet.kt index e7bbe4102..5b413b174 100644 --- a/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestMultiSet.kt +++ b/solve-concurrent/src/jvmTest/kotlin/it/unibo/tuprolog/solve/concurrent/TestMultiSet.kt @@ -12,63 +12,67 @@ import kotlin.test.Test import kotlin.test.assertNotEquals class TestMultiSet { - @OptIn(ExperimentalCoroutinesApi::class) @Test - fun testEmptyMultiSet() = multiRunConcurrentTest { - val multiSet1 = MultiSet() - val multiSet2 = MultiSet() - multiSet1.assertingEquals(multiSet2) - val empty = MultiSet(sequenceOf()) - multiSet1.assertingEquals(empty) - } + fun testEmptyMultiSet() = + multiRunConcurrentTest { + val multiSet1 = MultiSet() + val multiSet2 = MultiSet() + multiSet1.assertingEquals(multiSet2) + val empty = MultiSet(sequenceOf()) + multiSet1.assertingEquals(empty) + } @OptIn(ExperimentalCoroutinesApi::class) @Test - fun testMultiSet() = multiRunConcurrentTest { - logicProgramming { - val query = "X" equalsTo 1 and `var`("X") - val solutions = sequenceOf(query.no()) - val multiSet1 = MultiSet(solutions) - val multiSet2 = MultiSet(solutions) - multiSet1.assertingEquals(multiSet2) + fun testMultiSetCreationAndEquality() = + multiRunConcurrentTest { + logicProgramming { + val query = "X" equalsTo 1 and `var`("X") + val solutions = sequenceOf(query.no()) + val multiSet1 = MultiSet(solutions) + val multiSet2 = MultiSet(solutions) + multiSet1.assertingEquals(multiSet2) - val query2 = `var`("X") and ("X" equalsTo 1) - val solutions2 = sequenceOf( - query2.yes("X" to 1), - query2.yes("X" to 1), - query.no(), - query2.yes("X" to 1) - ) - MultiSet(solutions2).assertingEquals(MultiSet(solutions2)) + val query2 = `var`("X") and ("X" equalsTo 1) + val solutions2 = + sequenceOf( + query2.yes("X" to 1), + query2.yes("X" to 1), + query.no(), + query2.yes("X" to 1), + ) + MultiSet(solutions2).assertingEquals(MultiSet(solutions2)) - val solutionHalt = sequenceOf( - query.halt( - ExistenceError.forProcedure( - DummyInstances.executionContext, - Signature("nofoo", 1) + val solutionHalt = + sequenceOf( + query.halt( + ExistenceError.forProcedure( + DummyInstances.executionContext, + Signature("nofoo", 1), + ), + ), ) - ) - ) - MultiSet(solutionHalt).assertingEquals(MultiSet(solutionHalt)) + MultiSet(solutionHalt).assertingEquals(MultiSet(solutionHalt)) + } } - } @OptIn(ExperimentalCoroutinesApi::class) @Test - fun testDifferentMultiSet() = multiRunConcurrentTest { - logicProgramming { - val query = "X" equalsTo 1 and `var`("X") - val query2 = `var`("X") and ("X" equalsTo 1) - val solutions = sequenceOf(query.no()) - val solutions2 = sequenceOf(query2.yes("X" to 1)) - val solutions3 = sequenceOf(query2.no()) - val multiSet1 = MultiSet(solutions) - val multiSet2 = MultiSet(solutions2) - val multiSet3 = MultiSet(solutions3) - assertNotEquals(multiSet1, multiSet2) - assertNotEquals(multiSet1, multiSet3) - assertNotEquals(multiSet2, multiSet3) + fun testDifferentMultiSet() = + multiRunConcurrentTest { + logicProgramming { + val query = "X" equalsTo 1 and `var`("X") + val query2 = `var`("X") and ("X" equalsTo 1) + val solutions = sequenceOf(query.no()) + val solutions2 = sequenceOf(query2.yes("X" to 1)) + val solutions3 = sequenceOf(query2.no()) + val multiSet1 = MultiSet(solutions) + val multiSet2 = MultiSet(solutions2) + val multiSet3 = MultiSet(solutions3) + assertNotEquals(multiSet1, multiSet2) + assertNotEquals(multiSet1, multiSet3) + assertNotEquals(multiSet2, multiSet3) + } } - } } diff --git a/solve-plp/src/commonMain/kotlin/it/unibo/tuprolog/solve/ProbExtensions.kt b/solve-plp/src/commonMain/kotlin/it/unibo/tuprolog/solve/ProbExtensions.kt index 35021b3a3..530fdf678 100644 --- a/solve-plp/src/commonMain/kotlin/it/unibo/tuprolog/solve/ProbExtensions.kt +++ b/solve-plp/src/commonMain/kotlin/it/unibo/tuprolog/solve/ProbExtensions.kt @@ -24,8 +24,7 @@ private const val PROBABILISTIC_OPTION_TAG = const val DEFAULT_PROBABILITY = 1.0 const val DEFAULT_PROBABILISTIC_OPTION = false -private fun normalizeProbability(probability: Double): Double = - max(min(1.0, probability), 0.0) +private fun normalizeProbability(probability: Double): Double = max(min(1.0, probability), 0.0) /** * Returns the probability value assigned to this object. @@ -37,9 +36,7 @@ val , U : T> U.probability: Double * Assigns a probability value to this object. */ @JsName("setProbability") -fun , U : T> U.setProbability( - value: Double -): U = setTag(PROBABILITY_TAG, normalizeProbability(value)) +fun , U : T> U.setProbability(value: Double): U = setTag(PROBABILITY_TAG, normalizeProbability(value)) /** * Returns true if probabilistic computation option is enabled. @@ -51,16 +48,15 @@ fun , U : T> U.setProbability( * default value. */ val SolveOptions.isProbabilistic: Boolean - get() = (customOptions[PROBABILISTIC_OPTION_TAG] as Boolean?) - ?: DEFAULT_PROBABILISTIC_OPTION + get() = + (customOptions[PROBABILISTIC_OPTION_TAG] as Boolean?) + ?: DEFAULT_PROBABILISTIC_OPTION /** * Sets the probabilistic computation option to [value]. */ @JsName("setProbabilistic") -fun SolveOptions.setProbabilistic( - value: Boolean -) = setOption(PROBABILISTIC_OPTION_TAG, value) +fun SolveOptions.setProbabilistic(value: Boolean) = setOption(PROBABILISTIC_OPTION_TAG, value) @JsName("probabilistic") fun SolveOptions.probabilistic() = setProbabilistic(true) @@ -82,6 +78,5 @@ val Solution.binaryDecisionDiagram: BinaryDecisionDiagram? * of [BinaryDecisionDiagram] to [this] [Solution]. */ @JsName("setBinaryDecisionDiagram") -fun Solution.setBinaryDecisionDiagram( - value: BinaryDecisionDiagram -) = setTag(BINARY_DECISION_DIAGRAM_TAG, value) +fun Solution.setBinaryDecisionDiagram(value: BinaryDecisionDiagram) = + setTag(BINARY_DECISION_DIAGRAM_TAG, value) diff --git a/solve-plp/src/jsMain/kotlin/it/unibo/tuprolog/solve/ProbExtensionsJs.kt b/solve-plp/src/jsMain/kotlin/it/unibo/tuprolog/solve/ProbExtensionsJs.kt index 86f97a2ec..cc152c965 100644 --- a/solve-plp/src/jsMain/kotlin/it/unibo/tuprolog/solve/ProbExtensionsJs.kt +++ b/solve-plp/src/jsMain/kotlin/it/unibo/tuprolog/solve/ProbExtensionsJs.kt @@ -5,17 +5,13 @@ import it.unibo.tuprolog.core.Term import it.unibo.tuprolog.utils.Taggable @JsName("probability") -fun , U : T> probability(taggable: U): Double = - taggable.probability +fun , U : T> probability(taggable: U): Double = taggable.probability @JsName("isProbabilistic") -fun isProbabilistic(solveOptions: SolveOptions): Boolean = - solveOptions.isProbabilistic +fun isProbabilistic(solveOptions: SolveOptions): Boolean = solveOptions.isProbabilistic @JsName("hasBinaryDecisionDiagram") -fun hasBinaryDecisionDiagram(solution: Solution): Boolean = - solution.hasBinaryDecisionDiagram +fun hasBinaryDecisionDiagram(solution: Solution): Boolean = solution.hasBinaryDecisionDiagram @JsName("binaryDecisionDiagram") -fun binaryDecisionDiagram(solution: Solution): BinaryDecisionDiagram? = - solution.binaryDecisionDiagram +fun binaryDecisionDiagram(solution: Solution): BinaryDecisionDiagram? = solution.binaryDecisionDiagram diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/MutableProblogSolver.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/MutableProblogSolver.kt index 1a7d5c324..b13f03ba6 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/MutableProblogSolver.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/MutableProblogSolver.kt @@ -18,9 +18,8 @@ import it.unibo.tuprolog.theory.Theory import it.unibo.tuprolog.unify.Unificator internal class MutableProblogSolver( - private val solver: MutableSolver + private val solver: MutableSolver, ) : ProblogSolver(solver), MutableSolver { - override fun loadLibrary(library: Library) { solver.loadLibrary(library) } @@ -89,7 +88,10 @@ internal class MutableProblogSolver( return solver.retractAll(ProblogTheory.of(solver.unificator, Fact.of(fact)).clauses.first()) } - override fun setFlag(name: String, value: Term) { + override fun setFlag( + name: String, + value: Term, + ) { solver.setFlag(name, value) } @@ -126,10 +128,10 @@ internal class MutableProblogSolver( stdIn: InputChannel, stdOut: OutputChannel, stdErr: OutputChannel, - warnings: OutputChannel + warnings: OutputChannel, ): MutableSolver { return MutableProblogSolver( - solver.copy(unificator, libraries, flags, staticKb, dynamicKb, stdIn, stdOut, stdErr, warnings) + solver.copy(unificator, libraries, flags, staticKb, dynamicKb, stdIn, stdOut, stdErr, warnings), ) } diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/ProblogSolver.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/ProblogSolver.kt index 51bdc5085..57cdc2112 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/ProblogSolver.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/ProblogSolver.kt @@ -27,29 +27,29 @@ import it.unibo.tuprolog.theory.Theory import it.unibo.tuprolog.unify.Unificator internal open class ProblogSolver( - private val solver: Solver + private val solver: Solver, ) : Solver by solver { - private fun solveNonProbabilistically( goal: Struct, - options: SolveOptions + options: SolveOptions, ): Sequence { val anonVar = Var.anonymous() return solver.solve( Tuple.of( Struct.of( ProbSetConfig.functor, - options.toProbConfigTerm() + options.toProbConfigTerm(), ), - Struct.of(Prob.functor, anonVar, goal) + Struct.of(Prob.functor, anonVar, goal), ), - options + options, ).map { when (it) { - is Solution.Yes -> Solution.yes( - goal, - it.substitution.filter { key, _ -> key != anonVar } - ) + is Solution.Yes -> + Solution.yes( + goal, + it.substitution.filter { key, _ -> key != anonVar }, + ) is Solution.Halt -> Solution.halt(goal, it.exception) else -> Solution.no(goal) } @@ -58,7 +58,7 @@ internal open class ProblogSolver( private fun solveProbabilistically( goal: Struct, - options: SolveOptions + options: SolveOptions, ): Sequence { val probabilityVar = Var.of("Prob") val bddVar = Var.of("BDD") @@ -68,41 +68,46 @@ internal open class ProblogSolver( probabilityVar, goal, options.toProbConfigTerm(), - bddVar + bddVar, ), - options + options, ).map { val probabilityTerm = it.substitution[probabilityVar] val bddTerm = it.substitution[bddVar] - var newSolution = when (it) { - is Solution.Yes -> Solution.yes( - goal, - it.substitution.filter { - key, _ -> - key != probabilityVar && key != bddVar - } - ) - is Solution.Halt -> Solution.halt(goal, it.exception) - else -> Solution.no(goal) - } + var newSolution = + when (it) { + is Solution.Yes -> + Solution.yes( + goal, + it.substitution.filter { + key, _ -> + key != probabilityVar && key != bddVar + }, + ) + is Solution.Halt -> Solution.halt(goal, it.exception) + else -> Solution.no(goal) + } if (!options.isProbabilistic) { newSolution } else { // Set the probability property - newSolution = when (probabilityTerm) { - is Numeric -> newSolution.setProbability( - probabilityTerm.decimalValue.toDouble() - ) - else -> newSolution.setProbability(Double.NaN) - } + newSolution = + when (probabilityTerm) { + is Numeric -> + newSolution.setProbability( + probabilityTerm.decimalValue.toDouble(), + ) + else -> newSolution.setProbability(Double.NaN) + } // Set the Binary Decision Diagram property if (bddTerm != null && bddTerm is ProbExplanationTerm) { val explanation = bddTerm.explanation if (explanation is BinaryDecisionDiagramExplanation) { - newSolution = newSolution.setBinaryDecisionDiagram( - explanation.diagram - ) + newSolution = + newSolution.setBinaryDecisionDiagram( + explanation.diagram, + ) } } newSolution @@ -112,7 +117,7 @@ internal open class ProblogSolver( override fun solve( goal: Struct, - options: SolveOptions + options: SolveOptions, ): Sequence = if (!options.isProbabilistic) { solveNonProbabilistically(goal, options) @@ -122,41 +127,33 @@ internal open class ProblogSolver( override fun solve( goal: Struct, - timeout: TimeDuration - ): Sequence = - solve(goal, SolveOptions.allLazilyWithTimeout(timeout)) + timeout: TimeDuration, + ): Sequence = solve(goal, SolveOptions.allLazilyWithTimeout(timeout)) - override fun solve( - goal: Struct - ): Sequence = solve(goal, SolveOptions.DEFAULT) + override fun solve(goal: Struct): Sequence = solve(goal, SolveOptions.DEFAULT) override fun solveList( goal: Struct, - timeout: TimeDuration + timeout: TimeDuration, ): List = solve(goal, timeout).toList() - override fun solveList( - goal: Struct - ): List = solve(goal).toList() + override fun solveList(goal: Struct): List = solve(goal).toList() override fun solveList( goal: Struct, - options: SolveOptions + options: SolveOptions, ): List = solve(goal, options).toList() override fun solveOnce( goal: Struct, - timeout: TimeDuration - ): Solution = - solve(goal, SolveOptions.someLazilyWithTimeout(1, timeout)).first() + timeout: TimeDuration, + ): Solution = solve(goal, SolveOptions.someLazilyWithTimeout(1, timeout)).first() - override fun solveOnce( - goal: Struct - ): Solution = solve(goal, SolveOptions.someLazily(1)).first() + override fun solveOnce(goal: Struct): Solution = solve(goal, SolveOptions.someLazily(1)).first() override fun solveOnce( goal: Struct, - options: SolveOptions + options: SolveOptions, ): Solution = solve(goal, options.setLimit(1)).first() override fun copy( @@ -168,7 +165,7 @@ internal open class ProblogSolver( stdIn: InputChannel, stdOut: OutputChannel, stdErr: OutputChannel, - warnings: OutputChannel + warnings: OutputChannel, ): Solver { return ProblogSolver( solver.copy( @@ -180,8 +177,8 @@ internal open class ProblogSolver( stdIn, stdOut, stdErr, - warnings - ) + warnings, + ), ) } diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/ProblogSolverFactory.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/ProblogSolverFactory.kt index 7d0edfb0f..9f67c92b8 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/ProblogSolverFactory.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/ProblogSolverFactory.kt @@ -23,15 +23,13 @@ import kotlin.js.JsExport @Suppress("NON_EXPORTABLE_TYPE") @JsExport object ProblogSolverFactory : SolverFactory { - override val defaultBuiltins: Library get() = ProblogLib.DefaultBuiltins override val defaultFlags: FlagStore get() = ensureVariablesTracking(super.defaultFlags) - private fun ensureVariablesTracking(flags: FlagStore): FlagStore = - flags + TrackVariables { ON } + private fun ensureVariablesTracking(flags: FlagStore): FlagStore = flags + TrackVariables { ON } override fun solverOf( unificator: Unificator, @@ -40,7 +38,7 @@ object ProblogSolverFactory : SolverFactory { staticKb: Theory, dynamicKb: Theory, inputs: InputStore, - outputs: OutputStore + outputs: OutputStore, ): Solver = ProblogSolver( ClassicSolverFactory.solverOf( @@ -50,8 +48,8 @@ object ProblogSolverFactory : SolverFactory { ProblogTheory.of(unificator, staticKb), ProblogTheory.of(unificator, dynamicKb), inputs, - outputs - ) + outputs, + ), ) private fun fixLibraries(libraries: Runtime): Runtime { @@ -71,7 +69,7 @@ object ProblogSolverFactory : SolverFactory { stdIn: InputChannel, stdOut: OutputChannel, stdErr: OutputChannel, - warnings: OutputChannel + warnings: OutputChannel, ): Solver = ProblogSolver( ClassicSolverFactory.solverOf( @@ -83,8 +81,8 @@ object ProblogSolverFactory : SolverFactory { stdIn, stdOut, stdErr, - warnings - ) + warnings, + ), ) override fun mutableSolverOf( @@ -96,7 +94,7 @@ object ProblogSolverFactory : SolverFactory { stdIn: InputChannel, stdOut: OutputChannel, stdErr: OutputChannel, - warnings: OutputChannel + warnings: OutputChannel, ): MutableSolver = MutableProblogSolver( ClassicSolverFactory.mutableSolverOf( @@ -108,8 +106,8 @@ object ProblogSolverFactory : SolverFactory { stdIn, stdOut, stdErr, - warnings - ) + warnings, + ), ) override fun mutableSolverOf( @@ -119,7 +117,7 @@ object ProblogSolverFactory : SolverFactory { staticKb: Theory, dynamicKb: Theory, inputs: InputStore, - outputs: OutputStore + outputs: OutputStore, ): MutableSolver = MutableProblogSolver( ClassicSolverFactory.mutableSolverOf( @@ -129,7 +127,7 @@ object ProblogSolverFactory : SolverFactory { ProblogTheory.of(unificator, staticKb), ProblogTheory.of(unificator, dynamicKb), inputs, - outputs - ) + outputs, + ), ) } diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/ProblogLib.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/ProblogLib.kt index 743a69e7b..72bfdf1c9 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/ProblogLib.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/ProblogLib.kt @@ -28,24 +28,25 @@ object ProblogLib : ExtensionLibrary(Library.of("problog.lang")) { get() = PROBLOG_SPECIFIC_OPERATORS override val additionalRules: Iterable> - get() = listOf( - Prob - ) + get() = + listOf( + Prob, + ) override val additionalPrimitives: Iterable> - get() = listOf( - ProbHelper, - ProbSolve, - ProbExplAnd, - ProbQuery, - ProbSolveEvidence, - ProbSolveWithEvidence, - ProbNegationAsFailure, - ProbSetConfig - ) + get() = + listOf( + ProbHelper, + ProbSolve, + ProbExplAnd, + ProbQuery, + ProbSolveEvidence, + ProbSolveWithEvidence, + ProbNegationAsFailure, + ProbSetConfig, + ) internal object DefaultBuiltins : ExtensionLibrary(ClassicDefaultBuiltins) { - override val alias: String get() = ProblogLib.alias @@ -60,15 +61,16 @@ object ProblogLib : ExtensionLibrary(Library.of("problog.lang")) { } internal object MinimalBuiltins : ExtensionLibrary(ProblogLib) { - override val additionalPrimitives: Iterable> - get() = listOf( - EnsureExecutable - ) + get() = + listOf( + EnsureExecutable, + ) override val additionalRules: Iterable> - get() = listOf( - Call - ) + get() = + listOf( + Call, + ) } } diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/exception/ClauseMappingException.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/exception/ClauseMappingException.kt index 9d02543a1..4aed04461 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/exception/ClauseMappingException.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/exception/ClauseMappingException.kt @@ -3,7 +3,9 @@ package it.unibo.tuprolog.solve.problog.lib.exception import it.unibo.tuprolog.core.exception.TuPrologException import kotlin.jvm.JvmOverloads -open class ClauseMappingException @JvmOverloads constructor( - override val message: String?, - cause: Throwable? = null -) : TuPrologException(cause) +open class ClauseMappingException + @JvmOverloads + constructor( + override val message: String?, + cause: Throwable? = null, + ) : TuPrologException(cause) diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/MutableProblogTheory.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/MutableProblogTheory.kt index 840f8aad1..83c0401e1 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/MutableProblogTheory.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/MutableProblogTheory.kt @@ -23,7 +23,6 @@ import kotlin.jvm.JvmStatic * @author Jason Dellaluce * */ interface MutableProblogTheory : ProblogTheory, MutableTheory { - override val isMutable: Boolean get() = true override fun toMutableTheory(): MutableProblogTheory = this @@ -58,13 +57,14 @@ interface MutableProblogTheory : ProblogTheory, MutableTheory { override fun retract(clauses: Sequence): RetractResult - override fun retract(head: Struct): RetractResult = - retract(Rule.of(head, Var.anonymous())) + override fun retract(head: Struct): RetractResult = retract(Rule.of(head, Var.anonymous())) override fun retractAll(clause: Clause): RetractResult override fun retractAll(head: Struct): RetractResult = - retractAll(Rule.of(head, Var.anonymous())) + retractAll( + Rule.of(head, Var.anonymous()), + ) override fun abolish(indicator: Indicator): MutableProblogTheory @@ -72,32 +72,39 @@ interface MutableProblogTheory : ProblogTheory, MutableTheory { /** Creates an empty [MutableProblogTheory] */ @JvmStatic @JsName("empty") - fun empty(unificator: Unificator): MutableTheory = - of(unificator, emptyList()) + fun empty(unificator: Unificator): MutableTheory = of(unificator, emptyList()) /** Creates a [MutableProblogTheory], containing the given clauses */ @JvmStatic @JsName("of") - fun of(unificator: Unificator, vararg clauses: Clause): MutableTheory = - of(unificator, clauses.asIterable()) + fun of( + unificator: Unificator, + vararg clauses: Clause, + ): MutableTheory = of(unificator, clauses.asIterable()) /** Creates a [MutableProblogTheory], containing the given clauses */ @JvmStatic @JsName("ofSequence") - fun of(unificator: Unificator, clauses: Sequence): MutableTheory = - of(unificator, clauses.asIterable()) + fun of( + unificator: Unificator, + clauses: Sequence, + ): MutableTheory = of(unificator, clauses.asIterable()) /** Let developers easily create a [[MutableProblogTheory], while avoiding variables names clashing by using a * different [Scope] for each [Clause] */ @JvmStatic @JsName("ofScopes") - fun of(unificator: Unificator, vararg clauses: Scope.() -> Clause): MutableTheory = - of(unificator, clauses.map { Scope.empty().it() }) + fun of( + unificator: Unificator, + vararg clauses: Scope.() -> Clause, + ): MutableTheory = of(unificator, clauses.map { Scope.empty().it() }) /** Creates a [MutableProblogTheory] containing the given clauses */ @JvmStatic @JsName("ofIterable") - fun of(unificator: Unificator, clauses: Iterable): MutableProblogTheory = - MappedMutableProblogTheory(clauses, unificator) + fun of( + unificator: Unificator, + clauses: Iterable, + ): MutableProblogTheory = MappedMutableProblogTheory(clauses, unificator) } } diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/ProbExplanation.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/ProbExplanation.kt index 2c5531fb9..897c31055 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/ProbExplanation.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/ProbExplanation.kt @@ -24,7 +24,6 @@ import kotlin.js.JsName * @author Jason Dellaluce */ internal interface ProbExplanation { - override fun toString(): String /** @@ -84,24 +83,26 @@ internal interface ProbExplanation { companion object { /** A [ProbExplanation] representing a logic falsity. */ - val FALSE: ProbExplanation = BinaryDecisionDiagramExplanation( - bddTerminalOf(false), - BinaryDecisionDiagramExplanation.FALSE_COMPUTED_VALUE - ) + val FALSE: ProbExplanation = + BinaryDecisionDiagramExplanation( + bddTerminalOf(false), + BinaryDecisionDiagramExplanation.FALSE_COMPUTED_VALUE, + ) /** A [ProbExplanation] representing a logic truth. */ - val TRUE: ProbExplanation = BinaryDecisionDiagramExplanation( - bddTerminalOf(true), - BinaryDecisionDiagramExplanation.TRUE_COMPUTED_VALUE - ) + val TRUE: ProbExplanation = + BinaryDecisionDiagramExplanation( + bddTerminalOf(true), + BinaryDecisionDiagramExplanation.TRUE_COMPUTED_VALUE, + ) /** Creates a new [ProbExplanation] representing the single probabilistic logic term [term]. */ fun of(term: ProbTerm): ProbExplanation { return BinaryDecisionDiagramExplanation( bddOf(term), BinaryDecisionDiagramExplanation.ComputedValue( - term.probability - ) + term.probability, + ), ) } } diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/ProbExplanationTerm.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/ProbExplanationTerm.kt index 25fe96fab..d96a7c319 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/ProbExplanationTerm.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/ProbExplanationTerm.kt @@ -13,9 +13,8 @@ import it.unibo.tuprolog.core.Substitution * @author Jason Dellaluce */ internal class ProbExplanationTerm( - val explanation: ProbExplanation + val explanation: ProbExplanation, ) : Atom by Atom.of("") { - override val isConstant: Boolean get() = false @@ -29,11 +28,17 @@ internal class ProbExplanationTerm( return ProbExplanationTerm(explanation.apply { it.freshCopy(scope) }) } - override fun get(substitution: Substitution, vararg substitutions: Substitution): ProbExplanationTerm { + override fun get( + substitution: Substitution, + vararg substitutions: Substitution, + ): ProbExplanationTerm { return this.apply(substitution, *substitutions) } - override fun apply(substitution: Substitution, vararg substitutions: Substitution): ProbExplanationTerm { + override fun apply( + substitution: Substitution, + vararg substitutions: Substitution, + ): ProbExplanationTerm { return this.apply(Substitution.of(substitution, *substitutions)) } diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/ProbTerm.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/ProbTerm.kt index e55186e0f..4f045e29c 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/ProbTerm.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/ProbTerm.kt @@ -29,9 +29,8 @@ internal class ProbTerm( val id: Long, val probability: Double, val term: Term, - val extraVariables: Set = emptySet() + val extraVariables: Set = emptySet(), ) : Term by Struct.of(ANNOTATION_FUNCTOR, Numeric.of(probability), term) { - override fun freshCopy(): ProbTerm { val termCopy = term.freshCopy() return ProbTerm(id, probability, termCopy, extraVariables.map { it.freshCopy() }.toSet()) @@ -42,11 +41,17 @@ internal class ProbTerm( return ProbTerm(id, probability, termCopy, extraVariables.map { it.freshCopy(scope) }.toSet()) } - override fun get(substitution: Substitution, vararg substitutions: Substitution): ProbTerm { + override fun get( + substitution: Substitution, + vararg substitutions: Substitution, + ): ProbTerm { return this.apply(substitution, *substitutions) } - override fun apply(substitution: Substitution, vararg substitutions: Substitution): ProbTerm { + override fun apply( + substitution: Substitution, + vararg substitutions: Substitution, + ): ProbTerm { return this.apply(Substitution.of(substitution, *substitutions)) } @@ -54,13 +59,14 @@ internal class ProbTerm( return if (substitution.isEmpty() || this.isGround) { this } else { - val newExtraVars = if (!extraVariables.any { it.isVar }) { - extraVariables - } else { - extraVariables - .mapNotNull { substitution.applyTo(it) } - .toSet() - } + val newExtraVars = + if (!extraVariables.any { it.isVar }) { + extraVariables + } else { + extraVariables + .mapNotNull { substitution.applyTo(it) } + .toSet() + } ProbTerm(id, probability, term.apply(substitution), newExtraVars) } } diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/ProblogTheory.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/ProblogTheory.kt index b0e299e28..f6dbfa42c 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/ProblogTheory.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/ProblogTheory.kt @@ -23,7 +23,6 @@ import kotlin.jvm.JvmStatic * @author Jason Dellaluce * */ interface ProblogTheory : Theory { - override val isMutable: Boolean get() = false override fun toMutableTheory(): MutableProblogTheory @@ -58,13 +57,11 @@ interface ProblogTheory : Theory { override fun retract(clauses: Sequence): RetractResult - override fun retract(head: Struct): RetractResult = - retract(Rule.of(head, Var.anonymous())) + override fun retract(head: Struct): RetractResult = retract(Rule.of(head, Var.anonymous())) override fun retractAll(clause: Clause): RetractResult - override fun retractAll(head: Struct): RetractResult = - retractAll(Rule.of(head, Var.anonymous())) + override fun retractAll(head: Struct): RetractResult = retractAll(Rule.of(head, Var.anonymous())) override fun abolish(indicator: Indicator): ProblogTheory @@ -72,32 +69,40 @@ interface ProblogTheory : Theory { /** Creates an empty [ProblogTheory] */ @JvmStatic @JsName("empty") - fun empty(unificator: Unificator): ProblogTheory = - of(unificator, emptyList()) + fun empty(unificator: Unificator): ProblogTheory = of(unificator, emptyList()) /** Creates a [ProblogTheory], containing the given clauses */ @JvmStatic @JsName("of") - fun of(unificator: Unificator, vararg clause: Clause): ProblogTheory = - of(unificator, clause.asIterable()) + fun of( + unificator: Unificator, + vararg clause: Clause, + ): ProblogTheory = of(unificator, clause.asIterable()) /** Creates a [ProblogTheory], containing the given clauses */ @JvmStatic @JsName("ofSequence") - fun of(unificator: Unificator, clauses: Sequence): ProblogTheory = - of(unificator, clauses.asIterable()) + fun of( + unificator: Unificator, + clauses: Sequence, + ): ProblogTheory = of(unificator, clauses.asIterable()) /** Let developers easily create a [[ProblogTheory], while avoiding variables names clashing by using a * different [Scope] for each [Clause] */ @JvmStatic @JsName("ofScopes") - fun of(unificator: Unificator, vararg clauses: Scope.() -> Clause): ProblogTheory = - of(unificator, clauses.map { Scope.empty().it() }) + fun of( + unificator: Unificator, + vararg clauses: Scope.() -> Clause, + ): ProblogTheory = of(unificator, clauses.map { Scope.empty().it() }) /** Creates a [ProblogTheory] containing the given clauses */ @JvmStatic @JsName("ofIterable") - fun of(unificator: Unificator, clauses: Iterable): ProblogTheory = + fun of( + unificator: Unificator, + clauses: Iterable, + ): ProblogTheory = if (clauses is MutableTheory) { MutableProblogTheory.of(unificator, clauses) } else { diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/AnnotatedDisjunctionClauseMapper.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/AnnotatedDisjunctionClauseMapper.kt index bd5c5e3e2..56e5aefd9 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/AnnotatedDisjunctionClauseMapper.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/AnnotatedDisjunctionClauseMapper.kt @@ -46,22 +46,23 @@ internal object AnnotatedDisjunctionClauseMapper : ClauseMapper { collectAllHeads(clause.head, disjointHeads) var probSum = 0.0 - val mappedRules = disjointHeads.map { cur -> - val curProb = (cur[0] as Numeric).decimalValue.toDouble() - val curRuleHead = if (cur[1] is Struct) cur[1] as Struct else Struct.of(cur[1].toString()) + val mappedRules = + disjointHeads.map { cur -> + val curProb = (cur[0] as Numeric).decimalValue.toDouble() + val curRuleHead = if (cur[1] is Struct) cur[1] as Struct else Struct.of(cur[1].toString()) - probSum += curProb - ProbabilisticClauseMapper.mapRuleInternal( - Rule.of( - Struct.of( - ANNOTATION_FUNCTOR, - Numeric.of(curProb / (1.0 - (probSum - curProb))), - curRuleHead + probSum += curProb + ProbabilisticClauseMapper.mapRuleInternal( + Rule.of( + Struct.of( + ANNOTATION_FUNCTOR, + Numeric.of(curProb / (1.0 - (probSum - curProb))), + curRuleHead, + ), + body, ), - body ) - ) - }.toList() + }.toList() var explanation: ProbExplanation = ProbExplanation.TRUE return mappedRules.map { @@ -72,7 +73,10 @@ internal object AnnotatedDisjunctionClauseMapper : ClauseMapper { } } - private fun collectAllHeads(head: Term, accumulator: MutableList) { + private fun collectAllHeads( + head: Term, + accumulator: MutableList, + ) { if (head is Struct && head.arity == 2) { if (head.functor != Semicolon.FUNCTOR && head.functor != ANNOTATION_FUNCTOR) { throw TuPrologException("Badly formatted disjoint annotation: $head") @@ -88,10 +92,11 @@ internal object AnnotatedDisjunctionClauseMapper : ClauseMapper { curHead = if (head.functor == Semicolon.FUNCTOR) head[0] else head if (curHead is Struct && curHead.functor == ANNOTATION_FUNCTOR) { val curHeadProbTerm = curHead[0] - curHeadProb = when (curHeadProbTerm) { - is Numeric -> curHeadProbTerm.decimalValue.toDouble() - else -> curHeadProbTerm.solveArithmeticExpression() - } + curHeadProb = + when (curHeadProbTerm) { + is Numeric -> curHeadProbTerm.decimalValue.toDouble() + else -> curHeadProbTerm.solveArithmeticExpression() + } curHead = curHead[1] } } diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/BinaryDecisionDiagramExplanation.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/BinaryDecisionDiagramExplanation.kt index 6f90015de..580e6fae8 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/BinaryDecisionDiagramExplanation.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/BinaryDecisionDiagramExplanation.kt @@ -17,11 +17,10 @@ import it.unibo.tuprolog.solve.problog.lib.knowledge.ProbTerm * */ internal class BinaryDecisionDiagramExplanation( val diagram: BinaryDecisionDiagram, - private val computedValue: ComputedValue = EMPTY_COMPUTED_VALUE + private val computedValue: ComputedValue = EMPTY_COMPUTED_VALUE, ) : ProbExplanation { - internal data class ComputedValue( - val probability: Double? + val probability: Double?, ) companion object { @@ -37,39 +36,46 @@ internal class BinaryDecisionDiagramExplanation( return that } - private fun computeExpansion(value: ProbTerm, low: ComputedValue, high: ComputedValue): ComputedValue { + private fun computeExpansion( + value: ProbTerm, + low: ComputedValue, + high: ComputedValue, + ): ComputedValue { return ComputedValue( if (low.probability != null && high.probability != null) { value.probability * high.probability + (1.0 - value.probability) * low.probability } else { null - } + }, ) } private val cachedNot: ProbExplanation by lazy { - val result = diagram.notThenExpansion(FALSE_COMPUTED_VALUE, TRUE_COMPUTED_VALUE) { - node, low, high -> - computeExpansion(node, low, high) - } + val result = + diagram.notThenExpansion(FALSE_COMPUTED_VALUE, TRUE_COMPUTED_VALUE) { + node, low, high -> + computeExpansion(node, low, high) + } BinaryDecisionDiagramExplanation(result.first, result.second) } override fun not(): ProbExplanation = cachedNot override fun and(that: ProbExplanation): ProbExplanation { - val result = diagram.andThenExpansion(getAsInternal(that).diagram, FALSE_COMPUTED_VALUE, TRUE_COMPUTED_VALUE) { - node, low, high -> - computeExpansion(node, low, high) - } + val result = + diagram.andThenExpansion(getAsInternal(that).diagram, FALSE_COMPUTED_VALUE, TRUE_COMPUTED_VALUE) { + node, low, high -> + computeExpansion(node, low, high) + } return BinaryDecisionDiagramExplanation(result.first, result.second) } override fun or(that: ProbExplanation): ProbExplanation { - val result = diagram.orThenExpansion(getAsInternal(that).diagram, FALSE_COMPUTED_VALUE, TRUE_COMPUTED_VALUE) { - node, low, high -> - computeExpansion(node, low, high) - } + val result = + diagram.orThenExpansion(getAsInternal(that).diagram, FALSE_COMPUTED_VALUE, TRUE_COMPUTED_VALUE) { + node, low, high -> + computeExpansion(node, low, high) + } return BinaryDecisionDiagramExplanation(result.first, result.second) } @@ -92,7 +98,7 @@ internal class BinaryDecisionDiagramExplanation( return BinaryDecisionDiagramExplanation( diagram.map { transformation(it) - } + }, ) } } diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/ClauseMapper.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/ClauseMapper.kt index cd48f3296..d656ea438 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/ClauseMapper.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/ClauseMapper.kt @@ -9,7 +9,6 @@ import it.unibo.tuprolog.core.Clause * @author Jason Dellaluce */ internal interface ClauseMapper { - /** Returns true if this mapping can be applied to [clause]. */ fun isCompatible(clause: Clause): Boolean diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/ClauseMappingUtils.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/ClauseMappingUtils.kt index f15ad7805..49ec9e035 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/ClauseMappingUtils.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/ClauseMappingUtils.kt @@ -24,17 +24,17 @@ import it.unibo.tuprolog.utils.setTag * @author Jason Dellaluce */ internal object ClauseMappingUtils { - private var clauseIndex: Long = 1 - private val cascadeMappers = listOf( - DirectiveClauseMapper, - AnnotatedDisjunctionClauseMapper, - ProbabilisticClauseMapper, - EvidenceClauseMapper, - PrologClauseMapper, - NothingClauseMapper - ) + private val cascadeMappers = + listOf( + DirectiveClauseMapper, + AnnotatedDisjunctionClauseMapper, + ProbabilisticClauseMapper, + EvidenceClauseMapper, + PrologClauseMapper, + NothingClauseMapper, + ) /** Generates a new clause identifier. * Identifying clauses is necessary to distinguish them @@ -60,7 +60,7 @@ internal object ClauseMappingUtils { when (arityTerm) { is Numeric -> Numeric.of(arityTerm.intValue.toInt() + 1) else -> arityTerm - } + }, ) } } @@ -79,7 +79,7 @@ internal val Term.isWrappableWithExplanation: Boolean get() = this.safeToStruct( internal fun Term.withExplanationNonWrappable(explanation: Term): Struct { return Tuple.of( this, - Struct.of("=", explanation, ProbExplanation.TRUE.toTerm()) + Struct.of("=", explanation, ProbExplanation.TRUE.toTerm()), ) } @@ -113,7 +113,10 @@ internal fun Term.withBodyExplanation(explanation: Term): Struct { * * The wrapping is not applied recursively. * */ -internal fun Term.wrapInPredicate(functor: String, explanation: Term): Struct { +internal fun Term.wrapInPredicate( + functor: String, + explanation: Term, +): Struct { return if (!this.isWrappableWithExplanation) { this.withExplanationNonWrappable(explanation) } else { @@ -134,7 +137,11 @@ internal fun Term.wrapInPredicate(functor: String, explanation: Term): Struct { * semantics provided by Prolog for those predicates. Most of them represent, in fact, * an operator. * */ -internal fun Term.wrapInPredicateRecursive(functor: String, explanation: Term, depth: Int = 1): Struct { +internal fun Term.wrapInPredicateRecursive( + functor: String, + explanation: Term, + depth: Int = 1, +): Struct { return when (this) { is Struct -> { when (this.functor) { @@ -144,21 +151,21 @@ internal fun Term.wrapInPredicateRecursive(functor: String, explanation: Term, d Tuple.of( this[0].wrapInPredicateRecursive(functor, leftVar, depth + 1), this[1].wrapInPredicateRecursive(functor, rightVar, depth + 1), - Struct.of(ProbExplAnd.functor, explanation, leftVar, rightVar) + Struct.of(ProbExplAnd.functor, explanation, leftVar, rightVar), ) } ";" -> { Struct.of( ";", this[0].wrapInPredicateRecursive(functor, explanation, depth + 1), - this[1].wrapInPredicateRecursive(functor, explanation, depth + 1) + this[1].wrapInPredicateRecursive(functor, explanation, depth + 1), ) } "->" -> { Struct.of( "->", this[0].wrapInPredicateRecursive(functor, Var.anonymous(), depth + 1), - this[1].wrapInPredicateRecursive(functor, explanation, depth + 1) + this[1].wrapInPredicateRecursive(functor, explanation, depth + 1), ) } else -> { @@ -200,24 +207,26 @@ internal fun Term.safeToStruct(): Struct { /** Given a [this], removes all anonymous [Var] variables contained * in head and body, substituting them with non-anonymous variables. */ internal fun Rule.withoutAnonymousVars(): Rule { - val anonVarSubstitution = Substitution.of( - this.head.variables.toSet() - .plus(this.body.variables.toSet()) - .filter { - it.isAnonymous - } - .mapIndexed { index, it -> - Pair(it, Var.of("ANON_$index")) - } - ) + val anonVarSubstitution = + Substitution.of( + this.head.variables.toSet() + .plus(this.body.variables.toSet()) + .filter { + it.isAnonymous + } + .mapIndexed { index, it -> + Pair(it, Var.of("ANON_$index")) + }, + ) return when (this) { is Fact -> { Fact.of(this.head.apply(anonVarSubstitution).safeToStruct()) } - else -> Rule.of( - this.head.apply(anonVarSubstitution).safeToStruct(), - this.body.apply(anonVarSubstitution).safeToStruct() - ) + else -> + Rule.of( + this.head.apply(anonVarSubstitution).safeToStruct(), + this.body.apply(anonVarSubstitution).safeToStruct(), + ) } } @@ -231,16 +240,17 @@ internal fun ProbExplanation.toTerm(): Term { * an exception is thrown. */ internal fun Term.solveArithmeticExpression(): Double { val termStr = this.toString().replace("\\s".toRegex(), "") - val regexMatch = Regex("([0-9.]+)(/)([0-9.]+).*").find(termStr) - ?: throw TuPrologException( - "Unsupported probability notation in annotated disjunction: $termStr" - ) + val regexMatch = + Regex("([0-9.]+)(/)([0-9.]+).*").find(termStr) + ?: throw TuPrologException( + "Unsupported probability notation in annotated disjunction: $termStr", + ) val (dividendStr, _, divisorStr) = regexMatch.destructured val dividend = dividendStr.toDoubleOrNull() val divisor = divisorStr.toDoubleOrNull() if (dividend == null || divisor == null) { throw TuPrologException( - "Unable to parse arithmetic division expression: $termStr" + "Unable to parse arithmetic division expression: $termStr", ) } return dividend / divisor diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/DirectiveClauseMapper.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/DirectiveClauseMapper.kt index fde7a88c2..d09dd4855 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/DirectiveClauseMapper.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/DirectiveClauseMapper.kt @@ -12,7 +12,6 @@ import it.unibo.tuprolog.solve.problog.lib.exception.ClauseMappingException * * @author Jason Dellaluce */ internal object DirectiveClauseMapper : ClauseMapper { - override fun isCompatible(clause: Clause): Boolean { return clause.isDirective } @@ -38,9 +37,9 @@ internal object DirectiveClauseMapper : ClauseMapper { Directive.of( Struct.of( body.functor, - Indicator.of(name, Numeric.of(arity.decimalValue.toInt() + 1)) - ) - ) + Indicator.of(name, Numeric.of(arity.decimalValue.toInt() + 1)), + ), + ), ) } @@ -49,9 +48,9 @@ internal object DirectiveClauseMapper : ClauseMapper { Directive.of( Struct.of( body.functor, - body[0].withBodyExplanation(Var.anonymous()) - ) - ) + body[0].withBodyExplanation(Var.anonymous()), + ), + ), ) } diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/EvidenceClauseMapper.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/EvidenceClauseMapper.kt index 7256e288e..e8c579d70 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/EvidenceClauseMapper.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/EvidenceClauseMapper.kt @@ -37,7 +37,7 @@ internal object EvidenceClauseMapper : ClauseMapper { throw TuPrologException("Invalid evidence predicate: ${clause.head}") } - /* Adjust implicit evidence predicates */ + // Adjust implicit evidence predicates var headTerm = clause.head if (headTerm.arity == 1) { headTerm = Struct.of(headTerm.functor, headTerm[0], Truth.TRUE) @@ -49,9 +49,9 @@ internal object EvidenceClauseMapper : ClauseMapper { } else { Rule.of( headTerm, - clause.body.withBodyExplanation(Var.anonymous()) + clause.body.withBodyExplanation(Var.anonymous()), ) - } + }, ) } } diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/MappedMutableProblogTheory.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/MappedMutableProblogTheory.kt index 08117054e..602869374 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/MappedMutableProblogTheory.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/MappedMutableProblogTheory.kt @@ -24,9 +24,14 @@ import it.unibo.tuprolog.unify.Unificator internal class MappedMutableProblogTheory( clauses: Iterable?, unificator: Unificator = Unificator.default, - val theory: MutableTheory = MutableTheory.indexedOf(unificator, clauses?.flatMap { ClauseMappingUtils.map(it) } ?: emptyList()) + val theory: MutableTheory = + MutableTheory.indexedOf( + unificator, + clauses?.flatMap { + ClauseMappingUtils.map(it) + } ?: emptyList(), + ), ) : MutableTheory by theory, MutableProblogTheory { - override val isMutable: Boolean get() = false @@ -63,10 +68,11 @@ internal class MappedMutableProblogTheory( override fun retract(clauses: Iterable): RetractResult { val mapped = clauses.flatMap { ClauseMappingUtils.map(it) } return when (val result = theory.retract(mapped)) { - is RetractResult.Success -> RetractResult.Success( - MappedMutableProblogTheory(null, unificator, result.theory), - result.clauses - ) + is RetractResult.Success -> + RetractResult.Success( + MappedMutableProblogTheory(null, unificator, result.theory), + result.clauses, + ) else -> RetractResult.Failure(MappedMutableProblogTheory(null, unificator, result.theory)) } } @@ -84,11 +90,15 @@ internal class MappedMutableProblogTheory( } return when (result) { - is RetractResult.Success -> RetractResult.Success( - MappedMutableProblogTheory(null, unificator, result.theory), - result.clauses - ) - is RetractResult.Failure -> RetractResult.Failure(MappedMutableProblogTheory(null, unificator, result.theory)) + is RetractResult.Success -> + RetractResult.Success( + MappedMutableProblogTheory(null, unificator, result.theory), + result.clauses, + ) + is RetractResult.Failure -> + RetractResult.Failure( + MappedMutableProblogTheory(null, unificator, result.theory), + ) else -> RetractResult.Failure(this) } } @@ -117,8 +127,7 @@ internal class MappedMutableProblogTheory( return assertZ(clauses.asIterable()) } - override fun retract(head: Struct): RetractResult = - retract(Rule.of(head, Var.anonymous())) + override fun retract(head: Struct): RetractResult = retract(Rule.of(head, Var.anonymous())) override fun retract(clause: Clause): RetractResult { return retract(listOf(clause)) @@ -129,5 +138,7 @@ internal class MappedMutableProblogTheory( } override fun retractAll(head: Struct): RetractResult = - retractAll(Rule.of(head, Var.anonymous())) + retractAll( + Rule.of(head, Var.anonymous()), + ) } diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/MappedProblogTheory.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/MappedProblogTheory.kt index df75bec82..96a463238 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/MappedProblogTheory.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/MappedProblogTheory.kt @@ -23,9 +23,8 @@ import it.unibo.tuprolog.unify.Unificator internal class MappedProblogTheory( clauses: Iterable?, unificator: Unificator = Unificator.default, - val theory: Theory = Theory.indexedOf(unificator, clauses?.flatMap { ClauseMappingUtils.map(it) } ?: emptyList()) + val theory: Theory = Theory.indexedOf(unificator, clauses?.flatMap { ClauseMappingUtils.map(it) } ?: emptyList()), ) : Theory by theory, ProblogTheory { - override val isMutable: Boolean get() = false @@ -62,10 +61,11 @@ internal class MappedProblogTheory( override fun retract(clauses: Iterable): RetractResult { val mapped = clauses.flatMap { ClauseMappingUtils.map(it) } return when (val result = theory.retract(mapped)) { - is RetractResult.Success -> RetractResult.Success( - MappedProblogTheory(null, unificator, result.theory), - result.clauses - ) + is RetractResult.Success -> + RetractResult.Success( + MappedProblogTheory(null, unificator, result.theory), + result.clauses, + ) else -> RetractResult.Failure(MappedProblogTheory(null, unificator, result.theory)) } } @@ -80,10 +80,11 @@ internal class MappedProblogTheory( } return when (result) { - is RetractResult.Success -> RetractResult.Success( - MappedProblogTheory(null, unificator, result.theory), - result.clauses - ) + is RetractResult.Success -> + RetractResult.Success( + MappedProblogTheory(null, unificator, result.theory), + result.clauses, + ) else -> RetractResult.Failure(this) } } @@ -112,8 +113,7 @@ internal class MappedProblogTheory( return assertZ(clauses.asIterable()) } - override fun retract(head: Struct): RetractResult = - retract(Rule.of(head, Var.anonymous())) + override fun retract(head: Struct): RetractResult = retract(Rule.of(head, Var.anonymous())) override fun retract(clause: Clause): RetractResult { return retract(listOf(clause)) @@ -123,6 +123,5 @@ internal class MappedProblogTheory( return retract(clauses.asIterable()) } - override fun retractAll(head: Struct): RetractResult = - retractAll(Rule.of(head, Var.anonymous())) + override fun retractAll(head: Struct): RetractResult = retractAll(Rule.of(head, Var.anonymous())) } diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/ProbabilisticClauseMapper.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/ProbabilisticClauseMapper.kt index 35ee0cd19..f4607276f 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/ProbabilisticClauseMapper.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/ProbabilisticClauseMapper.kt @@ -39,13 +39,14 @@ internal object ProbabilisticClauseMapper : ClauseMapper { throw TuPrologException("Invalid probabilistic rule: ${rule.head}") } - /* Extract probability value */ - var probability = when (val probTerm = rule.head[0]) { - is Numeric -> probTerm.decimalValue.toDouble() - else -> probTerm.solveArithmeticExpression() - } + // Extract probability value + var probability = + when (val probTerm = rule.head[0]) { + is Numeric -> probTerm.decimalValue.toDouble() + else -> probTerm.solveArithmeticExpression() + } - /* Extract head predicate */ + // Extract head predicate var headTerm = rule.head[1].safeToStruct() if (headTerm.functor == ProblogLib.EVIDENCE_PREDICATE) { throw TuPrologException("Probability notation can't be expressed on evidence: " + rule.head) @@ -65,28 +66,31 @@ internal object ProbabilisticClauseMapper : ClauseMapper { } } - /* Remove anonymous variables */ + // Remove anonymous variables val anonVariablesFix = Rule.of(headTerm, bodyTerm).withoutAnonymousVars() headTerm = anonVariablesFix.head bodyTerm = anonVariablesFix.body - /* Probabilistic term of this rule */ + // Probabilistic term of this rule val extraVariables = Rule.of(headTerm, bodyTerm).extraVariables val probTerm = ProbTerm(ClauseMappingUtils.newClauseId(), probability, headTerm, extraVariables) return Pair(Rule.of(headTerm, bodyTerm), probTerm) } - fun mapRuleWithExplanation(rule: Rule, explanation: ProbExplanation): Rule { - /* Problog probabilistic facts */ + fun mapRuleWithExplanation( + rule: Rule, + explanation: ProbExplanation, + ): Rule { + // Problog probabilistic facts if (rule.body is Truth) { return Rule.of( rule.head.withExplanation(explanation.toTerm()), - rule.body + rule.body, ) } - /* Problog probabilistic rules */ + // Problog probabilistic rules val explanationVar = Var.of("${ProblogLib.EXPLANATION_VAR_NAME}_Res") val explanationBodyVar = Var.of("${ProblogLib.EXPLANATION_VAR_NAME}_Body") val newBody = rule.body.withBodyExplanation(explanationBodyVar) @@ -95,8 +99,8 @@ internal object ProbabilisticClauseMapper : ClauseMapper { Struct.of( ",", newBody, - Struct.of(ProbExplAnd.functor, explanationVar, explanationBodyVar, explanation.toTerm()) - ) + Struct.of(ProbExplAnd.functor, explanationVar, explanationBodyVar, explanation.toTerm()), + ), ) } } diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/PrologClauseMapper.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/PrologClauseMapper.kt index ad05d6fee..43d4ebba7 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/PrologClauseMapper.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/PrologClauseMapper.kt @@ -15,7 +15,6 @@ import it.unibo.tuprolog.solve.problog.lib.knowledge.ProbExplanation * * @author Jason Dellaluce */ internal object PrologClauseMapper : ClauseMapper { - override fun isCompatible(clause: Clause): Boolean { return clause is Rule } @@ -25,13 +24,13 @@ internal object PrologClauseMapper : ClauseMapper { throw ClauseMappingException("Clause is not an instance of Rule: $clause") } - /* Map facts and truths differently */ + // Map facts and truths differently if (clause.body is Truth) { return listOf( Rule.of( clause.head.withExplanation(ProbExplanation.TRUE.toTerm()), - clause.body - ) + clause.body, + ), ) } @@ -39,8 +38,8 @@ internal object PrologClauseMapper : ClauseMapper { return listOf( Rule.of( clause.head.withExplanation(explanationVar), - clause.body.withBodyExplanation(explanationVar) - ) + clause.body.withBodyExplanation(explanationVar), + ), ) } } diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbExplAnd.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbExplAnd.kt index 562cf3159..8911f2961 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbExplAnd.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbExplAnd.kt @@ -18,26 +18,33 @@ import it.unibo.tuprolog.solve.problog.lib.primitive.ProbSetConfig.isPrologMode * @author Jason Dellaluce */ internal object ProbExplAnd : TernaryRelation.NonBacktrackable( - "${ProblogLib.PREDICATE_PREFIX}_expl_and" + "${ProblogLib.PREDICATE_PREFIX}_expl_and", ) { + private val ProbExplanationTerm.prob: Double + get() = explanation.probability - override fun Solve.Request.computeOne(first: Term, second: Term, third: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + third: Term, + ): Solve.Response { ensuringArgumentIsInstantiated(1) ensuringArgumentIsCallable(1) - /* Skip computations for Prolog-only queries */ + // Skip computations for Prolog-only queries if (context.isPrologMode()) { return replyWith(mgu(first, ProbExplanation.TRUE.toTerm())) } return if (first is Var && second is ProbExplanationTerm && third is ProbExplanationTerm) { - val explanation = when { - second.explanation.probability == 0.0 || third.explanation.probability == 0.0 -> ProbExplanation.FALSE - second.explanation.probability == 1.0 && third.explanation.probability == 1.0 -> ProbExplanation.TRUE - second.explanation.probability == 1.0 -> third.explanation - third.explanation.probability == 1.0 -> second.explanation - else -> second.explanation and third.explanation - } + val explanation = + when { + second.prob == 0.0 || third.prob == 0.0 -> ProbExplanation.FALSE + second.prob == 1.0 && third.prob == 1.0 -> ProbExplanation.TRUE + second.prob == 1.0 -> third.explanation + third.prob == 1.0 -> second.explanation + else -> second.explanation and third.explanation + } if (explanation.probability == 0.0) { replyWith(false) } else { diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbHelper.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbHelper.kt index 404d7b6bf..eeb815b1c 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbHelper.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbHelper.kt @@ -35,11 +35,10 @@ import it.unibo.tuprolog.solve.problog.lib.rules.Prob * @author Jason Dellaluce */ internal object ProbHelper : TernaryRelation.WithoutSideEffects("${PREDICATE_PREFIX}_helper") { - override fun Solve.Request.computeAllSubstitutions( first: Term, second: Term, - third: Term + third: Term, ): Sequence { ensuringArgumentIsInstantiated(1) ensuringArgumentIsCallable(1) @@ -47,32 +46,34 @@ internal object ProbHelper : TernaryRelation.WithoutSideEffects yield( - /* Optimize Prolog-only queries */ - if (context.isPrologMode()) { - mgu(third, Struct.of(goal.functor, Struct.of(Prob.functor, Var.anonymous(), goal[0]))) + - mgu(first, ProbExplanation.TRUE.toTerm()) - } else { - mgu(third, Struct.of(ProbNegationAsFailure.functor, first, goal[0])) - } - ) + // Edge case: Negation as failure + "\\+", "not" -> + yield( + // Optimize Prolog-only queries + if (context.isPrologMode()) { + mgu(third, Struct.of(goal.functor, Struct.of(Prob.functor, Var.anonymous(), goal[0]))) + + mgu(first, ProbExplanation.TRUE.toTerm()) + } else { + mgu(third, Struct.of(ProbNegationAsFailure.functor, first, goal[0])) + }, + ) /* Edge case: The current goal is a conjunction/disjunction or any sort of recursive predicate. * NOTE: This is not supposed to trigger regularly because we map the theory prior to query execution, * however this happens when the current goal is the initial query itself. As such, we want recursive * predicates in queries to be supported. */ - ",", ";", "->" -> yield( - /* Optimize Prolog-only queries */ - if (context.isPrologMode()) { - mgu(third, goal.withBodyExplanation(Var.anonymous())) + - mgu(first, ProbExplanation.TRUE.toTerm()) - } else { - mgu(third, goal.withBodyExplanation(first)) - } - ) - /* Edge case: call/1 predicate*/ + ",", ";", "->" -> + yield( + // Optimize Prolog-only queries + if (context.isPrologMode()) { + mgu(third, goal.withBodyExplanation(Var.anonymous())) + + mgu(first, ProbExplanation.TRUE.toTerm()) + } else { + mgu(third, goal.withBodyExplanation(first)) + }, + ) + // Edge case: call/1 predicate "call" -> { val newGoal = goal[0] yield( @@ -80,12 +81,12 @@ internal object ProbHelper : TernaryRelation.WithoutSideEffects { yield( mgu( @@ -94,45 +95,48 @@ internal object ProbHelper : TernaryRelation.WithoutSideEffects { val goalArgs = goal.args.toTypedArray() goalArgs[1] = goalArgs[1].withBodyExplanation(Var.anonymous()) yield( mgu(third, Struct.of(goal.functor, *goalArgs)) + - mgu(first, ProbExplanation.TRUE.toTerm()) + mgu(first, ProbExplanation.TRUE.toTerm()), ) } - /* Edge case: assert family */ + // Edge case: assert family "assert", "asserta", "assertz" -> { val subGoal = goal[0] - val subGoalSignature = when (subGoal) { - is Clause -> subGoal.head!!.extractSignature() - else -> subGoal.safeToStruct().extractSignature() - } + val subGoalSignature = + when (subGoal) { + is Clause -> subGoal.head!!.extractSignature() + else -> subGoal.safeToStruct().extractSignature() + } if (subGoalSignature in context.libraries || (subGoal is Clause && !subGoal.isWellFormed)) { yield(mgu(third, goal) + mgu(first, ProbExplanation.TRUE.toTerm())) } else { - val newGoals = when (subGoal) { - is Clause -> ClauseMappingUtils.map(subGoal) - is Struct -> ClauseMappingUtils.map(Fact.of(subGoal)).map { - it.head!! + val newGoals = + when (subGoal) { + is Clause -> ClauseMappingUtils.map(subGoal) + is Struct -> + ClauseMappingUtils.map(Fact.of(subGoal)).map { + it.head!! + } + else -> listOf(subGoal) } - else -> listOf(subGoal) - } yieldAll( newGoals.map { mgu(third, Struct.of(goal.functor, it)) + mgu(first, ProbExplanation.TRUE.toTerm()) - } + }, ) } } - /* Edge case: retract family */ + // Edge case: retract family "retract", "retractall" -> { val goalArg = goal[0] yield( @@ -147,12 +151,12 @@ internal object ProbHelper : TernaryRelation.WithoutSideEffects { val subGoal = goal[0] if (subGoal !is Struct || context.libraries.hasProtected(subGoal.extractSignature())) { @@ -164,15 +168,15 @@ internal object ProbHelper : TernaryRelation.WithoutSideEffects { - /* Support for Prolog libraries backwards compatibility */ + // Support for Prolog libraries backwards compatibility val isPrologOnly = second is Truth || goalSignature in context.libraries if (isPrologOnly || goalSignature.toIndicator() in context.staticKb || @@ -181,7 +185,7 @@ internal object ProbHelper : TernaryRelation.WithoutSideEffects( - "${ProblogLib.PREDICATE_PREFIX}_negation_as_failure" + "${ProblogLib.PREDICATE_PREFIX}_negation_as_failure", ) { - - override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response { ensuringArgumentIsInstantiated(1) ensuringArgumentIsCallable(1) @@ -33,15 +35,16 @@ internal object ProbNegationAsFailure : BinaryRelation.NonBacktrackable( - "${PREDICATE_PREFIX}_query" + "${PREDICATE_PREFIX}_query", ) { override fun Solve.Request.computeAllSubstitutions( first: Term, second: Term, third: Term, - fourth: Term + fourth: Term, ): Sequence { ensuringArgumentIsInstantiated(1) ensuringArgumentIsCallable(1) @@ -36,13 +36,14 @@ internal object ProbQuery : QuaternaryRelation.WithoutSideEffects - v != evidenceExplanation && v != queryWithEvidenceExplanation - } + val solutionSubstitution = + solution.substitution.filter { + v, _ -> + v != evidenceExplanation && v != queryWithEvidenceExplanation + } val probabilityTerm = Numeric.of(queryWithEvidenceProbability / evidenceProbability) yield( Substitution.of( solutionSubstitution, mgu(first, probabilityTerm), - mgu(fourth, queryWithEvidenceExplanationTerm) - ) + mgu(fourth, queryWithEvidenceExplanationTerm), + ), ) } } diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbSetConfig.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbSetConfig.kt index 1252d776f..ca991c7d8 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbSetConfig.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbSetConfig.kt @@ -13,9 +13,8 @@ import it.unibo.tuprolog.solve.sideffects.SideEffect import it.unibo.tuprolog.utils.setTag internal object ProbSetConfig : UnaryPredicate.NonBacktrackable( - "${ProblogLib.PREDICATE_PREFIX}_set_config" + "${ProblogLib.PREDICATE_PREFIX}_set_config", ) { - private val CONFIG_FLAG = "${this.functor}_flag" private val CONFIG_TERM_NAME = "${this.functor}_term" private val CONFIG_TERM_TAG = "it.unibo.tuprolog.solve.probability${this.functor}_tag" diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbSolve.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbSolve.kt index a93408f89..acf49b4d2 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbSolve.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbSolve.kt @@ -37,15 +37,14 @@ import it.unibo.tuprolog.solve.problog.lib.rules.Prob * @author Jason Dellaluce */ internal object ProbSolve : BinaryRelation.WithoutSideEffects("${PREDICATE_PREFIX}_solve") { - override fun Solve.Request.computeAllSubstitutions( first: Term, - second: Term + second: Term, ): Sequence { ensuringArgumentIsInstantiated(1) ensuringArgumentIsCallable(1) - /* Optimize Prolog-only queries */ + // Optimize Prolog-only queries if (context.isPrologMode()) { return subSolver().solve(Struct.of(Prob.functor, first, second), context.getSolverOptions()).map { if (it.isHalt) throw it.exception!! @@ -54,36 +53,40 @@ internal object ProbSolve : BinaryRelation.WithoutSideEffects( } val explanationVar = Var.of(EXPLANATION_VAR_NAME) - val solutions = subSolver() - .solve(Struct.of(Prob.functor, explanationVar, second), context.getSolverOptions()) - .toList() + val solutions = + subSolver() + .solve(Struct.of(Prob.functor, explanationVar, second), context.getSolverOptions()) + .toList() val error = solutions.asSequence().filterIsInstance().firstOrNull() if (error != null) throw error.exception return if (!solutions.any { s -> s is Solution.Yes }) { sequenceOf(Substitution.of(mgu(first, ProbExplanationTerm(ProbExplanation.FALSE)))) } else { - val solutionGroups = solutions - .filterIsInstance() - .groupBy { it.substitution.filter { v, _ -> v != explanationVar } } + val solutionGroups = + solutions + .filterIsInstance() + .groupBy { it.substitution.filter { v, _ -> v != explanationVar } } sequence { for (solutionGroup in solutionGroups) { - val explanation: ProbExplanation = solutionGroup.value - .map { v -> v.substitution[explanationVar] } - .filterIsInstance() - .map { e -> e.explanation } - .reduce { acc, expl -> - when { - expl.probability == 1.0 -> acc - acc.probability == 1.0 -> expl - else -> acc or expl + val explanation: ProbExplanation = + solutionGroup.value + .map { v -> v.substitution[explanationVar] } + .filterIsInstance() + .map { e -> e.explanation } + .reduce { acc, expl -> + when { + expl.probability == 1.0 -> acc + acc.probability == 1.0 -> expl + else -> acc or expl + } } - } - val substitution = Substitution.of( - solutionGroup.key, - mgu(first, ProbExplanationTerm(explanation)) - ) + val substitution = + Substitution.of( + solutionGroup.key, + mgu(first, ProbExplanationTerm(explanation)), + ) yield(substitution) } } diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbSolveEvidence.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbSolveEvidence.kt index 18a98e3b2..93912bee3 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbSolveEvidence.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbSolveEvidence.kt @@ -36,9 +36,8 @@ import it.unibo.tuprolog.solve.problog.lib.primitive.ProbSetConfig.getSolverOpti * @author Jason Dellaluce */ internal object ProbSolveEvidence : UnaryPredicate.NonBacktrackable( - "${PREDICATE_PREFIX}_solve_evidence" + "${PREDICATE_PREFIX}_solve_evidence", ) { - override fun Solve.Request.computeOne(first: Term): Solve.Response { val evidenceIndicator = Indicator.of(EVIDENCE_PREDICATE, 2) if (evidenceIndicator !in context.staticKb && evidenceIndicator !in context.dynamicKb) { @@ -49,32 +48,34 @@ internal object ProbSolveEvidence : UnaryPredicate.NonBacktrackable() - .toList() - .map { - val truth = it.substitution[evidenceTruthVar] - val term = it.substitution[evidenceTermVar] + val result = + subSolver().solve(subQuery, subOptions) + .filterIsInstance() + .toList() + .map { + val truth = it.substitution[evidenceTruthVar] + val term = it.substitution[evidenceTermVar] - if (term == null || term.isVar || truth == null || truth !is Truth) { - ProbExplanation.FALSE - } else { - val explanationVar = Var.of(EXPLANATION_VAR_NAME) - val totalExplanation = solve(Struct.of(ProbSolve.functor, explanationVar, term)) - .map { s -> s.substitution[explanationVar] } - .filterIsInstance() - .map { t -> t.explanation } - .reduce { acc, t -> - when { - t.probability == 1.0 -> acc - acc.probability == 1.0 -> t - else -> t or acc - } - } - if (truth.isTrue) totalExplanation else totalExplanation.not() + if (term == null || term.isVar || truth == null || truth !is Truth) { + ProbExplanation.FALSE + } else { + val explanationVar = Var.of(EXPLANATION_VAR_NAME) + val totalExplanation = + solve(Struct.of(ProbSolve.functor, explanationVar, term)) + .map { s -> s.substitution[explanationVar] } + .filterIsInstance() + .map { t -> t.explanation } + .reduce { acc, t -> + when { + t.probability == 1.0 -> acc + acc.probability == 1.0 -> t + else -> t or acc + } + } + if (truth.isTrue) totalExplanation else totalExplanation.not() + } } - } - .filter { it != ProbExplanation.FALSE } + .filter { it != ProbExplanation.FALSE } val resultExplanation = if (result.isEmpty()) ProbExplanation.TRUE else result.reduce { acc, t -> t and acc } return replyWith(mgu(first, ProbExplanationTerm(resultExplanation))) diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbSolveWithEvidence.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbSolveWithEvidence.kt index 3007631a4..d1f069523 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbSolveWithEvidence.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/primitive/ProbSolveWithEvidence.kt @@ -23,31 +23,33 @@ import it.unibo.tuprolog.solve.problog.lib.primitive.ProbSetConfig.isPrologMode * @author Jason Dellaluce */ internal object ProbSolveWithEvidence : TernaryRelation.WithoutSideEffects( - "${PREDICATE_PREFIX}_solve_with_evidence" + "${PREDICATE_PREFIX}_solve_with_evidence", ) { override fun Solve.Request.computeAllSubstitutions( first: Term, second: Term, - third: Term + third: Term, ): Sequence { ensuringArgumentIsInstantiated(2) ensuringArgumentIsCallable(2) val evidenceExplanationVar = Var.of("EvidenceExplanation") - val evidenceExplanationTerm = if (context.isPrologMode()) { - /* No need to compute evidence for Prolog-only queries */ - ProbExplanation.TRUE.toTerm() - } else { - val subQuery = Struct.of(ProbSolveEvidence.functor, evidenceExplanationVar) - val solution = subSolver().solveOnce(subQuery, context.getSolverOptions()) - solution.substitution[evidenceExplanationVar] - } + val evidenceExplanationTerm = + if (context.isPrologMode()) { + // No need to compute evidence for Prolog-only queries + ProbExplanation.TRUE.toTerm() + } else { + val subQuery = Struct.of(ProbSolveEvidence.functor, evidenceExplanationVar) + val solution = subSolver().solveOnce(subQuery, context.getSolverOptions()) + solution.substitution[evidenceExplanationVar] + } val goalExplanationVar = Var.of("GoalExplanation") - val solutions = subSolver().solve( - Struct.of(ProbSolve.functor, goalExplanationVar, third), - context.getSolverOptions() - ) + val solutions = + subSolver().solve( + Struct.of(ProbSolve.functor, goalExplanationVar, third), + context.getSolverOptions(), + ) return sequence { for (solution in solutions) { if (solution.isHalt) throw solution.exception!! @@ -60,15 +62,16 @@ internal object ProbSolveWithEvidence : TernaryRelation.WithoutSideEffects v != goalExplanationVar } - ) + solution.substitution.filter { v, _ -> v != goalExplanationVar }, + ), ) } } diff --git a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/rules/Prob.kt b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/rules/Prob.kt index 6860c85d2..aff255f27 100644 --- a/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/rules/Prob.kt +++ b/solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/rules/Prob.kt @@ -41,7 +41,7 @@ internal object Prob : RuleWrapper(ProblogLib.PREDICATE atomOf("!"), structOf("ensure_executable", goal), structOf(ProbHelper.functor, expl, goal, newGoal), - newGoal + newGoal, ) } } diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveProblogTest.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveProblogTest.kt index 497b8accf..3d22f214e 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveProblogTest.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveProblogTest.kt @@ -4,9 +4,10 @@ import kotlin.jvm.JvmField object SolveProblogTest { @JvmField - val expectations = Expectations( - classicShouldWork = true, - prologShouldWork = true, - problogShouldWork = true - ) + val expectations = + Expectations( + classicShouldWork = true, + prologShouldWork = true, + problogShouldWork = true, + ) } diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestProblogStaticFactory.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestProblogStaticFactory.kt index 89f63a120..6e59012eb 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestProblogStaticFactory.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestProblogStaticFactory.kt @@ -3,9 +3,10 @@ package it.unibo.tuprolog.solve import kotlin.test.Test class TestProblogStaticFactory : TestStaticFactory { - private val prototype = TestStaticFactory.prototype( - SolveProblogTest.expectations - ) + private val prototype = + TestStaticFactory.prototype( + SolveProblogTest.expectations, + ) @Test override fun testStaticSolverFactoryForClassic() { diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/TestProblogSolverConstruction.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/TestProblogSolverConstruction.kt index e00e9629c..927862194 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/TestProblogSolverConstruction.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/TestProblogSolverConstruction.kt @@ -9,11 +9,11 @@ import kotlin.test.Test class TestProblogSolverConstruction : TestSolverConstruction, SolverFactory by ProblogSolverFactory { - - private val prototype = TestSolverConstruction.prototype( - this, - ProblogSolverFactory.defaultBuiltins - ) + private val prototype = + TestSolverConstruction.prototype( + this, + ProblogSolverFactory.defaultBuiltins, + ) @Test override fun testCreatingEmptySolver() { diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestMontyHallExamples.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestMontyHallExamples.kt index 9a6aab214..5bb560b5b 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestMontyHallExamples.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestMontyHallExamples.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.theory.parsing.parseAsTheory import kotlin.test.Test class TestMontyHallExamples { - /*** * https://dtai.cs.kuleuven.be/problog/tutorial/various/01_montyhall.html */ @@ -44,22 +43,22 @@ class TestMontyHallExamples { listOf( ExpectedSolution("prize(1)".parseAsStruct(), 0.33333333), ExpectedSolution("prize(2)".parseAsStruct(), 0.33333333), - ExpectedSolution("prize(3)".parseAsStruct(), 0.33333333) - ) + ExpectedSolution("prize(3)".parseAsStruct(), 0.33333333), + ), ), QueryWithSolutions( "select_door(X)".parseAsStruct(), - listOf(ExpectedSolution("select_door(1)".parseAsStruct(), 1.0)) + listOf(ExpectedSolution("select_door(1)".parseAsStruct(), 1.0)), ), QueryWithSolutions( "win_keep".parseAsStruct(), - listOf(ExpectedSolution("win_keep".parseAsStruct(), 0.33333333)) + listOf(ExpectedSolution("win_keep".parseAsStruct(), 0.33333333)), ), QueryWithSolutions( "win_switch".parseAsStruct(), - listOf(ExpectedSolution("win_switch".parseAsStruct(), 0.66666667)) - ) - ) + listOf(ExpectedSolution("win_switch".parseAsStruct(), 0.66666667)), + ), + ), ) } @@ -85,13 +84,13 @@ class TestMontyHallExamples { listOf( QueryWithSolutions( "switched_gets_goat".parseAsStruct(), - listOf(ExpectedSolution("switched_gets_goat".parseAsStruct(), 0.33333333)) + listOf(ExpectedSolution("switched_gets_goat".parseAsStruct(), 0.33333333)), ), QueryWithSolutions( "switched_gets_car".parseAsStruct(), - listOf(ExpectedSolution("switched_gets_car".parseAsStruct(), 0.66666667)) - ) - ) + listOf(ExpectedSolution("switched_gets_car".parseAsStruct(), 0.66666667)), + ), + ), ) } } diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestProbabilisticGraphExamples.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestProbabilisticGraphExamples.kt index f90e3613b..95b49c8df 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestProbabilisticGraphExamples.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestProbabilisticGraphExamples.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.theory.parsing.parseAsTheory import kotlin.test.Test class TestProbabilisticGraphExamples { - /*** * https://dtai.cs.kuleuven.be/problog/tutorial/basic/04_pgraph.html */ @@ -31,13 +30,13 @@ class TestProbabilisticGraphExamples { listOf( QueryWithSolutions( "path(1,5)".parseAsStruct(), - listOf(ExpectedSolution("path(1,5)".parseAsStruct(), 0.25824)) + listOf(ExpectedSolution("path(1,5)".parseAsStruct(), 0.25824)), ), QueryWithSolutions( "path(1,6)".parseAsStruct(), - listOf(ExpectedSolution("path(1,6)".parseAsStruct(), 0.2167296)) - ) - ) + listOf(ExpectedSolution("path(1,6)".parseAsStruct(), 0.2167296)), + ), + ), ) } } diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestProbabilisticMode.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestProbabilisticMode.kt index 6173885ae..93ee550e1 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestProbabilisticMode.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestProbabilisticMode.kt @@ -18,9 +18,9 @@ import kotlin.test.assertNull import kotlin.test.assertTrue class TestProbabilisticMode { - private fun createSolver(): Solver { - val theory = """ + val theory = + """ 0.6::heads(C) :- coin(C). coin(c1). coin(c2). @@ -85,7 +85,7 @@ class TestProbabilisticMode { assertNotNull(solutions[0].binaryDecisionDiagram) assertEquals( solutions[0].binaryDecisionDiagram!!.countVariableNodes(), - 4 + 4, ) } } diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestProblogBayesianNetworksExamples.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestProblogBayesianNetworksExamples.kt index 7b8d9d0a5..a47085cfa 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestProblogBayesianNetworksExamples.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestProblogBayesianNetworksExamples.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.theory.parsing.parseAsTheory import kotlin.test.Test class TestProblogBayesianNetworksExamples { - /*** * https://dtai.cs.kuleuven.be/problog/tutorial/basic/02_bayes.html#probabilistic-facts * */ @@ -27,13 +26,13 @@ class TestProblogBayesianNetworksExamples { listOf( QueryWithSolutions( "burglary".parseAsStruct(), - listOf(ExpectedSolution("burglary".parseAsStruct(), 0.98965517)) + listOf(ExpectedSolution("burglary".parseAsStruct(), 0.98965517)), ), QueryWithSolutions( "earthquake".parseAsStruct(), - listOf(ExpectedSolution("earthquake".parseAsStruct(), 0.22758621)) - ) - ) + listOf(ExpectedSolution("earthquake".parseAsStruct(), 0.22758621)), + ), + ), ) } @@ -54,13 +53,13 @@ class TestProblogBayesianNetworksExamples { listOf( QueryWithSolutions( "burglary".parseAsStruct(), - listOf(ExpectedSolution("burglary".parseAsStruct(), 0.98193926)) + listOf(ExpectedSolution("burglary".parseAsStruct(), 0.98193926)), ), QueryWithSolutions( "earthquake".parseAsStruct(), - listOf(ExpectedSolution("earthquake".parseAsStruct(), 0.22685136)) - ) - ) + listOf(ExpectedSolution("earthquake".parseAsStruct(), 0.22685136)), + ), + ), ) } @@ -86,13 +85,13 @@ class TestProblogBayesianNetworksExamples { listOf( QueryWithSolutions( "burglary".parseAsStruct(), - listOf(ExpectedSolution("burglary".parseAsStruct(), 0.98965517)) + listOf(ExpectedSolution("burglary".parseAsStruct(), 0.98965517)), ), QueryWithSolutions( "earthquake".parseAsStruct(), - listOf(ExpectedSolution("earthquake".parseAsStruct(), 0.22758621)) - ) - ) + listOf(ExpectedSolution("earthquake".parseAsStruct(), 0.22758621)), + ), + ), ) } @@ -120,17 +119,17 @@ class TestProblogBayesianNetworksExamples { listOf( QueryWithSolutions( "burglary".parseAsStruct(), - listOf(ExpectedSolution("burglary".parseAsStruct(), 0.98965517)) + listOf(ExpectedSolution("burglary".parseAsStruct(), 0.98965517)), ), QueryWithSolutions( "earthquake(X)".parseAsStruct(), listOf( ExpectedSolution("earthquake(heavy)".parseAsStruct(), 0.012476167), ExpectedSolution("earthquake(mild)".parseAsStruct(), 0.20644476), - ExpectedSolution("earthquake(none)".parseAsStruct(), 0.78107907) - ) - ) - ) + ExpectedSolution("earthquake(none)".parseAsStruct(), 0.78107907), + ), + ), + ), ) } } diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestProblogRollingDiceExamples.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestProblogRollingDiceExamples.kt index f66537a78..019f581be 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestProblogRollingDiceExamples.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestProblogRollingDiceExamples.kt @@ -3,10 +3,10 @@ package it.unibo.tuprolog.solve.problog.probabilistic import it.unibo.tuprolog.core.parsing.parseAsStruct import it.unibo.tuprolog.solve.problog.ProblogSolverFactory import it.unibo.tuprolog.theory.parsing.parseAsTheory +import kotlin.test.Ignore import kotlin.test.Test class TestProblogRollingDiceExamples { - /*** * https://dtai.cs.kuleuven.be/problog/tutorial/basic/03_dice.html#annotated-disjunctions-dealing-with-multi-valued-variables * */ @@ -23,21 +23,21 @@ class TestProblogRollingDiceExamples { listOf( QueryWithSolutions( "six1".parseAsStruct(), - listOf(ExpectedSolution("six1".parseAsStruct(), 0.16666667)) + listOf(ExpectedSolution("six1".parseAsStruct(), 0.16666667)), ), QueryWithSolutions( "six2".parseAsStruct(), - listOf(ExpectedSolution("six2".parseAsStruct(), 0.25)) + listOf(ExpectedSolution("six2".parseAsStruct(), 0.25)), ), QueryWithSolutions( "someSix".parseAsStruct(), - listOf(ExpectedSolution("someSix".parseAsStruct(), 0.375)) + listOf(ExpectedSolution("someSix".parseAsStruct(), 0.375)), ), QueryWithSolutions( "twoSix".parseAsStruct(), - listOf(ExpectedSolution("twoSix".parseAsStruct(), 0.041666667)) - ) - ) + listOf(ExpectedSolution("twoSix".parseAsStruct(), 0.041666667)), + ), + ), ) } @@ -58,21 +58,21 @@ class TestProblogRollingDiceExamples { listOf( QueryWithSolutions( "odd(1)".parseAsStruct(), - listOf(ExpectedSolution("odd(1)".parseAsStruct(), 0.5)) + listOf(ExpectedSolution("odd(1)".parseAsStruct(), 0.5)), ), QueryWithSolutions( "even(1)".parseAsStruct(), - listOf(ExpectedSolution("even(1)".parseAsStruct(), 0.5)) + listOf(ExpectedSolution("even(1)".parseAsStruct(), 0.5)), ), QueryWithSolutions( "odd(2)".parseAsStruct(), - listOf(ExpectedSolution("odd(2)".parseAsStruct(), 0.45)) + listOf(ExpectedSolution("odd(2)".parseAsStruct(), 0.45)), ), QueryWithSolutions( "even(2)".parseAsStruct(), - listOf(ExpectedSolution("even(2)".parseAsStruct(), 0.55)) - ) - ) + listOf(ExpectedSolution("even(2)".parseAsStruct(), 0.55)), + ), + ), ) } @@ -95,14 +95,14 @@ class TestProblogRollingDiceExamples { "odd(X)".parseAsStruct(), listOf( ExpectedSolution("odd(1)".parseAsStruct(), 0.5), - ExpectedSolution("odd(2)".parseAsStruct(), 0.45) - ) + ExpectedSolution("odd(2)".parseAsStruct(), 0.45), + ), ), QueryWithSolutions( "even(_)".parseAsStruct(), - emptyList() - ) - ) + emptyList(), + ), + ), ) } @@ -131,9 +131,9 @@ class TestProblogRollingDiceExamples { ExpectedSolution("sum(5)".parseAsStruct(), 0.22222222), ExpectedSolution("sum(7)".parseAsStruct(), 0.33333333), ExpectedSolution("sum(9)".parseAsStruct(), 0.22222222), - ExpectedSolution("sum(11)".parseAsStruct(), 0.11111111) - ) - ) + ExpectedSolution("sum(11)".parseAsStruct(), 0.11111111), + ), + ), ) } @@ -144,7 +144,8 @@ class TestProblogRollingDiceExamples { fun testArithmeticExpressions2() { TestUtils.assertQueryWithSolutions( """ - 1/6::dice(1,D); 1/6::dice(2,D); 1/6::dice(3,D); 1/6::dice(4,D); 1/6::dice(5,D); 1/6::dice(6,D) :- die(D). + 1/6::dice(1,D); 1/6::dice(2,D); 1/6::dice(3,D); 1/6::dice(4,D); 1/6::dice(5,D); 1/6::dice(6,D) :- + die(D). die(1). die(2). die(3). @@ -165,87 +166,92 @@ class TestProblogRollingDiceExamples { ExpectedSolution("sum(12)".parseAsStruct(), 0.15), ExpectedSolution("sum(13)".parseAsStruct(), 0.1), ExpectedSolution("sum(14)".parseAsStruct(), 0.05), - ExpectedSolution("sum(15)".parseAsStruct(), 0.05) - ) - ) + ExpectedSolution("sum(15)".parseAsStruct(), 0.05), + ), + ), ) } /*** * https://dtai.cs.kuleuven.be/problog/tutorial/basic/03_dice.html#built-in-predicate-between-3 * */ -// @Test -// fun testBetweenPredicate() { -// TestUtils.assertQueryWithSolutions( -// """ -// 1/6::dice(1,1); 1/6::dice(2,1); 1/6::dice(3,1); 1/6::dice(4,1); 1/6::dice(5,1); 1/6::dice(6,1). -// 1/6::dice(1,D); 1/6::dice(2,D); 1/6::dice(3,D); 1/6::dice(4,D); 1/6::dice(5,D); 1/6::dice(6,D) :- D > 1, P is D-1, continue(P). -// stop(N) :- dice(6,N). -// continue(N) :- dice(X,N), X < 6. -// """.parseAsTheory(ProblogProbSolverFactory.defaultBuiltins.operators), -// listOf( -// QueryWithSolutions( -// "stop(1)".parseAsStruct(), -// listOf(ExpectedSolution("stop(1)".parseAsStruct(), 0.16666667)) -// ), -// QueryWithSolutions( -// "stop(2)".parseAsStruct(), -// listOf(ExpectedSolution("stop(2)".parseAsStruct(), 0.13888889)) -// ), -// QueryWithSolutions( -// "stop(3)".parseAsStruct(), -// listOf(ExpectedSolution("stop(3)".parseAsStruct(), 0.11574074)) -// ), -// QueryWithSolutions( -// "stop(4)".parseAsStruct(), -// listOf(ExpectedSolution("stop(4)".parseAsStruct(), 0.096450617)) -// ), -// QueryWithSolutions( -// "stop(5)".parseAsStruct(), -// listOf(ExpectedSolution("stop(5)".parseAsStruct(), 0.080375514)) -// ), -// ) -// ) -// } + @Test + @Ignore + fun testBetweenPredicate() { + TestUtils.assertQueryWithSolutions( + """ + 1/6::dice(1,1); 1/6::dice(2,1); 1/6::dice(3,1); 1/6::dice(4,1); 1/6::dice(5,1); 1/6::dice(6,1). + 1/6::dice(1,D); 1/6::dice(2,D); 1/6::dice(3,D); 1/6::dice(4,D); 1/6::dice(5,D); 1/6::dice(6,D) :- + D > 1, + P is D-1, + continue(P). + stop(N) :- dice(6,N). + continue(N) :- dice(X,N), X < 6. + """.parseAsTheory(ProblogSolverFactory.defaultBuiltins.operators), + listOf( + QueryWithSolutions( + "stop(1)".parseAsStruct(), + listOf(ExpectedSolution("stop(1)".parseAsStruct(), 0.16666667)), + ), + QueryWithSolutions( + "stop(2)".parseAsStruct(), + listOf(ExpectedSolution("stop(2)".parseAsStruct(), 0.13888889)), + ), + QueryWithSolutions( + "stop(3)".parseAsStruct(), + listOf(ExpectedSolution("stop(3)".parseAsStruct(), 0.11574074)), + ), + QueryWithSolutions( + "stop(4)".parseAsStruct(), + listOf(ExpectedSolution("stop(4)".parseAsStruct(), 0.096450617)), + ), + QueryWithSolutions( + "stop(5)".parseAsStruct(), + listOf(ExpectedSolution("stop(5)".parseAsStruct(), 0.080375514)), + ), + ), + ) + } /*** * https://dtai.cs.kuleuven.be/problog/tutorial/basic/03_dice.html#built-in-predicate-between-3 * */ -// @Test -// fun testRecursionAndLists() { -// TestUtils.assertQueryWithSolutions( -// """ -// 1/3::dice(1,D); 1/3::dice(2,D); 1/3::dice(3,D) :- die(D). -// die(X) :- between(1,3,X). -// roll(L) :- -// next(1,[1],L). -// next(N,Seen,Rev) :- -// dice(Now,N), -// member(Now,Seen), -// reverse(Seen,[],Rev). -// next(N,Seen,List) :- -// dice(Now,N), -// \+ member(Now,Seen), -// next(Now,[Now|Seen],List). -// member(X,[X|_]). -// member(X,[_|Z]) :- -// member(X,Z). -// reverse([],L,L). -// reverse([H|T],A,L) :- -// reverse(T,[H|A],L). -// """.parseAsTheory(ProblogProbSolverFactory.defaultBuiltins.operators), -// listOf( -// QueryWithSolutions( -// "roll(_)".parseAsStruct(), -// listOf( -// ExpectedSolution("roll([1, 2, 3])".parseAsStruct(), 0.11111111), -// ExpectedSolution("roll([1, 2])".parseAsStruct(), 0.22222222), -// ExpectedSolution("roll([1, 3, 2])".parseAsStruct(), 0.11111111), -// ExpectedSolution("roll([1, 3])".parseAsStruct(), 0.22222222), -// ExpectedSolution("roll([1])".parseAsStruct(), 0.33333333) -// ) -// ), -// ) -// ) -// } + @Test + @Ignore + fun testRecursionAndLists() { + TestUtils.assertQueryWithSolutions( + """ + 1/3::dice(1,D); 1/3::dice(2,D); 1/3::dice(3,D) :- die(D). + die(X) :- between(1,3,X). + roll(L) :- + next(1,[1],L). + next(N,Seen,Rev) :- + dice(Now,N), + member(Now,Seen), + reverse(Seen,[],Rev). + next(N,Seen,List) :- + dice(Now,N), + \+ member(Now,Seen), + next(Now,[Now|Seen],List). + member(X,[X|_]). + member(X,[_|Z]) :- + member(X,Z). + reverse([],L,L). + reverse([H|T],A,L) :- + reverse(T,[H|A],L). + """.parseAsTheory(ProblogSolverFactory.defaultBuiltins.operators), + listOf( + QueryWithSolutions( + "roll(_)".parseAsStruct(), + listOf( + ExpectedSolution("roll([1, 2, 3])".parseAsStruct(), 0.11111111), + ExpectedSolution("roll([1, 2])".parseAsStruct(), 0.22222222), + ExpectedSolution("roll([1, 3, 2])".parseAsStruct(), 0.11111111), + ExpectedSolution("roll([1, 3])".parseAsStruct(), 0.22222222), + ExpectedSolution("roll([1])".parseAsStruct(), 0.33333333), + ), + ), + ), + ) + } } diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestProblogTossingCoinsExamples.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestProblogTossingCoinsExamples.kt index aa650d967..84f27adee 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestProblogTossingCoinsExamples.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestProblogTossingCoinsExamples.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.theory.parsing.parseAsTheory import kotlin.test.Test class TestProblogTossingCoinsExamples { - /*** * https://dtai.cs.kuleuven.be/problog/tutorial/basic/01_coins.html#basic-problog-probabilistic-facts-and-clauses */ @@ -21,17 +20,17 @@ class TestProblogTossingCoinsExamples { listOf( QueryWithSolutions( "heads1".parseAsStruct(), - listOf(ExpectedSolution("heads1".parseAsStruct(), 0.5)) + listOf(ExpectedSolution("heads1".parseAsStruct(), 0.5)), ), QueryWithSolutions( "heads2".parseAsStruct(), - listOf(ExpectedSolution("heads2".parseAsStruct(), 0.6)) + listOf(ExpectedSolution("heads2".parseAsStruct(), 0.6)), ), QueryWithSolutions( "twoHeads".parseAsStruct(), - listOf(ExpectedSolution("twoHeads".parseAsStruct(), 0.3)) - ) - ) + listOf(ExpectedSolution("twoHeads".parseAsStruct(), 0.3)), + ), + ), ) } @@ -49,8 +48,8 @@ class TestProblogTossingCoinsExamples { """.parseAsTheory(ProblogSolverFactory.defaultBuiltins.operators), QueryWithSolutions( "someHeads".parseAsStruct(), - listOf(ExpectedSolution("someHeads".parseAsStruct(), 0.8)) - ) + listOf(ExpectedSolution("someHeads".parseAsStruct(), 0.8)), + ), ) } @@ -71,8 +70,8 @@ class TestProblogTossingCoinsExamples { """.parseAsTheory(ProblogSolverFactory.defaultBuiltins.operators), QueryWithSolutions( "someHeads".parseAsStruct(), - listOf(ExpectedSolution("someHeads".parseAsStruct(), 0.9744)) - ) + listOf(ExpectedSolution("someHeads".parseAsStruct(), 0.9744)), + ), ) } @@ -92,8 +91,8 @@ class TestProblogTossingCoinsExamples { """.parseAsTheory(ProblogSolverFactory.defaultBuiltins.operators), QueryWithSolutions( "someHeads".parseAsStruct(), - listOf(ExpectedSolution("someHeads".parseAsStruct(), 0.9744)) - ) + listOf(ExpectedSolution("someHeads".parseAsStruct(), 0.9744)), + ), ) } } diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestUtils.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestUtils.kt index ab07010cd..04f8732da 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestUtils.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/probabilistic/TestUtils.kt @@ -15,61 +15,63 @@ typealias ExpectedSolution = Pair typealias QueryWithSolutions = Pair> internal object TestUtils { - private const val DEFAULT_DOUBLE_PRECISION = 0.01 fun assertEqualsDouble( first: Double, second: Double, - precision: Double = DEFAULT_DOUBLE_PRECISION + precision: Double = DEFAULT_DOUBLE_PRECISION, ): Boolean { return abs(first / second - 1) < precision } fun assertQueryWithSolutions( theory: Theory, - queryWithSolutions: Iterable + queryWithSolutions: Iterable, ) { val solver = ProblogSolverFactory.mutableSolverWithDefaultBuiltins() solver.loadStaticKb(theory) queryWithSolutions.forEach { val expectedSolutions = it.second.toList() - val solutions = solver - .solve(it.first, SolveOptions.DEFAULT.setProbabilistic(true)) - .filterIsInstance() - .toList() + val solutions = + solver + .solve(it.first, SolveOptions.DEFAULT.setProbabilistic(true)) + .filterIsInstance() + .toList() var currentActual: ExpectedSolution? = null var currentExpected: ExpectedSolution? = null assertTrue( expectedSolutions.size <= solutions.size, - "Actual solutions size should be larger or equal than the expected one" + "Actual solutions size should be larger or equal than the expected one", ) assertFalse( expectedSolutions .any { s -> !solutions.any { sol -> - val solution = ExpectedSolution( - sol.solvedQuery, - sol.probability - ) + val solution = + ExpectedSolution( + sol.solvedQuery, + sol.probability, + ) currentActual = solution currentExpected = s - s.first == solution.first && assertEqualsDouble( - s.second, - solution.second - ) + s.first == solution.first && + assertEqualsDouble( + s.second, + solution.second, + ) } }, - """Failed to assert expected solution: expected=$currentExpected, actual=$currentActual""" + """Failed to assert expected solution: expected=$currentExpected, actual=$currentActual""", ) } } fun assertQueryWithSolutions( theory: Theory, - queryWithSolutions: QueryWithSolutions + queryWithSolutions: QueryWithSolutions, ) { assertQueryWithSolutions(theory, listOf(queryWithSolutions)) } diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogAnd.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogAnd.kt index f955ad4b4..7dc66e0d2 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogAnd.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogAnd.kt @@ -7,7 +7,6 @@ import kotlin.test.Ignore import kotlin.test.Test class TestProblogAnd : TestAnd, SolverFactory by ProblogSolverFactory { - private val prototype = TestAnd.prototype(this) @Test @@ -25,7 +24,7 @@ class TestProblogAnd : TestAnd, SolverFactory by ProblogSolverFactory { prototype.testFailIsCallable() } - /* NOTE: Ignored because it relies on the internal representation of the knowledge base, not significant here */ + // NOTE: Ignored because it relies on the internal representation of the knowledge base, not significant here @Ignore @Test override fun testNoFooIsCallable() { diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogArg.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogArg.kt index 828585a8e..69da379b2 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogArg.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogArg.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.problog.ProblogSolverFactory import kotlin.test.Test class TestProblogArg : TestArg, SolverFactory by ProblogSolverFactory { - private val prototype = TestArg.prototype(this) @Test diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogAssertA.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogAssertA.kt index cee59659b..bb4d035e0 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogAssertA.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogAssertA.kt @@ -9,7 +9,7 @@ import kotlin.test.Test class TestProblogAssertA : TestAssertA, SolverFactory by ProblogSolverFactory { private val prototype = TestAssertA.prototype(this) - /* NOTE: Ignored because it relies on the internal representation of the knowledge base, not significant here */ + // NOTE: Ignored because it relies on the internal representation of the knowledge base, not significant here @Ignore @Test override fun testAssertAClause() { diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogAtom.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogAtom.kt index 785357054..67b867c5c 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogAtom.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogAtom.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.problog.ProblogSolverFactory import kotlin.test.Test class TestProblogAtom : TestAtom, SolverFactory by ProblogSolverFactory { - private val prototype = TestAtom.prototype(this) @Test diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogAtomic.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogAtomic.kt index 19632388e..8fe174414 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogAtomic.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogAtomic.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.problog.ProblogSolverFactory import kotlin.test.Test class TestProblogAtomic : TestAtomic, SolverFactory by ProblogSolverFactory { - private val prototype = TestAtomic.prototype(this) @Test diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogBigList.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogBigList.kt index e424d21cb..63e259f93 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogBigList.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogBigList.kt @@ -6,7 +6,7 @@ import it.unibo.tuprolog.solve.problog.ProblogSolverFactory import kotlin.test.Ignore import kotlin.test.Test -/* NOTE: Ignored because the heavier stack usage of this implementation makes this not meaningful. */ +// NOTE: Ignored because the heavier stack usage of this implementation makes this not meaningful. @Ignore class TestProblogBigList : TestBigList, SolverFactory by ProblogSolverFactory { private val prototype = TestBigList.prototype(this) diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogClassicCut.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogClassicCut.kt index 3e79603a9..cb8c39f2e 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogClassicCut.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogClassicCut.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.problog.ProblogSolverFactory import kotlin.test.Test class TestProblogClassicCut : TestCut, SolverFactory by ProblogSolverFactory { - private val prototype = TestCut.prototype(this) @Test diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogClassicFail.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogClassicFail.kt index 889b7aadb..6ed6b933c 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogClassicFail.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogClassicFail.kt @@ -14,21 +14,21 @@ class TestProblogClassicFail : TestFail, SolverFactory by ProblogSolverFactory { prototype.testFail() } - /* NOTE: Ignored because it relies on the internal representation of the knowledge base, not significant here */ + // NOTE: Ignored because it relies on the internal representation of the knowledge base, not significant here @Ignore @Test override fun testUndefPred() { prototype.testUndefPred() } - /* NOTE: Ignored because of a mismatch between error codes */ + // NOTE: Ignored because of a mismatch between error codes @Ignore @Test override fun testSetFlagFail() { prototype.testSetFlagFail() } - /* NOTE: Ignored because of a mismatch between error codes */ + // NOTE: Ignored because of a mismatch between error codes @Ignore @Test override fun testSetFlagWarning() { diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogClassicFindAll.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogClassicFindAll.kt index 2ae61ccc8..e4241b85a 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogClassicFindAll.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogClassicFindAll.kt @@ -8,7 +8,6 @@ import kotlin.test.Ignore import kotlin.test.Test class TestProblogClassicFindAll : TestFindAll, SolverFactory by ProblogSolverFactory { - private val prototype = TestFindAll.prototype(this, Signature("ensure_executable", 1)) override val errorSignature: Signature @@ -53,7 +52,7 @@ class TestProblogClassicFindAll : TestFindAll, SolverFactory by ProblogSolverFac prototype.testFindXinGoal() } - /* NOTE: See comment above */ + // NOTE: See comment above @Ignore @Test override fun testFindXinNumber() { diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogCustomData.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogCustomData.kt index cd9268c28..6a5419d67 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogCustomData.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogCustomData.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.problog.ProblogSolverFactory import kotlin.test.Test class TestProblogCustomData : TestCustomData, SolverFactory by ProblogSolverFactory { - val prototype = TestCustomData.prototype(this) @Test diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogDirectives.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogDirectives.kt index 2e191e036..b43a888c5 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogDirectives.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogDirectives.kt @@ -9,7 +9,6 @@ import kotlin.test.Test /* NOTE: Many of these tests are ignored because they heavily rely on the representation of static and dynamic Knowledge Base, which is altered in this implementation due to internal mappings. */ class TestProblogDirectives : TestDirectives, SolverFactory by ProblogSolverFactory { - private val prototype = TestDirectives.prototype(this) @Ignore diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogInteger.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogInteger.kt index 7a2135a08..a6975b92d 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogInteger.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogInteger.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.problog.ProblogSolverFactory import kotlin.test.Test class TestProblogInteger : TestInteger, SolverFactory by ProblogSolverFactory { - private val prototype = TestInteger.prototype(this) @Test diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogNonVar.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogNonVar.kt index 80d20d255..63016faae 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogNonVar.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogNonVar.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.problog.ProblogSolverFactory import kotlin.test.Test class TestProblogNonVar : TestNonVar, SolverFactory by ProblogSolverFactory { - private val prototype = TestNonVar.prototype(this) @Test diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogNotUnify.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogNotUnify.kt index 9952643cc..a951787b0 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogNotUnify.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogNotUnify.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.problog.ProblogSolverFactory import kotlin.test.Test class TestProblogNotUnify : TestNotUnify, SolverFactory by ProblogSolverFactory { - private val prototype = TestNotUnify.prototype(this) @Test diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogNumber.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogNumber.kt index db8558f89..8a1e872c6 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogNumber.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogNumber.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.problog.ProblogSolverFactory import kotlin.test.Test class TestProblogNumber : TestNumber, SolverFactory by ProblogSolverFactory { - private val prototype = TestNumber.prototype(this) @Test diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogOr.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogOr.kt index 3e6889559..264423717 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogOr.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogOr.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.problog.ProblogSolverFactory import kotlin.test.Test class TestProblogOr : TestOr, SolverFactory by ProblogSolverFactory { - private val prototype = TestOr.prototype(this) @Test diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogRecursion.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogRecursion.kt index e909f9f32..10e66aca3 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogRecursion.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogRecursion.kt @@ -6,7 +6,7 @@ import it.unibo.tuprolog.solve.problog.ProblogSolverFactory import kotlin.test.Ignore import kotlin.test.Test -/* NOTE: Ignored because the heavier stack usage of this implementation makes this not meaningful. */ +// NOTE: Ignored because the heavier stack usage of this implementation makes this not meaningful. @Ignore class TestProblogRecursion : TestRecursion, SolverFactory by ProblogSolverFactory { private val prototype = TestRecursion.prototype(this) diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogSetOf.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogSetOf.kt index 26caf5dfe..d4bb13a35 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogSetOf.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogSetOf.kt @@ -19,8 +19,8 @@ class TestProblogSetOf : TestSetOf, SolverFactory by ProblogSolverFactory { } @Test - override fun testSetOfNoSorted() { - prototype.testSetOfNoSorted() + override fun testSetOfSorted() { + prototype.testSetOfSorted() } @Test diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogSolutionPresentation.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogSolutionPresentation.kt index 8049561bd..ac957c478 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogSolutionPresentation.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogSolutionPresentation.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.problog.ProblogSolverFactory import kotlin.test.Test class TestProblogSolutionPresentation : TestSolutionPresentation, SolverFactory by ProblogSolverFactory { - val prototype = TestSolutionPresentation.prototype(this) @Test diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogSolver.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogSolver.kt index 6d3447f80..bfa09515b 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogSolver.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogSolver.kt @@ -8,10 +8,10 @@ import kotlin.test.Ignore import kotlin.test.Test class TestProblogSolver : TestSolver, SolverFactory by ProblogSolverFactory { - - private val prototype = Signature("ensure_executable", 1).let { - TestSolver.prototype(this, it, it, it) - } + private val prototype = + Signature("ensure_executable", 1).let { + TestSolver.prototype(this, it, it, it) + } override val callErrorSignature: Signature get() = prototype.callErrorSignature @@ -27,7 +27,7 @@ class TestProblogSolver : TestSolver, SolverFactory by ProblogSolverFactory { prototype.testUnknownFlag2() } - /* NOTE: Ignored because it relies on the internal representation of the knowledge base, not significant here */ + // NOTE: Ignored because it relies on the internal representation of the knowledge base, not significant here @Ignore @Test override fun testUnknownFlag1() { @@ -39,28 +39,28 @@ class TestProblogSolver : TestSolver, SolverFactory by ProblogSolverFactory { prototype.testSideEffectsPersistentAfterBacktracking1() } - /* NOTE: Ignored because it relies on the internal representation of the knowledge base, not significant here. */ + // NOTE: Ignored because it relies on the internal representation of the knowledge base, not significant here. @Ignore @Test override fun testFindAll() { prototype.testFindAll() } - /* NOTE: Ignored because it relies on the internal representation of the knowledge base, not significant here */ + // NOTE: Ignored because it relies on the internal representation of the knowledge base, not significant here @Ignore @Test override fun testAssert() { prototype.testAssert() } - /* NOTE: Ignored because it relies on the internal representation of the knowledge base, not significant here */ + // NOTE: Ignored because it relies on the internal representation of the knowledge base, not significant here @Ignore @Test override fun testAssertZ() { prototype.testAssertZ() } - /* NOTE: Ignored because it relies on the internal representation of the knowledge base, not significant here */ + // NOTE: Ignored because it relies on the internal representation of the knowledge base, not significant here @Ignore @Test override fun testAssertA() { @@ -302,7 +302,7 @@ class TestProblogSolver : TestSolver, SolverFactory by ProblogSolverFactory { prototype.testBasicBacktracking4() } - /* NOTE: Ignored because it relies on the internal representation of the knowledge base, not significant here */ + // NOTE: Ignored because it relies on the internal representation of the knowledge base, not significant here @Ignore @Test override fun testAssertRules() { diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogStackTrace.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogStackTrace.kt index ef49deb05..884d32136 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogStackTrace.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogStackTrace.kt @@ -6,7 +6,7 @@ import it.unibo.tuprolog.solve.problog.ProblogSolverFactory import kotlin.test.Ignore import kotlin.test.Test -/* NOTE: Ignored because the heavier stack usage of this implementation makes this not meaningful. */ +// NOTE: Ignored because the heavier stack usage of this implementation makes this not meaningful. @Ignore class TestProblogStackTrace : TestStackTrace, SolverFactory by ProblogSolverFactory { val prototype = TestStackTrace.prototype(this) diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogTerm.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogTerm.kt index c370f80d2..20bd76f08 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogTerm.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogTerm.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.problog.ProblogSolverFactory import kotlin.test.Test class TestProblogTerm : TestTerm, SolverFactory by ProblogSolverFactory { - private val prototype = TestTerm.prototype(this) @Test diff --git a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogUnify.kt b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogUnify.kt index dc439321f..6d66f81f8 100644 --- a/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogUnify.kt +++ b/solve-problog/src/commonTest/kotlin/it/unibo/tuprolog/solve/problog/prolog/TestProblogUnify.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.problog.ProblogSolverFactory import kotlin.test.Test class TestProblogUnify : TestUnify, SolverFactory by ProblogSolverFactory { - private val prototype = TestUnify.prototype(this) @Test diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/SolverStrategies.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/SolverStrategies.kt index fa39bcebe..6a1434310 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/SolverStrategies.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/SolverStrategies.kt @@ -10,34 +10,44 @@ import it.unibo.tuprolog.solve.ExecutionContext * @author Enrico */ interface SolverStrategies { - /** Selects the predication to be solved first, from provided sequence */ - fun

predicationChoiceStrategy(predicationSequence: Sequence

, context: ExecutionContext): P + fun

predicationChoiceStrategy( + predicationSequence: Sequence

, + context: ExecutionContext, + ): P /** Selects the clause to be expanded in place of unifying predication, from provided sequence */ - fun clauseChoiceStrategy(unifiableClauses: Sequence, context: ExecutionContext): C + fun clauseChoiceStrategy( + unifiableClauses: Sequence, + context: ExecutionContext, + ): C /** Determines "when and what" is considered successfully demonstrated, during solution process */ - fun successCheckStrategy(term: Term, context: ExecutionContext): Boolean + fun successCheckStrategy( + term: Term, + context: ExecutionContext, + ): Boolean companion object { - /** Returns a strategy object containing the key solution strategies used by a Standard Prolog solver */ - val prologStandard = object : SolverStrategies { - - /** The default implementation, following the Prolog Standard, selects the first predication found */ - override fun

predicationChoiceStrategy( - predicationSequence: Sequence

, - context: ExecutionContext - ): P = predicationSequence.first() - - /** The default implementation, following the Prolog Standard, selects the first clause found */ - override fun clauseChoiceStrategy( - unifiableClauses: Sequence, - context: ExecutionContext - ): C = unifiableClauses.first() - - override fun successCheckStrategy(term: Term, context: ExecutionContext): Boolean = term.isTrue - } + val prologStandard = + object : SolverStrategies { + /** The default implementation, following the Prolog Standard, selects the first predication found */ + override fun

predicationChoiceStrategy( + predicationSequence: Sequence

, + context: ExecutionContext, + ): P = predicationSequence.first() + + /** The default implementation, following the Prolog Standard, selects the first clause found */ + override fun clauseChoiceStrategy( + unifiableClauses: Sequence, + context: ExecutionContext, + ): C = unifiableClauses.first() + + override fun successCheckStrategy( + term: Term, + context: ExecutionContext, + ): Boolean = term.isTrue + } } } diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/StreamsSolver.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/StreamsSolver.kt index 0c92f5e33..5c3705a62 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/StreamsSolver.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/StreamsSolver.kt @@ -37,9 +37,8 @@ internal class StreamsSolver constructor( staticKb: Theory = Theory.empty(unificator), dynamicKb: Theory = Theory.empty(unificator), inputChannels: InputStore = InputStore.fromStandard(), - outputChannels: OutputStore = OutputStore.fromStandard() + outputChannels: OutputStore = OutputStore.fromStandard(), ) : Solver { - constructor( unificator: Unificator = Unificator.default, libraries: Runtime = Runtime.empty(), @@ -49,7 +48,7 @@ internal class StreamsSolver constructor( stdIn: InputChannel = InputChannel.stdIn(), stdOut: OutputChannel = OutputChannel.stdOut(), stdErr: OutputChannel = OutputChannel.stdErr(), - warnings: OutputChannel = OutputChannel.warn() + warnings: OutputChannel = OutputChannel.warn(), ) : this( unificator, libraries, @@ -57,42 +56,48 @@ internal class StreamsSolver constructor( staticKb, dynamicKb, InputStore.fromStandard(stdIn), - OutputStore.fromStandard(stdOut, stdErr, warnings) + OutputStore.fromStandard(stdOut, stdErr, warnings), ) - private var executionContext: StreamsExecutionContext = StreamsExecutionContext( - unificator, - libraries, - flags, - staticKb, - dynamicKb, - getAllOperators(libraries, staticKb, dynamicKb).toOperatorSet(), - inputChannels, - outputChannels - ) - - override fun solve(goal: Struct, options: SolveOptions): Sequence { - executionContext = StreamsExecutionContext( - unificator = unificator, - libraries = libraries, - flags = flags, - staticKb = staticKb, - dynamicKb = dynamicKb, - inputChannels = inputChannels, - outputChannels = outputChannels, - maxDuration = options.timeout + private var executionContext: StreamsExecutionContext = + StreamsExecutionContext( + unificator, + libraries, + flags, + staticKb, + dynamicKb, + getAllOperators(libraries, staticKb, dynamicKb).toOperatorSet(), + inputChannels, + outputChannels, ) - var solutionSequence = solveToFinalStates( - Solve.Request( - goal.extractSignature(), - goal.args, - executionContext + override fun solve( + goal: Struct, + options: SolveOptions, + ): Sequence { + executionContext = + StreamsExecutionContext( + unificator = unificator, + libraries = libraries, + flags = flags, + staticKb = staticKb, + dynamicKb = dynamicKb, + inputChannels = inputChannels, + outputChannels = outputChannels, + maxDuration = options.timeout, ) - ).map { - executionContext = it.context.apply(it.solve.sideEffects) - it.solve.solution.cleanUp() - } + + var solutionSequence = + solveToFinalStates( + Solve.Request( + goal.extractSignature(), + goal.args, + executionContext, + ), + ).map { + executionContext = it.context.apply(it.solve.sideEffects) + it.solve.solution.cleanUp() + } if (options.limit > 0) { solutionSequence = solutionSequence.take(options.limit) } @@ -111,7 +116,7 @@ internal class StreamsSolver constructor( stdIn: InputChannel, stdOut: OutputChannel, stdErr: OutputChannel, - warnings: OutputChannel + warnings: OutputChannel, ) = StreamsSolver(unificator, libraries, flags, staticKb, dynamicKb, stdIn, stdOut, stdErr, warnings) override val unificator: Unificator @@ -139,7 +144,6 @@ internal class StreamsSolver constructor( get() = executionContext.operators internal companion object { - /** Internal version of other [solve] method, that accepts raw requests and returns raw statemachine final states */ internal fun solveToFinalStates(goalRequest: Solve.Request): Sequence = StateMachineExecutor.execute(StateInit(goalRequest)) diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/StreamsSolverFactory.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/StreamsSolverFactory.kt index 3d44423a0..b14cddec7 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/StreamsSolverFactory.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/StreamsSolverFactory.kt @@ -29,7 +29,7 @@ object StreamsSolverFactory : SolverFactory { staticKb: Theory, dynamicKb: Theory, inputs: InputStore, - outputs: OutputStore + outputs: OutputStore, ): Solver = StreamsSolver(unificator, libraries, flags, staticKb, dynamicKb, inputs, outputs) override fun solverOf( @@ -41,16 +41,17 @@ object StreamsSolverFactory : SolverFactory { stdIn: InputChannel, stdOut: OutputChannel, stdErr: OutputChannel, - warnings: OutputChannel - ): Solver = StreamsSolver( - unificator, - libraries, - flags, - staticKb, - dynamicKb, - InputStore.fromStandard(stdIn), - OutputStore.fromStandard(stdOut, stdErr, warnings) - ) + warnings: OutputChannel, + ): Solver = + StreamsSolver( + unificator, + libraries, + flags, + staticKb, + dynamicKb, + InputStore.fromStandard(stdIn), + OutputStore.fromStandard(stdOut, stdErr, warnings), + ) override fun mutableSolverOf( unificator: Unificator, @@ -61,7 +62,7 @@ object StreamsSolverFactory : SolverFactory { stdIn: InputChannel, stdOut: OutputChannel, stdErr: OutputChannel, - warnings: OutputChannel + warnings: OutputChannel, ): MutableSolver { TODO("Mutable stream solver is not supported yet") } @@ -73,7 +74,7 @@ object StreamsSolverFactory : SolverFactory { staticKb: Theory, dynamicKb: Theory, inputs: InputStore, - outputs: OutputStore + outputs: OutputStore, ): MutableSolver { TODO("Mutable stream solver is not supported yet") } diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/SideEffectManagerImpl.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/SideEffectManagerImpl.kt index c96c10e83..0a0132284 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/SideEffectManagerImpl.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/SideEffectManagerImpl.kt @@ -15,36 +15,31 @@ import it.unibo.tuprolog.unify.Unificator.Companion.matches * @author Enrico */ internal data class SideEffectManagerImpl( - - // CUT side effect fields - /** The sequence of parent execution contexts before this, limited to a "clause scope" */ private val clauseScopedParents: List = emptyList(), /** Valued when this execution context is child of a choicePoint context, indicating a point where to cut */ private val isChoicePointChild: Boolean = false, /** Filled when cut execution happens, this indicates which are the parent contexts whose unexplored children should be cut */ private val toCutContextsParent: Sequence = emptySequence(), - - // Catch / Throw side effects fields - /** The sequence of parent [Solve.Request]s from this execution context till the resolution root */ internal val logicalParentRequests: List> = emptyList(), /** The sequence of no more selectable parent requests, because already used */ private val throwNonSelectableParentContexts: Sequence = emptySequence(), /** The execution context where a `catch` was found and till which other unexplored sub-trees should be cut */ - private val throwRelatedToCutContextsParent: StreamsExecutionContext? = null - + private val throwRelatedToCutContextsParent: StreamsExecutionContext? = null, ) : SideEffectManager { - - override fun cut(): SideEffectManager = copy( - toCutContextsParent = toCutContextsParent + getFirstChoicePointContext() // only second value could be enough, but more testing needed - ) + override fun cut(): SideEffectManager = + copy( + // only second value could be enough, but more testing needed + toCutContextsParent = toCutContextsParent + getFirstChoicePointContext(), + ) /** Initializes isChoicePointChild to `false` whatever it was, and adds given [currentContext] to clauseScopedParents */ - internal fun stateInitInitialize(currentContext: StreamsExecutionContext): SideEffectManagerImpl = copy( - clauseScopedParents = clauseScopedParents.toMutableList().apply { add(0, currentContext) }, - isChoicePointChild = false - ) + internal fun stateInitInitialize(currentContext: StreamsExecutionContext): SideEffectManagerImpl = + copy( + clauseScopedParents = clauseScopedParents.toMutableList().apply { add(0, currentContext) }, + isChoicePointChild = false, + ) /** * Method that updates internal structures when creating a new solve request @@ -56,27 +51,31 @@ internal data class SideEffectManagerImpl( internal fun creatingNewRequest( currentContext: StreamsExecutionContext, isChoicePointChild: Boolean, - logicalParentRequest: Solve.Request + logicalParentRequest: Solve.Request, ) = copy( clauseScopedParents = clauseScopedParents.toMutableList().apply { add(0, currentContext) }, isChoicePointChild = isChoicePointChild, - logicalParentRequests = when (logicalParentRequest) { - in logicalParentRequests -> logicalParentRequests.dropWhile { it != logicalParentRequest } - else -> logicalParentRequests.toMutableList().apply { add(0, logicalParentRequest) } - } + logicalParentRequests = + when (logicalParentRequest) { + in logicalParentRequests -> logicalParentRequests.dropWhile { it != logicalParentRequest } + else -> logicalParentRequests.toMutableList().apply { add(0, logicalParentRequest) } + }, ) /** Method that updates sideEffects manager to not consider parents older than current first, because entering new "rule-scope" */ - internal fun enterRuleSubScope() = copy( - clauseScopedParents = listOf(clauseScopedParents.first()) - ) + internal fun enterRuleSubScope() = + copy( + clauseScopedParents = listOf(clauseScopedParents.first()), + ) /** Method that updates clauseScopedParent to include upper scope parents; this is needed to maintain Cut functionality through Response chain */ - internal fun extendParentScopeWith(upperScopeSideEffectsManager: SideEffectManagerImpl) = copy( - clauseScopedParents = clauseScopedParents - .toMutableList() - .apply { addAll(upperScopeSideEffectsManager.clauseScopedParents) } - ) + internal fun extendParentScopeWith(upperScopeSideEffectsManager: SideEffectManagerImpl) = + copy( + clauseScopedParents = + clauseScopedParents + .toMutableList() + .apply { addAll(upperScopeSideEffectsManager.clauseScopedParents) }, + ) /** * Method that queries if a Cut should be executed in StateRuleSelection @@ -91,25 +90,28 @@ internal data class SideEffectManagerImpl( /** A method to retrieve the first ancestor catch request that has its second argument that unifies with [toUnifyArgument] */ internal fun retrieveAncestorCatchRequest(toUnifyArgument: Term): Solve.Request? { - val ancestorCatchesRequests = logicalParentRequests.filter { it.signature == Catch.signature } - .filterNot { it.context in throwNonSelectableParentContexts } // exclude already used catch requests + val ancestorCatchesRequests = + logicalParentRequests.filter { it.signature == Catch.signature } + .filterNot { it.context in throwNonSelectableParentContexts } // exclude already used catch requests return ancestorCatchesRequests.find { it.arguments[1].matches(toUnifyArgument) } } /** Method to set the catch request whose not explored children should be cut from search tree */ - internal fun throwCut(ancestorCatchContext: StreamsExecutionContext) = copy( - throwRelatedToCutContextsParent = ancestorCatchContext - ) + internal fun throwCut(ancestorCatchContext: StreamsExecutionContext) = + copy( + throwRelatedToCutContextsParent = ancestorCatchContext, + ) /** Method to query if provided context was that selected by [throwCut] invocation */ internal fun isSelectedThrowCatch(contextImpl: StreamsExecutionContext) = throwRelatedToCutContextsParent == contextImpl /** Method to remove catch request with that [contextImpl], ensuring that's no more selectable */ - internal fun ensureNoMoreSelectableCatch(contextImpl: StreamsExecutionContext) = copy( - throwNonSelectableParentContexts = throwNonSelectableParentContexts + contextImpl - ) + internal fun ensureNoMoreSelectableCatch(contextImpl: StreamsExecutionContext) = + copy( + throwNonSelectableParentContexts = throwNonSelectableParentContexts + contextImpl, + ) /** * Utility method to reset [Cut] changed data structures to initial value before exiting [Call] scope @@ -123,13 +125,13 @@ internal data class SideEffectManagerImpl( /** * Method to query if the throw Cut should execute; the throw cut can exit clause Scope, so it uses different data structures */ - internal fun shouldExecuteThrowCut() = - logicalParentRequests.any { it.context == throwRelatedToCutContextsParent } + internal fun shouldExecuteThrowCut() = logicalParentRequests.any { it.context == throwRelatedToCutContextsParent } /** Internal function to retrieve the first choice point to be Cut, if present */ - private fun getFirstChoicePointContext() = clauseScopedParents - .filter { it.sideEffectManager.isChoicePointChild } - .mapNotNull { it.sideEffectManager.clauseScopedParents.firstOrNull() } + private fun getFirstChoicePointContext() = + clauseScopedParents + .filter { it.sideEffectManager.isChoicePointChild } + .mapNotNull { it.sideEffectManager.clauseScopedParents.firstOrNull() } } /** Bridge method to reach [SideEffectManagerImpl.shouldCutExecuteInRuleSelection] homonym method from a [SideEffectManager] */ @@ -137,8 +139,9 @@ internal fun SideEffectManager?.shouldCutExecuteInRuleSelection(): Boolean = (this as? SideEffectManagerImpl)?.shouldCutExecuteInRuleSelection() ?: false /** Bridge method to reach [SideEffectManagerImpl.extendParentScopeWith] homonym method from a [SideEffectManager] */ -internal fun SideEffectManager?.extendParentScopeWith(upperScopeSideEffectsManager: SideEffectManagerImpl): SideEffectManagerImpl? = - (this as? SideEffectManagerImpl)?.extendParentScopeWith(upperScopeSideEffectsManager) +internal fun SideEffectManager?.extendParentScopeWith( + upperScopeSideEffectsManager: SideEffectManagerImpl, +): SideEffectManagerImpl? = (this as? SideEffectManagerImpl)?.extendParentScopeWith(upperScopeSideEffectsManager) /** Bridge method to reach [SideEffectManagerImpl.resetCutWorkChanges] homonym method from a [SideEffectManager] */ internal fun SideEffectManager?.resetCutWorkChanges(toRecoverSituation: SideEffectManagerImpl): SideEffectManagerImpl? = diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/SolverUtils.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/SolverUtils.kt index 1fb5a35b5..302587998 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/SolverUtils.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/SolverUtils.kt @@ -36,31 +36,33 @@ fun Term.prepareForExecutionAsGoal(): Struct = /** Computes the ordered selection of elements, lazily, according to provided selection strategy */ fun Sequence.orderWithStrategy( context: ExecutionContext, - selectionStrategy: (Sequence, ExecutionContext) -> E + selectionStrategy: (Sequence, ExecutionContext) -> E, ): Sequence = when (any()) { - true -> sequence { - selectionStrategy(this@orderWithStrategy, context).let { selected -> - yield(selected) - yieldAll( - filterIndexed { index, _ -> index != indexOf(selected) } - .orderWithStrategy(context, selectionStrategy) - ) + true -> + sequence { + selectionStrategy(this@orderWithStrategy, context).let { selected -> + yield(selected) + yieldAll( + filterIndexed { index, _ -> index != indexOf(selected) } + .orderWithStrategy(context, selectionStrategy), + ) + } } - } else -> emptySequence() } /** Checks if this sequence of elements holds more than one element, lazily */ -fun moreThanOne(elements: Sequence<*>): Boolean = with(elements.iterator()) { - when { - !hasNext() -> false // no element - else -> { - next() - hasNext() // more elements, if first element has a next element +fun moreThanOne(elements: Sequence<*>): Boolean = + with(elements.iterator()) { + when { + !hasNext() -> false // no element + else -> { + next() + hasNext() // more elements, if first element has a next element + } } } -} /** * A method to create a new [Solve.Request] physically chained to receiver request. @@ -78,22 +80,23 @@ internal fun Solve.Request.newSolveRequest( toPropagateContextData: ExecutionContext = context, baseSideEffectManager: SideEffectManagerImpl = context.sideEffectManager, requestIssuingInstant: TimeInstant = this.startTime, - isChoicePointChild: Boolean = false -): Solve.Request = copy( - newGoal.extractSignature(), - newGoal.args, - context.copy( - libraries = toPropagateContextData.libraries, - flags = toPropagateContextData.flags, - staticKb = toPropagateContextData.staticKb, - dynamicKb = toPropagateContextData.dynamicKb, - inputChannels = toPropagateContextData.inputChannels, - outputChannels = toPropagateContextData.outputChannels, - substitution = (context.substitution + toAddSubstitutions) as Substitution.Unifier, - sideEffectManager = baseSideEffectManager.creatingNewRequest(context, isChoicePointChild, this) - ), - startTime = requestIssuingInstant -) + isChoicePointChild: Boolean = false, +): Solve.Request = + copy( + newGoal.extractSignature(), + newGoal.args, + context.copy( + libraries = toPropagateContextData.libraries, + flags = toPropagateContextData.flags, + staticKb = toPropagateContextData.staticKb, + dynamicKb = toPropagateContextData.dynamicKb, + inputChannels = toPropagateContextData.inputChannels, + outputChannels = toPropagateContextData.outputChannels, + substitution = (context.substitution + toAddSubstitutions) as Substitution.Unifier, + sideEffectManager = baseSideEffectManager.creatingNewRequest(context, isChoicePointChild, this), + ), + startTime = requestIssuingInstant, + ) /** Responds to this solve request forwarding the provided [otherResponse] data */ fun Solve.Request.replyWith(otherResponse: Solve.Response): Solve.Response = @@ -101,7 +104,7 @@ fun Solve.Request.replyWith(otherResponse: Solve.Response): So replyWith( solution, sideEffectManager ?: this@replyWith.context.getSideEffectManager(), - *sideEffects.toTypedArray() + *sideEffects.toTypedArray(), ) } diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/StreamsExecutionContext.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/StreamsExecutionContext.kt index 66405bbea..28ba2f7e7 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/StreamsExecutionContext.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/StreamsExecutionContext.kt @@ -41,10 +41,9 @@ internal data class StreamsExecutionContext( /** The key strategies that a solver should use during resolution process */ val solverStrategies: SolverStrategies = SolverStrategies.prologStandard, /** The side effects manager to be used during resolution process */ - val sideEffectManager: SideEffectManagerImpl = SideEffectManagerImpl() + val sideEffectManager: SideEffectManagerImpl = SideEffectManagerImpl(), ) : ExecutionContext { - - constructor(context: ExecutionContext, newCurrentSubstitution: Substitution.Unifier) : this( // to be tested + constructor(context: ExecutionContext, newCurrentSubstitution: Substitution.Unifier) : this( context.unificator, context.libraries, context.flags, @@ -56,7 +55,7 @@ internal data class StreamsExecutionContext( context.customData, newCurrentSubstitution, solverStrategies = (context as? StreamsExecutionContext)?.solverStrategies ?: SolverStrategies.prologStandard, - sideEffectManager = (context as? StreamsExecutionContext)?.sideEffectManager ?: SideEffectManagerImpl() + sideEffectManager = (context as? StreamsExecutionContext)?.sideEffectManager ?: SideEffectManagerImpl(), ) override val procedure: Struct? @@ -73,7 +72,7 @@ internal data class StreamsExecutionContext( staticKb: Theory, dynamicKb: Theory, inputChannels: InputStore, - outputChannels: OutputStore + outputChannels: OutputStore, ) = StreamsSolver(unificator, libraries, flags, staticKb, dynamicKb, inputChannels, outputChannels) override fun createMutableSolver( @@ -83,7 +82,7 @@ internal data class StreamsExecutionContext( staticKb: Theory, dynamicKb: Theory, inputChannels: InputStore, - outputChannels: OutputStore + outputChannels: OutputStore, ) = TODO("Not yet implemented") override fun apply(sideEffect: SideEffect): StreamsExecutionContext { @@ -107,7 +106,7 @@ internal data class StreamsExecutionContext( operators: OperatorSet, inputChannels: InputStore, outputChannels: OutputStore, - customData: CustomDataStore + customData: CustomDataStore, ): StreamsExecutionContext { return copy( unificator = unificator, @@ -118,7 +117,7 @@ internal data class StreamsExecutionContext( operators = operators, inputChannels = inputChannels, outputChannels = outputChannels, - customData = customData + customData = customData, ) } } diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/AbstractState.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/AbstractState.kt index 9c9d24c39..54a4e88af 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/AbstractState.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/AbstractState.kt @@ -8,6 +8,5 @@ import it.unibo.tuprolog.solve.primitive.Solve * @author Enrico */ internal abstract class AbstractState(override val solve: Solve) : State { - override val hasBehaved = false } diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/FinalState.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/FinalState.kt index cdb44ce65..4948b2fbc 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/FinalState.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/FinalState.kt @@ -8,7 +8,6 @@ import it.unibo.tuprolog.solve.primitive.Solve * @author Enrico */ internal interface FinalState : State { - /** The [Solve.Response] characterizing this Final State */ override val solve: Solve.Response } diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/IntermediateState.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/IntermediateState.kt index 3c16a06c4..e1d7f7dde 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/IntermediateState.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/IntermediateState.kt @@ -11,7 +11,6 @@ import it.unibo.tuprolog.solve.streams.solver.StreamsExecutionContext * @author Enrico */ internal interface IntermediateState : State { - /** The [Solve.Request] that drives the State behaviour towards [Response]s */ override val solve: Solve.Request diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/State.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/State.kt index 6b66d7f9f..5569bf819 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/State.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/State.kt @@ -9,7 +9,6 @@ import it.unibo.tuprolog.solve.streams.solver.StreamsExecutionContext * @author Enrico */ internal interface State { - /** The [Solve.Request] or [Solve.Response] that this state carries with it */ val solve: Solve diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/StateMachineExecutor.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/StateMachineExecutor.kt index da3501de9..a7ab23f28 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/StateMachineExecutor.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/StateMachineExecutor.kt @@ -6,19 +6,19 @@ package it.unibo.tuprolog.solve.streams.solver.fsm * @author Enrico */ internal object StateMachineExecutor { - /** * Executes the state-machine starting from [state], returning lazily next states * * It takes also care of not re-executing already executed ones according to [State.hasBehaved], * and unwraps those wrapped as [AlreadyExecutedState] */ - fun execute(state: State): Sequence = when { - state.hasBehaved -> emptySequence() + fun execute(state: State): Sequence = + when { + state.hasBehaved -> emptySequence() - // drop(1) is to exclude provided [state] from next states' sequence - else -> internalExecute(state).drop(1).map { it.unwrapIfNeeded() } - } + // drop(1) is to exclude provided [state] from next states' sequence + else -> internalExecute(state).drop(1).map { it.unwrapIfNeeded() } + } /** * As [execute] and wraps lazily executed states into [AlreadyExecutedState], to signal that they should not execute again @@ -34,19 +34,22 @@ internal object StateMachineExecutor { * * It takes also care of not re-executing already executed ones according to [State.hasBehaved] */ - private fun internalExecute(state: State): Sequence = when { - state.hasBehaved -> sequenceOf(state) + private fun internalExecute(state: State): Sequence = + when { + state.hasBehaved -> sequenceOf(state) - else -> sequence { - yield(state) + else -> + sequence { + yield(state) - state.behave().forEach { yieldAll(internalExecute(it)) } + state.behave().forEach { yieldAll(internalExecute(it)) } + } } - } /** Utility function refactoring logic to unwrap already executed state */ - internal fun State.unwrapIfNeeded(): State = when (this) { - is AlreadyExecutedState -> this.wrappedState - else -> this - } + internal fun State.unwrapIfNeeded(): State = + when (this) { + is AlreadyExecutedState -> this.wrappedState + else -> this + } } diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/TimedState.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/TimedState.kt index 26b1ec17c..3ed224d28 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/TimedState.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/TimedState.kt @@ -8,7 +8,6 @@ import it.unibo.tuprolog.solve.TimeInstant * @author Enrico */ internal interface TimedState : State { - /** Returns current time instant in some notion of "time" */ fun getCurrentTime(): TimeInstant } diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/AbstractTimedState.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/AbstractTimedState.kt index c833c7cc3..116aabcb5 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/AbstractTimedState.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/AbstractTimedState.kt @@ -19,49 +19,52 @@ import it.unibo.tuprolog.solve.streams.solver.fsm.TimedState */ internal abstract class AbstractTimedState( /** The [Solve.Request] that guides the State behaviour towards [Response]s */ - override val solve: Solve.Request + override val solve: Solve.Request, ) : AbstractState(solve), IntermediateState, TimedState { - /** Internal cached currentTime at first behave() call, enabling identical re-execution of that state */ private val stateCurrentTime by lazy { currentTimeInstant() } - override fun behave(): Sequence = when { - solve.maxDuration == TimeDuration.MAX_VALUE -> behaveTimed() // optimized without check, when maxDuration is infinite + override fun behave(): Sequence = + when { + // optimized without check, when maxDuration is infinite + solve.maxDuration == TimeDuration.MAX_VALUE -> behaveTimed() - timeIsOver(stateCurrentTime - solve.startTime, solve.maxDuration) -> - sequenceOf(statEndHaltTimeout()) - else -> behaveTimed() - } + timeIsOver(stateCurrentTime - solve.startTime, solve.maxDuration) -> + sequenceOf(statEndHaltTimeout()) + else -> behaveTimed() + } /** Called only if executionTimeout has not been reached yet, and computation should go on */ protected abstract fun behaveTimed(): Sequence /** A function to check if currently the timeout has expired and return the halt state if yes, * the provided [toYieldState] otherwise*/ - protected fun IntermediateState.ifTimeIsNotOver(toYieldState: State): State = when { - timeIsOver(currentTimeInstant() - solve.startTime, solve.maxDuration) -> - statEndHaltTimeout() - else -> toYieldState - } + protected fun IntermediateState.ifTimeIsNotOver(toYieldState: State): State = + when { + timeIsOver(currentTimeInstant() - solve.startTime, solve.maxDuration) -> + statEndHaltTimeout() + else -> toYieldState + } override fun getCurrentTime(): TimeInstant = stateCurrentTime /** A function to check if time for execution has ended */ - private fun timeIsOver(currentDuration: TimeDuration, maxDuration: TimeDuration) = - currentDuration >= maxDuration + private fun timeIsOver( + currentDuration: TimeDuration, + maxDuration: TimeDuration, + ) = currentDuration >= maxDuration override fun toString(): String = "${this::class} with $solve" companion object { - /** An utility function to create the end Halt state to be returned upon timeout expiry */ private fun IntermediateState.statEndHaltTimeout(): State = stateEndHalt( TimeOutException( "Given time for `${solve.query}` computation (${solve.maxDuration}) wasn't enough for completion", context = solve.context, - exceededDuration = solve.maxDuration - ) + exceededDuration = solve.maxDuration, + ), ) } } diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateEnd.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateEnd.kt index 574023ca8..ca0d23e5a 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateEnd.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateEnd.kt @@ -24,45 +24,50 @@ import it.unibo.tuprolog.solve.streams.solver.getSideEffectManager */ internal sealed class StateEnd( private val sourceContext: ExecutionContext, - override val solve: Solve.Response + override val solve: Solve.Response, ) : AbstractState(solve), FinalState { - override fun behave(): Sequence = emptySequence() override val context: StreamsExecutionContext by lazy { StreamsExecutionContext( sourceContext, - newCurrentSubstitution = solve.solution.substitution as? Substitution.Unifier ?: Substitution.empty() + newCurrentSubstitution = solve.solution.substitution as? Substitution.Unifier ?: Substitution.empty(), ) } /** The *True* state is reached when a successful computational path has ended */ internal data class True( private val sourceContext: ExecutionContext, - override val solve: Solve.Response + override val solve: Solve.Response, ) : StateEnd(sourceContext, solve), FinalState { init { - require(solve.solution is Solution.Yes) { "True end state can be created only with Solution.Yes. Current: `${solve.solution}`" } + require(solve.solution is Solution.Yes) { + "True end state can be created only with Solution.Yes. Current: `${solve.solution}`" + } } } /** The *False* state is reached when a failed computational path has ended */ internal data class False( private val sourceContext: ExecutionContext, - override val solve: Solve.Response + override val solve: Solve.Response, ) : StateEnd(sourceContext, solve), FinalState { init { - require(solve.solution is Solution.No) { "False end state can be created only with Solution.No. Current: `${solve.solution}`" } + require(solve.solution is Solution.No) { + "False end state can be created only with Solution.No. Current: `${solve.solution}`" + } } } /** The *Halt* state is reached when an [HaltException] is caught, terminating the computation */ internal data class Halt( private val sourceContext: ExecutionContext, - override val solve: Solve.Response + override val solve: Solve.Response, ) : StateEnd(sourceContext, solve), FinalState { init { - require(solve.solution is Solution.Halt) { "Halt end state can be created only with Solution.Halt. Current: `${solve.solution}`" } + require( + solve.solution is Solution.Halt, + ) { "Halt end state can be created only with Solution.Halt. Current: `${solve.solution}`" } } /** Shorthand property to access `solve.solution.exception` */ @@ -74,33 +79,33 @@ internal sealed class StateEnd( internal fun IntermediateState.stateEndTrue( substitution: Substitution.Unifier = Substitution.empty(), sideEffectManager: SideEffectManager? = null, - vararg sideEffects: SideEffect + vararg sideEffects: SideEffect, ) = StateEnd.True( context, solve.replySuccess( substitution, sideEffectManager ?: solve.context.getSideEffectManager(), - *sideEffects - ) + *sideEffects, + ), ) /** Transition from this intermediate state to [StateEnd.False], creating a [Solve.Response] with given data */ internal fun IntermediateState.stateEndFalse( sideEffectManager: SideEffectManager? = null, - vararg sideEffects: SideEffect + vararg sideEffects: SideEffect, ) = StateEnd.False( context, solve.replyFail( sideEffectManager ?: solve.context.getSideEffectManager(), - *sideEffects - ) + *sideEffects, + ), ) /** Transition from this intermediate state to [StateEnd.Halt], creating a [Solve.Response] with given data */ internal fun IntermediateState.stateEndHalt( exception: ResolutionException, sideEffectManager: SideEffectManager? = null, - vararg sideEffects: SideEffect + vararg sideEffects: SideEffect, ) = StateEnd.Halt( context, solve.replyException( @@ -108,28 +113,30 @@ internal fun IntermediateState.stateEndHalt( sideEffectManager ?: exception.context.getSideEffectManager() ?: solve.context.getSideEffectManager(), - *sideEffects - ) + *sideEffects, + ), ) /** Transition from this intermediate state to the correct [StateEnd] depending on provided [solution] */ internal fun IntermediateState.stateEnd( solution: Solution, sideEffectManager: SideEffectManager? = null, - vararg sideEffects: SideEffect -): StateEnd = solution.whenIs( - yes = { sol -> - stateEndTrue( - sol.substitution.takeUnless { it.isEmpty() } ?: solve.context.substitution, - sideEffectManager, - *sideEffects - ) - }, - no = { stateEndFalse(sideEffectManager, *sideEffects) }, - halt = { stateEndHalt(it.exception, sideEffectManager, *sideEffects) } -) + vararg sideEffects: SideEffect, +): StateEnd = + solution.whenIs( + yes = { sol -> + stateEndTrue( + sol.substitution.takeUnless { it.isEmpty() } ?: solve.context.substitution, + sideEffectManager, + *sideEffects, + ) + }, + no = { stateEndFalse(sideEffectManager, *sideEffects) }, + halt = { stateEndHalt(it.exception, sideEffectManager, *sideEffects) }, + ) /** Transition from this intermediate state to a [StateEnd] containing provided [response] data */ -internal fun IntermediateState.stateEnd(response: Solve.Response) = with(response) { - stateEnd(solution, sideEffectManager, *sideEffects.toTypedArray()) -} +internal fun IntermediateState.stateEnd(response: Solve.Response) = + with(response) { + stateEnd(solution, sideEffectManager, *sideEffects.toTypedArray()) + } diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateGoalEvaluation.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateGoalEvaluation.kt index 3f33198f1..78d344892 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateGoalEvaluation.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateGoalEvaluation.kt @@ -21,44 +21,44 @@ import it.unibo.tuprolog.solve.streams.stdlib.primitive.Throw * @author Enrico */ internal class StateGoalEvaluation( - override val solve: Solve.Request + override val solve: Solve.Request, ) : AbstractTimedState(solve) { + override fun behaveTimed(): Sequence = + sequence { + val primitive = with(solve) { context.libraries.primitives[signature] } - override fun behaveTimed(): Sequence = sequence { - val primitive = with(solve) { context.libraries.primitives[signature] } + primitive?.also { + // primitive with request signature present + var responses: Sequence? = null + try { + responses = primitive.solve(solve) // execute primitive + } catch (exception: HaltException) { + yield(stateEndHalt(exception)) + } catch (logicError: LogicError) { + // if primitive throws LogicError try to solve corresponding throw/1 request - primitive?.also { - // primitive with request signature present - var responses: Sequence? = null - try { - responses = primitive.solve(solve) // execute primitive - } catch (exception: HaltException) { - yield(stateEndHalt(exception)) - } catch (logicError: LogicError) { - // if primitive throws LogicError try to solve corresponding throw/1 request + responses = StreamsSolver.solveToResponses(solve.newThrowSolveRequest(logicError)) + } - responses = StreamsSolver.solveToResponses(solve.newThrowSolveRequest(logicError)) - } + var allSideEffectsSoFar = emptyList() + responses?.forEach { + allSideEffectsSoFar = allSideEffectsSoFar.addWithNoDuplicates(it.sideEffects) - var allSideEffectsSoFar = emptyList() - responses?.forEach { - allSideEffectsSoFar = allSideEffectsSoFar.addWithNoDuplicates(it.sideEffects) + yield(ifTimeIsNotOver(stateEnd(it.copy(sideEffects = allSideEffectsSoFar)))) - yield(ifTimeIsNotOver(stateEnd(it.copy(sideEffects = allSideEffectsSoFar)))) - - if (it.solution is Solution.Halt) return@sequence // if halt reached, overall computation should stop - } - } ?: yield(StateRuleSelection(solve)) - } + // if halt reached, overall computation should stop + if (it.solution is Solution.Halt) return@sequence + } + } ?: yield(StateRuleSelection(solve)) + } private companion object { - /** Utility function to create "throw/1" solve requests */ private fun Solve.Request.newThrowSolveRequest(error: LogicError) = newSolveRequest( Struct.of(Throw.functor, error.errorStruct), baseSideEffectManager = error.context.getSideEffectManager() ?: context.sideEffectManager, - requestIssuingInstant = currentTimeInstant() + requestIssuingInstant = currentTimeInstant(), ) } } diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateInit.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateInit.kt index 3b8c5a759..96cbe0121 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateInit.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateInit.kt @@ -13,42 +13,47 @@ import it.unibo.tuprolog.solve.streams.solver.prepareForExecutionAsGoal * @author Enrico */ internal class StateInit( - override val solve: Solve.Request + override val solve: Solve.Request, ) : AbstractTimedState(solve) { + override fun behaveTimed(): Sequence = + sequence { + val initializedSideEffectsManager = with(solve.context) { sideEffectManager.stateInitInitialize(this) } + val currentGoal = solve.query - override fun behaveTimed(): Sequence = sequence { - val initializedSideEffectsManager = with(solve.context) { sideEffectManager.stateInitInitialize(this) } - val currentGoal = solve.query - - when { - with(solve.context) { solverStrategies.successCheckStrategy(currentGoal, this) } -> - // current goal is already demonstrated - yield( - ifTimeIsNotOver( - stateEndTrue( - solve.context.substitution, - sideEffectManager = initializedSideEffectsManager - ) - ) - ) - - else -> when { - currentGoal.isWellFormed() -> currentGoal.prepareForExecutionAsGoal().also { preparedGoal -> - // a primitive call or well-formed goal + when { + with(solve.context) { solverStrategies.successCheckStrategy(currentGoal, this) } -> + // current goal is already demonstrated yield( - StateGoalEvaluation( - solve.copy( - signature = preparedGoal.extractSignature(), - arguments = preparedGoal.args, - context = with(solve.context) { copy(sideEffectManager = initializedSideEffectsManager) } - ) - ) + ifTimeIsNotOver( + stateEndTrue( + solve.context.substitution, + sideEffectManager = initializedSideEffectsManager, + ), + ), ) - } - // goal non well-formed - else -> yield(stateEndFalse(sideEffectManager = initializedSideEffectsManager)) + else -> + when { + currentGoal.isWellFormed() -> + currentGoal.prepareForExecutionAsGoal().also { preparedGoal -> + // a primitive call or well-formed goal + yield( + StateGoalEvaluation( + solve.copy( + signature = preparedGoal.extractSignature(), + arguments = preparedGoal.args, + context = + with( + solve.context, + ) { copy(sideEffectManager = initializedSideEffectsManager) }, + ), + ), + ) + } + + // goal non well-formed + else -> yield(stateEndFalse(sideEffectManager = initializedSideEffectsManager)) + } } } - } } diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateRuleSelection.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateRuleSelection.kt index 9d6c758a5..1bd0b23d5 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateRuleSelection.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateRuleSelection.kt @@ -27,79 +27,86 @@ import it.unibo.tuprolog.solve.streams.solver.shouldCutExecuteInRuleSelection * @author Enrico */ internal class StateRuleSelection( - override val solve: Solve.Request + override val solve: Solve.Request, ) : AbstractTimedState(solve) { - /** The execute function to be used when a [State] needs, internally, to execute sub-[State]s behaviour */ private val subStateExecute: (State) -> Sequence = StateMachineExecutor::executeWrapping - override fun behaveTimed(): Sequence = sequence { - val currentGoal = solve.query - val matchingRules = solve.context.retrieveRulesMatching(currentGoal) - val isChoicePoint = moreThanOne(matchingRules) - - when { - matchingRules.none() -> yield(stateEndFalse()) - - else -> - with(solve.context) { - matchingRules.orderWithStrategy(this, solverStrategies::clauseChoiceStrategy) - }.map { it.prepareForExecution().freshCopy() as Rule } - .forEachWithLookahead { refreshedRule, hasAlternatives -> - val unifyingSubstitution = context.unificator.mgu(currentGoal, refreshedRule.head) - - val wellFormedRuleBody = refreshedRule.body.apply(unifyingSubstitution) as Struct - - val subSolveRequest = - solve.newSolveRequest( - wellFormedRuleBody, - unifyingSubstitution, - isChoicePointChild = isChoicePoint, - requestIssuingInstant = currentTimeInstant() - ) - - val subInitialState = StateInit(subSolveRequest.initializeForSubRuleScope()) - .also { yield(it.asAlreadyExecuted()) } - - var cutNextSiblings = false - - // execute internally the sub-request in a sub-state-machine, to see what it will respond - subStateExecute(subInitialState).forEach { - val subState = it.wrappedState - - // find in sub-goal state sequence, the final state responding to current solveRequest - if (subState is FinalState && subState.solve.solution.query == subSolveRequest.query) { - if (subState.solve.sideEffectManager.shouldCutExecuteInRuleSelection()) { - cutNextSiblings = true - } - - // yield only non-false states or false states when there are no open alternatives (because no more or cut) - if (subState !is StateEnd.False || !hasAlternatives || cutNextSiblings) { - val extendedScopeSideEffectManager = subState.solve.sideEffectManager - .extendParentScopeWith(solve.context.sideEffectManager) - - yield( - stateEnd( - subState.solve.copy( - solution = subState.solve.solution.removeSubstitutionFor(refreshedRule.variables), - sideEffectManager = extendedScopeSideEffectManager - ) + override fun behaveTimed(): Sequence = + sequence { + val currentGoal = solve.query + val matchingRules = solve.context.retrieveRulesMatching(currentGoal) + val isChoicePoint = moreThanOne(matchingRules) + + when { + matchingRules.none() -> yield(stateEndFalse()) + + else -> + with(solve.context) { + matchingRules.orderWithStrategy(this, solverStrategies::clauseChoiceStrategy) + }.map { it.prepareForExecution().freshCopy() as Rule } + .forEachWithLookahead { refreshedRule, hasAlternatives -> + val unifyingSubstitution = context.unificator.mgu(currentGoal, refreshedRule.head) + + val wellFormedRuleBody = refreshedRule.body.apply(unifyingSubstitution) as Struct + + val subSolveRequest = + solve.newSolveRequest( + wellFormedRuleBody, + unifyingSubstitution, + isChoicePointChild = isChoicePoint, + requestIssuingInstant = currentTimeInstant(), + ) + + val subInitialState = + StateInit(subSolveRequest.initializeForSubRuleScope()) + .also { yield(it.asAlreadyExecuted()) } + + var cutNextSiblings = false + + // execute internally the sub-request in a sub-state-machine, to see what it will respond + subStateExecute(subInitialState).forEach { + val subState = it.wrappedState + + // find in sub-goal state sequence, the final state responding to current solveRequest + if (subState is FinalState && subState.solve.solution.query == subSolveRequest.query) { + if (subState.solve.sideEffectManager.shouldCutExecuteInRuleSelection()) { + cutNextSiblings = true + } + + // yield only non-false states or false states when there are no open alternatives (because no more or cut) + if (subState !is StateEnd.False || !hasAlternatives || cutNextSiblings) { + val extendedScopeSideEffectManager = + subState.solve.sideEffectManager + .extendParentScopeWith(solve.context.sideEffectManager) + + yield( + stateEnd( + subState.solve.copy( + solution = + subState.solve.solution.removeSubstitutionFor( + refreshedRule.variables, + ), + sideEffectManager = extendedScopeSideEffectManager, + ), + ), ) - ) - } + } - if (subState is StateEnd.Halt) return@sequence // if halt reached, overall computation should stop - } else { - yield(it) // return wrapped subState as is, only if not interested in it + // if halt reached, overall computation should stop + if (subState is StateEnd.Halt) return@sequence + } else { + // return wrapped subState as is, only if not interested in it + yield(it) + } } + // cut here other matching rules trial + if (cutNextSiblings) return@sequence } - if (cutNextSiblings) return@sequence // cut here other matching rules trial - } + } } - } private companion object { - /** * Retrieves from receiver [ExecutionContext] those rules whose head matches [currentGoal] * @@ -120,9 +127,10 @@ internal class StateRuleSelection( * Utility function to eliminate from solution substitution non meaningful variables * for the "upper scope" query, (i.e. variables introduced only for solving the "current" query) */ - private fun Solution.removeSubstitutionFor(unusedVariables: Sequence) = when (this) { - is Solution.Yes -> copy(substitution = substitution - unusedVariables.asIterable()) - else -> this - } + private fun Solution.removeSubstitutionFor(unusedVariables: Sequence) = + when (this) { + is Solution.Yes -> copy(substitution = substitution - unusedVariables.asIterable()) + else -> this + } } } diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/DefaultBuiltins.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/DefaultBuiltins.kt index 21b8a6bd9..0043ba429 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/DefaultBuiltins.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/DefaultBuiltins.kt @@ -11,14 +11,14 @@ import it.unibo.tuprolog.solve.streams.stdlib.primitive.Not import it.unibo.tuprolog.solve.streams.stdlib.primitive.Throw object DefaultBuiltins : ExtensionLibrary(CommonBuiltins) { - override val additionalPrimitives: Iterable> - get() = listOf( - Call, - Catch, - Conjunction, - Cut, - Throw, - Not - ) + get() = + listOf( + Call, + Catch, + Conjunction, + Cut, + Throw, + Not, + ) } diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Call.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Call.kt index 3b3d6d747..1f7fb0dd3 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Call.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Call.kt @@ -17,17 +17,19 @@ import it.unibo.tuprolog.solve.streams.solver.resetCutWorkChanges * @author Enrico */ internal object Call : PrimitiveWrapper("call", 1) { - override fun uncheckedImplementation(request: Solve.Request): Sequence = request.ensuringAllArgumentsAreInstantiated().arguments.single().let { toBeCalledGoal -> when { toBeCalledGoal.isWellFormed() -> - StreamsSolver.solveToResponses(request.newSolveRequest(toBeCalledGoal.prepareForExecutionAsGoal())).map { + StreamsSolver.solveToResponses( + request.newSolveRequest(toBeCalledGoal.prepareForExecutionAsGoal()), + ).map { request.replyWith( it.copy( - sideEffectManager = it.sideEffectManager - .resetCutWorkChanges(request.context.sideEffectManager) - ) + sideEffectManager = + it.sideEffectManager + .resetCutWorkChanges(request.context.sideEffectManager), + ), ) } @@ -35,7 +37,7 @@ internal object Call : PrimitiveWrapper("call", 1) { message = "call/1 argument is neither a Variable nor a well-formed goal", context = request.context, expectedType = TypeError.Expected.CALLABLE, - culprit = toBeCalledGoal + culprit = toBeCalledGoal, ) } } diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Catch.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Catch.kt index d8658ccc2..62a022089 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Catch.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Catch.kt @@ -18,7 +18,6 @@ import it.unibo.tuprolog.solve.streams.solver.replyWith * @author Enrico */ internal object Catch : PrimitiveWrapper("catch", 3) { - override fun uncheckedImplementation(request: Solve.Request): Sequence = sequence { val goalArgument = request.arguments.first() @@ -30,11 +29,12 @@ internal object Catch : PrimitiveWrapper("catch", 3) { val recoverGoalArgument = request.arguments.last().apply(goalResponse.solution.substitution) // attaching recover goal's solve request to catch/3 parent, to not re-execute this catch/3 if error thrown - val recoverGoalSolveRequest = request.newSolveRequest( - call(recoverGoalArgument), - goalResponse.solution.substitution - request.context.substitution, - requestIssuingInstant = currentTimeInstant() - ).ensureNoMoreSelectableCatch(request.context) + val recoverGoalSolveRequest = + request.newSolveRequest( + call(recoverGoalArgument), + goalResponse.solution.substitution - request.context.substitution, + requestIssuingInstant = currentTimeInstant(), + ).ensureNoMoreSelectableCatch(request.context) yieldAll(StreamsSolver.solveToResponses(recoverGoalSolveRequest).map { request.replyWith(it) }) } @@ -47,10 +47,12 @@ internal object Catch : PrimitiveWrapper("catch", 3) { private fun call(goal: Term) = Struct.of(Call.functor, goal) /** Calls [SideEffectManagerImpl.ensureNoMoreSelectableCatch] */ - private fun Solve.Request.ensureNoMoreSelectableCatch(notSelectableContext: StreamsExecutionContext) = - copy( - context = context.copy( - sideEffectManager = context.sideEffectManager.ensureNoMoreSelectableCatch(notSelectableContext) - ) - ) + private fun Solve.Request.ensureNoMoreSelectableCatch( + notSelectableContext: StreamsExecutionContext, + ) = copy( + context = + context.copy( + sideEffectManager = context.sideEffectManager.ensureNoMoreSelectableCatch(notSelectableContext), + ), + ) } diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Conjunction.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Conjunction.kt index 3a3ad5d85..ba38038e6 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Conjunction.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Conjunction.kt @@ -26,14 +26,14 @@ import it.unibo.tuprolog.solve.streams.solver.shouldExecuteThrowCut * @author Enrico */ internal object Conjunction : PrimitiveWrapper(Tuple.FUNCTOR, 2) { - override fun uncheckedImplementation(request: Solve.Request): Sequence = sequence { - val subGoals = with(request) { - query.castToTuple().toSequence() - .orderWithStrategy(context, context.solverStrategies::predicationChoiceStrategy) - .toList() - } + val subGoals = + with(request) { + query.castToTuple().toSequence() + .orderWithStrategy(context, context.solverStrategies::predicationChoiceStrategy) + .toList() + } solveConjunctionGoals( request, @@ -42,7 +42,7 @@ internal object Conjunction : PrimitiveWrapper(Tuple.FU Substitution.empty(), emptyList(), request.context.sideEffectManager, - previousGoalsHadAlternatives = false + previousGoalsHadAlternatives = false, ) } @@ -64,16 +64,17 @@ internal object Conjunction : PrimitiveWrapper(Tuple.FU accumulatedSubstitutions: Substitution, accumulatedSideEffects: List, previousResponseSideEffectManager: SideEffectManagerImpl?, - previousGoalsHadAlternatives: Boolean + previousGoalsHadAlternatives: Boolean, ): Pair> { val goal = goals.first().apply(accumulatedSubstitutions).prepareForExecutionAsGoal() - val goalRequest = mainRequest.newSolveRequest( - goal, - accumulatedSubstitutions, - toPropagateContext, - baseSideEffectManager = previousResponseSideEffectManager ?: mainRequest.context.sideEffectManager - ) + val goalRequest = + mainRequest.newSolveRequest( + goal, + accumulatedSubstitutions, + toPropagateContext, + baseSideEffectManager = previousResponseSideEffectManager ?: mainRequest.context.sideEffectManager, + ) var cutExecuted = false var currentSideEffects = emptyList() @@ -89,15 +90,16 @@ internal object Conjunction : PrimitiveWrapper(Tuple.FU goalResponse.sideEffectManager?.shouldExecuteThrowCut() == false && goalResponse.solution is Solution.Yes && moreThanOne(goals.asSequence()) -> { - val sideEffectPair = solveConjunctionGoals( - mainRequest, - goals.drop(1), - goalFinalState.context.apply(currentSideEffects), - goalResponse.solution.substitution - mainRequest.context.substitution, - currentSideEffects, - goalResponse.sideEffectManager as? SideEffectManagerImpl, - previousGoalsHadAlternatives || currentHasAlternatives - ) + val sideEffectPair = + solveConjunctionGoals( + mainRequest, + goals.drop(1), + goalFinalState.context.apply(currentSideEffects), + goalResponse.solution.substitution - mainRequest.context.substitution, + currentSideEffects, + goalResponse.sideEffectManager as? SideEffectManagerImpl, + previousGoalsHadAlternatives || currentHasAlternatives, + ) if (sideEffectPair.first) { cutExecuted = true @@ -107,11 +109,15 @@ internal object Conjunction : PrimitiveWrapper(Tuple.FU } else -> // yield only non-false responses or false responses when there are no open alternatives (because no more or cut) - if (goalResponse.solution !is Solution.No || (!previousGoalsHadAlternatives && !currentHasAlternatives) || cutExecuted) { + if ( + goalResponse.solution !is Solution.No || + (!previousGoalsHadAlternatives && !currentHasAlternatives) || + cutExecuted + ) { yield( mainRequest.replyWith( - goalResponse.copy(sideEffects = accumulatedSideEffects + currentSideEffects) - ) + goalResponse.copy(sideEffects = accumulatedSideEffects + currentSideEffects), + ), ) } } diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Cut.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Cut.kt index 52ae1713b..ad76387b5 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Cut.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Cut.kt @@ -10,14 +10,13 @@ import it.unibo.tuprolog.solve.streams.solver.StreamsExecutionContext * @author Enrico */ internal object Cut : PrimitiveWrapper("!", 0) { - override fun uncheckedImplementation(request: Solve.Request): Sequence = with(request) { sequenceOf( replySuccess( context.substitution, - sideEffectManager = context.sideEffectManager.cut() - ) + sideEffectManager = context.sideEffectManager.cut(), + ), ) } } diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Not.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Not.kt index d785be22d..dd42b2d42 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Not.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Not.kt @@ -15,12 +15,13 @@ import it.unibo.tuprolog.solve.streams.solver.replyWith * @author Enrico */ internal object Not : PrimitiveWrapper("\\+", 1) { - override fun uncheckedImplementation(request: Solve.Request): Sequence = sequence { val goalArgument = request.arguments.single() - StreamsSolver.solveToResponses(request.newSolveRequest(Struct.of(Call.functor, goalArgument))).forEach { goalResponse -> + StreamsSolver.solveToResponses( + request.newSolveRequest(Struct.of(Call.functor, goalArgument)), + ).forEach { goalResponse -> when (goalResponse.solution) { is Solution.Yes -> { yield(request.replyFail()) diff --git a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Throw.kt b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Throw.kt index c268c1e4c..6b40459b1 100644 --- a/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Throw.kt +++ b/solve-streams/src/commonMain/kotlin/it/unibo/tuprolog/solve/streams/stdlib/primitive/Throw.kt @@ -17,7 +17,6 @@ import it.unibo.tuprolog.solve.streams.solver.StreamsExecutionContext * @author Enrico */ internal object Throw : UnaryPredicate.NonBacktrackable("throw") { - override fun Solve.Request.computeOne(first: Term): Solve.Response = try { ensuringAllArgumentsAreInstantiated().arguments.single().freshCopy().let { throwArgument -> @@ -29,7 +28,7 @@ internal object Throw : UnaryPredicate.NonBacktrackable val newSubstitution = (context.substitution + catcher) as Substitution.Unifier replySuccess( newSubstitution, - sideEffectManager = context.sideEffectManager.throwCut(ancestorCatch.context) + sideEffectManager = context.sideEffectManager.throwCut(ancestorCatch.context), ) } @@ -51,13 +50,14 @@ internal object Throw : UnaryPredicate.NonBacktrackable } /** Utility function to extract error type from a term that should be `error(TYPE_STRUCT, ...)` */ - private fun Term.extractErrorTypeAndExtra() = with(this as? Struct) { - when { - this?.functor == ErrorUtils.errorWrapperFunctor && this.arity == 2 -> - (this.args.firstOrNull() as? Struct)?.let { Pair(it, this.args[1]) } - else -> null + private fun Term.extractErrorTypeAndExtra() = + with(this as? Struct) { + when { + this?.functor == ErrorUtils.ERROR_FUNCTOR && this.arity == 2 -> + (this.args.firstOrNull() as? Struct)?.let { Pair(it, this.args[1]) } + else -> null + } } - } /** Utility function to extract error, with filled cause field, till the error root */ private fun Term.extractErrorCauseChain(withContext: ExecutionContext): LogicError? = @@ -66,7 +66,7 @@ internal object Throw : UnaryPredicate.NonBacktrackable context = withContext, type = type, extraData = extra, - cause = extra.extractErrorCauseChain(withContext) + cause = extra.extractErrorCauseChain(withContext), ) } } diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveStreamsTest.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveStreamsTest.kt index d1ecc48d4..4cc428a48 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveStreamsTest.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveStreamsTest.kt @@ -4,7 +4,8 @@ import kotlin.jvm.JvmField object SolveStreamsTest { @JvmField - val expectations = Expectations( - streamsShouldWork = true - ) + val expectations = + Expectations( + streamsShouldWork = true, + ) } diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestStreamsStaticFactory.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestStreamsStaticFactory.kt index ce3aa311b..95b4fb54a 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestStreamsStaticFactory.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestStreamsStaticFactory.kt @@ -3,9 +3,10 @@ package it.unibo.tuprolog.solve import kotlin.test.Test class TestStreamsStaticFactory : TestStaticFactory { - private val prototype = TestStaticFactory.prototype( - SolveStreamsTest.expectations - ) + private val prototype = + TestStaticFactory.prototype( + SolveStreamsTest.expectations, + ) @Test override fun testStaticSolverFactoryForClassic() { diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/SolverStrategiesTest.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/SolverStrategiesTest.kt index d271def76..4787f9238 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/SolverStrategiesTest.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/SolverStrategiesTest.kt @@ -17,7 +17,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class SolverStrategiesTest { - private val aContext = DummyInstances.executionContext private val predication = logicProgramming { "a" and "b" and "c" }.argsSequence diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/StreamsSolverTest.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/StreamsSolverTest.kt index 55b4e885d..0186dd360 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/StreamsSolverTest.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/StreamsSolverTest.kt @@ -12,7 +12,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class StreamsSolverTest { - @Test fun defaultConstructorParameters() { val toBeTested = StreamsSolver() diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/TestStreamsSolverConstruction.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/TestStreamsSolverConstruction.kt index 870ea16a2..e777dc82a 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/TestStreamsSolverConstruction.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/TestStreamsSolverConstruction.kt @@ -10,7 +10,6 @@ import kotlin.test.Test class TestStreamsSolverConstruction : TestSolverConstruction, SolverFactory by StreamsSolverFactory { - private val prototype = TestSolverConstruction.prototype(this, DefaultBuiltins) @Test diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/CallTest.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/CallTest.kt index e619665b4..87332436f 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/CallTest.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/CallTest.kt @@ -19,7 +19,6 @@ import kotlin.test.assertFailsWith * @author Enrico */ internal class CallTest { - @Test fun callForwardsResponsesFromArgumentExecutionIfWellFormedGoalAndNotVariable() { requestSolutionMap.forEach { (request, solutionList) -> diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/CatchTest.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/CatchTest.kt index ed3b8321b..370f01c49 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/CatchTest.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/CatchTest.kt @@ -13,7 +13,6 @@ import kotlin.test.Test */ @Ignore internal class CatchTest { - @Test fun catchWorksLikeCallIfNoErrorIsThrownByFirstArgument() { CatchUtils.requestSolutionMap.forEach { (request, solutionList) -> diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/ConjunctionTest.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/ConjunctionTest.kt index e7c857abb..b5c278ce2 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/ConjunctionTest.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/ConjunctionTest.kt @@ -26,7 +26,6 @@ import kotlin.test.Test * @author Enrico */ internal class ConjunctionTest { - @Test fun conjunctionOfTrueReturnsTrue() { val responses = Conjunction.implementation.solve(trueAndTrueSolveRequest) @@ -59,30 +58,35 @@ internal class ConjunctionTest { val firstSubstitution = "L" to "first" val secondSubstitution = "R" to "second" - val leftPrimitive = PrimitiveWrapper.wrap("left", 0) { - sequenceOf(it.replySuccess(firstSubstitution)) - } - val rightPrimitive = PrimitiveWrapper.wrap("right", 0) { - sequenceOf(it.replySuccess(secondSubstitution)) - } + val leftPrimitive = + PrimitiveWrapper.wrap("left", 0) { + sequenceOf(it.replySuccess(firstSubstitution)) + } + val rightPrimitive = + PrimitiveWrapper.wrap("right", 0) { + sequenceOf(it.replySuccess(secondSubstitution)) + } val goal = "left" and "right" - val request = Solve.Request( - goal.extractSignature(), - goal.args, - StreamsExecutionContext( - substitution = preRequestSubstitution, - libraries = Runtime.of( - Library.of( - alias = "conjunction.test", - primitives = mapOf( - *ktListOf(Conjunction, leftPrimitive, rightPrimitive) - .map { it.descriptionPair }.toTypedArray() - ) - ) - ) + val request = + Solve.Request( + goal.extractSignature(), + goal.args, + StreamsExecutionContext( + substitution = preRequestSubstitution, + libraries = + Runtime.of( + Library.of( + alias = "conjunction.test", + primitives = + mapOf( + *ktListOf(Conjunction, leftPrimitive, rightPrimitive) + .map { it.descriptionPair }.toTypedArray(), + ), + ), + ), + ), ) - ) val responses = Conjunction.implementation.solve(request) diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/CutTest.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/CutTest.kt index 5aadbd842..0b5fe3c8f 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/CutTest.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/CutTest.kt @@ -20,7 +20,6 @@ import kotlin.test.assertNotSame * @author Enrico */ internal class CutTest { - private val cutPrimitiveSignature = Signature("!", 0) private fun cutRequest(context: ExecutionContext = StreamsExecutionContext()) = diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/NotTest.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/NotTest.kt index 5dc9b4246..4e6424d5f 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/NotTest.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/NotTest.kt @@ -21,13 +21,13 @@ import kotlin.test.Test * @author Enrico */ internal class NotTest { - @Test fun notRevertsProvidedNoResponse() { val query = logicProgramming { "\\+"(false) } - val solutions = Not.implementation.solve( - createSolveRequest(query, primitives = mapOf(Not.descriptionPair, Call.descriptionPair)) - ).map { it.solution }.asIterable() + val solutions = + Not.implementation.solve( + createSolveRequest(query, primitives = mapOf(Not.descriptionPair, Call.descriptionPair)), + ).map { it.solution }.asIterable() assertSolutionEquals(listOf(query.yes()), solutions) } @@ -35,9 +35,10 @@ internal class NotTest { @Test fun notRevertsProvidedYesResponse() { val query = logicProgramming { "\\+"(true) } - val solutions = Not.implementation.solve( - createSolveRequest(query, primitives = mapOf(Not.descriptionPair, Call.descriptionPair)) - ).map { it.solution }.asIterable() + val solutions = + Not.implementation.solve( + createSolveRequest(query, primitives = mapOf(Not.descriptionPair, Call.descriptionPair)), + ).map { it.solution }.asIterable() assertSolutionEquals(listOf(query.no()), solutions) } @@ -45,13 +46,14 @@ internal class NotTest { @Test fun notReturnsOnlyOneFailResponseIfMoreTrueOnes() { val query = logicProgramming { "\\+"("a") } - val solutions = Not.implementation.solve( - createSolveRequest( - query, - primitives = mapOf(Not.descriptionPair, Call.descriptionPair), - database = LogicProgrammingScopeWithTheories.of().theory({ "a" }, { "a" }) - ) - ).map { it.solution }.asIterable() + val solutions = + Not.implementation.solve( + createSolveRequest( + query, + primitives = mapOf(Not.descriptionPair, Call.descriptionPair), + database = LogicProgrammingScopeWithTheories.of().theory({ "a" }, { "a" }), + ), + ).map { it.solution }.asIterable() assertSolutionEquals(listOf(query.no()), solutions) } @@ -60,12 +62,13 @@ internal class NotTest { @Ignore fun notReturnsAsIsAnHaltSolution() { val query = logicProgramming { "\\+"(1) } - val solutions = Not.implementation.solve( - createSolveRequest( - query, - primitives = mapOf(Not.descriptionPair, Call.descriptionPair, Throw.descriptionPair) - ) - ).map { it.solution }.asIterable() + val solutions = + Not.implementation.solve( + createSolveRequest( + query, + primitives = mapOf(Not.descriptionPair, Call.descriptionPair, Throw.descriptionPair), + ), + ).map { it.solution }.asIterable() assertSolutionEquals( listOf( @@ -74,11 +77,11 @@ internal class NotTest { DummyInstances.executionContext, Not.signature, TypeError.Expected.CALLABLE, - logicProgramming { numOf(1) } - ) - ) + logicProgramming { numOf(1) }, + ), + ), ), - solutions + solutions, ) } } diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/ThrowTest.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/ThrowTest.kt index b8606163b..60d7042cd 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/ThrowTest.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/ThrowTest.kt @@ -11,7 +11,6 @@ import kotlin.test.Test * @author Enrico */ internal class ThrowTest { - @Test fun throwPrimitiveThrowCorrectErrors() { ThrowUtils.errorThrowingBehaviourRequest.forEach { (request, errorType) -> diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/integrationtest/CutAndConjunctionIntegrationTest.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/integrationtest/CutAndConjunctionIntegrationTest.kt index 0f38bada3..c8d48e345 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/integrationtest/CutAndConjunctionIntegrationTest.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/integrationtest/CutAndConjunctionIntegrationTest.kt @@ -19,7 +19,6 @@ import kotlin.test.Test * @author Enrico */ internal class CutAndConjunctionIntegrationTest { - @Test fun cutAsFirstGoalInConjunctionDoesNothing() { logicProgramming { @@ -29,11 +28,12 @@ internal class CutAndConjunctionIntegrationTest { } modifiedSimpleFactDatabaseGoals.forEach { (goal, solutionList) -> - val request = createSolveRequest( - goal, - simpleFactTheory, - mapOf(Conjunction.descriptionPair, Cut.descriptionPair) - ) + val request = + createSolveRequest( + goal, + simpleFactTheory, + mapOf(Conjunction.descriptionPair, Cut.descriptionPair), + ) val solutions = Conjunction.implementation.solve(request).map { it.solution }.asIterable() assertSolutionEquals(solutionList, solutions) @@ -50,11 +50,12 @@ internal class CutAndConjunctionIntegrationTest { } modifiedSimpleFactDatabaseGoals.forEach { (goal, solutionList) -> - val request = createSolveRequest( - goal, - simpleFactTheory, - mapOf(Conjunction.descriptionPair, Cut.descriptionPair) - ) + val request = + createSolveRequest( + goal, + simpleFactTheory, + mapOf(Conjunction.descriptionPair, Cut.descriptionPair), + ) val solutions = Conjunction.implementation.solve(request).map { it.solution }.asIterable() assertSolutionEquals(solutionList, solutions) @@ -85,9 +86,9 @@ internal class CutAndConjunctionIntegrationTest { assertSolutionEquals( ktListOf( query.yes("A" to "a", "B" to "a"), - query.yes("A" to "a", "B" to "b") + query.yes("A" to "a", "B" to "b"), ), - responses + responses, ) } } @@ -107,15 +108,16 @@ internal class CutAndConjunctionIntegrationTest { @Test fun deepCutsInConjunctionsDoesntCutOuterScopeNodes() { logicProgramming { - val database = theoryOf( - *simpleFactTheory.takeWhile { it.head != "g"("b") }.toTypedArray(), - rule { "g"("cutting") `if` "g1"("deep1") }, - rule { "g1"("deep1") `if` "g2"("deep2") }, - rule { "g1"("deep1") `if` "g3"("deep3") }, - rule { "g2"("deep2") `if` "!" }, - rule { "g3"("deep3") `if` "!" }, - *simpleFactTheory.dropWhile { it.head != "g"("b") }.toTypedArray() - ) + val database = + theoryOf( + *simpleFactTheory.takeWhile { it.head != "g"("b") }.toTypedArray(), + rule { "g"("cutting") `if` "g1"("deep1") }, + rule { "g1"("deep1") `if` "g2"("deep2") }, + rule { "g1"("deep1") `if` "g3"("deep3") }, + rule { "g2"("deep2") `if` "!" }, + rule { "g3"("deep3") `if` "!" }, + *simpleFactTheory.dropWhile { it.head != "g"("b") }.toTypedArray(), + ) val query = "g"("A") and "!" and "g"("B") val request = createSolveRequest(query, database, mapOf(Conjunction.descriptionPair, Cut.descriptionPair)) val responses = Conjunction.implementation.solve(request).map { it.solution }.asIterable() @@ -125,9 +127,9 @@ internal class CutAndConjunctionIntegrationTest { query.yes("A" to "a", "B" to "a"), query.yes("A" to "a", "B" to "cutting"), query.yes("A" to "a", "B" to "cutting"), - query.yes("A" to "a", "B" to "b") + query.yes("A" to "a", "B" to "b"), ), - responses + responses, ) } } diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/testutils/CallUtils.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/testutils/CallUtils.kt index acbe1397a..8ce3d4a74 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/testutils/CallUtils.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/testutils/CallUtils.kt @@ -31,7 +31,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal object CallUtils { - private val aContext = DummyInstances.executionContext /** @@ -59,12 +58,12 @@ internal object CallUtils { }.toTypedArray(), *simpleFactTheoryNotableGoalToSolutions.map { (goal, solutionList) -> Call.functor(goal and "!").run { to(solutionList.subList(0, 1).changeQueriesTo(this)) } - }.toTypedArray() + }.toTypedArray(), ).mapKeys { (query, _) -> createSolveRequest( query, database = simpleFactTheory, - primitives = mapOf(*ktListOf(Call, Cut, Conjunction).map { it.descriptionPair }.toTypedArray()) + primitives = mapOf(*ktListOf(Call, Cut, Conjunction).map { it.descriptionPair }.toTypedArray()), ) } } @@ -89,17 +88,18 @@ internal object CallUtils { TypeError( context = aContext, expectedType = TypeError.Expected.CALLABLE, - culprit = true and 1 - ) + culprit = true and 1, + ), ) - }) + }), ).mapKeys { (query, _) -> createSolveRequest( query, - primitives = mapOf( - *ktListOf(Call, Cut, Throw, Conjunction) - .map { it.descriptionPair }.toTypedArray() - ) + primitives = + mapOf( + *ktListOf(Call, Cut, Throw, Conjunction) + .map { it.descriptionPair }.toTypedArray(), + ), ) } } @@ -117,12 +117,12 @@ internal object CallUtils { Call.functor(goal and Call.functor("!")).run { to(solutionList.changeQueriesTo(this)) } - }.toTypedArray() + }.toTypedArray(), ).mapKeys { (query, _) -> createSolveRequest( query, database = simpleFactTheory, - primitives = mapOf(*ktListOf(Call, Cut, Conjunction).map { it.descriptionPair }.toTypedArray()) + primitives = mapOf(*ktListOf(Call, Cut, Conjunction).map { it.descriptionPair }.toTypedArray()), ) } } @@ -136,7 +136,7 @@ internal object CallUtils { */ internal fun assertErrorCauseChainComputedCorrectly( request: Solve.Request, - expectedErrorSolution: Solution.Halt + expectedErrorSolution: Solution.Halt, ) { val nextState = StateGoalEvaluation(request).behave().toList().single() diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/testutils/CatchUtils.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/testutils/CatchUtils.kt index a2e9ce228..70c57385e 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/testutils/CatchUtils.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/testutils/CatchUtils.kt @@ -21,7 +21,6 @@ import kotlin.collections.listOf as ktListOf * @author Enrico */ internal object CatchUtils { - /** * Catch primitive examples, with expected responses * @@ -40,21 +39,19 @@ internal object CatchUtils { *catchTestingGoalsToSolutions.map { (goal, solutionList) -> createSolveRequest( goal, - primitives = mapOf(*ktListOf(Call, Catch, Conjunction, Throw).map { it.descriptionPair }.toTypedArray()) + primitives = sequenceOf(Call, Catch, Conjunction, Throw).associate { it.descriptionPair }, ) to solutionList }.toTypedArray(), - *CallUtils.requestSolutionMap.flatMap { (callRequest, solutions) -> ktListOf( logicProgramming { Catch.functor(callRequest.query, `_`, false) }, - logicProgramming { Catch.functor(callRequest.arguments.single(), `_`, false) } + logicProgramming { Catch.functor(callRequest.arguments.single(), `_`, false) }, ).map { with(callRequest.context.libraries) { createSolveRequest(it, clauses, primitives + Catch.descriptionPair) } to solutions.changeQueriesTo(it) } }.toTypedArray(), - *CallUtils.requestToErrorSolutionMap.map { (callRequest, solutions) -> val updatedPrimitives = callRequest.context.libraries.primitives + Catch.descriptionPair logicProgramming { @@ -65,7 +62,7 @@ internal object CatchUtils { } } } - }.toTypedArray() + }.toTypedArray(), ) } @@ -86,10 +83,11 @@ internal object CatchUtils { .map { (goal, solutionList) -> createSolveRequest( goal, - primitives = mapOf( - *ktListOf(Call, Catch, Conjunction, Throw).map { it.descriptionPair }.toTypedArray() - ), - database = catchAndThrowTheoryExample + primitives = + mapOf( + *ktListOf(Call, Catch, Conjunction, Throw).map { it.descriptionPair }.toTypedArray(), + ), + database = catchAndThrowTheoryExample, ) to solutionList } } diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/testutils/ConjunctionUtils.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/testutils/ConjunctionUtils.kt index ff7e8a875..c8844e42a 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/testutils/ConjunctionUtils.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/testutils/ConjunctionUtils.kt @@ -12,27 +12,28 @@ import it.unibo.tuprolog.solve.yes * @author Enrico */ internal object ConjunctionUtils { - internal val trueAndTrueSolveRequest = logicProgramming { createSolveRequest("true" and "true") } internal val twoMatchesDB = logicProgramming { theory({ "f"("a") }, { "f"("b") }) } - internal val myRequestToSolutions = logicProgramming { - ktListOf( - ("f"("A") and "f"("B")).hasSolutions( - { yes("A" to "a", "B" to "a") }, - { yes("A" to "a", "B" to "b") }, - { yes("A" to "b", "B" to "a") }, - { yes("A" to "b", "B" to "b") } + internal val myRequestToSolutions = + logicProgramming { + ktListOf( + ("f"("A") and "f"("B")).hasSolutions( + { yes("A" to "a", "B" to "a") }, + { yes("A" to "a", "B" to "b") }, + { yes("A" to "b", "B" to "a") }, + { yes("A" to "b", "B" to "b") }, + ), ) - ) - } + } /** Requests that should fail */ - internal val failedRequests = logicProgramming { - ktListOf( - "true" and "fail", - "fail" and "true", - "true" and "true" and "fail" - ).map { createSolveRequest(it) } - } + internal val failedRequests = + logicProgramming { + ktListOf( + "true" and "fail", + "fail" and "true", + "true" and "true" and "fail", + ).map { createSolveRequest(it) } + } } diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/testutils/PrimitiveUtils.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/testutils/PrimitiveUtils.kt index 31485be18..d15f2ed20 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/testutils/PrimitiveUtils.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/testutils/PrimitiveUtils.kt @@ -12,9 +12,11 @@ import kotlin.test.assertEquals * @author Enrico */ internal object PrimitiveUtils { - /** Utility function to assert that there's only one Solution of given type, with given query and substitution */ - internal fun assertOnlyOneSolution(expectedSolution: Solution, solutions: Sequence) { + internal fun assertOnlyOneSolution( + expectedSolution: Solution, + solutions: Sequence, + ) { assertEquals(1, solutions.count(), "Expected only one solution, but ${solutions.toList()}") with(solutions.single().solution) { assertEquals(expectedSolution::class, this::class) @@ -35,6 +37,8 @@ internal object PrimitiveUtils { } /** Utility function to assert the [LogicError] type correctness of [Solution.Halt] */ - internal fun assertPrologError(expected: KClass, actualSolution: Solution) = - assertEquals(expected, (actualSolution as Solution.Halt).exception::class) + internal fun assertPrologError( + expected: KClass, + actualSolution: Solution, + ) = assertEquals(expected, (actualSolution as Solution.Halt).exception::class) } diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/testutils/ThrowUtils.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/testutils/ThrowUtils.kt index 3639e0d1b..b25a37150 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/testutils/ThrowUtils.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/primitive/testutils/ThrowUtils.kt @@ -14,7 +14,6 @@ import it.unibo.tuprolog.solve.streams.testutils.SolverTestUtils.createSolveRequ * @author Enrico */ internal object ThrowUtils { - /** Requests that will return exceptions, if primitive invoked */ internal val errorThrowingBehaviourRequest by lazy { logicProgramming { @@ -23,7 +22,7 @@ internal object ThrowUtils { Throw.functor(1).run { to(SystemError::class) }, Throw.functor("ciao").run { to(SystemError::class) }, Throw.functor(ErrorUtils.errorStructOf(atomOf(SystemError.typeFunctor))).run { to(SystemError::class) }, - Throw.functor(ErrorUtils.errorStructOf("type_error"("integer", "ciao"))).run { to(TypeError::class) } + Throw.functor(ErrorUtils.errorStructOf("type_error"("integer", "ciao"))).run { to(TypeError::class) }, ).mapKeys { (query, _) -> createSolveRequest(query, primitives = mapOf(Throw.descriptionPair)) } } } diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/ExecutionContextImplTest.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/ExecutionContextImplTest.kt index c01e0a14f..2f9704bf6 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/ExecutionContextImplTest.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/ExecutionContextImplTest.kt @@ -14,20 +14,21 @@ import kotlin.test.assertNull * @author Enrico */ internal class ExecutionContextImplTest { - @Test fun logicStackTraceCorrectlyComputed() { - val sideEffectManagerWithLogicalParents = SideEffectManagerImpl( - logicalParentRequests = listOf( - createSolveRequest(Atom.of("ciao")), - createSolveRequest(Atom.of("ciao2")) + val sideEffectManagerWithLogicalParents = + SideEffectManagerImpl( + logicalParentRequests = + listOf( + createSolveRequest(Atom.of("ciao")), + createSolveRequest(Atom.of("ciao2")), + ), ) - ) val toBeTested = StreamsExecutionContext(sideEffectManager = sideEffectManagerWithLogicalParents) assertEquals( sequenceOf(Atom.of("ciao"), Atom.of("ciao2")).toList(), - toBeTested.logicStackTrace.toList() + toBeTested.logicStackTrace.toList(), ) } diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/SolverUtilsTest.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/SolverUtilsTest.kt index 18fc000e8..b43a88d3d 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/SolverUtilsTest.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/SolverUtilsTest.kt @@ -35,12 +35,12 @@ import kotlin.test.fail * @author Enrico */ internal class SolverUtilsTest { - - private val aContext = StreamsExecutionContext( - dynamicKb = Theory.of({ factOf(atomOf("a")) }), - staticKb = Theory.of({ factOf(atomOf("a")) }), - flags = FlagStore.EMPTY - ) + private val aContext = + StreamsExecutionContext( + dynamicKb = Theory.of({ factOf(atomOf("a")) }), + staticKb = Theory.of({ factOf(atomOf("a")) }), + flags = FlagStore.EMPTY, + ) /** A "true" solveRequest */ private val solveRequest = Solve.Request(Signature("true", 0), emptyList(), aContext) @@ -71,7 +71,7 @@ internal class SolverUtilsTest { fun orderWithStrategyWithEmptyElementsDoesNothing() { assertEquals( emptySequence().toList(), - emptySequence().orderWithStrategy(aContext) { seq, _ -> seq.first() }.toList() + emptySequence().orderWithStrategy(aContext) { seq, _ -> seq.first() }.toList(), ) } @@ -130,7 +130,7 @@ internal class SolverUtilsTest { yield(1) yield(1) fail("Should not evaluate entire sequence") - } + }, ) } } @@ -157,12 +157,13 @@ internal class SolverUtilsTest { @Test fun newSolveRequestPropagatesCorrectlyContextFields() { val aClause = Clause.of(Atom.of("ddd"), Atom.of("ccc")) - val modifiedContext = aContext.copy( - dynamicKb = Theory.empty(), - staticKb = aContext.staticKb.assertA(aClause), - flags = FlagStore.of("someFlag" to Atom.of("someFlagValue")), - libraries = Runtime.empty() - ) + val modifiedContext = + aContext.copy( + dynamicKb = Theory.empty(), + staticKb = aContext.staticKb.assertA(aClause), + flags = FlagStore.of("someFlag" to Atom.of("someFlagValue")), + libraries = Runtime.empty(), + ) val toBeTested = solveRequest.newSolveRequest(solveRequest.query, toPropagateContextData = modifiedContext) @@ -196,13 +197,14 @@ internal class SolverUtilsTest { val underTestResponses = listOf(aYesResponse, aNoResponse, anHaltResponse) - val correct = with(solveRequest) { - listOf( - replySuccess(expectedSubstitution, sideEffectManager = expectedSideEffectsManager), - replyFail(sideEffectManager = expectedSideEffectsManager), - replyException(expectedException, sideEffectManager = expectedSideEffectsManager) - ) - } + val correct = + with(solveRequest) { + listOf( + replySuccess(expectedSubstitution, sideEffectManager = expectedSideEffectsManager), + replyFail(sideEffectManager = expectedSideEffectsManager), + replyException(expectedException, sideEffectManager = expectedSideEffectsManager), + ) + } val toBeTested = underTestResponses.map { solveRequest.replyWith(it) } correct.zip(toBeTested).forEach { (expected, actual) -> diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/AbstractStateTest.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/AbstractStateTest.kt index e073f3d14..ae2a2abde 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/AbstractStateTest.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/AbstractStateTest.kt @@ -12,14 +12,15 @@ import kotlin.test.assertEquals * @author Enrico */ internal class AbstractStateTest { - private val solveRequest = createSolveRequest(Atom.of("test")) /** An [AbstractState] instance with dummy parameters, and emptySequence returning behaviour */ - private val abstractStateUnderTest = object : AbstractState(solveRequest) { - override fun behave(): Sequence = emptySequence() - override val context: StreamsExecutionContext = solveRequest.context - } + private val abstractStateUnderTest = + object : AbstractState(solveRequest) { + override fun behave(): Sequence = emptySequence() + + override val context: StreamsExecutionContext = solveRequest.context + } @Test fun holdsInsertedData() { diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/AlreadyExecutedStateTest.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/AlreadyExecutedStateTest.kt index ea2b9b40d..447c6b0b7 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/AlreadyExecutedStateTest.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/AlreadyExecutedStateTest.kt @@ -12,7 +12,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class AlreadyExecutedStateTest { - private val endState = StateMachineExecutorUtils.endState @Test diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/StateMachineExecutorTest.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/StateMachineExecutorTest.kt index 6a2c6c7c7..1ed9a1b03 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/StateMachineExecutorTest.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/StateMachineExecutorTest.kt @@ -25,7 +25,6 @@ import kotlin.test.fail * @author Enrico */ internal class StateMachineExecutorTest { - @Test fun executeOfOneShotStateWorksAsExpected() { val stateSequence = StateMachineExecutor.execute(oneShotState) @@ -103,16 +102,18 @@ internal class StateMachineExecutorTest { assertEquals(correctlyExecuted.flatten().count(), toBeTested.flatten().count()) assertEquals( correctlyExecuted.flatten().map { it.toString() }, - toBeTested.flatten().map { it.wrappedState.toString() } + toBeTested.flatten().map { it.wrappedState.toString() }, ) } @Test fun executeWrappingCanBeUsedTransparentlyInternallyBeforeExternalExecuteCall() { - val mixedBehavedAndNonBehavedStates = object : State by endState { - override val hasBehaved: Boolean = false - override fun behave(): Sequence = StateMachineExecutor.executeWrapping(threeShotState) - } + val mixedBehavedAndNonBehavedStates = + object : State by endState { + override val hasBehaved: Boolean = false + + override fun behave(): Sequence = StateMachineExecutor.executeWrapping(threeShotState) + } val stateSequence = StateMachineExecutor.execute(mixedBehavedAndNonBehavedStates) assertEquals(4, stateSequence.count()) diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/AbstractTimedStateTest.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/AbstractTimedStateTest.kt index fbdc3f4af..a8a468518 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/AbstractTimedStateTest.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/AbstractTimedStateTest.kt @@ -19,7 +19,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class AbstractTimedStateTest { - private val behaviourResponse = emptySequence() /** Creates an [AbstractTimedState] instance with provided parameters, and emptySequence returning behaviour */ @@ -29,13 +28,15 @@ internal class AbstractTimedStateTest { } /** Creates a test solve request with given timing fields, or defaults if not provided */ - private fun createTimedRequest(requestIssuingInstant: TimeInstant? = null, maxDuration: TimeDuration? = null) = - with(createSolveRequest(Truth.TRUE)) { - copy( - startTime = requestIssuingInstant ?: this.startTime, - maxDuration = maxDuration ?: this.maxDuration - ) - } + private fun createTimedRequest( + requestIssuingInstant: TimeInstant? = null, + maxDuration: TimeDuration? = null, + ) = with(createSolveRequest(Truth.TRUE)) { + copy( + startTime = requestIssuingInstant ?: this.startTime, + maxDuration = maxDuration ?: this.maxDuration, + ) + } @Test fun behaveWorksAsUsualIfLongMaxValueTimeoutSpecified() { diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateGoalEvaluationTest.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateGoalEvaluationTest.kt index 29172cb25..2c06a6635 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateGoalEvaluationTest.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateGoalEvaluationTest.kt @@ -16,7 +16,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class StateGoalEvaluationTest { - @Test fun signaturesNotRecognizedAsPrimitivesFlowToStateRuleSelection() { StateGoalEvaluationUtils.nonPrimitiveRequests.forEach { request -> @@ -38,19 +37,20 @@ internal class StateGoalEvaluationTest { @Test fun returningSolutionHaltHasSameBehaviourOfThrowingTheException() { val throwingPrimitive = createRequestForPrimitiveResponding { throw HaltException(context = expectedContext) } - val nonThrowingPrimitive = createRequestForPrimitiveResponding { - sequenceOf( - it.replyException(HaltException(context = expectedContext)), - it.replyFail() - ) - } + val nonThrowingPrimitive = + createRequestForPrimitiveResponding { + sequenceOf( + it.replyException(HaltException(context = expectedContext)), + it.replyFail(), + ) + } val throwingEndState = StateGoalEvaluation(throwingPrimitive).behave().single() val nonThrowingEndState = StateGoalEvaluation(nonThrowingPrimitive).behave().single() assertEquals( throwingEndState.solve.getSideEffectsManager(), - nonThrowingEndState.solve.getSideEffectsManager() + nonThrowingEndState.solve.getSideEffectsManager(), ) } diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateInitTest.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateInitTest.kt index d5458840b..765927ca9 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateInitTest.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateInitTest.kt @@ -26,14 +26,13 @@ import kotlin.test.assertTrue * @author Enrico */ internal class StateInitTest { - @Test fun trueGoalGoesIntoTrueEndState() { // precondition assertTrue { SolverStrategies.prologStandard.successCheckStrategy( Truth.TRUE, - DummyInstances.executionContext + DummyInstances.executionContext, ) } @@ -71,7 +70,7 @@ internal class StateInitTest { assertEquals( prepareGoalForExecution(it.query), - (nextStates.single().solve as Solve.Request<*>).query + (nextStates.single().solve as Solve.Request<*>).query, ) } } diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateRuleSelectionTest.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateRuleSelectionTest.kt index 93c224a22..06dfb5e49 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateRuleSelectionTest.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/StateRuleSelectionTest.kt @@ -25,27 +25,28 @@ import kotlin.test.Test * @author Enrico */ internal class StateRuleSelectionTest { - private val theQueryVariable = Var.of("V") /** A struct query in the form `f(V)` */ private val theQuery = logicProgramming { "f"(theQueryVariable) } /** A Solve.Request with three databases and three different facts, to test how they should be used/combined in searching */ - private val threeDBSolveRequest = Solve.Request( - theQuery.extractSignature(), - theQuery.args, - StreamsExecutionContext( - libraries = Runtime.of( - Library.of( - alias = "testLib", - clauses = logicProgramming { theory({ "f"("a") }) } - ) + private val threeDBSolveRequest = + Solve.Request( + theQuery.extractSignature(), + theQuery.args, + StreamsExecutionContext( + libraries = + Runtime.of( + Library.of( + alias = "testLib", + clauses = logicProgramming { theory({ "f"("a") }) }, + ), + ), + staticKb = logicProgramming { theory({ "f"("b") }) }, + dynamicKb = logicProgramming { theory({ "f"("c") }) }, ), - staticKb = logicProgramming { theory({ "f"("b") }) }, - dynamicKb = logicProgramming { theory({ "f"("c") }) } ) - ) @Test fun noMatchingRulesFoundMakeItGoIntoFalseState() { @@ -104,12 +105,13 @@ internal class StateRuleSelectionTest { fun stateRuleSelectionUsesCombinationOfStaticAndDynamicKBWhenLibraryTheoriesDoesntProvideMatches() { val dynamicAndStaticKBSolveRequest = with(threeDBSolveRequest) { copy(context = context.copy(libraries = Runtime.empty())) } - val correctSubstitutions = logicProgramming { - ktListOf( - theQueryVariable to "b", - theQueryVariable to "c" - ) - } + val correctSubstitutions = + logicProgramming { + ktListOf( + theQueryVariable to "b", + theQueryVariable to "c", + ) + } val nextStates = StateRuleSelection(dynamicAndStaticKBSolveRequest).behave() diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/integrationtest/StateIntegrationTesting.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/integrationtest/StateIntegrationTesting.kt index 3f8ff9d48..ce19d2a0d 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/integrationtest/StateIntegrationTesting.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/integrationtest/StateIntegrationTesting.kt @@ -46,29 +46,30 @@ import kotlin.test.assertEquals * @author Enrico */ internal class StateIntegrationTesting { - /** Shorthand function to execute a solveRequest */ private fun Solve.Request.executeFSM(): Sequence = - StateMachineExecutor.execute(StateInit(this)) + StateMachineExecutor.execute( + StateInit(this), + ) /** Utility function to test correct states behaviour inside this class */ private fun assertSolutionsCorrect( querySolutionsMap: List>>, - database: Theory + database: Theory, ) { querySolutionsMap.forEach { (goal, solutionList) -> val nextStates = createSolveRequest(goal, database, DefaultBuiltins.primitives).executeFSM() assertOverFilteredStateInstances( nextStates, - { it.solve.solution.query == goal } + { it.solve.solution.query == goal }, ) { index, finalState -> assertSolutionEquals( solutionList[index], finalState.solve.solution.let { // cleanUp as in StreamsSolver (it as? Solution.Yes)?.copy(substitution = it.substitution.filter { _, t -> t !is Var }) ?: it - } + }, ) } } @@ -89,9 +90,9 @@ internal class StateIntegrationTesting { listOf( StateGoalEvaluation::class, StateRuleSelection::class, - StateEnd.False::class + StateEnd.False::class, ), - nextStates.map { it::class } + nextStates.map { it::class }, ) } @@ -114,7 +115,7 @@ internal class StateIntegrationTesting { fun queriesWithCutConjunctionAndBacktrackingTheory() { assertSolutionsCorrect( cutConjunctionAndBacktrackingTheoryNotableGoalToSolutions, - cutConjunctionAndBacktrackingTheory + cutConjunctionAndBacktrackingTheory, ) } @@ -122,17 +123,18 @@ internal class StateIntegrationTesting { fun timeoutExceptionCorrectlyThrown() { infiniteComputationTheoryNotableGoalToSolution.forEach { (goal, solutionList) -> val maxDuration = 100L - val request = Solve.Request( - goal.extractSignature(), - goal.args, - StreamsExecutionContext(staticKb = infiniteComputationTheory), - maxDuration = maxDuration - ) + val request = + Solve.Request( + goal.extractSignature(), + goal.args, + StreamsExecutionContext(staticKb = infiniteComputationTheory), + maxDuration = maxDuration, + ) val nextStates = request.executeFSM() assertOverFilteredStateInstances( nextStates, - { it.solve.solution.query == goal } + { it.solve.solution.query == goal }, ) { index, finalState -> assertEquals(solutionList[index]::class, finalState.solve.solution::class) } @@ -149,7 +151,7 @@ internal class StateIntegrationTesting { fun prologStandardSearchTreeWithCutExample() { assertSolutionsCorrect( prologStandardExampleWithCutTheoryNotableGoalToSolution, - prologStandardExampleWithCutTheory + prologStandardExampleWithCutTheory, ) } diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/testutils/StateGoalEvaluationUtils.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/testutils/StateGoalEvaluationUtils.kt index 1f94259c9..846667f4a 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/testutils/StateGoalEvaluationUtils.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/testutils/StateGoalEvaluationUtils.kt @@ -24,19 +24,21 @@ import it.unibo.tuprolog.solve.streams.testutils.SolverTestUtils.createSolveRequ * @author Enrico */ internal object StateGoalEvaluationUtils { - internal val expectedContext = StreamsExecutionContext(sideEffectManager = SideEffectManagerImpl()) /** Creates a request launching exactly given primitive behaviour */ - internal fun createRequestForPrimitiveResponding(primitiveBehaviour: Primitive): Solve.Request { - val testPrimitive = PrimitiveWrapper.wrap("testPrimitive", 0) { - primitiveBehaviour.solve(it) - } + internal fun createRequestForPrimitiveResponding( + primitiveBehaviour: Primitive, + ): Solve.Request { + val testPrimitive = + PrimitiveWrapper.wrap("testPrimitive", 0) { + primitiveBehaviour.solve(it) + } return testPrimitive.run { createSolveRequest( signature withArgs emptyList(), - primitives = mapOf(descriptionPair, Throw.descriptionPair) + primitives = mapOf(descriptionPair, Throw.descriptionPair), ) } } @@ -56,15 +58,23 @@ internal object StateGoalEvaluationUtils { to listOf(StateEnd.Halt::class), createRequestForPrimitiveResponding { sequence { - yieldAll(StreamsSolver.solveToResponses(createRequestForPrimitiveResponding { throw HaltException(context = it.context) })) + yieldAll( + StreamsSolver.solveToResponses( + createRequestForPrimitiveResponding { throw HaltException(context = it.context) }, + ), + ) } } to listOf(StateEnd.Halt::class), createRequestForPrimitiveResponding { sequence { - yieldAll(StreamsSolver.solveToResponses(createRequestForPrimitiveResponding { throw HaltException(context = it.context) })) + yieldAll( + StreamsSolver.solveToResponses( + createRequestForPrimitiveResponding { throw HaltException(context = it.context) }, + ), + ) yield(it.replyFail()) } - } to listOf(StateEnd.Halt::class) + } to listOf(StateEnd.Halt::class), ) } @@ -77,9 +87,9 @@ internal object StateGoalEvaluationUtils { throw TypeError( context = it.context, expectedType = TypeError.Expected.CALLABLE, - culprit = Var.of("X") + culprit = Var.of("X"), ) - } + }, ) } diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/testutils/StateInitUtils.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/testutils/StateInitUtils.kt index 286df1295..e5268301b 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/testutils/StateInitUtils.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/testutils/StateInitUtils.kt @@ -16,10 +16,11 @@ import it.unibo.tuprolog.solve.streams.solver.fsm.impl.StateInit * @author Enrico */ internal object StateInitUtils { - /** Utility function to create a [Solve.Request] */ - private fun createSolveRequest(signature: Signature, argList: List = emptyList()) = - Solve.Request(signature, argList, StreamsExecutionContext()) + private fun createSolveRequest( + signature: Signature, + argList: List = emptyList(), + ) = Solve.Request(signature, argList, StreamsExecutionContext()) /** Solve request for `true` Atom */ internal val trueRequest = createSolveRequest(Signature("true", 0)) @@ -28,22 +29,25 @@ internal object StateInitUtils { private val failRequest = createSolveRequest(Signature("fail", 0)) /** Solve request for some vararg primitive */ - private val varargPrimitiveRequest = createSolveRequest( - Signature("varargPrimitive", 2, true), - listOf(Truth.TRUE, Truth.TRUE, Truth.TRUE) - ) + private val varargPrimitiveRequest = + createSolveRequest( + Signature("varargPrimitive", 2, true), + listOf(Truth.TRUE, Truth.TRUE, Truth.TRUE), + ) /** Solve request with well-formed goal */ - private val wellFormedGoalRequest = createSolveRequest( - Signature(";", 2), - listOf(Truth.TRUE, Truth.FAIL) - ) + private val wellFormedGoalRequest = + createSolveRequest( + Signature(";", 2), + listOf(Truth.TRUE, Truth.FAIL), + ) /** Solve request with a goal that needs preparation for execution */ - private val preparationNeededGoalRequest = createSolveRequest( - Signature(",", 2), - listOf(Var.of("A"), Var.of("B")) - ) + private val preparationNeededGoalRequest = + createSolveRequest( + Signature(",", 2), + listOf(Var.of("A"), Var.of("B")), + ) /** Well formed goals needing preparation for execution */ internal val wellFormedGoalRequestsNeedingPreparationForExecution by lazy { @@ -55,7 +59,7 @@ internal object StateInitUtils { listOf( failRequest, varargPrimitiveRequest, - wellFormedGoalRequest + wellFormedGoalRequest, ) } @@ -66,10 +70,11 @@ internal object StateInitUtils { } /** Solve request with non well-formed goal */ - internal val nonWellFormedGoalRequest = createSolveRequest( - Signature(",", 2), - listOf(Truth.TRUE, Integer.of(2)) - ) + internal val nonWellFormedGoalRequest = + createSolveRequest( + Signature(",", 2), + listOf(Truth.TRUE, Integer.of(2)), + ) /** All [StateInit] testing requests */ internal val allRequests by lazy { allWellFormedGoalRequests + nonWellFormedGoalRequest } diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/testutils/StateRuleSelectionUtils.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/testutils/StateRuleSelectionUtils.kt index 8443dacfd..89e65fd1c 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/testutils/StateRuleSelectionUtils.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/testutils/StateRuleSelectionUtils.kt @@ -13,18 +13,20 @@ import it.unibo.tuprolog.theory.Theory * @author Enrico */ internal object StateRuleSelectionUtils { - private val emptyUnifier = Substitution.empty() /** Utility function to create a Solve.Request of given query against given rule database */ - internal fun createRequest(query: Struct, ruleDatabase: Theory) = createSolveRequest(query, ruleDatabase) + internal fun createRequest( + query: Struct, + ruleDatabase: Theory, + ) = createSolveRequest(query, ruleDatabase) /** Test data in the form (query Struct, a database with no query matches) */ internal val queryToNoMatchesTheoryMap by lazy { logicProgramming { mapOf( atomOf("a") to theoryOf(), - atomOf("a") to theory({ "b" }) + atomOf("a") to theory({ "b" }), ) } } @@ -40,10 +42,10 @@ internal object StateRuleSelectionUtils { "f"("Var"), theory( { "f"("a") }, - { "f"("a", "b") } + { "f"("a", "b") }, ), - "Var" to "a" - ) + "Var" to "a", + ), ) } } @@ -58,10 +60,10 @@ internal object StateRuleSelectionUtils { "f"("Var"), theory( { "f"("Var") impliedBy "g"("Var") }, - { "g"("a") } + { "g"("a") }, ), - "Var" to "a" - ) + "Var" to "a", + ), ) } } @@ -74,29 +76,29 @@ internal object StateRuleSelectionUtils { atomOf("a"), theory( { "a" }, - { "a" impliedBy "b" } + { "a" impliedBy "b" }, ), - ktListOf(emptyUnifier, Substitution.failed()) + ktListOf(emptyUnifier, Substitution.failed()), ), Triple( atomOf("a"), theory( { "a" impliedBy "b" }, - { "a" } + { "a" }, ), - ktListOf(emptyUnifier) + ktListOf(emptyUnifier), ), Triple( "f"("Var"), theory( { "f"("Var") impliedBy "g"("Var") }, { "g"("a") }, - { "g"("b") } + { "g"("b") }, ), ktListOf( "Var" to "a", - "Var" to "b" - ) + "Var" to "b", + ), ), Triple( structOf("f", varOf("V")), @@ -106,15 +108,15 @@ internal object StateRuleSelectionUtils { { "g"("c1") }, { "g"("c2") }, { "h"("d1") }, - { "h"("d2") } + { "h"("d2") }, ), ktListOf( "V" to "c1", "V" to "c2", "V" to "d1", - "V" to "d2" - ) - ) + "V" to "d2", + ), + ), ) } } diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/testutils/StateUtils.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/testutils/StateUtils.kt index 660399c2d..0bae62c7d 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/testutils/StateUtils.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/impl/testutils/StateUtils.kt @@ -17,19 +17,21 @@ import kotlin.test.fail * @author Enrico */ internal object StateUtils { - /** Utility function to assert that there's only one next state of given type */ internal inline fun assertOnlyOneNextState(actualNextStateSequence: Sequence) { assertEquals( 1, actualNextStateSequence.count(), - "Expected only one state, but ${actualNextStateSequence.toList()}" + "Expected only one state, but ${actualNextStateSequence.toList()}", ) assertTrue { actualNextStateSequence.single() is S } } /** Utility function to assert over a State instance after casting it to expected type */ - internal inline fun assertOverState(state: State, assertion: (S) -> Unit) { + internal inline fun assertOverState( + state: State, + assertion: (S) -> Unit, + ) { assertTrue("Expected state type to be ${S::class} but was ${state::class}") { state is S } assertion(state as S) } @@ -38,18 +40,22 @@ internal object StateUtils { internal inline fun assertOverFilteredStateInstances( states: Sequence, noinline filteringPredicate: (state: S) -> Boolean = { true }, - assertion: (index: Int, state: S) -> Unit + assertion: (index: Int, state: S) -> Unit, ) = states.filterIsInstance().filter(filteringPredicate).forEachIndexed(assertion) /** Utility function to assert that receiver solution contains expected query and substitution */ - internal fun Solution.assertCorrectQueryAndSubstitution(query: Struct, substitution: Substitution) { + internal fun Solution.assertCorrectQueryAndSubstitution( + query: Struct, + substitution: Substitution, + ) { assertEquals(query, this.query) assertEquals(substitution, this.substitution) } /** Utility function to extract the SideEffectsManager from a [Solve] either Request or Response */ - internal fun Solve.getSideEffectsManager(): SideEffectManager = when (this) { - is Solve.Response -> sideEffectManager - is Solve.Request<*> -> context.getSideEffectManager() - } ?: fail("SideEffectManager is not present in $this") + internal fun Solve.getSideEffectsManager(): SideEffectManager = + when (this) { + is Solve.Response -> sideEffectManager + is Solve.Request<*> -> context.getSideEffectManager() + } ?: fail("SideEffectManager is not present in $this") } diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/testutils/StateMachineExecutorUtils.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/testutils/StateMachineExecutorUtils.kt index d41c2c36c..9d79b1aeb 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/testutils/StateMachineExecutorUtils.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/solver/fsm/testutils/StateMachineExecutorUtils.kt @@ -13,15 +13,20 @@ import kotlin.test.fail * @author Enrico */ internal object StateMachineExecutorUtils { - /** A dummy state that has not already behaved and whose behaviour returns an emptySequence, making execution stop */ - private val defaultDummyEndState = object : State { - override val solve: Solve by lazy { throw NotImplementedError() } - override fun behave(): Sequence = emptySequence() - override val hasBehaved: Boolean = false - override val context: StreamsExecutionContext by lazy { throw NotImplementedError() } - override fun toString(): String = this::class.className() - } + private val defaultDummyEndState = + object : State { + override val solve: Solve by lazy { throw NotImplementedError() } + + override fun behave(): Sequence = emptySequence() + + override val hasBehaved: Boolean = false + override val context: StreamsExecutionContext by lazy { + throw NotImplementedError() + } + + override fun toString(): String = this::class.className() + } /** A state behaving as an end state, it returns an emptySequence behaving, and this should make computation stop */ internal val endState = defaultDummyEndState @@ -31,15 +36,19 @@ internal object StateMachineExecutorUtils { * * `state->state->state->...->otherState` */ - internal fun oneStateAtATimeState(nextCountToProceed: Int, otherState: State): State = + internal fun oneStateAtATimeState( + nextCountToProceed: Int, + otherState: State, + ): State = object : State by defaultDummyEndState { - override fun behave(): Sequence = sequence { - if (nextCountToProceed > 0) { - yield(oneStateAtATimeState(nextCountToProceed - 1, otherState)) - } else { - yield(otherState) + override fun behave(): Sequence = + sequence { + if (nextCountToProceed > 0) { + yield(oneStateAtATimeState(nextCountToProceed - 1, otherState)) + } else { + yield(otherState) + } } - } override fun toString(): String = "${this::class.className()} nextCountToProceed:$nextCountToProceed" } @@ -54,11 +63,15 @@ internal object StateMachineExecutorUtils { * > nextState * ``` */ - internal fun allNextStatesFromThis(nextCount: Int, nextState: State): State = + internal fun allNextStatesFromThis( + nextCount: Int, + nextState: State, + ): State = object : State by defaultDummyEndState { - override fun behave(): Sequence = sequence { - repeat(nextCount) { yield(nextState) } - } + override fun behave(): Sequence = + sequence { + repeat(nextCount) { yield(nextState) } + } override fun toString(): String = "${this::class.className()} nextCount:$nextCount" } @@ -66,10 +79,12 @@ internal object StateMachineExecutorUtils { /** Returns the same state but with [State.hasBehaved] set true, and before behave execution it launches [onBehaveAction] hook */ internal fun toBehavedState( state: State, - onBehaveAction: () -> Unit = { fail("Behave method should not be called for `hasBehaved = true` states") } + onBehaveAction: () -> Unit = { fail("Behave method should not be called for `hasBehaved = true` states") }, ) = object : State by state { override val hasBehaved: Boolean = true + override fun behave(): Sequence = onBehaveAction().run { state.behave() } + override fun toString(): String = "${this::class.className()} originalState: $state" } @@ -88,28 +103,30 @@ internal object StateMachineExecutorUtils { 2, allNextStatesFromThis( 2, - allNextStatesFromThis(2, endState) - ) + allNextStatesFromThis(2, endState), + ), ) /** A [threeShotState] that won't produce any state because already executed */ internal val threeShotStateAlreadyExecuted = toBehavedState(threeShotState) /** A `fiveShotState` that has the third state that has already executed */ - internal val thirdStateHasAlreadyBehaved = oneStateAtATimeState( - 2, - toBehavedState(oneStateAtATimeState(2, endState)) - ) + internal val thirdStateHasAlreadyBehaved = + oneStateAtATimeState( + 2, + toBehavedState(oneStateAtATimeState(2, endState)), + ) /** All state machines that are finite */ - internal val allFiniteStateMachines = listOf( - oneShotState, - threeShotState, - twoAlternativeState, - eightLeafSearchTreeState, - threeShotStateAlreadyExecuted, - thirdStateHasAlreadyBehaved - ) + internal val allFiniteStateMachines = + listOf( + oneShotState, + threeShotState, + twoAlternativeState, + eightLeafSearchTreeState, + threeShotStateAlreadyExecuted, + thirdStateHasAlreadyBehaved, + ) /** Utility function to print meaningful names in object toString */ private fun KClass<*>.className() = this.toString().substringAfter("$").substringBefore("(").trim() diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAnd.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAnd.kt index f97293df4..3bfbfe3f1 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAnd.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAnd.kt @@ -7,7 +7,6 @@ import kotlin.test.Ignore import kotlin.test.Test class TestStreamsAnd : TestAnd, SolverFactory by StreamsSolverFactory { - private val prototype = TestAnd.prototype(this) @Test diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsArg.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsArg.kt index 025649ff4..fa7d15353 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsArg.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsArg.kt @@ -7,7 +7,6 @@ import kotlin.test.Ignore import kotlin.test.Test class TestStreamsArg : TestArg, SolverFactory by StreamsSolverFactory { - private val prototype = TestArg.prototype(this) @Test diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAssertA.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAssertA.kt index fc7fedfe3..4b5596240 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAssertA.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAssertA.kt @@ -7,7 +7,6 @@ import kotlin.test.Ignore import kotlin.test.Test class TestStreamsAssertA : TestAssertA, SolverFactory by StreamsSolverFactory { - private val prototype = TestAssertA.prototype(this) @Test diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAssertZ.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAssertZ.kt index a5f362dfd..ac8104fb2 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAssertZ.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAssertZ.kt @@ -7,7 +7,6 @@ import kotlin.test.Ignore import kotlin.test.Test class TestStreamsAssertZ : TestAssertZ, SolverFactory by StreamsSolverFactory { - private val prototype = TestAssertZ.prototype(this) @Test diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAtom.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAtom.kt index d7d9c749d..ee259b4f1 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAtom.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAtom.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.streams.StreamsSolverFactory import kotlin.test.Test class TestStreamsAtom : TestAtom, SolverFactory by StreamsSolverFactory { - private val prototype = TestAtom.prototype(this) @Test diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAtomConcat.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAtomConcat.kt index 56e771437..e939277b2 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAtomConcat.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAtomConcat.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.streams.StreamsSolverFactory import kotlin.test.Test class TestStreamsAtomConcat : TestAtomConcat, SolverFactory by StreamsSolverFactory { - private val prototype = TestAtomConcat.prototype(this) @Test diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAtomic.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAtomic.kt index afb82bc35..6944dcb0c 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAtomic.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsAtomic.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.streams.StreamsSolverFactory import kotlin.test.Test class TestStreamsAtomic : TestAtomic, SolverFactory by StreamsSolverFactory { - private val prototype = TestAtomic.prototype(this) @Test diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsCustomData.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsCustomData.kt index d39029554..919a348d3 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsCustomData.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsCustomData.kt @@ -8,7 +8,6 @@ import kotlin.test.Test @Ignore class TestStreamsCustomData : TestCustomData, SolverFactory by StreamsSolverFactory { - val prototype = TestCustomData.prototype(this) @Test diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsCut.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsCut.kt index 7ca121e46..9b8ca4e3b 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsCut.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsCut.kt @@ -7,7 +7,6 @@ import kotlin.test.Ignore import kotlin.test.Test class TestStreamsCut : TestCut, SolverFactory by StreamsSolverFactory { - private val prototype = TestCut.prototype(this) @Test diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsDirectives.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsDirectives.kt index 065dc5680..dd3c72fd0 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsDirectives.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsDirectives.kt @@ -8,7 +8,6 @@ import kotlin.test.Test @Ignore class TestStreamsDirectives : TestDirectives, SolverFactory by StreamsSolverFactory { - private val prototype = TestDirectives.prototype(this) @Test diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsFindAll.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsFindAll.kt index 56f3616ce..dc8537ad4 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsFindAll.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsFindAll.kt @@ -8,7 +8,6 @@ import kotlin.test.Ignore import kotlin.test.Test class TestStreamsFindAll : TestFindAll, SolverFactory by StreamsSolverFactory { - private val prototype = TestFindAll.prototype(this) override val errorSignature: Signature diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsFlags.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsFlags.kt index 2541f797c..daa57257c 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsFlags.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsFlags.kt @@ -7,7 +7,6 @@ import kotlin.test.Ignore import kotlin.test.Test class TestStreamsFlags : TestFlags, SolverFactory by StreamsSolverFactory { - private val prototype = TestFlags.prototype(this) @Test diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsInteger.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsInteger.kt index 287803ce2..17562ac98 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsInteger.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsInteger.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.streams.StreamsSolverFactory import kotlin.test.Test class TestStreamsInteger : TestInteger, SolverFactory by StreamsSolverFactory { - private val prototype = TestInteger.prototype(this) @Test diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsNonVar.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsNonVar.kt index 5c807667e..1dc609d9a 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsNonVar.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsNonVar.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.streams.StreamsSolverFactory import kotlin.test.Test class TestStreamsNonVar : TestNonVar, SolverFactory by StreamsSolverFactory { - private val prototype = TestNonVar.prototype(this) @Test diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsNotUnify.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsNotUnify.kt index 869419390..922fca4e9 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsNotUnify.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsNotUnify.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.streams.StreamsSolverFactory import kotlin.test.Test class TestStreamsNotUnify : TestNotUnify, SolverFactory by StreamsSolverFactory { - private val prototype = TestNotUnify.prototype(this) @Test diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsNumber.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsNumber.kt index 870f2c251..6495f1537 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsNumber.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsNumber.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.streams.StreamsSolverFactory import kotlin.test.Test class TestStreamsNumber : TestNumber, SolverFactory by StreamsSolverFactory { - private val prototype = TestNumber.prototype(this) @Test diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsOr.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsOr.kt index d603617a6..59c712717 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsOr.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsOr.kt @@ -7,7 +7,6 @@ import kotlin.test.Ignore import kotlin.test.Test class TestStreamsOr : TestOr, SolverFactory by StreamsSolverFactory { - private val prototype = TestOr.prototype(this) @Test diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsSetOf.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsSetOf.kt index 0976252a7..a1ea6d4ea 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsSetOf.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsSetOf.kt @@ -20,8 +20,8 @@ class TestStreamsSetOf : TestSetOf, SolverFactory by StreamsSolverFactory { } @Test - override fun testSetOfNoSorted() { - prototype.testSetOfNoSorted() + override fun testSetOfSorted() { + prototype.testSetOfSorted() } @Test diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsSolutionPresentation.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsSolutionPresentation.kt index 3ed62a238..777753bf7 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsSolutionPresentation.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsSolutionPresentation.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.streams.StreamsSolverFactory import kotlin.test.Test class TestStreamsSolutionPresentation : TestSolutionPresentation, SolverFactory by StreamsSolverFactory { - val prototype = TestSolutionPresentation.prototype(this) @Test diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsSolver.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsSolver.kt index f03aab4c6..5eaa0f084 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsSolver.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsSolver.kt @@ -8,7 +8,6 @@ import kotlin.test.Ignore import kotlin.test.Test class TestStreamsSolver : TestSolver, SolverFactory by StreamsSolverFactory { - private val prototype = TestSolver.prototype(this) override val callErrorSignature: Signature diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsTerm.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsTerm.kt index d42a82a6f..80a876ba6 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsTerm.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsTerm.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.streams.StreamsSolverFactory import kotlin.test.Test class TestStreamsTerm : TestTerm, SolverFactory by StreamsSolverFactory { - private val prototype = TestTerm.prototype(this) @Test diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsUnify.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsUnify.kt index 6381007e2..aa854983d 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsUnify.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/systemtest/TestStreamsUnify.kt @@ -7,7 +7,6 @@ import kotlin.test.Ignore import kotlin.test.Test class TestStreamsUnify : TestUnify, SolverFactory by StreamsSolverFactory { - private val prototype = TestUnify.prototype(this) @Test diff --git a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/testutils/SolverTestUtils.kt b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/testutils/SolverTestUtils.kt index 50c176f92..5d3833ca1 100644 --- a/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/testutils/SolverTestUtils.kt +++ b/solve-streams/src/commonTest/kotlin/it/unibo/tuprolog/solve/streams/testutils/SolverTestUtils.kt @@ -17,23 +17,23 @@ import it.unibo.tuprolog.solve.streams.solver.StreamsExecutionContext * @author Enrico */ internal object SolverTestUtils { - /** Creates a Solve.Request with provided goal, against provided database as library theory, loading given primitives */ internal fun createSolveRequest( query: Struct, database: Iterable = emptyList(), - primitives: Map = mapOf() + primitives: Map = mapOf(), ) = Solve.Request( query.extractSignature(), query.args, StreamsExecutionContext( - libraries = Runtime.of( - Library.of( - alias = "solve.solver.test", - primitives = primitives, - clauses = database - ) - ) - ) + libraries = + Runtime.of( + Library.of( + alias = "solve.solver.test", + primitives = primitives, + clauses = database, + ), + ), + ), ) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/AbstractWrapper.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/AbstractWrapper.kt index 62c7221fc..2ee476a5f 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/AbstractWrapper.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/AbstractWrapper.kt @@ -9,8 +9,9 @@ import kotlin.js.JsName * * @author Enrico */ -abstract class AbstractWrapper(@JsName("signature") val signature: Signature) { - +abstract class AbstractWrapper( + @JsName("signature") val signature: Signature, +) { constructor(name: String, arity: Int, vararg: Boolean = false) : this(Signature(name, arity, vararg)) /** The wrapped implementation */ diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/ExecutionContext.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/ExecutionContext.kt index 8bba7100a..02fe171a7 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/ExecutionContext.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/ExecutionContext.kt @@ -14,9 +14,7 @@ import it.unibo.tuprolog.unify.Unificator import kotlin.js.JsName /** An interface representing the Solver execution context, containing important information that determines its behaviour */ -// TODO: 25/09/2019 solverStrategies should go here... in common with other implementations, if the idea is approved interface ExecutionContext : ExecutionContextAware, Durable { - /** The current procedure being executed */ @JsName("procedure") val procedure: Struct? @@ -40,7 +38,7 @@ interface ExecutionContext : ExecutionContextAware, Durable { staticKb: Theory = this.staticKb, dynamicKb: Theory = this.dynamicKb, inputChannels: InputStore = this.inputChannels, - outputChannels: OutputStore = this.outputChannels + outputChannels: OutputStore = this.outputChannels, ): Solver @JsName("createMutableSolver") @@ -51,7 +49,7 @@ interface ExecutionContext : ExecutionContextAware, Durable { staticKb: Theory = this.staticKb, dynamicKb: Theory = this.dynamicKb, inputChannels: InputStore = this.inputChannels, - outputChannels: OutputStore = this.outputChannels + outputChannels: OutputStore = this.outputChannels, ): MutableSolver @JsName("apply") @@ -81,6 +79,6 @@ interface ExecutionContext : ExecutionContextAware, Durable { operators: OperatorSet = this.operators, inputChannels: InputStore = this.inputChannels, outputChannels: OutputStore = this.outputChannels, - customData: CustomDataStore = this.customData + customData: CustomDataStore = this.customData, ): ExecutionContext } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/ExecutionContextAware.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/ExecutionContextAware.kt index aac8e0889..a90d2f420 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/ExecutionContextAware.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/ExecutionContextAware.kt @@ -14,7 +14,6 @@ import kotlin.js.JsName /** Base type for all entities which must be aware of the current state of a solver */ interface ExecutionContextAware { - @JsName("unificator") val unificator: Unificator diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Extensions.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Extensions.kt index a9801c1ce..c7787a71d 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Extensions.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Extensions.kt @@ -9,11 +9,10 @@ import kotlin.jvm.JvmName /** Extracts this [Struct] indicator and converts it to [Signature] */ @JsName("extractSignature") -fun Struct.extractSignature(): Signature = - Signature.fromIndicator(indicator)!! +fun Struct.extractSignature(): Signature = Signature.fromIndicator(indicator)!! @JsName("solve") fun Solver.solve( maxDuration: TimeDuration = TimeDuration.MAX_VALUE, - scopedContext: Scope.() -> Struct + scopedContext: Scope.() -> Struct, ): Sequence = solve(scopedContext(Scope.empty()), maxDuration) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/MutableSolver.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/MutableSolver.kt index 191af0534..c8126fb78 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/MutableSolver.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/MutableSolver.kt @@ -21,7 +21,6 @@ import kotlin.js.JsName * of the solver -- e.g. affecting the KB -- while no resolution process is ongoing. */ interface MutableSolver : Solver { - @JsName("loadLibrary") fun loadLibrary(library: Library) @@ -35,16 +34,13 @@ interface MutableSolver : Solver { fun loadStaticKb(theory: Theory) @JsName("loadStaticClauses") - fun loadStaticClauses(vararg clauses: Clause) = - loadStaticKb(Theory.indexedOf(unificator, *clauses)) + fun loadStaticClauses(vararg clauses: Clause) = loadStaticKb(Theory.indexedOf(unificator, *clauses)) @JsName("loadStaticClausesIterable") - fun loadStaticClauses(clauses: Iterable) = - loadStaticKb(Theory.indexedOf(unificator, clauses)) + fun loadStaticClauses(clauses: Iterable) = loadStaticKb(Theory.indexedOf(unificator, clauses)) @JsName("loadStaticClausesSequence") - fun loadStaticClauses(clauses: Sequence) = - loadStaticKb(Theory.indexedOf(unificator, clauses)) + fun loadStaticClauses(clauses: Sequence) = loadStaticKb(Theory.indexedOf(unificator, clauses)) @JsName("appendStaticKb") fun appendStaticKb(theory: Theory) @@ -56,16 +52,13 @@ interface MutableSolver : Solver { fun loadDynamicKb(theory: Theory) @JsName("loadDynamicClauses") - fun loadDynamicClauses(vararg clauses: Clause) = - loadDynamicKb(Theory.indexedOf(unificator, *clauses)) + fun loadDynamicClauses(vararg clauses: Clause) = loadDynamicKb(Theory.indexedOf(unificator, *clauses)) @JsName("loadDynamicClausesIterable") - fun loadDynamicClauses(clauses: Iterable) = - loadDynamicKb(Theory.indexedOf(unificator, clauses)) + fun loadDynamicClauses(clauses: Iterable) = loadDynamicKb(Theory.indexedOf(unificator, clauses)) @JsName("loadDynamicClausesSequence") - fun loadDynamicClauses(clauses: Sequence) = - loadDynamicKb(Theory.indexedOf(unificator, clauses)) + fun loadDynamicClauses(clauses: Sequence) = loadDynamicKb(Theory.indexedOf(unificator, clauses)) @JsName("appendDynamicKb") fun appendDynamicKb(theory: Theory) @@ -98,7 +91,10 @@ interface MutableSolver : Solver { fun retractAll(fact: Struct): RetractResult @JsName("setFlag") - fun setFlag(name: String, value: Term) + fun setFlag( + name: String, + value: Term, + ) @JsName("setFlagPair") fun setFlag(flag: Pair) @@ -127,7 +123,7 @@ interface MutableSolver : Solver { stdIn: InputChannel, stdOut: OutputChannel, stdErr: OutputChannel, - warnings: OutputChannel + warnings: OutputChannel, ): MutableSolver override fun clone(): MutableSolver diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Signature.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Signature.kt index 2d2ffbabd..59356651c 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Signature.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Signature.kt @@ -15,9 +15,8 @@ data class Signature( @JsName("arity") val arity: Int, @JsName("vararg") - val vararg: Boolean = false + val vararg: Boolean = false, ) : TermConvertible { - init { require(arity >= 0) { "Signature arity should be greater than or equals to 0: $arity" } } @@ -30,10 +29,10 @@ data class Signature( FUNCTOR, Atom.of(name), Struct.of( - varargStructFunctor, + VARARG_FUNCTOR, Integer.of(arity), - varargAtom - ) + varargAtom, + ), ) } else -> { @@ -51,14 +50,17 @@ data class Signature( /** Creates corresponding Struct of this Signature with provided arguments */ @JsName("withArgs") - infix fun withArgs(arguments: Iterable): Struct = when { - vararg -> require(arguments.count() >= this.arity) { - "Trying to create Struct of signature `$this` with not enough arguments ${arguments.toList()}" - } - else -> require(arguments.count() == this.arity) { - "Trying to create Struct of signature `$this` with wrong number of arguments ${arguments.toList()}" - } - }.let { Struct.of(name, arguments.asSequence()) } + infix fun withArgs(arguments: Iterable): Struct = + when { + vararg -> + require(arguments.count() >= this.arity) { + "Trying to create Struct of signature `$this` with not enough arguments ${arguments.toList()}" + } + else -> + require(arguments.count() == this.arity) { + "Trying to create Struct of signature `$this` with wrong number of arguments ${arguments.toList()}" + } + }.let { Struct.of(name, arguments.asSequence()) } // TODO: 24/09/2019 maybe, to fully support vararg signatures, a method to check if a non vararg signature can be treated as another vararg one, should be added // for example: if user query is `ciao(1, 2)` with Signature("ciao", 2, false), it should be matched with @@ -72,63 +74,67 @@ data class Signature( // this method should use "includedBy(Signature)" to retrieve matches and the sort them with the rule above companion object { - /** An atom to denote vararg presence */ private val varargAtom = Atom.of("vararg") - private const val varargStructFunctor = "+" + private const val VARARG_FUNCTOR = "+" /** The functor of a Signature struct */ const val FUNCTOR = Indicator.FUNCTOR /** Creates a Signature instance from a well-formed Signature Struct, or returns `null` if it cannot be interpreted as Signature */ @JsName("fromSignatureStruct") - fun fromSignatureTerm(term: Struct): Signature? = try { - with(term) { - when { - functor == FUNCTOR && arity == 2 && args.first().isAtom -> when { - args.last().isInteger -> { - Signature( - args.first().castToAtom().value, - args.last().castToInteger().intValue.toInt() - ) - } - args.last().let { - it is Struct && it.functor == varargStructFunctor && it.arity == 2 && - it.args.first().isInteger && - it.args.last() == varargAtom - } -> { - Signature( - args.first().castToAtom().value, - args.last().castToStruct()[0].castToInteger().intValue.toInt(), - true - ) - } + fun fromSignatureTerm(term: Struct): Signature? = + try { + with(term) { + when { + functor == FUNCTOR && arity == 2 && args.first().isAtom -> + when { + args.last().isInteger -> { + Signature( + args.first().castToAtom().value, + args.last().castToInteger().intValue.toInt(), + ) + } + args.last().let { + it is Struct && it.functor == VARARG_FUNCTOR && it.arity == 2 && + it.args.first().isInteger && + it.args.last() == varargAtom + } -> { + Signature( + args.first().castToAtom().value, + args.last().castToStruct()[0].castToInteger().intValue.toInt(), + true, + ) + } + else -> null + } else -> null } - else -> null } + } catch (ex: IllegalArgumentException) { + // caught when parsed arity is negative + null } - } catch (ex: IllegalArgumentException) { // caught when parsed arity is negative - null - } /** Creates a Signature instance from a well-formed Signature Term, or returns `null` if it cannot be interpreted as Signature */ @JsName("fromSignatureTerm") - fun fromSignatureTerm(term: Term): Signature? = when (term) { - is Struct -> fromSignatureTerm(term) - else -> null - } + fun fromSignatureTerm(term: Term): Signature? = + when (term) { + is Struct -> fromSignatureTerm(term) + else -> null + } /** Creates a Signature instance from a well-formed Indicator, or returns `null` if it wasn't */ @JsName("fromIndicator") - fun fromIndicator(indicator: Indicator): Signature? = when { - indicator.isWellFormed -> { - Signature( - indicator.indicatedName!!, - indicator.indicatedArity!! - ) + fun fromIndicator(indicator: Indicator): Signature? = + when { + indicator.isWellFormed -> { + Signature( + indicator.indicatedName!!, + indicator.indicatedArity!!, + ) + } + else -> null } - else -> null - } } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Solution.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Solution.kt index 44010c337..d7b7fff7f 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Solution.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Solution.kt @@ -12,7 +12,6 @@ import kotlin.jvm.JvmStatic /** A type representing a solution to a goal */ sealed interface Solution : Taggable, Castable { - /** The query to which the solution refers */ @JsName("query") val query: Struct @@ -87,7 +86,7 @@ sealed interface Solution : Taggable, Castable { yes: ((Yes) -> T)? = null, no: ((No) -> T)? = null, halt: ((Halt) -> T)? = null, - otherwise: ((Solution) -> T) = { throw IllegalStateException("Cannot handle solution $it") } + otherwise: ((Solution) -> T) = { throw IllegalStateException("Cannot handle solution $it") }, ): T @JsName("cleanUp") @@ -108,7 +107,10 @@ sealed interface Solution : Taggable, Castable { override fun replaceTags(tags: Map): Yes @JsName("copy") - fun copy(query: Struct = this.query, substitution: Substitution.Unifier = this.substitution): Yes + fun copy( + query: Struct = this.query, + substitution: Substitution.Unifier = this.substitution, + ): Yes override fun cleanUp(): Yes @@ -138,7 +140,10 @@ sealed interface Solution : Taggable, Castable { override fun replaceTags(tags: Map): Halt @JsName("copy") - fun copy(query: Struct = this.query, exception: ResolutionException = this.exception): Halt + fun copy( + query: Struct = this.query, + exception: ResolutionException = this.exception, + ): Halt override fun cleanUp(): Halt @@ -148,15 +153,17 @@ sealed interface Solution : Taggable, Castable { companion object { @JvmStatic @JsName("yes") - fun yes(query: Struct, substitution: Substitution.Unifier = Substitution.empty()): Yes = - SolutionImpl.YesImpl(query, substitution) + fun yes( + query: Struct, + substitution: Substitution.Unifier = Substitution.empty(), + ): Yes = SolutionImpl.YesImpl(query, substitution) @JvmStatic @JsName("yesBySignature") fun yes( signature: Signature, arguments: List, - substitution: Substitution.Unifier = Substitution.empty() + substitution: Substitution.Unifier = Substitution.empty(), ): Yes = SolutionImpl.YesImpl(signature, arguments, substitution) @JvmStatic @@ -165,18 +172,24 @@ sealed interface Solution : Taggable, Castable { @JvmStatic @JsName("noBySignature") - fun no(signature: Signature, arguments: List): No = SolutionImpl.NoImpl(signature, arguments) + fun no( + signature: Signature, + arguments: List, + ): No = SolutionImpl.NoImpl(signature, arguments) @JvmStatic @JsName("halt") - fun halt(query: Struct, exception: ResolutionException): Halt = SolutionImpl.HaltImpl(query, exception) + fun halt( + query: Struct, + exception: ResolutionException, + ): Halt = SolutionImpl.HaltImpl(query, exception) @JvmStatic @JsName("haltBySignature") fun halt( signature: Signature, arguments: List, - exception: ResolutionException + exception: ResolutionException, ): Halt = SolutionImpl.HaltImpl(signature, arguments, exception) } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolutionImpl.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolutionImpl.kt index 874776f0e..c6c6b6d79 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolutionImpl.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolutionImpl.kt @@ -10,9 +10,8 @@ import kotlin.jvm.JvmStatic /** A class representing a solution to a goal */ internal sealed class SolutionImpl( override val query: Struct, - override val tags: Map + override val tags: Map, ) : Solution { - override val isYes: Boolean get() = false @@ -29,7 +28,7 @@ internal sealed class SolutionImpl( yes: ((Solution.Yes) -> T)?, no: ((Solution.No) -> T)?, halt: ((Solution.Halt) -> T)?, - otherwise: ((Solution) -> T) + otherwise: ((Solution) -> T), ): T { if (this is Solution.Yes && yes != null) { return yes(this) @@ -61,25 +60,22 @@ internal sealed class SolutionImpl( return result } - override fun valueOf(variable: Var): Term? = - (substitution as? Substitution.Unifier)?.get(variable) + override fun valueOf(variable: Var): Term? = (substitution as? Substitution.Unifier)?.get(variable) - override fun valueOf(variable: String): Term? = - (substitution as? Substitution.Unifier)?.getByName(variable) + override fun valueOf(variable: String): Term? = (substitution as? Substitution.Unifier)?.getByName(variable) /** A class representing the successful solution */ class YesImpl( query: Struct, /** The successful substitution applied finding the solution */ override val substitution: Substitution.Unifier = Substitution.empty(), - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : SolutionImpl(query, tags), Solution.Yes { - constructor( signature: Signature, arguments: List, substitution: Substitution.Unifier = Substitution.empty(), - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : this(signature withArgs arguments, substitution, tags) { // a solution always refers to a fully instantiated Struct, that cannot have a vararg Signature noVarargSignatureCheck(signature) @@ -89,12 +85,23 @@ internal sealed class SolutionImpl( override val solvedQuery: Struct by lazy { substitution.applyTo(query) as Struct } override fun replaceTags(tags: Map): YesImpl = - if (tags === this.tags) this else YesImpl(query, substitution, tags) + if (tags === this.tags) { + this + } else { + YesImpl( + query, + substitution, + tags, + ) + } override val isYes: Boolean get() = true - override fun copy(query: Struct, substitution: Substitution.Unifier) = YesImpl(query, substitution, tags) + override fun copy( + query: Struct, + substitution: Substitution.Unifier, + ) = YesImpl(query, substitution, tags) override fun toString(): String = "Yes(query=$query, substitution=$substitution)" @@ -109,13 +116,12 @@ internal sealed class SolutionImpl( /** A class representing a failed solution */ class NoImpl( query: Struct, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : SolutionImpl(query, tags), Solution.No { - constructor( signature: Signature, arguments: List, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : this(signature withArgs arguments, tags) { noVarargSignatureCheck(signature) } @@ -126,8 +132,7 @@ internal sealed class SolutionImpl( override val solvedQuery: Nothing? get() = null - override fun replaceTags(tags: Map): NoImpl = - if (tags === this.tags) this else NoImpl(query, tags) + override fun replaceTags(tags: Map): NoImpl = if (tags === this.tags) this else NoImpl(query, tags) override val isNo: Boolean get() = true @@ -144,20 +149,27 @@ internal sealed class SolutionImpl( query: Struct, /** The exception that made the resolution to halt */ override val exception: ResolutionException, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : SolutionImpl(query, tags), Solution.Halt { - constructor( signature: Signature, arguments: List, exception: ResolutionException, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : this(signature withArgs arguments, exception, tags) { noVarargSignatureCheck(signature) } override fun replaceTags(tags: Map): HaltImpl = - if (tags === this.tags) this else HaltImpl(query, exception, tags) + if (tags === this.tags) { + this + } else { + HaltImpl( + query, + exception, + tags, + ) + } override fun equals(other: Any?): Boolean { if (!super.equals(other)) return false @@ -184,7 +196,10 @@ internal sealed class SolutionImpl( override val isHalt: Boolean get() = true - override fun copy(query: Struct, exception: ResolutionException) = HaltImpl(query, exception, tags) + override fun copy( + query: Struct, + exception: ResolutionException, + ) = HaltImpl(query, exception, tags) override fun toString(): String = "Halt(query=$query, exception=$exception)" diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolveOptions.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolveOptions.kt index 218b65e0a..873437cad 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolveOptions.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolveOptions.kt @@ -38,16 +38,19 @@ interface SolveOptions { fun setOptions(options: Map): SolveOptions @JsName("addOptions") - fun addOptions(options: Map): SolveOptions = - setOptions(customOptions + options) + fun addOptions(options: Map): SolveOptions = setOptions(customOptions + options) @JsName("setOption") - fun setOption(key: String, value: X): SolveOptions = - setOptions(customOptions.toMutableMap().also { it[key] = value }) + fun setOption( + key: String, + value: X, + ): SolveOptions = setOptions(customOptions.toMutableMap().also { it[key] = value }) @JsName("addOption") - fun addOption(key: String, value: X): SolveOptions = - addOptions(mapOf(key to (value as Any))) + fun addOption( + key: String, + value: X, + ): SolveOptions = addOptions(mapOf(key to (value as Any))) companion object { const val MAX_TIMEOUT: Long = Long.MAX_VALUE @@ -64,13 +67,16 @@ interface SolveOptions { timeout: TimeDuration = MAX_TIMEOUT, limit: Int = ALL_SOLUTIONS, customOption: Pair, - vararg customOptions: Pair + vararg customOptions: Pair, ): SolveOptions = SolveOptionsImpl(lazy, timeout, limit, arrayOf(customOption, *customOptions).toMap()) @JsName("of") @JvmStatic - fun of(lazy: Boolean, timeout: TimeDuration = MAX_TIMEOUT, limit: Int = ALL_SOLUTIONS): SolveOptions = - SolveOptionsImpl(lazy, timeout, limit) + fun of( + lazy: Boolean, + timeout: TimeDuration = MAX_TIMEOUT, + limit: Int = ALL_SOLUTIONS, + ): SolveOptions = SolveOptionsImpl(lazy, timeout, limit) @JsName("allLazily") @JvmStatic @@ -86,8 +92,10 @@ interface SolveOptions { @JsName("someLazilyWithTimeout") @JvmStatic - fun someLazilyWithTimeout(limit: Int, timeout: TimeDuration): SolveOptions = - of(true, timeout = timeout, limit = limit) + fun someLazilyWithTimeout( + limit: Int, + timeout: TimeDuration, + ): SolveOptions = of(true, timeout = timeout, limit = limit) @JsName("allEagerly") @JvmStatic @@ -103,7 +111,9 @@ interface SolveOptions { @JsName("someEagerlyWithTimeout") @JvmStatic - fun someEagerlyWithTimeout(limit: Int, timeout: TimeDuration): SolveOptions = - of(false, timeout = timeout, limit = limit) + fun someEagerlyWithTimeout( + limit: Int, + timeout: TimeDuration, + ): SolveOptions = of(false, timeout = timeout, limit = limit) } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Solver.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Solver.kt index aae66f2f5..9997d6bf8 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Solver.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Solver.kt @@ -19,35 +19,50 @@ import kotlin.jvm.JvmStatic * __Solvers are not immutable entities__. Their state may mutate as an effect of solving queries. */ interface Solver : ExecutionContextAware { - @JsName("solveWithTimeout") - fun solve(goal: Struct, timeout: TimeDuration): Sequence = - solve(goal, SolveOptions.allLazilyWithTimeout(timeout)) + fun solve( + goal: Struct, + timeout: TimeDuration, + ): Sequence = solve(goal, SolveOptions.allLazilyWithTimeout(timeout)) @JsName("solve") fun solve(goal: Struct): Sequence = solve(goal, SolveOptions.DEFAULT) @JsName("solveWithOptions") - fun solve(goal: Struct, options: SolveOptions): Sequence + fun solve( + goal: Struct, + options: SolveOptions, + ): Sequence @JsName("solveListWithTimeout") - fun solveList(goal: Struct, timeout: TimeDuration): List = solve(goal, timeout).toList() + fun solveList( + goal: Struct, + timeout: TimeDuration, + ): List = solve(goal, timeout).toList() @JsName("solveList") fun solveList(goal: Struct): List = solve(goal).toList() @JsName("solveListWithOptions") - fun solveList(goal: Struct, options: SolveOptions): List = solve(goal, options).toList() + fun solveList( + goal: Struct, + options: SolveOptions, + ): List = solve(goal, options).toList() @JsName("solveOnceWithTimeout") - fun solveOnce(goal: Struct, timeout: TimeDuration): Solution = - solve(goal, SolveOptions.someLazilyWithTimeout(1, timeout)).first() + fun solveOnce( + goal: Struct, + timeout: TimeDuration, + ): Solution = solve(goal, SolveOptions.someLazilyWithTimeout(1, timeout)).first() @JsName("solveOnce") fun solveOnce(goal: Struct): Solution = solve(goal, SolveOptions.someLazily(1)).first() @JsName("solveOnceWithOptions") - fun solveOnce(goal: Struct, options: SolveOptions): Solution = solve(goal, options.setLimit(1)).first() + fun solveOnce( + goal: Struct, + options: SolveOptions, + ): Solution = solve(goal, options.setLimit(1)).first() @JsName("copy") fun copy( @@ -59,7 +74,7 @@ interface Solver : ExecutionContextAware { stdIn: InputChannel = this.standardInput, stdOut: OutputChannel = this.standardOutput, stdErr: OutputChannel = this.standardError, - warnings: OutputChannel = this.warnings + warnings: OutputChannel = this.warnings, ): Solver @JsName("clone") @@ -71,7 +86,7 @@ interface Solver : ExecutionContextAware { @JsName("classic") @Deprecated( message = "This method is being renamed into \"prolog\" and its usage in this form is now deprecated", - replaceWith = ReplaceWith("Solver.prolog") + replaceWith = ReplaceWith("Solver.prolog"), ) val classic: SolverFactory by lazy { classicSolverFactory() } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolverBuilder.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolverBuilder.kt index 1c35ec322..2b8af3328 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolverBuilder.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolverBuilder.kt @@ -16,7 +16,6 @@ import it.unibo.tuprolog.unify.Unificator import kotlin.js.JsName interface SolverBuilder { - @JsName("toFactory") fun toFactory(): SolverFactory @@ -39,10 +38,17 @@ interface SolverBuilder { fun runtime(runtime: Runtime): SolverBuilder @JsName("setLibrary") - fun library(alias: String?, item1: AbstractWrapper<*>, vararg items: AbstractWrapper<*>): SolverBuilder + fun library( + alias: String?, + item1: AbstractWrapper<*>, + vararg items: AbstractWrapper<*>, + ): SolverBuilder @JsName("setLibraryWithDefaultAlias") - fun library(item1: AbstractWrapper<*>, vararg items: AbstractWrapper<*>): SolverBuilder + fun library( + item1: AbstractWrapper<*>, + vararg items: AbstractWrapper<*>, + ): SolverBuilder @JsName("builtins") var builtins: Library? @@ -60,7 +66,10 @@ interface SolverBuilder { fun flags(flags: FlagStore): SolverBuilder @JsName("setFlag") - fun flag(name: String, value: Term): SolverBuilder + fun flag( + name: String, + value: Term, + ): SolverBuilder @JsName("setFlagByPair") fun flag(flag: Pair): SolverBuilder @@ -69,10 +78,16 @@ interface SolverBuilder { fun flag(flag: NotableFlag): SolverBuilder @JsName("setNotableFlagValue") - fun flag(flag: NotableFlag, value: Term): SolverBuilder + fun flag( + flag: NotableFlag, + value: Term, + ): SolverBuilder @JsName("setNotableFlagByValue") - fun flag(flag: T, value: T.() -> Term): SolverBuilder + fun flag( + flag: T, + value: T.() -> Term, + ): SolverBuilder @JsName("staticKb") var staticKb: Theory @@ -111,7 +126,10 @@ interface SolverBuilder { fun inputs(inputs: InputStore): SolverBuilder @JsName("setInput") - fun input(alias: String, channel: InputChannel): SolverBuilder + fun input( + alias: String, + channel: InputChannel, + ): SolverBuilder @JsName("standardInput") var standardInput: InputChannel @@ -126,7 +144,10 @@ interface SolverBuilder { fun outputs(outputs: OutputStore): SolverBuilder @JsName("setOutput") - fun output(alias: String, channel: OutputChannel): SolverBuilder + fun output( + alias: String, + channel: OutputChannel, + ): SolverBuilder @JsName("standardOutput") var standardOutput: OutputChannel diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolverExtensions.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolverExtensions.kt index 6e9a10e2f..3296da879 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolverExtensions.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolverExtensions.kt @@ -1,13 +1,16 @@ package it.unibo.tuprolog.solve internal object FactoryClassNames { - const val classic = "it.unibo.tuprolog.solve.classic.ClassicSolverFactory" - const val streams = "it.unibo.tuprolog.solve.streams.StreamsSolverFactory" - const val problog = "it.unibo.tuprolog.solve.problog.ProblogSolverFactory" - const val concurrent = "it.unibo.tuprolog.solve.concurrent.ConcurrentSolverFactory" + const val CLASSIC = "it.unibo.tuprolog.solve.classic.ClassicSolverFactory" + const val STREAMS = "it.unibo.tuprolog.solve.streams.StreamsSolverFactory" + const val PROBLOG = "it.unibo.tuprolog.solve.problog.ProblogSolverFactory" + const val CONCURRENT = "it.unibo.tuprolog.solve.concurrent.ConcurrentSolverFactory" } -internal expect fun solverFactory(className: String, vararg classNames: String): SolverFactory +internal expect fun solverFactory( + className: String, + vararg classNames: String, +): SolverFactory expect fun classicSolverFactory(): SolverFactory diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolverFactory.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolverFactory.kt index c44b36a02..eaca8c21e 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolverFactory.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolverFactory.kt @@ -14,7 +14,6 @@ import it.unibo.tuprolog.unify.Unificator import kotlin.js.JsName interface SolverFactory { - @JsName("newBuilder") fun newBuilder(): SolverBuilder = SolverBuilderImpl(this) @@ -65,11 +64,12 @@ interface SolverFactory { staticKb: Theory = defaultStaticKb, dynamicKb: Theory = defaultDynamicKb, inputs: InputStore = InputStore.fromStandard(defaultInputChannel), - outputs: OutputStore = OutputStore.fromStandard( - defaultOutputChannel, - defaultErrorChannel, - defaultWarningsChannel - ) + outputs: OutputStore = + OutputStore.fromStandard( + defaultOutputChannel, + defaultErrorChannel, + defaultWarningsChannel, + ), ): Solver @JsName("solverOf") @@ -82,7 +82,7 @@ interface SolverFactory { stdIn: InputChannel = defaultInputChannel, stdOut: OutputChannel = defaultOutputChannel, stdErr: OutputChannel = defaultErrorChannel, - warnings: OutputChannel = defaultWarningsChannel + warnings: OutputChannel = defaultWarningsChannel, ): Solver @JsName("solverWithDefaultBuiltinsAnd") @@ -95,18 +95,19 @@ interface SolverFactory { stdIn: InputChannel = defaultInputChannel, stdOut: OutputChannel = defaultOutputChannel, stdErr: OutputChannel = defaultErrorChannel, - warnings: OutputChannel = defaultWarningsChannel - ): Solver = solverOf( - unificator, - otherLibraries + defaultBuiltins, - flags, - staticKb, - dynamicKb, - stdIn, - stdOut, - stdErr, - warnings - ) + warnings: OutputChannel = defaultWarningsChannel, + ): Solver = + solverOf( + unificator, + otherLibraries + defaultBuiltins, + flags, + staticKb, + dynamicKb, + stdIn, + stdOut, + stdErr, + warnings, + ) @JsName("mutableSolverOf") fun mutableSolverOf( @@ -118,7 +119,7 @@ interface SolverFactory { stdIn: InputChannel = defaultInputChannel, stdOut: OutputChannel = defaultOutputChannel, stdErr: OutputChannel = defaultErrorChannel, - warnings: OutputChannel = defaultWarningsChannel + warnings: OutputChannel = defaultWarningsChannel, ): MutableSolver @JsName("mutableSolverWithDefaultBuiltinsAnd") @@ -131,18 +132,19 @@ interface SolverFactory { stdIn: InputChannel = defaultInputChannel, stdOut: OutputChannel = defaultOutputChannel, stdErr: OutputChannel = defaultErrorChannel, - warnings: OutputChannel = defaultWarningsChannel - ): MutableSolver = mutableSolverOf( - unificator, - otherLibraries + defaultBuiltins, - flags, - staticKb, - dynamicKb, - stdIn, - stdOut, - stdErr, - warnings - ) + warnings: OutputChannel = defaultWarningsChannel, + ): MutableSolver = + mutableSolverOf( + unificator, + otherLibraries + defaultBuiltins, + flags, + staticKb, + dynamicKb, + stdIn, + stdOut, + stdErr, + warnings, + ) @JsName("rawMutableSolverOf") fun mutableSolverOf( @@ -152,10 +154,11 @@ interface SolverFactory { staticKb: Theory = defaultStaticKb, dynamicKb: Theory = defaultDynamicKb, inputs: InputStore = InputStore.fromStandard(defaultInputChannel), - outputs: OutputStore = OutputStore.fromStandard( - defaultOutputChannel, - defaultErrorChannel, - defaultWarningsChannel - ) + outputs: OutputStore = + OutputStore.fromStandard( + defaultOutputChannel, + defaultErrorChannel, + defaultWarningsChannel, + ), ): MutableSolver } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Time.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Time.kt index 1677b4f69..b9d0fbf2b 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Time.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Time.kt @@ -2,7 +2,6 @@ package it.unibo.tuprolog.solve -import kotlin.js.JsName import kotlin.jvm.JvmName /** This type represents how the solver will see time instants */ @@ -12,5 +11,4 @@ typealias TimeInstant = Long typealias TimeDuration = Long /** A function returning current Time instant */ -@JsName("currentTimeInstant") expect fun currentTimeInstant(): TimeInstant diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Utils.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Utils.kt index 20ba3875d..5b433e363 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Utils.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Utils.kt @@ -28,12 +28,10 @@ inline fun Iterator.forEachWithLookahead(action: (T, Boolean) -> Unit) { } /** Performs the given [action] on each element, giving a lookahead hint (i.e. if there's another element to process after). */ -inline fun Iterable.forEachWithLookahead(action: (T, Boolean) -> Unit) = - iterator().forEachWithLookahead(action) +inline fun Iterable.forEachWithLookahead(action: (T, Boolean) -> Unit) = iterator().forEachWithLookahead(action) /** Performs the given [action] on each element, giving a lookahead hint (i.e. if there's another element to process after). */ -inline fun Sequence.forEachWithLookahead(action: (T, Boolean) -> Unit) = - iterator().forEachWithLookahead(action) +inline fun Sequence.forEachWithLookahead(action: (T, Boolean) -> Unit) = iterator().forEachWithLookahead(action) fun Iterable.getAllOperators(): Sequence { return asSequence() @@ -53,7 +51,10 @@ fun Runtime.getAllOperators(): Sequence { return operators.asSequence() } -fun getAllOperators(libraries: Runtime, vararg theories: Theory): Sequence { +fun getAllOperators( + libraries: Runtime, + vararg theories: Theory, +): Sequence { return libraries.getAllOperators() + sequenceOf(*theories).flatMap { it.getAllOperators() } } @@ -63,7 +64,11 @@ fun Sequence.toOperatorSet(): OperatorSet { @JvmOverloads @JsName("libraryOf") -fun libraryOf(alias: String? = null, item1: AbstractWrapper<*>, vararg items: AbstractWrapper<*>): Library { +fun libraryOf( + alias: String? = null, + item1: AbstractWrapper<*>, + vararg items: AbstractWrapper<*>, +): Library { val clauses = mutableListOf() val primitives = mutableMapOf() val functions = mutableMapOf() @@ -81,6 +86,10 @@ fun libraryOf(alias: String? = null, item1: AbstractWrapper<*>, vararg items: Ab @JvmOverloads @JsName("runtimeOf") -fun runtimeOf(alias: String? = null, item1: AbstractWrapper<*>, vararg items: AbstractWrapper<*>): Runtime { +fun runtimeOf( + alias: String? = null, + item1: AbstractWrapper<*>, + vararg items: AbstractWrapper<*>, +): Runtime { return libraryOf(alias, item1, *items).toRuntime() } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/Channel.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/Channel.kt index edfa33841..db7235f69 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/Channel.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/Channel.kt @@ -28,11 +28,14 @@ interface Channel { companion object { @JvmStatic @JsName("streamTerm") - fun streamTerm(input: Boolean? = null, id: String? = null): Struct = + fun streamTerm( + input: Boolean? = null, + id: String? = null, + ): Struct = Struct.of( "\$stream", input?.let { if (it) "in" else "out" }?.let { Atom.of(it) } ?: Var.anonymous(), - id?.let { Atom.of(it) } ?: Var.anonymous() + id?.let { Atom.of(it) } ?: Var.anonymous(), ) } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/ChannelStore.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/ChannelStore.kt index 1303277f8..32be39865 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/ChannelStore.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/ChannelStore.kt @@ -32,37 +32,35 @@ interface ChannelStore, Self : ChannelStore> operator fun plus(others: Map): Self @JsName("plus") - operator fun plus(other: Pair): Self = - plus(mapOf(other)) + operator fun plus(other: Pair): Self = plus(mapOf(other)) @JsName("plusIterable") - operator fun plus(others: Iterable>): Self = - plus(others.toMap()) + operator fun plus(others: Iterable>): Self = plus(others.toMap()) @JsName("plusSequence") - operator fun plus(others: Sequence>): Self = - plus(others.toMap()) + operator fun plus(others: Sequence>): Self = plus(others.toMap()) @JsName("plusMany") - fun plus(first: Pair, vararg others: Pair): Self = - plus(mapOf(first, *others)) + fun plus( + first: Pair, + vararg others: Pair, + ): Self = plus(mapOf(first, *others)) @JsName("minus") - operator fun minus(other: String): Self = - minus(sequenceOf(other)) + operator fun minus(other: String): Self = minus(sequenceOf(other)) @JsName("minusIterable") - operator fun minus(others: Iterable): Self = - minus(others.asSequence()) + operator fun minus(others: Iterable): Self = minus(others.asSequence()) @JsName("minusSequence") operator fun minus(others: Sequence): Self @JsName("minusMany") - fun minus(other: String, vararg others: String): Self = - minus(sequenceOf(other, *others)) + fun minus( + other: String, + vararg others: String, + ): Self = minus(sequenceOf(other, *others)) @JsName("close") - fun close(channel: C): Self = - this - aliasesOf(channel.also { it.close() }) + fun close(channel: C): Self = this - aliasesOf(channel.also { it.close() }) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/InputChannel.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/InputChannel.kt index bdb65923e..10825d99a 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/InputChannel.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/InputChannel.kt @@ -14,13 +14,14 @@ interface InputChannel : Channel { @JvmStatic @JsName("ofWithAvailabilityChecker") - fun of(generator: () -> X?, availabilityChecker: () -> Boolean): InputChannel = - InputChannelFromFunction(generator, availabilityChecker) + fun of( + generator: () -> X?, + availabilityChecker: () -> Boolean, + ): InputChannel = InputChannelFromFunction(generator, availabilityChecker) @JvmStatic @JsName("of") - fun of(generator: () -> X?): InputChannel = - InputChannelFromFunction(generator, { true }) + fun of(generator: () -> X?): InputChannel = InputChannelFromFunction(generator, { true }) @JvmStatic @JsName("ofString") @@ -45,6 +46,5 @@ interface InputChannel : Channel { fun peek(): T? @JsName("use") - fun use(function: InputChannel.() -> R): R = - this.function().also { close() } + fun use(function: InputChannel.() -> R): R = this.function().also { close() } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/OutputChannel.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/OutputChannel.kt index 49d52d45d..28156759f 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/OutputChannel.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/OutputChannel.kt @@ -28,13 +28,11 @@ interface OutputChannel : Channel { @JvmStatic @JvmOverloads @JsName("streamTerm") - fun streamTerm(id: String? = null): Struct = - Channel.streamTerm(input = false, id) + fun streamTerm(id: String? = null): Struct = Channel.streamTerm(input = false, id) } @JsName("use") - fun use(function: OutputChannel.() -> R): R = - this.function().also { close() } + fun use(function: OutputChannel.() -> R): R = this.function().also { close() } @JsName("write") fun write(value: T) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/OutputStore.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/OutputStore.kt index 73796691d..e6a52074d 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/OutputStore.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/OutputStore.kt @@ -36,7 +36,7 @@ interface OutputStore : ChannelStore, OutputStore> fun fromStandard( output: OutputChannel = OutputChannel.stdOut(), error: OutputChannel = OutputChannel.stdErr(), - warnings: OutputChannel = OutputChannel.warn() + warnings: OutputChannel = OutputChannel.warn(), ): OutputStore = OutputStoreImpl(output, error, warnings, mapOf("user_output" to output)) @JsName("of") @@ -44,7 +44,7 @@ interface OutputStore : ChannelStore, OutputStore> @JvmOverloads fun of( channels: Map>, - warnings: OutputChannel = OutputChannel.warn() + warnings: OutputChannel = OutputChannel.warn(), ): OutputStore { val stdOut = channels[STDOUT] ?: OutputChannel.stdOut() val stdErr = channels[STDERR] ?: OutputChannel.stdErr() diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/AbstractChannel.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/AbstractChannel.kt index da4ba3c14..115afd513 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/AbstractChannel.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/AbstractChannel.kt @@ -3,10 +3,9 @@ package it.unibo.tuprolog.solve.channel.impl import it.unibo.tuprolog.solve.channel.Channel import it.unibo.tuprolog.solve.channel.Listener import it.unibo.tuprolog.utils.synchronizedOnSelf -import kotlin.jvm.Volatile +import kotlin.concurrent.Volatile abstract class AbstractChannel : Channel { - companion object { @Volatile private var instanceCount: Long = 0 @@ -14,33 +13,38 @@ abstract class AbstractChannel : Channel { private fun nextId(): String = (instanceCount++).toString(16).padStart(16, '0') } + @Suppress("ktlint:standard:property-naming") private val _listeners: MutableList> = mutableListOf() protected val id = nextId() - override fun addListener(listener: Listener): Unit = synchronizedOnSelf { - _listeners.add(listener) - } + override fun addListener(listener: Listener): Unit = + synchronizedOnSelf { + _listeners.add(listener) + } - override fun removeListener(listener: Listener): Unit = synchronizedOnSelf { - _listeners.remove(listener) - } + override fun removeListener(listener: Listener): Unit = + synchronizedOnSelf { + _listeners.remove(listener) + } - override fun clearListeners() = synchronizedOnSelf { - _listeners.clear() - } + override fun clearListeners() = + synchronizedOnSelf { + _listeners.clear() + } protected fun notify(value: T?) { _listeners.forEach { it(value) } } - override fun close() = synchronizedOnSelf { - if (!isClosed) { - isClosed = true - } else { - throw IllegalStateException("Channel is already closed") + override fun close() = + synchronizedOnSelf { + if (!isClosed) { + isClosed = true + } else { + throw IllegalStateException("Channel is already closed") + } } - } final override var isClosed: Boolean = false get() = synchronizedOnSelf { field } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/AbstractChannelStore.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/AbstractChannelStore.kt index 381cb93cc..558489add 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/AbstractChannelStore.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/AbstractChannelStore.kt @@ -6,14 +6,13 @@ import it.unibo.tuprolog.solve.channel.ChannelStore import it.unibo.tuprolog.unify.Unificator.Companion.matches abstract class AbstractChannelStore, Self : ChannelStore>( - protected val channels: Map + protected val channels: Map, ) : ChannelStore, Map by channels { - override fun toString(): String = channels.entries.joinToString( separator = ", ", prefix = "${this::class.simpleName}(", - postfix = ")" + postfix = ")", ) { "${it.key}->${it.value}" } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/AbstractInputChannel.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/AbstractInputChannel.kt index 45a62bc7e..427de4967 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/AbstractInputChannel.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/AbstractInputChannel.kt @@ -7,7 +7,6 @@ import it.unibo.tuprolog.utils.synchronizedOnSelf import it.unibo.tuprolog.utils.takeFirst abstract class AbstractInputChannel : AbstractChannel(), InputChannel { - private val queue: MutableList = dequeOf() override val available: Boolean @@ -15,19 +14,21 @@ abstract class AbstractInputChannel : AbstractChannel(), InputChanne protected abstract fun readActually(): T? - final override fun read(): T? = synchronizedOnSelf { - if (isClosed) throw IllegalStateException("Input channel is closed") - refillQueueIfNecessary() - val read = queue.takeFirst() - notify(read) - read - } + final override fun read(): T? = + synchronizedOnSelf { + if (isClosed) throw IllegalStateException("Input channel is closed") + refillQueueIfNecessary() + val read = queue.takeFirst() + notify(read) + read + } - final override fun peek(): T? = synchronizedOnSelf { - if (isClosed) throw IllegalStateException("Input channel is closed") - refillQueueIfNecessary() - queue[0] - } + final override fun peek(): T? = + synchronizedOnSelf { + if (isClosed) throw IllegalStateException("Input channel is closed") + refillQueueIfNecessary() + queue[0] + } private fun refillQueue() { queue.add(readActually()) @@ -40,11 +41,12 @@ abstract class AbstractInputChannel : AbstractChannel(), InputChanne } override val isOver: Boolean - get() = synchronizedOnSelf { - if (isClosed) throw IllegalStateException("Input channel is closed") - refillQueueIfNecessary() - queue.first() == null - } + get() = + synchronizedOnSelf { + if (isClosed) throw IllegalStateException("Input channel is closed") + refillQueueIfNecessary() + queue.first() == null + } override fun toString(): String = "${this::class.simpleName}(id=$id, available=$available, closed=$isClosed)" diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/AbstractOutputChannel.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/AbstractOutputChannel.kt index 7a74bbae0..f4f036e23 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/AbstractOutputChannel.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/AbstractOutputChannel.kt @@ -5,11 +5,12 @@ import it.unibo.tuprolog.solve.channel.OutputChannel import it.unibo.tuprolog.utils.synchronizedOnSelf abstract class AbstractOutputChannel : AbstractChannel(), OutputChannel { - final override fun write(value: T) = synchronizedOnSelf { - if (isClosed) throw IllegalStateException("Output channel is closed") - writeActually(value) - notify(value) - } + final override fun write(value: T) = + synchronizedOnSelf { + if (isClosed) throw IllegalStateException("Output channel is closed") + writeActually(value) + notify(value) + } protected abstract fun writeActually(value: T) @@ -17,10 +18,11 @@ abstract class AbstractOutputChannel : AbstractChannel(), OutputChan override val streamTerm: Struct by lazy { OutputChannel.streamTerm(id) } - final override fun flush() = synchronizedOnSelf { - if (isClosed) throw IllegalStateException("Output channel is closed") - flushActually() - } + final override fun flush() = + synchronizedOnSelf { + if (isClosed) throw IllegalStateException("Output channel is closed") + flushActually() + } protected abstract fun flushActually() } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/ChannelStoreUtils.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/ChannelStoreUtils.kt index b7e15164b..71461b12f 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/ChannelStoreUtils.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/ChannelStoreUtils.kt @@ -4,12 +4,18 @@ import it.unibo.tuprolog.solve.channel.Channel import it.unibo.tuprolog.solve.channel.ChannelStore internal object ChannelStoreUtils { - fun > MutableMap.ensureAliasRefersToChannel(key: String, channel: C): MutableMap { + fun > MutableMap.ensureAliasRefersToChannel( + key: String, + channel: C, + ): MutableMap { this[key] = channel return this } - fun > MutableMap.setCurrent(key: String, defaultChannel: C): MutableMap { + fun > MutableMap.setCurrent( + key: String, + defaultChannel: C, + ): MutableMap { if (ChannelStore.CURRENT !in this) { this[ChannelStore.CURRENT] = this[key] ?: defaultChannel } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/InputChannelFromFunction.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/InputChannelFromFunction.kt index d41b1a938..243c3a9ed 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/InputChannelFromFunction.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/InputChannelFromFunction.kt @@ -4,9 +4,8 @@ import it.unibo.tuprolog.utils.synchronizedOnSelf internal class InputChannelFromFunction( private val generator: () -> T?, - private val availabilityChecker: () -> Boolean + private val availabilityChecker: () -> Boolean, ) : AbstractInputChannel() { - override val available: Boolean get() = synchronizedOnSelf { availabilityChecker() } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/InputChannelFromString.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/InputChannelFromString.kt index 211449cd3..03230cc86 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/InputChannelFromString.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/InputChannelFromString.kt @@ -1,9 +1,8 @@ package it.unibo.tuprolog.solve.channel.impl internal class InputChannelFromString( - private val string: String + private val string: String, ) : AbstractInputChannel() { - private val iterator by lazy { string.lineSequence() .flatMap { it.toCharArray().asSequence() + sequenceOf('\n') } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/InputStoreImpl.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/InputStoreImpl.kt index beeb67d2f..d8aaaea85 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/InputStoreImpl.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/InputStoreImpl.kt @@ -9,12 +9,12 @@ import it.unibo.tuprolog.solve.channel.impl.ChannelStoreUtils.setCurrent internal class InputStoreImpl( override val stdIn: InputChannel, - channels: Map> = emptyMap() + channels: Map> = emptyMap(), ) : InputStore, AbstractChannelStore, InputStore>( - channels.toMutableMap() - .ensureAliasRefersToChannel(STDIN, stdIn) - .setCurrent(STDIN, stdIn) -) { + channels.toMutableMap() + .ensureAliasRefersToChannel(STDIN, stdIn) + .setCurrent(STDIN, stdIn), + ) { override fun setStdIn(channel: InputChannel): InputStore = (channels - STDIN).let { if (current == stdIn) { @@ -31,8 +31,9 @@ internal class InputStoreImpl( } override fun setCurrent(channel: InputChannel): InputStore { - val key = entries.firstOrNull { (_, v) -> v == channel }?.key - ?: throw NoSuchElementException("Channel $channel has no alias") + val key = + entries.firstOrNull { (_, v) -> v == channel }?.key + ?: throw NoSuchElementException("Channel $channel has no alias") return setCurrent(key) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/OutputChannelFromFunction.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/OutputChannelFromFunction.kt index 11eed8c2d..f6b580a96 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/OutputChannelFromFunction.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/OutputChannelFromFunction.kt @@ -1,9 +1,8 @@ package it.unibo.tuprolog.solve.channel.impl internal class OutputChannelFromFunction( - private val consumer: (T) -> Unit + private val consumer: (T) -> Unit, ) : AbstractOutputChannel() { - override fun writeActually(value: T) = consumer(value) override fun flushActually() = Unit diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/OutputStoreImpl.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/OutputStoreImpl.kt index a21176390..a1db035cc 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/OutputStoreImpl.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/channel/impl/OutputStoreImpl.kt @@ -13,7 +13,7 @@ internal class OutputStoreImpl( override val stdOut: OutputChannel, override val stdErr: OutputChannel, override val warnings: OutputChannel = OutputChannel.warn(), - outputChannels: Map> = emptyMap() + outputChannels: Map> = emptyMap(), ) : AbstractChannelStore, OutputStore>(checkChannels(stdOut, stdErr, outputChannels)), OutputStore { override fun setStdOut(channel: OutputChannel): OutputStore = @@ -35,7 +35,12 @@ internal class OutputStoreImpl( } override fun setWarnings(channel: OutputChannel): OutputStore = - OutputStoreImpl(stdOut, stdErr, channel, channels) + OutputStoreImpl( + stdOut, + stdErr, + channel, + channels, + ) override fun setCurrent(alias: String): OutputStore = when (val newCurrentChannel = get(alias)) { @@ -44,8 +49,9 @@ internal class OutputStoreImpl( } override fun setCurrent(channel: OutputChannel): OutputStore { - val key = entries.firstOrNull { (_, v) -> v == channel }?.key - ?: throw NoSuchElementException("Channel $channel has no alias") + val key = + entries.firstOrNull { (_, v) -> v == channel }?.key + ?: throw NoSuchElementException("Channel $channel has no alias") return setCurrent(key) } @@ -53,13 +59,18 @@ internal class OutputStoreImpl( OutputStoreImpl(stdOut, stdErr, warnings, (this as Map>) + others) override fun minus(others: Sequence): OutputStore = - OutputStoreImpl(stdOut, stdErr, warnings, channels - others) + OutputStoreImpl( + stdOut, + stdErr, + warnings, + channels - others, + ) companion object { private fun checkChannels( stdOut: OutputChannel, stdErr: OutputChannel, - channels: Map> + channels: Map>, ): Map> { return channels.toMutableMap() .ensureAliasRefersToChannel(STDOUT, stdOut) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/data/CustomDataStore.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/data/CustomDataStore.kt index 899768fbb..19ccd412d 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/data/CustomDataStore.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/data/CustomDataStore.kt @@ -9,7 +9,7 @@ data class CustomDataStore private constructor( @JsName("durable") val durable: CustomData = emptyMap(), @JsName("ephemeral") - val ephemeral: CustomData = emptyMap() + val ephemeral: CustomData = emptyMap(), ) { companion object { @JsName("empty") @@ -18,10 +18,8 @@ data class CustomDataStore private constructor( } @JsName("discardEphemeral") - fun discardEphemeral(): CustomDataStore = - copy(ephemeral = emptyMap()) + fun discardEphemeral(): CustomDataStore = copy(ephemeral = emptyMap()) @JsName("preservePersistent") - fun preservePersistent(): CustomDataStore = - copy(durable = emptyMap(), ephemeral = emptyMap()) + fun preservePersistent(): CustomDataStore = copy(durable = emptyMap(), ephemeral = emptyMap()) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/ClauseExtensions.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/ClauseExtensions.kt index f54c0a7ed..e1f3e71a5 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/ClauseExtensions.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/ClauseExtensions.kt @@ -13,12 +13,12 @@ import kotlin.jvm.JvmOverloads @JsName("partitionClauses") fun Iterable.partition( unificator: Unificator = Unificator.default, - staticByDefault: Boolean = true + staticByDefault: Boolean = true, ): ClausePartition = ClausePartitioner(unificator, this, staticByDefault) @JvmOverloads @JsName("partitionTheory") fun Theory.partition( unificator: Unificator = this.unificator, - staticByDefault: Boolean = true + staticByDefault: Boolean = true, ): ClausePartition = ClausePartitioner(unificator, this, staticByDefault) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/ClauseListener.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/ClauseListener.kt index 2da2d6575..65dd9e5b1 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/ClauseListener.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/ClauseListener.kt @@ -7,7 +7,6 @@ import it.unibo.tuprolog.core.Rule import kotlin.js.JsName interface ClauseListener { - @JsName("onDirective") fun onDirective(directive: Directive) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/ClausePartition.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/ClausePartition.kt index f229def22..826754086 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/ClausePartition.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/ClausePartition.kt @@ -36,7 +36,7 @@ interface ClausePartition { operators + other.operators, initialGoals + other.initialGoals, includes + other.includes, - flagStore + other.flagStore + flagStore + other.flagStore, ) companion object { @@ -48,14 +48,15 @@ interface ClausePartition { operators: OperatorSet? = null, initialGoals: List? = null, includes: List? = null, - flagStore: FlagStore? = null - ): ClausePartition = ClausePartitionImpl( - staticClauses ?: Theory.emptyIndexed(unificator), - dynamicClauses ?: MutableTheory.emptyIndexed(unificator), - operators ?: OperatorSet.EMPTY, - initialGoals ?: emptyList(), - includes ?: emptyList(), - flagStore ?: FlagStore.empty() - ) + flagStore: FlagStore? = null, + ): ClausePartition = + ClausePartitionImpl( + staticClauses ?: Theory.emptyIndexed(unificator), + dynamicClauses ?: MutableTheory.emptyIndexed(unificator), + operators ?: OperatorSet.EMPTY, + initialGoals ?: emptyList(), + includes ?: emptyList(), + flagStore ?: FlagStore.empty(), + ) } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/ClausePartitionImpl.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/ClausePartitionImpl.kt index 23a46a410..948e0b9a0 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/ClausePartitionImpl.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/ClausePartitionImpl.kt @@ -12,5 +12,5 @@ internal data class ClausePartitionImpl( override val operators: OperatorSet, override val initialGoals: List, override val includes: List, - override val flagStore: FlagStore + override val flagStore: FlagStore, ) : ClausePartition diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/ClausePartitioner.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/ClausePartitioner.kt index 5f8fd13da..e6c10cd35 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/ClausePartitioner.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/ClausePartitioner.kt @@ -24,9 +24,8 @@ import it.unibo.tuprolog.utils.dequeOf class ClausePartitioner( override val unificator: Unificator, private val source: Iterable, - private val staticByDefault: Boolean = true + private val staticByDefault: Boolean = true, ) : ClausePartition, DirectiveSelector { - private val _staticClauses: MutableTheory = MutableTheory.emptyIndexed(unificator) private val _dynamicClauses: MutableTheory = MutableTheory.emptyIndexed(unificator) private val _operators: MutableList = dequeOf() @@ -84,14 +83,23 @@ class ClausePartitioner( private val defaultClauses: MutableTheory by lazy { if (staticByDefault) _staticClauses else _dynamicClauses } - override fun onSetFlag(directive: Directive, name: Term, value: Term) { + override fun onSetFlag( + directive: Directive, + name: Term, + value: Term, + ) { onDirective(directive) if (name is Atom) { _flagStore += name.value to value } } - override fun onOperator(directive: Directive, priority: Term, specifier: Term, name: Term) { + override fun onOperator( + directive: Directive, + priority: Term, + specifier: Term, + name: Term, + ) { onDirective(directive) if (priority is Integer) { try { @@ -105,35 +113,51 @@ class ClausePartitioner( } } - override fun onLoad(directive: Directive, goal: Term) { + override fun onLoad( + directive: Directive, + goal: Term, + ) { onDirective(directive) if (goal is Atom) { _includes += goal } } - override fun onSolve(directive: Directive, goal: Term) { + override fun onSolve( + directive: Directive, + goal: Term, + ) { onDirective(directive) if (goal is Struct) { _initialGoals += goal } } - override fun onStatic(directive: Directive, indicator: Indicator) { + override fun onStatic( + directive: Directive, + indicator: Indicator, + ) { onDirective(directive) if (indicator.isWellFormed) { staticSignatures += Signature.fromIndicator(indicator)!! } } - override fun onDynamic(directive: Directive, indicator: Indicator) { + override fun onDynamic( + directive: Directive, + indicator: Indicator, + ) { onDirective(directive) if (indicator.isWellFormed) { dynamicSignatures += Signature.fromIndicator(indicator)!! } } - override fun onDirectiveMatchingPattern(directive: Directive, pattern: Term, unifier: Substitution.Unifier) { + override fun onDirectiveMatchingPattern( + directive: Directive, + pattern: Term, + unifier: Substitution.Unifier, + ) { onDirective(directive) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/DirectiveListener.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/DirectiveListener.kt index eb8269f9b..e2b01f84c 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/DirectiveListener.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/DirectiveListener.kt @@ -8,7 +8,6 @@ import it.unibo.tuprolog.unify.Unificator import kotlin.js.JsName interface DirectiveListener : ClauseListener { - @JsName("unificator") val unificator: Unificator @@ -16,7 +15,11 @@ interface DirectiveListener : ClauseListener { val patterns: List @JsName("onDirectiveMatchingPattern") - fun onDirectiveMatchingPattern(directive: Directive, pattern: Term, unifier: Unifier) + fun onDirectiveMatchingPattern( + directive: Directive, + pattern: Term, + unifier: Unifier, + ) @JsName("listenDirective") fun listenDirective(directive: Directive) { @@ -30,8 +33,11 @@ interface DirectiveListener : ClauseListener { } @JsName("listenDirectiveMatchingPattern") - fun listenDirectiveMatchingPattern(directive: Directive, pattern: Term, unifier: Unifier) = - onDirectiveMatchingPattern(directive, pattern, unifier) + fun listenDirectiveMatchingPattern( + directive: Directive, + pattern: Term, + unifier: Unifier, + ) = onDirectiveMatchingPattern(directive, pattern, unifier) override fun listen(clause: Clause) { when (clause) { diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/DirectiveSelector.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/DirectiveSelector.kt index cfd392ff6..1901c5402 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/DirectiveSelector.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/directives/DirectiveSelector.kt @@ -10,7 +10,6 @@ import it.unibo.tuprolog.solve.stdlib.primitive.SetFlag import it.unibo.tuprolog.solve.stdlib.rule.SetPrologFlag interface DirectiveSelector : DirectiveListener { - @Suppress("MemberVisibilityCanBePrivate") companion object { private val scope = Scope.empty() @@ -45,12 +44,17 @@ interface DirectiveSelector : DirectiveListener { val SET_PROLOG_FLAG = scope.structOf(SetPrologFlag.functor, Name, Value) - private val PATTERNS = listOf(DYNAMIC, STATIC, INITIALIZATION, SOLVE, INCLUDE, LOAD, OP, SET_FLAG, SET_PROLOG_FLAG) + private val PATTERNS = + listOf(DYNAMIC, STATIC, INITIALIZATION, SOLVE, INCLUDE, LOAD, OP, SET_FLAG, SET_PROLOG_FLAG) } override val patterns: List get() = PATTERNS - override fun listenDirectiveMatchingPattern(directive: Directive, pattern: Term, unifier: Unifier) { + override fun listenDirectiveMatchingPattern( + directive: Directive, + pattern: Term, + unifier: Unifier, + ) { when (pattern) { DYNAMIC -> onDynamic(directive, Indicator.of(unifier[Name]!!, unifier[Arity]!!)) STATIC -> onStatic(directive, Indicator.of(unifier[Name]!!, unifier[Arity]!!)) @@ -62,15 +66,36 @@ interface DirectiveSelector : DirectiveListener { } } - fun onSetFlag(directive: Directive, name: Term, value: Term) - - fun onOperator(directive: Directive, priority: Term, specifier: Term, name: Term) - - fun onLoad(directive: Directive, goal: Term) - - fun onSolve(directive: Directive, goal: Term) - - fun onStatic(directive: Directive, indicator: Indicator) - - fun onDynamic(directive: Directive, indicator: Indicator) + fun onSetFlag( + directive: Directive, + name: Term, + value: Term, + ) + + fun onOperator( + directive: Directive, + priority: Term, + specifier: Term, + name: Term, + ) + + fun onLoad( + directive: Directive, + goal: Term, + ) + + fun onSolve( + directive: Directive, + goal: Term, + ) + + fun onStatic( + directive: Directive, + indicator: Indicator, + ) + + fun onDynamic( + directive: Directive, + indicator: Indicator, + ) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/HaltException.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/HaltException.kt index 448b9547c..eddbf38ae 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/HaltException.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/HaltException.kt @@ -17,24 +17,28 @@ class HaltException( @JsName("exitStatus") val exitStatus: Int = 0, message: String? = "Resolution has been halted with exit code $exitStatus", cause: Throwable? = null, - contexts: Array + contexts: Array, ) : ResolutionException(message, cause, contexts) { - constructor( exitStatus: Int = 0, message: String? = "Resolution has been halted with exit code $exitStatus", cause: Throwable? = null, - context: ExecutionContext + context: ExecutionContext, ) : this(exitStatus, message, cause, arrayOf(context)) constructor(exitStatus: Int = 0, cause: Throwable?, context: ExecutionContext) : this(exitStatus, cause?.toString(), cause, context) - override fun updateContext(newContext: ExecutionContext, index: Int): HaltException = - HaltException(exitStatus, message, cause, contexts.setItem(index, newContext)) + override fun updateContext( + newContext: ExecutionContext, + index: Int, + ): HaltException = HaltException(exitStatus, message, cause, contexts.setItem(index, newContext)) override fun updateLastContext(newContext: ExecutionContext): HaltException = - updateContext(newContext, contexts.lastIndex) + updateContext( + newContext, + contexts.lastIndex, + ) override fun pushContext(newContext: ExecutionContext): HaltException = HaltException(exitStatus, message, cause, contexts.addLast(newContext)) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/LogicError.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/LogicError.kt index 1836d07d8..10410c9a4 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/LogicError.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/LogicError.kt @@ -42,15 +42,14 @@ abstract class LogicError( cause: Throwable? = null, contexts: Array, @JsName("type") open val type: Struct, - @JsName("extraData") open val extraData: Term? = null + @JsName("extraData") open val extraData: Term? = null, ) : ResolutionException(message, cause, contexts) { - constructor( message: String? = null, cause: Throwable? = null, context: ExecutionContext, type: Struct, - extraData: Term? = null + extraData: Term? = null, ) : this(message, cause, arrayOf(context), type, extraData) constructor(cause: Throwable?, context: ExecutionContext, type: Struct, extraData: Term? = null) : @@ -60,10 +59,12 @@ abstract class LogicError( @JsName("errorStruct") val errorStruct: Struct by lazy { generateErrorStruct() } - private fun generateErrorStruct() = - extraData?.let { errorStructOf(type, it) } ?: errorStructOf(type) + private fun generateErrorStruct() = extraData?.let { errorStructOf(type, it) } ?: errorStructOf(type) - abstract override fun updateContext(newContext: ExecutionContext, index: Int): LogicError + abstract override fun updateContext( + newContext: ExecutionContext, + index: Int, + ): LogicError abstract override fun updateLastContext(newContext: ExecutionContext): LogicError @@ -72,15 +73,14 @@ abstract class LogicError( override fun toString(): String = errorStruct.toString() companion object { + internal fun message( + message: String, + f: (String, Atom) -> E, + ): E = f(message, Atom.of(message)) - internal fun message(message: String, f: (String, Atom) -> E): E = - f(message, Atom.of(message)) - - internal fun Term.pretty(): String = - format(TermFormatter.prettyVariables()) + internal fun Term.pretty(): String = format(TermFormatter.prettyVariables()) - internal fun Signature.pretty(): String = - toIndicator().toString() + internal fun Signature.pretty(): String = toIndicator().toString() /** * Factory method for [LogicError]s @@ -94,7 +94,7 @@ abstract class LogicError( cause: Throwable? = null, context: ExecutionContext, type: Struct, - extraData: Term? = null + extraData: Term? = null, ): LogicError = of(message, cause, arrayOf(context), type, extraData) private fun customError( @@ -102,17 +102,30 @@ abstract class LogicError( cause: Throwable? = null, contexts: Array, type: Struct, - extraData: Term? = null - ): LogicError = object : LogicError(message ?: type.pretty(), cause, contexts, type, extraData) { - override fun updateContext(newContext: ExecutionContext, index: Int): LogicError = - of(this.message, this.cause, this.contexts.setItem(index, newContext), this.type, this.extraData) - - override fun updateLastContext(newContext: ExecutionContext): LogicError = - updateContext(newContext, this.contexts.lastIndex) - - override fun pushContext(newContext: ExecutionContext): LogicError = - of(this.message, this.cause, this.contexts.addLast(newContext), this.type, this.extraData) - } + extraData: Term? = null, + ): LogicError = + object : LogicError(message ?: type.pretty(), cause, contexts, type, extraData) { + override fun updateContext( + newContext: ExecutionContext, + index: Int, + ): LogicError = + of( + this.message, + this.cause, + this.contexts.setItem(index, newContext), + this.type, + this.extraData, + ) + + override fun updateLastContext(newContext: ExecutionContext): LogicError = + updateContext( + newContext, + this.contexts.lastIndex, + ) + + override fun pushContext(newContext: ExecutionContext): LogicError = + of(this.message, this.cause, this.contexts.addLast(newContext), this.type, this.extraData) + } @JvmStatic @JsName("ofManyContexts") @@ -121,70 +134,71 @@ abstract class LogicError( cause: Throwable? = null, contexts: Array, type: Struct, - extraData: Term? = null - ): LogicError = with(type) { - val actualMessage = message ?: type.pretty() - try { - when { - functor == InstantiationError.typeFunctor -> - InstantiationError(actualMessage, cause, contexts, Var.anonymous(), extraData) - functor == SystemError.typeFunctor -> - SystemError(actualMessage, cause, contexts, extraData) - functor == SyntaxError.typeFunctor -> - SyntaxError(actualMessage, cause, contexts, extraData) - functor == MessageError.typeFunctor -> - MessageError(actualMessage, cause, contexts, extraData) - functor == RepresentationError.typeFunctor && arity == 1 -> - RepresentationError(actualMessage, cause, contexts, Limit.fromTerm(type[0])!!, extraData) - functor == ExistenceError.typeFunctor && arity == 2 -> - ExistenceError( - actualMessage, - cause, - contexts, - ExistenceError.ObjectType.fromTerm(type[0])!!, - type[1] - ) - functor == DomainError.typeFunctor && arity == 2 -> - DomainError( - actualMessage, - cause, - contexts, - DomainError.Expected.fromTerm(getArgAt(0))!!, - getArgAt(1), - extraData - ) - functor == TypeError.typeFunctor && arity == 2 -> - TypeError( - actualMessage, - cause, - contexts, - TypeError.Expected.fromTerm(getArgAt(0))!!, - getArgAt(1), - extraData - ) - functor == EvaluationError.typeFunctor && arity == 1 -> - EvaluationError( - actualMessage, - cause, - contexts, - EvaluationError.Type.fromTerm(getArgAt(0))!!, - extraData - ) - functor == PermissionError.typeFunctor && arity == 3 -> - PermissionError( - actualMessage, - cause, - contexts, - Operation.fromTerm(getArgAt(0))!!, - Permission.fromTerm(getArgAt(1))!!, - getArgAt(2), - extraData - ) - else -> customError(message, cause, contexts, type, extraData) + extraData: Term? = null, + ): LogicError = + with(type) { + val actualMessage = message ?: type.pretty() + try { + when { + functor == InstantiationError.typeFunctor -> + InstantiationError(actualMessage, cause, contexts, Var.anonymous(), extraData) + functor == SystemError.typeFunctor -> + SystemError(actualMessage, cause, contexts, extraData) + functor == SyntaxError.typeFunctor -> + SyntaxError(actualMessage, cause, contexts, extraData) + functor == MessageError.typeFunctor -> + MessageError(actualMessage, cause, contexts, extraData) + functor == RepresentationError.typeFunctor && arity == 1 -> + RepresentationError(actualMessage, cause, contexts, Limit.fromTerm(type[0])!!, extraData) + functor == ExistenceError.typeFunctor && arity == 2 -> + ExistenceError( + actualMessage, + cause, + contexts, + ExistenceError.ObjectType.fromTerm(type[0])!!, + type[1], + ) + functor == DomainError.typeFunctor && arity == 2 -> + DomainError( + actualMessage, + cause, + contexts, + DomainError.Expected.fromTerm(getArgAt(0))!!, + getArgAt(1), + extraData, + ) + functor == TypeError.typeFunctor && arity == 2 -> + TypeError( + actualMessage, + cause, + contexts, + TypeError.Expected.fromTerm(getArgAt(0))!!, + getArgAt(1), + extraData, + ) + functor == EvaluationError.typeFunctor && arity == 1 -> + EvaluationError( + actualMessage, + cause, + contexts, + EvaluationError.Type.fromTerm(getArgAt(0))!!, + extraData, + ) + functor == PermissionError.typeFunctor && arity == 3 -> + PermissionError( + actualMessage, + cause, + contexts, + Operation.fromTerm(getArgAt(0))!!, + Permission.fromTerm(getArgAt(1))!!, + getArgAt(2), + extraData, + ) + else -> customError(message, cause, contexts, type, extraData) + } + } catch (_: NullPointerException) { + customError(message, cause, contexts, type, extraData) } - } catch (_: NullPointerException) { - customError(message, cause, contexts, type, extraData) } - } } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/ResolutionException.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/ResolutionException.kt index 47fee25ef..e00a10a6a 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/ResolutionException.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/ResolutionException.kt @@ -17,9 +17,8 @@ import kotlin.jvm.JvmOverloads open class ResolutionException( message: String? = null, cause: Throwable? = null, - @JsName("contexts") val contexts: Array + @JsName("contexts") val contexts: Array, ) : TuPrologException(message, cause) { - init { require(contexts.isNotEmpty()) } @@ -28,7 +27,7 @@ open class ResolutionException( message: String? = null, cause: Throwable? = null, context: ExecutionContext, - vararg otherContexts: ExecutionContext + vararg otherContexts: ExecutionContext, ) : this(message, cause, arrayOf(context, *otherContexts)) constructor(cause: Throwable?, context: ExecutionContext) : this(cause?.toString(), cause, context) @@ -40,14 +39,15 @@ open class ResolutionException( /** The exception stacktrace; shorthand for `context.prologStackTrace` */ @JsName("logicStackTrace") val logicStackTrace: List - get() = when (contexts.size) { - 1 -> context.logicStackTrace - else -> - ( - sequenceOf(*contexts).take(contexts.size - 1).flatMap { it.fullStackTraceButLast } + - contexts.last().fullStackTrace + get() = + when (contexts.size) { + 1 -> context.logicStackTrace + else -> + ( + sequenceOf(*contexts).take(contexts.size - 1).flatMap { it.fullStackTraceButLast } + + contexts.last().fullStackTrace ).toList() - } + } private val ExecutionContext.fullStackTrace: Sequence get() = logicStackTrace.asSequence() @@ -61,8 +61,10 @@ open class ResolutionException( */ @JsName("updateContext") @JvmOverloads - open fun updateContext(newContext: ExecutionContext, index: Int = 0): ResolutionException = - ResolutionException(message, cause, contexts.setItem(index, newContext)) + open fun updateContext( + newContext: ExecutionContext, + index: Int = 0, + ): ResolutionException = ResolutionException(message, cause, contexts.setItem(index, newContext)) @JsName("updateLastContext") open fun updateLastContext(newContext: ExecutionContext): ResolutionException = @@ -72,9 +74,14 @@ open class ResolutionException( open fun pushContext(newContext: ExecutionContext): ResolutionException = ResolutionException(message, cause, contexts.addLast(newContext)) - protected fun Array.setItem(index: Int, item: ExecutionContext): Array = - copyOf().also { it[index] = item } + protected fun Array.setItem( + index: Int, + item: ExecutionContext, + ): Array = copyOf().also { it[index] = item } protected fun Array.addLast(item: ExecutionContext): Array = - arrayOf(*this, item) + arrayOf( + *this, + item, + ) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/TimeOutException.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/TimeOutException.kt index ee9922dcf..b57f51d19 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/TimeOutException.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/TimeOutException.kt @@ -18,24 +18,28 @@ class TimeOutException( message: String? = null, cause: Throwable? = null, contexts: Array, - @JsName("exceededDuration") val exceededDuration: TimeDuration + @JsName("exceededDuration") val exceededDuration: TimeDuration, ) : ResolutionException(message, cause, contexts) { - constructor( message: String? = null, cause: Throwable? = null, context: ExecutionContext, - exceededDuration: TimeDuration + exceededDuration: TimeDuration, ) : this(message, cause, arrayOf(context), exceededDuration) constructor(cause: Throwable?, context: ExecutionContext, exceededDuration: TimeDuration) : this(cause?.toString(), cause, context, exceededDuration) - override fun updateContext(newContext: ExecutionContext, index: Int): TimeOutException = - TimeOutException(message, cause, contexts.setItem(index, newContext), exceededDuration) + override fun updateContext( + newContext: ExecutionContext, + index: Int, + ): TimeOutException = TimeOutException(message, cause, contexts.setItem(index, newContext), exceededDuration) override fun updateLastContext(newContext: ExecutionContext): TimeOutException = - updateContext(newContext, contexts.lastIndex) + updateContext( + newContext, + contexts.lastIndex, + ) override fun pushContext(newContext: ExecutionContext): TimeOutException = TimeOutException(message, cause, arrayOf(*contexts, newContext), exceededDuration) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/Warning.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/Warning.kt index 7a88c4f5b..5887703fa 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/Warning.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/Warning.kt @@ -14,15 +14,18 @@ import it.unibo.tuprolog.solve.ExecutionContext abstract class Warning( message: String? = null, cause: Throwable? = null, - contexts: Array + contexts: Array, ) : ResolutionException(message, cause, contexts) { constructor( message: String? = null, cause: Throwable? = null, - context: ExecutionContext + context: ExecutionContext, ) : this(message, cause, arrayOf(context)) - abstract override fun updateContext(newContext: ExecutionContext, index: Int): Warning + abstract override fun updateContext( + newContext: ExecutionContext, + index: Int, + ): Warning abstract override fun updateLastContext(newContext: ExecutionContext): Warning diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/DomainError.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/DomainError.kt index b131edc47..d0e76efa3 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/DomainError.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/DomainError.kt @@ -27,23 +27,35 @@ class DomainError( contexts: Array, @JsName("expectedDomain") val expectedDomain: Expected, @JsName("culprit") val culprit: Term, - extraData: Term? = null + extraData: Term? = null, ) : LogicError(message, cause, contexts, Atom.of(typeFunctor), extraData) { - constructor( message: String? = null, cause: Throwable? = null, context: ExecutionContext, expectedDomain: Expected, actualValue: Term, - extraData: Term? = null + extraData: Term? = null, ) : this(message, cause, arrayOf(context), expectedDomain, actualValue, extraData) - override fun updateContext(newContext: ExecutionContext, index: Int): DomainError = - DomainError(message, cause, contexts.setItem(index, newContext), expectedDomain, culprit, extraData) + override fun updateContext( + newContext: ExecutionContext, + index: Int, + ): DomainError = + DomainError( + message, + cause, + contexts.setItem(index, newContext), + expectedDomain, + culprit, + extraData, + ) override fun updateLastContext(newContext: ExecutionContext): DomainError = - updateContext(newContext, contexts.lastIndex) + updateContext( + newContext, + contexts.lastIndex, + ) override fun pushContext(newContext: ExecutionContext): DomainError = DomainError(message, cause, contexts.addLast(newContext), expectedDomain, culprit, extraData) @@ -51,7 +63,6 @@ class DomainError( override val type: Struct by lazy { Struct.of(super.type.functor, expectedDomain.toTerm(), culprit) } companion object { - @JsName("forFlagValues") @JvmStatic fun forFlagValues( @@ -59,21 +70,22 @@ class DomainError( procedure: Signature, flagValues: Iterable, actualValue: Term, - index: Int? = null - ): DomainError = message( - (index?.let { "The $it-th argument" } ?: "An argument") + - "of `${procedure.pretty()}` should be one of " + - flagValues.joinToString(", ", "{", "}") { "`${it.pretty()}`" } + - " but `${actualValue.pretty()}` has been provided instead" - ) { m, extra -> - DomainError( - message = m, - context = context, - expectedDomain = Expected.FLAG_VALUE, - actualValue = actualValue, - extraData = extra - ) - } + index: Int? = null, + ): DomainError = + message( + (index?.let { "The $it-th argument" } ?: "An argument") + + "of `${procedure.pretty()}` should be one of " + + flagValues.joinToString(", ", "{", "}") { "`${it.pretty()}`" } + + " but `${actualValue.pretty()}` has been provided instead", + ) { m, extra -> + DomainError( + message = m, + context = context, + expectedDomain = Expected.FLAG_VALUE, + actualValue = actualValue, + extraData = extra, + ) + } @JsName("forArgument") @JvmStatic @@ -82,38 +94,40 @@ class DomainError( procedure: Signature, expectedDomain: Expected, actualValue: Term, - index: Int? = null - ): DomainError = message( - (index?.let { "The $it-th argument" } ?: "An argument") + - "of `${procedure.pretty()}` should be `$expectedDomain`, " + - "but `${actualValue.pretty()}` has been provided instead" - ) { m, extra -> - DomainError( - message = m, - context = context, - expectedDomain = expectedDomain, - actualValue = actualValue, - extraData = extra - ) - } + index: Int? = null, + ): DomainError = + message( + (index?.let { "The $it-th argument" } ?: "An argument") + + "of `${procedure.pretty()}` should be `$expectedDomain`, " + + "but `${actualValue.pretty()}` has been provided instead", + ) { m, extra -> + DomainError( + message = m, + context = context, + expectedDomain = expectedDomain, + actualValue = actualValue, + extraData = extra, + ) + } @JsName("forTerm") @JvmStatic fun forTerm( context: ExecutionContext, expectedDomain: Expected, - actualValue: Term - ): DomainError = message( - "Term `${actualValue.pretty()}` is not a valid $expectedDomain" - ) { m, extra -> - DomainError( - message = m, - context = context, - expectedDomain = expectedDomain, - actualValue = actualValue, - extraData = extra - ) - } + actualValue: Term, + ): DomainError = + message( + "Term `${actualValue.pretty()}` is not a valid $expectedDomain", + ) { m, extra -> + DomainError( + message = m, + context = context, + expectedDomain = expectedDomain, + actualValue = actualValue, + extraData = extra, + ) + } @JsName("forGoal") @JvmStatic @@ -121,20 +135,22 @@ class DomainError( context: ExecutionContext, procedure: Signature, expectedDomain: Expected, - actualValue: Term - ): DomainError = message( - "Subgoal `${actualValue.pretty()}` of ${procedure.pretty()} is not $expectedDomain term" - ) { m, extra -> - DomainError( - message = m, - context = context, - expectedDomain = expectedDomain, - actualValue = actualValue, - extraData = extra - ) - } + actualValue: Term, + ): DomainError = + message( + "Subgoal `${actualValue.pretty()}` of ${procedure.pretty()} is not $expectedDomain term", + ) { m, extra -> + DomainError( + message = m, + context = context, + expectedDomain = expectedDomain, + actualValue = actualValue, + extraData = extra, + ) + } /** The domain error Struct functor */ + @Suppress("ConstPropertyName", "ktlint:standard:property-naming") const val typeFunctor = "domain_error" } @@ -180,7 +196,8 @@ class DomainError( CLAUSE, RULE, FACT, - DIRECTIVE; + DIRECTIVE, + ; /** The expected domain string description */ @JsName("domain") @@ -192,7 +209,6 @@ class DomainError( override fun toString(): String = domain companion object { - /** Returns the Expected instance described by [domain]; creates a new instance only if [domain] was not predefined */ @JsName("of") @JvmStatic @@ -201,10 +217,11 @@ class DomainError( /** Gets [Expected] instance from [term] representation, if possible */ @JsName("fromTerm") @JvmStatic - fun fromTerm(term: Term): Expected? = when (term) { - is Atom -> of(term.value) - else -> null - } + fun fromTerm(term: Term): Expected? = + when (term) { + is Atom -> of(term.value) + else -> null + } } } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/ErrorUtils.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/ErrorUtils.kt index 619d3f9f4..7b3a6686e 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/ErrorUtils.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/ErrorUtils.kt @@ -10,12 +10,11 @@ import it.unibo.tuprolog.core.Term * @author Enrico */ object ErrorUtils { - /** The functor `error` used to wrap errors generated by built-ins */ - const val errorWrapperFunctor = "error" + const val ERROR_FUNCTOR = "error" /** - * The error struct, with [errorWrapperFunctor], that can be used in `throw/1` predicate; It will create a + * The error struct, with [ERROR_FUNCTOR], that can be used in `throw/1` predicate; It will create a * struct in the form of `error(`[errorDescription], [customErrorData]`)` * * For example if the [errorDescription] is `instantiation_error` the corresponding error struct, according to prolog standard, will be @@ -24,6 +23,8 @@ object ErrorUtils { * If the error [errorDescription] is composite like `type_error(callable, Goal)` the corresponding struct, according to prolog standard, will be * `error(type_error(callable, Goal), `[customErrorData]`)` */ - fun errorStructOf(errorDescription: Struct, customErrorData: Term = Atom.of("")) = - Struct.of(errorWrapperFunctor, errorDescription, customErrorData) + fun errorStructOf( + errorDescription: Struct, + customErrorData: Term = Atom.of(""), + ) = Struct.of(ERROR_FUNCTOR, errorDescription, customErrorData) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/EvaluationError.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/EvaluationError.kt index e427e78ca..d118379d7 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/EvaluationError.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/EvaluationError.kt @@ -25,22 +25,26 @@ class EvaluationError( cause: Throwable? = null, contexts: Array, @JsName("errorType") val errorType: Type, - extraData: Term? = null + extraData: Term? = null, ) : LogicError(message, cause, contexts, Atom.of(typeFunctor), extraData) { - constructor( message: String? = null, cause: Throwable? = null, context: ExecutionContext, errorType: Type, - extraData: Term? = null + extraData: Term? = null, ) : this(message, cause, arrayOf(context), errorType, extraData) - override fun updateContext(newContext: ExecutionContext, index: Int): EvaluationError = - EvaluationError(message, cause, contexts.setItem(index, newContext), errorType, extraData) + override fun updateContext( + newContext: ExecutionContext, + index: Int, + ): EvaluationError = EvaluationError(message, cause, contexts.setItem(index, newContext), errorType, extraData) override fun updateLastContext(newContext: ExecutionContext): EvaluationError = - updateContext(newContext, contexts.lastIndex) + updateContext( + newContext, + contexts.lastIndex, + ) override fun pushContext(newContext: ExecutionContext): EvaluationError = EvaluationError(message, cause, contexts.addLast(newContext), errorType, extraData) @@ -48,8 +52,8 @@ class EvaluationError( override val type: Struct by lazy { Struct.of(super.type.functor, errorType.toTerm()) } companion object { - /** The evaluation error Struct functor */ + @Suppress("ConstPropertyName", "ktlint:standard:property-naming") const val typeFunctor = "evaluation_error" } @@ -59,7 +63,12 @@ class EvaluationError( * @author Enrico */ enum class Type : TermConvertible { - INT_OVERFLOW, FLOAT_OVERFLOW, UNDERFLOW, ZERO_DIVISOR, UNDEFINED; + INT_OVERFLOW, + FLOAT_OVERFLOW, + UNDERFLOW, + ZERO_DIVISOR, + UNDEFINED, + ; /** A function to transform the type to corresponding [Atom] representation */ override fun toTerm(): Atom = Atom.of(toString()) @@ -67,21 +76,21 @@ class EvaluationError( override fun toString(): String = super.toString().lowercase() companion object { - /** Gets [Type] instance from [term] representation, if possible */ @JsName("fromTerm") @JvmStatic - fun fromTerm(term: Term): Type? = when (term) { - is Atom -> - try { - valueOf(term.value.uppercase()) - } catch (e: IllegalArgumentException) { - null - } catch (e: IllegalStateException) { - null - } - else -> null - } + fun fromTerm(term: Term): Type? = + when (term) { + is Atom -> + try { + valueOf(term.value.uppercase()) + } catch (e: IllegalArgumentException) { + null + } catch (e: IllegalStateException) { + null + } + else -> null + } } } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/ExistenceError.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/ExistenceError.kt index f099c141a..f929baf0f 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/ExistenceError.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/ExistenceError.kt @@ -26,60 +26,71 @@ class ExistenceError( contexts: Array, @JsName("expectedObject") val expectedObject: ObjectType, @JsName("culprit") val culprit: Term, - extraData: Term? = null + extraData: Term? = null, ) : LogicError(message, cause, contexts, Atom.of(typeFunctor), extraData) { - constructor( message: String? = null, cause: Throwable? = null, context: ExecutionContext, expectedObject: ObjectType, actualValue: Term, - extraData: Term? = null + extraData: Term? = null, ) : this(message, cause, arrayOf(context), expectedObject, actualValue, extraData) override val type: Struct by lazy { Struct.of(super.type.functor, expectedObject.toTerm(), culprit) } - override fun updateContext(newContext: ExecutionContext, index: Int): ExistenceError = - ExistenceError(message, cause, contexts.setItem(index, newContext), expectedObject, culprit, extraData) + override fun updateContext( + newContext: ExecutionContext, + index: Int, + ): ExistenceError = + ExistenceError( + message, + cause, + contexts.setItem(index, newContext), + expectedObject, + culprit, + extraData, + ) override fun updateLastContext(newContext: ExecutionContext): ExistenceError = - updateContext(newContext, contexts.lastIndex) + updateContext( + newContext, + contexts.lastIndex, + ) override fun pushContext(newContext: ExecutionContext): ExistenceError = ExistenceError(message, cause, contexts.addLast(newContext), expectedObject, culprit, extraData) companion object { - @JsName("of") @JvmStatic fun of( context: ExecutionContext, expectedType: ObjectType, culprit: Term, - message: String + message: String, ) = ExistenceError( message = message, context = context, expectedObject = expectedType, actualValue = culprit, - extraData = Atom.of(message) + extraData = Atom.of(message), ) @JsName("forProcedure") @JvmStatic fun forProcedure( context: ExecutionContext, - procedure: Signature + procedure: Signature, ) = message( - "Procedure `${procedure.pretty()}` does not exist" + "Procedure `${procedure.pretty()}` does not exist", ) { m, extra -> ExistenceError( message = m, context = context, expectedObject = ObjectType.PROCEDURE, actualValue = procedure.toIndicator(), - extraData = extra + extraData = extra, ) } @@ -87,23 +98,23 @@ class ExistenceError( @JvmStatic fun forSourceSink( context: ExecutionContext, - alias: Atom + alias: Atom, ) = forSourceSink(context, alias.value) @JsName("forSourceSinkWithAlias") @JvmStatic fun forSourceSink( context: ExecutionContext, - alias: String + alias: String, ) = message( - "There exists no stream whose alias is `$alias`" + "There exists no stream whose alias is `$alias`", ) { m, extra -> ExistenceError( message = m, context = context, expectedObject = ObjectType.SOURCE_SINK, actualValue = Atom.of(alias), - extraData = extra + extraData = extra, ) } @@ -111,16 +122,16 @@ class ExistenceError( @JvmStatic fun forStream( context: ExecutionContext, - steamTerm: Struct + steamTerm: Struct, ) = message( - "No such a stream exists: $steamTerm" + "No such a stream exists: $steamTerm", ) { m, extra -> ExistenceError( message = m, context = context, expectedObject = ObjectType.STREAM, actualValue = steamTerm, - extraData = extra + extraData = extra, ) } @@ -128,20 +139,21 @@ class ExistenceError( @JvmStatic fun forResource( context: ExecutionContext, - name: String + name: String, ) = message( - "There exists no such a resource `$name`" + "There exists no such a resource `$name`", ) { m, extra -> ExistenceError( message = m, context = context, expectedObject = ObjectType.RESOURCE, actualValue = Atom.of(name), - extraData = extra + extraData = extra, ) } /** The existence error Struct functor */ + @Suppress("ConstPropertyName", "ktlint:standard:property-naming") const val typeFunctor = "existence_error" } @@ -149,7 +161,6 @@ class ExistenceError( * A class describing the expected type whose absence caused the error */ enum class ObjectType : TermConvertible { - PROCEDURE, SOURCE_SINK, RESOURCE, @@ -157,7 +168,8 @@ class ExistenceError( OOP_ALIAS, OOP_METHOD, OOP_CONSTRUCTOR, - OOP_PROPERTY; + OOP_PROPERTY, + ; /** The type expected string description */ private val type: String by lazy { name.lowercase() } @@ -168,7 +180,6 @@ class ExistenceError( override fun toString(): String = type companion object { - /** Returns the [ObjectType] instance described by [type]; creates a new instance only if [type] was not predefined */ @JsName("of") @JvmStatic @@ -177,10 +188,11 @@ class ExistenceError( /** Gets [ObjectType] instance from [term] representation, if possible */ @JsName("fromTerm") @JvmStatic - fun fromTerm(term: Term): ObjectType? = when (term) { - is Atom -> of(term.value) - else -> null - } + fun fromTerm(term: Term): ObjectType? = + when (term) { + is Atom -> of(term.value) + else -> null + } } } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/InstantiationError.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/InstantiationError.kt index ea2ac8427..297ba9654 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/InstantiationError.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/InstantiationError.kt @@ -24,58 +24,69 @@ class InstantiationError( cause: Throwable? = null, contexts: Array, @JsName("culprit") val culprit: Var = Var.anonymous(), - extraData: Term? = null + extraData: Term? = null, ) : LogicError(message, cause, contexts, Atom.of(typeFunctor), extraData) { - constructor( message: String? = null, cause: Throwable? = null, context: ExecutionContext, culprit: Var = Var.anonymous(), - extraData: Term? = null + extraData: Term? = null, ) : this(message, cause, arrayOf(context), culprit, extraData) - override fun updateContext(newContext: ExecutionContext, index: Int): InstantiationError = - InstantiationError(message, cause, contexts.setItem(index, newContext), culprit, extraData) + override fun updateContext( + newContext: ExecutionContext, + index: Int, + ): InstantiationError = InstantiationError(message, cause, contexts.setItem(index, newContext), culprit, extraData) override fun updateLastContext(newContext: ExecutionContext): InstantiationError = - updateContext(newContext, contexts.lastIndex) + updateContext( + newContext, + contexts.lastIndex, + ) override fun pushContext(newContext: ExecutionContext): InstantiationError = InstantiationError(message, cause, contexts.addLast(newContext), culprit, extraData) companion object { - /** The instantiation error Struct functor */ + @Suppress("ConstPropertyName", "ktlint:standard:property-naming") const val typeFunctor = "instantiation_error" @JsName("forArgument") @JvmStatic - fun forArgument(context: ExecutionContext, procedure: Signature, variable: Var, index: Int? = null) = - message( - "${index?.let { "The $it-th argument" } ?: "The argument"} `${variable.pretty()}` " + - "of ${procedure.pretty()} is unexpectedly not instantiated" - ) { m, extra -> - InstantiationError( - message = m, - context = context, - culprit = variable, - extraData = extra - ) - } + fun forArgument( + context: ExecutionContext, + procedure: Signature, + variable: Var, + index: Int? = null, + ) = message( + "${index?.let { "The $it-th argument" } ?: "The argument"} `${variable.pretty()}` " + + "of ${procedure.pretty()} is unexpectedly not instantiated", + ) { m, extra -> + InstantiationError( + message = m, + context = context, + culprit = variable, + extraData = extra, + ) + } @JsName("forGoal") @JvmStatic - fun forGoal(context: ExecutionContext, procedure: Signature, variable: Var) = - message( - "Uninstantiated subgoal ${variable.pretty()} in procedure ${procedure.pretty()}" - ) { m, extra -> - InstantiationError( - message = m, - context = context, - culprit = variable, - extraData = extra - ) - } + fun forGoal( + context: ExecutionContext, + procedure: Signature, + variable: Var, + ) = message( + "Uninstantiated subgoal ${variable.pretty()} in procedure ${procedure.pretty()}", + ) { m, extra -> + InstantiationError( + message = m, + context = context, + culprit = variable, + extraData = extra, + ) + } } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/MessageError.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/MessageError.kt index 834361625..1b0a5d77a 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/MessageError.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/MessageError.kt @@ -15,39 +15,46 @@ import it.unibo.tuprolog.solve.exception.LogicError * * @author Giovanni */ -class MessageError internal constructor( // TODO: 16/01/2020 test this class +class MessageError internal constructor( message: String? = null, cause: Throwable? = null, contexts: Array, - extraData: Term? = null + extraData: Term? = null, ) : LogicError(message, cause, contexts, Atom.of(typeFunctor), extraData) { - constructor( message: String? = null, cause: Throwable? = null, context: ExecutionContext, - extraData: Term? = null + extraData: Term? = null, ) : this(message, cause, arrayOf(context), extraData) /** The content of this message error */ val content: Term by lazy { extraData ?: errorStruct } - override fun updateContext(newContext: ExecutionContext, index: Int): MessageError = - MessageError(message, cause, contexts.setItem(index, newContext), extraData) + override fun updateContext( + newContext: ExecutionContext, + index: Int, + ): MessageError = MessageError(message, cause, contexts.setItem(index, newContext), extraData) override fun updateLastContext(newContext: ExecutionContext): MessageError = - updateContext(newContext, contexts.lastIndex) + updateContext( + newContext, + contexts.lastIndex, + ) override fun pushContext(newContext: ExecutionContext): MessageError = MessageError(message, cause, contexts.addLast(newContext), extraData) companion object { - /** The message error Struct functor */ + @Suppress("ConstPropertyName", "ktlint:standard:property-naming") const val typeFunctor = "" /** Factory method to create a [MessageError] */ - fun of(content: Term, context: ExecutionContext, cause: Throwable? = null) = - MessageError(content.toString(), cause, context, content) + fun of( + content: Term, + context: ExecutionContext, + cause: Throwable? = null, + ) = MessageError(content.toString(), cause, context, content) } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/PermissionError.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/PermissionError.kt index 8508d9c2a..dc9394b31 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/PermissionError.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/PermissionError.kt @@ -28,9 +28,8 @@ class PermissionError( @JsName("operation") val operation: Operation, @JsName("permission") val permission: Permission, @JsName("culprit") val culprit: Term, - extraData: Term? = null + extraData: Term? = null, ) : LogicError(message, cause, contexts, Atom.of(typeFunctor), extraData) { - constructor( message: String? = null, cause: Throwable? = null, @@ -38,14 +37,28 @@ class PermissionError( operation: Operation, permission: Permission, culprit: Term, - extraData: Term? = null + extraData: Term? = null, ) : this(message, cause, arrayOf(context), operation, permission, culprit, extraData) - override fun updateContext(newContext: ExecutionContext, index: Int): PermissionError = - PermissionError(message, cause, contexts.setItem(index, newContext), operation, permission, culprit, extraData) + override fun updateContext( + newContext: ExecutionContext, + index: Int, + ): PermissionError = + PermissionError( + message, + cause, + contexts.setItem(index, newContext), + operation, + permission, + culprit, + extraData, + ) override fun updateLastContext(newContext: ExecutionContext): PermissionError = - updateContext(newContext, contexts.lastIndex) + updateContext( + newContext, + contexts.lastIndex, + ) override fun pushContext(newContext: ExecutionContext): PermissionError = PermissionError(message, cause, contexts.addLast(newContext), operation, permission, culprit, extraData) @@ -55,12 +68,11 @@ class PermissionError( super.type.functor, operation.toTerm(), permission.toTerm(), - culprit + culprit, ) } companion object { - @JsName("of") @JvmStatic fun of( @@ -68,22 +80,24 @@ class PermissionError( procedure: Signature, operation: Operation, permission: Permission, - culprit: Term - ): PermissionError = message( - "Permission error while executing ${procedure.pretty()}: " + - "operation of type `$operation` is not possible on $permission: ${culprit.pretty()}" - ) { m, extra -> - PermissionError( - message = m, - context = context, - operation = operation, - permission = permission, - culprit = culprit, - extraData = extra - ) - } + culprit: Term, + ): PermissionError = + message( + "Permission error while executing ${procedure.pretty()}: " + + "operation of type `$operation` is not possible on $permission: ${culprit.pretty()}", + ) { m, extra -> + PermissionError( + message = m, + context = context, + operation = operation, + permission = permission, + culprit = culprit, + extraData = extra, + ) + } /** The permission error Struct functor */ + @Suppress("ConstPropertyName", "ktlint:standard:property-naming") const val typeFunctor = "permission_error" } @@ -100,7 +114,8 @@ class PermissionError( MODIFY, OPEN, OUTPUT, - REPOSITION; + REPOSITION, + ; @JsName("operation") val operation: String by lazy { this.name.lowercase() } @@ -111,7 +126,6 @@ class PermissionError( override fun toString(): String = operation companion object { - /** Returns the [Operation] instance described by [operation]; creates a new instance only if [operation] was not predefined */ @JsName("of") @JvmStatic @@ -120,10 +134,11 @@ class PermissionError( /** Gets [Operation] instance from [term] representation, if possible */ @JsName("fromTerm") @JvmStatic - fun fromTerm(term: Term): Operation? = when (term) { - is Atom -> of(term.value) - else -> null - } + fun fromTerm(term: Term): Operation? = + when (term) { + is Atom -> of(term.value) + else -> null + } } } @@ -140,7 +155,8 @@ class PermissionError( STATIC_PROCEDURE, OOP_METHOD, STREAM, - TEXT_STREAM; + TEXT_STREAM, + ; @JsName("permission") val permission: String by lazy { this.name.lowercase() } @@ -151,7 +167,6 @@ class PermissionError( override fun toString(): String = permission companion object { - /** Returns the [Permission] instance described by [permission]; creates a new instance only if [permission] was not predefined */ @JsName("of") @JvmStatic @@ -160,10 +175,11 @@ class PermissionError( /** Gets [Permission] instance from [term] representation, if possible */ @JsName("fromTerm") @JvmStatic - fun fromTerm(term: Term): Permission? = when (term) { - is Atom -> of(term.value) - else -> null - } + fun fromTerm(term: Term): Permission? = + when (term) { + is Atom -> of(term.value) + else -> null + } } } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/RepresentationError.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/RepresentationError.kt index 2950d1f3d..dd3b2f4c5 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/RepresentationError.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/RepresentationError.kt @@ -25,22 +25,26 @@ class RepresentationError( cause: Throwable? = null, contexts: Array, @JsName("limit") val limit: Limit, - extraData: Term? = null + extraData: Term? = null, ) : LogicError(message, cause, contexts, Atom.of(typeFunctor), extraData) { - constructor( message: String? = null, cause: Throwable? = null, context: ExecutionContext, limit: Limit, - extraData: Term? = null + extraData: Term? = null, ) : this(message, cause, arrayOf(context), limit, extraData) - override fun updateContext(newContext: ExecutionContext, index: Int): RepresentationError = - RepresentationError(message, cause, contexts.setItem(index, newContext), limit, extraData) + override fun updateContext( + newContext: ExecutionContext, + index: Int, + ): RepresentationError = RepresentationError(message, cause, contexts.setItem(index, newContext), limit, extraData) override fun updateLastContext(newContext: ExecutionContext): RepresentationError = - updateContext(newContext, contexts.lastIndex) + updateContext( + newContext, + contexts.lastIndex, + ) override fun pushContext(newContext: ExecutionContext): RepresentationError = RepresentationError(message, cause, contexts.addLast(newContext), limit, extraData) @@ -48,7 +52,7 @@ class RepresentationError( override val type: Struct by lazy { Struct.of( super.type.functor, - limit.toTerm() + limit.toTerm(), ) } @@ -59,21 +63,23 @@ class RepresentationError( context: ExecutionContext, signature: Signature, limit: Limit, - cause: Throwable? = null - ): RepresentationError = message( - "Reached representation limit while executing `${signature.pretty()}`: $limit" + - cause?.message?.let { ". $it" } - ) { m, extra -> - RepresentationError( - message = m, - context = context, - limit = limit, - extraData = extra, - cause = cause - ) - } + cause: Throwable? = null, + ): RepresentationError = + message( + "Reached representation limit while executing `${signature.pretty()}`: $limit" + + cause?.message?.let { ". $it" }, + ) { m, extra -> + RepresentationError( + message = m, + context = context, + limit = limit, + extraData = extra, + cause = cause, + ) + } /** The permission error Struct functor */ + @Suppress("ConstPropertyName", "ktlint:standard:property-naming") const val typeFunctor = "representation_error" } @@ -88,7 +94,8 @@ class RepresentationError( MAX_INTEGER, MIN_INTEGER, OOP_OBJECT, - TOO_MANY_VARIABLES; + TOO_MANY_VARIABLES, + ; @JsName("limit") val limit: String by lazy { this.name.lowercase() } @@ -99,7 +106,6 @@ class RepresentationError( override fun toString(): String = limit companion object { - /** Returns the [Limit] instance described by [limit]; creates a new instance only if [limit] was not predefined */ @JsName("of") @JvmStatic @@ -108,10 +114,11 @@ class RepresentationError( /** Gets [Limit] instance from [term] representation, if possible */ @JsName("fromTerm") @JvmStatic - fun fromTerm(term: Term): Limit? = when (term) { - is Atom -> of(term.value) - else -> null - } + fun fromTerm(term: Term): Limit? = + when (term) { + is Atom -> of(term.value) + else -> null + } } } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/SyntaxError.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/SyntaxError.kt index 77c6604cb..f3b09e7cc 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/SyntaxError.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/SyntaxError.kt @@ -11,38 +11,45 @@ class SyntaxError constructor( message: String? = null, cause: Throwable? = null, contexts: Array, - extraData: Term? = null + extraData: Term? = null, ) : LogicError(message, cause, contexts, Atom.of(typeFunctor), extraData) { - constructor( message: String? = null, cause: Throwable? = null, context: ExecutionContext, - extraData: Term? = null + extraData: Term? = null, ) : this(message, cause, arrayOf(context), extraData) - override fun updateContext(newContext: ExecutionContext, index: Int): SyntaxError = - SyntaxError(message, cause, contexts.setItem(index, newContext), extraData) + override fun updateContext( + newContext: ExecutionContext, + index: Int, + ): SyntaxError = SyntaxError(message, cause, contexts.setItem(index, newContext), extraData) override fun updateLastContext(newContext: ExecutionContext): SyntaxError = - updateContext(newContext, contexts.lastIndex) + updateContext( + newContext, + contexts.lastIndex, + ) override fun pushContext(newContext: ExecutionContext): SyntaxError = SyntaxError(message, cause, contexts.addLast(newContext), extraData) companion object { - /** The system error Struct functor */ + @Suppress("ConstPropertyName", "ktlint:standard:property-naming") const val typeFunctor = "syntax_error" @JsName("of") @JvmStatic - fun of(context: ExecutionContext, message: String): SyntaxError = + fun of( + context: ExecutionContext, + message: String, + ): SyntaxError = message("Syntax error: $message") { m, extra -> SyntaxError( message = m, context = context, - extraData = extra + extraData = extra, ) } @@ -53,13 +60,13 @@ class SyntaxError constructor( input: String, row: Int, column: Int, - message: String + message: String, ): SyntaxError = message("Syntax error at $row:$column while parsing `$input`: $message") { m, extra -> SyntaxError( message = m, context = context, - extraData = extra + extraData = extra, ) } @@ -71,18 +78,18 @@ class SyntaxError constructor( index: Int, row: Int, column: Int, - message: String + message: String, ): SyntaxError = message( """ |Syntax error at $row:$column while parsing clause $index: $message | ${errorDetector(input, row, column, message).replace("\n", "\n| ")} - """.trimMargin() + """.trimMargin(), ) { m, extra -> SyntaxError( message = m, context = context, - extraData = extra + extraData = extra, ) } @@ -98,11 +105,21 @@ class SyntaxError constructor( @JsName("errorDetector") @JvmStatic - fun errorDetector(text: String, line: Int, column: Int, message: String? = null): String { + fun errorDetector( + text: String, + line: Int, + column: Int, + message: String? = null, + ): String { val lines = text.lineSequence().drop(line - 1).take(1).toList() if (lines.isEmpty()) return text val padding = kotlin.math.max(line.log10(), (line - 1).log10()) - val prefix = if (line > 1) { "${(line - 1).toString().padStart(padding)}: ...\n" } else "" + val prefix = + if (line > 1) { + "${(line - 1).toString().padStart(padding)}: ...\n" + } else { + "" + } val culprit = "${line.toString().padStart(padding)}: ${lines.last()}\n" val detector = "".padStart(padding + column + 1) + "^ " + (message ?: "") return prefix + culprit + detector diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/SystemError.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/SystemError.kt index 44601763d..60ae53982 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/SystemError.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/SystemError.kt @@ -21,50 +21,60 @@ class SystemError constructor( message: String? = null, cause: Throwable? = null, contexts: Array, - extraData: Term? = null + extraData: Term? = null, ) : LogicError(message, cause, contexts, Atom.of(typeFunctor), extraData) { - constructor( message: String? = null, cause: Throwable? = null, context: ExecutionContext, - extraData: Term? = null + extraData: Term? = null, ) : this(message, cause, arrayOf(context), extraData) - override fun updateContext(newContext: ExecutionContext, index: Int): SystemError = - SystemError(message, cause, contexts.setItem(index, newContext), extraData) + override fun updateContext( + newContext: ExecutionContext, + index: Int, + ): SystemError = SystemError(message, cause, contexts.setItem(index, newContext), extraData) override fun updateLastContext(newContext: ExecutionContext): SystemError = - updateContext(newContext, contexts.lastIndex) + updateContext( + newContext, + contexts.lastIndex, + ) override fun pushContext(newContext: ExecutionContext): SystemError = SystemError(message, cause, contexts.addLast(newContext), extraData) companion object { - /** The system error Struct functor */ + @Suppress("ConstPropertyName", "ktlint:standard:property-naming") const val typeFunctor = "system_error" @JsName("forUncaughtKtException") @JvmStatic - fun forUncaughtException(context: ExecutionContext, exception: Throwable): SystemError = + fun forUncaughtException( + context: ExecutionContext, + exception: Throwable, + ): SystemError = message("Uncaught exception `${exception::class.simpleName}: ${exception.message}`") { m, extra -> SystemError( message = m, context = context, extraData = extra, - cause = exception + cause = exception, ) } @JsName("forUncaughtException") @JvmStatic - fun forUncaughtException(context: ExecutionContext, exception: Term): SystemError = + fun forUncaughtException( + context: ExecutionContext, + exception: Term, + ): SystemError = message("Uncaught exception `${exception.pretty()}`") { m, extra -> SystemError( message = m, context = context, - extraData = extra + extraData = extra, ) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/TypeError.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/TypeError.kt index 2209effee..0770ba383 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/TypeError.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/error/TypeError.kt @@ -29,23 +29,27 @@ class TypeError( contexts: Array, @JsName("expectedType") val expectedType: Expected, @JsName("culprit") val culprit: Term, - extraData: Term? = null + extraData: Term? = null, ) : LogicError(message, cause, contexts, Atom.of(typeFunctor), extraData) { - constructor( message: String? = null, cause: Throwable? = null, context: ExecutionContext, expectedType: Expected, culprit: Term, - extraData: Term? = null + extraData: Term? = null, ) : this(message, cause, arrayOf(context), expectedType, culprit, extraData) - override fun updateContext(newContext: ExecutionContext, index: Int): TypeError = - TypeError(message, cause, contexts.setItem(index, newContext), expectedType, culprit, extraData) + override fun updateContext( + newContext: ExecutionContext, + index: Int, + ): TypeError = TypeError(message, cause, contexts.setItem(index, newContext), expectedType, culprit, extraData) override fun updateLastContext(newContext: ExecutionContext): TypeError = - updateContext(newContext, contexts.lastIndex) + updateContext( + newContext, + contexts.lastIndex, + ) override fun pushContext(newContext: ExecutionContext): TypeError = TypeError(message, cause, contexts.addLast(newContext), expectedType, culprit, extraData) @@ -53,21 +57,20 @@ class TypeError( override val type: Struct by lazy { Struct.of(super.type.functor, expectedType.toTerm(), culprit) } companion object { - @JsName("of") @JvmStatic fun of( context: ExecutionContext, expectedType: Expected, actualValue: Term, - message: String + message: String, ) = message(message) { m, extra -> TypeError( message = m, context = context, expectedType = expectedType, culprit = actualValue, - extraData = extra + extraData = extra, ) } @@ -78,18 +81,18 @@ class TypeError( procedure: Signature, expectedType: Expected, culprit: Term, - index: Int? = null + index: Int? = null, ) = message( (index?.let { "The $it-th argument" } ?: "An argument") + " of `${procedure.pretty()}` should be a list of `$expectedType`, " + - "but `${culprit.pretty()}` has been provided instead" + "but `${culprit.pretty()}` has been provided instead", ) { m, extra -> TypeError( message = m, context = context, expectedType = expectedType, culprit = culprit, - extraData = extra + extraData = extra, ) } @@ -100,18 +103,18 @@ class TypeError( procedure: Signature, expectedType: Expected, culprit: Term, - index: Int? = null + index: Int? = null, ) = message( (index?.let { "The $it-th argument" } ?: "An argument") + " of `${procedure.pretty()}` should be a `$expectedType`, " + - "but `${culprit.pretty()}` has been provided instead" + "but `${culprit.pretty()}` has been provided instead", ) { m, extra -> TypeError( message = m, context = context, expectedType = expectedType, culprit = culprit, - extraData = extra + extraData = extra, ) } @@ -121,20 +124,21 @@ class TypeError( context: ExecutionContext, procedure: Signature, expectedType: Expected, - culprit: Term + culprit: Term, ) = message( - "Subgoal `${culprit.pretty()}` of ${procedure.pretty()} is not a $expectedType term" + "Subgoal `${culprit.pretty()}` of ${procedure.pretty()} is not a $expectedType term", ) { m, extra -> TypeError( message = m, context = context, expectedType = expectedType, culprit = culprit, - extraData = extra + extraData = extra, ) } /** The type error Struct functor */ + @Suppress("ConstPropertyName", "ktlint:standard:property-naming") const val typeFunctor = "type_error" } @@ -164,7 +168,8 @@ class TypeError( REFERENCE, TYPE_REFERENCE, URL, - VARIABLE; + VARIABLE, + ; /** * The type expected string description @@ -185,10 +190,11 @@ class TypeError( /** Gets [Expected] instance from [term] representation, if possible */ @JsName("fromTerm") @JvmStatic - fun fromTerm(term: Term): Expected? = when (term) { - is Atom -> of(term.value) - else -> null - } + fun fromTerm(term: Term): Expected? = + when (term) { + is Atom -> of(term.value) + else -> null + } } } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/warning/InitializationIssue.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/warning/InitializationIssue.kt index a9ab3e6e1..f7118cfb2 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/warning/InitializationIssue.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/warning/InitializationIssue.kt @@ -9,20 +9,24 @@ import kotlin.js.JsName class InitializationIssue( @JsName("goal") val goal: Struct, override val cause: ResolutionException? = null, - contexts: Array + contexts: Array, ) : Warning("Error while solving initialization goal $goal: ${cause ?: "failure"}", cause, contexts) { - constructor( goal: Struct, cause: ResolutionException? = null, - context: ExecutionContext + context: ExecutionContext, ) : this(goal, cause, arrayOf(context)) - override fun updateContext(newContext: ExecutionContext, index: Int): InitializationIssue = - InitializationIssue(goal, cause, contexts.setItem(index, newContext)) + override fun updateContext( + newContext: ExecutionContext, + index: Int, + ): InitializationIssue = InitializationIssue(goal, cause, contexts.setItem(index, newContext)) override fun updateLastContext(newContext: ExecutionContext): InitializationIssue = - updateContext(newContext, contexts.lastIndex) + updateContext( + newContext, + contexts.lastIndex, + ) override fun pushContext(newContext: ExecutionContext): InitializationIssue = InitializationIssue(goal, cause, contexts.addLast(newContext)) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/warning/MissingPredicate.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/warning/MissingPredicate.kt index df8e0c8f1..876920e62 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/warning/MissingPredicate.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/exception/warning/MissingPredicate.kt @@ -8,25 +8,29 @@ import kotlin.js.JsName class MissingPredicate( cause: Throwable?, contexts: Array, - @JsName("signature") val signature: Signature + @JsName("signature") val signature: Signature, ) : Warning("No such a predicate: ${signature.toIndicator()}", cause, contexts) { - constructor( cause: Throwable?, context: ExecutionContext, - signature: Signature + signature: Signature, ) : this(cause, arrayOf(context), signature) constructor( context: ExecutionContext, - signature: Signature + signature: Signature, ) : this(null, arrayOf(context), signature) - override fun updateContext(newContext: ExecutionContext, index: Int): MissingPredicate = - MissingPredicate(cause, contexts.setItem(index, newContext), signature) + override fun updateContext( + newContext: ExecutionContext, + index: Int, + ): MissingPredicate = MissingPredicate(cause, contexts.setItem(index, newContext), signature) override fun updateLastContext(newContext: ExecutionContext): MissingPredicate = - updateContext(newContext, contexts.lastIndex) + updateContext( + newContext, + contexts.lastIndex, + ) override fun pushContext(newContext: ExecutionContext): MissingPredicate = MissingPredicate(cause, contexts.addLast(newContext), signature) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/DoubleQuotes.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/DoubleQuotes.kt index 49b90e98a..f98947766 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/DoubleQuotes.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/DoubleQuotes.kt @@ -6,7 +6,6 @@ import kotlin.jvm.JvmField @Suppress("MemberVisibilityCanBePrivate") object DoubleQuotes : NotableFlag { - @JvmField val ATOM = Atom.of("atom") diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/FlagStore.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/FlagStore.kt index 744705de1..ff7532423 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/FlagStore.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/FlagStore.kt @@ -7,21 +7,23 @@ import kotlin.jvm.JvmStatic /** A storage for flags and their values */ data class FlagStore(private val flags: Map) : Map by flags { - @JsName("get") - operator fun get(notableFlag: NotableFlag): Term? = - this[notableFlag.name] + operator fun get(notableFlag: NotableFlag): Term? = this[notableFlag.name] @JsName("set") - operator fun set(name: String, value: Term): FlagStore = - plus(name, value) + operator fun set( + name: String, + value: Term, + ): FlagStore = plus(name, value) @JsName("setNotableToDefault") - fun set(notableFlag: NotableFlag): FlagStore = - set(notableFlag.name, notableFlag.defaultValue) + fun set(notableFlag: NotableFlag): FlagStore = set(notableFlag.name, notableFlag.defaultValue) @JsName("setNotable") - operator fun set(notableFlag: NotableFlag, value: Term): FlagStore = + operator fun set( + notableFlag: NotableFlag, + value: Term, + ): FlagStore = if (value in notableFlag.admissibleValues) { set(notableFlag.name, value) } else { @@ -29,28 +31,26 @@ data class FlagStore(private val flags: Map) : Map b } @JsName("plus") - fun plus(name: String, value: Term): FlagStore = - this + (name to value) + fun plus( + name: String, + value: Term, + ): FlagStore = this + (name to value) @JsName("plusPair") - operator fun plus(flagValue: Pair): FlagStore = - FlagStore(this.flags + mapOf(flagValue)) + operator fun plus(flagValue: Pair): FlagStore = FlagStore(this.flags + mapOf(flagValue)) @JsName("plusNotable") operator fun plus(notableFlagValue: NotableFlag): FlagStore = FlagStore(this.flags + mapOf(notableFlagValue.toPair())) @JsName("plusMap") - operator fun plus(flags: Map): FlagStore = - FlagStore(this.flags + flags) + operator fun plus(flags: Map): FlagStore = FlagStore(this.flags + flags) @JsName("minus") - operator fun minus(flagName: String): FlagStore = - FlagStore(this.flags - flagName) + operator fun minus(flagName: String): FlagStore = FlagStore(this.flags - flagName) @JsName("minusMany") - operator fun minus(flagNames: Iterable): FlagStore = - FlagStore(this.flags - flagNames) + operator fun minus(flagNames: Iterable): FlagStore = FlagStore(this.flags - flagNames) companion object { @JvmField @@ -61,13 +61,14 @@ data class FlagStore(private val flags: Map) : Map b fun of(vararg flagValues: Pair) = FlagStore(mapOf(*flagValues)) @JvmField - val DEFAULT = FlagStore.of( - Unknown, - MaxArity, - DoubleQuotes, - LastCallOptimization, - TrackVariables - ) + val DEFAULT = + FlagStore.of( + Unknown, + MaxArity, + DoubleQuotes, + LastCallOptimization, + TrackVariables, + ) @JsName("empty") @JvmStatic diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/FlagsUtils.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/FlagsUtils.kt index 48b16f542..65e7e8c8d 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/FlagsUtils.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/FlagsUtils.kt @@ -5,7 +5,9 @@ package it.unibo.tuprolog.solve.flags import it.unibo.tuprolog.core.Term import kotlin.jvm.JvmName -fun flag(notableFlag: T, f: T.() -> Term): Pair = - notableFlag.let { it.name to it.f() } +fun flag( + notableFlag: T, + f: T.() -> Term, +): Pair = notableFlag.let { it.name to it.f() } operator fun T.invoke(f: T.() -> Term): Pair = flag(this, f) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/LastCallOptimization.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/LastCallOptimization.kt index e12a960f2..8a9c0337a 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/LastCallOptimization.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/LastCallOptimization.kt @@ -6,7 +6,6 @@ import kotlin.jvm.JvmField @Suppress("MemberVisibilityCanBePrivate") object LastCallOptimization : NotableFlag { - @JvmField val ON = Atom.of("on") diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/MaxArity.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/MaxArity.kt index a345e03b8..c85523933 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/MaxArity.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/MaxArity.kt @@ -4,7 +4,6 @@ import it.unibo.tuprolog.core.Integer @Suppress("MemberVisibilityCanBePrivate") object MaxArity : NotableFlag { - override val name: String = "max_arity" override val defaultValue: Integer = Integer.of(Int.MAX_VALUE) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/NotableFlag.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/NotableFlag.kt index 748371c8d..8a74bf97f 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/NotableFlag.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/NotableFlag.kt @@ -5,7 +5,6 @@ import kotlin.js.JsName import kotlin.jvm.JvmStatic interface NotableFlag { - @JsName("name") val name: String @@ -20,20 +19,19 @@ interface NotableFlag { val admissibleValues: Sequence @JsName("isAdmissibleValue") - fun isAdmissibleValue(value: Term): Boolean = - value in admissibleValues + fun isAdmissibleValue(value: Term): Boolean = value in admissibleValues @JsName("toPair") - fun toPair(): Pair = - this to defaultValue + fun toPair(): Pair = this to defaultValue @JsName("to") infix fun to(value: Term): Pair = - name to value.also { - require(isAdmissibleValue(it)) { - "$value is not an admissible value for flag $name" + name to + value.also { + require(isAdmissibleValue(it)) { + "$value is not an admissible value for flag $name" + } } - } companion object { @JsName("fromName") @@ -43,7 +41,7 @@ interface NotableFlag { DoubleQuotes, LastCallOptimization, MaxArity, - Unknown + Unknown, ).firstOrNull { it.name == name } } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/TrackVariables.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/TrackVariables.kt index 246ca32dd..03989fed0 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/TrackVariables.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/TrackVariables.kt @@ -6,7 +6,6 @@ import kotlin.jvm.JvmField @Suppress("MemberVisibilityCanBePrivate") object TrackVariables : NotableFlag { - @JvmField val ON = Atom.of("on") diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/Unknown.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/Unknown.kt index 6a845ff96..4d0623a5c 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/Unknown.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/flags/Unknown.kt @@ -6,7 +6,6 @@ import kotlin.jvm.JvmField @Suppress("MemberVisibilityCanBePrivate") object Unknown : NotableFlag { - @JvmField val ERROR = Atom.of("error") diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/AbstractEvaluator.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/AbstractEvaluator.kt index 04d6825db..e8e4f7992 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/AbstractEvaluator.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/AbstractEvaluator.kt @@ -12,9 +12,8 @@ import it.unibo.tuprolog.solve.primitive.Solve abstract class AbstractEvaluator( protected val request: Solve.Request, - protected val index: Int? + protected val index: Int?, ) : TermVisitor { - /** Shorthand to access context loaded functions */ @Suppress("MemberVisibilityCanBePrivate") protected val loadedFunctions by lazy { request.context.libraries.functions } @@ -24,29 +23,31 @@ abstract class AbstractEvaluator( override fun defaultValue(term: Term): T = casting { term } - override fun visitTerm(term: Term): T = - defaultValue(term.apply { staticCheck() }) + override fun visitTerm(term: Term): T = defaultValue(term.apply { staticCheck() }) - override fun visitAtom(term: Atom): T = casting { - visitStruct(term) - } + override fun visitAtom(term: Atom): T = + casting { + visitStruct(term) + } - override fun visitIndicator(term: Indicator): T = casting { - visitStruct(term) - } + override fun visitIndicator(term: Indicator): T = + casting { + visitStruct(term) + } - override fun visitStruct(term: Struct): T = casting { - val functionSignature = term.extractSignature() - loadedFunctions[functionSignature]?.let { function -> - function.compute( - Compute.Request( - functionSignature, - term.argsSequence.map { it.accept(this).apply { dynamicCheck(term) } }.toList(), - request.context - ) - ).result - } ?: unevaluable(term) - } + override fun visitStruct(term: Struct): T = + casting { + val functionSignature = term.extractSignature() + loadedFunctions[functionSignature]?.let { function -> + function.compute( + Compute.Request( + functionSignature, + term.argsSequence.map { it.accept(this).apply { dynamicCheck(term) } }.toList(), + request.context, + ), + ).result + } ?: unevaluable(term) + } open fun unevaluable(struct: Struct): Term = throw TypeError.forArgument(request.context, request.signature, TypeError.Expected.EVALUABLE, struct, index) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/ArithmeticEvaluator.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/ArithmeticEvaluator.kt index 63e2bafd2..1c47c38a3 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/ArithmeticEvaluator.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/ArithmeticEvaluator.kt @@ -31,7 +31,6 @@ import it.unibo.tuprolog.solve.stdlib.function.BitwiseRightShift */ class ArithmeticEvaluator(request: Solve.Request, index: Int?) : AbstractEvaluator(request, index) { - constructor(request: Solve.Request) : this(request, null) /** This method implements all the check required by the Prolog Standard for expressions to be considered valid (statically) */ @@ -60,7 +59,6 @@ class ArithmeticEvaluator(request: Solve.Request, index } companion object { - /** All allowed arithmetic signatures in Prolog expressions */ val allowedArithmeticSignatures by lazy { CommonBuiltins.functions.map { (signature, _) -> signature } @@ -73,7 +71,7 @@ class ArithmeticEvaluator(request: Solve.Request, index BitwiseComplement, BitwiseLeftShift, BitwiseOr, - BitwiseRightShift + BitwiseRightShift, ).map { it.signature } } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/ArithmeticUtils.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/ArithmeticUtils.kt index 801e39e65..ee6a4f6ce 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/ArithmeticUtils.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/ArithmeticUtils.kt @@ -8,16 +8,20 @@ import it.unibo.tuprolog.solve.primitive.Solve private fun Term.eval( request: Solve.Request, index: Int? = null, - evaluator: (Solve.Request, Int?) -> AbstractEvaluator + evaluator: (Solve.Request, Int?) -> AbstractEvaluator, ): T = accept(evaluator(request, index)) private fun Term.eval( request: Solve.Request, - evaluator: (Solve.Request) -> AbstractEvaluator + evaluator: (Solve.Request) -> AbstractEvaluator, ): T = accept(evaluator(request)) -fun Term.evalAsExpression(request: Solve.Request<*>, index: Int? = null): Term = - eval(request, index, ::ExpressionEvaluator) +fun Term.evalAsExpression( + request: Solve.Request<*>, + index: Int? = null, +): Term = eval(request, index, ::ExpressionEvaluator) -fun Term.evalAsArithmeticExpression(request: Solve.Request<*>, index: Int? = null): Numeric = - eval(request, index, ::ArithmeticEvaluator) +fun Term.evalAsArithmeticExpression( + request: Solve.Request<*>, + index: Int? = null, +): Numeric = eval(request, index, ::ArithmeticEvaluator) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/BinaryMathFunction.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/BinaryMathFunction.kt index 83a255df9..3bfe8ac9c 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/BinaryMathFunction.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/BinaryMathFunction.kt @@ -16,32 +16,48 @@ import it.unibo.tuprolog.solve.exception.error.TypeError * @author Enrico */ abstract class BinaryMathFunction(name: String) : MathFunction(name, 2) { - - override fun uncheckedImplementation(request: Compute.Request): Compute.Response = with(request) { - val term1 = arguments.first() - val term2 = arguments.last() - replyWith( - when { - term1 is Integer && term2 is Integer -> mathFunction(term1, term2, context) - term1 is Real && term2 is Integer -> mathFunction(term1, term2, context) - term1 is Integer && term2 is Real -> mathFunction(term1, term2, context) - term1 is Real && term2 is Real -> mathFunction(term1, term2, context) - term1 is Var -> throw InstantiationError.forArgument(context, signature, term1, 0) - term2 is Var -> throw InstantiationError.forArgument(context, signature, term2, 1) - else -> throw TypeError.forArgument(context, signature, TypeError.Expected.NUMBER, term1, 0) - } - ) - } + override fun uncheckedImplementation(request: Compute.Request): Compute.Response = + with(request) { + val term1 = arguments.first() + val term2 = arguments.last() + replyWith( + when { + term1 is Integer && term2 is Integer -> mathFunction(term1, term2, context) + term1 is Real && term2 is Integer -> mathFunction(term1, term2, context) + term1 is Integer && term2 is Real -> mathFunction(term1, term2, context) + term1 is Real && term2 is Real -> mathFunction(term1, term2, context) + term1 is Var -> throw InstantiationError.forArgument(context, signature, term1, 0) + term2 is Var -> throw InstantiationError.forArgument(context, signature, term2, 1) + else -> throw TypeError.forArgument(context, signature, TypeError.Expected.NUMBER, term1, 0) + }, + ) + } /** The actual math function implementation, for [Integer]s */ - protected abstract fun mathFunction(integer1: Integer, integer2: Integer, context: ExecutionContext): Numeric + protected abstract fun mathFunction( + integer1: Integer, + integer2: Integer, + context: ExecutionContext, + ): Numeric /** The actual math function implementation, for [Real] and [Integer] */ - protected abstract fun mathFunction(real: Real, integer: Integer, context: ExecutionContext): Numeric + protected abstract fun mathFunction( + real: Real, + integer: Integer, + context: ExecutionContext, + ): Numeric /** The actual math function implementation, for [Integer] and [Real] */ - protected abstract fun mathFunction(integer: Integer, real: Real, context: ExecutionContext): Numeric + protected abstract fun mathFunction( + integer: Integer, + real: Real, + context: ExecutionContext, + ): Numeric /** The actual math function implementation, for [Real]s */ - protected abstract fun mathFunction(real1: Real, real2: Real, context: ExecutionContext): Numeric + protected abstract fun mathFunction( + real1: Real, + real2: Real, + context: ExecutionContext, + ): Numeric } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/Compute.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/Compute.kt index bd4db1e60..983650925 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/Compute.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/Compute.kt @@ -11,7 +11,6 @@ import kotlin.js.JsName /** A base class for Computation requests and responses */ sealed class Compute { - /** Class representing a Request to be full-filled by the Expression evaluator */ data class Request( /** Signature of the function to be executed in this [Request] */ @@ -28,19 +27,27 @@ sealed class Compute { val requestIssuingInstant: TimeInstant = currentTimeInstant(), /** The execution max duration after which the computation should end, because no more useful */ @JsName("executionMaxDuration") - val executionMaxDuration: TimeDuration = TimeDuration.MAX_VALUE + val executionMaxDuration: TimeDuration = TimeDuration.MAX_VALUE, ) : Compute() { init { when { - signature.vararg -> require(arguments.count() >= signature.arity) { - "Trying to create Compute.Request of signature `$signature` with not enough arguments ${arguments.toList()}" - } - else -> require(arguments.count() == signature.arity) { - "Trying to create Compute.Request of signature `$signature` with wrong number of arguments ${arguments.toList()}" - } + signature.vararg -> + require(arguments.count() >= signature.arity) { + "Trying to create Compute.Request of signature `$signature` " + + "with not enough arguments ${arguments.toList()}" + } + else -> + require(arguments.count() == signature.arity) { + "Trying to create Compute.Request of signature `$signature` " + + "with wrong number of arguments ${arguments.toList()}" + } + } + require(requestIssuingInstant >= 0) { + "The request issuing instant can't be negative: $requestIssuingInstant" + } + require(executionMaxDuration >= 0) { + "The execution max duration can't be negative: $executionMaxDuration" } - require(requestIssuingInstant >= 0) { "The request issuing instant can't be negative: $requestIssuingInstant" } - require(executionMaxDuration >= 0) { "The execution max duration can't be negative: $executionMaxDuration" } } /** The current expression [Struct] of this request */ @@ -56,6 +63,6 @@ sealed class Compute { data class Response( /** The result of evaluation process */ @JsName("result") - val result: Term + val result: Term, ) : Compute() } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/ExpressionEvaluator.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/ExpressionEvaluator.kt index 3b4e32154..c90b69c29 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/ExpressionEvaluator.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/ExpressionEvaluator.kt @@ -14,5 +14,5 @@ import it.unibo.tuprolog.solve.primitive.Solve */ class ExpressionEvaluator( request: Solve.Request, - index: Int? = null + index: Int? = null, ) : AbstractEvaluator(request, index) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/ExpressionReducer.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/ExpressionReducer.kt index 5ce49a32e..f1e9bec62 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/ExpressionReducer.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/ExpressionReducer.kt @@ -15,7 +15,7 @@ import it.unibo.tuprolog.solve.primitive.Solve */ class ExpressionReducer( request: Solve.Request, - index: Int? = null + index: Int? = null, ) : AbstractEvaluator(request, index) { override fun unevaluable(struct: Struct): Term { return if (struct.arity > 0) { diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/FunctionWrapper.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/FunctionWrapper.kt index f5388cfa1..9fd2b6955 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/FunctionWrapper.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/FunctionWrapper.kt @@ -10,7 +10,6 @@ import it.unibo.tuprolog.solve.Signature * @author Enrico */ abstract class FunctionWrapper : AbstractWrapper { - constructor(signature: Signature) : super(signature) constructor(name: String, arity: Int, vararg: Boolean = false) : super(name, arity, vararg) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/IntegersBinaryMathFunction.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/IntegersBinaryMathFunction.kt index 12b897150..a5e2a843c 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/IntegersBinaryMathFunction.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/IntegersBinaryMathFunction.kt @@ -13,25 +13,36 @@ import it.unibo.tuprolog.solve.ExecutionContext * @author Enrico */ abstract class IntegersBinaryMathFunction(name: String) : BinaryMathFunction(name) { - - override fun mathFunction(real: Real, integer: Integer, context: ExecutionContext): Numeric = + override fun mathFunction( + real: Real, + integer: Integer, + context: ExecutionContext, + ): Numeric = throwTypeErrorBecauseOnlyIntegersAccepted( functor, real, - context + context, ) - override fun mathFunction(integer: Integer, real: Real, context: ExecutionContext): Numeric = + override fun mathFunction( + integer: Integer, + real: Real, + context: ExecutionContext, + ): Numeric = throwTypeErrorBecauseOnlyIntegersAccepted( functor, real, - context + context, ) - override fun mathFunction(real1: Real, real2: Real, context: ExecutionContext): Numeric = + override fun mathFunction( + real1: Real, + real2: Real, + context: ExecutionContext, + ): Numeric = throwTypeErrorBecauseOnlyIntegersAccepted( functor, real1, - context + context, ) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/LogicFunction.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/LogicFunction.kt index 394892054..2170b5df4 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/LogicFunction.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/LogicFunction.kt @@ -28,21 +28,24 @@ fun interface LogicFunction { @JvmStatic fun enforcingSignature( supportedSignature: Signature, - uncheckedFunction: (Compute.Request) -> Compute.Response - ): LogicFunction = LogicFunction { - // TODO see TODO in "Signature"; here should be called that method to check if primitive could execute - @Suppress("UNCHECKED_CAST") - when (it.signature) { - supportedSignature -> uncheckedFunction(it as Compute.Request) - else -> throw IllegalArgumentException("This function supports only this signature `$supportedSignature`") + uncheckedFunction: (Compute.Request) -> Compute.Response, + ): LogicFunction = + LogicFunction { + // TODO see TODO in "Signature"; here should be called that method to check if primitive could execute + @Suppress("UNCHECKED_CAST") + when (it.signature) { + supportedSignature -> uncheckedFunction(it as Compute.Request) + else -> throw IllegalArgumentException( + "This function supports only this signature `$supportedSignature`", + ) + } } - } @JsName("enforcingSignatureForLogicFunction") @JvmStatic fun enforcingSignature( supportedSignature: Signature, - uncheckedFunction: LogicFunction + uncheckedFunction: LogicFunction, ): LogicFunction = enforcingSignature(supportedSignature, uncheckedFunction::compute) } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/MathFunction.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/MathFunction.kt index be6dd14d8..9afcb2a53 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/MathFunction.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/MathFunction.kt @@ -12,7 +12,6 @@ import it.unibo.tuprolog.solve.exception.error.TypeError * @author Enrico */ abstract class MathFunction : FunctionWrapper { - constructor(signature: Signature) : super(signature) constructor(name: String, arity: Int, vararg: Boolean = false) : super(name, arity, vararg) @@ -40,11 +39,12 @@ abstract class MathFunction : FunctionWrapper { protected fun throwTypeErrorBecauseOnlyIntegersAccepted( opName: String, actualValue: Term, - context: ExecutionContext - ): Nothing = throw TypeError( - "Operator `$opName` accepts only integers!", - context = context, - expectedType = TypeError.Expected.INTEGER, - culprit = actualValue - ) + context: ExecutionContext, + ): Nothing = + throw TypeError( + "Operator `$opName` accepts only integers!", + context = context, + expectedType = TypeError.Expected.INTEGER, + culprit = actualValue, + ) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/NullaryMathFunction.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/NullaryMathFunction.kt index e16a0928e..4eb01bf7a 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/NullaryMathFunction.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/NullaryMathFunction.kt @@ -11,7 +11,6 @@ import it.unibo.tuprolog.solve.ExecutionContext * @author Enrico */ abstract class NullaryMathFunction(name: String) : MathFunction(name, 0) { - override fun uncheckedImplementation(request: Compute.Request): Compute.Response = with(request) { replyWith(mathFunction(context)) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/UnaryMathFunction.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/UnaryMathFunction.kt index 2c6cffeac..35d30b899 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/UnaryMathFunction.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/function/UnaryMathFunction.kt @@ -13,21 +13,27 @@ import it.unibo.tuprolog.solve.ExecutionContext * @author Enrico */ abstract class UnaryMathFunction(name: String) : MathFunction(name, 1) { - - override fun uncheckedImplementation(request: Compute.Request): Compute.Response = with(request) { - val term = arguments.single() - replyWith( - when (term) { - is Integer -> mathFunction(term, context) - is Real -> mathFunction(term, context) - else -> term - } - ) - } + override fun uncheckedImplementation(request: Compute.Request): Compute.Response = + with(request) { + val term = arguments.single() + replyWith( + when (term) { + is Integer -> mathFunction(term, context) + is Real -> mathFunction(term, context) + else -> term + }, + ) + } /** The actual math function implementation, for [Integer]s */ - protected abstract fun mathFunction(integer: Integer, context: ExecutionContext): Numeric + protected abstract fun mathFunction( + integer: Integer, + context: ExecutionContext, + ): Numeric /** The actual math function implementation, for [Real]s */ - protected abstract fun mathFunction(real: Real, context: ExecutionContext): Numeric + protected abstract fun mathFunction( + real: Real, + context: ExecutionContext, + ): Numeric } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/impl/AbstractSolver.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/impl/AbstractSolver.kt index da9cb637b..b6b09870d 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/impl/AbstractSolver.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/impl/AbstractSolver.kt @@ -34,25 +34,25 @@ abstract class AbstractSolver( initialDynamicKb: Theory, inputChannels: InputStore, outputChannels: OutputStore, - trustKb: Boolean = false + trustKb: Boolean = false, ) : Solver { - protected abstract var currentContext: E init { val staticKb = initialStaticKb.setUnificator(unificator).toImmutableTheory() val dynamicKb = initialDynamicKb.setUnificator(unificator).toMutableTheory() - currentContext = initializeContext( - unificator, - libraries, - flags, - staticKb, - dynamicKb, - getAllOperators(libraries).toOperatorSet(), - inputChannels, - outputChannels, - trustKb - ) + currentContext = + initializeContext( + unificator, + libraries, + flags, + staticKb, + dynamicKb, + getAllOperators(libraries).toOperatorSet(), + inputChannels, + outputChannels, + trustKb, + ) if (!trustKb) { initializeKb(staticKb, dynamicKb) } @@ -72,7 +72,7 @@ abstract class AbstractSolver( operators: OperatorSet, inputChannels: InputStore, outputChannels: OutputStore, - trustKb: Boolean = false + trustKb: Boolean = false, ): E protected fun updateContext(operator: E.() -> ExecutionContext) { @@ -82,11 +82,14 @@ abstract class AbstractSolver( protected fun loadGoal(theory: Atom): Struct = Struct.of("consult", theory) - private fun resetKb(resetStatic: Boolean, resetDynamic: Boolean) { + private fun resetKb( + resetStatic: Boolean, + resetDynamic: Boolean, + ) { updateContext { update( staticKb = if (resetStatic) Theory.emptyIndexed(unificator) else this.staticKb, - dynamicKb = if (resetDynamic) MutableTheory.emptyIndexed(unificator) else this.dynamicKb + dynamicKb = if (resetDynamic) MutableTheory.emptyIndexed(unificator) else this.dynamicKb, ) } } @@ -97,7 +100,7 @@ abstract class AbstractSolver( staticKb = (this.staticKb + clausePartition.staticClauses).toImmutableTheory(), dynamicKb = (this.dynamicKb + clausePartition.dynamicClauses).toMutableTheory(), operators = operators + clausePartition.operators, - flags = flags + clausePartition.flagStore + flags = flags + clausePartition.flagStore, ) } } @@ -106,17 +109,19 @@ abstract class AbstractSolver( staticKb: Theory? = null, dynamicKb: Theory? = null, appendStatic: Boolean = true, - appendDynamic: Boolean = true + appendDynamic: Boolean = true, ) { val staticSkippable = staticKb.let { it == null || it.directives.none() } val dynamicSkippable = dynamicKb.let { it == null || it.directives.none() } - val merged = when { - staticSkippable && dynamicSkippable -> ClausePartition.of(unificator, staticKb, dynamicKb) - staticSkippable -> ClausePartition.of(unificator, staticKb) + - dynamicKb?.partition(unificator, staticByDefault = false) - dynamicSkippable -> ClausePartition.of(unificator, dynamicKb) + staticKb?.partition(unificator) - else -> staticKb?.partition(unificator) + dynamicKb?.partition(unificator, staticByDefault = false) - } + val merged = + when { + staticSkippable && dynamicSkippable -> ClausePartition.of(unificator, staticKb, dynamicKb) + staticSkippable -> + ClausePartition.of(unificator, staticKb) + + dynamicKb?.partition(unificator, staticByDefault = false) + dynamicSkippable -> ClausePartition.of(unificator, dynamicKb) + staticKb?.partition(unificator) + else -> staticKb?.partition(unificator) + dynamicKb?.partition(unificator, staticByDefault = false) + } resetKb(!appendStatic, !appendDynamic) merged?.includes?.map { loadGoal(it) }?.forEach(this::solveInitialGoal) merged?.let { updateContextWith(it) } @@ -163,7 +168,10 @@ abstract class AbstractSolver( final override val operators: OperatorSet get() = currentContext.operators - final override fun solve(goal: Struct, options: SolveOptions): Sequence { + final override fun solve( + goal: Struct, + options: SolveOptions, + ): Sequence { var solutionSequence = solveImpl(goal, options) if (options.limit > 0) { solutionSequence = solutionSequence.take(options.limit) @@ -174,7 +182,10 @@ abstract class AbstractSolver( return solutionSequence } - protected abstract fun solveImpl(goal: Struct, options: SolveOptions): Sequence + protected abstract fun solveImpl( + goal: Struct, + options: SolveOptions, + ): Sequence override fun equals(other: Any?): Boolean { if (this === other) return true @@ -200,7 +211,7 @@ abstract class AbstractSolver( stdIn: InputChannel, stdOut: OutputChannel, stdErr: OutputChannel, - warnings: OutputChannel + warnings: OutputChannel, ): AbstractSolver abstract override fun clone(): AbstractSolver diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/impl/SolutionFormatterImpl.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/impl/SolutionFormatterImpl.kt index 980ffc6e7..92e256ee9 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/impl/SolutionFormatterImpl.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/impl/SolutionFormatterImpl.kt @@ -8,15 +8,17 @@ import it.unibo.tuprolog.solve.exception.ResolutionException import it.unibo.tuprolog.solve.exception.TimeOutException internal class SolutionFormatterImpl(private val termFormatter: TermFormatter) : SolutionFormatter { - override fun format(value: Solution): String = when (value) { - is Solution.Yes -> formatYes(value) - is Solution.No -> "no." - is Solution.Halt -> when (val e = value.exception) { - is TimeOutException -> "timeout." - is HaltException -> "halt: ${e.exitStatus}" - else -> formatException(e) + override fun format(value: Solution): String = + when (value) { + is Solution.Yes -> formatYes(value) + is Solution.No -> "no." + is Solution.Halt -> + when (val e = value.exception) { + is TimeOutException -> "timeout." + is HaltException -> "halt: ${e.exitStatus}" + else -> formatException(e) + } } - } private fun formatException(e: ResolutionException): String = "halt: ${e.message ?: ""}" + diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/impl/SolveOptionsImpl.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/impl/SolveOptionsImpl.kt index 8a8df035a..6bd7290f5 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/impl/SolveOptionsImpl.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/impl/SolveOptionsImpl.kt @@ -7,9 +7,8 @@ internal data class SolveOptionsImpl( override val isLazy: Boolean, override val timeout: TimeDuration = SolveOptions.MAX_TIMEOUT, override val limit: Int = SolveOptions.ALL_SOLUTIONS, - override val customOptions: Map = emptyMap() + override val customOptions: Map = emptyMap(), ) : SolveOptions { - init { require(timeout >= 0L) { "Invalid timeout: $timeout" } require(limit != 0) { "Invalid limit: $limit" } @@ -21,6 +20,5 @@ internal data class SolveOptionsImpl( override fun setLimit(value: Int): SolveOptions = copy(limit = value) - override fun setOptions(options: Map): SolveOptions = - copy(customOptions = options) + override fun setOptions(options: Map): SolveOptions = copy(customOptions = options) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/impl/SolverBuilderImpl.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/impl/SolverBuilderImpl.kt index 658408efa..887ee0ec5 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/impl/SolverBuilderImpl.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/impl/SolverBuilderImpl.kt @@ -21,7 +21,6 @@ import it.unibo.tuprolog.theory.Theory import it.unibo.tuprolog.unify.Unificator internal class SolverBuilderImpl(private val factory: SolverFactory) : SolverBuilder { - private inline fun returningThis(action: () -> Unit): SolverBuilder { action() return this @@ -29,100 +28,127 @@ internal class SolverBuilderImpl(private val factory: SolverFactory) : SolverBui override var unificator: Unificator = factory.defaultUnificator - override fun unificator(unificator: Unificator): SolverBuilder = returningThis { - this.unificator = unificator - } + override fun unificator(unificator: Unificator): SolverBuilder = + returningThis { + this.unificator = unificator + } override var runtime: Runtime = factory.defaultRuntime - override fun runtime(runtime: Runtime): SolverBuilder = returningThis { - this.runtime = runtime - } + override fun runtime(runtime: Runtime): SolverBuilder = + returningThis { + this.runtime = runtime + } private var anonymousCount = 0 - override fun library(alias: String?, item1: AbstractWrapper<*>, vararg items: AbstractWrapper<*>): SolverBuilder = - runtime(runtime + runtimeOf(alias ?: "anonymous${anonymousCount++}", item1, *items)) + override fun library( + alias: String?, + item1: AbstractWrapper<*>, + vararg items: AbstractWrapper<*>, + ): SolverBuilder = runtime(runtime + runtimeOf(alias ?: "anonymous${anonymousCount++}", item1, *items)) - override fun library(item1: AbstractWrapper<*>, vararg items: AbstractWrapper<*>): SolverBuilder = - library(null, item1, *items) + override fun library( + item1: AbstractWrapper<*>, + vararg items: AbstractWrapper<*>, + ): SolverBuilder = library(null, item1, *items) override var builtins: Library? = factory.defaultBuiltins - override fun builtins(builtins: Library): SolverBuilder = returningThis { - this.builtins = builtins - } + override fun builtins(builtins: Library): SolverBuilder = + returningThis { + this.builtins = builtins + } - override fun noBuiltins(): SolverBuilder = returningThis { - this.builtins = null - } + override fun noBuiltins(): SolverBuilder = + returningThis { + this.builtins = null + } override var flags: FlagStore = factory.defaultFlags - override fun flags(flags: FlagStore): SolverBuilder = returningThis { - this.flags = flags - } + override fun flags(flags: FlagStore): SolverBuilder = + returningThis { + this.flags = flags + } - override fun flag(name: String, value: Term): SolverBuilder = - flags(flags + (name to value)) + override fun flag( + name: String, + value: Term, + ): SolverBuilder = flags(flags + (name to value)) - override fun flag(flag: Pair): SolverBuilder = - flags(flags + flag) + override fun flag(flag: Pair): SolverBuilder = flags(flags + flag) - override fun flag(flag: NotableFlag): SolverBuilder = - flags(flags.set(flag)) + override fun flag(flag: NotableFlag): SolverBuilder = flags(flags.set(flag)) - override fun flag(flag: NotableFlag, value: Term): SolverBuilder = - flags(flags.set(flag, value)) + override fun flag( + flag: NotableFlag, + value: Term, + ): SolverBuilder = flags(flags.set(flag, value)) - override fun flag(flag: T, value: T.() -> Term): SolverBuilder = - flags(flags.set(flag, flag.value())) + override fun flag( + flag: T, + value: T.() -> Term, + ): SolverBuilder = flags(flags.set(flag, flag.value())) override var staticKb: Theory = factory.defaultStaticKb - override fun staticKb(theory: Theory): SolverBuilder = returningThis { - staticKb = theory - } + override fun staticKb(theory: Theory): SolverBuilder = + returningThis { + staticKb = theory + } - override fun staticKb(vararg clauses: Clause): SolverBuilder = returningThis { - staticKb = Theory.of(unificator, *clauses) - } + override fun staticKb(vararg clauses: Clause): SolverBuilder = + returningThis { + staticKb = Theory.of(unificator, *clauses) + } - override fun staticKb(clauses: Iterable): SolverBuilder = returningThis { - staticKb = Theory.of(unificator, clauses) - } + override fun staticKb(clauses: Iterable): SolverBuilder = + returningThis { + staticKb = Theory.of(unificator, clauses) + } - override fun staticKb(clauses: Sequence): SolverBuilder = returningThis { - staticKb = Theory.of(unificator, clauses) - } + override fun staticKb(clauses: Sequence): SolverBuilder = + returningThis { + staticKb = Theory.of(unificator, clauses) + } override var dynamicKb: Theory = factory.defaultDynamicKb - override fun dynamicKb(theory: Theory): SolverBuilder = returningThis { - dynamicKb = theory - } + override fun dynamicKb(theory: Theory): SolverBuilder = + returningThis { + dynamicKb = theory + } - override fun dynamicKb(vararg clauses: Clause): SolverBuilder = returningThis { - dynamicKb = Theory.listedOf(unificator, *clauses) - } + override fun dynamicKb(vararg clauses: Clause): SolverBuilder = + returningThis { + dynamicKb = Theory.listedOf(unificator, *clauses) + } - override fun dynamicKb(clauses: Iterable): SolverBuilder = returningThis { - dynamicKb = Theory.listedOf(unificator, clauses) - } + override fun dynamicKb(clauses: Iterable): SolverBuilder = + returningThis { + dynamicKb = Theory.listedOf(unificator, clauses) + } - override fun dynamicKb(clauses: Sequence): SolverBuilder = returningThis { - dynamicKb = Theory.listedOf(unificator, clauses) - } + override fun dynamicKb(clauses: Sequence): SolverBuilder = + returningThis { + dynamicKb = Theory.listedOf(unificator, clauses) + } override var inputs: InputStore = InputStore.fromStandard(factory.defaultInputChannel) - override fun inputs(inputs: InputStore): SolverBuilder = returningThis { - this.inputs = inputs - } + override fun inputs(inputs: InputStore): SolverBuilder = + returningThis { + this.inputs = inputs + } - override fun input(alias: String, channel: InputChannel): SolverBuilder = returningThis { - this.inputs += (alias to channel) - } + override fun input( + alias: String, + channel: InputChannel, + ): SolverBuilder = + returningThis { + this.inputs += (alias to channel) + } override var standardInput: InputChannel get() = inputs.stdIn @@ -130,23 +156,30 @@ internal class SolverBuilderImpl(private val factory: SolverFactory) : SolverBui inputs = inputs.setStdIn(value) } - override fun standardInput(channel: InputChannel): SolverBuilder = returningThis { - standardInput = channel - } + override fun standardInput(channel: InputChannel): SolverBuilder = + returningThis { + standardInput = channel + } - override var outputs: OutputStore = OutputStore.fromStandard( - factory.defaultOutputChannel, - factory.defaultErrorChannel, - factory.defaultWarningsChannel - ) + override var outputs: OutputStore = + OutputStore.fromStandard( + factory.defaultOutputChannel, + factory.defaultErrorChannel, + factory.defaultWarningsChannel, + ) - override fun outputs(outputs: OutputStore): SolverBuilder = returningThis { - this.outputs = outputs - } + override fun outputs(outputs: OutputStore): SolverBuilder = + returningThis { + this.outputs = outputs + } - override fun output(alias: String, channel: OutputChannel): SolverBuilder = returningThis { - outputs += (alias to channel) - } + override fun output( + alias: String, + channel: OutputChannel, + ): SolverBuilder = + returningThis { + outputs += (alias to channel) + } override var standardOutput: OutputChannel get() = outputs.stdOut @@ -154,9 +187,10 @@ internal class SolverBuilderImpl(private val factory: SolverFactory) : SolverBui outputs = outputs.setStdOut(value) } - override fun standardOutput(channel: OutputChannel): SolverBuilder = returningThis { - standardOutput = channel - } + override fun standardOutput(channel: OutputChannel): SolverBuilder = + returningThis { + standardOutput = channel + } override var standardError: OutputChannel get() = outputs.stdErr @@ -164,9 +198,10 @@ internal class SolverBuilderImpl(private val factory: SolverFactory) : SolverBui outputs = outputs.setStdErr(value) } - override fun standardError(channel: OutputChannel): SolverBuilder = returningThis { - standardError = channel - } + override fun standardError(channel: OutputChannel): SolverBuilder = + returningThis { + standardError = channel + } override var warnings: OutputChannel get() = outputs.warnings @@ -174,9 +209,10 @@ internal class SolverBuilderImpl(private val factory: SolverFactory) : SolverBui outputs = outputs.setWarnings(value) } - override fun warnings(channel: OutputChannel): SolverBuilder = returningThis { - warnings = channel - } + override fun warnings(channel: OutputChannel): SolverBuilder = + returningThis { + warnings = channel + } private val runtimeWithBuiltins: Runtime get() = builtins?.let { runtime + it } ?: runtime @@ -189,7 +225,7 @@ internal class SolverBuilderImpl(private val factory: SolverFactory) : SolverBui dynamicKb = dynamicKb, flags = flags, inputs = inputs, - outputs = outputs + outputs = outputs, ) override fun buildMutable(): MutableSolver = @@ -200,7 +236,7 @@ internal class SolverBuilderImpl(private val factory: SolverFactory) : SolverBui dynamicKb = dynamicKb, flags = flags, inputs = inputs, - outputs = outputs + outputs = outputs, ) override fun equals(other: Any?): Boolean { diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/Library.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/Library.kt index 1d46d88a9..34da28e4d 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/Library.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/Library.kt @@ -22,7 +22,6 @@ import kotlin.jvm.JvmStatic * A library alias is aimed at identifying the library in the eyes of a solver. * */ interface Library : Pluggable { - /** The alias identifying this library */ @JsName("alias") val alias: String @@ -34,7 +33,6 @@ interface Library : Pluggable { override fun toString(): String // Leave this here to allow delegation in `: ... by` companion object { - /** The character used to separate library alias from original name */ const val ALIAS_SEPARATOR = "." @@ -69,7 +67,7 @@ interface Library : Pluggable { primitives: Map = emptyMap(), clauses: Iterable = emptyList(), operators: OperatorSet = OperatorSet(), - functions: Map = emptyMap() + functions: Map = emptyMap(), ): Library { require(ALIAS_PATTERN.matches(alias)) { "Aliases should match the pattern $ALIAS_PATTERN" @@ -84,7 +82,7 @@ interface Library : Pluggable { primitives: Map = emptyMap(), clauses: Iterable = emptyList(), operators: OperatorSet = OperatorSet(), - functions: Map = emptyMap() + functions: Map = emptyMap(), ): Library = of(DEFAULT_ALIAS, primitives, clauses, operators, functions) @JvmStatic @@ -92,7 +90,7 @@ interface Library : Pluggable { @JvmOverloads fun of( alias: String = DEFAULT_ALIAS, - library: Library + library: Library, ): Library = of(alias, library.primitives, library.clauses, library.operators, library.functions) } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/Pluggable.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/Pluggable.kt index 65d7d898b..17810580a 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/Pluggable.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/Pluggable.kt @@ -55,12 +55,13 @@ interface Pluggable { @JsName("ruleSignatures") val rulesSignatures: Sequence - get() = clauses.asSequence() - .filterIsInstance() - .map { it.head.indicator } - .map { Signature.fromIndicator(it) } - .filterNotNull() - .distinct() + get() = + clauses.asSequence() + .filterIsInstance() + .map { it.head.indicator } + .map { Signature.fromIndicator(it) } + .filterNotNull() + .distinct() /** Checks whether the provided signature, is protected in this library */ @JsName("hasProtected") diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/Runtime.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/Runtime.kt index 308b4674c..efb479f24 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/Runtime.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/Runtime.kt @@ -8,7 +8,6 @@ import kotlin.jvm.JvmStatic /** Represents a group of [Library] objects constituting the runtime a logic solver may leverage upon */ interface Runtime : Pluggable, Map { - @JsName("aliases") val aliases: Set diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/exception/AlreadyLoadedLibraryException.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/exception/AlreadyLoadedLibraryException.kt index 8bf0f6805..482941e7b 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/exception/AlreadyLoadedLibraryException.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/exception/AlreadyLoadedLibraryException.kt @@ -2,7 +2,7 @@ package it.unibo.tuprolog.solve.library.exception class AlreadyLoadedLibraryException( message: String? = null, - cause: Throwable? = null + cause: Throwable? = null, ) : LibraryException(message, cause) { constructor(cause: Throwable?) : this(cause?.toString(), cause) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/exception/LibraryException.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/exception/LibraryException.kt index 7027a5e2a..b3ba276ad 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/exception/LibraryException.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/exception/LibraryException.kt @@ -4,7 +4,7 @@ import it.unibo.tuprolog.core.exception.TuPrologException open class LibraryException( message: String? = null, - cause: Throwable? = null + cause: Throwable? = null, ) : TuPrologException(message, cause) { constructor(cause: Throwable?) : this(cause?.toString(), cause) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/exception/NoSuchALibraryException.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/exception/NoSuchALibraryException.kt index d92a58e49..d22f06d64 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/exception/NoSuchALibraryException.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/exception/NoSuchALibraryException.kt @@ -2,7 +2,7 @@ package it.unibo.tuprolog.solve.library.exception class NoSuchALibraryException( message: String? = null, - cause: Throwable? = null + cause: Throwable? = null, ) : LibraryException(message, cause) { constructor(cause: Throwable?) : this(cause?.toString(), cause) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/impl/AbstractLibrary.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/impl/AbstractLibrary.kt index bf9f8a12b..0b44002d8 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/impl/AbstractLibrary.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/impl/AbstractLibrary.kt @@ -8,7 +8,6 @@ import it.unibo.tuprolog.solve.library.Library import it.unibo.tuprolog.solve.primitive.Primitive abstract class AbstractLibrary : Library, AbstractPluggable() { - override val operators: OperatorSet get() = OperatorSet.EMPTY @@ -24,14 +23,17 @@ abstract class AbstractLibrary : Library, AbstractPluggable() { override fun toString(): String { return "${super.toString()}(" + "alias=" + alias + - ", primitives=" + primitives.keys.joinToString(", ", "{", "}") { - "'${it.name}'/${it.arity}" - } + ", functions=" + functions.keys.joinToString(", ", "{", "}") { - "'${it.name}'/${it.arity}" - } + ", theory=" + clauses.joinToString(". ", "{", "}") + - ", operators=" + operators.joinToString(", ", "{", "}") { - "'${it.functor}':${it.priority}:${it.specifier}" - } + ")" + ", primitives=" + + primitives.keys.joinToString(", ", "{", "}") { + "'${it.name}'/${it.arity}" + } + ", functions=" + + functions.keys.joinToString(", ", "{", "}") { + "'${it.name}'/${it.arity}" + } + ", theory=" + clauses.joinToString(". ", "{", "}") + + ", operators=" + + operators.joinToString(", ", "{", "}") { + "'${it.functor}':${it.priority}:${it.specifier}" + } + ")" } override fun equals(other: Any?): Boolean { diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/impl/ExtensionLibrary.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/impl/ExtensionLibrary.kt index 3147724a8..f965c7d8e 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/impl/ExtensionLibrary.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/impl/ExtensionLibrary.kt @@ -14,7 +14,7 @@ import it.unibo.tuprolog.solve.rule.RuleWrapper @Suppress("MemberVisibilityCanBePrivate") abstract class ExtensionLibrary( - private val extended: Library + private val extended: Library, ) : AbstractLibrary() { override val alias: String get() = extended.alias diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/impl/LibraryImpl.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/impl/LibraryImpl.kt index 6e3a9b6b1..eb3c19ead 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/impl/LibraryImpl.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/impl/LibraryImpl.kt @@ -17,7 +17,7 @@ internal data class LibraryImpl( override val operators: OperatorSet, override val clauses: List, override val primitives: Map, - override val functions: Map + override val functions: Map, ) : AbstractLibrary() { init { require(alias.isNotBlank()) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/impl/RuntimeImpl.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/impl/RuntimeImpl.kt index 1d87a9ca4..3e1bc13d6 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/impl/RuntimeImpl.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/library/impl/RuntimeImpl.kt @@ -18,7 +18,6 @@ internal class RuntimeImpl(private val delegate: Map) : Runtime, AbstractPluggable(), Map by delegate { - constructor(libraries: Sequence) : this(libraries.map { it.alias to it }.toMap()) /** All aliases of all libraries included in this library group */ @@ -47,7 +46,7 @@ internal class RuntimeImpl(private val delegate: Map) : lib.primitives.entries.asSequence().flatMap { sequenceOf( it.toPair(), - it.key.copy(name = lib.alias + Library.ALIAS_SEPARATOR + it.key.name) to it.value + it.key.copy(name = lib.alias + Library.ALIAS_SEPARATOR + it.key.name) to it.value, ) } }.toMap() @@ -58,7 +57,7 @@ internal class RuntimeImpl(private val delegate: Map) : lib.functions.entries.asSequence().flatMap { sequenceOf( it.toPair(), - it.key.copy(name = lib.alias + Library.ALIAS_SEPARATOR + it.key.name) to it.value + it.key.copy(name = lib.alias + Library.ALIAS_SEPARATOR + it.key.name) to it.value, ) } }.toMap() @@ -90,12 +89,13 @@ internal class RuntimeImpl(private val delegate: Map) : } override operator fun minus(aliases: Iterable): RuntimeImpl { - val toBeRemoved = aliases.map { - if (it in this.aliases) { - noSuchALibraryError(it) - } - it - }.toSet() + val toBeRemoved = + aliases.map { + if (it in this.aliases) { + noSuchALibraryError(it) + } + it + }.toSet() return RuntimeImpl(libraries.asSequence().filterNot { it.alias in toBeRemoved }) } @@ -125,8 +125,7 @@ internal class RuntimeImpl(private val delegate: Map) : private inline fun alreadyLoadedError(library: Library): Nothing = throw AlreadyLoadedLibraryException("A library aliased as `${library.alias}` has already been loaded") - private inline fun noSuchALibraryError(library: Library): Nothing = - noSuchALibraryError(library.alias) + private inline fun noSuchALibraryError(library: Library): Nothing = noSuchALibraryError(library.alias) private inline fun noSuchALibraryError(alias: String): Nothing = throw NoSuchALibraryException("No library with alias `$alias` has been loaded") diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/ArithmeticRelation.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/ArithmeticRelation.kt index af8741659..6b9761781 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/ArithmeticRelation.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/ArithmeticRelation.kt @@ -7,14 +7,21 @@ import it.unibo.tuprolog.solve.function.evalAsArithmeticExpression /** Base class for implementing arithmetic relation between [Numeric] terms */ abstract class ArithmeticRelation(operator: String) : BinaryRelation.Predicative(operator) { - - final override fun Solve.Request.compute(first: Term, second: Term): Boolean { + final override fun Solve.Request.compute( + first: Term, + second: Term, + ): Boolean { ensuringAllArgumentsAreInstantiated() return evaluateAndCompute(first, second) } - private fun Solve.Request.evaluateAndCompute(x: Term, y: Term): Boolean = - computeNumeric(x.evalAsArithmeticExpression(this, 0), y.evalAsArithmeticExpression(this, 1)) + private fun Solve.Request.evaluateAndCompute( + x: Term, + y: Term, + ): Boolean = computeNumeric(x.evalAsArithmeticExpression(this, 0), y.evalAsArithmeticExpression(this, 1)) - abstract fun computeNumeric(x: Numeric, y: Numeric): Boolean + abstract fun computeNumeric( + x: Numeric, + y: Numeric, + ): Boolean } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/BinaryRelation.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/BinaryRelation.kt index 770b62b29..97d2a4cda 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/BinaryRelation.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/BinaryRelation.kt @@ -6,11 +6,10 @@ import it.unibo.tuprolog.solve.ExecutionContext /** Base class to implement primitives that relate two [Term]s and provide a single response */ abstract class BinaryRelation(operator: String) : PrimitiveWrapper(operator, 2) { - /** Template method aimed at computing the application of this relation to three [Term]s */ protected abstract fun Solve.Request.computeAll( first: Term, - second: Term + second: Term, ): Sequence final override fun uncheckedImplementation(request: Solve.Request): Sequence { @@ -20,10 +19,13 @@ abstract class BinaryRelation(operator: String) : Primitiv abstract class WithoutSideEffects(operator: String) : BinaryRelation(operator) { protected abstract fun Solve.Request.computeAllSubstitutions( first: Term, - second: Term + second: Term, ): Sequence - final override fun Solve.Request.computeAll(first: Term, second: Term): Sequence { + final override fun Solve.Request.computeAll( + first: Term, + second: Term, + ): Sequence { return computeAllSubstitutions(first, second).map { replyWith(it) } } } @@ -31,10 +33,13 @@ abstract class BinaryRelation(operator: String) : Primitiv abstract class NonBacktrackable(operator: String) : BinaryRelation(operator) { protected abstract fun Solve.Request.computeOne( first: Term, - second: Term + second: Term, ): Solve.Response - final override fun Solve.Request.computeAll(first: Term, second: Term): Sequence { + final override fun Solve.Request.computeAll( + first: Term, + second: Term, + ): Sequence { return sequenceOf(computeOne(first, second)) } } @@ -42,10 +47,13 @@ abstract class BinaryRelation(operator: String) : Primitiv abstract class Functional(operator: String) : NonBacktrackable(operator) { protected abstract fun Solve.Request.computeOneSubstitution( first: Term, - second: Term + second: Term, ): Substitution - final override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response { + final override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response { return replyWith(computeOneSubstitution(first, second)) } } @@ -53,10 +61,13 @@ abstract class BinaryRelation(operator: String) : Primitiv abstract class Predicative(operator: String) : NonBacktrackable(operator) { protected abstract fun Solve.Request.compute( first: Term, - second: Term + second: Term, ): Boolean - final override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response { + final override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response { return if (compute(first, second)) replySuccess() else replyFail() } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/Primitive.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/Primitive.kt index e7a20fd68..cc99bc303 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/Primitive.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/Primitive.kt @@ -23,21 +23,24 @@ fun interface Primitive { @JvmStatic fun enforcingSignature( supportedSignature: Signature, - uncheckedPrimitive: (Solve.Request) -> Sequence - ): Primitive = Primitive { - // TODO see TODO in "Signature"; here should be called that method to check if primitive could execute - @Suppress("UNCHECKED_CAST") - when (it.signature) { - supportedSignature -> uncheckedPrimitive(it as Solve.Request) - else -> throw IllegalArgumentException("This primitive supports only this signature `$supportedSignature`") + uncheckedPrimitive: (Solve.Request) -> Sequence, + ): Primitive = + Primitive { + // TODO see TODO in "Signature"; here should be called that method to check if primitive could execute + @Suppress("UNCHECKED_CAST") + when (it.signature) { + supportedSignature -> uncheckedPrimitive(it as Solve.Request) + else -> throw IllegalArgumentException( + "This primitive supports only this signature `$supportedSignature`", + ) + } } - } @JsName("enforcingSignatureForPrimitive") @JvmStatic fun enforcingSignature( supportedSignature: Signature, - uncheckedPrimitive: Primitive + uncheckedPrimitive: Primitive, ): Primitive = enforcingSignature(supportedSignature, uncheckedPrimitive::solve) } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/PrimitiveWrapper.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/PrimitiveWrapper.kt index d3aa1d455..6624c920c 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/PrimitiveWrapper.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/PrimitiveWrapper.kt @@ -41,7 +41,6 @@ import kotlin.jvm.JvmStatic * @author Giovanni */ abstract class PrimitiveWrapper : AbstractWrapper { - constructor(signature: Signature) : super(signature) constructor(name: String, arity: Int, vararg: Boolean = false) : super(name, arity, vararg) @@ -52,25 +51,32 @@ abstract class PrimitiveWrapper : AbstractWrapper Solve.Request.mgu(term1: Term, term2: Term): Substitution = - context.unificator.mgu(term1, term2) + fun Solve.Request.mgu( + term1: Term, + term2: Term, + ): Substitution = context.unificator.mgu(term1, term2) @JvmStatic - fun Solve.Request.match(term1: Term, term2: Term): Boolean = - context.unificator.match(term1, term2) + fun Solve.Request.match( + term1: Term, + term2: Term, + ): Boolean = context.unificator.match(term1, term2) @JvmStatic - fun Solve.Request.unify(term1: Term, term2: Term): Term? = - context.unificator.unify(term1, term2) + fun Solve.Request.unify( + term1: Term, + term2: Term, + ): Term? = context.unificator.unify(term1, term2) /** * Utility factory to build a [PrimitiveWrapper] out of a [Signature] and a [Primitive] function */ @JvmStatic - fun wrap(signature: Signature, primitive: Primitive): PrimitiveWrapper = - FromFunction(signature, primitive) + fun wrap( + signature: Signature, + primitive: Primitive, + ): PrimitiveWrapper = FromFunction(signature, primitive) /** * Utility factory to build a [PrimitiveWrapper] out of a [Primitive] function @@ -80,39 +86,47 @@ abstract class PrimitiveWrapper : AbstractWrapper = FromFunction(name, arity, vararg, primitive) /** * Utility factory to build a [PrimitiveWrapper] out of a [Primitive] function */ @JvmStatic - fun wrap(name: String, arity: Int, primitive: Primitive): PrimitiveWrapper = - wrap(name, arity, false, primitive) + fun wrap( + name: String, + arity: Int, + primitive: Primitive, + ): PrimitiveWrapper = wrap(name, arity, false, primitive) /** Private class to support the wrap methods, without using the object literal notation */ private class FromFunction( signature: Signature, - private val uncheckedPrimitive: Primitive + private val uncheckedPrimitive: Primitive, ) : PrimitiveWrapper(signature) { - constructor(name: String, arity: Int, vararg: Boolean = false, uncheckedPrimitive: Primitive) : this(Signature(name, arity, vararg), uncheckedPrimitive) override fun uncheckedImplementation(request: Solve.Request): Sequence = - uncheckedPrimitive.solve(request) + uncheckedPrimitive.solve( + request, + ) } - private fun ensurerVisitor(context: ExecutionContext, procedure: Signature): TermVisitor = + private fun ensurerVisitor( + context: ExecutionContext, + procedure: Signature, + ): TermVisitor = object : TermVisitor { override fun defaultValue(term: Term): Nothing? = null - override fun visitStruct(term: Struct) = when { - Clause.notableFunctors.contains(term.functor) && term.arity == 2 -> { - term.argsSequence.map { it.accept(this) }.filterNotNull().firstOrNull() + override fun visitStruct(term: Struct) = + when { + Clause.notableFunctors.contains(term.functor) && term.arity == 2 -> { + term.argsSequence.map { it.accept(this) }.filterNotNull().firstOrNull() + } + else -> defaultValue(term) } - else -> defaultValue(term) - } override fun visitNumeric(term: Numeric): TypeError = TypeError.forGoal(context, procedure, TypeError.Expected.CALLABLE, term) @@ -131,21 +145,21 @@ abstract class PrimitiveWrapper : AbstractWrapper Solve.Request.ensureIsInstantiated( term: Term?, - index: Int + index: Int, ): Solve.Request = term?.asVar()?.let { throw InstantiationError.forArgument( context, signature, it, - index + index, ) } ?: this @JvmStatic fun Solve.Request.ensuringProcedureHasPermission( signature: Signature?, - operation: PermissionError.Operation + operation: PermissionError.Operation, ): Solve.Request { if (signature != null) { if (context.libraries.hasProtected(signature)) { @@ -154,7 +168,7 @@ abstract class PrimitiveWrapper : AbstractWrapper : AbstractWrapper : AbstractWrapper Solve.Request.ensuringClauseProcedureHasPermission( clause: Clause, - operation: PermissionError.Operation + operation: PermissionError.Operation, ): Solve.Request { val headSignature: Signature? = clause.head?.extractSignature() return ensuringProcedureHasPermission(headSignature, operation) } @JvmStatic - fun Solve.Request.ensuringArgumentIsWellFormedIndicator(index: Int): Solve.Request { + fun Solve.Request.ensuringArgumentIsWellFormedIndicator( + index: Int, + ): Solve.Request { ensuringArgumentIsInstantiated(index) val candidate = arguments[index] when { @@ -209,12 +225,12 @@ abstract class PrimitiveWrapper : AbstractWrapper Solve.Request.notImplemented( - message: String = "Primitive for ${signature.name}/${signature.arity} is not implemented, yet" + message: String = "Primitive for ${signature.name}/${signature.arity} is not implemented, yet", ): Solve.Response = throw SystemError.forUncaughtException(context, NotImplementedError(message)) @JvmStatic fun Solve.Request.notSupported( - message: String = "Operation ${signature.name}/${signature.arity} is not supported" + message: String = "Operation ${signature.name}/${signature.arity} is not supported", ): Solve.Response = throw SystemError.forUncaughtException(context, IllegalStateException(message)) @JvmStatic @@ -253,7 +269,13 @@ abstract class PrimitiveWrapper : AbstractWrapper Solve.Request.ensuringArgumentIsStruct(index: Int): Solve.Request { val arg = arguments[index] return when { - !arg.isStruct -> throw TypeError.forArgument(context, signature, TypeError.Expected.CALLABLE, arg, index) + !arg.isStruct -> throw TypeError.forArgument( + context, + signature, + TypeError.Expected.CALLABLE, + arg, + index, + ) else -> this } } @@ -271,7 +293,7 @@ abstract class PrimitiveWrapper : AbstractWrapper this } @@ -286,7 +308,7 @@ abstract class PrimitiveWrapper : AbstractWrapper this } @@ -393,7 +415,7 @@ abstract class PrimitiveWrapper : AbstractWrapper this } @@ -426,10 +448,11 @@ abstract class PrimitiveWrapper : AbstractWrapper Solve.Request.ensuringArgumentIsWellFormedList(index: Int): Solve.Request { val term = arguments[index] return when { - term.isList -> when { - term.castToList().isWellFormed -> this - else -> throw DomainError.forArgument(context, signature, WELL_FORMED_LIST, term, index) - } + term.isList -> + when { + term.castToList().isWellFormed -> this + else -> throw DomainError.forArgument(context, signature, WELL_FORMED_LIST, term, index) + } else -> throw TypeError.forArgument(context, signature, LIST, term, index) } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/QuaternaryRelation.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/QuaternaryRelation.kt index f60d6d943..285802311 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/QuaternaryRelation.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/QuaternaryRelation.kt @@ -5,13 +5,12 @@ import it.unibo.tuprolog.core.Term import it.unibo.tuprolog.solve.ExecutionContext abstract class QuaternaryRelation(operator: String) : PrimitiveWrapper(operator, 4) { - /** Template method aimed at computing the application of this relation to three [Term]s */ protected abstract fun Solve.Request.computeAll( first: Term, second: Term, third: Term, - fourth: Term + fourth: Term, ): Sequence override fun uncheckedImplementation(request: Solve.Request): Sequence { @@ -19,7 +18,7 @@ abstract class QuaternaryRelation(operator: String) : Prim request.arguments[0], request.arguments[1], request.arguments[2], - request.arguments[3] + request.arguments[3], ) } @@ -28,14 +27,14 @@ abstract class QuaternaryRelation(operator: String) : Prim first: Term, second: Term, third: Term, - fourth: Term + fourth: Term, ): Sequence final override fun Solve.Request.computeAll( first: Term, second: Term, third: Term, - fourth: Term + fourth: Term, ): Sequence { return computeAllSubstitutions(first, second, third, fourth).map { replyWith(it) } } @@ -46,14 +45,14 @@ abstract class QuaternaryRelation(operator: String) : Prim first: Term, second: Term, third: Term, - fourth: Term + fourth: Term, ): Solve.Response final override fun Solve.Request.computeAll( first: Term, second: Term, third: Term, - fourth: Term + fourth: Term, ): Sequence { return sequenceOf(computeOne(first, second, third, fourth)) } @@ -64,14 +63,14 @@ abstract class QuaternaryRelation(operator: String) : Prim first: Term, second: Term, third: Term, - fourth: Term + fourth: Term, ): Substitution final override fun Solve.Request.computeOne( first: Term, second: Term, third: Term, - fourth: Term + fourth: Term, ): Solve.Response { return replyWith(computeOneSubstitution(first, second, third, fourth)) } @@ -82,14 +81,14 @@ abstract class QuaternaryRelation(operator: String) : Prim first: Term, second: Term, third: Term, - fourth: Term + fourth: Term, ): Boolean final override fun Solve.Request.computeOne( first: Term, second: Term, third: Term, - fourth: Term + fourth: Term, ): Solve.Response { return if (compute(first, second, third, fourth)) replySuccess() else replyFail() } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/QuinaryRelation.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/QuinaryRelation.kt index c045feb89..fc52b371f 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/QuinaryRelation.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/QuinaryRelation.kt @@ -5,18 +5,23 @@ import it.unibo.tuprolog.core.Term import it.unibo.tuprolog.solve.ExecutionContext abstract class QuinaryRelation(operator: String) : PrimitiveWrapper(operator, 5) { - /** Template method aimed at computing the application of this relation to three [Term]s */ protected abstract fun Solve.Request.computeAll( first: Term, second: Term, third: Term, fourth: Term, - fifth: Term + fifth: Term, ): Sequence final override fun uncheckedImplementation(request: Solve.Request): Sequence { - return request.computeAll(request.arguments[0], request.arguments[1], request.arguments[2], request.arguments[3], request.arguments[4]) + return request.computeAll( + request.arguments[0], + request.arguments[1], + request.arguments[2], + request.arguments[3], + request.arguments[4], + ) } abstract class WithoutSideEffects(operator: String) : QuinaryRelation(operator) { @@ -25,7 +30,7 @@ abstract class QuinaryRelation(operator: String) : Primiti second: Term, third: Term, fourth: Term, - fifth: Term + fifth: Term, ): Sequence final override fun Solve.Request.computeAll( @@ -33,7 +38,7 @@ abstract class QuinaryRelation(operator: String) : Primiti second: Term, third: Term, fourth: Term, - fifth: Term + fifth: Term, ): Sequence { return computeAllSubstitutions(first, second, third, fourth, fifth).map { replyWith(it) } } @@ -45,7 +50,7 @@ abstract class QuinaryRelation(operator: String) : Primiti second: Term, third: Term, fourth: Term, - fifth: Term + fifth: Term, ): Solve.Response final override fun Solve.Request.computeAll( @@ -53,7 +58,7 @@ abstract class QuinaryRelation(operator: String) : Primiti second: Term, third: Term, fourth: Term, - fifth: Term + fifth: Term, ): Sequence { return sequenceOf(computeOne(first, second, third, fourth, fifth)) } @@ -65,10 +70,16 @@ abstract class QuinaryRelation(operator: String) : Primiti second: Term, third: Term, fourth: Term, - fifth: Term + fifth: Term, ): Substitution - final override fun Solve.Request.computeOne(first: Term, second: Term, third: Term, fourth: Term, fifth: Term): Solve.Response { + final override fun Solve.Request.computeOne( + first: Term, + second: Term, + third: Term, + fourth: Term, + fifth: Term, + ): Solve.Response { return replyWith(computeOneSubstitution(first, second, third, fourth, fifth)) } } @@ -79,10 +90,16 @@ abstract class QuinaryRelation(operator: String) : Primiti second: Term, third: Term, fourth: Term, - fifth: Term + fifth: Term, ): Boolean - final override fun Solve.Request.computeOne(first: Term, second: Term, third: Term, fourth: Term, fifth: Term): Solve.Response { + final override fun Solve.Request.computeOne( + first: Term, + second: Term, + third: Term, + fourth: Term, + fifth: Term, + ): Solve.Response { return if (compute(first, second, third, fourth, fifth)) replySuccess() else replyFail() } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/Solve.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/Solve.kt index b5d39fc24..aeb8cd14a 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/Solve.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/Solve.kt @@ -21,7 +21,6 @@ import kotlin.js.JsName /** A base class for Solve requests and responses */ sealed class Solve { - /** Class representing a Request to be full-filled by the Solver */ data class Request( /** Signature of the goal to be solved in this [Request] */ @@ -36,23 +35,27 @@ sealed class Solve { /** The time instant when the request was submitted for resolution */ override val startTime: TimeInstant = currentTimeInstant(), /** The execution max duration after which the computation should end, because no more useful */ - override val maxDuration: TimeDuration = context.endTime - startTime + override val maxDuration: TimeDuration = context.endTime - startTime, ) : Durable, Solve() { init { when { - signature.vararg -> require(arguments.count() >= signature.arity) { - "Trying to create Solve.Request of signature `$signature` with not enough arguments ${arguments.toList()}" - } - else -> require(arguments.count() == signature.arity) { - "Trying to create Solve.Request of signature `$signature` with wrong number of arguments ${arguments.toList()}" - } + signature.vararg -> + require(arguments.count() >= signature.arity) { + "Trying to create Solve.Request of signature `$signature` " + + "with not enough arguments ${arguments.toList()}" + } + else -> + require(arguments.count() == signature.arity) { + "Trying to create Solve.Request of signature `$signature` " + + "with wrong number of arguments ${arguments.toList()}" + } } require(startTime >= 0) { "The request issuing instant can't be negative: $startTime" } if (maxDuration < 0) { throw TimeOutException( message = "Request's max duration can't be negative: $maxDuration", context = context, - exceededDuration = context.maxDuration + exceededDuration = context.maxDuration, ) } } @@ -70,7 +73,7 @@ sealed class Solve { fun replyWith( substitution: Substitution, sideEffectManager: SideEffectManager? = null, - vararg sideEffects: SideEffect + vararg sideEffects: SideEffect, ) = when (substitution) { is Substitution.Unifier -> replySuccess(substitution, sideEffectManager, *sideEffects) else -> replyFail(sideEffectManager, *sideEffects) @@ -81,7 +84,7 @@ sealed class Solve { fun replyWith( substitution: Substitution, sideEffectManager: SideEffectManager? = null, - buildSideEffects: SideEffectsBuilder.() -> Unit + buildSideEffects: SideEffectsBuilder.() -> Unit, ) = when (substitution) { is Substitution.Unifier -> replySuccess(substitution, sideEffectManager, buildSideEffects) else -> replyFail(sideEffectManager, buildSideEffects) @@ -92,11 +95,11 @@ sealed class Solve { fun replyWith( solution: Solution, sideEffectManager: SideEffectManager? = null, - vararg sideEffects: SideEffect + vararg sideEffects: SideEffect, ) = solution.whenIs( yes = { replySuccess(it.substitution, sideEffectManager, *sideEffects) }, no = { replyFail(sideEffectManager, *sideEffects) }, - halt = { replyException(it.exception, sideEffectManager, *sideEffects) } + halt = { replyException(it.exception, sideEffectManager, *sideEffects) }, ) /** Creates a new [Response] to this Request */ @@ -104,11 +107,11 @@ sealed class Solve { fun replyWith( solution: Solution, sideEffectManager: SideEffectManager? = null, - buildSideEffects: SideEffectsBuilder.() -> Unit + buildSideEffects: SideEffectsBuilder.() -> Unit, ) = solution.whenIs( yes = { replySuccess(it.substitution, sideEffectManager, buildSideEffects) }, no = { replyFail(sideEffectManager, buildSideEffects) }, - halt = { replyException(it.exception, sideEffectManager, buildSideEffects) } + halt = { replyException(it.exception, sideEffectManager, buildSideEffects) }, ) /** Creates a new successful or failed [Response] depending on [condition]; to be used when the substitution doesn't change */ @@ -116,7 +119,7 @@ sealed class Solve { fun replyWith( condition: Boolean, sideEffectManager: SideEffectManager? = null, - vararg sideEffects: SideEffect + vararg sideEffects: SideEffect, ) = if (condition) { replySuccess(Substitution.empty(), sideEffectManager, *sideEffects) } else { @@ -128,7 +131,7 @@ sealed class Solve { fun replyWith( condition: Boolean, sideEffectManager: SideEffectManager? = null, - buildSideEffects: SideEffectsBuilder.() -> Unit + buildSideEffects: SideEffectsBuilder.() -> Unit, ) = if (condition) { replySuccess(Substitution.empty(), sideEffectManager, buildSideEffects) } else { @@ -140,11 +143,11 @@ sealed class Solve { fun replySuccess( substitution: Substitution.Unifier = Substitution.empty(), sideEffectManager: SideEffectManager? = null, - vararg sideEffects: SideEffect + vararg sideEffects: SideEffect, ) = Response( Solution.yes(query, substitution), sideEffectManager, - *sideEffects + *sideEffects, ) /** Creates a new successful [Response] to this Request, with substitution */ @@ -152,33 +155,33 @@ sealed class Solve { fun replySuccess( substitution: Substitution.Unifier = Substitution.empty(), sideEffectManager: SideEffectManager? = null, - buildSideEffects: SideEffectsBuilder.() -> Unit + buildSideEffects: SideEffectsBuilder.() -> Unit, ) = Response( Solution.yes(query, substitution), sideEffectManager, - SideEffectsBuilder.empty().also { it.buildSideEffects() }.build() + SideEffectsBuilder.empty().also { it.buildSideEffects() }.build(), ) /** Creates a new failed [Response] to this Request */ @JsName("replyFail") fun replyFail( sideEffectManager: SideEffectManager? = null, - vararg sideEffects: SideEffect + vararg sideEffects: SideEffect, ) = Response( Solution.no(query), sideEffectManager, - *sideEffects + *sideEffects, ) /** Creates a new failed [Response] to this Request */ @JsName("replyFailBuildingSideEffects") fun replyFail( sideEffectManager: SideEffectManager? = null, - buildSideEffects: SideEffectsBuilder.() -> Unit + buildSideEffects: SideEffectsBuilder.() -> Unit, ) = Response( Solution.no(query), sideEffectManager, - SideEffectsBuilder.empty().also { it.buildSideEffects() }.build() + SideEffectsBuilder.empty().also { it.buildSideEffects() }.build(), ) /** Creates a new halt [Response] to this Request, with cause exception */ @@ -186,11 +189,11 @@ sealed class Solve { fun replyException( exception: ResolutionException, sideEffectManager: SideEffectManager? = null, - vararg sideEffects: SideEffect + vararg sideEffects: SideEffect, ) = Response( Solution.halt(query, exception), sideEffectManager, - *sideEffects + *sideEffects, ) /** Creates a new halt [Response] to this Request, with cause exception */ @@ -198,11 +201,11 @@ sealed class Solve { fun replyException( exception: ResolutionException, sideEffectManager: SideEffectManager? = null, - buildSideEffects: SideEffectsBuilder.() -> Unit + buildSideEffects: SideEffectsBuilder.() -> Unit, ) = Response( Solution.halt(query, exception), sideEffectManager, - SideEffectsBuilder.empty().also { it.buildSideEffects() }.build() + SideEffectsBuilder.empty().also { it.buildSideEffects() }.build(), ) @JsName("subSolver") @@ -211,7 +214,10 @@ sealed class Solve { } @JsName("solve") - fun solve(goal: Struct, maxDuration: TimeDuration = this.maxDuration): Sequence { + fun solve( + goal: Struct, + maxDuration: TimeDuration = this.maxDuration, + ): Sequence { return subSolver().solve(goal, maxDuration) } } @@ -227,24 +233,24 @@ sealed class Solve { /** The (possibly empty) [List] of [SideEffect]s to be applied to the execution context after a primitive has been * executed */ @JsName("sideEffects") - val sideEffects: List + val sideEffects: List, ) : Solve() { constructor( solution: Solution, sideEffectManager: SideEffectManager? = null, - sideEffects: Iterable + sideEffects: Iterable, ) : this(solution, sideEffectManager, sideEffects as? List ?: sideEffects.toList()) constructor( solution: Solution, sideEffectManager: SideEffectManager? = null, - sideEffects: Sequence + sideEffects: Sequence, ) : this(solution, sideEffectManager, sideEffects.asIterable()) constructor( solution: Solution, sideEffectManager: SideEffectManager? = null, - vararg sideEffects: SideEffect + vararg sideEffects: SideEffect, ) : this(solution, sideEffectManager, listOf(*sideEffects)) } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/TernaryRelation.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/TernaryRelation.kt index b48301620..7da7f3cf9 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/TernaryRelation.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/TernaryRelation.kt @@ -6,12 +6,11 @@ import it.unibo.tuprolog.solve.ExecutionContext /** Base class to implement primitives that relate tree [Term]s */ abstract class TernaryRelation(operator: String) : PrimitiveWrapper(operator, 3) { - /** Template method aimed at computing the application of this relation to three [Term]s */ protected abstract fun Solve.Request.computeAll( first: Term, second: Term, - third: Term + third: Term, ): Sequence final override fun uncheckedImplementation(request: Solve.Request): Sequence { @@ -22,13 +21,13 @@ abstract class TernaryRelation(operator: String) : Primiti protected abstract fun Solve.Request.computeAllSubstitutions( first: Term, second: Term, - third: Term + third: Term, ): Sequence final override fun Solve.Request.computeAll( first: Term, second: Term, - third: Term + third: Term, ): Sequence { return computeAllSubstitutions(first, second, third).map { replyWith(it) } } @@ -38,13 +37,13 @@ abstract class TernaryRelation(operator: String) : Primiti protected abstract fun Solve.Request.computeOne( first: Term, second: Term, - third: Term + third: Term, ): Solve.Response final override fun Solve.Request.computeAll( first: Term, second: Term, - third: Term + third: Term, ): Sequence { return sequenceOf(computeOne(first, second, third)) } @@ -54,10 +53,14 @@ abstract class TernaryRelation(operator: String) : Primiti protected abstract fun Solve.Request.computeOneSubstitution( first: Term, second: Term, - third: Term + third: Term, ): Substitution - final override fun Solve.Request.computeOne(first: Term, second: Term, third: Term): Solve.Response { + final override fun Solve.Request.computeOne( + first: Term, + second: Term, + third: Term, + ): Solve.Response { return replyWith(computeOneSubstitution(first, second, third)) } } @@ -66,10 +69,14 @@ abstract class TernaryRelation(operator: String) : Primiti protected abstract fun Solve.Request.compute( first: Term, second: Term, - third: Term + third: Term, ): Boolean - final override fun Solve.Request.computeOne(first: Term, second: Term, third: Term): Solve.Response { + final override fun Solve.Request.computeOne( + first: Term, + second: Term, + third: Term, + ): Solve.Response { return if (compute(first, second, third)) replySuccess() else replyFail() } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/TypeEnsurer.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/TypeEnsurer.kt index 39b75acbc..3fe7f503f 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/TypeEnsurer.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/TypeEnsurer.kt @@ -9,5 +9,8 @@ abstract class TypeEnsurer(typeName: String) : UnaryPredic return true } - abstract fun Solve.Request.ensureType(context: E, term: Term) + abstract fun Solve.Request.ensureType( + context: E, + term: Term, + ) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/UnaryPredicate.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/UnaryPredicate.kt index d865b0986..90b291400 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/UnaryPredicate.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/primitive/UnaryPredicate.kt @@ -6,20 +6,15 @@ import it.unibo.tuprolog.solve.ExecutionContext /** A base class to implement predicates with one argument */ abstract class UnaryPredicate(operator: String) : PrimitiveWrapper(operator, 1) { - /** Template method aimed at computing the application of this predicate to a [Term] */ - protected abstract fun Solve.Request.computeAll( - first: Term - ): Sequence + protected abstract fun Solve.Request.computeAll(first: Term): Sequence final override fun uncheckedImplementation(request: Solve.Request): Sequence { return request.computeAll(request.arguments[0]) } abstract class WithoutSideEffects(operator: String) : UnaryPredicate(operator) { - protected abstract fun Solve.Request.computeAllSubstitutions( - first: Term - ): Sequence + protected abstract fun Solve.Request.computeAllSubstitutions(first: Term): Sequence final override fun Solve.Request.computeAll(first: Term): Sequence { return computeAllSubstitutions(first).map { replyWith(it) } @@ -27,9 +22,7 @@ abstract class UnaryPredicate(operator: String) : Primitiv } abstract class NonBacktrackable(operator: String) : UnaryPredicate(operator) { - protected abstract fun Solve.Request.computeOne( - first: Term - ): Solve.Response + protected abstract fun Solve.Request.computeOne(first: Term): Solve.Response final override fun Solve.Request.computeAll(first: Term): Sequence { return sequenceOf(computeOne(first)) @@ -37,9 +30,7 @@ abstract class UnaryPredicate(operator: String) : Primitiv } abstract class Functional(operator: String) : NonBacktrackable(operator) { - protected abstract fun Solve.Request.computeOneSubstitution( - first: Term - ): Substitution + protected abstract fun Solve.Request.computeOneSubstitution(first: Term): Substitution final override fun Solve.Request.computeOne(first: Term): Solve.Response { return replyWith(computeOneSubstitution(first)) @@ -47,9 +38,7 @@ abstract class UnaryPredicate(operator: String) : Primitiv } abstract class Predicative(operator: String) : NonBacktrackable(operator) { - protected abstract fun Solve.Request.compute( - first: Term - ): Boolean + protected abstract fun Solve.Request.compute(first: Term): Boolean final override fun Solve.Request.computeOne(first: Term): Solve.Response { return if (compute(first)) replySuccess() else replyFail() diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/rule/RuleWrapper.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/rule/RuleWrapper.kt index e41719b8e..cca4929a6 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/rule/RuleWrapper.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/rule/RuleWrapper.kt @@ -12,7 +12,6 @@ import kotlin.collections.List as KtList // TODO: 16/01/2020 document and test this class abstract class RuleWrapper(signature: Signature) : AbstractWrapper(signature) { - constructor(functor: String, arity: Int, vararg: Boolean = false) : this(Signature(functor, arity, vararg)) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/SideEffect.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/SideEffect.kt index fbc040161..c35184d51 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/SideEffect.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/SideEffect.kt @@ -17,7 +17,6 @@ import it.unibo.tuprolog.theory.MutableTheory import it.unibo.tuprolog.theory.Theory abstract class SideEffect { - abstract fun applyTo(context: ExecutionContext): ExecutionContext abstract class SetClausesOfKb(open val clauses: Iterable) : SideEffect() { @@ -51,13 +50,12 @@ abstract class SideEffect { constructor(clauses: Sequence) : this(clauses.asIterable()) - override fun applyTo(context: ExecutionContext): ExecutionContext = - context.update(staticKb = theory(context)) + override fun applyTo(context: ExecutionContext): ExecutionContext = context.update(staticKb = theory(context)) } data class AddStaticClauses( override val clauses: Iterable, - override val onTop: Boolean = false + override val onTop: Boolean = false, ) : AddClausesToKb(clauses, onTop) { constructor(vararg clauses: Clause, onTop: Boolean = false) : this(listOf(*clauses), onTop) @@ -82,12 +80,14 @@ abstract class SideEffect { constructor(clauses: Sequence) : this(clauses.asIterable()) override fun applyTo(context: ExecutionContext): ExecutionContext = - context.update(dynamicKb = mutableTheory(context)) + context.update( + dynamicKb = mutableTheory(context), + ) } data class AddDynamicClauses( override val clauses: Iterable, - override val onTop: Boolean = false + override val onTop: Boolean = false, ) : AddClausesToKb(clauses, onTop) { constructor(vararg clauses: Clause, onTop: Boolean = false) : this(listOf(*clauses), onTop) @@ -95,9 +95,10 @@ abstract class SideEffect { override fun applyTo(context: ExecutionContext): ExecutionContext = context.update( - dynamicKb = context.dynamicKb.let { - if (onTop) it.assertA(clauses) else it.assertZ(clauses) - }.toMutableTheory() + dynamicKb = + context.dynamicKb.let { + if (onTop) it.assertA(clauses) else it.assertZ(clauses) + }.toMutableTheory(), ) } @@ -134,7 +135,9 @@ abstract class SideEffect { constructor(flags: Sequence>) : this(flags.toMap()) override fun applyTo(context: ExecutionContext): ExecutionContext = - context.update(flags = context.flags + flags) + context.update( + flags = context.flags + flags, + ) } data class ResetFlags(override val flags: Map) : AlterFlagsByEntries(flags) { @@ -144,8 +147,7 @@ abstract class SideEffect { constructor(flags: Sequence>) : this(flags.toMap()) - override fun applyTo(context: ExecutionContext): ExecutionContext = - context.update(flags = flagStore) + override fun applyTo(context: ExecutionContext): ExecutionContext = context.update(flags = flagStore) } data class ClearFlags(override val names: Iterable) : AlterFlagsByName(names) { @@ -154,7 +156,9 @@ abstract class SideEffect { constructor(names: Sequence) : this(names.toList()) override fun applyTo(context: ExecutionContext): ExecutionContext = - context.update(flags = context.flags - names) + context.update( + flags = context.flags - names, + ) } abstract class AlterRuntime : SideEffect() @@ -182,7 +186,9 @@ abstract class SideEffect { constructor(vararg aliases: String) : this(listOf(*aliases)) override fun applyTo(context: ExecutionContext): ExecutionContext = - context.update(libraries = context.libraries - aliases) + context.update( + libraries = context.libraries - aliases, + ) } data class UpdateLibrary(override val library: Library) : AlterLibrary(library) { @@ -198,7 +204,9 @@ abstract class SideEffect { constructor(vararg libraries: Library) : this(Runtime.of(*libraries)) override fun applyTo(context: ExecutionContext): ExecutionContext = - context.update(libraries = context.libraries + libraries) + context.update( + libraries = context.libraries + libraries, + ) } data class ResetRuntime(override val libraries: Runtime) : AlterAliasedRuntime() { @@ -208,8 +216,7 @@ abstract class SideEffect { constructor(vararg libraries: Library) : this(Runtime.of(*libraries)) - override fun applyTo(context: ExecutionContext): ExecutionContext = - context.update(libraries = libraries) + override fun applyTo(context: ExecutionContext): ExecutionContext = context.update(libraries = libraries) } abstract class AlterOperators(open val operators: Iterable) : SideEffect() { @@ -230,7 +237,9 @@ abstract class SideEffect { constructor(operators: Sequence) : this(operators.toOperatorSet()) override fun applyTo(context: ExecutionContext): ExecutionContext = - context.update(operators = context.operators + operatorSet) + context.update( + operators = context.operators + operatorSet, + ) } data class ResetOperators(override val operators: Iterable) : AlterOperators(operators) { @@ -239,7 +248,9 @@ abstract class SideEffect { constructor(operators: Sequence) : this(operators.toOperatorSet()) override fun applyTo(context: ExecutionContext): ExecutionContext = - context.update(operators = context.operators + operatorSet) + context.update( + operators = context.operators + operatorSet, + ) } data class RemoveOperators(override val operators: Iterable) : AlterOperators(operators) { @@ -248,7 +259,9 @@ abstract class SideEffect { constructor(operators: Sequence) : this(operators.toOperatorSet()) override fun applyTo(context: ExecutionContext): ExecutionContext = - context.update(operators = context.operators - operatorSet) + context.update( + operators = context.operators - operatorSet, + ) } abstract class AlterChannels : SideEffect() @@ -260,7 +273,7 @@ abstract class SideEffect { abstract class AlterOutputChannels(open val outputChannels: Map>) : AlterChannels() data class OpenInputChannels( - override val inputChannels: Map> + override val inputChannels: Map>, ) : AlterInputChannels(inputChannels) { constructor(vararg inputChannels: Pair>) : this(listOf(*inputChannels)) @@ -273,7 +286,7 @@ abstract class SideEffect { } data class ResetInputChannels( - override val inputChannels: Map> + override val inputChannels: Map>, ) : AlterInputChannels(inputChannels) { constructor(vararg inputChannels: Pair>) : this(listOf(*inputChannels)) @@ -282,7 +295,9 @@ abstract class SideEffect { constructor(inputChannels: Sequence>>) : this(inputChannels.toMap()) override fun applyTo(context: ExecutionContext): ExecutionContext = - context.update(inputChannels = InputStore.of(inputChannels)) + context.update( + inputChannels = InputStore.of(inputChannels), + ) } data class CloseInputChannels(override val names: Iterable) : AlterChannelsByName(names) { @@ -291,11 +306,13 @@ abstract class SideEffect { constructor(names: Sequence) : this(names.toList()) override fun applyTo(context: ExecutionContext): ExecutionContext = - context.update(inputChannels = context.inputChannels - names) + context.update( + inputChannels = context.inputChannels - names, + ) } data class OpenOutputChannels( - override val outputChannels: Map> + override val outputChannels: Map>, ) : AlterOutputChannels(outputChannels) { constructor(vararg outputChannels: Pair>) : this(listOf(*outputChannels)) @@ -308,7 +325,7 @@ abstract class SideEffect { } data class ResetOutputChannels( - override val outputChannels: Map> + override val outputChannels: Map>, ) : AlterOutputChannels(outputChannels) { constructor(vararg outputChannels: Pair>) : this(listOf(*outputChannels)) @@ -317,7 +334,9 @@ abstract class SideEffect { constructor(outputChannels: Sequence>>) : this(outputChannels.toMap()) override fun applyTo(context: ExecutionContext): ExecutionContext = - context.update(outputChannels = OutputStore.of(outputChannels)) + context.update( + outputChannels = OutputStore.of(outputChannels), + ) } data class CloseOutputChannels(override val names: Iterable) : AlterChannelsByName(names) { @@ -326,14 +345,16 @@ abstract class SideEffect { constructor(names: Sequence) : this(names.toList()) override fun applyTo(context: ExecutionContext): ExecutionContext = - context.update(outputChannels = context.outputChannels - names) + context.update( + outputChannels = context.outputChannels - names, + ) } abstract class AlterCustomData(open val data: Map, open val reset: Boolean = false) : SideEffect() data class SetPersistentData( override val data: Map, - override val reset: Boolean = false + override val reset: Boolean = false, ) : AlterCustomData(data, reset) { constructor(key: String, value: Any, reset: Boolean = false) : this(listOf(key to value), reset) @@ -343,19 +364,21 @@ abstract class SideEffect { override fun applyTo(context: ExecutionContext): ExecutionContext = context.update( - customData = context.customData.copy( - persistent = if (reset) { - data - } else { - context.customData.persistent + data - } - ) + customData = + context.customData.copy( + persistent = + if (reset) { + data + } else { + context.customData.persistent + data + }, + ), ) } data class SetDurableData( override val data: Map, - override val reset: Boolean = false + override val reset: Boolean = false, ) : AlterCustomData(data, reset) { constructor(key: String, value: Any, reset: Boolean = false) : this(listOf(key to value), reset) @@ -365,19 +388,21 @@ abstract class SideEffect { override fun applyTo(context: ExecutionContext): ExecutionContext = context.update( - customData = context.customData.copy( - durable = if (reset) { - data - } else { - context.customData.durable + data - } - ) + customData = + context.customData.copy( + durable = + if (reset) { + data + } else { + context.customData.durable + data + }, + ), ) } data class SetEphemeralData( override val data: Map, - override val reset: Boolean = false + override val reset: Boolean = false, ) : AlterCustomData(data, reset) { constructor(key: String, value: Any, reset: Boolean = false) : this(listOf(key to value), reset) @@ -387,13 +412,15 @@ abstract class SideEffect { override fun applyTo(context: ExecutionContext): ExecutionContext = context.update( - customData = context.customData.copy( - ephemeral = if (reset) { - data - } else { - context.customData.ephemeral + data - } - ) + customData = + context.customData.copy( + ephemeral = + if (reset) { + data + } else { + context.customData.ephemeral + data + }, + ), ) } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/SideEffectFactory.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/SideEffectFactory.kt index d6e619442..066f9bfde 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/SideEffectFactory.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/SideEffectFactory.kt @@ -11,7 +11,6 @@ import it.unibo.tuprolog.solve.sideffects.impl.DefaultSideEffectFactory import kotlin.jvm.JvmStatic interface SideEffectFactory { - companion object { @JvmStatic val default: SideEffectFactory = DefaultSideEffectFactory @@ -23,11 +22,20 @@ interface SideEffectFactory { fun resetStaticKb(vararg clauses: Clause): SideEffect.ResetStaticKb - fun addStaticClauses(clauses: Iterable, onTop: Boolean = false): SideEffect.AddStaticClauses + fun addStaticClauses( + clauses: Iterable, + onTop: Boolean = false, + ): SideEffect.AddStaticClauses - fun addStaticClauses(clauses: Sequence, onTop: Boolean = false): SideEffect.AddStaticClauses + fun addStaticClauses( + clauses: Sequence, + onTop: Boolean = false, + ): SideEffect.AddStaticClauses - fun addStaticClauses(vararg clauses: Clause, onTop: Boolean = false): SideEffect.AddStaticClauses + fun addStaticClauses( + vararg clauses: Clause, + onTop: Boolean = false, + ): SideEffect.AddStaticClauses fun removeStaticClauses(clauses: Iterable): SideEffect.RemoveStaticClauses @@ -41,11 +49,20 @@ interface SideEffectFactory { fun resetDynamicKb(vararg clauses: Clause): SideEffect.ResetDynamicKb - fun addDynamicClauses(clauses: Iterable, onTop: Boolean = false): SideEffect.AddDynamicClauses + fun addDynamicClauses( + clauses: Iterable, + onTop: Boolean = false, + ): SideEffect.AddDynamicClauses - fun addDynamicClauses(clauses: Sequence, onTop: Boolean = false): SideEffect.AddDynamicClauses + fun addDynamicClauses( + clauses: Sequence, + onTop: Boolean = false, + ): SideEffect.AddDynamicClauses - fun addDynamicClauses(vararg clauses: Clause, onTop: Boolean = false): SideEffect.AddDynamicClauses + fun addDynamicClauses( + vararg clauses: Clause, + onTop: Boolean = false, + ): SideEffect.AddDynamicClauses fun removeDynamicClauses(clauses: Iterable): SideEffect.RemoveDynamicClauses @@ -57,7 +74,10 @@ interface SideEffectFactory { fun setFlags(vararg flags: Pair): SideEffect.SetFlags - fun setFlag(name: String, value: Term): SideEffect.SetFlags + fun setFlag( + name: String, + value: Term, + ): SideEffect.SetFlags fun resetFlags(flags: Map): SideEffect.ResetFlags @@ -117,7 +137,10 @@ interface SideEffectFactory { fun openInputChannels(vararg inputChannels: Pair>): SideEffect.OpenInputChannels - fun openInputChannel(name: String, inputChannel: InputChannel): SideEffect.OpenInputChannels + fun openInputChannel( + name: String, + inputChannel: InputChannel, + ): SideEffect.OpenInputChannels fun resetInputChannels(vararg inputChannels: Pair>): SideEffect.ResetInputChannels @@ -137,11 +160,18 @@ interface SideEffectFactory { fun openOutputChannels(vararg outputChannels: Pair>): SideEffect.OpenOutputChannels - fun openOutputChannel(name: String, outputChannel: OutputChannel): SideEffect.OpenOutputChannels + fun openOutputChannel( + name: String, + outputChannel: OutputChannel, + ): SideEffect.OpenOutputChannels - fun resetOutputChannels(outputChannels: Iterable>>): SideEffect.ResetOutputChannels + fun resetOutputChannels( + outputChannels: Iterable>>, + ): SideEffect.ResetOutputChannels - fun resetOutputChannels(outputChannels: Sequence>>): SideEffect.ResetOutputChannels + fun resetOutputChannels( + outputChannels: Sequence>>, + ): SideEffect.ResetOutputChannels fun resetOutputChannels(outputChannels: Map>): SideEffect.ResetOutputChannels @@ -153,37 +183,55 @@ interface SideEffectFactory { fun closeOutputChannels(vararg names: String): SideEffect.CloseOutputChannels - fun addEphemeralData(key: String, value: Any): SideEffect.SetEphemeralData + fun addEphemeralData( + key: String, + value: Any, + ): SideEffect.SetEphemeralData fun addEphemeralData(data: Map): SideEffect.SetEphemeralData fun addEphemeralData(vararg data: Pair): SideEffect.SetEphemeralData - fun setEphemeralData(key: String, value: Any): SideEffect.SetEphemeralData + fun setEphemeralData( + key: String, + value: Any, + ): SideEffect.SetEphemeralData fun setEphemeralData(data: Map): SideEffect.SetEphemeralData fun setEphemeralData(vararg data: Pair): SideEffect.SetEphemeralData - fun addDurableData(key: String, value: Any): SideEffect.SetDurableData + fun addDurableData( + key: String, + value: Any, + ): SideEffect.SetDurableData fun addDurableData(data: Map): SideEffect.SetDurableData fun addDurableData(vararg data: Pair): SideEffect.SetDurableData - fun setDurableData(key: String, value: Any): SideEffect.SetDurableData + fun setDurableData( + key: String, + value: Any, + ): SideEffect.SetDurableData fun setDurableData(data: Map): SideEffect.SetDurableData fun setDurableData(vararg data: Pair): SideEffect.SetDurableData - fun addPersistentData(key: String, value: Any): SideEffect.SetPersistentData + fun addPersistentData( + key: String, + value: Any, + ): SideEffect.SetPersistentData fun addPersistentData(data: Map): SideEffect.SetPersistentData fun addPersistentData(vararg data: Pair): SideEffect.SetPersistentData - fun setPersistentData(key: String, value: Any): SideEffect.SetPersistentData + fun setPersistentData( + key: String, + value: Any, + ): SideEffect.SetPersistentData fun setPersistentData(data: Map): SideEffect.SetPersistentData diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/SideEffectManager.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/SideEffectManager.kt index 38f468242..0f533a857 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/SideEffectManager.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/SideEffectManager.kt @@ -8,7 +8,6 @@ import kotlin.js.JsName * @author Enrico */ interface SideEffectManager { - /** A function to execute cut, and return a new [SideEffectManager] with executed cut */ @JsName("cut") fun cut(): SideEffectManager diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/SideEffectsBuilder.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/SideEffectsBuilder.kt index 556f3998a..4fb84fcfc 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/SideEffectsBuilder.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/SideEffectsBuilder.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.utils.dequeOf import kotlin.jvm.JvmStatic interface SideEffectsBuilder : SideEffectFactory { - val sideEffects: MutableList fun buildArray(): Array = sideEffects.toTypedArray() @@ -14,19 +13,15 @@ interface SideEffectsBuilder : SideEffectFactory { companion object { @JvmStatic - fun empty(): SideEffectsBuilder = - SideEffectsBuilderImpl(dequeOf()) + fun empty(): SideEffectsBuilder = SideEffectsBuilderImpl(dequeOf()) @JvmStatic - fun of(sideEffects: Iterable): SideEffectsBuilder = - SideEffectsBuilderImpl(dequeOf(sideEffects)) + fun of(sideEffects: Iterable): SideEffectsBuilder = SideEffectsBuilderImpl(dequeOf(sideEffects)) @JvmStatic - fun of(sideEffects: Sequence): SideEffectsBuilder = - SideEffectsBuilderImpl(dequeOf(sideEffects)) + fun of(sideEffects: Sequence): SideEffectsBuilder = SideEffectsBuilderImpl(dequeOf(sideEffects)) @JvmStatic - fun of(vararg sideEffects: SideEffect): SideEffectsBuilder = - SideEffectsBuilderImpl(dequeOf(*sideEffects)) + fun of(vararg sideEffects: SideEffect): SideEffectsBuilder = SideEffectsBuilderImpl(dequeOf(*sideEffects)) } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/impl/DefaultSideEffectFactory.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/impl/DefaultSideEffectFactory.kt index 8a46a5d08..7057e5345 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/impl/DefaultSideEffectFactory.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/impl/DefaultSideEffectFactory.kt @@ -11,158 +11,137 @@ import it.unibo.tuprolog.solve.sideffects.SideEffect import it.unibo.tuprolog.solve.sideffects.SideEffectFactory internal object DefaultSideEffectFactory : SideEffectFactory { - override fun resetStaticKb(clauses: Iterable) = - SideEffect.ResetStaticKb(clauses) + override fun resetStaticKb(clauses: Iterable) = SideEffect.ResetStaticKb(clauses) - override fun resetStaticKb(clauses: Sequence) = - SideEffect.ResetStaticKb(clauses) + override fun resetStaticKb(clauses: Sequence) = SideEffect.ResetStaticKb(clauses) - override fun resetStaticKb(vararg clauses: Clause) = - SideEffect.ResetStaticKb(*clauses) + override fun resetStaticKb(vararg clauses: Clause) = SideEffect.ResetStaticKb(*clauses) - override fun addStaticClauses(clauses: Iterable, onTop: Boolean) = - SideEffect.AddStaticClauses(clauses, onTop) + override fun addStaticClauses( + clauses: Iterable, + onTop: Boolean, + ) = SideEffect.AddStaticClauses(clauses, onTop) - override fun addStaticClauses(clauses: Sequence, onTop: Boolean) = - SideEffect.AddStaticClauses(clauses, onTop) + override fun addStaticClauses( + clauses: Sequence, + onTop: Boolean, + ) = SideEffect.AddStaticClauses(clauses, onTop) - override fun addStaticClauses(vararg clauses: Clause, onTop: Boolean) = - SideEffect.AddStaticClauses(*clauses, onTop = onTop) + override fun addStaticClauses( + vararg clauses: Clause, + onTop: Boolean, + ) = SideEffect.AddStaticClauses(*clauses, onTop = onTop) - override fun removeStaticClauses(clauses: Iterable) = - SideEffect.RemoveStaticClauses(clauses) + override fun removeStaticClauses(clauses: Iterable) = SideEffect.RemoveStaticClauses(clauses) - override fun removeStaticClauses(clauses: Sequence) = - SideEffect.RemoveStaticClauses(clauses) + override fun removeStaticClauses(clauses: Sequence) = SideEffect.RemoveStaticClauses(clauses) - override fun removeStaticClauses(vararg clauses: Clause) = - SideEffect.RemoveStaticClauses(*clauses) + override fun removeStaticClauses(vararg clauses: Clause) = SideEffect.RemoveStaticClauses(*clauses) - override fun resetDynamicKb(clauses: Iterable) = - SideEffect.ResetDynamicKb(clauses) + override fun resetDynamicKb(clauses: Iterable) = SideEffect.ResetDynamicKb(clauses) - override fun resetDynamicKb(clauses: Sequence) = - SideEffect.ResetDynamicKb(clauses) + override fun resetDynamicKb(clauses: Sequence) = SideEffect.ResetDynamicKb(clauses) - override fun resetDynamicKb(vararg clauses: Clause) = - SideEffect.ResetDynamicKb(*clauses) + override fun resetDynamicKb(vararg clauses: Clause) = SideEffect.ResetDynamicKb(*clauses) - override fun addDynamicClauses(clauses: Iterable, onTop: Boolean) = - SideEffect.AddDynamicClauses(clauses, onTop) + override fun addDynamicClauses( + clauses: Iterable, + onTop: Boolean, + ) = SideEffect.AddDynamicClauses(clauses, onTop) - override fun addDynamicClauses(clauses: Sequence, onTop: Boolean) = - SideEffect.AddDynamicClauses(clauses, onTop) + override fun addDynamicClauses( + clauses: Sequence, + onTop: Boolean, + ) = SideEffect.AddDynamicClauses(clauses, onTop) - override fun addDynamicClauses(vararg clauses: Clause, onTop: Boolean) = - SideEffect.AddDynamicClauses(*clauses, onTop = onTop) + override fun addDynamicClauses( + vararg clauses: Clause, + onTop: Boolean, + ) = SideEffect.AddDynamicClauses(*clauses, onTop = onTop) - override fun removeDynamicClauses(clauses: Iterable) = - SideEffect.RemoveDynamicClauses(clauses) + override fun removeDynamicClauses(clauses: Iterable) = SideEffect.RemoveDynamicClauses(clauses) - override fun removeDynamicClauses(clauses: Sequence) = - SideEffect.RemoveDynamicClauses(clauses) + override fun removeDynamicClauses(clauses: Sequence) = SideEffect.RemoveDynamicClauses(clauses) - override fun removeDynamicClauses(vararg clauses: Clause) = - SideEffect.RemoveDynamicClauses(*clauses) + override fun removeDynamicClauses(vararg clauses: Clause) = SideEffect.RemoveDynamicClauses(*clauses) - override fun setFlags(flags: Map) = - SideEffect.SetFlags(flags) + override fun setFlags(flags: Map) = SideEffect.SetFlags(flags) - override fun setFlags(vararg flags: Pair) = - SideEffect.SetFlags(*flags) + override fun setFlags(vararg flags: Pair) = SideEffect.SetFlags(*flags) - override fun setFlag(name: String, value: Term) = - SideEffect.SetFlags(name to value) + override fun setFlag( + name: String, + value: Term, + ) = SideEffect.SetFlags(name to value) - override fun resetFlags(flags: Map) = - SideEffect.ResetFlags(flags) + override fun resetFlags(flags: Map) = SideEffect.ResetFlags(flags) - override fun resetFlags(vararg flags: Pair) = - SideEffect.ResetFlags(*flags) + override fun resetFlags(vararg flags: Pair) = SideEffect.ResetFlags(*flags) - override fun clearFlags(names: Iterable) = - SideEffect.ClearFlags(names) + override fun clearFlags(names: Iterable) = SideEffect.ClearFlags(names) - override fun clearFlags(names: Sequence) = - SideEffect.ClearFlags(names) + override fun clearFlags(names: Sequence) = SideEffect.ClearFlags(names) - override fun clearFlags(vararg names: String) = - SideEffect.ClearFlags(*names) + override fun clearFlags(vararg names: String) = SideEffect.ClearFlags(*names) - override fun loadLibrary(library: Library) = - SideEffect.LoadLibrary(library) + override fun loadLibrary(library: Library) = SideEffect.LoadLibrary(library) - override fun unloadLibraries(aliases: Iterable) = - SideEffect.UnloadLibraries(aliases) + override fun unloadLibraries(aliases: Iterable) = SideEffect.UnloadLibraries(aliases) - override fun unloadLibraries(aliases: Sequence) = - SideEffect.UnloadLibraries(aliases) + override fun unloadLibraries(aliases: Sequence) = SideEffect.UnloadLibraries(aliases) - override fun unloadLibraries(vararg aliases: String) = - SideEffect.UnloadLibraries(*aliases) + override fun unloadLibraries(vararg aliases: String) = SideEffect.UnloadLibraries(*aliases) - override fun updateLibrary(library: Library) = - SideEffect.UpdateLibrary(library) + override fun updateLibrary(library: Library) = SideEffect.UpdateLibrary(library) - override fun resetRuntime(libraries: Runtime) = - SideEffect.ResetRuntime(libraries) + override fun resetRuntime(libraries: Runtime) = SideEffect.ResetRuntime(libraries) - override fun resetRuntime(libraries: Iterable) = - SideEffect.ResetRuntime(libraries) + override fun resetRuntime(libraries: Iterable) = SideEffect.ResetRuntime(libraries) - override fun resetRuntime(libraries: Sequence) = - SideEffect.ResetRuntime(libraries) + override fun resetRuntime(libraries: Sequence) = SideEffect.ResetRuntime(libraries) - override fun resetRuntime(vararg libraries: Library) = - SideEffect.ResetRuntime(*libraries) + override fun resetRuntime(vararg libraries: Library) = SideEffect.ResetRuntime(*libraries) - override fun addLibraries(libraries: Runtime) = - SideEffect.AddLibraries(libraries) + override fun addLibraries(libraries: Runtime) = SideEffect.AddLibraries(libraries) - override fun addLibraries(libraries: Iterable) = - SideEffect.AddLibraries(libraries) + override fun addLibraries(libraries: Iterable) = SideEffect.AddLibraries(libraries) - override fun addLibraries(libraries: Sequence) = - SideEffect.AddLibraries(libraries) + override fun addLibraries(libraries: Sequence) = SideEffect.AddLibraries(libraries) - override fun addLibraries(vararg libraries: Library) = - SideEffect.AddLibraries(*libraries) + override fun addLibraries(vararg libraries: Library) = SideEffect.AddLibraries(*libraries) - override fun setOperators(operators: Iterable) = - SideEffect.SetOperators(operators) + override fun setOperators(operators: Iterable) = SideEffect.SetOperators(operators) - override fun setOperators(operators: Sequence) = - SideEffect.SetOperators(operators) + override fun setOperators(operators: Sequence) = SideEffect.SetOperators(operators) - override fun setOperators(vararg operators: Operator) = - SideEffect.SetOperators(*operators) + override fun setOperators(vararg operators: Operator) = SideEffect.SetOperators(*operators) - override fun resetOperators(operators: Iterable) = - SideEffect.ResetOperators(operators) + override fun resetOperators(operators: Iterable) = SideEffect.ResetOperators(operators) - override fun resetOperators(operators: Sequence) = - SideEffect.ResetOperators(operators) + override fun resetOperators(operators: Sequence) = SideEffect.ResetOperators(operators) - override fun resetOperators(vararg operators: Operator) = - SideEffect.ResetOperators(*operators) + override fun resetOperators(vararg operators: Operator) = SideEffect.ResetOperators(*operators) - override fun removeOperators(operators: Iterable) = - SideEffect.RemoveOperators(operators) + override fun removeOperators(operators: Iterable) = SideEffect.RemoveOperators(operators) - override fun removeOperators(operators: Sequence) = - SideEffect.RemoveOperators(operators) + override fun removeOperators(operators: Sequence) = SideEffect.RemoveOperators(operators) - override fun removeOperators(vararg operators: Operator) = - SideEffect.RemoveOperators(*operators) + override fun removeOperators(vararg operators: Operator) = SideEffect.RemoveOperators(*operators) override fun openInputChannels(inputChannels: Map>) = - SideEffect.OpenInputChannels(inputChannels) + SideEffect.OpenInputChannels( + inputChannels, + ) override fun openInputChannels(vararg inputChannels: Pair>) = - SideEffect.OpenInputChannels(*inputChannels) + SideEffect.OpenInputChannels( + *inputChannels, + ) - override fun openInputChannel(name: String, inputChannel: InputChannel) = - SideEffect.OpenInputChannels(name to inputChannel) + override fun openInputChannel( + name: String, + inputChannel: InputChannel, + ) = SideEffect.OpenInputChannels(name to inputChannel) override fun resetInputChannels(vararg inputChannels: Pair>) = SideEffect.ResetInputChannels(*inputChannels) @@ -174,25 +153,28 @@ internal object DefaultSideEffectFactory : SideEffectFactory { SideEffect.ResetInputChannels(inputChannels) override fun resetInputChannels(inputChannels: Map>) = - SideEffect.ResetInputChannels(inputChannels) + SideEffect.ResetInputChannels( + inputChannels, + ) - override fun closeInputChannels(names: Iterable) = - SideEffect.CloseInputChannels(names) + override fun closeInputChannels(names: Iterable) = SideEffect.CloseInputChannels(names) - override fun closeInputChannels(names: Sequence) = - SideEffect.CloseInputChannels(names) + override fun closeInputChannels(names: Sequence) = SideEffect.CloseInputChannels(names) - override fun closeInputChannels(vararg names: String) = - SideEffect.CloseInputChannels(*names) + override fun closeInputChannels(vararg names: String) = SideEffect.CloseInputChannels(*names) override fun openOutputChannels(outputChannels: Map>) = - SideEffect.OpenOutputChannels(outputChannels) + SideEffect.OpenOutputChannels( + outputChannels, + ) override fun openOutputChannels(vararg outputChannels: Pair>) = SideEffect.OpenOutputChannels(*outputChannels) - override fun openOutputChannel(name: String, outputChannel: OutputChannel) = - SideEffect.OpenOutputChannels(name to outputChannel) + override fun openOutputChannel( + name: String, + outputChannel: OutputChannel, + ) = SideEffect.OpenOutputChannels(name to outputChannel) override fun resetOutputChannels(outputChannels: Iterable>>) = SideEffect.ResetOutputChannels(outputChannels) @@ -201,70 +183,107 @@ internal object DefaultSideEffectFactory : SideEffectFactory { SideEffect.ResetOutputChannels(outputChannels) override fun resetOutputChannels(outputChannels: Map>) = - SideEffect.ResetOutputChannels(outputChannels) + SideEffect.ResetOutputChannels( + outputChannels, + ) override fun resetOutputChannels(vararg outputChannels: Pair>) = SideEffect.ResetOutputChannels(*outputChannels) - override fun closeOutputChannels(names: Iterable) = - SideEffect.CloseOutputChannels(names) + override fun closeOutputChannels(names: Iterable) = SideEffect.CloseOutputChannels(names) - override fun closeOutputChannels(names: Sequence) = - SideEffect.CloseOutputChannels(names) + override fun closeOutputChannels(names: Sequence) = SideEffect.CloseOutputChannels(names) - override fun closeOutputChannels(vararg names: String) = - SideEffect.CloseOutputChannels(*names) + override fun closeOutputChannels(vararg names: String) = SideEffect.CloseOutputChannels(*names) - override fun addEphemeralData(key: String, value: Any) = - SideEffect.SetEphemeralData(key, value, reset = false) + override fun addEphemeralData( + key: String, + value: Any, + ) = SideEffect.SetEphemeralData(key, value, reset = false) override fun addEphemeralData(data: Map) = - SideEffect.SetEphemeralData(data.mapValues { it }, reset = false) + SideEffect.SetEphemeralData( + data.mapValues { + it + }, + reset = false, + ) override fun addEphemeralData(vararg data: Pair) = SideEffect.SetEphemeralData(data.map { (a, b) -> a to (b as Any) }, reset = false) - override fun setEphemeralData(key: String, value: Any) = - SideEffect.SetEphemeralData(key, value, reset = false) + override fun setEphemeralData( + key: String, + value: Any, + ) = SideEffect.SetEphemeralData(key, value, reset = false) override fun setEphemeralData(data: Map) = - SideEffect.SetEphemeralData(data.mapValues { it }, reset = false) + SideEffect.SetEphemeralData( + data.mapValues { + it + }, + reset = false, + ) override fun setEphemeralData(vararg data: Pair) = SideEffect.SetEphemeralData(data.map { (a, b) -> a to (b as Any) }, reset = false) - override fun addDurableData(key: String, value: Any) = - SideEffect.SetDurableData(key, value, reset = false) + override fun addDurableData( + key: String, + value: Any, + ) = SideEffect.SetDurableData(key, value, reset = false) override fun addDurableData(data: Map) = - SideEffect.SetDurableData(data.mapValues { it }, reset = false) + SideEffect.SetDurableData( + data.mapValues { it }, + reset = false, + ) override fun addDurableData(vararg data: Pair) = SideEffect.SetDurableData(data.map { (a, b) -> a to (b as Any) }, reset = false) - override fun setDurableData(key: String, value: Any) = - SideEffect.SetDurableData(key, value, reset = false) + override fun setDurableData( + key: String, + value: Any, + ) = SideEffect.SetDurableData(key, value, reset = false) override fun setDurableData(data: Map) = - SideEffect.SetDurableData(data.mapValues { it }, reset = false) + SideEffect.SetDurableData( + data.mapValues { it }, + reset = false, + ) override fun setDurableData(vararg data: Pair) = SideEffect.SetDurableData(data.map { (a, b) -> a to (b as Any) }, reset = false) - override fun addPersistentData(key: String, value: Any) = - SideEffect.SetPersistentData(key, value, reset = false) + override fun addPersistentData( + key: String, + value: Any, + ) = SideEffect.SetPersistentData(key, value, reset = false) override fun addPersistentData(data: Map) = - SideEffect.SetPersistentData(data.mapValues { it }, reset = false) + SideEffect.SetPersistentData( + data.mapValues { + it + }, + reset = false, + ) override fun addPersistentData(vararg data: Pair) = SideEffect.SetPersistentData(data.map { (a, b) -> a to (b as Any) }, reset = false) - override fun setPersistentData(key: String, value: Any) = - SideEffect.SetPersistentData(key, value, reset = false) + override fun setPersistentData( + key: String, + value: Any, + ) = SideEffect.SetPersistentData(key, value, reset = false) override fun setPersistentData(data: Map) = - SideEffect.SetPersistentData(data.mapValues { it }, reset = false) + SideEffect.SetPersistentData( + data.mapValues { + it + }, + reset = false, + ) override fun setPersistentData(vararg data: Pair) = SideEffect.SetPersistentData(data.map { (a, b) -> a to (b as Any) }, reset = false) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/impl/SideEffectsBuilderImpl.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/impl/SideEffectsBuilderImpl.kt index fae25db02..0de019735 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/impl/SideEffectsBuilderImpl.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/sideffects/impl/SideEffectsBuilderImpl.kt @@ -13,27 +13,39 @@ import it.unibo.tuprolog.solve.sideffects.SideEffectsBuilder internal data class SideEffectsBuilderImpl( override val sideEffects: MutableList, - private val factory: SideEffectFactory = DefaultSideEffectFactory + private val factory: SideEffectFactory = DefaultSideEffectFactory, ) : SideEffectsBuilder { private fun adding(f: () -> T): T = f().also { sideEffects.add(it) } override fun resetStaticKb(clauses: Iterable): SideEffect.ResetStaticKb = - adding { factory.resetStaticKb(clauses) } + adding { + factory.resetStaticKb(clauses) + } override fun resetStaticKb(clauses: Sequence): SideEffect.ResetStaticKb = - adding { factory.resetStaticKb(clauses) } + adding { + factory.resetStaticKb(clauses) + } override fun resetStaticKb(vararg clauses: Clause): SideEffect.ResetStaticKb = - adding { factory.resetStaticKb(*clauses) } + adding { + factory.resetStaticKb(*clauses) + } - override fun addStaticClauses(clauses: Iterable, onTop: Boolean): SideEffect.AddStaticClauses = - adding { factory.addStaticClauses(clauses, onTop) } + override fun addStaticClauses( + clauses: Iterable, + onTop: Boolean, + ): SideEffect.AddStaticClauses = adding { factory.addStaticClauses(clauses, onTop) } - override fun addStaticClauses(clauses: Sequence, onTop: Boolean): SideEffect.AddStaticClauses = - adding { factory.addStaticClauses(clauses, onTop) } + override fun addStaticClauses( + clauses: Sequence, + onTop: Boolean, + ): SideEffect.AddStaticClauses = adding { factory.addStaticClauses(clauses, onTop) } - override fun addStaticClauses(vararg clauses: Clause, onTop: Boolean): SideEffect.AddStaticClauses = - adding { factory.addStaticClauses(*clauses, onTop = onTop) } + override fun addStaticClauses( + vararg clauses: Clause, + onTop: Boolean, + ): SideEffect.AddStaticClauses = adding { factory.addStaticClauses(*clauses, onTop = onTop) } override fun removeStaticClauses(clauses: Iterable): SideEffect.RemoveStaticClauses = adding { factory.removeStaticClauses(clauses) } @@ -45,22 +57,34 @@ internal data class SideEffectsBuilderImpl( adding { factory.removeStaticClauses(*clauses) } override fun resetDynamicKb(clauses: Iterable): SideEffect.ResetDynamicKb = - adding { factory.resetDynamicKb(clauses) } + adding { + factory.resetDynamicKb(clauses) + } override fun resetDynamicKb(clauses: Sequence): SideEffect.ResetDynamicKb = - adding { factory.resetDynamicKb(clauses) } + adding { + factory.resetDynamicKb(clauses) + } override fun resetDynamicKb(vararg clauses: Clause): SideEffect.ResetDynamicKb = - adding { factory.resetDynamicKb(*clauses) } + adding { + factory.resetDynamicKb(*clauses) + } - override fun addDynamicClauses(clauses: Iterable, onTop: Boolean): SideEffect.AddDynamicClauses = - adding { factory.addDynamicClauses(clauses, onTop) } + override fun addDynamicClauses( + clauses: Iterable, + onTop: Boolean, + ): SideEffect.AddDynamicClauses = adding { factory.addDynamicClauses(clauses, onTop) } - override fun addDynamicClauses(clauses: Sequence, onTop: Boolean): SideEffect.AddDynamicClauses = - adding { factory.addDynamicClauses(clauses, onTop) } + override fun addDynamicClauses( + clauses: Sequence, + onTop: Boolean, + ): SideEffect.AddDynamicClauses = adding { factory.addDynamicClauses(clauses, onTop) } - override fun addDynamicClauses(vararg clauses: Clause, onTop: Boolean): SideEffect.AddDynamicClauses = - adding { factory.addDynamicClauses(*clauses, onTop = onTop) } + override fun addDynamicClauses( + vararg clauses: Clause, + onTop: Boolean, + ): SideEffect.AddDynamicClauses = adding { factory.addDynamicClauses(*clauses, onTop = onTop) } override fun removeDynamicClauses(clauses: Iterable): SideEffect.RemoveDynamicClauses = adding { factory.removeDynamicClauses(clauses) } @@ -75,12 +99,19 @@ internal data class SideEffectsBuilderImpl( override fun setFlags(vararg flags: Pair): SideEffect.SetFlags = adding { factory.setFlags(*flags) } - override fun setFlag(name: String, value: Term): SideEffect.SetFlags = adding { factory.setFlag(name, value) } + override fun setFlag( + name: String, + value: Term, + ): SideEffect.SetFlags = adding { factory.setFlag(name, value) } override fun resetFlags(flags: Map): SideEffect.ResetFlags = adding { factory.resetFlags(flags) } override fun resetFlags(vararg flags: Pair): SideEffect.ResetFlags = - adding { factory.resetFlags(*flags) } + adding { + factory.resetFlags( + *flags, + ) + } override fun clearFlags(names: Iterable): SideEffect.ClearFlags = adding { factory.clearFlags(names) } @@ -88,74 +119,105 @@ internal data class SideEffectsBuilderImpl( override fun clearFlags(vararg names: String): SideEffect.ClearFlags = adding { factory.clearFlags(*names) } - override fun loadLibrary(library: Library): SideEffect.LoadLibrary = - adding { factory.loadLibrary(library) } + override fun loadLibrary(library: Library): SideEffect.LoadLibrary = adding { factory.loadLibrary(library) } - override fun updateLibrary(library: Library): SideEffect.UpdateLibrary = - adding { factory.updateLibrary(library) } + override fun updateLibrary(library: Library): SideEffect.UpdateLibrary = adding { factory.updateLibrary(library) } override fun setOperators(operators: Iterable): SideEffect.SetOperators = - adding { factory.setOperators(operators) } + adding { + factory.setOperators(operators) + } override fun setOperators(operators: Sequence): SideEffect.SetOperators = - adding { factory.setOperators(operators) } + adding { + factory.setOperators(operators) + } override fun setOperators(vararg operators: Operator): SideEffect.SetOperators = - adding { factory.setOperators(*operators) } + adding { + factory.setOperators(*operators) + } override fun resetOperators(operators: Iterable): SideEffect.ResetOperators = - adding { factory.resetOperators(operators) } + adding { + factory.resetOperators(operators) + } override fun resetOperators(operators: Sequence): SideEffect.ResetOperators = - adding { factory.resetOperators(operators) } + adding { + factory.resetOperators(operators) + } override fun resetOperators(vararg operators: Operator): SideEffect.ResetOperators = - adding { factory.resetOperators(*operators) } + adding { + factory.resetOperators(*operators) + } override fun removeOperators(operators: Iterable): SideEffect.RemoveOperators = - adding { factory.removeOperators(operators) } + adding { + factory.removeOperators(operators) + } override fun removeOperators(operators: Sequence): SideEffect.RemoveOperators = - adding { factory.removeOperators(operators) } + adding { + factory.removeOperators(operators) + } override fun removeOperators(vararg operators: Operator): SideEffect.RemoveOperators = - adding { factory.removeOperators(*operators) } + adding { + factory.removeOperators(*operators) + } override fun openInputChannels(inputChannels: Map>): SideEffect.OpenInputChannels = adding { factory.openInputChannels(inputChannels) } - override fun openInputChannels(vararg inputChannels: Pair>): SideEffect.OpenInputChannels = - adding { factory.openInputChannels(*inputChannels) } + override fun openInputChannels( + vararg inputChannels: Pair>, + ): SideEffect.OpenInputChannels = adding { factory.openInputChannels(*inputChannels) } - override fun openInputChannel(name: String, inputChannel: InputChannel): SideEffect.OpenInputChannels = - adding { factory.openInputChannel(name, inputChannel) } + override fun openInputChannel( + name: String, + inputChannel: InputChannel, + ): SideEffect.OpenInputChannels = adding { factory.openInputChannel(name, inputChannel) } - override fun resetInputChannels(vararg inputChannels: Pair>): SideEffect.ResetInputChannels = - adding { factory.resetInputChannels(*inputChannels) } + override fun resetInputChannels( + vararg inputChannels: Pair>, + ): SideEffect.ResetInputChannels = adding { factory.resetInputChannels(*inputChannels) } override fun closeInputChannels(names: Iterable): SideEffect.CloseInputChannels = - adding { factory.closeInputChannels(names) } + adding { + factory.closeInputChannels(names) + } override fun closeInputChannels(names: Sequence): SideEffect.CloseInputChannels = - adding { factory.closeInputChannels(names) } + adding { + factory.closeInputChannels(names) + } override fun closeInputChannels(vararg names: String): SideEffect.CloseInputChannels = - adding { factory.closeInputChannels(*names) } + adding { + factory.closeInputChannels(*names) + } override fun openOutputChannels(outputChannels: Map>): SideEffect.OpenOutputChannels = adding { factory.openOutputChannels(outputChannels) } - override fun openOutputChannels(vararg outputChannels: Pair>): SideEffect.OpenOutputChannels = - adding { factory.openOutputChannels(*outputChannels) } + override fun openOutputChannels( + vararg outputChannels: Pair>, + ): SideEffect.OpenOutputChannels = adding { factory.openOutputChannels(*outputChannels) } - override fun openOutputChannel(name: String, outputChannel: OutputChannel): SideEffect.OpenOutputChannels = - adding { factory.openOutputChannel(name, outputChannel) } + override fun openOutputChannel( + name: String, + outputChannel: OutputChannel, + ): SideEffect.OpenOutputChannels = adding { factory.openOutputChannel(name, outputChannel) } - override fun resetOutputChannels(outputChannels: Map>): SideEffect.ResetOutputChannels = - adding { factory.resetOutputChannels(outputChannels) } + override fun resetOutputChannels( + outputChannels: Map>, + ): SideEffect.ResetOutputChannels = adding { factory.resetOutputChannels(outputChannels) } - override fun resetOutputChannels(vararg outputChannels: Pair>): SideEffect.ResetOutputChannels = - adding { factory.resetOutputChannels(*outputChannels) } + override fun resetOutputChannels( + vararg outputChannels: Pair>, + ): SideEffect.ResetOutputChannels = adding { factory.resetOutputChannels(*outputChannels) } override fun closeOutputChannels(names: Iterable): SideEffect.CloseOutputChannels = adding { factory.closeOutputChannels(names) } @@ -164,105 +226,156 @@ internal data class SideEffectsBuilderImpl( adding { factory.closeOutputChannels(names) } override fun closeOutputChannels(vararg names: String): SideEffect.CloseOutputChannels = - adding { factory.closeOutputChannels(*names) } + adding { + factory.closeOutputChannels(*names) + } override fun unloadLibraries(aliases: Iterable): SideEffect.UnloadLibraries = - adding { factory.unloadLibraries(aliases) } + adding { + factory.unloadLibraries(aliases) + } override fun unloadLibraries(aliases: Sequence): SideEffect.UnloadLibraries = - adding { factory.unloadLibraries(aliases) } + adding { + factory.unloadLibraries(aliases) + } override fun unloadLibraries(vararg aliases: String): SideEffect.UnloadLibraries = - adding { factory.unloadLibraries(*aliases) } + adding { + factory.unloadLibraries(*aliases) + } - override fun resetRuntime(libraries: Runtime): SideEffect.ResetRuntime = - adding { factory.resetRuntime(libraries) } + override fun resetRuntime(libraries: Runtime): SideEffect.ResetRuntime = adding { factory.resetRuntime(libraries) } override fun resetRuntime(libraries: Iterable): SideEffect.ResetRuntime = - adding { factory.resetRuntime(libraries) } + adding { + factory.resetRuntime(libraries) + } override fun resetRuntime(libraries: Sequence): SideEffect.ResetRuntime = - adding { factory.resetRuntime(libraries) } + adding { + factory.resetRuntime(libraries) + } override fun resetRuntime(vararg libraries: Library): SideEffect.ResetRuntime = - adding { factory.resetRuntime(*libraries) } + adding { + factory.resetRuntime(*libraries) + } override fun addLibraries(libraries: Runtime): SideEffect.AddLibraries = adding { factory.addLibraries(libraries) } override fun addLibraries(libraries: Iterable): SideEffect.AddLibraries = - adding { factory.addLibraries(libraries) } + adding { + factory.addLibraries(libraries) + } override fun addLibraries(libraries: Sequence): SideEffect.AddLibraries = - adding { factory.addLibraries(libraries) } + adding { + factory.addLibraries(libraries) + } override fun addLibraries(vararg libraries: Library): SideEffect.AddLibraries = - adding { factory.addLibraries(*libraries) } + adding { + factory.addLibraries(*libraries) + } - override fun resetInputChannels(inputChannels: Iterable>>): SideEffect.ResetInputChannels = - adding { factory.resetInputChannels(inputChannels) } + override fun resetInputChannels( + inputChannels: Iterable>>, + ): SideEffect.ResetInputChannels = adding { factory.resetInputChannels(inputChannels) } - override fun resetInputChannels(inputChannels: Sequence>>): SideEffect.ResetInputChannels = - adding { factory.resetInputChannels(inputChannels) } + override fun resetInputChannels( + inputChannels: Sequence>>, + ): SideEffect.ResetInputChannels = adding { factory.resetInputChannels(inputChannels) } override fun resetInputChannels(inputChannels: Map>): SideEffect.ResetInputChannels = adding { factory.resetInputChannels(inputChannels) } - override fun resetOutputChannels(outputChannels: Iterable>>): SideEffect.ResetOutputChannels = - adding { factory.resetOutputChannels(outputChannels) } + override fun resetOutputChannels( + outputChannels: Iterable>>, + ): SideEffect.ResetOutputChannels = adding { factory.resetOutputChannels(outputChannels) } - override fun resetOutputChannels(outputChannels: Sequence>>): SideEffect.ResetOutputChannels = - adding { factory.resetOutputChannels(outputChannels) } + override fun resetOutputChannels( + outputChannels: Sequence>>, + ): SideEffect.ResetOutputChannels = adding { factory.resetOutputChannels(outputChannels) } - override fun addEphemeralData(key: String, value: Any): SideEffect.SetEphemeralData = - adding { factory.addEphemeralData(key, value) } + override fun addEphemeralData( + key: String, + value: Any, + ): SideEffect.SetEphemeralData = adding { factory.addEphemeralData(key, value) } override fun addEphemeralData(data: Map): SideEffect.SetEphemeralData = - adding { factory.addEphemeralData(data) } + adding { + factory.addEphemeralData(data) + } override fun addEphemeralData(vararg data: Pair): SideEffect.SetEphemeralData = adding { factory.addEphemeralData(*data) } - override fun setEphemeralData(key: String, value: Any): SideEffect.SetEphemeralData = - adding { factory.setEphemeralData(key, value) } + override fun setEphemeralData( + key: String, + value: Any, + ): SideEffect.SetEphemeralData = adding { factory.setEphemeralData(key, value) } override fun setEphemeralData(data: Map): SideEffect.SetEphemeralData = - adding { factory.setEphemeralData(data) } + adding { + factory.setEphemeralData(data) + } override fun setEphemeralData(vararg data: Pair): SideEffect.SetEphemeralData = adding { factory.setEphemeralData(*data) } - override fun addDurableData(key: String, value: Any): SideEffect.SetDurableData = - adding { factory.addDurableData(key, value) } + override fun addDurableData( + key: String, + value: Any, + ): SideEffect.SetDurableData = adding { factory.addDurableData(key, value) } override fun addDurableData(data: Map): SideEffect.SetDurableData = - adding { factory.addDurableData(data) } + adding { + factory.addDurableData(data) + } override fun addDurableData(vararg data: Pair): SideEffect.SetDurableData = - adding { factory.addDurableData(*data) } + adding { + factory.addDurableData(*data) + } - override fun setDurableData(key: String, value: Any): SideEffect.SetDurableData = - adding { factory.setDurableData(key, value) } + override fun setDurableData( + key: String, + value: Any, + ): SideEffect.SetDurableData = adding { factory.setDurableData(key, value) } override fun setDurableData(data: Map): SideEffect.SetDurableData = - adding { factory.setDurableData(data) } + adding { + factory.setDurableData(data) + } override fun setDurableData(vararg data: Pair): SideEffect.SetDurableData = - adding { factory.setDurableData(*data) } + adding { + factory.setDurableData(*data) + } - override fun addPersistentData(key: String, value: Any): SideEffect.SetPersistentData = - adding { factory.addPersistentData(key, value) } + override fun addPersistentData( + key: String, + value: Any, + ): SideEffect.SetPersistentData = adding { factory.addPersistentData(key, value) } override fun addPersistentData(data: Map): SideEffect.SetPersistentData = - adding { factory.addPersistentData(data) } + adding { + factory.addPersistentData(data) + } override fun addPersistentData(vararg data: Pair): SideEffect.SetPersistentData = adding { factory.addPersistentData(*data) } - override fun setPersistentData(key: String, value: Any): SideEffect.SetPersistentData = - adding { factory.setPersistentData(key, value) } + override fun setPersistentData( + key: String, + value: Any, + ): SideEffect.SetPersistentData = adding { factory.setPersistentData(key, value) } override fun setPersistentData(data: Map): SideEffect.SetPersistentData = - adding { factory.setPersistentData(data) } + adding { + factory.setPersistentData(data) + } override fun setPersistentData(vararg data: Pair): SideEffect.SetPersistentData = adding { factory.setPersistentData(*data) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/CommonBuiltins.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/CommonBuiltins.kt index ebd2030e8..c1f987e1b 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/CommonBuiltins.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/CommonBuiltins.kt @@ -8,7 +8,6 @@ import it.unibo.tuprolog.solve.library.impl.AbstractLibrary import it.unibo.tuprolog.solve.primitive.Primitive object CommonBuiltins : AbstractLibrary() { - override val alias: String get() = "prolog.lang" diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/CommonFunctions.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/CommonFunctions.kt index b6b4119f0..0b7e44648 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/CommonFunctions.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/CommonFunctions.kt @@ -64,7 +64,7 @@ object CommonFunctions { Sine, SquareRoot, Subtraction, - Truncate + Truncate, ) val functions: Map = wrappers.map { it.descriptionPair }.toMap() diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/CommonPrimitives.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/CommonPrimitives.kt index aad9dd007..3d78d20f9 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/CommonPrimitives.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/CommonPrimitives.kt @@ -144,7 +144,7 @@ object CommonPrimitives { UnifiesWith, Univ, Var, - Write + Write, ) val primitives: Map = wrappers.map { it.descriptionPair }.toMap() diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/CommonRules.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/CommonRules.kt index e0c2c0965..ef4cb74f5 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/CommonRules.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/CommonRules.kt @@ -13,21 +13,22 @@ import it.unibo.tuprolog.solve.stdlib.rule.Semicolon import it.unibo.tuprolog.solve.stdlib.rule.SetPrologFlag object CommonRules { - val wrappers: Sequence> = sequenceOf( - Not, - Arrow, - Semicolon.If.Then, - Semicolon.If.Else, - Semicolon.Or.Left, - Semicolon.Or.Right, - Member.Base, - Member.Recursive, - Append.Base, - Append.Recursive, - Once, - SetPrologFlag, - CurrentPrologFlag - ) + val wrappers: Sequence> = + sequenceOf( + Not, + Arrow, + Semicolon.If.Then, + Semicolon.If.Else, + Semicolon.Or.Left, + Semicolon.Or.Right, + Member.Base, + Member.Recursive, + Append.Base, + Append.Recursive, + Once, + SetPrologFlag, + CurrentPrologFlag, + ) val clauses: List get() = wrappers.map { it.implementation }.toList() diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/AbsoluteValue.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/AbsoluteValue.kt index 00c92d35c..395dcffa1 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/AbsoluteValue.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/AbsoluteValue.kt @@ -12,10 +12,16 @@ import it.unibo.tuprolog.solve.function.UnaryMathFunction * @author Enrico */ object AbsoluteValue : UnaryMathFunction("abs") { + override fun mathFunction( + integer: Integer, + context: ExecutionContext, + ): Numeric = + Numeric.of( + integer.value.absoluteValue, + ) // TODO: 24/10/2019 missing Prolog Standard "int_overflow" check (see the standard) - override fun mathFunction(integer: Integer, context: ExecutionContext): Numeric = - Numeric.of(integer.value.absoluteValue) // TODO: 24/10/2019 missing Prolog Standard "int_overflow" check (see the standard) - - override fun mathFunction(real: Real, context: ExecutionContext): Numeric = - Numeric.of(real.value.absoluteValue) + override fun mathFunction( + real: Real, + context: ExecutionContext, + ): Numeric = Numeric.of(real.value.absoluteValue) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Addition.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Addition.kt index 186c1c5ef..a9a2432a3 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Addition.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Addition.kt @@ -13,20 +13,38 @@ import org.gciatto.kt.math.BigDecimal * @author Enrico */ object Addition : BinaryMathFunction("+") { + override fun mathFunction( + integer1: Integer, + integer2: Integer, + context: ExecutionContext, + ): Numeric = + Numeric.of( + integer1.value + integer2.value, + ) // TODO: 24/10/2019 "int_overflow" check missing (see the standard) - override fun mathFunction(integer1: Integer, integer2: Integer, context: ExecutionContext): Numeric = - Numeric.of(integer1.value + integer2.value) // TODO: 24/10/2019 "int_overflow" check missing (see the standard) + override fun mathFunction( + real: Real, + integer: Integer, + context: ExecutionContext, + ): Numeric = commonBehaviour(real.value, integer.decimalValue) - override fun mathFunction(real: Real, integer: Integer, context: ExecutionContext): Numeric = - commonBehaviour(real.value, integer.decimalValue) + override fun mathFunction( + integer: Integer, + real: Real, + context: ExecutionContext, + ): Numeric = commonBehaviour(integer.decimalValue, real.value) - override fun mathFunction(integer: Integer, real: Real, context: ExecutionContext): Numeric = - commonBehaviour(integer.decimalValue, real.value) - - override fun mathFunction(real1: Real, real2: Real, context: ExecutionContext): Numeric = - commonBehaviour(real1.value, real2.value) + override fun mathFunction( + real1: Real, + real2: Real, + context: ExecutionContext, + ): Numeric = commonBehaviour(real1.value, real2.value) /** Method implementing the behaviour when the two numbers are of different types */ - private fun commonBehaviour(decimal1: BigDecimal, decimal2: BigDecimal) = - Numeric.of(decimal1 + decimal2) // TODO: 24/10/2019 "float_overflow" and "underflow" checks missing (see the standard) + private fun commonBehaviour( + decimal1: BigDecimal, + decimal2: BigDecimal, + ) = Numeric.of( + decimal1 + decimal2, + ) // TODO: 24/10/2019 "float_overflow" and "underflow" checks missing (see the standard) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/ArcTangent.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/ArcTangent.kt index 4ce0295ba..dac289725 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/ArcTangent.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/ArcTangent.kt @@ -14,14 +14,16 @@ import kotlin.math.atan * @author Enrico */ object ArcTangent : UnaryMathFunction("atan") { + override fun mathFunction( + integer: Integer, + context: ExecutionContext, + ): Numeric = commonBehaviour(integer.decimalValue) - override fun mathFunction(integer: Integer, context: ExecutionContext): Numeric = - commonBehaviour(integer.decimalValue) - - override fun mathFunction(real: Real, context: ExecutionContext): Numeric = - commonBehaviour(real.value) + override fun mathFunction( + real: Real, + context: ExecutionContext, + ): Numeric = commonBehaviour(real.value) /** Implements the common behaviour for real and integer */ - private fun commonBehaviour(decimal: BigDecimal) = - Numeric.of(atan(decimal.toDouble())) + private fun commonBehaviour(decimal: BigDecimal) = Numeric.of(atan(decimal.toDouble())) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseAnd.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseAnd.kt index 0fa5e2108..041d4ff6a 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseAnd.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseAnd.kt @@ -11,7 +11,9 @@ import it.unibo.tuprolog.solve.function.IntegersBinaryMathFunction * @author Enrico */ object BitwiseAnd : IntegersBinaryMathFunction("/\\") { - - override fun mathFunction(integer1: Integer, integer2: Integer, context: ExecutionContext): Numeric = - Numeric.of(integer1.value.and(integer2.value)) + override fun mathFunction( + integer1: Integer, + integer2: Integer, + context: ExecutionContext, + ): Numeric = Numeric.of(integer1.value.and(integer2.value)) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseComplement.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseComplement.kt index f3b4d9238..f38ddc934 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseComplement.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseComplement.kt @@ -12,10 +12,13 @@ import it.unibo.tuprolog.solve.function.UnaryMathFunction * @author Enrico */ object BitwiseComplement : UnaryMathFunction("\\") { + override fun mathFunction( + integer: Integer, + context: ExecutionContext, + ): Numeric = Numeric.of(integer.value.not()) - override fun mathFunction(integer: Integer, context: ExecutionContext): Numeric = - Numeric.of(integer.value.not()) - - override fun mathFunction(real: Real, context: ExecutionContext): Numeric = - throwTypeErrorBecauseOnlyIntegersAccepted(functor, real, context) + override fun mathFunction( + real: Real, + context: ExecutionContext, + ): Numeric = throwTypeErrorBecauseOnlyIntegersAccepted(functor, real, context) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseLeftShift.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseLeftShift.kt index 83b230837..2ac70fb2b 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseLeftShift.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseLeftShift.kt @@ -11,7 +11,9 @@ import it.unibo.tuprolog.solve.function.IntegersBinaryMathFunction * @author Enrico */ object BitwiseLeftShift : IntegersBinaryMathFunction("<<") { - - override fun mathFunction(integer1: Integer, integer2: Integer, context: ExecutionContext): Numeric = - Numeric.of(integer1.value.shl(integer2.value.toInt())) + override fun mathFunction( + integer1: Integer, + integer2: Integer, + context: ExecutionContext, + ): Numeric = Numeric.of(integer1.value.shl(integer2.value.toInt())) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseOr.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseOr.kt index d05221d78..d04449a77 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseOr.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseOr.kt @@ -11,7 +11,9 @@ import it.unibo.tuprolog.solve.function.IntegersBinaryMathFunction * @author Enrico */ object BitwiseOr : IntegersBinaryMathFunction("\\/") { - - override fun mathFunction(integer1: Integer, integer2: Integer, context: ExecutionContext): Numeric = - Numeric.of(integer1.value.or(integer2.value)) + override fun mathFunction( + integer1: Integer, + integer2: Integer, + context: ExecutionContext, + ): Numeric = Numeric.of(integer1.value.or(integer2.value)) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseRightShift.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseRightShift.kt index 4e8965ca8..85bcd5786 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseRightShift.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseRightShift.kt @@ -11,7 +11,9 @@ import it.unibo.tuprolog.solve.function.IntegersBinaryMathFunction * @author Enrico */ object BitwiseRightShift : IntegersBinaryMathFunction(">>") { - - override fun mathFunction(integer1: Integer, integer2: Integer, context: ExecutionContext): Numeric = - Numeric.of(integer1.value.shr(integer2.value.toInt())) + override fun mathFunction( + integer1: Integer, + integer2: Integer, + context: ExecutionContext, + ): Numeric = Numeric.of(integer1.value.shr(integer2.value.toInt())) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Ceiling.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Ceiling.kt index fb54cbf85..e4b6cc7a3 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Ceiling.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Ceiling.kt @@ -13,9 +13,13 @@ import kotlin.math.ceil * @author Enrico */ object Ceiling : UnaryMathFunction("ceiling") { + override fun mathFunction( + integer: Integer, + context: ExecutionContext, + ): Numeric = integer - override fun mathFunction(integer: Integer, context: ExecutionContext): Numeric = integer - - override fun mathFunction(real: Real, context: ExecutionContext): Numeric = - Numeric.of(ceil(real.value.toDouble()).toLong()) + override fun mathFunction( + real: Real, + context: ExecutionContext, + ): Numeric = Numeric.of(ceil(real.value.toDouble()).toLong()) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Cosine.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Cosine.kt index 9709d9bbd..4675d4554 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Cosine.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Cosine.kt @@ -14,14 +14,16 @@ import kotlin.math.cos * @author Enrico */ object Cosine : UnaryMathFunction("cos") { + override fun mathFunction( + integer: Integer, + context: ExecutionContext, + ): Numeric = commonBehaviour(integer.decimalValue) - override fun mathFunction(integer: Integer, context: ExecutionContext): Numeric = - commonBehaviour(integer.decimalValue) - - override fun mathFunction(real: Real, context: ExecutionContext): Numeric = - commonBehaviour(real.value) + override fun mathFunction( + real: Real, + context: ExecutionContext, + ): Numeric = commonBehaviour(real.value) /** Implements the common behaviour for real and integer */ - private fun commonBehaviour(decimal: BigDecimal) = - Numeric.of(cos(decimal.toDouble())) + private fun commonBehaviour(decimal: BigDecimal) = Numeric.of(cos(decimal.toDouble())) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Exponential.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Exponential.kt index 515c787ec..220c5db1a 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Exponential.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Exponential.kt @@ -14,14 +14,19 @@ import kotlin.math.exp * @author Enrico */ object Exponential : UnaryMathFunction("exp") { + override fun mathFunction( + integer: Integer, + context: ExecutionContext, + ): Numeric = commonBehaviour(integer.decimalValue) - override fun mathFunction(integer: Integer, context: ExecutionContext): Numeric = - commonBehaviour(integer.decimalValue) - - override fun mathFunction(real: Real, context: ExecutionContext): Numeric = - commonBehaviour(real.value) + override fun mathFunction( + real: Real, + context: ExecutionContext, + ): Numeric = commonBehaviour(real.value) /** Implements the common behaviour for real and integer */ private fun commonBehaviour(decimal: BigDecimal) = - Numeric.of(exp(decimal.toDouble())) // TODO: 24/10/2019 missing "float_overflow" and "underflow" check (see the standard) + Numeric.of( + exp(decimal.toDouble()), + ) // TODO: 24/10/2019 missing "float_overflow" and "underflow" check (see the standard) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Exponentiation.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Exponentiation.kt index c5bb7c7c8..9aa35796f 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Exponentiation.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Exponentiation.kt @@ -14,27 +14,45 @@ import kotlin.math.pow * @author Enrico */ object Exponentiation : BinaryMathFunction("**") { - // TODO: 24/10/2019 missing "float_overflow", "underflow" and "undefined" error checks (see the standard) - override fun mathFunction(integer1: Integer, integer2: Integer, context: ExecutionContext): Numeric = + override fun mathFunction( + integer1: Integer, + integer2: Integer, + context: ExecutionContext, + ): Numeric = returnOneOfBothZero(integer1, integer2) ?: Real.of(integer1.decimalValue.pow(integer2.value.toInt())) - override fun mathFunction(real: Real, integer: Integer, context: ExecutionContext): Numeric = + override fun mathFunction( + real: Real, + integer: Integer, + context: ExecutionContext, + ): Numeric = returnOneOfBothZero(real, integer) ?: Real.of(real.value.pow(integer.value.toInt())) - override fun mathFunction(integer: Integer, real: Real, context: ExecutionContext): Numeric = + override fun mathFunction( + integer: Integer, + real: Real, + context: ExecutionContext, + ): Numeric = returnOneOfBothZero(integer, real) ?: Real.of(integer.value.toDouble().pow(real.value.toDouble())) - override fun mathFunction(real1: Real, real2: Real, context: ExecutionContext): Numeric = + override fun mathFunction( + real1: Real, + real2: Real, + context: ExecutionContext, + ): Numeric = returnOneOfBothZero(real1, real2) ?: Real.of(real1.value.toDouble().pow(real2.value.toDouble())) /** Implements the check for both zeros */ - private fun returnOneOfBothZero(numeric1: Numeric, numeric2: Numeric) = when { + private fun returnOneOfBothZero( + numeric1: Numeric, + numeric2: Numeric, + ) = when { numeric1.decimalValue == BigDecimal.ZERO && numeric2.decimalValue == BigDecimal.ZERO -> Numeric.of(1.0) else -> null } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/FloatFractionalPart.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/FloatFractionalPart.kt index 5f9861e37..b91c0e45b 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/FloatFractionalPart.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/FloatFractionalPart.kt @@ -14,18 +14,22 @@ import org.gciatto.kt.math.RoundingMode * @author Enrico */ object FloatFractionalPart : UnaryMathFunction("float_fractional_part") { + override fun mathFunction( + integer: Integer, + context: ExecutionContext, + ): Numeric = commonBehaviour(integer.decimalValue) - override fun mathFunction(integer: Integer, context: ExecutionContext): Numeric = - commonBehaviour(integer.decimalValue) - - override fun mathFunction(real: Real, context: ExecutionContext): Numeric = - commonBehaviour(real.decimalValue) + override fun mathFunction( + real: Real, + context: ExecutionContext, + ): Numeric = commonBehaviour(real.decimalValue) /** Implements common behaviour for Integer and Real */ - private fun commonBehaviour(decimal: BigDecimal): Numeric = Numeric.of( - when { - decimal >= BigDecimal.ZERO -> decimal - decimal.setScale(0, RoundingMode.FLOOR) - else -> -commonBehaviour(-decimal).decimalValue - }.stripTrailingZeros() - ) + private fun commonBehaviour(decimal: BigDecimal): Numeric = + Numeric.of( + when { + decimal >= BigDecimal.ZERO -> decimal - decimal.setScale(0, RoundingMode.FLOOR) + else -> -commonBehaviour(-decimal).decimalValue + }.stripTrailingZeros(), + ) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/FloatIntegerPart.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/FloatIntegerPart.kt index 8adb72a70..4bebbcd9c 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/FloatIntegerPart.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/FloatIntegerPart.kt @@ -14,18 +14,22 @@ import org.gciatto.kt.math.RoundingMode * @author Enrico */ object FloatIntegerPart : UnaryMathFunction("float_integer_part") { + override fun mathFunction( + integer: Integer, + context: ExecutionContext, + ): Numeric = commonBehaviour(integer.decimalValue) - override fun mathFunction(integer: Integer, context: ExecutionContext): Numeric = - commonBehaviour(integer.decimalValue) - - override fun mathFunction(real: Real, context: ExecutionContext): Numeric = - commonBehaviour(real.decimalValue) + override fun mathFunction( + real: Real, + context: ExecutionContext, + ): Numeric = commonBehaviour(real.decimalValue) /** Implements common behaviour for Integer and Real */ - private fun commonBehaviour(decimal: BigDecimal): Numeric = Numeric.of( - when { - decimal >= BigDecimal.ZERO -> decimal.setScale(0, RoundingMode.FLOOR) - else -> -commonBehaviour(-decimal).decimalValue - }.stripTrailingZeros() - ) + private fun commonBehaviour(decimal: BigDecimal): Numeric = + Numeric.of( + when { + decimal >= BigDecimal.ZERO -> decimal.setScale(0, RoundingMode.FLOOR) + else -> -commonBehaviour(-decimal).decimalValue + }.stripTrailingZeros(), + ) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/FloatingPointDivision.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/FloatingPointDivision.kt index 0c52af588..91a0aee55 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/FloatingPointDivision.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/FloatingPointDivision.kt @@ -14,21 +14,36 @@ import org.gciatto.kt.math.MathContext * @author Enrico */ object FloatingPointDivision : BinaryMathFunction("/") { + override fun mathFunction( + integer1: Integer, + integer2: Integer, + context: ExecutionContext, + ): Numeric = commonBehaviour(integer1.decimalValue, integer2.decimalValue, context) - override fun mathFunction(integer1: Integer, integer2: Integer, context: ExecutionContext): Numeric = - commonBehaviour(integer1.decimalValue, integer2.decimalValue, context) + override fun mathFunction( + real: Real, + integer: Integer, + context: ExecutionContext, + ): Numeric = commonBehaviour(real.value, integer.decimalValue, context) - override fun mathFunction(real: Real, integer: Integer, context: ExecutionContext): Numeric = - commonBehaviour(real.value, integer.decimalValue, context) + override fun mathFunction( + integer: Integer, + real: Real, + context: ExecutionContext, + ): Numeric = commonBehaviour(integer.decimalValue, real.value, context) - override fun mathFunction(integer: Integer, real: Real, context: ExecutionContext): Numeric = - commonBehaviour(integer.decimalValue, real.value, context) - - override fun mathFunction(real1: Real, real2: Real, context: ExecutionContext): Numeric = - commonBehaviour(real1.value, real2.value, context) + override fun mathFunction( + real1: Real, + real2: Real, + context: ExecutionContext, + ): Numeric = commonBehaviour(real1.value, real2.value, context) /** Implements common behaviour for Integer and Real */ - private fun commonBehaviour(dividend: BigDecimal, divisor: BigDecimal, context: ExecutionContext): Real = + private fun commonBehaviour( + dividend: BigDecimal, + divisor: BigDecimal, + context: ExecutionContext, + ): Real = // TODO: 25/10/2019 "float_overflow" and "underflow" checks missing (see the standard) if (divisor.compareTo(BigDecimal.ZERO) == 0) { throwZeroDivisorError(context) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Floor.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Floor.kt index 770f5898e..74c34db0a 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Floor.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Floor.kt @@ -14,12 +14,15 @@ import org.gciatto.kt.math.RoundingMode * @author Enrico */ object Floor : UnaryMathFunction("floor") { + override fun mathFunction( + integer: Integer, + context: ExecutionContext, + ): Numeric = commonBehaviour(integer.decimalValue) - override fun mathFunction(integer: Integer, context: ExecutionContext): Numeric = - commonBehaviour(integer.decimalValue) - - override fun mathFunction(real: Real, context: ExecutionContext): Numeric = - commonBehaviour(real.value) + override fun mathFunction( + real: Real, + context: ExecutionContext, + ): Numeric = commonBehaviour(real.value) /** Implementation of common behaviour for Real and Integer */ private fun commonBehaviour(decimal: BigDecimal): Integer = diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/IntegerDivision.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/IntegerDivision.kt index ed5a57038..76ccbaa3d 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/IntegerDivision.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/IntegerDivision.kt @@ -12,8 +12,11 @@ import org.gciatto.kt.math.BigInteger * @author Enrico */ object IntegerDivision : IntegersBinaryMathFunction("//") { - - override fun mathFunction(integer1: Integer, integer2: Integer, context: ExecutionContext): Numeric = + override fun mathFunction( + integer1: Integer, + integer2: Integer, + context: ExecutionContext, + ): Numeric = // TODO: 25/10/2019 "int_overflow" checks missing (see the standard) if (integer2.value.compareTo(BigInteger.ZERO) == 0) { throwZeroDivisorError(context) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Modulo.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Modulo.kt index 6e59ae7ba..3f221535a 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Modulo.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Modulo.kt @@ -12,8 +12,11 @@ import org.gciatto.kt.math.BigInteger * @author Enrico */ object Modulo : IntegersBinaryMathFunction("mod") { - - override fun mathFunction(integer1: Integer, integer2: Integer, context: ExecutionContext): Numeric = + override fun mathFunction( + integer1: Integer, + integer2: Integer, + context: ExecutionContext, + ): Numeric = when (integer2.value) { BigInteger.ZERO -> throwZeroDivisorError(context) else -> Numeric.of(integer1.value.remainder(integer2.value)) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Multiplication.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Multiplication.kt index fa6fcb0b1..ad0ed08b8 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Multiplication.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Multiplication.kt @@ -13,22 +13,37 @@ import org.gciatto.kt.math.BigDecimal * @author Enrico */ object Multiplication : BinaryMathFunction("*") { - - override fun mathFunction(integer1: Integer, integer2: Integer, context: ExecutionContext): Numeric = + override fun mathFunction( + integer1: Integer, + integer2: Integer, + context: ExecutionContext, + ): Numeric = // TODO: 25/10/2019 "int_overflow" check missing (see the standard) Numeric.of(integer1.value * integer2.value) - override fun mathFunction(real: Real, integer: Integer, context: ExecutionContext): Numeric = - commonBehaviour(real.value, integer.decimalValue) + override fun mathFunction( + real: Real, + integer: Integer, + context: ExecutionContext, + ): Numeric = commonBehaviour(real.value, integer.decimalValue) - override fun mathFunction(integer: Integer, real: Real, context: ExecutionContext): Numeric = - commonBehaviour(integer.decimalValue, real.value) + override fun mathFunction( + integer: Integer, + real: Real, + context: ExecutionContext, + ): Numeric = commonBehaviour(integer.decimalValue, real.value) - override fun mathFunction(real1: Real, real2: Real, context: ExecutionContext): Numeric = - commonBehaviour(real1.value, real2.value) + override fun mathFunction( + real1: Real, + real2: Real, + context: ExecutionContext, + ): Numeric = commonBehaviour(real1.value, real2.value) /** Implements common behaviour for mixed Integer and Real */ - private fun commonBehaviour(decimal1: BigDecimal, decimal2: BigDecimal): Real = + private fun commonBehaviour( + decimal1: BigDecimal, + decimal2: BigDecimal, + ): Real = // TODO: 25/10/2019 "float_overflow" and "underflow" checks missing (see the standard) Numeric.of(decimal1 * decimal2) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/NaturalLogarithm.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/NaturalLogarithm.kt index b4c6d031e..3fa37d558 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/NaturalLogarithm.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/NaturalLogarithm.kt @@ -15,14 +15,16 @@ import kotlin.math.log * @author Enrico */ object NaturalLogarithm : UnaryMathFunction("log") { + override fun mathFunction( + integer: Integer, + context: ExecutionContext, + ): Numeric = commonBehaviour(integer.decimalValue) - override fun mathFunction(integer: Integer, context: ExecutionContext): Numeric = - commonBehaviour(integer.decimalValue) - - override fun mathFunction(real: Real, context: ExecutionContext): Numeric = - commonBehaviour(real.value) + override fun mathFunction( + real: Real, + context: ExecutionContext, + ): Numeric = commonBehaviour(real.value) /** Implementation of common behaviour for Integer and Real */ - private fun commonBehaviour(decimal: BigDecimal): Real = - Numeric.of(log(decimal.toDouble(), E)) + private fun commonBehaviour(decimal: BigDecimal): Real = Numeric.of(log(decimal.toDouble(), E)) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Remainder.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Remainder.kt index bf20a1c6f..48185b8dd 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Remainder.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Remainder.kt @@ -12,8 +12,11 @@ import org.gciatto.kt.math.BigInteger * @author Enrico */ object Remainder : IntegersBinaryMathFunction("rem") { - - override fun mathFunction(integer1: Integer, integer2: Integer, context: ExecutionContext): Numeric = + override fun mathFunction( + integer1: Integer, + integer2: Integer, + context: ExecutionContext, + ): Numeric = when (integer2.value) { BigInteger.ZERO -> throwZeroDivisorError(context) else -> Numeric.of(integer1.value.rem(integer2.value)) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Round.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Round.kt index 7ee192685..fed5fb977 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Round.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Round.kt @@ -14,12 +14,15 @@ import org.gciatto.kt.math.RoundingMode * @author Enrico */ object Round : UnaryMathFunction("round") { + override fun mathFunction( + integer: Integer, + context: ExecutionContext, + ): Numeric = commonBehaviour(integer.decimalValue) - override fun mathFunction(integer: Integer, context: ExecutionContext): Numeric = - commonBehaviour(integer.decimalValue) - - override fun mathFunction(real: Real, context: ExecutionContext): Numeric = - commonBehaviour(real.value) + override fun mathFunction( + real: Real, + context: ExecutionContext, + ): Numeric = commonBehaviour(real.value) /** Implements common behaviour for Integer and Real */ private fun commonBehaviour(decimal: BigDecimal): Integer = diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Sign.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Sign.kt index d9fe77494..5a9ea5a1d 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Sign.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Sign.kt @@ -12,10 +12,13 @@ import it.unibo.tuprolog.solve.function.UnaryMathFunction * @author Enrico */ object Sign : UnaryMathFunction("sign") { + override fun mathFunction( + integer: Integer, + context: ExecutionContext, + ): Numeric = Integer.of(integer.value.signum.takeIf { it != 0 } ?: 1) - override fun mathFunction(integer: Integer, context: ExecutionContext): Numeric = - Integer.of(integer.value.signum.takeIf { it != 0 } ?: 1) - - override fun mathFunction(real: Real, context: ExecutionContext): Numeric = - Real.of(real.value.signum.takeIf { it != 0 }?.toDouble() ?: 1.0) + override fun mathFunction( + real: Real, + context: ExecutionContext, + ): Numeric = Real.of(real.value.signum.takeIf { it != 0 }?.toDouble() ?: 1.0) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/SignReversal.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/SignReversal.kt index 80c196f79..86226e2b3 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/SignReversal.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/SignReversal.kt @@ -12,11 +12,15 @@ import it.unibo.tuprolog.solve.function.UnaryMathFunction * @author Enrico */ object SignReversal : UnaryMathFunction("-") { - - override fun mathFunction(integer: Integer, context: ExecutionContext): Numeric = + override fun mathFunction( + integer: Integer, + context: ExecutionContext, + ): Numeric = // TODO: 25/10/2019 "int_overflow" check missing (see the standard) Integer.of(-integer.value) - override fun mathFunction(real: Real, context: ExecutionContext): Numeric = - Real.of(-real.value) + override fun mathFunction( + real: Real, + context: ExecutionContext, + ): Numeric = Real.of(-real.value) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Sine.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Sine.kt index 279616304..28b4bba59 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Sine.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Sine.kt @@ -14,14 +14,16 @@ import kotlin.math.sin * @author Enrico */ object Sine : UnaryMathFunction("sin") { + override fun mathFunction( + integer: Integer, + context: ExecutionContext, + ): Numeric = commonBehaviour(integer.decimalValue) - override fun mathFunction(integer: Integer, context: ExecutionContext): Numeric = - commonBehaviour(integer.decimalValue) - - override fun mathFunction(real: Real, context: ExecutionContext): Numeric = - commonBehaviour(real.value) + override fun mathFunction( + real: Real, + context: ExecutionContext, + ): Numeric = commonBehaviour(real.value) /** Implementation of common behaviour for Integer and Real */ - private fun commonBehaviour(decimal: BigDecimal) = - Numeric.of(sin(decimal.toDouble())) + private fun commonBehaviour(decimal: BigDecimal) = Numeric.of(sin(decimal.toDouble())) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/SquareRoot.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/SquareRoot.kt index 394550044..6becd96d2 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/SquareRoot.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/SquareRoot.kt @@ -13,12 +13,15 @@ import org.gciatto.kt.math.BigDecimal * @author Enrico */ object SquareRoot : UnaryMathFunction("sqrt") { + override fun mathFunction( + integer: Integer, + context: ExecutionContext, + ): Numeric = commonBehaviour(integer.decimalValue) - override fun mathFunction(integer: Integer, context: ExecutionContext): Numeric = - commonBehaviour(integer.decimalValue) - - override fun mathFunction(real: Real, context: ExecutionContext): Numeric = - commonBehaviour(real.value) + override fun mathFunction( + real: Real, + context: ExecutionContext, + ): Numeric = commonBehaviour(real.value) /** Implements common behaviour for Integer and Real*/ private fun commonBehaviour(decimal: BigDecimal): Real = diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Subtraction.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Subtraction.kt index e19180e6c..47eb06f9c 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Subtraction.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Subtraction.kt @@ -13,20 +13,38 @@ import org.gciatto.kt.math.BigDecimal * @author Enrico */ object Subtraction : BinaryMathFunction("-") { + override fun mathFunction( + integer1: Integer, + integer2: Integer, + context: ExecutionContext, + ): Numeric = + Numeric.of( + integer1.value - integer2.value, + ) // TODO: 24/10/2019 "int_overflow" check missing (see the standard) - override fun mathFunction(integer1: Integer, integer2: Integer, context: ExecutionContext): Numeric = - Numeric.of(integer1.value - integer2.value) // TODO: 24/10/2019 "int_overflow" check missing (see the standard) + override fun mathFunction( + real: Real, + integer: Integer, + context: ExecutionContext, + ): Numeric = commonBehaviour(real.value, integer.decimalValue) - override fun mathFunction(real: Real, integer: Integer, context: ExecutionContext): Numeric = - commonBehaviour(real.value, integer.decimalValue) + override fun mathFunction( + integer: Integer, + real: Real, + context: ExecutionContext, + ): Numeric = commonBehaviour(integer.decimalValue, real.value) - override fun mathFunction(integer: Integer, real: Real, context: ExecutionContext): Numeric = - commonBehaviour(integer.decimalValue, real.value) - - override fun mathFunction(real1: Real, real2: Real, context: ExecutionContext): Numeric = - commonBehaviour(real1.value, real2.value) + override fun mathFunction( + real1: Real, + real2: Real, + context: ExecutionContext, + ): Numeric = commonBehaviour(real1.value, real2.value) /** Method implementing the behaviour when the two numbers are of different types */ - private fun commonBehaviour(decimal1: BigDecimal, decimal2: BigDecimal) = - Numeric.of(decimal1 - decimal2) // TODO: 24/10/2019 "float_overflow" and "underflow" checks missing (see the standard) + private fun commonBehaviour( + decimal1: BigDecimal, + decimal2: BigDecimal, + ) = Numeric.of( + decimal1 - decimal2, + ) // TODO: 24/10/2019 "float_overflow" and "underflow" checks missing (see the standard) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/ToFloat.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/ToFloat.kt index 605a23937..a93c75436 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/ToFloat.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/ToFloat.kt @@ -12,14 +12,16 @@ import it.unibo.tuprolog.solve.function.UnaryMathFunction * @author Enrico */ object ToFloat : UnaryMathFunction("float") { + override fun mathFunction( + integer: Integer, + context: ExecutionContext, + ): Numeric = commonBehaviour(integer) - override fun mathFunction(integer: Integer, context: ExecutionContext): Numeric = - commonBehaviour(integer) - - override fun mathFunction(real: Real, context: ExecutionContext): Numeric = - commonBehaviour(real) + override fun mathFunction( + real: Real, + context: ExecutionContext, + ): Numeric = commonBehaviour(real) /** Implementation of common behaviour for Integer and Real */ - private fun commonBehaviour(numeric: Numeric) = - Numeric.of(numeric.decimalValue) + private fun commonBehaviour(numeric: Numeric) = Numeric.of(numeric.decimalValue) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Truncate.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Truncate.kt index 03f808e06..4b1161240 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Truncate.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/function/Truncate.kt @@ -14,13 +14,17 @@ import org.gciatto.kt.math.RoundingMode * @author Enrico */ object Truncate : UnaryMathFunction("truncate") { - - override fun mathFunction(integer: Integer, context: ExecutionContext): Numeric = + override fun mathFunction( + integer: Integer, + context: ExecutionContext, + ): Numeric = // TODO: 25/10/2019 "int_overflow" check missing (see the standard) commonBehaviour(integer.decimalValue) - override fun mathFunction(real: Real, context: ExecutionContext): Numeric = - commonBehaviour(real.value) + override fun mathFunction( + real: Real, + context: ExecutionContext, + ): Numeric = commonBehaviour(real.value) /** Implements common behaviour for Real and Integer */ private fun commonBehaviour(decimal: BigDecimal): Integer = diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/magic/MagicCut.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/magic/MagicCut.kt index 68511ff7e..f59b316df 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/magic/MagicCut.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/magic/MagicCut.kt @@ -9,7 +9,6 @@ import it.unibo.tuprolog.core.Term import it.unibo.tuprolog.core.TermVisitor object MagicCut : Atom by Atom.of("!") { - const val FUNCTOR: String = "!MagicCut!" override val isConstant: Boolean @@ -33,9 +32,15 @@ object MagicCut : Atom by Atom.of("!") { override fun apply(substitution: Substitution): Term = this - override fun get(substitution: Substitution, vararg substitutions: Substitution): Term = this + override fun get( + substitution: Substitution, + vararg substitutions: Substitution, + ): Term = this - override fun apply(substitution: Substitution, vararg substitutions: Substitution): Term = this + override fun apply( + substitution: Substitution, + vararg substitutions: Substitution, + ): Term = this override fun accept(visitor: TermVisitor): T = visitor.visitAtom(this) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AbstractAssert.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AbstractAssert.kt index 2b46dfd4e..38bdb4437 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AbstractAssert.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AbstractAssert.kt @@ -12,16 +12,16 @@ import it.unibo.tuprolog.solve.primitive.UnaryPredicate abstract class AbstractAssert( suffix: String, - private val before: Boolean + private val before: Boolean, ) : UnaryPredicate.NonBacktrackable("assert$suffix") { - override fun Solve.Request.computeOne(first: Term): Solve.Response { ensuringArgumentIsWellFormedClause(0) - val clause: Clause = when (first) { - is Clause -> first - is Struct -> Fact.of(first) - else -> return ensuringArgumentIsCallable(0).replyFail() - } + val clause: Clause = + when (first) { + is Clause -> first + is Struct -> Fact.of(first) + else -> return ensuringArgumentIsCallable(0).replyFail() + } ensuringClauseProcedureHasPermission(clause, MODIFY) return replySuccess { addDynamicClauses(clause.prepareForExecution(), onTop = before) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AbstractCollectingPrimitive.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AbstractCollectingPrimitive.kt index aff505684..75efb1829 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AbstractCollectingPrimitive.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AbstractCollectingPrimitive.kt @@ -15,7 +15,7 @@ abstract class AbstractCollectingPrimitive(name: String) : TernaryRelation.Witho context.remainingTime <= 0 -> { throw TimeOutException( exceededDuration = context.maxDuration, - context = context + context = context, ) } solution.isHalt -> { diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AbstractCollectionOf.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AbstractCollectionOf.kt index 24b3b28be..6450f1fb5 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AbstractCollectionOf.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AbstractCollectionOf.kt @@ -10,7 +10,7 @@ import it.unibo.tuprolog.solve.primitive.Solve import kotlin.collections.Set import it.unibo.tuprolog.core.List as LogicList -@Suppress("PrivatePropertyName") +@Suppress("PrivatePropertyName", "ktlint:standard:property-naming") abstract class AbstractCollectionOf(val name: String) : AbstractCollectingPrimitive(name) { private val VARS = Var.of("VARS") private val GOAL = Var.of("GOAL") @@ -19,19 +19,21 @@ abstract class AbstractCollectionOf(val name: String) : AbstractCollectingPrimit override fun Solve.Request.computeAllSubstitutions( first: Term, second: Term, - third: Term + third: Term, ): Sequence { ensuringArgumentIsInstantiated(1) ensuringArgumentIsCallable(1) val mgu = mgu(APEX_TEMPLATE, second) - val uninteresting: Set = when (mgu) { - is Substitution.Unifier -> when (val vars = mgu[VARS]) { - is Tuple -> vars.toSequence().filterIsInstance().toSet() - is Var -> setOf(vars) + val uninteresting: Set = + when (mgu) { + is Substitution.Unifier -> + when (val vars = mgu[VARS]) { + is Tuple -> vars.toSequence().filterIsInstance().toSet() + is Var -> setOf(vars) + else -> emptySet() + } else -> emptySet() } - else -> emptySet() - } val goal = if (mgu is Substitution.Unifier) mgu[GOAL]!! else second val solutions = computeIntermediateSolutions(goal.castToStruct()) val free = goal.variables.toSet() - first.variables.toSet() @@ -39,9 +41,10 @@ abstract class AbstractCollectionOf(val name: String) : AbstractCollectingPrimit val groups = solutions.groupBy { it.substitution.filter(interesting) } val nonPresentable = first.variables.toSet() return groups.asSequence().map { (sub, sols) -> - val solValues = sols.map { first[it.substitution] } - .filterNot { it in nonPresentable } - .map { it.freshCopy() } + val solValues = + sols.map { first[it.substitution] } + .filterNot { it in nonPresentable } + .map { it.freshCopy() } sub + mgu(third, LogicList.of(processSolutions(solValues))) } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AbstractGetData.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AbstractGetData.kt index e5be583e6..07134d865 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AbstractGetData.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AbstractGetData.kt @@ -9,7 +9,10 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve abstract class AbstractGetData(suffix: String) : BinaryRelation("get_$suffix") { - override fun Solve.Request.computeAll(first: Term, second: Term): Sequence { + override fun Solve.Request.computeAll( + first: Term, + second: Term, + ): Sequence { return when (first) { is Var -> data.entries.asSequence() @@ -18,10 +21,11 @@ abstract class AbstractGetData(suffix: String) : BinaryRelation mgu(first, k) + mgu(second, v) } .filterIsInstance() .map { replyWith(it) } + replyFail() - is Atom -> when (val value = data[first.value]) { - is Term -> sequenceOf(replyWith(mgu(second, value))) - else -> sequenceOf(replyFail()) - } + is Atom -> + when (val value = data[first.value]) { + is Term -> sequenceOf(replyWith(mgu(second, value))) + else -> sequenceOf(replyFail()) + } else -> { ensuringArgumentIsAtom(0) emptySequence() diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AbstractSetData.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AbstractSetData.kt index e79588a82..61d5ee92b 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AbstractSetData.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AbstractSetData.kt @@ -8,7 +8,10 @@ import it.unibo.tuprolog.solve.primitive.Solve import it.unibo.tuprolog.solve.sideffects.SideEffectsBuilder abstract class AbstractSetData(suffix: String) : BinaryRelation.NonBacktrackable("set_$suffix") { - override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response { ensuringArgumentIsGround(0) val key = (first as Atom).value return replySuccess { @@ -16,5 +19,8 @@ abstract class AbstractSetData(suffix: String) : BinaryRelation.NonBacktrackable } } - protected abstract fun SideEffectsBuilder.setData(key: String, value: Term) + protected abstract fun SideEffectsBuilder.setData( + key: String, + value: Term, + ) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Arg.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Arg.kt index e6c5e9d89..7597aaa5f 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Arg.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Arg.kt @@ -14,7 +14,7 @@ object Arg : TernaryRelation.WithoutSideEffects("arg") { override fun Solve.Request.computeAllSubstitutions( first: Term, second: Term, - third: Term + third: Term, ): Sequence = ensuringArgumentIsInstantiated(1) .ensuringArgumentIsCompound(1) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticEqual.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticEqual.kt index b96756334..e506ea34e 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticEqual.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticEqual.kt @@ -6,6 +6,8 @@ import it.unibo.tuprolog.solve.primitive.ArithmeticRelation /** Implementation of '=:='/2 predicate */ object ArithmeticEqual : ArithmeticRelation("=:=") { - override fun computeNumeric(x: Numeric, y: Numeric): Boolean = - x.compareValueTo(y) == 0 + override fun computeNumeric( + x: Numeric, + y: Numeric, + ): Boolean = x.compareValueTo(y) == 0 } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticGreaterThan.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticGreaterThan.kt index dfb02d3d4..fea676283 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticGreaterThan.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticGreaterThan.kt @@ -6,6 +6,8 @@ import it.unibo.tuprolog.solve.primitive.ArithmeticRelation /** Implementation of '>'/2 predicate */ object ArithmeticGreaterThan : ArithmeticRelation(">") { - override fun computeNumeric(x: Numeric, y: Numeric): Boolean = - x.compareValueTo(y) > 0 + override fun computeNumeric( + x: Numeric, + y: Numeric, + ): Boolean = x.compareValueTo(y) > 0 } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticGreaterThanOrEqualTo.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticGreaterThanOrEqualTo.kt index 912b7e5d6..91f97dbc7 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticGreaterThanOrEqualTo.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticGreaterThanOrEqualTo.kt @@ -6,6 +6,8 @@ import it.unibo.tuprolog.solve.primitive.ArithmeticRelation /** Implementation of '>='/2 predicate */ object ArithmeticGreaterThanOrEqualTo : ArithmeticRelation(">=") { - override fun computeNumeric(x: Numeric, y: Numeric): Boolean = - x.compareValueTo(y) >= 0 + override fun computeNumeric( + x: Numeric, + y: Numeric, + ): Boolean = x.compareValueTo(y) >= 0 } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticLowerThan.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticLowerThan.kt index f6b2ff0cb..24a9d4451 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticLowerThan.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticLowerThan.kt @@ -6,6 +6,8 @@ import it.unibo.tuprolog.solve.primitive.ArithmeticRelation /** Implementation of '<'/2 predicate */ object ArithmeticLowerThan : ArithmeticRelation("<") { - override fun computeNumeric(x: Numeric, y: Numeric): Boolean = - x.compareValueTo(y) < 0 + override fun computeNumeric( + x: Numeric, + y: Numeric, + ): Boolean = x.compareValueTo(y) < 0 } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticLowerThanOrEqualTo.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticLowerThanOrEqualTo.kt index 3e34c7e19..9eb1963af 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticLowerThanOrEqualTo.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticLowerThanOrEqualTo.kt @@ -6,6 +6,8 @@ import it.unibo.tuprolog.solve.primitive.ArithmeticRelation /** Implementation of '=<'/2 predicate */ object ArithmeticLowerThanOrEqualTo : ArithmeticRelation("=<") { - override fun computeNumeric(x: Numeric, y: Numeric): Boolean = - x.compareValueTo(y) <= 0 + override fun computeNumeric( + x: Numeric, + y: Numeric, + ): Boolean = x.compareValueTo(y) <= 0 } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticNotEqual.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticNotEqual.kt index 7c1696567..e5b307b7b 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticNotEqual.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticNotEqual.kt @@ -6,6 +6,8 @@ import it.unibo.tuprolog.solve.primitive.ArithmeticRelation /** Implementation of '=\='/2 predicate */ object ArithmeticNotEqual : ArithmeticRelation("=\\=") { - override fun computeNumeric(x: Numeric, y: Numeric): Boolean = - x.compareValueTo(y) != 0 + override fun computeNumeric( + x: Numeric, + y: Numeric, + ): Boolean = x.compareValueTo(y) != 0 } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AtomChars.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AtomChars.kt index f6cf1c6ee..1e77a54cd 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AtomChars.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AtomChars.kt @@ -11,7 +11,10 @@ import it.unibo.tuprolog.solve.primitive.Solve import it.unibo.tuprolog.core.List as LogicList object AtomChars : BinaryRelation.Functional("atom_chars") { - override fun Solve.Request.computeOneSubstitution(first: Term, second: Term): Substitution = + override fun Solve.Request.computeOneSubstitution( + first: Term, + second: Term, + ): Substitution = when { first is Var && second is Var -> { ensuringAllArgumentsAreInstantiated() @@ -20,15 +23,16 @@ object AtomChars : BinaryRelation.Functional("atom_chars") { first is Var -> { ensuringArgumentIsList(1) val chars = second as LogicList - val atom: Atom = Atom.of( - chars.toSequence().map { - if (it is Atom) { - it.value[0] - } else { - throw TypeError.forArgumentList(context, signature, TypeError.Expected.CHARACTER, it, 1) - } - }.joinToString("") - ) + val atom: Atom = + Atom.of( + chars.toSequence().map { + if (it is Atom) { + it.value[0] + } else { + throw TypeError.forArgumentList(context, signature, TypeError.Expected.CHARACTER, it, 1) + } + }.joinToString(""), + ) Substitution.of(first, atom) } second is Var -> { @@ -40,9 +44,10 @@ object AtomChars : BinaryRelation.Functional("atom_chars") { else -> { ensuringArgumentIsAtom(0) ensuringArgumentIsList(1) - val chars = LogicList.of( - (first as Atom).value.map { Atom.of("" + it) } - ) + val chars = + LogicList.of( + (first as Atom).value.map { Atom.of("" + it) }, + ) mgu(chars, second) } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AtomCodes.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AtomCodes.kt index 292b63a19..8d2e44988 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AtomCodes.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AtomCodes.kt @@ -13,26 +13,30 @@ import it.unibo.tuprolog.solve.primitive.Solve import it.unibo.tuprolog.core.List as LogicList object AtomCodes : BinaryRelation.Functional("atom_codes") { - override fun Solve.Request.computeOneSubstitution(first: Term, second: Term): Substitution = + override fun Solve.Request.computeOneSubstitution( + first: Term, + second: Term, + ): Substitution = when (first) { is Var -> { ensuringArgumentIsInstantiated(1) ensuringArgumentIsList(1) val codeList = second as LogicList - val chars: List = codeList.toList().map { - when (it) { - is Integer -> { - ensuringTermIsCharCode(it) - it.intValue.toChar() - } - is Var -> { - throw InstantiationError.forArgument(context, signature, it, 1) - } - else -> { - throw TypeError.forArgument(context, signature, TypeError.Expected.INTEGER, it, 1) + val chars: List = + codeList.toList().map { + when (it) { + is Integer -> { + ensuringTermIsCharCode(it) + it.intValue.toChar() + } + is Var -> { + throw InstantiationError.forArgument(context, signature, it, 1) + } + else -> { + throw TypeError.forArgument(context, signature, TypeError.Expected.INTEGER, it, 1) + } } } - } Substitution.of(first, Atom.of(chars.joinToString(separator = ""))) } else -> { diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AtomConcat.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AtomConcat.kt index 9d9f7a28c..4fc7671bc 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AtomConcat.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AtomConcat.kt @@ -16,7 +16,7 @@ object AtomConcat : TernaryRelation.Functional("atom_concat") override fun Solve.Request.computeOneSubstitution( first: Term, second: Term, - third: Term + third: Term, ): Substitution { return when { third is Var -> { diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AtomLength.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AtomLength.kt index d9a5f7a4a..52b95d101 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AtomLength.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/AtomLength.kt @@ -10,7 +10,10 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object AtomLength : BinaryRelation.Functional("atom_length") { - override fun Solve.Request.computeOneSubstitution(first: Term, second: Term): Substitution = + override fun Solve.Request.computeOneSubstitution( + first: Term, + second: Term, + ): Substitution = when { first is Var -> { ensuringAllArgumentsAreInstantiated() diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Between.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Between.kt index 9cccb1257..c054b282f 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Between.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Between.kt @@ -11,11 +11,10 @@ import org.gciatto.kt.math.BigInteger import it.unibo.tuprolog.core.Integer as LogicInteger object Between : TernaryRelation.WithoutSideEffects("between") { - override fun Solve.Request.computeAllSubstitutions( first: Term, second: Term, - third: Term + third: Term, ): Sequence { ensuringArgumentIsInstantiated(0) ensuringArgumentIsInstantiated(1) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/CharCode.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/CharCode.kt index 0a5fd0f0b..ee2a44ba7 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/CharCode.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/CharCode.kt @@ -10,14 +10,18 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object CharCode : BinaryRelation.Functional("char_code") { - override fun Solve.Request.computeOneSubstitution(first: Term, second: Term): Substitution { + override fun Solve.Request.computeOneSubstitution( + first: Term, + second: Term, + ): Substitution { return when { first is Var -> { ensuringArgumentIsInstantiated(1) ensuringArgumentIsCharCode(1) - val atom: Atom = Atom.of( - charArrayOf((second as Integer).intValue.toChar()).concatToString() - ) + val atom: Atom = + Atom.of( + charArrayOf((second as Integer).intValue.toChar()).concatToString(), + ) Substitution.of(first, atom) } else -> { diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Clause.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Clause.kt index c19829917..e5a27a72e 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Clause.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Clause.kt @@ -15,7 +15,7 @@ import it.unibo.tuprolog.utils.buffered object Clause : BinaryRelation.WithoutSideEffects("clause") { override fun Solve.Request.computeAllSubstitutions( first: Term, - second: Term + second: Term, ): Sequence { ensuringArgumentIsInstantiated(0) ensuringArgumentIsStruct(0) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Compound.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Compound.kt index a651a8d11..67c3bd7c3 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Compound.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Compound.kt @@ -6,6 +6,5 @@ import it.unibo.tuprolog.solve.ExecutionContext import it.unibo.tuprolog.solve.primitive.TypeTester object Compound : TypeTester("compound") { - override fun testType(term: Term): Boolean = - term is Struct && term.arity > 0 + override fun testType(term: Term): Boolean = term is Struct && term.arity > 0 } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/CopyTerm.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/CopyTerm.kt index 4b1958cf2..1f16edcc5 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/CopyTerm.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/CopyTerm.kt @@ -7,6 +7,8 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object CopyTerm : BinaryRelation.Functional("copy_term") { - override fun Solve.Request.computeOneSubstitution(first: Term, second: Term): Substitution = - mgu(first.freshCopy(), second) + override fun Solve.Request.computeOneSubstitution( + first: Term, + second: Term, + ): Substitution = mgu(first.freshCopy(), second) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/CurrentFlag.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/CurrentFlag.kt index f59889f26..b22b0920a 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/CurrentFlag.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/CurrentFlag.kt @@ -11,17 +11,18 @@ import it.unibo.tuprolog.solve.primitive.Solve object CurrentFlag : BinaryRelation.WithoutSideEffects("current_flag") { override fun Solve.Request.computeAllSubstitutions( first: Term, - second: Term - ): Sequence = when (first) { - is Atom, is Var -> { - context.flags.asSequence() - .map { (k, v) -> Atom.of(k) to v } - .map { (k, v) -> mgu(k, first) + mgu(v, second) } - .filter { it.isSuccess } + second: Term, + ): Sequence = + when (first) { + is Atom, is Var -> { + context.flags.asSequence() + .map { (k, v) -> Atom.of(k) to v } + .map { (k, v) -> mgu(k, first) + mgu(v, second) } + .filter { it.isSuccess } + } + else -> { + ensuringArgumentIsAtom(0) + emptySequence() + } } - else -> { - ensuringArgumentIsAtom(0) - emptySequence() - } - } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/CurrentOp.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/CurrentOp.kt index 79db6f2d6..64fef5f22 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/CurrentOp.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/CurrentOp.kt @@ -12,13 +12,13 @@ object CurrentOp : TernaryRelation.WithoutSideEffects("current override fun Solve.Request.computeAllSubstitutions( first: Term, second: Term, - third: Term + third: Term, ): Sequence = context.operators.asSequence().map { listOf( mgu(first, Integer.of(it.priority)), mgu(second, it.specifier.toTerm()), - mgu(third, Atom.of(it.functor)) + mgu(third, Atom.of(it.functor)), ) }.filter { it.all { sub -> sub is Substitution.Unifier } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/EnsureExecutable.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/EnsureExecutable.kt index 173644949..cd6f5cc56 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/EnsureExecutable.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/EnsureExecutable.kt @@ -10,7 +10,10 @@ import it.unibo.tuprolog.solve.primitive.Solve import it.unibo.tuprolog.solve.primitive.TypeEnsurer object EnsureExecutable : TypeEnsurer("ensure_executable") { - override fun Solve.Request.ensureType(context: ExecutionContext, term: Term) { + override fun Solve.Request.ensureType( + context: ExecutionContext, + term: Term, + ) { val signature = context.procedure?.extractSignature() ?: signature when (term) { is Var -> { diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/FindAll.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/FindAll.kt index ce6637a98..03c6b2814 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/FindAll.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/FindAll.kt @@ -7,11 +7,10 @@ import it.unibo.tuprolog.solve.primitive.Solve import it.unibo.tuprolog.core.List as LogicList object FindAll : AbstractCollectingPrimitive("findall") { - override fun Solve.Request.computeAllSubstitutions( first: Term, second: Term, - third: Term + third: Term, ): Sequence { ensuringArgumentIsInstantiated(1) ensuringArgumentIsCallable(1) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Functor.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Functor.kt index 51dcdf11f..f656fb744 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Functor.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Functor.kt @@ -18,53 +18,53 @@ import org.gciatto.kt.math.BigInteger * Implementation of 'functor'/3 predicate */ object Functor : TernaryRelation.Functional("functor") { - override fun Solve.Request.computeOneSubstitution( first: Term, second: Term, - third: Term - ): Substitution = when (first) { - is Struct -> { - if (third !is Var) { - ensuringArgumentIsArity(2) - } - mgu(second, Atom.of(first.functor)) + mgu(third, Integer.of(first.arity)) - } - is Numeric -> { - if (third !is Var) { - ensuringArgumentIsArity(2) - } - mgu(first, second) + mgu(third, Integer.of(0)) - } - is Var -> { - when (second) { - is Atom -> { - ensuringArgumentIsInstantiated(2) + third: Term, + ): Substitution = + when (first) { + is Struct -> { + if (third !is Var) { ensuringArgumentIsArity(2) - Substitution.of(first to Struct.template(second.value, (third as Integer).intValue.toInt())) } - is Numeric -> { - ensuringArgumentIsInstantiated(2) + mgu(second, Atom.of(first.functor)) + mgu(third, Integer.of(first.arity)) + } + is Numeric -> { + if (third !is Var) { ensuringArgumentIsArity(2) + } + mgu(first, second) + mgu(third, Integer.of(0)) + } + is Var -> { + when (second) { + is Atom -> { + ensuringArgumentIsInstantiated(2) + ensuringArgumentIsArity(2) + Substitution.of(first to Struct.template(second.value, (third as Integer).intValue.toInt())) + } + is Numeric -> { + ensuringArgumentIsInstantiated(2) + ensuringArgumentIsArity(2) - val arity = (third as Integer) + val arity = (third as Integer) - if (arity.intValue == BigInteger.ZERO) { - Substitution.of(first to second) + mgu(third, Integer.of(0)) - } else { - throw TypeError.forArgument(context, signature, TypeError.Expected.ATOM, second, 1) + if (arity.intValue == BigInteger.ZERO) { + Substitution.of(first to second) + mgu(third, Integer.of(0)) + } else { + throw TypeError.forArgument(context, signature, TypeError.Expected.ATOM, second, 1) + } + } + is Var -> { + throw InstantiationError.forArgument(context, signature, second, 1) + } + else -> { + throw TypeError.forArgument(context, signature, TypeError.Expected.ATOMIC, second, 1) } - } - is Var -> { - throw InstantiationError.forArgument(context, signature, second, 1) - } - else -> { - throw TypeError.forArgument(context, signature, TypeError.Expected.ATOMIC, second, 1) } } + else -> { + throw TypeError.forArgument(context, signature, TypeError.Expected.CALLABLE, first, 0) + } } - else -> { - throw TypeError.forArgument(context, signature, TypeError.Expected.CALLABLE, first, 0) - } - } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Is.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Is.kt index d8922b7b0..2c44be384 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Is.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Is.kt @@ -13,8 +13,10 @@ import it.unibo.tuprolog.solve.primitive.Solve * @author Enrico */ object Is : BinaryRelation.Functional("is") { - - override fun Solve.Request.computeOneSubstitution(first: Term, second: Term): Substitution = + override fun Solve.Request.computeOneSubstitution( + first: Term, + second: Term, + ): Substitution = ensuringArgumentIsInstantiated(1).run { mgu(first, second.evalAsExpression(this, 1)) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Natural.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Natural.kt index b1544dbce..5e668e174 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Natural.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Natural.kt @@ -18,8 +18,9 @@ object Natural : UnaryPredicate("natural") { } private fun generateValues(): Sequence = - generateSequence(BigInteger.ZERO) { it + BigInteger.ONE }.map { Integer.of(it) } + generateSequence(BigInteger.ZERO) { + it + BigInteger.ONE + }.map { Integer.of(it) } - private fun checkValue(value: Integer): Boolean = - value.intValue.signum >= 0 + private fun checkValue(value: Integer): Boolean = value.intValue.signum >= 0 } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/NotUnifiableWith.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/NotUnifiableWith.kt index 7dc0492ec..585b3b455 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/NotUnifiableWith.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/NotUnifiableWith.kt @@ -7,6 +7,8 @@ import it.unibo.tuprolog.solve.primitive.Solve /** Implementation of '\='/2 predicate */ object NotUnifiableWith : BinaryRelation.Predicative("\\=") { - override fun Solve.Request.compute(first: Term, second: Term): Boolean = - !match(first, second) + override fun Solve.Request.compute( + first: Term, + second: Term, + ): Boolean = !match(first, second) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/NumberChars.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/NumberChars.kt index d042d6526..8e6c01be6 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/NumberChars.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/NumberChars.kt @@ -12,7 +12,10 @@ import it.unibo.tuprolog.solve.primitive.Solve import it.unibo.tuprolog.core.List as LogicList object NumberChars : BinaryRelation.Functional("number_chars") { - override fun Solve.Request.computeOneSubstitution(first: Term, second: Term): Substitution { + override fun Solve.Request.computeOneSubstitution( + first: Term, + second: Term, + ): Substitution { return when { first is Var && second is Var -> { ensuringAllArgumentsAreInstantiated() @@ -34,9 +37,10 @@ object NumberChars : BinaryRelation.Functional("number_chars") else -> { ensuringArgumentIsNumeric(0) ensuringArgumentIsList(1) - val chars = LogicList.of( - (first).toString().toAtom().value.map { Atom.of("" + it) } - ) + val chars = + LogicList.of( + (first).toString().toAtom().value.map { Atom.of("" + it) }, + ) mgu(chars, second) } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/NumberCodes.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/NumberCodes.kt index d52debfcc..38cdb0d94 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/NumberCodes.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/NumberCodes.kt @@ -13,26 +13,30 @@ import it.unibo.tuprolog.solve.primitive.Solve import it.unibo.tuprolog.core.List as LogicList object NumberCodes : BinaryRelation.Functional("number_codes") { - override fun Solve.Request.computeOneSubstitution(first: Term, second: Term): Substitution { + override fun Solve.Request.computeOneSubstitution( + first: Term, + second: Term, + ): Substitution { return when (first) { is Var -> { ensuringArgumentIsInstantiated(1) ensuringArgumentIsList(1) val codeList = second as LogicList - val chars: List = codeList.toList().map { - when (it) { - is Integer -> { - ensuringTermIsCharCode(it) - it.intValue.toChar() - } - is Var -> { - throw InstantiationError.forArgument(context, signature, it, 1) - } - else -> { - throw TypeError.forArgument(context, signature, TypeError.Expected.INTEGER, it, 1) + val chars: List = + codeList.toList().map { + when (it) { + is Integer -> { + ensuringTermIsCharCode(it) + it.intValue.toChar() + } + is Var -> { + throw InstantiationError.forArgument(context, signature, it, 1) + } + else -> { + throw TypeError.forArgument(context, signature, TypeError.Expected.INTEGER, it, 1) + } } } - } val numberString = chars.joinToString(separator = "") Substitution.of(first, Numeric.of(numberString)) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Op.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Op.kt index 3a727bbbb..54eb37bd2 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Op.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Op.kt @@ -11,7 +11,11 @@ import it.unibo.tuprolog.solve.primitive.TernaryRelation import it.unibo.tuprolog.solve.sideffects.SideEffect object Op : TernaryRelation.NonBacktrackable("op") { - override fun Solve.Request.computeOne(first: Term, second: Term, third: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + third: Term, + ): Solve.Response { ensuringArgumentIsInteger(0) ensuringArgumentIsNonNegativeInteger(0) ensuringArgumentIsAtom(1) @@ -21,7 +25,7 @@ object Op : TernaryRelation.NonBacktrackable("op") { return replySuccess( Substitution.empty(), null, - SideEffect.SetOperators(operator) + SideEffect.SetOperators(operator), ) } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Retract.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Retract.kt index 195ad78e4..9b5af6ed0 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Retract.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Retract.kt @@ -15,17 +15,19 @@ import it.unibo.tuprolog.utils.buffered object Retract : UnaryPredicate("retract") { override fun Solve.Request.computeAll(first: Term): Sequence { ensuringArgumentIsWellFormedClause(0) - val clause: Clause = when (first) { - is Clause -> first - is Struct -> Rule.of(first, Var.anonymous()) - else -> return sequenceOf(ensuringArgumentIsCallable(0).replyFail()) - } + val clause: Clause = + when (first) { + is Clause -> first + is Struct -> Rule.of(first, Var.anonymous()) + else -> return sequenceOf(ensuringArgumentIsCallable(0).replyFail()) + } ensuringClauseProcedureHasPermission(clause, PermissionError.Operation.MODIFY) return context.dynamicKb[clause].buffered().map { - val substitution = when (first) { - is Clause -> mgu(first, it) as Substitution.Unifier - else -> mgu(first, it.head!!) as Substitution.Unifier - } + val substitution = + when (first) { + is Clause -> mgu(first, it) as Substitution.Unifier + else -> mgu(first, it.head!!) as Substitution.Unifier + } replySuccess(substitution) { removeDynamicClauses(it) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Reverse.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Reverse.kt index f0b79793d..11d16ef4b 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Reverse.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Reverse.kt @@ -9,7 +9,10 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object Reverse : BinaryRelation.Functional("reverse") { - override fun Solve.Request.computeOneSubstitution(first: Term, second: Term): Substitution { + override fun Solve.Request.computeOneSubstitution( + first: Term, + second: Term, + ): Substitution { return when { first is Var -> { ensuringArgumentIsWellFormedList(1) @@ -38,7 +41,10 @@ object Reverse : BinaryRelation.Functional("reverse") { } } - private fun Solve.Request.reverse(list: List, other: Term): Substitution { + private fun Solve.Request.reverse( + list: List, + other: Term, + ): Substitution { val reversed = List.of(list.toList().asReversed()) return mgu(reversed, other) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SetDurable.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SetDurable.kt index 9460a931a..0ed54cba4 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SetDurable.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SetDurable.kt @@ -4,7 +4,10 @@ import it.unibo.tuprolog.core.Term import it.unibo.tuprolog.solve.sideffects.SideEffectsBuilder object SetDurable : AbstractSetData("durable") { - override fun SideEffectsBuilder.setData(key: String, value: Term) { + override fun SideEffectsBuilder.setData( + key: String, + value: Term, + ) { setDurableData(key, value) } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SetEphemeral.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SetEphemeral.kt index 326350bce..2862ecf6d 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SetEphemeral.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SetEphemeral.kt @@ -4,7 +4,10 @@ import it.unibo.tuprolog.core.Term import it.unibo.tuprolog.solve.sideffects.SideEffectsBuilder object SetEphemeral : AbstractSetData("ephemeral") { - override fun SideEffectsBuilder.setData(key: String, value: Term) { + override fun SideEffectsBuilder.setData( + key: String, + value: Term, + ) { setEphemeralData(key, value) } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SetFlag.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SetFlag.kt index 38611e08d..cc0782835 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SetFlag.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SetFlag.kt @@ -12,7 +12,10 @@ import it.unibo.tuprolog.solve.primitive.BinaryRelation import it.unibo.tuprolog.solve.primitive.Solve object SetFlag : BinaryRelation.NonBacktrackable("set_flag") { - override fun Solve.Request.computeOne(first: Term, second: Term): Solve.Response { + override fun Solve.Request.computeOne( + first: Term, + second: Term, + ): Solve.Response { ensuringArgumentIsInstantiated(0) ensuringArgumentIsAtom(0) ensuringArgumentIsInstantiated(1) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SetOf.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SetOf.kt index 6f6fba6f4..433266914 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SetOf.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SetOf.kt @@ -3,6 +3,5 @@ package it.unibo.tuprolog.solve.stdlib.primitive import it.unibo.tuprolog.core.Term object SetOf : AbstractCollectionOf("setof") { - override fun processSolutions(list: List): Iterable = - list.toHashSet() + override fun processSolutions(list: List): Iterable = LinkedHashSet(list) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SetPersistent.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SetPersistent.kt index 0e4cd6b9a..f882edc82 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SetPersistent.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SetPersistent.kt @@ -4,7 +4,10 @@ import it.unibo.tuprolog.core.Term import it.unibo.tuprolog.solve.sideffects.SideEffectsBuilder object SetPersistent : AbstractSetData("persistent") { - override fun SideEffectsBuilder.setData(key: String, value: Term) { + override fun SideEffectsBuilder.setData( + key: String, + value: Term, + ) { setPersistentData(key, value) } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SubAtom.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SubAtom.kt index 95027f370..cc4293a93 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SubAtom.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/SubAtom.kt @@ -11,11 +11,16 @@ import it.unibo.tuprolog.solve.primitive.Solve object SubAtom : QuinaryRelation.WithoutSideEffects("sub_atom") { override fun Solve.Request.computeAllSubstitutions( - first: Term, // string - second: Term, // before - third: Term, // length - fourth: Term, // after - fifth: Term // sub + // string + first: Term, + // before + second: Term, + // length + third: Term, + // after + fourth: Term, + // sub + fifth: Term, ): Sequence { return if (fifth is Var) { ensuringArgumentIsInstantiated(0) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermGreaterThan.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermGreaterThan.kt index 804253ffd..f7b7a8524 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermGreaterThan.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermGreaterThan.kt @@ -7,7 +7,10 @@ import it.unibo.tuprolog.solve.primitive.Solve /** Implementation of '@>'/2 predicate */ object TermGreaterThan : BinaryRelation.Predicative("@>") { - override fun Solve.Request.compute(first: Term, second: Term): Boolean { + override fun Solve.Request.compute( + first: Term, + second: Term, + ): Boolean { return first > second } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermGreaterThanOrEqualTo.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermGreaterThanOrEqualTo.kt index 55399c968..5aebb6ded 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermGreaterThanOrEqualTo.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermGreaterThanOrEqualTo.kt @@ -7,7 +7,10 @@ import it.unibo.tuprolog.solve.primitive.Solve /** Implementation of '@>='/2 predicate */ object TermGreaterThanOrEqualTo : BinaryRelation.Predicative("@>=") { - override fun Solve.Request.compute(first: Term, second: Term): Boolean { + override fun Solve.Request.compute( + first: Term, + second: Term, + ): Boolean { return first >= second } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermIdentical.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermIdentical.kt index b3d4bf9b6..4faf4e72c 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermIdentical.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermIdentical.kt @@ -7,7 +7,10 @@ import it.unibo.tuprolog.solve.primitive.Solve /** Implementation of '=='/2 predicate */ object TermIdentical : BinaryRelation.Predicative("==") { - override fun Solve.Request.compute(first: Term, second: Term): Boolean { + override fun Solve.Request.compute( + first: Term, + second: Term, + ): Boolean { return first == second } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermLowerThan.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermLowerThan.kt index a34e180a8..d6d765166 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermLowerThan.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermLowerThan.kt @@ -7,7 +7,10 @@ import it.unibo.tuprolog.solve.primitive.Solve /** Implementation of '@<'/2 predicate */ object TermLowerThan : BinaryRelation.Predicative("@<") { - override fun Solve.Request.compute(first: Term, second: Term): Boolean { + override fun Solve.Request.compute( + first: Term, + second: Term, + ): Boolean { return first < second } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermLowerThanOrEqualTo.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermLowerThanOrEqualTo.kt index 70fb14076..4620b3663 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermLowerThanOrEqualTo.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermLowerThanOrEqualTo.kt @@ -7,7 +7,10 @@ import it.unibo.tuprolog.solve.primitive.Solve /** Implementation of '@=<'/2 predicate */ object TermLowerThanOrEqualTo : BinaryRelation.Predicative("@=<") { - override fun Solve.Request.compute(first: Term, second: Term): Boolean { + override fun Solve.Request.compute( + first: Term, + second: Term, + ): Boolean { return first <= second } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermNotIdentical.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermNotIdentical.kt index 11ac3dde1..61616b60c 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermNotIdentical.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermNotIdentical.kt @@ -7,7 +7,10 @@ import it.unibo.tuprolog.solve.primitive.Solve /** Implementation of `'\=='/2` predicate */ object TermNotIdentical : BinaryRelation.Predicative("\\==") { - override fun Solve.Request.compute(first: Term, second: Term): Boolean { + override fun Solve.Request.compute( + first: Term, + second: Term, + ): Boolean { return first != second } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermNotSame.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermNotSame.kt index 9902925e8..273f8514f 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermNotSame.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermNotSame.kt @@ -7,7 +7,10 @@ import it.unibo.tuprolog.solve.primitive.Solve /** Implementation of '=='/2 predicate */ object TermNotSame : BinaryRelation.Predicative("\\=@=") { - override fun Solve.Request.compute(first: Term, second: Term): Boolean { + override fun Solve.Request.compute( + first: Term, + second: Term, + ): Boolean { return first.compareTo(second) != 0 } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermSame.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermSame.kt index 03d39d4b4..1d58807d3 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermSame.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermSame.kt @@ -7,7 +7,10 @@ import it.unibo.tuprolog.solve.primitive.Solve /** Implementation of '=='/2 predicate */ object TermSame : BinaryRelation.Predicative("=@=") { - override fun Solve.Request.compute(first: Term, second: Term): Boolean { + override fun Solve.Request.compute( + first: Term, + second: Term, + ): Boolean { return first.compareTo(second) == 0 } } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/UnifiesWith.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/UnifiesWith.kt index f4c05f2a3..c640292e4 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/UnifiesWith.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/UnifiesWith.kt @@ -8,6 +8,8 @@ import it.unibo.tuprolog.solve.primitive.Solve /** Implementation of '='/2 predicate */ object UnifiesWith : BinaryRelation.Functional("=") { - override fun Solve.Request.computeOneSubstitution(first: Term, second: Term): Substitution = - mgu(first, second) + override fun Solve.Request.computeOneSubstitution( + first: Term, + second: Term, + ): Substitution = mgu(first, second) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Univ.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Univ.kt index a164a0543..5cbc54816 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Univ.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/Univ.kt @@ -16,18 +16,27 @@ import it.unibo.tuprolog.core.List as LogicList * Implementation of '=..'/2 predicate */ object Univ : BinaryRelation.Functional("=..") { - private fun Solve.Request.decompose(first: Struct, second: Term): Substitution { + private fun Solve.Request.decompose( + first: Struct, + second: Term, + ): Substitution { val decomposed = LogicList.of(Atom.of(first.functor), *first.args.toTypedArray()) return mgu(second, decomposed) } - private fun Solve.Request.recompose(first: Term, second: LogicList): Substitution { + private fun Solve.Request.recompose( + first: Term, + second: LogicList, + ): Substitution { val list = second.toList() val composed = Struct.of(list[0].castTo().value, list.subList(1, list.size)) return mgu(first, composed) } - override fun Solve.Request.computeOneSubstitution(first: Term, second: Term): Substitution { + override fun Solve.Request.computeOneSubstitution( + first: Term, + second: Term, + ): Substitution { return when (first) { is Struct -> { when (second) { diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Append.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Append.kt index 1a399aa5e..c259a5709 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Append.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Append.kt @@ -9,25 +9,26 @@ import kotlin.collections.List as KtList import kotlin.collections.listOf as ktListOf sealed class Append : RuleWrapper(FUNCTOR, ARITY) { - abstract override val Scope.head: KtList object Base : Append() { override val Scope.head: KtList - get() = ktListOf( - emptyList, - varOf("X"), - varOf("X") - ) + get() = + ktListOf( + emptyList, + varOf("X"), + varOf("X"), + ) } object Recursive : Append() { override val Scope.head: KtList - get() = ktListOf( - consOf(varOf("X"), varOf("Y")), - varOf("Z"), - consOf(varOf("X"), varOf("W")) - ) + get() = + ktListOf( + consOf(varOf("X"), varOf("Y")), + varOf("Z"), + consOf(varOf("X"), varOf("W")), + ) override val Scope.body: Term get() = structOf("append", varOf("Y"), varOf("Z"), varOf("W")) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Arrow.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Arrow.kt index 3506fee30..8f6d303e2 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Arrow.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Arrow.kt @@ -12,9 +12,10 @@ object Arrow : RuleWrapper("->", 2) { override val Scope.head: KtList get() = ktListOf(varOf("Cond"), varOf("Then")) - override val Scope.body: Term get() = tupleOf( - structOf("call", varOf("Cond")), - MagicCut, - varOf("Then") - ) + override val Scope.body: Term get() = + tupleOf( + structOf("call", varOf("Cond")), + MagicCut, + varOf("Then"), + ) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Member.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Member.kt index d42251991..dab3f8d62 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Member.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Member.kt @@ -9,23 +9,24 @@ import kotlin.collections.List as KtList import kotlin.collections.listOf as ktListOf sealed class Member : RuleWrapper(FUNCTOR, ARITY) { - abstract override val Scope.head: KtList object Base : Member() { override val Scope.head: KtList - get() = ktListOf( - varOf("H"), - consOf(varOf("H"), whatever()) - ) + get() = + ktListOf( + varOf("H"), + consOf(varOf("H"), whatever()), + ) } object Recursive : Member() { override val Scope.head: KtList - get() = ktListOf( - varOf("H"), - consOf(whatever(), varOf("T")) - ) + get() = + ktListOf( + varOf("H"), + consOf(whatever(), varOf("T")), + ) override val Scope.body: Term get() = structOf("member", varOf("H"), varOf("T")) diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Not.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Not.kt index b6c3d7a39..e2f568b3f 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Not.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Not.kt @@ -13,8 +13,9 @@ object Not : RuleWrapper("not", 1) { get() = ktListOf(varOf("G")) override val Scope.body: Term - get() = tupleOf( - structOf(EnsureExecutable.functor, varOf("G")), - structOf("\\+", varOf("G")) - ) + get() = + tupleOf( + structOf(EnsureExecutable.functor, varOf("G")), + structOf("\\+", varOf("G")), + ) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Once.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Once.kt index 48394101e..5a581e02c 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Once.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Once.kt @@ -9,14 +9,14 @@ import kotlin.collections.List as KtList import kotlin.collections.listOf as ktListOf object Once : RuleWrapper("once", 1) { - override val Scope.head: KtList get() = ktListOf(varOf("G")) override val Scope.body: Term - get() = tupleOf( - structOf(EnsureExecutable.functor, varOf("G")), - structOf("call", varOf("G")), - atomOf("!") - ) + get() = + tupleOf( + structOf(EnsureExecutable.functor, varOf("G")), + structOf("call", varOf("G")), + atomOf("!"), + ) } diff --git a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Semicolon.kt b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Semicolon.kt index 28abbf5e3..32adde4d7 100644 --- a/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Semicolon.kt +++ b/solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/stdlib/rule/Semicolon.kt @@ -10,7 +10,6 @@ import kotlin.collections.List as KtList import kotlin.collections.listOf as ktListOf sealed class Semicolon : RuleWrapper(FUNCTOR, ARITY) { - abstract override val Scope.head: KtList abstract override val Scope.body: Term @@ -21,21 +20,23 @@ sealed class Semicolon : RuleWrapper(FUNCTOR, ARITY) { object Then : If() { override val Scope.body: Term - get() = tupleOf( + get() = + tupleOf( // structOf(EnsureExecutable.functor, varOf("Cond")), - structOf("call", varOf("Cond")), - MagicCut, - varOf("Then") - ) + structOf("call", varOf("Cond")), + MagicCut, + varOf("Then"), + ) } object Else : If() { override val Scope.body: Term - get() = tupleOf( - MagicCut, + get() = + tupleOf( + MagicCut, // structOf(EnsureExecutable.functor, varOf("Else")), - varOf("Else") - ) + varOf("Else"), + ) } } diff --git a/solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/Dummy.kt b/solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/Dummy.kt index b33e40881..0a3de9376 100644 --- a/solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/Dummy.kt +++ b/solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/Dummy.kt @@ -38,7 +38,7 @@ object Dummy { staticKb: Theory, dynamicKb: Theory, inputChannels: InputStore, - outputChannels: OutputStore + outputChannels: OutputStore, ): Solver { TODO("Not yet implemented") } @@ -50,7 +50,7 @@ object Dummy { staticKb: Theory, dynamicKb: Theory, inputChannels: InputStore, - outputChannels: OutputStore + outputChannels: OutputStore, ): MutableSolver { TODO("Not yet implemented") } @@ -64,7 +64,7 @@ object Dummy { operators: OperatorSet, inputChannels: InputStore, outputChannels: OutputStore, - customData: CustomDataStore + customData: CustomDataStore, ): ExecutionContext { TODO("Not yet implemented") } diff --git a/solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestSolutionMetadata.kt b/solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestSolutionMetadata.kt index 98d18bc6b..27d63ae8b 100644 --- a/solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestSolutionMetadata.kt +++ b/solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestSolutionMetadata.kt @@ -24,7 +24,7 @@ import kotlin.test.assertNull import kotlin.test.assertTrue class TestSolutionMetadata { - + @Suppress("PrivatePropertyName", "ktlint:standard:property-naming") private val X = Var.of("X") private val someKey = "some_key1" @@ -34,29 +34,31 @@ class TestSolutionMetadata { private val someValue2 = Metadata("2") private val someOtherValue = Metadata("3") - private val queries = listOf( - Struct.of("q", X), - Struct.of("q", Var.anonymous()), - Atom.of("atom"), - Struct.of("q", Integer.ONE), - Struct.of("q", Real.ONE_TENTH), - EmptyList(), - EmptyBlock(), - Cons.of(Real.ONE_HALF, X), - Struct.of("g", X), - List.of(X), - Block.of(X), - Tuple.of(X, X) - ).map { it.setTag(yetAnotherKey, someValue2) } - - private val solutions = queries.flatMap { - listOf( - Solution.no(it), - Solution.halt(it, Dummy.RuntimeException), - Solution.yes(it), - Solution.yes(it, Substitution.of(X, Integer.ONE)) - ) - } + private val queries = + listOf( + Struct.of("q", X), + Struct.of("q", Var.anonymous()), + Atom.of("atom"), + Struct.of("q", Integer.ONE), + Struct.of("q", Real.ONE_TENTH), + EmptyList(), + EmptyBlock(), + Cons.of(Real.ONE_HALF, X), + Struct.of("g", X), + List.of(X), + Block.of(X), + Tuple.of(X, X), + ).map { it.setTag(yetAnotherKey, someValue2) } + + private val solutions = + queries.flatMap { + listOf( + Solution.no(it), + Solution.halt(it, Dummy.RuntimeException), + Solution.yes(it), + Solution.yes(it, Substitution.of(X, Integer.ONE)), + ) + } private data class Metadata(val value: T) diff --git a/solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestTimeoutException.kt b/solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestTimeoutException.kt index 81ea95d63..8e39007c3 100644 --- a/solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestTimeoutException.kt +++ b/solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/TestTimeoutException.kt @@ -35,7 +35,7 @@ class TestTimeoutException { staticKb: Theory, dynamicKb: Theory, inputChannels: InputStore, - outputChannels: OutputStore + outputChannels: OutputStore, ): Solver { TODO("Not yet implemented") } @@ -47,7 +47,7 @@ class TestTimeoutException { staticKb: Theory, dynamicKb: Theory, inputChannels: InputStore, - outputChannels: OutputStore + outputChannels: OutputStore, ): MutableSolver { TODO("Not yet implemented") } @@ -61,7 +61,7 @@ class TestTimeoutException { operators: OperatorSet, inputChannels: InputStore, outputChannels: OutputStore, - customData: CustomDataStore + customData: CustomDataStore, ): ExecutionContext { TODO("Not yet implemented") } @@ -88,11 +88,12 @@ class TestTimeoutException { override fun toString(): String = "DummyContext" } - private val exception = TimeOutException( - message = "dummy message", - context = DummyContext, - exceededDuration = DummyContext.maxDuration - ) + private val exception = + TimeOutException( + message = "dummy message", + context = DummyContext, + exceededDuration = DummyContext.maxDuration, + ) @Test fun testToString() { @@ -102,7 +103,7 @@ class TestTimeoutException { "exceededDuration=${DummyContext.maxDuration}, " + "contexts=[${DummyContext::class.simpleName}]" + ")", - exception.toString() + exception.toString(), ) } diff --git a/solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/directives/TestDirectivePartitioning.kt b/solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/directives/TestDirectivePartitioning.kt index dce22c1e2..ddba3507f 100644 --- a/solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/directives/TestDirectivePartitioning.kt +++ b/solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/directives/TestDirectivePartitioning.kt @@ -15,33 +15,36 @@ import kotlin.test.Test import kotlin.test.assertEquals class TestDirectivePartitioning { - private val theory = logicProgramming { - theoryOf( - directive { op(300, FY, "--") }, - directive { include("path/to/file1.pl") }, - directive { load("path/to/file2.pl") }, - fact { "a" }, - fact { "b" }, - directive { set_flag("flag1", 1) }, - directive { op(400, FX, "++") }, - fact { "c" }, - directive { static("f" / 1) }, - fact { "f"(1) }, - fact { "f"("a") }, - fact { "f"(1, "a") }, - directive { set_flag("flag2", 2) }, - directive { dynamic("g" / 1) }, - fact { "g"(2) }, - fact { "g"("b") }, - fact { "g"(2, "b") }, - directive { solve("g"(1)) }, - rule { "h"(X) impliedBy (Y `is` (X - 1) and "h"(Y)) }, - directive { initialization("f"(1)) } - ) - } - - private fun ruleSelector(name: String, arity: Int): (Clause) -> Boolean = - { it is Fact && it.head.let { h -> h.functor == name && h.arity == arity } } + private val theory = + logicProgramming { + theoryOf( + directive { op(300, FY, "--") }, + directive { include("path/to/file1.pl") }, + directive { load("path/to/file2.pl") }, + fact { "a" }, + fact { "b" }, + directive { set_flag("flag1", 1) }, + directive { op(400, FX, "++") }, + fact { "c" }, + directive { static("f" / 1) }, + fact { "f"(1) }, + fact { "f"("a") }, + fact { "f"(1, "a") }, + directive { set_flag("flag2", 2) }, + directive { dynamic("g" / 1) }, + fact { "g"(2) }, + fact { "g"("b") }, + fact { "g"(2, "b") }, + directive { solve("g"(1)) }, + rule { "h"(X) impliedBy (Y `is` (X - 1) and "h"(Y)) }, + directive { initialization("f"(1)) }, + ) + } + + private fun ruleSelector( + name: String, + arity: Int, + ): (Clause) -> Boolean = { it is Fact && it.head.let { h -> h.functor == name && h.arity == arity } } @Test fun testStaticPartitioning() { @@ -62,10 +65,11 @@ class TestDirectivePartitioning { val expectedGoals = listOf("g", "f").map { Struct.of(it, Integer.of(1)) } assertEquals(expectedGoals, partition.initialGoals) - val expectedOperators = OperatorSet( - Operator("--", FY, 300), - Operator("++", FX, 400) - ) + val expectedOperators = + OperatorSet( + Operator("--", FY, 300), + Operator("++", FX, 400), + ) assertEquals(expectedOperators, partition.operators) } @@ -88,10 +92,11 @@ class TestDirectivePartitioning { val expectedGoals = listOf("g", "f").map { Struct.of(it, Integer.of(1)) } assertEquals(expectedGoals, partition.initialGoals) - val expectedOperators = OperatorSet( - Operator("--", FY, 300), - Operator("++", FX, 400) - ) + val expectedOperators = + OperatorSet( + Operator("--", FY, 300), + Operator("++", FX, 400), + ) assertEquals(expectedOperators, partition.operators) } } diff --git a/solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/JsClassName.kt b/solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/JsClassName.kt index 7ee73296b..6363925e0 100644 --- a/solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/JsClassName.kt +++ b/solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/JsClassName.kt @@ -8,7 +8,7 @@ data class JsClassName(val module: String, val qualifiedName: String) { val splitted = fullName.split(":") return JsClassName( splitted.subList(0, splitted.lastIndex).joinToString(""), - splitted.last() + splitted.last(), ) } @@ -19,6 +19,7 @@ data class JsClassName(val module: String, val qualifiedName: String) { qualifiedName.split('.') } + @Suppress("TooGenericExceptionCaught", "SwallowedException") fun resolve(): dynamic { try { var resolved = require(module) diff --git a/solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/SolverExtensionsJs.kt b/solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/SolverExtensionsJs.kt index 30c161281..924798512 100644 --- a/solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/SolverExtensionsJs.kt +++ b/solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/SolverExtensionsJs.kt @@ -1,35 +1,41 @@ package it.unibo.tuprolog.solve private object ModuleNames { - const val organization = "." + const val ORGANIZATION = "." - private const val solvePrefix = "2p-solve" + private const val SOLVE_PREFIX = "2p-solve" - const val classic = "$solvePrefix-classic" + const val CLASSIC = "$SOLVE_PREFIX-classic" - private fun withOptionalPrefix(orgPrefix: Boolean = false, module: String, klass: String): String = - (if (orgPrefix) "$organization/" else "") + module + ":" + klass + private fun withOptionalPrefix( + orgPrefix: Boolean = false, + module: String, + klass: String, + ): String = (if (orgPrefix) "$ORGANIZATION/" else "") + module + ":" + klass fun classicFactoryClass(orgPrefix: Boolean = false) = - withOptionalPrefix(orgPrefix, classic, FactoryClassNames.classic) + withOptionalPrefix(orgPrefix, CLASSIC, FactoryClassNames.CLASSIC) - const val streams = "$solvePrefix-streams" + const val STREAMS = "$SOLVE_PREFIX-streams" fun streamsFactoryClass(orgPrefix: Boolean = false) = - withOptionalPrefix(orgPrefix, streams, FactoryClassNames.streams) + withOptionalPrefix(orgPrefix, STREAMS, FactoryClassNames.STREAMS) - const val problog = "$solvePrefix-problog" + const val PROBLOG = "$SOLVE_PREFIX-problog" fun problogFactoryClass(orgPrefix: Boolean = false) = - withOptionalPrefix(orgPrefix, problog, FactoryClassNames.problog) + withOptionalPrefix(orgPrefix, PROBLOG, FactoryClassNames.PROBLOG) - const val concurrent = "$solvePrefix-concurrent" + const val CONCURRENT = "$SOLVE_PREFIX-concurrent" fun concurrentFactoryClass(orgPrefix: Boolean = false) = - withOptionalPrefix(orgPrefix, concurrent, FactoryClassNames.concurrent) + withOptionalPrefix(orgPrefix, CONCURRENT, FactoryClassNames.CONCURRENT) } -internal actual fun solverFactory(className: String, vararg classNames: String): SolverFactory = +internal actual fun solverFactory( + className: String, + vararg classNames: String, +): SolverFactory = sequenceOf(className, *classNames) .map { JsClassName.parse(it) } .map { it.resolve() } @@ -37,29 +43,29 @@ internal actual fun solverFactory(className: String, vararg classNames: String): .firstOrNull() ?: throw IllegalStateException( "No viable implementation for ${SolverFactory::class.simpleName} in " + - sequenceOf(className, *classNames).joinToString(", ", "[", "]") + sequenceOf(className, *classNames).joinToString(", ", "[", "]"), ) actual fun classicSolverFactory(): SolverFactory = solverFactory( ModuleNames.classicFactoryClass(orgPrefix = true), - ModuleNames.classicFactoryClass(orgPrefix = false) + ModuleNames.classicFactoryClass(orgPrefix = false), ) actual fun streamsSolverFactory(): SolverFactory = solverFactory( ModuleNames.streamsFactoryClass(orgPrefix = true), - ModuleNames.streamsFactoryClass(orgPrefix = false) + ModuleNames.streamsFactoryClass(orgPrefix = false), ) actual fun problogSolverFactory(): SolverFactory = solverFactory( ModuleNames.problogFactoryClass(orgPrefix = true), - ModuleNames.problogFactoryClass(orgPrefix = false) + ModuleNames.problogFactoryClass(orgPrefix = false), ) actual fun concurrentSolverFactory(): SolverFactory = solverFactory( ModuleNames.concurrentFactoryClass(orgPrefix = true), - ModuleNames.concurrentFactoryClass(orgPrefix = false) + ModuleNames.concurrentFactoryClass(orgPrefix = false), ) diff --git a/solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/TimeJs.kt b/solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/TimeJs.kt index 81532a394..c57a49548 100644 --- a/solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/TimeJs.kt +++ b/solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/TimeJs.kt @@ -3,4 +3,5 @@ package it.unibo.tuprolog.solve import kotlin.js.Date /** A function returning current Time instant */ +@JsName("currentTimeInstant") actual fun currentTimeInstant(): TimeInstant = Date.now().toLong() diff --git a/solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/channel/Channels.kt b/solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/channel/Channels.kt index 27aaae62b..53d5ffadc 100644 --- a/solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/channel/Channels.kt +++ b/solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/channel/Channels.kt @@ -6,13 +6,10 @@ import it.unibo.tuprolog.solve.exception.Warning internal actual fun stdin(): InputChannel = InputChannel.of { throw IllegalStateException("No default implementation of stdin on JS") } -internal actual fun stderr(): OutputChannel = - OutputChannel.of { console.error(it) } +internal actual fun stderr(): OutputChannel = OutputChannel.of { console.error(it) } -internal actual fun stdout(): OutputChannel = - OutputChannel.of { print(it) } +internal actual fun stdout(): OutputChannel = OutputChannel.of { print(it) } -internal actual fun warning(): OutputChannel = - OutputChannel.of { console.warn(it.message) } +internal actual fun warning(): OutputChannel = OutputChannel.of { console.warn(it.message) } internal actual fun stringInputChannel(string: String): InputChannel = InputChannelFromString(string) diff --git a/solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/SolverExtensionsJvm.kt b/solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/SolverExtensionsJvm.kt index 425c28d02..d0f5daaa1 100644 --- a/solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/SolverExtensionsJvm.kt +++ b/solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/SolverExtensionsJvm.kt @@ -1,8 +1,10 @@ package it.unibo.tuprolog.solve -import java.lang.IllegalStateException - -internal actual fun solverFactory(className: String, vararg classNames: String): SolverFactory { +@Suppress("SwallowedException") +internal actual fun solverFactory( + className: String, + vararg classNames: String, +): SolverFactory { return sequenceOf(className, *classNames) .map { try { @@ -15,17 +17,13 @@ internal actual fun solverFactory(className: String, vararg classNames: String): .map { it.objectInstance } .filterIsInstance() .firstOrNull() - ?: throw IllegalStateException("No viable implementation for ${SolverFactory::class.simpleName}") + ?: error("No viable implementation for ${SolverFactory::class.simpleName}") } -actual fun classicSolverFactory(): SolverFactory = - solverFactory(FactoryClassNames.classic) +actual fun classicSolverFactory(): SolverFactory = solverFactory(FactoryClassNames.CLASSIC) -actual fun streamsSolverFactory(): SolverFactory = - solverFactory(FactoryClassNames.streams) +actual fun streamsSolverFactory(): SolverFactory = solverFactory(FactoryClassNames.STREAMS) -actual fun problogSolverFactory(): SolverFactory = - solverFactory(FactoryClassNames.problog) +actual fun problogSolverFactory(): SolverFactory = solverFactory(FactoryClassNames.PROBLOG) -actual fun concurrentSolverFactory(): SolverFactory = - solverFactory(FactoryClassNames.concurrent) +actual fun concurrentSolverFactory(): SolverFactory = solverFactory(FactoryClassNames.CONCURRENT) diff --git a/solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/channel/Channels.kt b/solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/channel/Channels.kt index 618e6260d..f4ef514f5 100644 --- a/solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/channel/Channels.kt +++ b/solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/channel/Channels.kt @@ -10,7 +10,9 @@ internal actual fun stderr(): OutputChannel = PrintStreamChannel(Sy internal actual fun stdout(): OutputChannel = PrintStreamChannel(System.out) internal actual fun warning(): OutputChannel = - OutputChannel.of { System.err.println(it.message); System.err.flush() } + OutputChannel.of { + System.err.println(it.message) + System.err.flush() + } -internal actual fun stringInputChannel(string: String): InputChannel = - ReaderChannel(StringReader(string)) +internal actual fun stringInputChannel(string: String): InputChannel = ReaderChannel(StringReader(string)) diff --git a/solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/channel/ReaderChannel.kt b/solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/channel/ReaderChannel.kt index 2a62d8200..282300ad6 100644 --- a/solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/channel/ReaderChannel.kt +++ b/solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/channel/ReaderChannel.kt @@ -7,19 +7,18 @@ import java.io.InputStreamReader import java.io.Reader class ReaderChannel(val reader: Reader) : AbstractInputChannel() { - constructor(inputStream: InputStream) : this(InputStreamReader(inputStream)) - override fun readActually(): String? = - reader.read().takeIf { it >= 0 }?.toChar()?.toString() + override fun readActually(): String? = reader.read().takeIf { it >= 0 }?.toChar()?.toString() override val available: Boolean @Synchronized - get() = try { - reader.ready() - } catch (_: IOException) { - false - } + get() = + try { + reader.ready() + } catch (_: IOException) { + false + } @Synchronized override fun close() { diff --git a/solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/channel/WriterChannel.kt b/solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/channel/WriterChannel.kt index c0fb8191d..0e7a029eb 100644 --- a/solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/channel/WriterChannel.kt +++ b/solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/channel/WriterChannel.kt @@ -6,7 +6,6 @@ import java.io.OutputStreamWriter import java.io.Writer class WriterChannel(private val writer: Writer) : AbstractOutputChannel() { - constructor(outputStream: OutputStream) : this(OutputStreamWriter(outputStream)) override fun writeActually(value: String) = writer.write(value) diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/CustomTheories.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/CustomTheories.kt index 9092f710d..bdc0fbb87 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/CustomTheories.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/CustomTheories.kt @@ -4,14 +4,13 @@ import it.unibo.tuprolog.dsl.theory.logicProgramming import it.unibo.tuprolog.theory.Theory object CustomTheories { - val ifThenTheory1: Theory by lazy { logicProgramming { theoryOf( fact { "a"(1) }, fact { "a"(2) }, fact { "b"(1) }, - fact { "c"(2) } + fact { "c"(2) }, ) } } @@ -22,7 +21,7 @@ object CustomTheories { fact { "a"(2) }, fact { "a"(1) }, fact { "b"(1) }, - fact { "c"(2) } + fact { "c"(2) }, ) } } @@ -31,41 +30,41 @@ object CustomTheories { logicProgramming { ktListOf( ("a"("X") then "b"("X")).hasSolutions( - { yes("X" to 1) } + { yes("X" to 1) }, ), ("a"("X") then "c"("X")).hasSolutions( - { no() } + { no() }, ), ("a"(1) then "b"("X")).hasSolutions( - { yes("X" to 1) } + { yes("X" to 1) }, ), ("a"(2) then "b"("X")).hasSolutions( - { yes("X" to 1) } + { yes("X" to 1) }, ), ("a"(1) then "c"("X")).hasSolutions( - { yes("X" to 2) } + { yes("X" to 2) }, ), ("a"(2) then "c"("X")).hasSolutions( - { yes("X" to 2) } + { yes("X" to 2) }, ), (("a"("X") and "!") then "b"("X")).hasSolutions( - { yes("X" to 1) } + { yes("X" to 1) }, ), (("a"("X") and "!") then "c"("X")).hasSolutions( - { no() } + { no() }, ), (("a"("X") and ("X" greaterThan 1)) then "b"("X")).hasSolutions( - { no() } + { no() }, ), (("a"("X") and ("X" greaterThan 1)) then "c"("X")).hasSolutions( - { yes("X" to 2) } + { yes("X" to 2) }, ), (("a"("X") and "!" and ("X" greaterThan 1)) then "b"("X")).hasSolutions( - { no() } + { no() }, ), (("a"("X") and "!" and ("X" greaterThan 1)) then "c"("X")).hasSolutions( - { no() } - ) + { no() }, + ), ) } } @@ -74,41 +73,41 @@ object CustomTheories { logicProgramming { ktListOf( ("a"("X") then "b"("X")).hasSolutions( - { no() } + { no() }, ), ("a"("X") then "c"("X")).hasSolutions( - { yes("X" to 2) } + { yes("X" to 2) }, ), ("a"(1) then "b"("X")).hasSolutions( - { yes("X" to 1) } + { yes("X" to 1) }, ), ("a"(2) then "b"("X")).hasSolutions( - { yes("X" to 1) } + { yes("X" to 1) }, ), ("a"(1) then "c"("X")).hasSolutions( - { yes("X" to 2) } + { yes("X" to 2) }, ), ("a"(2) then "c"("X")).hasSolutions( - { yes("X" to 2) } + { yes("X" to 2) }, ), (("a"("X") and "!") then "b"("X")).hasSolutions( - { no() } + { no() }, ), (("a"("X") and "!") then "c"("X")).hasSolutions( - { yes("X" to 2) } + { yes("X" to 2) }, ), (("a"("X") and ("X" greaterThan 1)) then "b"("X")).hasSolutions( - { no() } + { no() }, ), (("a"("X") and ("X" greaterThan 1)) then "c"("X")).hasSolutions( - { yes("X" to 2) } + { yes("X" to 2) }, ), (("a"("X") and "!" and ("X" greaterThan 1)) then "b"("X")).hasSolutions( - { no() } + { no() }, ), (("a"("X") and "!" and ("X" greaterThan 1)) then "c"("X")).hasSolutions( - { yes("X" to 2) } - ) + { yes("X" to 2) }, + ), ) } } @@ -117,42 +116,41 @@ object CustomTheories { logicProgramming { ktListOf( ("a"("X") then "b"("X") or "c"("X")).hasSolutions( - { yes("X" to 1) } + { yes("X" to 1) }, ), ("a"("X") and ("X" greaterThan 1) then "b"("X") or "c"("X")).hasSolutions( - { no() } + { no() }, ), ("a"("X") and ("X" lowerThan 2) then "b"("X") or "c"("X")).hasSolutions( - { yes("X" to 1) } + { yes("X" to 1) }, ), ("a"("X") and "!" then "b"("X") or "c"("X")).hasSolutions( - { yes("X" to 1) } + { yes("X" to 1) }, ), ("a"("X") and "!" and ("X" greaterThan 1) then "b"("X") or "c"("X")).hasSolutions( - { yes("X" to 2) } + { yes("X" to 2) }, ), ("a"("X") and "!" and ("X" lowerThan 2) then "b"("X") or "c"("X")).hasSolutions( - { yes("X" to 1) } + { yes("X" to 1) }, ), - ("a"("X") then "c"("X") or "b"("X")).hasSolutions( - { no() } + { no() }, ), ("a"("X") and ("X" greaterThan 1) then "c"("X") or "b"("X")).hasSolutions( - { yes("X" to 2) } + { yes("X" to 2) }, ), ("a"("X") and ("X" lowerThan 2) then "c"("X") or "b"("X")).hasSolutions( - { no() } + { no() }, ), ("a"("X") and "!" then "c"("X") or "b"("X")).hasSolutions( - { no() } + { no() }, ), ("a"("X") and "!" and ("X" greaterThan 1) then "c"("X") or "b"("X")).hasSolutions( - { yes("X" to 1) } + { yes("X" to 1) }, ), ("a"("X") and "!" and ("X" lowerThan 2) then "c"("X") or "b"("X")).hasSolutions( - { no() } - ) + { no() }, + ), ) } } @@ -161,42 +159,41 @@ object CustomTheories { logicProgramming { ktListOf( ("a"("X") then "b"("X") or "c"("X")).hasSolutions( - { no() } + { no() }, ), ("a"("X") and ("X" greaterThan 1) then "b"("X") or "c"("X")).hasSolutions( - { no() } + { no() }, ), ("a"("X") and ("X" lowerThan 2) then "b"("X") or "c"("X")).hasSolutions( - { yes("X" to 1) } + { yes("X" to 1) }, ), ("a"("X") and "!" then "b"("X") or "c"("X")).hasSolutions( - { no() } + { no() }, ), ("a"("X") and "!" and ("X" greaterThan 1) then "b"("X") or "c"("X")).hasSolutions( - { no() } + { no() }, ), ("a"("X") and "!" and ("X" lowerThan 2) then "b"("X") or "c"("X")).hasSolutions( - { yes("X" to 2) } + { yes("X" to 2) }, ), - ("a"("X") then "c"("X") or "b"("X")).hasSolutions( - { yes("X" to 2) } + { yes("X" to 2) }, ), ("a"("X") and ("X" greaterThan 1) then "c"("X") or "b"("X")).hasSolutions( - { yes("X" to 2) } + { yes("X" to 2) }, ), ("a"("X") and ("X" lowerThan 2) then "c"("X") or "b"("X")).hasSolutions( - { no() } + { no() }, ), ("a"("X") and "!" then "c"("X") or "b"("X")).hasSolutions( - { yes("X" to 2) } + { yes("X" to 2) }, ), ("a"("X") and "!" and ("X" greaterThan 1) then "c"("X") or "b"("X")).hasSolutions( - { yes("X" to 2) } + { yes("X" to 2) }, ), ("a"("X") and "!" and ("X" lowerThan 2) then "c"("X") or "b"("X")).hasSolutions( - { yes("X" to 1) } - ) + { yes("X" to 1) }, + ), ) } } @@ -208,11 +205,11 @@ object CustomTheories { { yes("X" to "a") }, { yes("X" to "b") }, { yes("X" to "c") }, - { no() } + { no() }, ), "member"("f"("X"), listOf("a"(1), "b"(2), "c"(3))).hasSolutions( - { no() } - ) + { no() }, + ), ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/DirectiveTestsUtils.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/DirectiveTestsUtils.kt index eb3c331e0..ab96a99be 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/DirectiveTestsUtils.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/DirectiveTestsUtils.kt @@ -10,38 +10,48 @@ import it.unibo.tuprolog.solve.exception.Warning import it.unibo.tuprolog.theory.Theory object DirectiveTestsUtils { - private const val BIG_THEORY_SIZE = 40000 - fun bigTheory(size: Int = BIG_THEORY_SIZE, last: (LogicProgrammingScope.() -> Clause)? = null) = - logicProgramming { - theoryOf( - sequence { - for (i in 1..size) { - yield(fact { "f$i" }) - } - if (last != null) { - yield(this@logicProgramming.last()) - } + fun bigTheory( + size: Int = BIG_THEORY_SIZE, + last: (LogicProgrammingScope.() -> Clause)? = null, + ) = logicProgramming { + theoryOf( + sequence { + for (i in 1..size) { + yield(fact { "f$i" }) } - ) - } + if (last != null) { + yield(this@logicProgramming.last()) + } + }, + ) + } - fun dynamicDirective(functor: String, arity: Int): Sequence = + fun dynamicDirective( + functor: String, + arity: Int, + ): Sequence = logicProgramming { sequenceOf( - directive { "dynamic"(functor / arity) } + directive { "dynamic"(functor / arity) }, ) } - fun staticDirective(functor: String, arity: Int): Sequence = + fun staticDirective( + functor: String, + arity: Int, + ): Sequence = logicProgramming { sequenceOf( - directive { "static"(functor / arity) } + directive { "static"(functor / arity) }, ) } - fun facts(functor: String, iterable: Iterable): Sequence = + fun facts( + functor: String, + iterable: Iterable, + ): Sequence = logicProgramming { iterable.asSequence().map { fact { functor(it) } } } @@ -51,11 +61,11 @@ object DirectiveTestsUtils { { solverFactory.solverOf(staticKb = it) }, { solverFactory.solverOf(dynamicKb = it.toMutableTheory()) }, { solverFactory.mutableSolverOf().also { s -> s.loadStaticKb(it) } }, - { solverFactory.mutableSolverOf().also { s -> s.loadDynamicKb(it.toMutableTheory()) } } + { solverFactory.mutableSolverOf().also { s -> s.loadDynamicKb(it.toMutableTheory()) } }, ) fun solverInitializersWithEventsList( - solverFactory: SolverFactory + solverFactory: SolverFactory, ): List Solver, MutableList>> { fun stdOut(action: (MutableList, OutputChannel, OutputChannel) -> R): R { val events = mutableListOf() @@ -75,7 +85,7 @@ object DirectiveTestsUtils { dynamicKb = t.toMutableTheory(), stdOut = out, stdErr = out, - warnings = warn + warnings = warn, ) } to event }, @@ -90,7 +100,7 @@ object DirectiveTestsUtils { solverFactory.mutableSolverWithDefaultBuiltins(stdOut = out, stdErr = out, warnings = warn) .also { it.loadDynamicKb(t.toMutableTheory()) } } to event - } + }, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/DummyInstances.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/DummyInstances.kt index 75a3eca9a..8eecee2c1 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/DummyInstances.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/DummyInstances.kt @@ -18,61 +18,61 @@ import it.unibo.tuprolog.unify.Unificator * @author Enrico */ object DummyInstances { - /** An empty context to be used where needed to fill parameters */ @Suppress("IMPLICIT_NOTHING_AS_TYPE_PARAMETER", "IMPLICIT_NOTHING_TYPE_ARGUMENT_IN_RETURN_POSITION") - val executionContext = object : ExecutionContext { - override val unificator: Unificator get() = Unificator.default - override val procedure: Struct by lazy { Atom.of("dummyProcedure") } - override val libraries: Nothing by lazy { throw NotImplementedError() } - override val flags: Nothing by lazy { throw NotImplementedError() } - override val staticKb: Nothing by lazy { throw NotImplementedError() } - override val dynamicKb: Nothing by lazy { throw NotImplementedError() } - override val operators: OperatorSet by lazy { throw NotImplementedError() } - override val inputChannels: Nothing by lazy { throw NotImplementedError() } - override val outputChannels: Nothing by lazy { throw NotImplementedError() } - override val substitution: Substitution.Unifier = Substitution.empty() - override val logicStackTrace: Nothing by lazy { throw NotImplementedError() } - override val customData: Nothing by lazy { throw NotImplementedError() } - override val startTime: TimeInstant = 0L - override val maxDuration: TimeDuration = TimeDuration.MAX_VALUE + val executionContext = + object : ExecutionContext { + override val unificator: Unificator get() = Unificator.default + override val procedure: Struct by lazy { Atom.of("dummyProcedure") } + override val libraries: Nothing by lazy { throw NotImplementedError() } + override val flags: Nothing by lazy { throw NotImplementedError() } + override val staticKb: Nothing by lazy { throw NotImplementedError() } + override val dynamicKb: Nothing by lazy { throw NotImplementedError() } + override val operators: OperatorSet by lazy { throw NotImplementedError() } + override val inputChannels: Nothing by lazy { throw NotImplementedError() } + override val outputChannels: Nothing by lazy { throw NotImplementedError() } + override val substitution: Substitution.Unifier = Substitution.empty() + override val logicStackTrace: Nothing by lazy { throw NotImplementedError() } + override val customData: Nothing by lazy { throw NotImplementedError() } + override val startTime: TimeInstant = 0L + override val maxDuration: TimeDuration = TimeDuration.MAX_VALUE - override fun createSolver( - unificator: Unificator, - libraries: Runtime, - flags: FlagStore, - staticKb: Theory, - dynamicKb: Theory, - inputChannels: InputStore, - outputChannels: OutputStore - ): Solver { - throw NotImplementedError() - } + override fun createSolver( + unificator: Unificator, + libraries: Runtime, + flags: FlagStore, + staticKb: Theory, + dynamicKb: Theory, + inputChannels: InputStore, + outputChannels: OutputStore, + ): Solver { + throw NotImplementedError() + } - override fun createMutableSolver( - unificator: Unificator, - libraries: Runtime, - flags: FlagStore, - staticKb: Theory, - dynamicKb: Theory, - inputChannels: InputStore, - outputChannels: OutputStore - ): MutableSolver { - throw NotImplementedError() - } + override fun createMutableSolver( + unificator: Unificator, + libraries: Runtime, + flags: FlagStore, + staticKb: Theory, + dynamicKb: Theory, + inputChannels: InputStore, + outputChannels: OutputStore, + ): MutableSolver { + throw NotImplementedError() + } - override fun update( - unificator: Unificator, - libraries: Runtime, - flags: FlagStore, - staticKb: Theory, - dynamicKb: Theory, - operators: OperatorSet, - inputChannels: InputStore, - outputChannels: OutputStore, - customData: CustomDataStore - ): ExecutionContext { - throw NotImplementedError() + override fun update( + unificator: Unificator, + libraries: Runtime, + flags: FlagStore, + staticKb: Theory, + dynamicKb: Theory, + operators: OperatorSet, + inputChannels: InputStore, + outputChannels: OutputStore, + customData: CustomDataStore, + ): ExecutionContext { + throw NotImplementedError() + } } - } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Expectations.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Expectations.kt index 1e8deff54..dddcc6401 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Expectations.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/Expectations.kt @@ -5,5 +5,5 @@ data class Expectations( val streamsShouldWork: Boolean = false, val prologShouldWork: Boolean = false, val problogShouldWork: Boolean = false, - val concurrentShouldWork: Boolean = false + val concurrentShouldWork: Boolean = false, ) diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/PrologStandardExampleTheories.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/PrologStandardExampleTheories.kt index cc85fc69b..98b7e7203 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/PrologStandardExampleTheories.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/PrologStandardExampleTheories.kt @@ -14,7 +14,6 @@ import it.unibo.tuprolog.theory.Theory * @author Enrico */ object PrologStandardExampleTheories { - /** * The clause database used in Prolog Standard reference manual, when explaining solver functionality and search-trees * @@ -39,7 +38,7 @@ object PrologStandardExampleTheories { { "q"("b") }, { "q"("c") }, { "r"("b", "b1") }, - { "r"("c", "c1") } + { "r"("c", "c1") }, ) } } @@ -56,8 +55,8 @@ object PrologStandardExampleTheories { "p"("U", "V").hasSolutions( { yes("U" to "b", "V" to "b1") }, { yes("U" to "c", "V" to "c1") }, - { yes("U" to "d", "V" to "Y") } - ) + { yes("U" to "d", "V" to "Y") }, + ), ) } } @@ -92,7 +91,7 @@ object PrologStandardExampleTheories { val prologStandardExampleWithCutTheoryNotableGoalToSolution by lazy { logicProgramming { ktListOf( - "p"("U", "V").hasSolutions({ no() }) + "p"("U", "V").hasSolutions({ no() }), ) } } @@ -114,7 +113,7 @@ object PrologStandardExampleTheories { { "legs"("A", 4) `if` "animal"("A") }, { "insect"("bee") }, { "insect"("ant") }, - { "fly"("bee") } + { "fly"("bee") }, ) } } @@ -131,13 +130,13 @@ object PrologStandardExampleTheories { (("insect"("X") or "legs"("X", 6)) and "fly"("X")).hasSolutions( { yes("X" to "bee") }, { yes("X" to "bee") }, - { no() } + { no() }, ), (("insect"("X") and "fly"("X")) or ("legs"("X", 6) and "fly"("X"))).hasSolutions( { yes("X" to "bee") }, { yes("X" to "bee") }, - { no() } - ) + { no() }, + ), ) } } @@ -153,7 +152,7 @@ object PrologStandardExampleTheories { logicProgramming { theory( { "a"(1) }, - { "a"(2) } + { "a"(2) }, ) } } @@ -174,15 +173,17 @@ object PrologStandardExampleTheories { ktListOf( ("call"("!") or true).hasSolutions({ yes() }, { yes() }), ("="("Z", "!") and "call"("="("Z", "!") and "a"("X") and "Z")).hasSolutions( - { yes("X" to 1, "Z" to "!") } + { yes("X" to 1, "Z" to "!") }, ), "call"("="("Z", "!") and "a"("X") and "Z").hasSolutions( { yes("X" to 1, "Z" to "!") }, - { yes("X" to 2, "Z" to "!") } + { yes("X" to 2, "Z" to "!") }, ), "call"(false).hasSolutions({ no() }), "call"(true and "X").hasSolutions({ halt(instantiationError(errorSignature, varOf("X"))) }), - "call"(true and (false and 1)).hasSolutions({ halt(typeError(errorSignature, true and (false and 1))) }) + "call"( + true and (false and 1), + ).hasSolutions({ halt(typeError(errorSignature, true and (false and 1))) }), ) } @@ -201,7 +202,7 @@ object PrologStandardExampleTheories { { "p" }, { "p" `if` "throw"("b") }, { "r"("X") `if` "throw"("X") }, - { "q" `if` ("catch"("p", "B", true) and "r"("c")) } + { "q" `if` ("catch"("p", "B", true) and "r"("c")) }, ) } } @@ -224,17 +225,17 @@ object PrologStandardExampleTheories { ktListOf( "catch"("p", "X", true).hasSolutions( { yes("X" to "E") }, - { yes("X" to "b") } + { yes("X" to "b") }, ), "catch"("q", "C", true).hasSolutions({ yes("C" to "c") }), "catch"("throw"("exit"(1)), "exit"("X"), true).hasSolutions({ yes("X" to 1) }), "catch"("throw"(true), "X", "X").hasSolutions({ yes("X" to true) }), "catch"("throw"(false), "X", "X").hasSolutions({ no() }), "catch"("throw"("f"("X", "X")), "f"("X", "g"("X")), true).hasSolutions( - { halt(systemError("f"("X", "X"))) } + { halt(systemError("f"("X", "X"))) }, ), "catch"("throw"(1), "X", false or "X").hasSolutions({ halt(typeError(";", 2, intOf(1))) }), - "catch"("throw"(false), true, "G").hasSolutions({ halt(systemError(truthOf(false))) }) + "catch"("throw"(false), true, "G").hasSolutions({ halt(systemError(truthOf(false))) }), ) } } @@ -258,15 +259,13 @@ object PrologStandardExampleTheories { logicProgramming { theory( { "shave"("barber", "X") `if` "not"("shave"("X", "X")) }, - { "test_Prolog_unifiable"("X", "Y") `if` "not"("not"("X" equalsTo "Y")) }, - { "p1" `if` "not"("q1") }, { "q1" `if` false }, { "q1" `if` true }, { "p2" `if` "not"("q2") }, { "q2" `if` ("!" and false) }, - { "q2" `if` true } + { "q2" `if` true }, ) } } @@ -292,34 +291,32 @@ object PrologStandardExampleTheories { * ?- p2. * ``` */ - fun notStandardExampleTheoryNotableGoalToSolution(nafErrorSignature: Signature, notErrorSignature: Signature) = - logicProgramming { - ktListOf( - (("X" equalsTo 3) and "\\+"(("X" equalsTo 1) or ("X" equalsTo 2))).hasSolutions({ yes("X" to 3) }), - "\\+"(fail).hasSolutions({ yes() }), - ("\\+"("!") or ("X" equalsTo 1)).hasSolutions({ yes("X" to 1) }), - ("\\+"(("X" equalsTo 1) or ("X" equalsTo 2)) and ("X" equalsTo 3)).hasSolutions({ no() }), - (("X" equalsTo 1) and "\\+"(("X" equalsTo 1) or ("X" equalsTo 2))).hasSolutions({ no() }), - "\\+"(fail and 1).hasSolutions({ halt(typeError(nafErrorSignature, fail and 1)) }), - - "shave"("barber", "'Donald'").hasSolutions({ yes() }), - "shave"("barber", "barber").hasSolutions({ halt(timeOutException) }), - - "test_Prolog_unifiable"("f"("a", "X"), "f"("X", "a")).hasSolutions({ yes() }), - "test_Prolog_unifiable"("f"("a", "X"), "f"("X", "b")).hasSolutions({ no() }), - "test_Prolog_unifiable"("X", "f"("X")).hasSolutions({ no() }), - - atomOf("p1").hasSolutions({ no() }), - atomOf("p2").hasSolutions({ yes() }), - - (("X" equalsTo 3) and "\\+"(("X" equalsTo 1) or ("X" equalsTo 2))).hasSolutions({ yes("X" to 3) }), - "not"(fail).hasSolutions({ yes() }), - ("not"("!") or ("X" equalsTo 1)).hasSolutions({ yes("X" to 1) }), - ("not"(("X" equalsTo 1) or ("X" equalsTo 2)) and ("X" equalsTo 3)).hasSolutions({ no() }), - (("X" equalsTo 1) and "not"(("X" equalsTo 1) or ("X" equalsTo 2))).hasSolutions({ no() }), - "not"(fail and 1).hasSolutions({ halt(typeError(notErrorSignature, fail and 1)) }) - ) - } + fun notStandardExampleTheoryNotableGoalToSolution( + nafErrorSignature: Signature, + notErrorSignature: Signature, + ) = logicProgramming { + ktListOf( + (("X" equalsTo 3) and "\\+"(("X" equalsTo 1) or ("X" equalsTo 2))).hasSolutions({ yes("X" to 3) }), + "\\+"(fail).hasSolutions({ yes() }), + ("\\+"("!") or ("X" equalsTo 1)).hasSolutions({ yes("X" to 1) }), + ("\\+"(("X" equalsTo 1) or ("X" equalsTo 2)) and ("X" equalsTo 3)).hasSolutions({ no() }), + (("X" equalsTo 1) and "\\+"(("X" equalsTo 1) or ("X" equalsTo 2))).hasSolutions({ no() }), + "\\+"(fail and 1).hasSolutions({ halt(typeError(nafErrorSignature, fail and 1)) }), + "shave"("barber", "'Donald'").hasSolutions({ yes() }), + "shave"("barber", "barber").hasSolutions({ halt(timeOutException) }), + "test_Prolog_unifiable"("f"("a", "X"), "f"("X", "a")).hasSolutions({ yes() }), + "test_Prolog_unifiable"("f"("a", "X"), "f"("X", "b")).hasSolutions({ no() }), + "test_Prolog_unifiable"("X", "f"("X")).hasSolutions({ no() }), + atomOf("p1").hasSolutions({ no() }), + atomOf("p2").hasSolutions({ yes() }), + (("X" equalsTo 3) and "\\+"(("X" equalsTo 1) or ("X" equalsTo 2))).hasSolutions({ yes("X" to 3) }), + "not"(fail).hasSolutions({ yes() }), + ("not"("!") or ("X" equalsTo 1)).hasSolutions({ yes("X" to 1) }), + ("not"(("X" equalsTo 1) or ("X" equalsTo 2)) and ("X" equalsTo 3)).hasSolutions({ no() }), + (("X" equalsTo 1) and "not"(("X" equalsTo 1) or ("X" equalsTo 2))).hasSolutions({ no() }), + "not"(fail and 1).hasSolutions({ halt(typeError(notErrorSignature, fail and 1)) }), + ) + } /** * The database used in Prolog standard while writing examples for If-Then @@ -336,7 +333,7 @@ object PrologStandardExampleTheories { { "legs"("A", 6) `if` "insect"("A") }, { "legs"("horse", 4) }, { "insect"("bee") }, - { "insect"("ant") } + { "insect"("ant") }, ) } } @@ -356,7 +353,7 @@ object PrologStandardExampleTheories { ("->"("X" equalsTo 0, true)).hasSolutions({ yes("X" to 0) }), ("->"("legs"("A", 6), true)).hasSolutions({ yes("A" to "bee") }), ("->"("\\="("X", 0), true)).hasSolutions({ no() }), - ("->"(false, ";"(true, true))).hasSolutions({ no() }) + ("->"(false, ";"(true, true))).hasSolutions({ no() }), ) } } @@ -380,12 +377,12 @@ object PrologStandardExampleTheories { ( "->"( "!" and ("X" equalsTo 1) and false, - true + true, ) or false - ) or ("X" equalsTo 2) - ).hasSolutions({ yes("X" to 2) }), + ) or ("X" equalsTo 2) + ).hasSolutions({ yes("X" to 2) }), ("->"(false, true) or true).hasSolutions({ yes() }), - ("->"("!" and ("X" equalsTo 1) and false, true) or false).hasSolutions({ no() }) + ("->"("!" and ("X" equalsTo 1) and false, true) or false).hasSolutions({ no() }), ) } } @@ -394,7 +391,7 @@ object PrologStandardExampleTheories { fun allPrologStandardTestingTheoryToRespectiveGoalsAndSolutions( callErrorSignature: Signature, nafErrorSignature: Signature, - notErrorSignature: Signature + notErrorSignature: Signature, ) = mapOf( prologStandardExampleTheory to prologStandardExampleTheoryNotableGoalToSolution, prologStandardExampleWithCutTheory to prologStandardExampleWithCutTheoryNotableGoalToSolution, @@ -403,6 +400,6 @@ object PrologStandardExampleTheories { catchAndThrowTheoryExample to catchAndThrowTheoryExampleNotableGoalToSolution, notStandardExampleTheory to notStandardExampleTheoryNotableGoalToSolution(nafErrorSignature, notErrorSignature), ifThenStandardExampleTheory to ifThenStandardExampleTheoryNotableGoalToSolution, - Theory.empty() to ifThenElseStandardExampleNotableGoalToSolution + Theory.empty() to ifThenElseStandardExampleNotableGoalToSolution, ) } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolverTest.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolverTest.kt index 8671c0934..118dbc254 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolverTest.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/SolverTest.kt @@ -17,9 +17,10 @@ interface SolverTest { get() = 4 * mediumDuration companion object { - private val OS_SPECIFIC_TIME_MULTIPLIER: Int = when (Info.OS) { - Os.WINDOWS -> 2 - else -> 1 - } + private val OS_SPECIFIC_TIME_MULTIPLIER: Int = + when (Info.OS) { + Os.WINDOWS -> 2 + else -> 1 + } } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAbolish.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAbolish.kt index 0821e295c..18fb5f07a 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAbolish.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAbolish.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestAbolish : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestAbolish = - TestAbolishImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestAbolish = TestAbolishImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAbolishImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAbolishImpl.kt index 09c24cb54..c76d5a78b 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAbolishImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAbolishImpl.kt @@ -22,11 +22,11 @@ internal class TestAbolishImpl(private val solverFactory: SolverFactory) : TestA Signature("abolish", 1), PermissionError.Operation.MODIFY, PermissionError.Permission.PRIVATE_PROCEDURE, - "abolish" / 1 - ) - ) + "abolish" / 1, + ), + ), ), - solutions + solutions, ) } } @@ -46,11 +46,11 @@ internal class TestAbolishImpl(private val solverFactory: SolverFactory) : TestA Signature("abolish", 1), TypeError.Expected.INTEGER, atomOf("a"), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } @@ -70,11 +70,11 @@ internal class TestAbolishImpl(private val solverFactory: SolverFactory) : TestA Signature("abolish", 1), DomainError.Expected.NOT_LESS_THAN_ZERO, intOf(-1), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } @@ -92,11 +92,11 @@ internal class TestAbolishImpl(private val solverFactory: SolverFactory) : TestA RepresentationError.of( DummyInstances.executionContext, Signature("abolish", 1), - RepresentationError.Limit.MAX_ARITY - ) - ) + RepresentationError.Limit.MAX_ARITY, + ), + ), ), - solutions + solutions, ) } } @@ -116,11 +116,11 @@ internal class TestAbolishImpl(private val solverFactory: SolverFactory) : TestA Signature("abolish", 1), TypeError.Expected.ATOM, intOf(5), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAnd.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAnd.kt index 531d22a47..7c08be120 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAnd.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAnd.kt @@ -2,10 +2,8 @@ package it.unibo.tuprolog.solve /** A prototype class for testing solver implementations */ interface TestAnd : SolverTest { - companion object { - fun prototype(solverFactory: SolverFactory): TestAnd = - TestAndImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestAnd = TestAndImpl(solverFactory) } /** Test presence of correct built-ins */ diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAndImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAndImpl.kt index b8a6ce18d..583b9db9a 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAndImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAndImpl.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.flags.FlagStore import it.unibo.tuprolog.solve.flags.Unknown internal class TestAndImpl(private val solverFactory: SolverFactory) : TestAnd { - override fun testTermIsFreeVariable() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() @@ -16,7 +15,7 @@ internal class TestAndImpl(private val solverFactory: SolverFactory) : TestAnd { assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } @@ -30,7 +29,7 @@ internal class TestAndImpl(private val solverFactory: SolverFactory) : TestAnd { assertSolutionEquals( ktListOf(query.yes("X" to 1)), - solutions + solutions, ) } } @@ -44,16 +43,17 @@ internal class TestAndImpl(private val solverFactory: SolverFactory) : TestAnd { assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } override fun testNoFooIsCallable() { logicProgramming { - val solver = solverFactory.solverWithDefaultBuiltins( - flags = FlagStore.of(Unknown to Unknown.ERROR) - ) + val solver = + solverFactory.solverWithDefaultBuiltins( + flags = FlagStore.of(Unknown to Unknown.ERROR), + ) val query = "nofoo"("X") and call("X") val solutions = solver.solve(query, mediumDuration).toList() @@ -63,11 +63,11 @@ internal class TestAndImpl(private val solverFactory: SolverFactory) : TestAnd { query.halt( ExistenceError.forProcedure( DummyInstances.executionContext, - Signature("nofoo", 1) - ) - ) + Signature("nofoo", 1), + ), + ), ), - solutions + solutions, ) } } @@ -81,7 +81,7 @@ internal class TestAndImpl(private val solverFactory: SolverFactory) : TestAnd { assertSolutionEquals( ktListOf(query.yes("X" to true)), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestArg.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestArg.kt index 7984443b2..c1add44cc 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestArg.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestArg.kt @@ -5,8 +5,7 @@ package it.unibo.tuprolog.solve */ interface TestArg : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestArg = - TestArgImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestArg = TestArgImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestArgImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestArgImpl.kt index 03cd7b0a1..dc1cab302 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestArgImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestArgImpl.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.exception.error.InstantiationError import it.unibo.tuprolog.solve.exception.error.TypeError internal class TestArgImpl(private val solverFactory: SolverFactory) : TestArg { - override fun testArgFromFoo() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() @@ -16,7 +15,7 @@ internal class TestArgImpl(private val solverFactory: SolverFactory) : TestArg { assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) } } @@ -30,7 +29,7 @@ internal class TestArgImpl(private val solverFactory: SolverFactory) : TestArg { assertSolutionEquals( ktListOf(query.yes("X" to "a")), - solutions + solutions, ) } } @@ -44,7 +43,7 @@ internal class TestArgImpl(private val solverFactory: SolverFactory) : TestArg { assertSolutionEquals( ktListOf(query.yes("X" to "a")), - solutions + solutions, ) } } @@ -59,10 +58,10 @@ internal class TestArgImpl(private val solverFactory: SolverFactory) : TestArg { assertSolutionEquals( with(query) { ktListOf( - yes("X" to "a", "Y" to "b") + yes("X" to "a", "Y" to "b"), ) }, - solutions + solutions, ) } } @@ -76,7 +75,7 @@ internal class TestArgImpl(private val solverFactory: SolverFactory) : TestArg { assertSolutionEquals( ktListOf(query.yes("Y" to "X")), - solutions + solutions, ) } } @@ -90,7 +89,7 @@ internal class TestArgImpl(private val solverFactory: SolverFactory) : TestArg { assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } @@ -104,7 +103,7 @@ internal class TestArgImpl(private val solverFactory: SolverFactory) : TestArg { assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } @@ -118,7 +117,7 @@ internal class TestArgImpl(private val solverFactory: SolverFactory) : TestArg { assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } @@ -132,9 +131,9 @@ internal class TestArgImpl(private val solverFactory: SolverFactory) : TestArg { assertSolutionEquals( ktListOf( - query.yes("X" to 1) + query.yes("X" to 1), ), - solutions + solutions, ) } } @@ -153,11 +152,11 @@ internal class TestArgImpl(private val solverFactory: SolverFactory) : TestArg { DummyInstances.executionContext, Signature("arg", 3), varOf("X"), - index = 1 - ) - ) + index = 1, + ), + ), ), - solutions + solutions, ) } } @@ -177,11 +176,11 @@ internal class TestArgImpl(private val solverFactory: SolverFactory) : TestArg { Signature("arg", 3), TypeError.Expected.COMPOUND, atomOf("atom"), - index = 1 - ) - ) + index = 1, + ), + ), ), - solutions + solutions, ) } } @@ -201,11 +200,11 @@ internal class TestArgImpl(private val solverFactory: SolverFactory) : TestArg { Signature("arg", 3), TypeError.Expected.COMPOUND, numOf(3), - index = 1 - ) - ) + index = 1, + ), + ), ), - solutions + solutions, ) } } @@ -225,11 +224,11 @@ internal class TestArgImpl(private val solverFactory: SolverFactory) : TestArg { Signature("arg", 3), DomainError.Expected.NOT_LESS_THAN_ZERO, numOf(-3), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } @@ -249,11 +248,11 @@ internal class TestArgImpl(private val solverFactory: SolverFactory) : TestArg { Signature("arg", 3), TypeError.Expected.INTEGER, atomOf("a"), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestArith.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestArith.kt index 13e418910..3c1dcd3e1 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestArith.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestArith.kt @@ -5,8 +5,7 @@ package it.unibo.tuprolog.solve */ interface TestArith : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestArith = - TestArithImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestArith = TestArithImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestArithImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestArithImpl.kt index 605fbf3b9..aabf9611b 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestArithImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestArithImpl.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.solve.exception.error.TypeError import it.unibo.tuprolog.solve.exception.error.TypeError.Expected.EVALUABLE internal class TestArithImpl(private val solverFactory: SolverFactory) : TestArith { - override fun testArithDiff() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() @@ -16,7 +15,7 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) query = 1.0 arithNeq 1 @@ -24,7 +23,7 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) query = (numOf(3) * 2) arithNeq (numOf(7) - 1) @@ -32,7 +31,7 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) query = "N" arithNeq 5 @@ -45,11 +44,11 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri DummyInstances.executionContext, Signature("=\\=", 2), varOf("N"), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) query = "floot"(1) arithNeq 5 @@ -63,11 +62,11 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri Signature("=\\=", 2), EVALUABLE, "floot"(1), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } @@ -81,7 +80,7 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) query = 1.0 arithEq 1 @@ -89,7 +88,7 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) query = (numOf(3) * 2) arithEq (numOf(7) - 1) @@ -97,7 +96,7 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) query = "N" arithEq 5 @@ -110,11 +109,11 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri DummyInstances.executionContext, Signature("=:=", 2), varOf("N"), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) query = "floot"(1) arithEq 5 @@ -128,11 +127,11 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri Signature("=:=", 2), EVALUABLE, "floot"(1), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) query = 0.333 arithEq (numOf(1) / 3) @@ -140,7 +139,7 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } @@ -154,7 +153,7 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) query = 1.0 greaterThan 1 @@ -162,7 +161,7 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) query = (numOf(3) * 2) greaterThan (numOf(7) - 1) @@ -170,7 +169,7 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) query = "X" greaterThan 5 @@ -183,11 +182,11 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri DummyInstances.executionContext, Signature(">", 2), varOf("X"), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) query = (2 + "floot"(1)) greaterThan 5 @@ -201,11 +200,11 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri Signature(">", 2), EVALUABLE, "floot"(1), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } @@ -219,7 +218,7 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) query = 1.0 greaterThanOrEqualsTo 1 @@ -227,7 +226,7 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) query = (numOf(3) * 2) greaterThanOrEqualsTo (numOf(7) - 1) @@ -235,7 +234,7 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) query = "X" greaterThanOrEqualsTo 5 @@ -248,11 +247,11 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri DummyInstances.executionContext, Signature(">=", 2), varOf("X"), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) query = (2 + "floot"(1)) greaterThanOrEqualsTo 5 @@ -266,11 +265,11 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri Signature(">=", 2), EVALUABLE, "floot"(1), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } @@ -284,7 +283,7 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) query = 1.0 lowerThan 1 @@ -292,7 +291,7 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) query = (numOf(3) * 2) lowerThan (numOf(7) - 1) @@ -300,7 +299,7 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) query = "X" lowerThan 5 @@ -313,11 +312,11 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri DummyInstances.executionContext, Signature("<", 2), varOf("X"), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) query = (2 + "floot"(1)) lowerThan 5 @@ -331,11 +330,11 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri Signature("<", 2), EVALUABLE, "floot"(1), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } @@ -349,7 +348,7 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) query = 1.0 lowerThanOrEqualsTo 1 @@ -357,7 +356,7 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) query = (numOf(3) * 2) lowerThanOrEqualsTo (numOf(7) - 1) @@ -365,7 +364,7 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) query = "X" lowerThanOrEqualsTo 5 @@ -378,11 +377,11 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri DummyInstances.executionContext, Signature("=<", 2), varOf("X"), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) query = (2 + "floot"(1)) lowerThanOrEqualsTo 5 @@ -396,11 +395,11 @@ internal class TestArithImpl(private val solverFactory: SolverFactory) : TestAri Signature("=<", 2), EVALUABLE, "floot"(1), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAssertA.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAssertA.kt index 47098b11c..55a1a01e2 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAssertA.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAssertA.kt @@ -5,8 +5,7 @@ package it.unibo.tuprolog.solve */ interface TestAssertA : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestAssertA = - TestAssertAImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestAssertA = TestAssertAImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAssertAImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAssertAImpl.kt index 641d2dade..9b3748196 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAssertAImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAssertAImpl.kt @@ -7,7 +7,6 @@ import it.unibo.tuprolog.solve.exception.error.PermissionError import it.unibo.tuprolog.solve.exception.error.TypeError internal class TestAssertAImpl(private val solverFactory: SolverFactory) : TestAssertA { - override fun testAssertAClause() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() @@ -17,7 +16,7 @@ internal class TestAssertAImpl(private val solverFactory: SolverFactory) : TestA assertSolutionEquals( ktListOf(query.yes("B" to call("X"))), - solutions + solutions, ) } } @@ -36,11 +35,11 @@ internal class TestAssertAImpl(private val solverFactory: SolverFactory) : TestA DummyInstances.executionContext, Signature("asserta", 1), `_`, - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } @@ -60,11 +59,11 @@ internal class TestAssertAImpl(private val solverFactory: SolverFactory) : TestA Signature("asserta", 1), TypeError.Expected.CALLABLE, numOf(4), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } @@ -84,11 +83,11 @@ internal class TestAssertAImpl(private val solverFactory: SolverFactory) : TestA Signature("asserta", 1), DomainError.Expected.CLAUSE, ("foo" `if` 4), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } @@ -108,11 +107,11 @@ internal class TestAssertAImpl(private val solverFactory: SolverFactory) : TestA Signature("asserta", 1), PermissionError.Operation.MODIFY, PermissionError.Permission.PRIVATE_PROCEDURE, - "atom" / 1 - ) - ) + "atom" / 1, + ), + ), ), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAssertZ.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAssertZ.kt index 17094380e..4d4255b55 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAssertZ.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAssertZ.kt @@ -5,8 +5,7 @@ package it.unibo.tuprolog.solve */ interface TestAssertZ : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestAssertZ = - TestAssertZImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestAssertZ = TestAssertZImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAssertZImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAssertZImpl.kt index 1f3558625..20d5457c0 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAssertZImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAssertZImpl.kt @@ -7,7 +7,6 @@ import it.unibo.tuprolog.solve.exception.error.PermissionError import it.unibo.tuprolog.solve.exception.error.TypeError internal class TestAssertZImpl(private val solverFactory: SolverFactory) : TestAssertZ { - override fun testAssertZClause() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() @@ -17,7 +16,7 @@ internal class TestAssertZImpl(private val solverFactory: SolverFactory) : TestA assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) } } @@ -36,11 +35,11 @@ internal class TestAssertZImpl(private val solverFactory: SolverFactory) : TestA DummyInstances.executionContext, Signature("assertz", 1), `_`, - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } @@ -60,11 +59,11 @@ internal class TestAssertZImpl(private val solverFactory: SolverFactory) : TestA Signature("assertz", 1), TypeError.Expected.CALLABLE, numOf(4), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } @@ -84,11 +83,11 @@ internal class TestAssertZImpl(private val solverFactory: SolverFactory) : TestA Signature("assertz", 1), DomainError.Expected.CLAUSE, ("foo" `if` 4), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } @@ -108,11 +107,11 @@ internal class TestAssertZImpl(private val solverFactory: SolverFactory) : TestA Signature("assertz", 1), PermissionError.Operation.MODIFY, PermissionError.Permission.PRIVATE_PROCEDURE, - "atom" / 1 - ) - ) + "atom" / 1, + ), + ), ), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtom.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtom.kt index f3988c352..6ec36dad2 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtom.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtom.kt @@ -5,8 +5,7 @@ package it.unibo.tuprolog.solve */ interface TestAtom : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestAtom = - TestAtomImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestAtom = TestAtomImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomChars.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomChars.kt index 91ee54291..30975be08 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomChars.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomChars.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestAtomChars : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestAtomCharsImpl = - TestAtomCharsImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestAtomCharsImpl = TestAtomCharsImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomCharsImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomCharsImpl.kt index 4b389f6ab..25ce11f23 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomCharsImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomCharsImpl.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.exception.error.InstantiationError import it.unibo.tuprolog.solve.exception.error.TypeError class TestAtomCharsImpl(private val solverFactory: SolverFactory) : TestAtomChars { - override fun atomCharsTestFirstIsVar() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() @@ -14,7 +13,7 @@ class TestAtomCharsImpl(private val solverFactory: SolverFactory) : TestAtomChar assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to "test")), - solutions + solutions, ) } } @@ -27,7 +26,7 @@ class TestAtomCharsImpl(private val solverFactory: SolverFactory) : TestAtomChar assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -40,7 +39,7 @@ class TestAtomCharsImpl(private val solverFactory: SolverFactory) : TestAtomChar assertSolutionEquals( kotlin.collections.listOf(query.yes(("T" to "t"))), - solutions + solutions, ) } } @@ -53,7 +52,7 @@ class TestAtomCharsImpl(private val solverFactory: SolverFactory) : TestAtomChar assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -66,7 +65,7 @@ class TestAtomCharsImpl(private val solverFactory: SolverFactory) : TestAtomChar assertSolutionEquals( kotlin.collections.listOf(query.yes("L" to emptyList)), - solutions + solutions, ) } } @@ -79,7 +78,7 @@ class TestAtomCharsImpl(private val solverFactory: SolverFactory) : TestAtomChar assertSolutionEquals( kotlin.collections.listOf(query.yes("C" to "c")), - solutions + solutions, ) } } @@ -97,11 +96,11 @@ class TestAtomCharsImpl(private val solverFactory: SolverFactory) : TestAtomChar DummyInstances.executionContext, Signature("atom_chars", 2), varOf("A"), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } @@ -120,11 +119,11 @@ class TestAtomCharsImpl(private val solverFactory: SolverFactory) : TestAtomChar Signature("atom_chars", 2), TypeError.Expected.LIST, atomOf("iso"), - index = 1 - ) - ) + index = 1, + ), + ), ), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomCodes.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomCodes.kt index 49637483b..16001aac2 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomCodes.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomCodes.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestAtomCodes : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestAtomCodesImpl = - TestAtomCodesImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestAtomCodesImpl = TestAtomCodesImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomCodesImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomCodesImpl.kt index 3490790c6..9127f782d 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomCodesImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomCodesImpl.kt @@ -3,7 +3,6 @@ package it.unibo.tuprolog.solve import it.unibo.tuprolog.dsl.theory.logicProgramming class TestAtomCodesImpl(private val solverFactory: SolverFactory) : TestAtomCodes { - override fun testAtomCodesSecondIsVar1() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() @@ -12,7 +11,7 @@ class TestAtomCodesImpl(private val solverFactory: SolverFactory) : TestAtomCode assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to listOf(97, 98, 99))), - solutions + solutions, ) } } @@ -25,7 +24,7 @@ class TestAtomCodesImpl(private val solverFactory: SolverFactory) : TestAtomCode assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to listOf(116, 101, 115, 116))), - solutions + solutions, ) } } @@ -38,7 +37,7 @@ class TestAtomCodesImpl(private val solverFactory: SolverFactory) : TestAtomCode assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to "abc")), - solutions + solutions, ) } } @@ -51,7 +50,7 @@ class TestAtomCodesImpl(private val solverFactory: SolverFactory) : TestAtomCode assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -64,7 +63,7 @@ class TestAtomCodesImpl(private val solverFactory: SolverFactory) : TestAtomCode assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomConcat.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomConcat.kt index d35f9287c..f89de0c88 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomConcat.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomConcat.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestAtomConcat : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestAtomConcatImpl = - TestAtomConcatImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestAtomConcatImpl = TestAtomConcatImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomConcatImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomConcatImpl.kt index 293977503..87de8cced 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomConcatImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomConcatImpl.kt @@ -3,7 +3,6 @@ package it.unibo.tuprolog.solve import it.unibo.tuprolog.dsl.theory.logicProgramming class TestAtomConcatImpl(private val solverFactory: SolverFactory) : TestAtomConcat { - override fun testAtomConcatThirdIsVar() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() @@ -12,7 +11,7 @@ class TestAtomConcatImpl(private val solverFactory: SolverFactory) : TestAtomCon assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to atomOf("testconcat"))), - solutions + solutions, ) } } @@ -25,7 +24,7 @@ class TestAtomConcatImpl(private val solverFactory: SolverFactory) : TestAtomCon assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -38,7 +37,7 @@ class TestAtomConcatImpl(private val solverFactory: SolverFactory) : TestAtomCon assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to atomOf("Test"))), - solutions + solutions, ) } } @@ -51,7 +50,7 @@ class TestAtomConcatImpl(private val solverFactory: SolverFactory) : TestAtomCon assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to atomOf("test"))), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomImpl.kt index f47a6179e..dec05a26e 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomImpl.kt @@ -3,7 +3,6 @@ package it.unibo.tuprolog.solve import it.unibo.tuprolog.dsl.theory.logicProgramming internal class TestAtomImpl(private val solverFactory: SolverFactory) : TestAtom { - override fun testAtomAtom() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() @@ -13,7 +12,7 @@ internal class TestAtomImpl(private val solverFactory: SolverFactory) : TestAtom assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) } } @@ -27,7 +26,7 @@ internal class TestAtomImpl(private val solverFactory: SolverFactory) : TestAtom assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) } } @@ -41,7 +40,7 @@ internal class TestAtomImpl(private val solverFactory: SolverFactory) : TestAtom assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } @@ -55,7 +54,7 @@ internal class TestAtomImpl(private val solverFactory: SolverFactory) : TestAtom assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } @@ -69,7 +68,7 @@ internal class TestAtomImpl(private val solverFactory: SolverFactory) : TestAtom assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) } } @@ -83,7 +82,7 @@ internal class TestAtomImpl(private val solverFactory: SolverFactory) : TestAtom assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } @@ -97,7 +96,7 @@ internal class TestAtomImpl(private val solverFactory: SolverFactory) : TestAtom assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomLength.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomLength.kt index c4fd280bb..3a0c34efa 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomLength.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomLength.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestAtomLength : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestAtomLengthImpl = - TestAtomLengthImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestAtomLengthImpl = TestAtomLengthImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomLengthImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomLengthImpl.kt index 00f85ca93..86900a3f3 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomLengthImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomLengthImpl.kt @@ -4,7 +4,6 @@ import it.unibo.tuprolog.dsl.theory.logicProgramming import it.unibo.tuprolog.solve.exception.error.TypeError class TestAtomLengthImpl(private val solverFactory: SolverFactory) : TestAtomLength { - override fun testAtomLengthNoVar() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() @@ -13,7 +12,7 @@ class TestAtomLengthImpl(private val solverFactory: SolverFactory) : TestAtomLen assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -26,7 +25,7 @@ class TestAtomLengthImpl(private val solverFactory: SolverFactory) : TestAtomLen assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to 4)), - solutions + solutions, ) } } @@ -45,11 +44,11 @@ class TestAtomLengthImpl(private val solverFactory: SolverFactory) : TestAtomLen Signature("char_code", 2), TypeError.Expected.INTEGER, atomOf("a"), - index = 1 - ) - ) + index = 1, + ), + ), ), - solutions + solutions, ) } } @@ -62,7 +61,7 @@ class TestAtomLengthImpl(private val solverFactory: SolverFactory) : TestAtomLen assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to 10)), - solutions + solutions, ) } } @@ -75,7 +74,7 @@ class TestAtomLengthImpl(private val solverFactory: SolverFactory) : TestAtomLen assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomic.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomic.kt index 43b4c1bde..232d5b271 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomic.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomic.kt @@ -5,8 +5,7 @@ package it.unibo.tuprolog.solve */ interface TestAtomic : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestAtomic = - TestAtomicImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestAtomic = TestAtomicImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomicImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomicImpl.kt index addd27cb1..b4a0b6aa3 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomicImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestAtomicImpl.kt @@ -3,7 +3,6 @@ package it.unibo.tuprolog.solve import it.unibo.tuprolog.dsl.theory.logicProgramming internal class TestAtomicImpl(private val solverFactory: SolverFactory) : TestAtomic { - override fun testAtomicAtom() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() @@ -13,7 +12,7 @@ internal class TestAtomicImpl(private val solverFactory: SolverFactory) : TestAt assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) } } @@ -27,7 +26,7 @@ internal class TestAtomicImpl(private val solverFactory: SolverFactory) : TestAt assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } @@ -41,7 +40,7 @@ internal class TestAtomicImpl(private val solverFactory: SolverFactory) : TestAt assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } @@ -55,7 +54,7 @@ internal class TestAtomicImpl(private val solverFactory: SolverFactory) : TestAt assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) } } @@ -69,7 +68,7 @@ internal class TestAtomicImpl(private val solverFactory: SolverFactory) : TestAt assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) } } @@ -83,7 +82,7 @@ internal class TestAtomicImpl(private val solverFactory: SolverFactory) : TestAt assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestBagOf.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestBagOf.kt index 596753b3e..37f5f23a5 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestBagOf.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestBagOf.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestBagOf : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestBagOfImpl = - TestBagOfImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestBagOfImpl = TestBagOfImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestBagOfImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestBagOfImpl.kt index 632b32413..9ffeabb77 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestBagOfImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestBagOfImpl.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.solve.exception.error.InstantiationError import it.unibo.tuprolog.solve.exception.error.TypeError class TestBagOfImpl(private val solverFactory: SolverFactory) : TestBagOf { - override fun testBagXInDifferentValues() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() @@ -14,7 +13,7 @@ class TestBagOfImpl(private val solverFactory: SolverFactory) : TestBagOf { assertSolutionEquals( ktListOf(query.yes("S" to listOf(1, 2))), - solutions + solutions, ) } } @@ -28,7 +27,7 @@ class TestBagOfImpl(private val solverFactory: SolverFactory) : TestBagOf { assertSolutionEquals( ktListOf(query.yes("X" to listOf(1, 2))), - solutions + solutions, ) } } @@ -42,7 +41,7 @@ class TestBagOfImpl(private val solverFactory: SolverFactory) : TestBagOf { assertSolutionEquals( ktListOf(query.yes("L" to listOf("Y", "Z"))), - solutions + solutions, ) } } @@ -56,7 +55,7 @@ class TestBagOfImpl(private val solverFactory: SolverFactory) : TestBagOf { assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } @@ -70,7 +69,7 @@ class TestBagOfImpl(private val solverFactory: SolverFactory) : TestBagOf { assertSolutionEquals( ktListOf(query.yes("S" to listOf(1))), - solutions + solutions, ) } } @@ -89,11 +88,11 @@ class TestBagOfImpl(private val solverFactory: SolverFactory) : TestBagOf { DummyInstances.executionContext, Signature("bagof", 3), varOf("G"), - index = 1 - ) - ) + index = 1, + ), + ), ), - solutions + solutions, ) } } @@ -113,11 +112,11 @@ class TestBagOfImpl(private val solverFactory: SolverFactory) : TestBagOf { Signature("bagof", 3), TypeError.Expected.CALLABLE, numOf(1), - index = 1 - ) - ) + index = 1, + ), + ), ), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestBigList.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestBigList.kt index d8b63d55a..5e34184c1 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestBigList.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestBigList.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestBigList : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestBigList = - TestBigListImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestBigList = TestBigListImpl(solverFactory) } fun testBigListGeneration() diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestBigListImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestBigListImpl.kt index b5c36a9ee..1be9c59e2 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestBigListImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestBigListImpl.kt @@ -4,22 +4,22 @@ import it.unibo.tuprolog.core.Integer import it.unibo.tuprolog.dsl.theory.logicProgramming internal class TestBigListImpl(private val solverFactory: SolverFactory) : TestBigList { - override val shortDuration: TimeDuration get() = 6000 override fun testBigListGeneration() { logicProgramming { - val theory = theoryOf( - fact { "biglist"(0, listOf(0)) }, - rule { - "biglist"(N, consOf(N, X)).impliedBy( - N greaterThan 0, - M `is` (N - 1), - "biglist"(M, X) - ) - } - ) + val theory = + theoryOf( + fact { "biglist"(0, listOf(0)) }, + rule { + "biglist"(N, consOf(N, X)).impliedBy( + N greaterThan 0, + M `is` (N - 1), + "biglist"(M, X), + ) + }, + ) val solver = solverFactory.solverWithDefaultBuiltins(staticKb = theory) @@ -29,11 +29,11 @@ internal class TestBigListImpl(private val solverFactory: SolverFactory) : TestB assertSolutionEquals( kotlin.collections.listOf( query.yes( - L to listOf((0..BigListOptions.SIZE).reversed().map { Integer.of(it) }) + L to listOf((0..BigListOptions.SIZE).reversed().map { Integer.of(it) }), ), - query.no() + query.no(), ), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCall.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCall.kt index d4833f603..cc13b92c8 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCall.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCall.kt @@ -4,7 +4,7 @@ interface TestCall : SolverTest { companion object { fun prototype( solverFactory: SolverFactory, - errorSignature: Signature = Signature("call", 1) + errorSignature: Signature = Signature("call", 1), ): TestCall = TestCallImpl(solverFactory, errorSignature) } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCallImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCallImpl.kt index 3bfc0cde0..14ccf0173 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCallImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCallImpl.kt @@ -6,7 +6,7 @@ import it.unibo.tuprolog.solve.exception.error.TypeError internal class TestCallImpl( private val solverFactory: SolverFactory, - override val errorSignature: Signature + override val errorSignature: Signature, ) : TestCall { override fun testCallCut() { logicProgramming { @@ -17,7 +17,7 @@ internal class TestCallImpl( assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) } } @@ -31,7 +31,7 @@ internal class TestCallImpl( assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } @@ -45,7 +45,7 @@ internal class TestCallImpl( assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } @@ -59,7 +59,7 @@ internal class TestCallImpl( assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } @@ -77,11 +77,11 @@ internal class TestCallImpl( InstantiationError.forGoal( DummyInstances.executionContext, errorSignature, - varOf("X") - ) - ) + varOf("X"), + ), + ), ), - solutions + solutions, ) } } @@ -100,11 +100,11 @@ internal class TestCallImpl( DummyInstances.executionContext, errorSignature, TypeError.Expected.CALLABLE, - numOf(1) - ) - ) + numOf(1), + ), + ), ), - solutions + solutions, ) } } @@ -122,11 +122,11 @@ internal class TestCallImpl( InstantiationError.forGoal( DummyInstances.executionContext, errorSignature, - varOf("X") - ) - ) + varOf("X"), + ), + ), ), - solutions + solutions, ) } } @@ -145,11 +145,11 @@ internal class TestCallImpl( DummyInstances.executionContext, errorSignature, TypeError.Expected.CALLABLE, - numOf(1) - ) - ) + numOf(1), + ), + ), ), - solutions + solutions, ) } } @@ -168,11 +168,12 @@ internal class TestCallImpl( DummyInstances.executionContext, errorSignature, TypeError.Expected.CALLABLE, - fail and 1 // solver returns 1 - ) - ) + // solver returns 1 + fail and 1, + ), + ), ), - solutions + solutions, ) } } @@ -191,11 +192,12 @@ internal class TestCallImpl( DummyInstances.executionContext, errorSignature, TypeError.Expected.CALLABLE, - write(3) and 1 // solver returns 1 - ) - ) + // solver returns 1 + write(3) and 1, + ), + ), ), - solutions + solutions, ) } } @@ -214,11 +216,12 @@ internal class TestCallImpl( DummyInstances.executionContext, errorSignature, TypeError.Expected.CALLABLE, - (1 or true) // solver returns 1 - ) - ) + // solver returns 1 + (1 or true), + ), + ), ), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCatchAndThrow.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCatchAndThrow.kt index 5dfdd4881..be06bcdc4 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCatchAndThrow.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCatchAndThrow.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestCatchAndThrow : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestCatchAndThrow = - TestCatchAndThrowImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestCatchAndThrow = TestCatchAndThrowImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCatchAndThrowImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCatchAndThrowImpl.kt index 95665250a..2f046e0c5 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCatchAndThrowImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCatchAndThrowImpl.kt @@ -16,11 +16,11 @@ internal class TestCatchAndThrowImpl(private val solverFactory: SolverFactory) : query.halt( SystemError.forUncaughtException( DummyInstances.executionContext, - atomOf("blabla") - ) - ) + atomOf("blabla"), + ), + ), ), - solutions + solutions, ) } } @@ -34,9 +34,9 @@ internal class TestCatchAndThrowImpl(private val solverFactory: SolverFactory) : assertSolutionEquals( kotlin.collections.listOf( - query.no() + query.no(), ), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCharCode.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCharCode.kt index b1e37c6e6..bf3909b81 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCharCode.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCharCode.kt @@ -1,23 +1,21 @@ package it.unibo.tuprolog.solve +/** + * char_code Testing + * + * Contained requests: + * ```prolog + * ?- char_code(a,X). + * ?- char_code(X,97). + * ?- char_code(X,a). + * ?- char_code(g,104). + * ``` + */ interface TestCharCode : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestCharCodeImpl = - TestCharCodeImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestCharCodeImpl = TestCharCodeImpl(solverFactory) } - /** - * char_code Testing - * - * Contained requests: - * ```prolog - * ?- char_code(a,X). - * ?- char_code(X,97). - * ?- char_code(X,a). - * ?- char_code(g,104). - * ``` - */ - /** * Tests the queries * ```prolog @@ -26,7 +24,6 @@ interface TestCharCode : SolverTest { * succeeds. * */ - fun testCharCodeSecondIsVar() /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCharCodeImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCharCodeImpl.kt index d5a0e3a1c..9b936a608 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCharCodeImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCharCodeImpl.kt @@ -4,7 +4,6 @@ import it.unibo.tuprolog.dsl.theory.logicProgramming import it.unibo.tuprolog.solve.exception.error.InstantiationError class TestCharCodeImpl(private val solverFactory: SolverFactory) : TestCharCode { - override fun testCharCodeSecondIsVar() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() @@ -13,7 +12,7 @@ class TestCharCodeImpl(private val solverFactory: SolverFactory) : TestCharCode assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to 97)), - solutions + solutions, ) } } @@ -26,7 +25,7 @@ class TestCharCodeImpl(private val solverFactory: SolverFactory) : TestCharCode assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to "a")), - solutions + solutions, ) } } @@ -44,11 +43,11 @@ class TestCharCodeImpl(private val solverFactory: SolverFactory) : TestCharCode DummyInstances.executionContext, Signature("atom_length", 2), varOf("X"), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } @@ -61,7 +60,7 @@ class TestCharCodeImpl(private val solverFactory: SolverFactory) : TestCharCode assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestClause.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestClause.kt index 872a05ef7..88d93544a 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestClause.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestClause.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestClause : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestClause = - TestClauseImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestClause = TestClauseImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestClauseImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestClauseImpl.kt index 34de8a464..ab9a900a5 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestClauseImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestClauseImpl.kt @@ -15,7 +15,7 @@ internal class TestClauseImpl(private val solverFactory: SolverFactory) : TestCl assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -34,11 +34,11 @@ internal class TestClauseImpl(private val solverFactory: SolverFactory) : TestCl DummyInstances.executionContext, Signature("clause", 2), `_`, - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } @@ -58,11 +58,11 @@ internal class TestClauseImpl(private val solverFactory: SolverFactory) : TestCl Signature("clause", 2), TypeError.Expected.CALLABLE, numOf(4), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } @@ -82,11 +82,11 @@ internal class TestClauseImpl(private val solverFactory: SolverFactory) : TestCl Signature("clause", 2), TypeError.Expected.CALLABLE, numOf(5), - index = 1 - ) - ) + index = 1, + ), + ), ), - solutions + solutions, ) } } @@ -106,31 +106,33 @@ internal class TestClauseImpl(private val solverFactory: SolverFactory) : TestCl Signature("clause", 2), PermissionError.Operation.ACCESS, PermissionError.Permission.PRIVATE_PROCEDURE, - "atom" / 1 - ) - ) + "atom" / 1, + ), + ), ), - solutions + solutions, ) } } override fun testClauseVariables() { logicProgramming { - val solver = solverFactory.solverWithDefaultBuiltins( - staticKb = theoryOf( - rule { "f"(X) impliedBy "g"(X) } + val solver = + solverFactory.solverWithDefaultBuiltins( + staticKb = + theoryOf( + rule { "f"(X) impliedBy "g"(X) }, + ), ) - ) var query = clause("f"(A), B) var solutions = solver.solve(query, mediumDuration).toList() assertSolutionEquals( ktListOf( - query.yes(B to "g"(A)) + query.yes(B to "g"(A)), ), - solutions + solutions, ) query = clause("f"(1), Z) @@ -138,9 +140,9 @@ internal class TestClauseImpl(private val solverFactory: SolverFactory) : TestCl assertSolutionEquals( ktListOf( - query.yes(Z to "g"(1)) + query.yes(Z to "g"(1)), ), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCompound.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCompound.kt index e2c248258..ca14fd7f3 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCompound.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCompound.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestCompound : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestCompound = - TestCompoundImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestCompound = TestCompoundImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCompoundImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCompoundImpl.kt index 777262e1f..b76d96f80 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCompoundImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCompoundImpl.kt @@ -12,7 +12,7 @@ internal class TestCompoundImpl(private val solverFactory: SolverFactory) : Test assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -26,7 +26,7 @@ internal class TestCompoundImpl(private val solverFactory: SolverFactory) : Test assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -40,7 +40,7 @@ internal class TestCompoundImpl(private val solverFactory: SolverFactory) : Test assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -54,7 +54,7 @@ internal class TestCompoundImpl(private val solverFactory: SolverFactory) : Test assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -68,7 +68,7 @@ internal class TestCompoundImpl(private val solverFactory: SolverFactory) : Test assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -82,7 +82,7 @@ internal class TestCompoundImpl(private val solverFactory: SolverFactory) : Test assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -96,7 +96,7 @@ internal class TestCompoundImpl(private val solverFactory: SolverFactory) : Test assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCopyTerm.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCopyTerm.kt index 714e91093..5d924814a 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCopyTerm.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCopyTerm.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestCopyTerm : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestCopyTerm = - TestCopyTermImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestCopyTerm = TestCopyTermImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCopyTermImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCopyTermImpl.kt index 49984f785..3ce0a161e 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCopyTermImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCopyTermImpl.kt @@ -12,7 +12,7 @@ class TestCopyTermImpl(private val solverFactory: SolverFactory) : TestCopyTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -26,7 +26,7 @@ class TestCopyTermImpl(private val solverFactory: SolverFactory) : TestCopyTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -40,7 +40,7 @@ class TestCopyTermImpl(private val solverFactory: SolverFactory) : TestCopyTerm assertSolutionEquals( kotlin.collections.listOf(query.yes(X to "a")), - solutions + solutions, ) } } @@ -54,7 +54,7 @@ class TestCopyTermImpl(private val solverFactory: SolverFactory) : TestCopyTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -68,7 +68,7 @@ class TestCopyTermImpl(private val solverFactory: SolverFactory) : TestCopyTerm assertSolutionEquals( kotlin.collections.listOf(query.yes(A to B)), - solutions + solutions, ) } } @@ -82,7 +82,7 @@ class TestCopyTermImpl(private val solverFactory: SolverFactory) : TestCopyTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -96,7 +96,7 @@ class TestCopyTermImpl(private val solverFactory: SolverFactory) : TestCopyTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -110,7 +110,7 @@ class TestCopyTermImpl(private val solverFactory: SolverFactory) : TestCopyTerm assertSolutionEquals( kotlin.collections.listOf(query.yes(X to "a")), - solutions + solutions, ) } } @@ -124,7 +124,7 @@ class TestCopyTermImpl(private val solverFactory: SolverFactory) : TestCopyTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCustomData.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCustomData.kt index 58c4a9d76..b6788f4a0 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCustomData.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCustomData.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestCustomData : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestCustomData = - TestCustomDataImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestCustomData = TestCustomDataImpl(solverFactory) } fun testApi() diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCustomDataImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCustomDataImpl.kt index 78a05c08f..b5c53cc38 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCustomDataImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCustomDataImpl.kt @@ -9,7 +9,6 @@ import it.unibo.tuprolog.solve.stdlib.primitive.SetEphemeral import it.unibo.tuprolog.solve.stdlib.primitive.SetPersistent class TestCustomDataImpl(private val solverFactory: SolverFactory) : TestCustomData { - override fun testApi() { val solver = solverFactory.solverWithDefaultBuiltins() @@ -31,20 +30,20 @@ class TestCustomDataImpl(private val solverFactory: SolverFactory) : TestCustomD assertSolutionEquals( ktListOf(setQuery.yes()), - solver.solve(setQuery, shortDuration).toList() + solver.solve(setQuery, shortDuration).toList(), ) assertSolutionEquals( ktListOf(getQuery.no()), - solver.solve(getQuery, shortDuration).toList() + solver.solve(getQuery, shortDuration).toList(), ) assertSolutionEquals( ktListOf( query.yes(X to 1), - query.no() + query.no(), ), - solver.solve(query, shortDuration).toList() + solver.solve(query, shortDuration).toList(), ) } } @@ -59,20 +58,20 @@ class TestCustomDataImpl(private val solverFactory: SolverFactory) : TestCustomD assertSolutionEquals( ktListOf(setQuery.yes()), - solver.solve(setQuery, shortDuration).toList() + solver.solve(setQuery, shortDuration).toList(), ) assertSolutionEquals( ktListOf(getQuery.no()), - solver.solve(getQuery, shortDuration).toList() + solver.solve(getQuery, shortDuration).toList(), ) assertSolutionEquals( ktListOf( query.yes(X to 1), - query.yes(X to 1) + query.yes(X to 1), ), - solver.solve(query, shortDuration).toList() + solver.solve(query, shortDuration).toList(), ) } } @@ -87,20 +86,20 @@ class TestCustomDataImpl(private val solverFactory: SolverFactory) : TestCustomD assertSolutionEquals( ktListOf(setQuery.yes()), - solver.solve(setQuery, shortDuration).toList() + solver.solve(setQuery, shortDuration).toList(), ) assertSolutionEquals( ktListOf(getQuery.yes(X to 1)), - solver.solve(getQuery, shortDuration).toList() + solver.solve(getQuery, shortDuration).toList(), ) assertSolutionEquals( ktListOf( query.yes(X to 1), - query.yes(X to 1) + query.yes(X to 1), ), - solver.solve(query, shortDuration).toList() + solver.solve(query, shortDuration).toList(), ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCut.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCut.kt index 4b55b61c1..1e32a45ae 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCut.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCut.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestCut : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestCut = - TestCutImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestCut = TestCutImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCutImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCutImpl.kt index 1d4bd32ca..fd56109d6 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCutImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestCutImpl.kt @@ -12,7 +12,7 @@ internal class TestCutImpl(private val solverFactory: SolverFactory) : TestCut { assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -26,7 +26,7 @@ internal class TestCutImpl(private val solverFactory: SolverFactory) : TestCut { assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -40,7 +40,7 @@ internal class TestCutImpl(private val solverFactory: SolverFactory) : TestCut { assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestDirectives.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestDirectives.kt index dff854d1d..fb170bbcb 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestDirectives.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestDirectives.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestDirectives : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestDirectives = - TestDirectivesImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestDirectives = TestDirectivesImpl(solverFactory) } fun testDynamic1() diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestDirectivesImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestDirectivesImpl.kt index f1c6b9118..5cfb0b3d9 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestDirectivesImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestDirectivesImpl.kt @@ -21,16 +21,16 @@ import kotlin.test.assertTrue @Suppress("DEPRECATION") class TestDirectivesImpl(private val solverFactory: SolverFactory) : TestDirectives { - override fun testDynamic1() { logicProgramming { - val initialStaticKb = theoryOf( - facts("f", 1..3), - staticDirective("g", 1), - facts("g", 4..6), - dynamicDirective("h", 1), - facts("h", 7..9) - ) + val initialStaticKb = + theoryOf( + facts("f", 1..3), + staticDirective("g", 1), + facts("g", 4..6), + dynamicDirective("h", 1), + facts("h", 7..9), + ) val expectedStatic = theoryOf(initialStaticKb.take(8)) val expectedDynamic = mutableTheoryOf(initialStaticKb.drop(8)) @@ -54,21 +54,23 @@ class TestDirectivesImpl(private val solverFactory: SolverFactory) : TestDirecti override fun testStatic1() { logicProgramming { - val initialDynamicKb = theoryOf( - facts("f", 1..3), - staticDirective("g", 1), - facts("g", 4..6), - dynamicDirective("h", 1), - facts("h", 7..9) - ) + val initialDynamicKb = + theoryOf( + facts("f", 1..3), + staticDirective("g", 1), + facts("g", 4..6), + dynamicDirective("h", 1), + facts("h", 7..9), + ) val expectedStatic = theoryOf(initialDynamicKb.drop(4).take(3)) - val expectedDynamic = theoryOf( - facts("f", 1..3), - staticDirective("g", 1), - dynamicDirective("h", 1), - facts("h", 7..9) - ).toMutableTheory() + val expectedDynamic = + theoryOf( + facts("f", 1..3), + staticDirective("g", 1), + dynamicDirective("h", 1), + facts("h", 7..9), + ).toMutableTheory() val solver = solverFactory.solverOf(staticKb = emptyTheory(), dynamicKb = initialDynamicKb) @@ -87,15 +89,16 @@ class TestDirectivesImpl(private val solverFactory: SolverFactory) : TestDirecti } } - private fun theoryWithInit(initGoal: String): Theory = logicProgramming { - theoryOf( - directive { initGoal(write("a")) }, - fact { "f"(1) }, - directive { initGoal(tupleOf("f"(X), write("f"(X)))) }, - fact { "f"(2) }, - directive { initGoal(write("b")) } - ) - } + private fun theoryWithInit(initGoal: String): Theory = + logicProgramming { + theoryOf( + directive { initGoal(write("a")) }, + fact { "f"(1) }, + directive { initGoal(tupleOf("f"(X), write("f"(X)))) }, + fact { "f"(2) }, + directive { initGoal(write("b")) }, + ) + } private fun testInit(initGoal: String) = logicProgramming { @@ -105,18 +108,19 @@ class TestDirectivesImpl(private val solverFactory: SolverFactory) : TestDirecti assertEquals( ktListOf("a", "f(1)", "f(2)", "b"), - writeEvents + writeEvents, ) val query = "f"(X) - val expectedSolutions = ktListOf( - query.yes(X to 1), - query.yes(X to 2) - ) + val expectedSolutions = + ktListOf( + query.yes(X to 1), + query.yes(X to 2), + ) assertEquals( expectedSolutions, - solver.solve(query).toList() + solver.solve(query).toList(), ) } } @@ -128,13 +132,14 @@ class TestDirectivesImpl(private val solverFactory: SolverFactory) : TestDirecti override fun testSetFlag2() { logicProgramming { for (solverOf in solverInitializers(solverFactory)) { - val solver = solverOf( - theoryOf( - directive { set_flag("a", 1) }, - directive { set_flag("b", 2) }, - directive { set_flag("c", 3) } + val solver = + solverOf( + theoryOf( + directive { set_flag("a", 1) }, + directive { set_flag("b", 2) }, + directive { set_flag("c", 3) }, + ), ) - ) assertTrue { solver.flags.size >= 3 } assertEquals(Integer.of(1), solver.flags["a"]) @@ -147,13 +152,14 @@ class TestDirectivesImpl(private val solverFactory: SolverFactory) : TestDirecti override fun testSetPrologFlag2() { logicProgramming { for (solverOf in solverInitializers(solverFactory)) { - val solver = solverOf( - theoryOf( - directive { set_prolog_flag("a", 1) }, - directive { set_prolog_flag("b", 2) }, - directive { set_prolog_flag("c", 3) } + val solver = + solverOf( + theoryOf( + directive { set_prolog_flag("a", 1) }, + directive { set_prolog_flag("b", 2) }, + directive { set_prolog_flag("c", 3) }, + ), ) - ) assertTrue { solver.flags.size >= 3 } assertEquals(Integer.of(1), solver.flags["a"]) @@ -166,19 +172,21 @@ class TestDirectivesImpl(private val solverFactory: SolverFactory) : TestDirecti override fun testOp3() { logicProgramming { for (solverOf in solverInitializers(solverFactory)) { - val solver = solverOf( - theoryOf( - directive { op(2, XFX, "++") }, - directive { op(3, XFY, "+++") }, - directive { op(4, YFX, "++++") } + val solver = + solverOf( + theoryOf( + directive { op(2, XFX, "++") }, + directive { op(3, XFY, "+++") }, + directive { op(4, YFX, "++++") }, + ), ) - ) - val expectedOperators = OperatorSet( - Operator("++++", YFX, 4), - Operator("+++", XFY, 3), - Operator("++", XFX, 2) - ) + val expectedOperators = + OperatorSet( + Operator("++++", YFX, 4), + Operator("+++", XFY, 3), + Operator("++", XFX, 2), + ) for (operator in expectedOperators) { assertTrue { operator in solver.operators } @@ -190,21 +198,22 @@ class TestDirectivesImpl(private val solverFactory: SolverFactory) : TestDirecti override fun testWrongDirectives() { logicProgramming { for ((solverOf, events) in solverInitializersWithEventsList(solverFactory)) { - val theory = theoryOf( - directive { op("a", XFX, "++") }, - directive { op(3, "b", "+++") }, - directive { "set_flag"("a", "x") }, - directive { "dinamic"("f" / 1) }, - fact { "f"("a") }, - directive { "statyc"("g" / 1) }, - fact { "g"("b") }, - directive { "init"(write("something")) } - ) + val theory = + theoryOf( + directive { op("a", XFX, "++") }, + directive { op(3, "b", "+++") }, + directive { "set_flag"("a", "x") }, + directive { "dinamic"("f" / 1) }, + fact { "f"("a") }, + directive { "statyc"("g" / 1) }, + fact { "g"("b") }, + directive { "init"(write("something")) }, + ) val solver = solverOf(theory) assertEquals( ktListOf(), - events + events, ) sequenceOf(solver.staticKb, solver.dynamicKb) @@ -214,9 +223,10 @@ class TestDirectivesImpl(private val solverFactory: SolverFactory) : TestDirecti } } - private fun theoryWithFailingInit(initGoal: String): Theory = logicProgramming { - theoryOf(directive { initGoal(fail) }) - } + private fun theoryWithFailingInit(initGoal: String): Theory = + logicProgramming { + theoryOf(directive { initGoal(fail) }) + } private fun testFailingInit(initGoal: String) = logicProgramming { @@ -242,9 +252,10 @@ class TestDirectivesImpl(private val solverFactory: SolverFactory) : TestDirecti testFailingInit("solve") } - private fun theoryWithExceptionalInit(initGoal: String): Theory = logicProgramming { - theoryOf(directive { initGoal(X `is` (Y + 1)) }) - } + private fun theoryWithExceptionalInit(initGoal: String): Theory = + logicProgramming { + theoryOf(directive { initGoal(X `is` (Y + 1)) }) + } private fun testExceptionalInit(initGoal: String) = logicProgramming { diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFail.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFail.kt index 822746c5c..c6e3bf61b 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFail.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFail.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestFail : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestFail = - TestFailImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestFail = TestFailImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFailImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFailImpl.kt index d8267f3a9..6ddb322c3 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFailImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFailImpl.kt @@ -15,16 +15,17 @@ internal class TestFailImpl(private val solverFactory: SolverFactory) : TestFail assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } override fun testUndefPred() { // streams solver: `No(query=undef_pred)` instead of undef_pred/0 logicProgramming { - val solver = solverFactory.solverWithDefaultBuiltins( - flags = FlagStore.of(Unknown to Unknown.ERROR) - ) + val solver = + solverFactory.solverWithDefaultBuiltins( + flags = FlagStore.of(Unknown to Unknown.ERROR), + ) val query = atomOf("undef_pred") val solutions = solver.solve(query, mediumDuration).toList() @@ -34,11 +35,11 @@ internal class TestFailImpl(private val solverFactory: SolverFactory) : TestFail query.halt( ExistenceError.forProcedure( DummyInstances.executionContext, - Signature("undef_pred", 0) - ) - ) + Signature("undef_pred", 0), + ), + ), ), - solutions + solutions, ) } } @@ -52,7 +53,7 @@ internal class TestFailImpl(private val solverFactory: SolverFactory) : TestFail assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -66,7 +67,7 @@ internal class TestFailImpl(private val solverFactory: SolverFactory) : TestFail assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFindAll.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFindAll.kt index c4f0fda00..c8d2be72e 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFindAll.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFindAll.kt @@ -4,11 +4,10 @@ package it.unibo.tuprolog.solve * Tests of findall */ interface TestFindAll : SolverTest { - companion object { fun prototype( solverFactory: SolverFactory, - errorSignature: Signature = Signature("call", 1) + errorSignature: Signature = Signature("call", 1), ): TestFindAll = TestFindAllImpl(solverFactory, errorSignature) } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFindAllImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFindAllImpl.kt index 13b926fa4..b817edbf8 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFindAllImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFindAllImpl.kt @@ -6,9 +6,8 @@ import it.unibo.tuprolog.solve.exception.error.TypeError internal class TestFindAllImpl( private val solverFactory: SolverFactory, - override val errorSignature: Signature + override val errorSignature: Signature, ) : TestFindAll { - override fun testFindXInDiffValues() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() @@ -18,7 +17,7 @@ internal class TestFindAllImpl( assertSolutionEquals( ktListOf(query.yes("S" to listOf(1, 2))), - solutions + solutions, ) } } @@ -32,7 +31,7 @@ internal class TestFindAllImpl( assertSolutionEquals( ktListOf(query.yes("S" to listOf(1 + "Y"))), - solutions + solutions, ) } } @@ -46,7 +45,7 @@ internal class TestFindAllImpl( assertSolutionEquals( ktListOf(query.yes("L" to emptyList)), - solutions + solutions, ) } } @@ -60,7 +59,7 @@ internal class TestFindAllImpl( assertSolutionEquals( ktListOf(query.yes("S" to listOf(1, 1))), - solutions + solutions, ) } } @@ -74,7 +73,7 @@ internal class TestFindAllImpl( assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } @@ -88,7 +87,7 @@ internal class TestFindAllImpl( assertSolutionEquals( ktListOf(query.yes("X" to 1, "Y" to 2)), - solutions + solutions, ) } } @@ -107,11 +106,11 @@ internal class TestFindAllImpl( DummyInstances.executionContext, Signature("findall", 3), varOf("Goal"), - index = 1 - ) - ) + index = 1, + ), + ), ), - solutions + solutions, ) } } @@ -131,11 +130,11 @@ internal class TestFindAllImpl( Signature("findall", 3), TypeError.Expected.CALLABLE, numOf(4), - index = 1 - ) - ) + index = 1, + ), + ), ), - solutions + solutions, ) } } @@ -154,11 +153,11 @@ internal class TestFindAllImpl( DummyInstances.executionContext, errorSignature, TypeError.Expected.CALLABLE, - numOf(1) - ) - ) + numOf(1), + ), + ), ), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFlags.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFlags.kt index 38838d79b..62286c3dd 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFlags.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFlags.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestFlags : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestFlags = - TestFlagsImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestFlags = TestFlagsImpl(solverFactory) } fun defaultLastCallOptimizationIsOn() diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFlagsImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFlagsImpl.kt index 79d3c192e..6e85049af 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFlagsImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFlagsImpl.kt @@ -27,7 +27,7 @@ class TestFlagsImpl(private val solverFactory: SolverFactory) : TestFlags { assertSolutionEquals( ktListOf(query.yes()), - solver.solve(query, shortDuration).toList() + solver.solve(query, shortDuration).toList(), ) } } @@ -42,7 +42,7 @@ class TestFlagsImpl(private val solverFactory: SolverFactory) : TestFlags { assertSolutionEquals( ktListOf(query.yes()), - solver.solve(query, shortDuration).toList() + solver.solve(query, shortDuration).toList(), ) } } @@ -56,7 +56,7 @@ class TestFlagsImpl(private val solverFactory: SolverFactory) : TestFlags { assertSolutionEquals( ktListOf(query.yes(V to value)), - solver.solve(query, shortDuration).toList() + solver.solve(query, shortDuration).toList(), ) } } @@ -83,10 +83,10 @@ class TestFlagsImpl(private val solverFactory: SolverFactory) : TestFlags { CurrentFlag.signature, TypeError.Expected.ATOM, term, - 0 - ) + 0, + ), ), - solver.solveOnce(query, shortDuration) + solver.solveOnce(query, shortDuration), ) query = set_flag(term, "value") @@ -97,10 +97,10 @@ class TestFlagsImpl(private val solverFactory: SolverFactory) : TestFlags { SetFlag.signature, TypeError.Expected.ATOM, term, - 0 - ) + 0, + ), ), - solver.solveOnce(query, shortDuration) + solver.solveOnce(query, shortDuration), ) } } @@ -117,7 +117,7 @@ class TestFlagsImpl(private val solverFactory: SolverFactory) : TestFlags { assertSolutionEquals( query.no(), - solver.solveOnce(query, shortDuration) + solver.solveOnce(query, shortDuration), ) } } @@ -134,7 +134,7 @@ class TestFlagsImpl(private val solverFactory: SolverFactory) : TestFlags { assertSolutionEquals( query.yes(X to value), - solver.solveOnce(query, shortDuration) + solver.solveOnce(query, shortDuration), ) assertEquals(value.toTerm(), solver.flags[flag]) @@ -151,10 +151,11 @@ class TestFlagsImpl(private val solverFactory: SolverFactory) : TestFlags { val query = current_flag(F, X) - val selectedFlags = solver.solve(query, shortDuration) - .filterIsInstance() - .map { it.substitution[F]!! to it.substitution[X]!! } - .toMap() + val selectedFlags = + solver.solve(query, shortDuration) + .filterIsInstance() + .map { it.substitution[F]!! to it.substitution[X]!! } + .toMap() assertEquals(defaultFlags, selectedFlags) } @@ -173,11 +174,11 @@ class TestFlagsImpl(private val solverFactory: SolverFactory) : TestFlags { DummyInstances.executionContext, SetFlag.signature, F, - index = 0 - ) - ) + index = 0, + ), + ), ), - solver.solveList(query, shortDuration) + solver.solveList(query, shortDuration), ) } } @@ -198,11 +199,11 @@ class TestFlagsImpl(private val solverFactory: SolverFactory) : TestFlags { SetFlag.signature, LastCallOptimization.admissibleValues.asIterable(), truthOf(true), - index = 1 - ) - ) + index = 1, + ), + ), ), - solver.solveList(query, shortDuration) + solver.solveList(query, shortDuration), ) } } @@ -221,11 +222,11 @@ class TestFlagsImpl(private val solverFactory: SolverFactory) : TestFlags { SetFlag.signature, PermissionError.Operation.MODIFY, PermissionError.Permission.FLAG, - atomOf(MaxArity.name) - ) - ) + atomOf(MaxArity.name), + ), + ), ), - solver.solveList(query, shortDuration) + solver.solveList(query, shortDuration), ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFloat.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFloat.kt index 2f2d6508f..64765e35d 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFloat.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFloat.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestFloat : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestFloat = - TestFloatImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestFloat = TestFloatImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFloatImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFloatImpl.kt index d1e2ae630..6e54539e8 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFloatImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFloatImpl.kt @@ -12,7 +12,7 @@ internal class TestFloatImpl(private val solverFactory: SolverFactory) : TestFlo assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -26,7 +26,7 @@ internal class TestFloatImpl(private val solverFactory: SolverFactory) : TestFlo assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -40,7 +40,7 @@ internal class TestFloatImpl(private val solverFactory: SolverFactory) : TestFlo assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -54,7 +54,7 @@ internal class TestFloatImpl(private val solverFactory: SolverFactory) : TestFlo assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -68,7 +68,7 @@ internal class TestFloatImpl(private val solverFactory: SolverFactory) : TestFlo assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFunctor.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFunctor.kt index 9765af4d3..5cef59843 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFunctor.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFunctor.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestFunctor : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestFunctor = - TestFunctorImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestFunctor = TestFunctorImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFunctorImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFunctorImpl.kt index fc3b5b1cd..e45092d4d 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFunctorImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestFunctorImpl.kt @@ -16,7 +16,7 @@ internal class TestFunctorImpl(private val solverFactory: SolverFactory) : TestF assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -30,7 +30,7 @@ internal class TestFunctorImpl(private val solverFactory: SolverFactory) : TestF assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to "foo", "Y" to 3)), - solutions + solutions, ) } } @@ -44,7 +44,7 @@ internal class TestFunctorImpl(private val solverFactory: SolverFactory) : TestF assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to "foo")), - solutions + solutions, ) } } @@ -58,7 +58,7 @@ internal class TestFunctorImpl(private val solverFactory: SolverFactory) : TestF assertSolutionEquals( kotlin.collections.listOf(query.yes("A" to "mats", "B" to 2)), - solutions + solutions, ) } } @@ -72,7 +72,7 @@ internal class TestFunctorImpl(private val solverFactory: SolverFactory) : TestF assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -86,7 +86,7 @@ internal class TestFunctorImpl(private val solverFactory: SolverFactory) : TestF assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -100,7 +100,7 @@ internal class TestFunctorImpl(private val solverFactory: SolverFactory) : TestF assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to 1, "Y" to 0)), - solutions + solutions, ) } } @@ -114,7 +114,7 @@ internal class TestFunctorImpl(private val solverFactory: SolverFactory) : TestF assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to 1.1)), - solutions + solutions, ) } } @@ -128,7 +128,7 @@ internal class TestFunctorImpl(private val solverFactory: SolverFactory) : TestF assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -142,7 +142,7 @@ internal class TestFunctorImpl(private val solverFactory: SolverFactory) : TestF assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -161,11 +161,11 @@ internal class TestFunctorImpl(private val solverFactory: SolverFactory) : TestF DummyInstances.executionContext, Signature("functor", 3), varOf("Y"), - 1 - ) - ) + 1, + ), + ), ), - solutions + solutions, ) } } @@ -184,11 +184,11 @@ internal class TestFunctorImpl(private val solverFactory: SolverFactory) : TestF DummyInstances.executionContext, Signature("functor", 3), varOf("N"), - index = 2 - ) - ) + index = 2, + ), + ), ), - solutions + solutions, ) } } @@ -208,11 +208,11 @@ internal class TestFunctorImpl(private val solverFactory: SolverFactory) : TestF Signature("functor", 3), TypeError.Expected.INTEGER, atomOf("a"), - index = 2 - ) - ) + index = 2, + ), + ), ), - solutions + solutions, ) } } @@ -232,11 +232,11 @@ internal class TestFunctorImpl(private val solverFactory: SolverFactory) : TestF Signature("functor", 3), TypeError.Expected.ATOM, numOf(1.5), - index = 1 - ) - ) + index = 1, + ), + ), ), - solutions + solutions, ) } } @@ -256,11 +256,11 @@ internal class TestFunctorImpl(private val solverFactory: SolverFactory) : TestF Signature("functor", 3), TypeError.Expected.ATOMIC, "foo"("a"), - index = 1 - ) - ) + index = 1, + ), + ), ), - solutions + solutions, ) } } @@ -269,8 +269,9 @@ internal class TestFunctorImpl(private val solverFactory: SolverFactory) : TestF logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() - val query = current_flag("max_arity", A) and ( - (X `is` (A + 1)) and functor(T, "foo", X) + val query = + current_flag("max_arity", A) and ( + (X `is` (A + 1)) and functor(T, "foo", X) ) val solutions = solver.solve(query, mediumDuration).toList() @@ -280,11 +281,11 @@ internal class TestFunctorImpl(private val solverFactory: SolverFactory) : TestF RepresentationError.of( DummyInstances.executionContext, Signature("functor", 3), - RepresentationError.Limit.MAX_ARITY - ) - ) + RepresentationError.Limit.MAX_ARITY, + ), + ), ), - solutions + solutions, ) } } @@ -304,11 +305,11 @@ internal class TestFunctorImpl(private val solverFactory: SolverFactory) : TestF Signature("functor", 3), DomainError.Expected.NOT_LESS_THAN_ZERO, intOf(-1), - index = 2 - ) - ) + index = 2, + ), + ), ), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIfThen.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIfThen.kt index ccc3a8b19..c2b3585e8 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIfThen.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIfThen.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestIfThen : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestIfThen = - TestIfThenImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestIfThen = TestIfThenImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIfThenElse.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIfThenElse.kt index fca5f3d38..d1e6abb49 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIfThenElse.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIfThenElse.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestIfThenElse : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestIfThenElse = - TestIfThenElseImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestIfThenElse = TestIfThenElseImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIfThenElseImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIfThenElseImpl.kt index 044860743..3e4777f8d 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIfThenElseImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIfThenElseImpl.kt @@ -12,7 +12,7 @@ internal class TestIfThenElseImpl(private val solverFactory: SolverFactory) : Te assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -26,7 +26,7 @@ internal class TestIfThenElseImpl(private val solverFactory: SolverFactory) : Te assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -40,7 +40,7 @@ internal class TestIfThenElseImpl(private val solverFactory: SolverFactory) : Te assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -54,7 +54,7 @@ internal class TestIfThenElseImpl(private val solverFactory: SolverFactory) : Te assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -68,7 +68,7 @@ internal class TestIfThenElseImpl(private val solverFactory: SolverFactory) : Te assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to 1)), - solutions + solutions, ) } } @@ -82,7 +82,7 @@ internal class TestIfThenElseImpl(private val solverFactory: SolverFactory) : Te assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to 2)), - solutions + solutions, ) } } @@ -98,10 +98,10 @@ internal class TestIfThenElseImpl(private val solverFactory: SolverFactory) : Te with(query) { kotlin.collections.listOf( yes("X" to 1), - yes("X" to 2) + yes("X" to 2), ) }, - solutions + solutions, ) } } @@ -115,7 +115,7 @@ internal class TestIfThenElseImpl(private val solverFactory: SolverFactory) : Te assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to 1)), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIfThenImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIfThenImpl.kt index dbf084e82..f4f90bf88 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIfThenImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIfThenImpl.kt @@ -12,7 +12,7 @@ internal class TestIfThenImpl(private val solverFactory: SolverFactory) : TestIf assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -26,7 +26,7 @@ internal class TestIfThenImpl(private val solverFactory: SolverFactory) : TestIf assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -40,7 +40,7 @@ internal class TestIfThenImpl(private val solverFactory: SolverFactory) : TestIf assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -54,7 +54,7 @@ internal class TestIfThenImpl(private val solverFactory: SolverFactory) : TestIf assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to 1)), - solutions + solutions, ) } } @@ -68,7 +68,7 @@ internal class TestIfThenImpl(private val solverFactory: SolverFactory) : TestIf assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to 1)), - solutions + solutions, ) } } @@ -84,10 +84,10 @@ internal class TestIfThenImpl(private val solverFactory: SolverFactory) : TestIf with(query) { kotlin.collections.listOf( yes("X" to 1), - yes("X" to 2) + yes("X" to 2), ) }, - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestInteger.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestInteger.kt index 8c16f4c90..0c67d6864 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestInteger.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestInteger.kt @@ -5,8 +5,7 @@ package it.unibo.tuprolog.solve */ interface TestInteger : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestInteger = - TestIntegerImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestInteger = TestIntegerImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIntegerImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIntegerImpl.kt index 0f2aa8fd7..f2a3f3011 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIntegerImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIntegerImpl.kt @@ -12,7 +12,7 @@ internal class TestIntegerImpl(private val solverFactory: SolverFactory) : TestI assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) } } @@ -26,7 +26,7 @@ internal class TestIntegerImpl(private val solverFactory: SolverFactory) : TestI assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) } } @@ -40,7 +40,7 @@ internal class TestIntegerImpl(private val solverFactory: SolverFactory) : TestI assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } @@ -54,7 +54,7 @@ internal class TestIntegerImpl(private val solverFactory: SolverFactory) : TestI assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } @@ -68,7 +68,7 @@ internal class TestIntegerImpl(private val solverFactory: SolverFactory) : TestI assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIs.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIs.kt index 0e4e5ef38..44e675b52 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIs.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIs.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestIs : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestIs = - TestIsImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestIs = TestIsImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIsImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIsImpl.kt index 5e02a4b7a..c3ff868f4 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIsImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestIsImpl.kt @@ -14,7 +14,7 @@ internal class TestIsImpl(private val solverFactory: SolverFactory) : TestIs { assertSolutionEquals( kotlin.collections.listOf(query.yes("Result" to realOf(14.0))), - solutions + solutions, ) } } @@ -28,7 +28,7 @@ internal class TestIsImpl(private val solverFactory: SolverFactory) : TestIs { assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to intOf(1) + intOf(2), "Y" to intOf(9))), - solutions + solutions, ) } } @@ -42,7 +42,7 @@ internal class TestIsImpl(private val solverFactory: SolverFactory) : TestIs { assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -61,11 +61,11 @@ internal class TestIsImpl(private val solverFactory: SolverFactory) : TestIs { DummyInstances.executionContext, Signature("is", 2), varOf("N"), - index = 1 - ) - ) + index = 1, + ), + ), ), - solutions + solutions, ) } } @@ -85,11 +85,11 @@ internal class TestIsImpl(private val solverFactory: SolverFactory) : TestIs { Signature("is", 2), TypeError.Expected.EVALUABLE, atomOf("foo"), - index = 1 - ) - ) + index = 1, + ), + ), ), - solutions + solutions, ) } } @@ -103,7 +103,7 @@ internal class TestIsImpl(private val solverFactory: SolverFactory) : TestIs { assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to realOf(3.0))), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNonVar.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNonVar.kt index a37d43f6f..c27a51d7e 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNonVar.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNonVar.kt @@ -4,10 +4,8 @@ package it.unibo.tuprolog.solve * Tests of nonvar */ interface TestNonVar : SolverTest { - companion object { - fun prototype(solverFactory: SolverFactory): TestNonVar = - TestNonVarImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestNonVar = TestNonVarImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNonVarImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNonVarImpl.kt index 9919b0166..df7461a36 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNonVarImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNonVarImpl.kt @@ -3,7 +3,6 @@ package it.unibo.tuprolog.solve import it.unibo.tuprolog.dsl.theory.logicProgramming internal class TestNonVarImpl(private val solverFactory: SolverFactory) : TestNonVar { - override fun testNonVarNumber() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() @@ -13,7 +12,7 @@ internal class TestNonVarImpl(private val solverFactory: SolverFactory) : TestNo assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) } } @@ -27,7 +26,7 @@ internal class TestNonVarImpl(private val solverFactory: SolverFactory) : TestNo assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) } } @@ -41,7 +40,7 @@ internal class TestNonVarImpl(private val solverFactory: SolverFactory) : TestNo assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } @@ -55,7 +54,7 @@ internal class TestNonVarImpl(private val solverFactory: SolverFactory) : TestNo assertSolutionEquals( ktListOf(query.yes("Foo" to "foo")), - solutions + solutions, ) } } @@ -69,7 +68,7 @@ internal class TestNonVarImpl(private val solverFactory: SolverFactory) : TestNo assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } @@ -83,7 +82,7 @@ internal class TestNonVarImpl(private val solverFactory: SolverFactory) : TestNo assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNotProvable.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNotProvable.kt index e3dfc4b69..cfba2f38a 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNotProvable.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNotProvable.kt @@ -4,7 +4,7 @@ interface TestNotProvable : SolverTest { companion object { fun prototype( solverFactory: SolverFactory, - errorSignature: Signature = Signature("not", 1) + errorSignature: Signature = Signature("not", 1), ): TestNotProvable = TestNotProvableImpl(solverFactory, errorSignature) } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNotProvableImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNotProvableImpl.kt index 06951e74d..1a57e858d 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNotProvableImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNotProvableImpl.kt @@ -6,7 +6,7 @@ import it.unibo.tuprolog.solve.exception.error.TypeError class TestNotProvableImpl( private val solverFactory: SolverFactory, - override val errorSignature: Signature + override val errorSignature: Signature, ) : TestNotProvable { override fun testNPTrue() { logicProgramming { @@ -17,9 +17,9 @@ class TestNotProvableImpl( assertSolutionEquals( kotlin.collections.listOf( - query.no() + query.no(), ), - solutions + solutions, ) } } @@ -33,9 +33,9 @@ class TestNotProvableImpl( assertSolutionEquals( kotlin.collections.listOf( - query.no() + query.no(), ), - solutions + solutions, ) } } @@ -49,9 +49,9 @@ class TestNotProvableImpl( assertSolutionEquals( kotlin.collections.listOf( - query.yes() + query.yes(), ), - solutions + solutions, ) } } @@ -67,10 +67,10 @@ class TestNotProvableImpl( with(query) { kotlin.collections.listOf( yes("X" to 1), - yes("X" to 2) + yes("X" to 2), ) }, - solutions + solutions, ) } } @@ -84,9 +84,9 @@ class TestNotProvableImpl( assertSolutionEquals( kotlin.collections.listOf( - query.yes() + query.yes(), ), - solutions + solutions, ) } } @@ -105,12 +105,11 @@ class TestNotProvableImpl( DummyInstances.executionContext, errorSignature, TypeError.Expected.CALLABLE, - numOf(3) - - ) - ) + numOf(3), + ), + ), ), - solutions + solutions, ) } } @@ -128,11 +127,11 @@ class TestNotProvableImpl( InstantiationError.forGoal( DummyInstances.executionContext, errorSignature, - varOf("X") - ) - ) + varOf("X"), + ), + ), ), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNotUnify.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNotUnify.kt index 36f7f329b..6e4e8d6b7 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNotUnify.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNotUnify.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestNotUnify : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestNotUnify = - TestNotUnifyImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestNotUnify = TestNotUnifyImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNotUnifyImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNotUnifyImpl.kt index d7d0f7cb1..adca79e0a 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNotUnifyImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNotUnifyImpl.kt @@ -3,7 +3,6 @@ package it.unibo.tuprolog.solve import it.unibo.tuprolog.dsl.theory.logicProgramming internal class TestNotUnifyImpl(private val solverFactory: SolverFactory) : TestNotUnify { - override fun testNumberNotUnify() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() @@ -13,7 +12,7 @@ internal class TestNotUnifyImpl(private val solverFactory: SolverFactory) : Test assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -27,7 +26,7 @@ internal class TestNotUnifyImpl(private val solverFactory: SolverFactory) : Test assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -41,7 +40,7 @@ internal class TestNotUnifyImpl(private val solverFactory: SolverFactory) : Test assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -55,7 +54,7 @@ internal class TestNotUnifyImpl(private val solverFactory: SolverFactory) : Test assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } @@ -69,7 +68,7 @@ internal class TestNotUnifyImpl(private val solverFactory: SolverFactory) : Test assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } @@ -83,7 +82,7 @@ internal class TestNotUnifyImpl(private val solverFactory: SolverFactory) : Test assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -97,7 +96,7 @@ internal class TestNotUnifyImpl(private val solverFactory: SolverFactory) : Test assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -111,7 +110,7 @@ internal class TestNotUnifyImpl(private val solverFactory: SolverFactory) : Test assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -125,7 +124,7 @@ internal class TestNotUnifyImpl(private val solverFactory: SolverFactory) : Test assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -139,7 +138,7 @@ internal class TestNotUnifyImpl(private val solverFactory: SolverFactory) : Test assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumber.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumber.kt index 5d11f9a59..39458089b 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumber.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumber.kt @@ -5,8 +5,7 @@ package it.unibo.tuprolog.solve */ interface TestNumber : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestNumber = - TestNumberImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestNumber = TestNumberImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumberChars.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumberChars.kt index 45428d6b3..0a238990e 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumberChars.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumberChars.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestNumberChars : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestNumberCharsImpl = - TestNumberCharsImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestNumberCharsImpl = TestNumberCharsImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumberCharsImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumberCharsImpl.kt index f70119d4c..5efe7f23a 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumberCharsImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumberCharsImpl.kt @@ -13,7 +13,7 @@ class TestNumberCharsImpl(private val solverFactory: SolverFactory) : TestNumber assertSolutionEquals( kotlin.collections.listOf(query.yes("L" to listOf("3", "3"))), - solutions + solutions, ) } } @@ -27,7 +27,7 @@ class TestNumberCharsImpl(private val solverFactory: SolverFactory) : TestNumber assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -41,7 +41,7 @@ class TestNumberCharsImpl(private val solverFactory: SolverFactory) : TestNumber assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to 33)), - solutions + solutions, ) } } @@ -55,7 +55,7 @@ class TestNumberCharsImpl(private val solverFactory: SolverFactory) : TestNumber assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to intOf(-25))), - solutions + solutions, ) } } @@ -69,7 +69,7 @@ class TestNumberCharsImpl(private val solverFactory: SolverFactory) : TestNumber assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to 3)), - solutions + solutions, ) } } @@ -83,7 +83,7 @@ class TestNumberCharsImpl(private val solverFactory: SolverFactory) : TestNumber assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to 4.2)), - solutions + solutions, ) } } @@ -97,7 +97,7 @@ class TestNumberCharsImpl(private val solverFactory: SolverFactory) : TestNumber assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to 3.9)), - solutions + solutions, ) } } @@ -116,11 +116,11 @@ class TestNumberCharsImpl(private val solverFactory: SolverFactory) : TestNumber DummyInstances.executionContext, Signature("number_chars", 2), varOf("X"), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumberCodes.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumberCodes.kt index 856889da4..ae6bfb4b7 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumberCodes.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumberCodes.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestNumberCodes : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestNumberCodesImpl = - TestNumberCodesImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestNumberCodesImpl = TestNumberCodesImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumberCodesImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumberCodesImpl.kt index 832744c3f..3a39d1c39 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumberCodesImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumberCodesImpl.kt @@ -13,7 +13,7 @@ class TestNumberCodesImpl(private val solverFactory: SolverFactory) : TestNumber assertSolutionEquals( kotlin.collections.listOf(query.yes("L" to listOf(51, 51))), - solutions + solutions, ) } } @@ -27,7 +27,7 @@ class TestNumberCodesImpl(private val solverFactory: SolverFactory) : TestNumber assertSolutionEquals( kotlin.collections.listOf(query.yes("L" to listOf(51, 51, 46, 49))), - solutions + solutions, ) } } @@ -41,7 +41,7 @@ class TestNumberCodesImpl(private val solverFactory: SolverFactory) : TestNumber assertSolutionEquals( kotlin.collections.listOf(query.yes("L" to listOf(57, 57, 50, 49, 46, 49))), - solutions + solutions, ) } } @@ -55,7 +55,7 @@ class TestNumberCodesImpl(private val solverFactory: SolverFactory) : TestNumber assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -69,7 +69,7 @@ class TestNumberCodesImpl(private val solverFactory: SolverFactory) : TestNumber assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -83,7 +83,7 @@ class TestNumberCodesImpl(private val solverFactory: SolverFactory) : TestNumber assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to numOf("-3.8"))), - solutions + solutions, ) } } @@ -103,11 +103,11 @@ class TestNumberCodesImpl(private val solverFactory: SolverFactory) : TestNumber Signature("number_codes", 2), TypeError.Expected.NUMBER, atomOf("a"), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumberImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumberImpl.kt index 06e97571d..beeffc32f 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumberImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestNumberImpl.kt @@ -12,7 +12,7 @@ internal class TestNumberImpl(private val solverFactory: SolverFactory) : TestNu assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -26,7 +26,7 @@ internal class TestNumberImpl(private val solverFactory: SolverFactory) : TestNu assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -40,7 +40,7 @@ internal class TestNumberImpl(private val solverFactory: SolverFactory) : TestNu assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -54,7 +54,7 @@ internal class TestNumberImpl(private val solverFactory: SolverFactory) : TestNu assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -68,7 +68,7 @@ internal class TestNumberImpl(private val solverFactory: SolverFactory) : TestNu assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestOnce.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestOnce.kt index 649e20173..7d8ae7e86 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestOnce.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestOnce.kt @@ -4,7 +4,7 @@ interface TestOnce : SolverTest { companion object { fun prototype( solverFactory: SolverFactory, - errorSignature: Signature = Signature("once", 1) + errorSignature: Signature = Signature("once", 1), ): TestOnce = TestOnceImpl(solverFactory, errorSignature) } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestOnceImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestOnceImpl.kt index 080b96e3c..567041cea 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestOnceImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestOnceImpl.kt @@ -6,7 +6,7 @@ import it.unibo.tuprolog.solve.exception.error.TypeError internal class TestOnceImpl( private val solverFactory: SolverFactory, - override val errorSignature: Signature + override val errorSignature: Signature, ) : TestOnce { override fun testOnceCut() { logicProgramming { @@ -17,7 +17,7 @@ internal class TestOnceImpl( assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -33,10 +33,10 @@ internal class TestOnceImpl( with(query) { kotlin.collections.listOf( yes("X" to 1), - yes("X" to 2) + yes("X" to 2), ) }, - solutions + solutions, ) } } @@ -50,7 +50,7 @@ internal class TestOnceImpl( assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -64,7 +64,7 @@ internal class TestOnceImpl( assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -83,12 +83,11 @@ internal class TestOnceImpl( DummyInstances.executionContext, errorSignature, TypeError.Expected.CALLABLE, - numOf(3) - - ) - ) + numOf(3), + ), + ), ), - solutions + solutions, ) } } @@ -106,11 +105,11 @@ internal class TestOnceImpl( InstantiationError.forGoal( DummyInstances.executionContext, errorSignature, - varOf("X") - ) - ) + varOf("X"), + ), + ), ), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestOr.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestOr.kt index bd0f3a5df..eacf21ab3 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestOr.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestOr.kt @@ -4,10 +4,8 @@ package it.unibo.tuprolog.solve * Tests of ';'/2 (= or, disjunction) */ interface TestOr : SolverTest { - companion object { - fun prototype(solverFactory: SolverFactory): TestOr = - TestOrImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestOr = TestOrImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestOrImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestOrImpl.kt index d31936802..fac34723e 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestOrImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestOrImpl.kt @@ -3,7 +3,6 @@ package it.unibo.tuprolog.solve import it.unibo.tuprolog.dsl.theory.logicProgramming internal class TestOrImpl(private val solverFactory: SolverFactory) : TestOr { - override fun testTrueOrFalse() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() @@ -15,10 +14,10 @@ internal class TestOrImpl(private val solverFactory: SolverFactory) : TestOr { with(query) { ktListOf( yes(), - no() + no(), ) }, - solutions + solutions, ) } } @@ -33,7 +32,7 @@ internal class TestOrImpl(private val solverFactory: SolverFactory) : TestOr { assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } @@ -48,7 +47,7 @@ internal class TestOrImpl(private val solverFactory: SolverFactory) : TestOr { assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) } } @@ -63,7 +62,7 @@ internal class TestOrImpl(private val solverFactory: SolverFactory) : TestOr { assertSolutionEquals( ktListOf(query.yes("X" to 1)), - solutions + solutions, ) } } @@ -80,10 +79,10 @@ internal class TestOrImpl(private val solverFactory: SolverFactory) : TestOr { with(query) { ktListOf( yes("X" to 1), - yes("X" to 2) + yes("X" to 2), ) }, - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRecursion.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRecursion.kt index a78222158..3f16e34d8 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRecursion.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRecursion.kt @@ -1,10 +1,8 @@ package it.unibo.tuprolog.solve interface TestRecursion : SolverTest { - companion object { - fun prototype(solverFactory: SolverFactory): TestRecursion = - TestRecursionImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestRecursion = TestRecursionImpl(solverFactory) } fun testRecursion1() diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRecursionImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRecursionImpl.kt index 30b43ba4e..8522f0db9 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRecursionImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRecursionImpl.kt @@ -11,11 +11,13 @@ import kotlin.test.assertEquals import kotlin.test.assertTrue internal class TestRecursionImpl(private val solverFactory: SolverFactory) : TestRecursion { - override val shortDuration: TimeDuration get() = 1000 - private fun thermostat(initialTemp: Int, goodRange: IntRange) = logicProgramming { + private fun thermostat( + initialTemp: Int, + goodRange: IntRange, + ) = logicProgramming { theoryOf( directive { dynamic("temp" / 1) }, fact { "temp"(initialTemp) }, @@ -27,7 +29,7 @@ internal class TestRecursionImpl(private val solverFactory: SolverFactory) : Tes write(X), T `is` (X - 1), "change_temperature"(T), - "check_temperature" + "check_temperature", ) }, rule { @@ -38,7 +40,7 @@ internal class TestRecursionImpl(private val solverFactory: SolverFactory) : Tes write(X), T `is` (X + 1), "change_temperature"(T), - "check_temperature" + "check_temperature", ) }, rule { @@ -47,25 +49,29 @@ internal class TestRecursionImpl(private val solverFactory: SolverFactory) : Tes X greaterThan goodRange.first, X lowerThan goodRange.last, cut, - write(X) + write(X), ) }, rule { "change_temperature"(X).impliedBy( retract("temp"(`_`)), - assert("temp"(X)) + assert("temp"(X)), ) - } + }, ) } - private fun testRecursion(init: Int, range: IntRange) { + private fun testRecursion( + init: Int, + range: IntRange, + ) { logicProgramming { val prints = mutableListOf() - val solver = solverFactory.solverWithDefaultBuiltins( - staticKb = thermostat(init, range), - stdOut = OutputChannel.of { prints.add(it) } - ) + val solver = + solverFactory.solverWithDefaultBuiltins( + staticKb = thermostat(init, range), + stdOut = OutputChannel.of { prints.add(it) }, + ) val sol = solver.solveOnce(atomOf("check_temperature"), mediumDuration) @@ -74,12 +80,12 @@ internal class TestRecursionImpl(private val solverFactory: SolverFactory) : Tes if (init <= range.first) { assertEquals( (init..range.first + 1).map { it.toString() }, - prints + prints, ) } else if (init >= range.last) { assertEquals( (range.last - 1..init).toList().asReversed().map { it.toString() }, - prints + prints, ) } } @@ -93,27 +99,32 @@ internal class TestRecursionImpl(private val solverFactory: SolverFactory) : Tes testRecursion(30, 18..22) } - private fun canary(message: String) = logicProgramming { - theoryOf( - rule { "recursive"(0) impliedBy `throw`(message) }, - rule { - "recursive"(N).impliedBy( - N greaterThan 0, - M `is` (N - 1), - "recursive"(M) - ) - } - ) - } + private fun canary(message: String) = + logicProgramming { + theoryOf( + rule { "recursive"(0) impliedBy `throw`(message) }, + rule { + "recursive"(N).impliedBy( + N greaterThan 0, + M `is` (N - 1), + "recursive"(M), + ) + }, + ) + } - private fun testTailRecursion(lastCallOptimization: Boolean, n: Int = 100) { + private fun testTailRecursion( + lastCallOptimization: Boolean, + n: Int = 100, + ) { logicProgramming { val prints = mutableListOf() - val solver = solverFactory.solverWithDefaultBuiltins( - staticKb = canary("ball"), - flags = FlagStore.DEFAULT.set(LastCallOptimization, if (lastCallOptimization) ON else OFF), - stdOut = OutputChannel.of { prints.add(it) } - ) + val solver = + solverFactory.solverWithDefaultBuiltins( + staticKb = canary("ball"), + flags = FlagStore.DEFAULT.set(LastCallOptimization, if (lastCallOptimization) ON else OFF), + stdOut = OutputChannel.of { prints.add(it) }, + ) assertEquals(if (lastCallOptimization) ON else OFF, solver.flags[LastCallOptimization]) @@ -125,10 +136,10 @@ internal class TestRecursionImpl(private val solverFactory: SolverFactory) : Tes query.halt( SystemError.forUncaughtException( DummyInstances.executionContext, - atomOf("ball") - ) + atomOf("ball"), + ), ), - sol + sol, ) if (lastCallOptimization) { assertEquals(2, (sol as Solution.Halt).exception.logicStackTrace.size) diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRepeat.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRepeat.kt index 8c8d6c6de..f77f07147 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRepeat.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRepeat.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestRepeat : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestRepeat = - TestRepeatImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestRepeat = TestRepeatImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRepeatImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRepeatImpl.kt index 74b6e09b2..7b1347be0 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRepeatImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRepeatImpl.kt @@ -12,7 +12,7 @@ internal class TestRepeatImpl(private val solverFactory: SolverFactory) : TestRe assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRetract.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRetract.kt index 7247d75d2..1069dc7a9 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRetract.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRetract.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestRetract : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestRetract = - TestRetractImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestRetract = TestRetractImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRetractImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRetractImpl.kt index 4c995d3c3..b191389ef 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRetractImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestRetractImpl.kt @@ -20,11 +20,11 @@ internal class TestRetractImpl(private val solverFactory: SolverFactory) : TestR Signature("retract", 1), DomainError.Expected.CLAUSE, ":-"(4, "X"), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } @@ -44,11 +44,11 @@ internal class TestRetractImpl(private val solverFactory: SolverFactory) : TestR Signature("retract", 1), PermissionError.Operation.MODIFY, PermissionError.Permission.PRIVATE_PROCEDURE, - "atom" / 1 - ) - ) - ), // Permission_error - solutions + "atom" / 1, + ), + ), + ), + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSetOf.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSetOf.kt index 74330ee21..1de0b3748 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSetOf.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSetOf.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestSetOf : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestSetOfImpl = - TestSetOfImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestSetOfImpl = TestSetOfImpl(solverFactory) } /** @@ -28,7 +27,7 @@ interface TestSetOf : SolverTest { * ?- setof(X,(X=2;X=1),L) * ``` */ - fun testSetOfNoSorted() + fun testSetOfSorted() /** * Tests the queries diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSetOfImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSetOfImpl.kt index 31e8bc925..b00bfb2fd 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSetOfImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSetOfImpl.kt @@ -3,7 +3,6 @@ package it.unibo.tuprolog.solve import it.unibo.tuprolog.dsl.theory.logicProgramming class TestSetOfImpl(private val solverFactory: SolverFactory) : TestSetOf { - override fun testSetOfBasic() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() @@ -13,7 +12,7 @@ class TestSetOfImpl(private val solverFactory: SolverFactory) : TestSetOf { assertSolutionEquals( ktListOf(query.yes("S" to listOf(1, 2))), - solutions + solutions, ) } } @@ -27,12 +26,12 @@ class TestSetOfImpl(private val solverFactory: SolverFactory) : TestSetOf { assertSolutionEquals( ktListOf(query.yes("X" to listOf(1, 2))), - solutions + solutions, ) } } - override fun testSetOfNoSorted() { + override fun testSetOfSorted() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() @@ -40,8 +39,8 @@ class TestSetOfImpl(private val solverFactory: SolverFactory) : TestSetOf { val solutions = solver.solve(query, mediumDuration).toList() assertSolutionEquals( - ktListOf(query.yes("X" to listOf(1, 2))), - solutions + ktListOf(query.yes("X" to listOf(2, 1))), + solutions, ) } } @@ -55,7 +54,7 @@ class TestSetOfImpl(private val solverFactory: SolverFactory) : TestSetOf { assertSolutionEquals( ktListOf(query.yes("L" to listOf(2))), - solutions + solutions, ) } } @@ -69,7 +68,7 @@ class TestSetOfImpl(private val solverFactory: SolverFactory) : TestSetOf { assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) } } @@ -83,7 +82,7 @@ class TestSetOfImpl(private val solverFactory: SolverFactory) : TestSetOf { assertSolutionEquals( ktListOf(query.yes("S" to listOf(1, 2))), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSolutionPresentationImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSolutionPresentationImpl.kt index b24399552..c5913d88f 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSolutionPresentationImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSolutionPresentationImpl.kt @@ -8,9 +8,10 @@ import kotlin.test.assertTrue class TestSolutionPresentationImpl(private val solverFactory: SolverFactory) : TestSolutionPresentation { override fun testSolutionWithDandlingVars() { logicProgramming { - val theory = theoryOf( - fact { "append"("seq"(X), X) } - ) + val theory = + theoryOf( + fact { "append"("seq"(X), X) }, + ) val solver = solverFactory.solverOf(staticKb = theory) val query = "append"(A, B) val sol = solver.solveOnce(query) diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSolver.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSolver.kt index 5fd59bf1f..6ddc2c8e1 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSolver.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSolver.kt @@ -29,13 +29,12 @@ import it.unibo.tuprolog.solve.TimeRelatedTheories.slightlyMoreThan700MsGoalToSo /** A prototype class for testing solver implementations */ interface TestSolver : SolverTest { - companion object { fun prototype( solverFactory: SolverFactory, callErrorSignature: Signature = Signature("call", 1), nafErrorSignature: Signature = Signature("\\+", 1), - notErrorSignature: Signature = Signature("not", 1) + notErrorSignature: Signature = Signature("not", 1), ): TestSolver = TestSolverImpl(solverFactory, callErrorSignature, nafErrorSignature, notErrorSignature) } @@ -152,29 +151,52 @@ interface TestSolver : SolverTest { /** Test with [customRangeListGeneratorTheoryNotableGoalToSolution] */ fun testNumbersRangeListGeneration() + fun testFailure() + fun testBasicBacktracking1() + fun testBasicBacktracking2() + fun testBasicBacktracking3() + fun testBasicBacktracking4() + fun testConjunction() + fun testConjunctionOfConjunctions() + fun testConjunctionWithUnification() + fun testDisjunction() + fun testDisjunctionWithUnification() + fun testMember() + fun testAssertRules() + fun testRetract() + fun testNatural() + fun testFunctor() + fun testUniv() + fun testAppend() + fun testRetractAll() fun testTermGreaterThan() + fun testTermGreaterThanOrEqual() + fun testTermSame() + fun testTermNotSame() + fun testTermLowerThan() + fun testTermLowerThanOrEqual() } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSolverConstruction.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSolverConstruction.kt index cd8659e38..6464af5fd 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSolverConstruction.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSolverConstruction.kt @@ -3,11 +3,10 @@ package it.unibo.tuprolog.solve import it.unibo.tuprolog.solve.library.Library interface TestSolverConstruction { - companion object { inline fun prototype( factory: SolverFactory, - defaultBuiltins: Library + defaultBuiltins: Library, ): TestSolverConstruction = TestSolverConstructionImpl(factory, defaultBuiltins, T::class, MT::class) } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSolverConstructionImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSolverConstructionImpl.kt index d38de4e4b..c750a056f 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSolverConstructionImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSolverConstructionImpl.kt @@ -23,19 +23,20 @@ class TestSolverConstructionImpl( private val factory: SolverFactory, private val defaultBuiltIns: Library, private val solverType: KClass, - private val mutableSolverType: KClass + private val mutableSolverType: KClass, ) : TestSolverConstruction { - private object Dummy { val library = libraryOf("dummy", Sleep) val runtime = library.toRuntime() val flags = FlagStore.of(Unknown { ERROR }, LastCallOptimization { OFF }) - val theory1 = logicProgramming { - theoryOf(fact { "a" }, fact { "b" }, fact { "c" }) - } - val theory2 = logicProgramming { - theoryOf(fact { "nat"("z") }, rule { "nat"("s"(X)) impliedBy "nat"(X) }) - } + val theory1 = + logicProgramming { + theoryOf(fact { "a" }, fact { "b" }, fact { "c" }) + } + val theory2 = + logicProgramming { + theoryOf(fact { "nat"("z") }, rule { "nat"("s"(X)) impliedBy "nat"(X) }) + } val input = InputChannel.of("") val output = OutputChannel.of { } val error = OutputChannel.of { } @@ -51,11 +52,12 @@ class TestSolverConstructionImpl( val dynamicKb = Theory.empty(unificator) val flags = FlagStore.DEFAULT val inputs = InputStore.fromStandard(InputChannel.stdIn()) - val outputs = OutputStore.fromStandard( - OutputChannel.stdOut(), - OutputChannel.stdErr(), - OutputChannel.warn() - ) + val outputs = + OutputStore.fromStandard( + OutputChannel.stdOut(), + OutputChannel.stdErr(), + OutputChannel.warn(), + ) } private fun Solver.asserHasDefaultProperties(mutable: Boolean) { @@ -65,7 +67,7 @@ class TestSolverConstructionImpl( dynamicKb = Default.dynamicKb, flags = Default.flags, inputs = Default.inputs, - outputs = Default.outputs + outputs = Default.outputs, ) assertEquals(true, solverType.isInstance(this)) assertEquals(mutable, mutableSolverType.isInstance(this)) @@ -82,7 +84,7 @@ class TestSolverConstructionImpl( dynamicKb = Dummy.theory2, flags = Dummy.flags, inputs = Dummy.inputs, - outputs = Dummy.outputs + outputs = Dummy.outputs, ) assertEquals(mutable, this is MutableSolver) } @@ -96,7 +98,7 @@ class TestSolverConstructionImpl( stdIn = Dummy.input, stdOut = Dummy.output, stdErr = Dummy.error, - warnings = Dummy.warning + warnings = Dummy.warning, ).asserHasCustomProperties(mutable = false) } @@ -107,7 +109,7 @@ class TestSolverConstructionImpl( dynamicKb = Default.dynamicKb, flags = Default.flags, inputs = Default.inputs, - outputs = Default.outputs + outputs = Default.outputs, ) assertEquals(mutable, this is MutableSolver) } @@ -123,7 +125,7 @@ class TestSolverConstructionImpl( dynamicKb = Dummy.theory2, flags = Dummy.flags, inputs = Dummy.inputs, - outputs = Dummy.outputs + outputs = Dummy.outputs, ) assertEquals(mutable, this is MutableSolver) } @@ -137,7 +139,7 @@ class TestSolverConstructionImpl( stdIn = Dummy.input, stdOut = Dummy.output, stdErr = Dummy.error, - warnings = Dummy.warning + warnings = Dummy.warning, ).asserHasDefaultBultinsAndCustomProperties(mutable = false) } @@ -154,7 +156,7 @@ class TestSolverConstructionImpl( stdIn = Dummy.input, stdOut = Dummy.output, stdErr = Dummy.error, - warnings = Dummy.warning + warnings = Dummy.warning, ).asserHasCustomProperties(mutable = true) } @@ -171,7 +173,7 @@ class TestSolverConstructionImpl( stdIn = Dummy.input, stdOut = Dummy.output, stdErr = Dummy.error, - warnings = Dummy.warning + warnings = Dummy.warning, ).asserHasDefaultBultinsAndCustomProperties(mutable = true) } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSolverImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSolverImpl.kt index 4efc6a576..0e1b1dcbe 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSolverImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSolverImpl.kt @@ -149,63 +149,70 @@ internal class TestSolverImpl( private val solverFactory: SolverFactory, override val callErrorSignature: Signature, override val nafErrorSignature: Signature, - override val notErrorSignature: Signature + override val notErrorSignature: Signature, ) : TestSolver { - override fun testUnknownFlag2() { logicProgramming { - val theory = theoryOf( - rule { - "ancestor"(X, Y) `if` "parent"(X, Y) - }, - rule { - "ancestor"(X, Y) `if` ("parent"(X, Z) and "ancestor"(Z, Y)) - }, - fact { "parent"("abraham", "isaac") }, - fact { "parent"("isaac", "jacob") }, - fact { "parent"("jacob", "joseph") } - ) + val theory = + theoryOf( + rule { + "ancestor"(X, Y) `if` "parent"(X, Y) + }, + rule { + "ancestor"(X, Y) `if` ("parent"(X, Z) and "ancestor"(Z, Y)) + }, + fact { "parent"("abraham", "isaac") }, + fact { "parent"("isaac", "jacob") }, + fact { "parent"("jacob", "joseph") }, + ) val observedWarnings = mutableListOf() - var solver = solverFactory.solverWithDefaultBuiltins( - staticKb = theory, - flags = FlagStore.of(Unknown to WARNING), - warnings = OutputChannel.of { - observedWarnings.add(it) - } - ) + var solver = + solverFactory.solverWithDefaultBuiltins( + staticKb = theory, + flags = FlagStore.of(Unknown to WARNING), + warnings = + OutputChannel.of { + observedWarnings.add(it) + }, + ) val query = "ancestor"("abraham", X) - val expectedSolutions = ktListOf( - query.yes(X to "isaac"), - query.yes(X to "jacob"), - query.yes(X to "joseph"), - query.no() - ) + val expectedSolutions = + ktListOf( + query.yes(X to "isaac"), + query.yes(X to "jacob"), + query.yes(X to "joseph"), + query.no(), + ) assertSolutionEquals(expectedSolutions, solver.solve(query).toList()) assertEquals(mutableListOf(), observedWarnings) - solver = solverFactory.solverWithDefaultBuiltins( - staticKb = theory, - flags = FlagStore.of(Unknown to ERROR), - warnings = OutputChannel.of { - observedWarnings.add(it) - } - ) + solver = + solverFactory.solverWithDefaultBuiltins( + staticKb = theory, + flags = FlagStore.of(Unknown to ERROR), + warnings = + OutputChannel.of { + observedWarnings.add(it) + }, + ) assertSolutionEquals(expectedSolutions, solver.solve(query).toList()) assertEquals(mutableListOf(), observedWarnings) - solver = solverFactory.solverWithDefaultBuiltins( - staticKb = theory, - flags = FlagStore.of(Unknown to FAIL), - warnings = OutputChannel.of { - observedWarnings.add(it) - } - ) + solver = + solverFactory.solverWithDefaultBuiltins( + staticKb = theory, + flags = FlagStore.of(Unknown to FAIL), + warnings = + OutputChannel.of { + observedWarnings.add(it) + }, + ) assertSolutionEquals(expectedSolutions, solver.solve(query).toList()) assertEquals(mutableListOf(), observedWarnings) @@ -218,51 +225,57 @@ internal class TestSolverImpl( val observedWarnings = mutableListOf() - var solver = solverFactory.solverWithDefaultBuiltins( - flags = FlagStore.of(Unknown to ERROR), - warnings = OutputChannel.of { - observedWarnings.add(it) - } - ) + var solver = + solverFactory.solverWithDefaultBuiltins( + flags = FlagStore.of(Unknown to ERROR), + warnings = + OutputChannel.of { + observedWarnings.add(it) + }, + ) assertSolutionEquals( ktListOf( query.halt( ExistenceError.forProcedure( DummyInstances.executionContext, - query.extractSignature() - ) - ) + query.extractSignature(), + ), + ), ), - solver.solve(query).toList() + solver.solve(query).toList(), ) assertTrue { observedWarnings.isEmpty() } - solver = solverFactory.solverWithDefaultBuiltins( - flags = FlagStore.of(Unknown to WARNING), - warnings = OutputChannel.of { - observedWarnings.add(it) - } - ) + solver = + solverFactory.solverWithDefaultBuiltins( + flags = FlagStore.of(Unknown to WARNING), + warnings = + OutputChannel.of { + observedWarnings.add(it) + }, + ) assertSolutionEquals( ktListOf(query.no()), - solver.solve(query).toList() + solver.solve(query).toList(), ) assertEquals(1, observedWarnings.size) assertTrue { observedWarnings[0] is MissingPredicate } assertEquals(query.extractSignature(), (observedWarnings[0] as MissingPredicate).signature) - solver = solverFactory.solverWithDefaultBuiltins( - flags = FlagStore.of(Unknown to FAIL), - warnings = OutputChannel.of { - observedWarnings.add(it) - } - ) + solver = + solverFactory.solverWithDefaultBuiltins( + flags = FlagStore.of(Unknown to FAIL), + warnings = + OutputChannel.of { + observedWarnings.add(it) + }, + ) assertSolutionEquals( ktListOf(query.no()), - solver.solve(query).toList() + solver.solve(query).toList(), ) assertTrue { observedWarnings.size == 1 } } @@ -360,22 +373,26 @@ internal class TestSolverImpl( } } - private fun testAssert(suffix: String, inverse: Boolean) { + private fun testAssert( + suffix: String, + inverse: Boolean, + ) { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() val assertX = "assert$suffix" - val query = assertX("f"(1)) and - assertX("f"(2)) and - assertX("f"(3)) and - "f"(X) + val query = + assertX("f"(1)) and + assertX("f"(2)) and + assertX("f"(3)) and + "f"(X) val solutions = solver.solve(query, mediumDuration).toList() val ints = if (inverse) (3 downTo 1) else (1..3) assertSolutionEquals( (ints).map { query.yes(X to it) }, - solutions + solutions, ) ints.forEach { @@ -405,14 +422,15 @@ internal class TestSolverImpl( solver.standardOutput.addListener { outputs += it!! } - val terms = ktListOf( - atomOf("atom"), - atomOf("a string"), - varOf("A_Var"), - numOf(1), - numOf(2.1), - "f"("x") - ) + val terms = + ktListOf( + atomOf("atom"), + atomOf("a string"), + varOf("A_Var"), + numOf(1), + numOf(2.1), + "f"("x"), + ) val query = tupleOf(terms.map { write(it) }.append(nl)) @@ -420,12 +438,12 @@ internal class TestSolverImpl( assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) assertEquals( terms.map { it.format(TermFormatter.default()) }.append("\n"), - outputs + outputs, ) } } @@ -446,34 +464,36 @@ internal class TestSolverImpl( assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) solver.standardOutput.write("e") assertEquals( ktListOf("a", "b", "c", "d", "\n", "e"), - outputs + outputs, ) } } override fun testFindAll() { logicProgramming { - val solver = solverFactory.solverWithDefaultBuiltins( - staticKb = theoryOf( - fact { "a"(1) }, - fact { "a"(2) }, - fact { "a"(3) } + val solver = + solverFactory.solverWithDefaultBuiltins( + staticKb = + theoryOf( + fact { "a"(1) }, + fact { "a"(2) }, + fact { "a"(3) }, + ), ) - ) var query = findall(N, "a"(N), L) var solutions = solver.solve(query, mediumDuration).toList() assertSolutionEquals( ktListOf(query.yes(L to listOf(1, 2, 3))), - solutions + solutions, ) query = findall(`_`, false, L) @@ -481,7 +501,7 @@ internal class TestSolverImpl( assertSolutionEquals( ktListOf(query.yes(L to emptyList)), - solutions + solutions, ) query = findall(`_`, G, `_`) @@ -494,36 +514,39 @@ internal class TestSolverImpl( DummyInstances.executionContext, Signature("findall", 3), variable = G, - index = 1 - ) - ) + index = 1, + ), + ), ), - solutions + solutions, ) } } override fun testSideEffectsPersistentAfterBacktracking1() { logicProgramming { - val solver = solverFactory.solverWithDefaultBuiltins( - dynamicKb = theoryOf( - fact { "f"(1) }, - fact { "f"(2) }, - fact { "f"(3) } - ), - staticKb = theoryOf( - clause { "getf"(F) `if` findall(X, "f"(X), F) }, - clause { "getg"(G) `if` findall(X, "g"(X), G) }, - clause { - "ftog"(F, G) `if` ( - retract("f"(X)) and - assert("g"(X)) and - "getf"(F) and - "getg"(G) - ) - } + val solver = + solverFactory.solverWithDefaultBuiltins( + dynamicKb = + theoryOf( + fact { "f"(1) }, + fact { "f"(2) }, + fact { "f"(3) }, + ), + staticKb = + theoryOf( + clause { "getf"(F) `if` findall(X, "f"(X), F) }, + clause { "getg"(G) `if` findall(X, "g"(X), G) }, + clause { + "ftog"(F, G) `if` ( + retract("f"(X)) and + assert("g"(X)) and + "getf"(F) and + "getg"(G) + ) + }, + ), ) - ) val query = "ftog"(X, Y) val solutions = solver.solve(query, longDuration).toList() @@ -532,9 +555,9 @@ internal class TestSolverImpl( ktListOf( query.yes(X to listOf(2, 3), Y to listOf(1)), query.yes(X to listOf(3), Y to listOf(1, 2)), - query.yes(X to emptyList, Y to listOf(1, 2, 3)) + query.yes(X to emptyList, Y to listOf(1, 2, 3)), ), - solutions + solutions, ) } } @@ -548,7 +571,7 @@ internal class TestSolverImpl( assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) } } @@ -556,44 +579,48 @@ internal class TestSolverImpl( /** Test with [lessThan500MsGoalToSolution] */ override fun testTimeout1() { assertSolverSolutionsCorrect( - solver = solverFactory.solverWithDefaultBuiltins( - staticKb = timeRelatedTheory - ), + solver = + solverFactory.solverWithDefaultBuiltins( + staticKb = timeRelatedTheory, + ), goalToSolutions = lessThan500MsGoalToSolution, - maxDuration = 400L + maxDuration = 400L, ) } /** Test with [slightlyMoreThan500MsGoalToSolution] */ override fun testTimeout2() { assertSolverSolutionsCorrect( - solver = solverFactory.solverWithDefaultBuiltins( - staticKb = timeRelatedTheory - ), + solver = + solverFactory.solverWithDefaultBuiltins( + staticKb = timeRelatedTheory, + ), goalToSolutions = slightlyMoreThan500MsGoalToSolution, - maxDuration = 599L + maxDuration = 599L, ) } /** Test with [slightlyMoreThan600MsGoalToSolution] */ override fun testTimeout3() { assertSolverSolutionsCorrect( - solver = solverFactory.solverWithDefaultBuiltins( - staticKb = timeRelatedTheory - ), + solver = + solverFactory.solverWithDefaultBuiltins( + staticKb = timeRelatedTheory, + ), goalToSolutions = slightlyMoreThan600MsGoalToSolution, - maxDuration = 699L + maxDuration = 699L, ) } /** Test with [slightlyMoreThan700MsGoalToSolution] */ override fun testTimeout4() { assertSolverSolutionsCorrect( - solver = solverFactory.solverWithDefaultBuiltins( - staticKb = timeRelatedTheory - ), + solver = + solverFactory.solverWithDefaultBuiltins( + staticKb = timeRelatedTheory, + ), goalToSolutions = slightlyMoreThan700MsGoalToSolution, - maxDuration = 799L + maxDuration = 799L, ) } @@ -602,7 +629,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solver = solverFactory.solverWithDefaultBuiltins(staticKb = ifThenTheory1), goalToSolutions = ifThen1ToSolution, - maxDuration = mediumDuration + maxDuration = mediumDuration, ) } @@ -611,7 +638,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solver = solverFactory.solverWithDefaultBuiltins(staticKb = ifThenTheory1), goalToSolutions = ifThenElse1ToSolution, - maxDuration = mediumDuration + maxDuration = mediumDuration, ) } @@ -620,7 +647,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solver = solverFactory.solverWithDefaultBuiltins(staticKb = ifThenTheory2), goalToSolutions = ifThenElse2ToSolution, - maxDuration = mediumDuration + maxDuration = mediumDuration, ) } @@ -629,7 +656,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solver = solverFactory.solverWithDefaultBuiltins(staticKb = ifThenTheory2), goalToSolutions = ifThen2ToSolution, - maxDuration = mediumDuration + maxDuration = mediumDuration, ) } @@ -638,7 +665,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(staticKb = simpleFactTheory), simpleFactTheoryNotableGoalToSolutions, - mediumDuration + mediumDuration, ) } @@ -647,7 +674,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(staticKb = simpleCutTheory), simpleCutTheoryNotableGoalToSolutions, - mediumDuration + mediumDuration, ) } @@ -656,7 +683,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(staticKb = simpleCutAndConjunctionTheory), simpleCutAndConjunctionTheoryNotableGoalToSolutions, - mediumDuration + mediumDuration, ) } @@ -665,7 +692,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(staticKb = cutConjunctionAndBacktrackingTheory), cutConjunctionAndBacktrackingTheoryNotableGoalToSolutions, - mediumDuration + mediumDuration, ) } @@ -674,7 +701,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(staticKb = infiniteComputationTheory), infiniteComputationTheoryNotableGoalToSolution, - shortDuration + shortDuration, ) } @@ -683,16 +710,18 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(staticKb = prologStandardExampleTheory), prologStandardExampleTheoryNotableGoalToSolution, - mediumDuration + mediumDuration, ) } /** Test with [prologStandardExampleWithCutTheoryNotableGoalToSolution] */ override fun testPrologStandardSearchTreeWithCutExample() { assertSolverSolutionsCorrect( - solverFactory.solverWithDefaultBuiltins(staticKb = PrologStandardExampleTheories.prologStandardExampleWithCutTheory), + solverFactory.solverWithDefaultBuiltins( + staticKb = PrologStandardExampleTheories.prologStandardExampleWithCutTheory, + ), prologStandardExampleWithCutTheoryNotableGoalToSolution, - mediumDuration + mediumDuration, ) } @@ -701,7 +730,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(staticKb = customReverseListTheory), customReverseListTheoryNotableGoalToSolution, - mediumDuration + mediumDuration, ) } @@ -710,7 +739,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(staticKb = conjunctionStandardExampleTheory), conjunctionStandardExampleTheoryNotableGoalToSolution, - mediumDuration + mediumDuration, ) } @@ -721,14 +750,13 @@ internal class TestSolverImpl( allPrologTestingTheoriesToRespectiveGoalsAndSolutions( callErrorSignature, nafErrorSignature, - notErrorSignature + notErrorSignature, ) .mapValues { (_, listOfGoalToSolutions) -> listOfGoalToSolutions.flatMap { (goal, expectedSolutions) -> ktListOf( (goal and true).run { to(expectedSolutions.changeQueriesTo(this)) }, (true and goal).run { to(expectedSolutions.changeQueriesTo(this)) }, - (goal and false).run { when { expectedSolutions.any { it is Solution.Halt } -> @@ -736,8 +764,7 @@ internal class TestSolverImpl( else -> hasSolutions({ no() }) } }, - - (false and goal).hasSolutions({ no() }) + (false and goal).hasSolutions({ no() }), ) } } @@ -747,7 +774,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(staticKb = database), goalToSolutions, - mediumDuration + mediumDuration, ) } } @@ -758,13 +785,13 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(staticKb = callStandardExampleTheory), callStandardExampleTheoryGoalsToSolution(callErrorSignature), - mediumDuration + mediumDuration, ) assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(), callTestingGoalsToSolutions(callErrorSignature), - mediumDuration + mediumDuration, ) } @@ -774,7 +801,7 @@ internal class TestSolverImpl( allPrologTestingTheoriesToRespectiveGoalsAndSolutions( callErrorSignature, nafErrorSignature, - notErrorSignature + notErrorSignature, ) .mapValues { (_, listOfGoalToSolutions) -> listOfGoalToSolutions.map { (goal, expectedSolutions) -> @@ -784,7 +811,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(staticKb = database), goalToSolutions, - mediumDuration + mediumDuration, ) } } @@ -795,28 +822,29 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(staticKb = catchAndThrowTheoryExample), catchAndThrowTheoryExampleNotableGoalToSolution, - mediumDuration + mediumDuration, ) assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(), catchTestingGoalsToSolutions, - mediumDuration + mediumDuration, ) } /** A test in which all testing goals are called through the Catch primitive */ override fun testCatchPrimitiveTransparency() { logicProgramming { - fun Struct.containsHaltPrimitive(): Boolean = when (functor) { - "halt" -> true - else -> argsSequence.filterIsInstance().any { it.containsHaltPrimitive() } - } + fun Struct.containsHaltPrimitive(): Boolean = + when (functor) { + "halt" -> true + else -> argsSequence.filterIsInstance().any { it.containsHaltPrimitive() } + } allPrologTestingTheoriesToRespectiveGoalsAndSolutions( callErrorSignature, nafErrorSignature, - notErrorSignature + notErrorSignature, ) .mapValues { (_, listOfGoalToSolutions) -> listOfGoalToSolutions.flatMap { (goal, expectedSolutions) -> @@ -833,14 +861,14 @@ internal class TestSolverImpl( }, `catch`(goal, "notUnifyingCatcher", false).run { to(expectedSolutions.changeQueriesTo(this)) - } + }, ) } }.forEach { (database, goalToSolutions) -> assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(staticKb = database), goalToSolutions, - mediumDuration + mediumDuration, ) } } @@ -851,7 +879,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(), haltTestingGoalsToSolutions, - mediumDuration + mediumDuration, ) } @@ -860,7 +888,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(staticKb = notStandardExampleTheory), notStandardExampleTheoryNotableGoalToSolution(nafErrorSignature, notErrorSignature), - mediumDuration + mediumDuration, ) } @@ -870,7 +898,7 @@ internal class TestSolverImpl( allPrologTestingTheoriesToRespectiveGoalsAndSolutions( callErrorSignature, nafErrorSignature, - notErrorSignature + notErrorSignature, ) .mapValues { (_, listOfGoalToSolutions) -> listOfGoalToSolutions.flatMap { (goal, expectedSolutions) -> @@ -902,14 +930,14 @@ internal class TestSolverImpl( expectedSolutions.first() is Solution.No -> hasSolutions({ no() }) else -> to(expectedSolutions.changeQueriesTo(this)) } - } + }, ) } }.forEach { (database, goalToSolutions) -> assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(staticKb = database), goalToSolutions, - mediumDuration + mediumDuration, ) } } @@ -920,7 +948,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(staticKb = ifThenStandardExampleTheory), ifThenStandardExampleTheoryNotableGoalToSolution, - mediumDuration + mediumDuration, ) } @@ -929,7 +957,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(), ifThenElseStandardExampleNotableGoalToSolution, - mediumDuration + mediumDuration, ) } @@ -938,7 +966,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(staticKb = customRangeListGeneratorTheory), customRangeListGeneratorTheoryNotableGoalToSolution, - mediumDuration + mediumDuration, ) } @@ -951,203 +979,221 @@ internal class TestSolverImpl( assertSolutionEquals( ktListOf( - query.no() + query.no(), ), - solutions + solutions, ) } } override fun testBasicBacktracking1() { logicProgramming { - val solver = solverFactory.solverWithDefaultBuiltins( - staticKb = theory( - { "a"(X) impliedBy ("b"(X) and "c"(X)) }, - { "b"(1) }, - { "b"(2) impliedBy cut }, - { "b"(3) }, - { "c"(2) }, - { "c"(3) } + val solver = + solverFactory.solverWithDefaultBuiltins( + staticKb = + theory( + { "a"(X) impliedBy ("b"(X) and "c"(X)) }, + { "b"(1) }, + { "b"(2) impliedBy cut }, + { "b"(3) }, + { "c"(2) }, + { "c"(3) }, + ), ) - ) val query = "a"(N) val solutions = solver.solve(query, mediumDuration).toList() assertSolutionEquals( ktListOf( - query.yes(N to 2) + query.yes(N to 2), ), - solutions + solutions, ) } } override fun testBasicBacktracking2() { logicProgramming { - val solver = solverFactory.solverWithDefaultBuiltins( - staticKb = theory( - { "a"(X) impliedBy ("c"(X) and "b"(X)) }, - { "b"(2) impliedBy cut }, - { "b"(3) }, - { "c"(3) }, - { "c"(2) } + val solver = + solverFactory.solverWithDefaultBuiltins( + staticKb = + theory( + { "a"(X) impliedBy ("c"(X) and "b"(X)) }, + { "b"(2) impliedBy cut }, + { "b"(3) }, + { "c"(3) }, + { "c"(2) }, + ), ) - ) val query = "a"(N) val solutions = solver.solve(query, mediumDuration).toList() assertSolutionEquals( with(query) { ktListOf(yes(N to 3), yes(N to 2)) }, - solutions + solutions, ) } } override fun testBasicBacktracking3() { logicProgramming { - val solver = solverFactory.solverWithDefaultBuiltins( - staticKb = theory( - { "a"(X) impliedBy (("b"(X) and cut) and "c"(X)) }, - { "b"(2) }, - { "b"(3) }, - { "c"(2) }, - { "c"(3) } + val solver = + solverFactory.solverWithDefaultBuiltins( + staticKb = + theory( + { "a"(X) impliedBy (("b"(X) and cut) and "c"(X)) }, + { "b"(2) }, + { "b"(3) }, + { "c"(2) }, + { "c"(3) }, + ), ) - ) val query = "a"(N) val solutions = solver.solve(query, mediumDuration).toList() assertSolutionEquals( ktListOf( - query.yes(N to 2) + query.yes(N to 2), ), - solutions + solutions, ) } } override fun testBasicBacktracking4() { logicProgramming { - val solver = solverFactory.solverWithDefaultBuiltins( - staticKb = theory( - { "a"(X) impliedBy ("b"(X) and (cut and "c"(X))) }, - { "b"(2) }, - { "b"(3) }, - { "c"(2) }, - { "c"(3) } + val solver = + solverFactory.solverWithDefaultBuiltins( + staticKb = + theory( + { "a"(X) impliedBy ("b"(X) and (cut and "c"(X))) }, + { "b"(2) }, + { "b"(3) }, + { "c"(2) }, + { "c"(3) }, + ), ) - ) val query = "a"(N) val solutions = solver.solve(query, mediumDuration).toList() assertSolutionEquals( ktListOf( - query.yes(N to 2) + query.yes(N to 2), ), - solutions + solutions, ) } } override fun testConjunction() { logicProgramming { - val solver = solverFactory.solverWithDefaultBuiltins( - staticKb = theory( - { "a" impliedBy ("b" and "c") }, - { "b" }, - { "c" } + val solver = + solverFactory.solverWithDefaultBuiltins( + staticKb = + theory( + { "a" impliedBy ("b" and "c") }, + { "b" }, + { "c" }, + ), ) - ) val query = atomOf("a") val solutions = solver.solve(query, mediumDuration).toList() assertSolutionEquals( ktListOf( - query.yes() + query.yes(), ), - solutions + solutions, ) } } override fun testConjunctionOfConjunctions() { logicProgramming { - val solver = solverFactory.solverWithDefaultBuiltins( - staticKb = theory( - { "a" impliedBy (tupleOf("b", "c") and tupleOf("d", "e")) }, - { "b" }, - { "c" }, - { "d" }, - { "e" } + val solver = + solverFactory.solverWithDefaultBuiltins( + staticKb = + theory( + { "a" impliedBy (tupleOf("b", "c") and tupleOf("d", "e")) }, + { "b" }, + { "c" }, + { "d" }, + { "e" }, + ), ) - ) val query = atomOf("a") val solutions = solver.solve(query, mediumDuration).toList() assertSolutionEquals( ktListOf( - query.yes() + query.yes(), ), - solutions + solutions, ) } } override fun testConjunctionWithUnification() { logicProgramming { - val solver = solverFactory.solverWithDefaultBuiltins( - staticKb = theory( - { "a"(X) impliedBy ("b"(X) and "c"(X)) }, - { "b"(1) }, - { "c"(1) } + val solver = + solverFactory.solverWithDefaultBuiltins( + staticKb = + theory( + { "a"(X) impliedBy ("b"(X) and "c"(X)) }, + { "b"(1) }, + { "c"(1) }, + ), ) - ) val query = "a"(N) val solutions = solver.solve(query, mediumDuration).toList() assertSolutionEquals( ktListOf( - query.yes(N to 1) + query.yes(N to 1), ), - solutions + solutions, ) } } override fun testDisjunction() { logicProgramming { - val solver = solverFactory.solverWithDefaultBuiltins( - staticKb = theory( - { "a" impliedBy ("b" or "c") }, - { "b" }, - { "c" } + val solver = + solverFactory.solverWithDefaultBuiltins( + staticKb = + theory( + { "a" impliedBy ("b" or "c") }, + { "b" }, + { "c" }, + ), ) - ) val query = atomOf("a") val solutions = solver.solve(query, mediumDuration).toList() assertSolutionEquals( with(query) { ktListOf(yes(), yes()) }, - solutions + solutions, ) } } override fun testDisjunctionWithUnification() { logicProgramming { - val solver = solverFactory.solverWithDefaultBuiltins( - staticKb = theory( - { "a"(X) impliedBy ("b"(X) or "c"(X)) }, - { "b"(1) }, - { "c"(2) } + val solver = + solverFactory.solverWithDefaultBuiltins( + staticKb = + theory( + { "a"(X) impliedBy ("b"(X) or "c"(X)) }, + { "b"(1) }, + { "c"(2) }, + ), ) - ) val query = "a"(N) val solutions = solver.solve(query, mediumDuration).toList() assertSolutionEquals( with(query) { ktListOf(yes(N to 1), yes(N to 2)) }, - solutions + solutions, ) assertEquals(2, solutions.size) @@ -1172,27 +1218,29 @@ internal class TestSolverImpl( assertSolutionEquals( ktListOf(query.yes()), - solutions + solutions, ) assertEquals( ktListOf( factOf(structOf("f", numOf(1))), - ruleOf(structOf("f", numOf(2)), atomOf("false")) + ruleOf(structOf("f", numOf(2)), atomOf("false")), ), - solver.dynamicKb.toList() + solver.dynamicKb.toList(), ) } } override fun testRetract() { logicProgramming { - val solver = solverFactory.solverWithDefaultBuiltins( - dynamicKb = theoryOf( - factOf(structOf("f", numOf(1))), - ruleOf(structOf("f", numOf(2)), atomOf("false")) + val solver = + solverFactory.solverWithDefaultBuiltins( + dynamicKb = + theoryOf( + factOf(structOf("f", numOf(1))), + ruleOf(structOf("f", numOf(2)), atomOf("false")), + ), ) - ) val query = retract("f"(X)) // retract(f(X)) @@ -1201,15 +1249,14 @@ internal class TestSolverImpl( assertSolutionEquals( ktListOf( query.yes(X to 1), - query.yes(X to 2) - + query.yes(X to 2), ), - solutions + solutions, ) assertEquals( ktListOf(), - solver.dynamicKb.toList() + solver.dynamicKb.toList(), ) assertEquals(0L, solver.dynamicKb.size) } @@ -1227,7 +1274,7 @@ internal class TestSolverImpl( assertSolutionEquals( (0 until n).map { query.yes(X to it) }, - solutions + solutions, ) } } @@ -1241,7 +1288,7 @@ internal class TestSolverImpl( assertSolutionEquals( ktListOf(query.yes(X to "a", Y to 2)), - solutions + solutions, ) query = functor("a"("b", "c"), "a", Y) @@ -1249,7 +1296,7 @@ internal class TestSolverImpl( assertSolutionEquals( ktListOf(query.yes(Y to 2)), - solutions + solutions, ) query = functor("a"("b", "c"), X, 2) @@ -1257,7 +1304,7 @@ internal class TestSolverImpl( assertSolutionEquals( ktListOf(query.yes(X to "a")), - solutions + solutions, ) query = functor(X, "a", 2) @@ -1265,7 +1312,7 @@ internal class TestSolverImpl( assertSolutionEquals( ktListOf(query.yes(X to structOf("a", anonymous(), anonymous()))), - solutions + solutions, ) query = functor(X, Y, 2) @@ -1278,11 +1325,11 @@ internal class TestSolverImpl( DummyInstances.executionContext, Signature("functor", 3), variable = Y, - index = 1 - ) - ) + index = 1, + ), + ), ), - solutions + solutions, ) query = functor(X, "a", "2") @@ -1296,11 +1343,11 @@ internal class TestSolverImpl( Signature("functor", 3), TypeError.Expected.INTEGER, atomOf("2"), - 2 - ) - ) + 2, + ), + ), ), - solutions + solutions, ) } } @@ -1314,7 +1361,7 @@ internal class TestSolverImpl( assertSolutionEquals( ktListOf(query.yes(X to listOf("a", "b", "c"))), - solutions + solutions, ) query = X univ listOf("a", "b", "c") @@ -1322,7 +1369,7 @@ internal class TestSolverImpl( assertSolutionEquals( ktListOf(query.yes(X to structOf("a", "b", "c"))), - solutions + solutions, ) query = X univ Y @@ -1335,11 +1382,11 @@ internal class TestSolverImpl( DummyInstances.executionContext, Signature("=..", 2), variable = X, - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) query = "a"("b", "c") univ "a" @@ -1353,23 +1400,25 @@ internal class TestSolverImpl( Signature("=..", 2), TypeError.Expected.LIST, atomOf("a"), - 1 - ) - ) + 1, + ), + ), ), - solutions + solutions, ) } } override fun testRetractAll() { logicProgramming { - val solver = solverFactory.solverWithDefaultBuiltins( - dynamicKb = theoryOf( - factOf(structOf("f", numOf(1))), - ruleOf(structOf("f", numOf(2)), atomOf("false")) + val solver = + solverFactory.solverWithDefaultBuiltins( + dynamicKb = + theoryOf( + factOf(structOf("f", numOf(1))), + ruleOf(structOf("f", numOf(2)), atomOf("false")), + ), ) - ) var query = retractall("f"(X)) @@ -1377,14 +1426,14 @@ internal class TestSolverImpl( assertSolutionEquals( ktListOf( - query.yes() + query.yes(), ), - solutions + solutions, ) assertEquals( ktListOf(), - solver.dynamicKb.toList() + solver.dynamicKb.toList(), ) assertEquals(0L, solver.dynamicKb.size) @@ -1393,9 +1442,9 @@ internal class TestSolverImpl( assertSolutionEquals( ktListOf( - query.yes() + query.yes(), ), - solutions + solutions, ) } } @@ -1409,7 +1458,7 @@ internal class TestSolverImpl( assertSolutionEquals( ktListOf(query.yes(X to listOf(1, 2, 3, 4, 5, 6))), - solutions + solutions, ) query = append(listOf(1, 2, 3), X, listOf(1, 2, 3, 4, 5, 6)) @@ -1417,7 +1466,7 @@ internal class TestSolverImpl( assertSolutionEquals( ktListOf(query.yes(X to listOf(4, 5, 6))), - solutions + solutions, ) query = append(X, X, listOf(1, 2, 3, 4, 5, 6)) @@ -1425,7 +1474,7 @@ internal class TestSolverImpl( assertSolutionEquals( ktListOf(query.no()), - solutions + solutions, ) query = append(X, Y, listOf(1, 2, 3, 4, 5, 6)) @@ -1439,9 +1488,9 @@ internal class TestSolverImpl( query.yes(X to listOf(1, 2, 3), Y to listOf(4, 5, 6)), query.yes(X to listOf(1, 2, 3, 4), Y to listOf(5, 6)), query.yes(X to listOf(1, 2, 3, 4, 5), Y to listOf(6)), - query.yes(X to listOf(1, 2, 3, 4, 5, 6), Y to emptyList) + query.yes(X to listOf(1, 2, 3, 4, 5, 6), Y to emptyList), ), - solutions + solutions, ) } } @@ -1450,7 +1499,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(), greaterThanTesting, - mediumDuration + mediumDuration, ) } @@ -1458,7 +1507,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(), greaterThanOrEqualTesting, - mediumDuration + mediumDuration, ) } @@ -1466,7 +1515,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(), equalTesting, - mediumDuration + mediumDuration, ) } @@ -1474,7 +1523,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(), notEqualTesting, - mediumDuration + mediumDuration, ) } @@ -1482,7 +1531,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(), lowerThanTesting, - mediumDuration + mediumDuration, ) } @@ -1490,7 +1539,7 @@ internal class TestSolverImpl( assertSolverSolutionsCorrect( solverFactory.solverWithDefaultBuiltins(), lowerThanOrEqualTesting, - mediumDuration + mediumDuration, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestStackTrace.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestStackTrace.kt index 4f58eae80..c2eaa5931 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestStackTrace.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestStackTrace.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestStackTrace : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestStackTrace = - TestStackTraceImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestStackTrace = TestStackTraceImpl(solverFactory) } fun testSimpleStackTrace() diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestStackTraceImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestStackTraceImpl.kt index b9e03cb87..c26cb0451 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestStackTraceImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestStackTraceImpl.kt @@ -9,14 +9,14 @@ import it.unibo.tuprolog.solve.exception.error.SystemError import it.unibo.tuprolog.theory.Theory import kotlin.test.assertEquals +@Suppress("LocalVariableName", "ktlint:standard:property-naming") class TestStackTraceImpl(private val solverFactory: SolverFactory) : TestStackTrace { - private fun threeLayersTheory(errorExpression: LogicProgrammingScope.() -> Struct): Theory = logicProgramming { theoryOf( rule { "foo"(X) impliedBy "bar"(X) }, rule { "bar"(X) impliedBy "baz"(X) }, - rule { "baz"(X) impliedBy errorExpression() } + rule { "baz"(X) impliedBy errorExpression() }, ) } @@ -33,15 +33,15 @@ class TestStackTraceImpl(private val solverFactory: SolverFactory) : TestStackTr DummyInstances.executionContext, Signature("+", 2), Y, - index = 0 - ) + index = 0, + ), ), - solution + solution, ) assertEquals( ktListOf("is" / 2, "baz" / 1, "bar" / 1, "foo" / 1, "?-" / 1), - (solution as Solution.Halt).exception.logicStackTrace.map { it.indicator } + (solution as Solution.Halt).exception.logicStackTrace.map { it.indicator }, ) } } @@ -59,15 +59,15 @@ class TestStackTraceImpl(private val solverFactory: SolverFactory) : TestStackTr DummyInstances.executionContext, Signature("+", 2), Y, - index = 0 - ) + index = 0, + ), ), - solution + solution, ) assertEquals( ktListOf("is" / 2, "baz" / 1, "bar" / 1, "foo" / 1, "findall" / 3, "?-" / 1), - (solution as Solution.Halt).exception.logicStackTrace.map { it.indicator } + (solution as Solution.Halt).exception.logicStackTrace.map { it.indicator }, ) } } @@ -85,15 +85,15 @@ class TestStackTraceImpl(private val solverFactory: SolverFactory) : TestStackTr DummyInstances.executionContext, Signature("+", 2), Y, - index = 0 - ) + index = 0, + ), ), - solution + solution, ) assertEquals( ktListOf("is" / 2, "baz" / 1, "bar" / 1, "foo" / 1, "bagof" / 3, "findall" / 3, "?-" / 1), - (solution as Solution.Halt).exception.logicStackTrace.map { it.indicator } + (solution as Solution.Halt).exception.logicStackTrace.map { it.indicator }, ) } } @@ -109,16 +109,16 @@ class TestStackTraceImpl(private val solverFactory: SolverFactory) : TestStackTr SystemError.forUncaughtError( MessageError( context = DummyInstances.executionContext, - extraData = atomOf("x") - ) - ) + extraData = atomOf("x"), + ), + ), ), - solution + solution, ) assertEquals( ktListOf("baz" / 1, "bar" / 1, "foo" / 1, "bagof" / 3, "findall" / 3, "?-" / 1), - (solution as Solution.Halt).exception.logicStackTrace.map { it.indicator } + (solution as Solution.Halt).exception.logicStackTrace.map { it.indicator }, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestStaticFactory.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestStaticFactory.kt index 1f1fd0a4c..d27f0e9a4 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestStaticFactory.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestStaticFactory.kt @@ -1,7 +1,6 @@ package it.unibo.tuprolog.solve interface TestStaticFactory { - companion object { fun prototype(expectations: Expectations): TestStaticFactory = TestStaticFactoryImpl(expectations) } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestStaticFactoryImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestStaticFactoryImpl.kt index 601fa090a..04ceedfe2 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestStaticFactoryImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestStaticFactoryImpl.kt @@ -6,7 +6,7 @@ import kotlin.test.assertNotNull import kotlin.test.assertNotSame import kotlin.test.fail -@Suppress("DEPRECATION") +@Suppress("DEPRECATION", "ConstPropertyName", "ktlint:standard:property-naming") class TestStaticFactoryImpl(private val expectations: Expectations) : TestStaticFactory { companion object { private const val classicSolverClass = "it.unibo.tuprolog.solve.classic.ClassicSolver" @@ -52,7 +52,10 @@ class TestStaticFactoryImpl(private val expectations: Expectations) : TestStatic } } - fun testStaticSolverFactoryShouldWork(`class`: String, factory: () -> SolverFactory) { + fun testStaticSolverFactoryShouldWork( + `class`: String, + factory: () -> SolverFactory, + ) { assertNotNull(factory()) val solver = factory().solverOf() assertNotNull(solver) @@ -64,7 +67,10 @@ class TestStaticFactoryImpl(private val expectations: Expectations) : TestStatic assertClassNameIs(solver2::class, `class`) } - private fun testStaticFactoryShouldFail(name: String, factory: () -> SolverFactory) { + private fun testStaticFactoryShouldFail( + name: String, + factory: () -> SolverFactory, + ) { try { // this may either fail or not on JS, depending on how the tests are launched // while it should always fail on JVM @@ -77,7 +83,7 @@ class TestStaticFactoryImpl(private val expectations: Expectations) : TestStatic // ... in any case, if it fails, an IllegalStateException should be thrown assertEquals( true, - e.message?.startsWith("No viable implementation for SolverFactory") + e.message?.startsWith("No viable implementation for SolverFactory"), ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSubAtom.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSubAtom.kt index 5b8fea4c3..f626ae131 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSubAtom.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSubAtom.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestSubAtom : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestSubAtom = - TestSubAtomImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestSubAtom = TestSubAtomImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSubAtomImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSubAtomImpl.kt index 72e5832bd..6d3faa866 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSubAtomImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSubAtomImpl.kt @@ -15,7 +15,7 @@ class TestSubAtomImpl(private val solverFactory: SolverFactory) : TestSubAtom { assertSolutionEquals( kotlin.collections.listOf(query.yes("S" to atomOf("a"))), - solutions + solutions, ) } } @@ -28,7 +28,7 @@ class TestSubAtomImpl(private val solverFactory: SolverFactory) : TestSubAtom { assertSolutionEquals( kotlin.collections.listOf(query.yes("S" to atomOf("dabra"))), - solutions + solutions, ) } } @@ -41,7 +41,7 @@ class TestSubAtomImpl(private val solverFactory: SolverFactory) : TestSubAtom { assertSolutionEquals( kotlin.collections.listOf(query.yes("S" to atomOf("acada")), query.yes("L" to 5)), - solutions + solutions, ) } } @@ -54,7 +54,7 @@ class TestSubAtomImpl(private val solverFactory: SolverFactory) : TestSubAtom { assertSolutionEquals( kotlin.collections.listOf(query.yes("S" to atomOf("an")), query.yes("T" to 1)), - solutions + solutions, ) } } @@ -72,11 +72,11 @@ class TestSubAtomImpl(private val solverFactory: SolverFactory) : TestSubAtom { DummyInstances.executionContext, Signature("sub_atom", 5), varOf("Banana"), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } @@ -96,11 +96,11 @@ class TestSubAtomImpl(private val solverFactory: SolverFactory) : TestSubAtom { Signature("sub_atom", 5), TypeError.Expected.ATOM, Integer.of("5"), - index = 0 - ) - ) + index = 0, + ), + ), ), - solutions + solutions, ) } } @@ -121,11 +121,11 @@ class TestSubAtomImpl(private val solverFactory: SolverFactory) : TestSubAtom { Signature("sub_atom", 5), TypeError.Expected.ATOM, Integer.of("2"), - index = 4 - ) - ) + index = 4, + ), + ), ), - solutions + solutions, ) } } @@ -146,11 +146,11 @@ class TestSubAtomImpl(private val solverFactory: SolverFactory) : TestSubAtom { Signature("sub_atom", 5), TypeError.Expected.INTEGER, Atom.of("a"), - index = 1 - ) - ) + index = 1, + ), + ), ), - solutions + solutions, ) } } @@ -170,11 +170,11 @@ class TestSubAtomImpl(private val solverFactory: SolverFactory) : TestSubAtom { Signature("sub_atom", 5), TypeError.Expected.INTEGER, Atom.of("n"), - index = 2 - ) - ) + index = 2, + ), + ), ), - solutions + solutions, ) } } @@ -194,11 +194,11 @@ class TestSubAtomImpl(private val solverFactory: SolverFactory) : TestSubAtom { Signature("sub_atom", 5), TypeError.Expected.INTEGER, Atom.of("m"), - index = 3 - ) - ) + index = 3, + ), + ), ), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSubstitutions.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSubstitutions.kt index c98830798..7d35a7b22 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSubstitutions.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSubstitutions.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestSubstitutions : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestSubstitutions = - TestSubstitutionsImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestSubstitutions = TestSubstitutionsImpl(solverFactory) } fun interestingVariablesAreNotObliterated() diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSubstitutionsImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSubstitutionsImpl.kt index 94c71ab41..963948314 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSubstitutionsImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestSubstitutionsImpl.kt @@ -11,16 +11,16 @@ import kotlin.test.assertEquals import kotlin.test.assertIs class TestSubstitutionsImpl(private val solverFactory: SolverFactory) : TestSubstitutions { - private class Inspect( - private val inspections: MutableList> + private val inspections: MutableList>, ) : UnaryPredicate.Predicative("inspect") { override fun Solve.Request.compute(first: Term): Boolean { - inspections += first.variables.distinct() - .map { context.substitution.getOriginal(it) } - .filterNotNull() - .map { it.name } - .toSet() + inspections += + first.variables.distinct() + .map { context.substitution.getOriginal(it) } + .filterNotNull() + .map { it.name } + .toSet() return true } } @@ -33,11 +33,12 @@ class TestSubstitutionsImpl(private val solverFactory: SolverFactory) : TestSubs val inspections = mutableListOf>() logicProgramming { val inspect = Inspect(inspections) - val solver = solverFactory.solverOf( - staticKb = TestingClauseTheories.callsWithVariablesAndInspectorTheory("p", inspect.functor), - libraries = runtimeOf("default", inspect), - flags = FlagStore.EMPTY + TrackVariables { if (tracking) ON else OFF } - ) + val solver = + solverFactory.solverOf( + staticKb = TestingClauseTheories.callsWithVariablesAndInspectorTheory("p", inspect.functor), + libraries = runtimeOf("default", inspect), + flags = FlagStore.EMPTY + TrackVariables { if (tracking) ON else OFF }, + ) val query = "p"(A, B, C) solver.solveOnce(query) } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestTerm.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestTerm.kt index fa1c8339e..caf200f72 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestTerm.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestTerm.kt @@ -5,8 +5,7 @@ package it.unibo.tuprolog.solve */ interface TestTerm : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestTerm = - TestTermImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestTerm = TestTermImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestTermImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestTermImpl.kt index 0516a2635..b4313df86 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestTermImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestTermImpl.kt @@ -12,7 +12,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) query = "\\=="("X", "X") @@ -20,7 +20,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) query = "\\=="(intOf(1), intOf(2)) @@ -28,7 +28,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) query = "\\=="("X", intOf(1)) @@ -36,7 +36,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) query = "\\=="("X", "Y") @@ -44,7 +44,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) query = "\\=="(`_`, `_`) @@ -52,7 +52,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) query = "\\=="("X", "a"("X")) @@ -60,7 +60,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) query = "\\=="("f"("a"), "f"("a")) @@ -68,7 +68,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -82,7 +82,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) query = "=="("X", "X") @@ -90,7 +90,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) query = "=="(intOf(1), intOf(2)) @@ -98,7 +98,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) query = "=="("X", intOf(1)) @@ -106,7 +106,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) query = "=="("X", "Y") @@ -114,7 +114,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) query = "=="(`_`, `_`) @@ -122,7 +122,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) query = "=="("X", "a"("X")) @@ -130,7 +130,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) query = "=="("f"("a"), "f"("a")) @@ -138,7 +138,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -152,7 +152,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) query = "@>"("aardvark", "zebra") @@ -160,7 +160,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) query = "@>"("short", "short") @@ -168,7 +168,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) query = "@>"("short", "shorter") @@ -176,7 +176,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) query = "@>"("foo"("b"), "foo"("a")) @@ -184,7 +184,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) query = "@>"("X", "X") @@ -192,7 +192,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) query = "@>"("foo"("a", "X"), "foo"("b", "Y")) @@ -200,7 +200,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -214,7 +214,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) query = "@>="("aardvark", "zebra") @@ -222,7 +222,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) query = "@>="("short", "short") @@ -230,7 +230,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) query = "@>="("short", "shorter") @@ -238,7 +238,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) query = "@>="("foo"("b"), "foo"("a")) @@ -246,7 +246,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) query = "@>="("X", "X") @@ -254,7 +254,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) query = "@>="("foo"("a", "X"), "foo"("b", "Y")) @@ -262,7 +262,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -276,7 +276,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) query = "@<"("aardvark", "zebra") @@ -284,7 +284,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) query = "@<"("short", "short") @@ -292,7 +292,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) query = "@<"("short", "shorter") @@ -300,7 +300,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) query = "@<"("foo"("b"), "foo"("a")) @@ -308,7 +308,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) query = "@<"("X", "X") @@ -316,7 +316,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) query = "@<"("foo"("a", "X"), "foo"("b", "Y")) @@ -324,7 +324,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -338,7 +338,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) query = "@=<"(realOf(1.1), realOf(1.1)) @@ -346,7 +346,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) query = "@=<"(realOf(1.0), realOf(1.2)) @@ -354,7 +354,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) query = "@=<"(intOf(1), intOf(1)) @@ -362,7 +362,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) query = "@=<"(intOf(1), intOf(2)) @@ -370,7 +370,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) query = "@=<"("aardvark", "zebra") @@ -378,7 +378,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) query = "@=<"("short", "short") @@ -386,7 +386,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) query = "@=<"("short", "shorter") @@ -394,7 +394,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) query = "@=<"("foo"("b"), "foo"("a")) @@ -402,7 +402,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) query = "@=<"("X", "X") @@ -410,7 +410,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) query = "@=<"("foo"("a", "X"), "foo"("b", "Y")) @@ -418,7 +418,7 @@ internal class TestTermImpl(private val solverFactory: SolverFactory) : TestTerm assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestTimeoutImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestTimeoutImpl.kt index fd920afbd..4affa9697 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestTimeoutImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestTimeoutImpl.kt @@ -20,22 +20,24 @@ class TestTimeoutImpl(private val solverFactory: SolverFactory) : TestTimeout { assertSolutionEquals( ktListOf( query.halt( - TimeOutException(context = DummyInstances.executionContext, exceededDuration = shortDuration) - ) + TimeOutException(context = DummyInstances.executionContext, exceededDuration = shortDuration), + ), ), - solutions + solutions, ) } } private fun testInfiniteCollectingGoal(goalProvider: LogicProgrammingScopeWithTheories.() -> Struct) { logicProgramming { - val solver = solverFactory.solverWithDefaultBuiltins( - staticKb = theoryOf( - fact { "nat"("z") }, - rule { "nat"("s"(Z)) impliedBy "nat"(Z) } + val solver = + solverFactory.solverWithDefaultBuiltins( + staticKb = + theoryOf( + fact { "nat"("z") }, + rule { "nat"("s"(Z)) impliedBy "nat"(Z) }, + ), ) - ) solver.assertHasPredicateInAPI(FindAll) val query = goalProvider() @@ -45,10 +47,10 @@ class TestTimeoutImpl(private val solverFactory: SolverFactory) : TestTimeout { assertSolutionEquals( ktListOf( query.halt( - TimeOutException(context = DummyInstances.executionContext, exceededDuration = shortDuration) - ) + TimeOutException(context = DummyInstances.executionContext, exceededDuration = shortDuration), + ), ), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestTrue.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestTrue.kt index 60dbed44d..c1a78d182 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestTrue.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestTrue.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestTrue : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestTrue = - TestTrueImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestTrue = TestTrueImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestTrueImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestTrueImpl.kt index e07a108e0..98651b3a8 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestTrueImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestTrueImpl.kt @@ -12,7 +12,7 @@ internal class TestTrueImpl(private val solverFactory: SolverFactory) : TestTrue assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestUnify.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestUnify.kt index 1f1ae672a..ae524a7fd 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestUnify.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestUnify.kt @@ -2,8 +2,7 @@ package it.unibo.tuprolog.solve interface TestUnify : SolverTest { companion object { - fun prototype(solverFactory: SolverFactory): TestUnify = - TestUnifyImpl(solverFactory) + fun prototype(solverFactory: SolverFactory): TestUnify = TestUnifyImpl(solverFactory) } /** diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestUnifyImpl.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestUnifyImpl.kt index 7c40cb4e5..4c3383551 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestUnifyImpl.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestUnifyImpl.kt @@ -3,7 +3,6 @@ package it.unibo.tuprolog.solve import it.unibo.tuprolog.dsl.theory.logicProgramming internal class TestUnifyImpl(private val solverFactory: SolverFactory) : TestUnify { - override fun testNumberUnify() { logicProgramming { val solver = solverFactory.solverWithDefaultBuiltins() @@ -13,7 +12,7 @@ internal class TestUnifyImpl(private val solverFactory: SolverFactory) : TestUni assertSolutionEquals( kotlin.collections.listOf(query.yes()), - solutions + solutions, ) } } @@ -27,7 +26,7 @@ internal class TestUnifyImpl(private val solverFactory: SolverFactory) : TestUni assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to 1)), - solutions + solutions, ) } } @@ -41,7 +40,7 @@ internal class TestUnifyImpl(private val solverFactory: SolverFactory) : TestUni assertSolutionEquals( kotlin.collections.listOf(query.yes("X" to "Y")), - solutions + solutions, ) } } @@ -55,7 +54,7 @@ internal class TestUnifyImpl(private val solverFactory: SolverFactory) : TestUni assertSolutionEquals( ktListOf(query.yes("X" to "abc", "Y" to "abc")), - solutions + solutions, ) } } @@ -69,7 +68,7 @@ internal class TestUnifyImpl(private val solverFactory: SolverFactory) : TestUni assertSolutionEquals( ktListOf(query.yes("X" to "def", "Y" to "def")), - solutions + solutions, ) } } @@ -83,7 +82,7 @@ internal class TestUnifyImpl(private val solverFactory: SolverFactory) : TestUni assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -97,7 +96,7 @@ internal class TestUnifyImpl(private val solverFactory: SolverFactory) : TestUni assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -111,7 +110,7 @@ internal class TestUnifyImpl(private val solverFactory: SolverFactory) : TestUni assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -125,7 +124,7 @@ internal class TestUnifyImpl(private val solverFactory: SolverFactory) : TestUni assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -139,7 +138,7 @@ internal class TestUnifyImpl(private val solverFactory: SolverFactory) : TestUni assertSolutionEquals( kotlin.collections.listOf(query.no()), - solutions + solutions, ) } } @@ -156,10 +155,10 @@ internal class TestUnifyImpl(private val solverFactory: SolverFactory) : TestUni query.yes( "A" to "g"("g"("g"("D", "D"), "g"("D", "D")), "g"("g"("D", "D"), "g"("D", "D"))), "B" to "g"("g"("D", "D"), "g"("D", "D")), - "C" to "g"("D", "D") - ) + "C" to "g"("D", "D"), + ), ), - solutions + solutions, ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestUtils.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestUtils.kt index 5f616ceb7..8357418b0 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestUtils.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestUtils.kt @@ -30,17 +30,20 @@ import kotlin.test.fail private inline val loggingOn get() = false -fun ktListConcat(l1: List, l2: List): List = l1 + l2 +fun ktListConcat( + l1: List, + l2: List, +): List = l1 + l2 /** Utility function to help writing tests; it creates a mapping between the receiver goal struct and the list of given solutions */ -fun Struct.hasSolutions(vararg solution: Struct.() -> S) = - this to solution.map { it() } +fun Struct.hasSolutions(vararg solution: Struct.() -> S) = this to solution.map { it() } /** Utility function to help writing tests; it creates a [Solution.Yes] with receiver query and provided substitution */ -fun Struct.yes(vararg withSubstitution: Substitution) = Solution.yes( - this, - Substitution.of(withSubstitution.flatMap { s -> s.map { it.toPair() } }) as Substitution.Unifier -) +fun Struct.yes(vararg withSubstitution: Substitution) = + Solution.yes( + this, + Substitution.of(withSubstitution.flatMap { s -> s.map { it.toPair() } }) as Substitution.Unifier, + ) /** Utility function to help writing tests; it creates a [Solution.No] with receiver query */ fun Struct.no() = Solution.no(this) @@ -49,24 +52,27 @@ fun Struct.no() = Solution.no(this) fun Struct.halt(withException: ResolutionException) = Solution.halt(this, withException) /** Utility function to help writing tests; it forwards the `copy` method call to subclasses changing only the `query` field */ -fun Solution.changeQueryTo(query: Struct) = whenIs( - yes = { it.copy(query) }, - no = { it.copy(query) }, - halt = { it.copy(query) } -) +fun Solution.changeQueryTo(query: Struct) = + whenIs( + yes = { it.copy(query) }, + no = { it.copy(query) }, + halt = { it.copy(query) }, + ) /** Utility function to help writing tests; applies [changeQueryTo] to all [Solution]s in receiver iterable */ fun Iterable.changeQueriesTo(query: Struct) = map { it.changeQueryTo(query) } /** Utility function to assert [assertion] over thrown exception by [throwExpression] */ -inline fun assertOverFailure(throwExpression: () -> Unit, assertion: (E) -> Unit) = - try { - throwExpression() - fail("Expected an Exception to be thrown!") - } catch (error: Throwable) { - assertTrue("Thrown error `${error::class}` is not of expected type `${E::class}`") { error is E } - assertion(error as E) - } +inline fun assertOverFailure( + throwExpression: () -> Unit, + assertion: (E) -> Unit, +) = try { + throwExpression() + fail("Expected an Exception to be thrown!") +} catch (error: Throwable) { + assertTrue("Thrown error `${error::class}` is not of expected type `${E::class}`") { error is E } + assertion(error as E) +} /** * Utility method to assert that two [Solution]s are equals, with some exceptions. @@ -76,15 +82,25 @@ inline fun assertOverFailure(throwExpression: () -> Unit * 2) In case a substitution points to a variable or a term containing variables (i.e. `X/Y` or `X/a(Y)` ), * **these variables are compared only by name**, because instances will differ */ -fun assertSolutionEquals(expected: Solution, actual: Solution) { - fun reportMsg(expected: Any, actual: Any, motivation: String = "") = - "Expected: `$expected`\nActual\t: `$actual`" + if (motivation.isNotBlank()) " ($motivation)" else "" - - fun assertSameClass(expected: Solution, actual: Solution) = - assertEquals(expected::class, actual::class, reportMsg(expected, actual)) - - fun assertSameQuery(expected: Solution, actual: Solution) = - assertEquals(expected.query, actual.query, reportMsg(expected, actual)) +fun assertSolutionEquals( + expected: Solution, + actual: Solution, +) { + fun reportMsg( + expected: Any, + actual: Any, + motivation: String = "", + ) = "Expected: `$expected`\nActual\t: `$actual`" + if (motivation.isNotBlank()) " ($motivation)" else "" + + fun assertSameClass( + expected: Solution, + actual: Solution, + ) = assertEquals(expected::class, actual::class, reportMsg(expected, actual)) + + fun assertSameQuery( + expected: Solution, + actual: Solution, + ) = assertEquals(expected.query, actual.query, reportMsg(expected, actual)) when { expected is Solution.Halt -> { @@ -95,7 +111,7 @@ fun assertSolutionEquals(expected: Solution, actual: Solution) { assertEquals( expected.exception::class, (actual as Solution.Halt).exception::class, - reportMsg(expected, actual, "Wrong exception type") + reportMsg(expected, actual, "Wrong exception type"), ) when (val expectedEx = expected.exception) { is LogicError -> { @@ -103,8 +119,8 @@ fun assertSolutionEquals(expected: Solution, actual: Solution) { reportMsg( expected, actual, - "Exception is not LogicError" - ) + "Exception is not LogicError", + ), ) { actual.exception is LogicError } val actualEx = actual.exception as LogicError assertTrue(reportMsg(expected, actual, "The error structs do not match")) { @@ -113,7 +129,7 @@ fun assertSolutionEquals(expected: Solution, actual: Solution) { assertEquals( expectedEx.message, actualEx.message, - reportMsg(expected, actual, "Different messages") + reportMsg(expected, actual, "Different messages"), ) } } @@ -133,7 +149,7 @@ fun assertSolutionEquals(expected: Solution, actual: Solution) { assertEquals( termExpected.variables.map { it.name }.toList(), termActual.variables.map { it.name }.toList(), - "Comparing variable names of expected `$expected` with `$actual`" + "Comparing variable names of expected `$expected` with `$actual`", ) } } @@ -151,7 +167,7 @@ fun assertSolutionEquals(expected: Solution, actual: Solution) { inline fun assertSolutionEquals( expected: Iterable, actual: Iterable, - equalityAssertion: (Solution, Solution) -> Unit = ::assertSolutionEquals + equalityAssertion: (Solution, Solution) -> Unit = ::assertSolutionEquals, ) { assertEquals(expected.count(), actual.count(), "Expected: `${expected.toList()}`\nActual: `${actual.toList()}`") @@ -162,7 +178,7 @@ inline fun assertSolutionEquals( fun assertSolverSolutionsCorrect( solver: Solver, goalToSolutions: List>>, - maxDuration: TimeDuration + maxDuration: TimeDuration, ) { goalToSolutions.forEach { (goal, solutionList) -> if (loggingOn) solver.logKBs() @@ -186,7 +202,11 @@ fun Solver.assertHasPredicateInAPI(signature: Signature) { assertHasPredicateInAPI(signature.name, signature.arity, signature.vararg) } -fun Solver.assertHasPredicateInAPI(functor: String, arity: Int, vararg: Boolean = false) { +fun Solver.assertHasPredicateInAPI( + functor: String, + arity: Int, + vararg: Boolean = false, +) { val varargMsg = if (vararg) "(vararg) " else "" assertTrue("Missing predicate $functor/$arity ${varargMsg}in solver API") { Signature(functor, arity, vararg) in libraries @@ -201,7 +221,10 @@ fun Solver.logKBs() { } /** Utility function to log passed goal and solutions */ -fun logGoalAndSolutions(goal: Struct, solutions: Iterable) { +fun logGoalAndSolutions( + goal: Struct, + solutions: Iterable, +) { println("?- $goal.") solutions.forEach { when (it) { @@ -220,7 +243,10 @@ expect fun internalsOf(x: () -> Any): String expect fun log(x: () -> Any): Unit -expect fun assertClassNameIs(`class`: KClass, name: String) +expect fun assertClassNameIs( + klass: KClass, + name: String, +) fun Solver.assertHas( libraries: Runtime, @@ -228,7 +254,7 @@ fun Solver.assertHas( dynamicKb: Theory, flags: FlagStore, inputs: InputStore, - outputs: OutputStore + outputs: OutputStore, ) { assertRuntimesAreEqual(libraries, this.libraries) assertEquals(staticKb, this.staticKb) @@ -238,7 +264,10 @@ fun Solver.assertHas( assertChannelStoresAreEquals(outputs, this.outputChannels) } -internal fun assertRuntimesAreEqual(expected: Runtime, actual: Runtime) { +internal fun assertRuntimesAreEqual( + expected: Runtime, + actual: Runtime, +) { assertEquals(expected.keys, actual.keys) for ((alias, e) in expected) { val a = actual[alias] @@ -247,7 +276,10 @@ internal fun assertRuntimesAreEqual(expected: Runtime, actual: Runtime) { } } -internal fun assertLibrariesAreEqual(expected: Library, actual: Library) { +internal fun assertLibrariesAreEqual( + expected: Library, + actual: Library, +) { assertEquals(expected.alias, actual.alias) assertEquals(expected.clauses, actual.clauses) assertEquals(expected.operators, actual.operators) @@ -257,7 +289,7 @@ internal fun assertLibrariesAreEqual(expected: Library, actual: Library) { assertEquals( expected = e, actual = a, - message = "Wrong primitive: $signature. Expected $e, actual $a." + message = "Wrong primitive: $signature. Expected $e, actual $a.", ) } assertEquals(expected.functions.keys, actual.functions.keys) @@ -266,21 +298,27 @@ internal fun assertLibrariesAreEqual(expected: Library, actual: Library) { assertEquals( expected = e, actual = a, - message = "Wrong function: $signature. Expected $e, actual $a." + message = "Wrong function: $signature. Expected $e, actual $a.", ) } } -internal fun > assertChannelAreEquals(expected: C, actual: C) { +internal fun > assertChannelAreEquals( + expected: C, + actual: C, +) { assertEquals( expected::class, actual::class, - message = "Wrong channel type. Expected ${expected::class}, actual ${actual::class}" + message = "Wrong channel type. Expected ${expected::class}, actual ${actual::class}", ) assertEquals(expected.isClosed, actual.isClosed) } -internal fun , CS : ChannelStore<*, C, CS>> assertChannelStoresAreEquals(expected: CS, actual: CS) { +internal fun , CS : ChannelStore<*, C, CS>> assertChannelStoresAreEquals( + expected: CS, + actual: CS, +) { assertEquals(expected.keys, actual.keys) for (alias in expected.keys) { assertChannelAreEquals(expected[alias]!!, actual[alias]!!) diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestingClauseTheories.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestingClauseTheories.kt index 61f05bcc7..be357de7f 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestingClauseTheories.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestingClauseTheories.kt @@ -19,51 +19,71 @@ import it.unibo.tuprolog.theory.Theory * @author Enrico */ object TestingClauseTheories { - internal val aContext = DummyInstances.executionContext internal val haltException = HaltException(context = aContext) - internal fun instantiationError(functor: String, arity: Int, culprit: Var, index: Int? = null) = - instantiationError(Signature(functor, arity), culprit, index) - - internal fun instantiationError(signature: Signature, culprit: Var, index: Int? = null) = - if (index != null) { - InstantiationError.forArgument(aContext, signature, culprit, index) - } else { - InstantiationError.forGoal(aContext, signature, culprit) - } - - internal fun typeError(functor: String, arity: Int, actualValue: Term, index: Int? = null) = - typeError(Signature(functor, arity), actualValue, index) + internal fun instantiationError( + functor: String, + arity: Int, + culprit: Var, + index: Int? = null, + ) = instantiationError(Signature(functor, arity), culprit, index) + + internal fun instantiationError( + signature: Signature, + culprit: Var, + index: Int? = null, + ) = if (index != null) { + InstantiationError.forArgument(aContext, signature, culprit, index) + } else { + InstantiationError.forGoal(aContext, signature, culprit) + } - internal fun typeError(signature: Signature, actualValue: Term, index: Int? = null) = - if (index != null) { - TypeError.forArgument(aContext, signature, TypeError.Expected.CALLABLE, actualValue, index) - } else { - TypeError.forGoal(aContext, signature, TypeError.Expected.CALLABLE, actualValue) - } + internal fun typeError( + functor: String, + arity: Int, + actualValue: Term, + index: Int? = null, + ) = typeError(Signature(functor, arity), actualValue, index) + + internal fun typeError( + signature: Signature, + actualValue: Term, + index: Int? = null, + ) = if (index != null) { + TypeError.forArgument(aContext, signature, TypeError.Expected.CALLABLE, actualValue, index) + } else { + TypeError.forGoal(aContext, signature, TypeError.Expected.CALLABLE, actualValue) + } internal fun systemError(uncaught: Term) = SystemError.forUncaughtException(aContext, uncaught) internal val timeOutException = TimeOutException(context = aContext, exceededDuration = 1) /** Utility function to deeply replace all occurrences of one functor with another in a Struct */ - internal fun Struct.replaceAllFunctors(oldFunctor: String, withFunctor: String): Struct = + internal fun Struct.replaceAllFunctors( + oldFunctor: String, + withFunctor: String, + ): Struct = logicProgramming { - val synonymReplacer = object : TermVisitor { - override fun defaultValue(term: Term): Term = term - override fun visitStruct(term: Struct): Term = when (term.functor) { - oldFunctor -> withFunctor(term.args.single().accept(this)) - else -> term.args.map { it.accept(this) }.let { - if (it.none()) { - term - } else { - term.functor(it.first(), *it.drop(1).toTypedArray()) + val synonymReplacer = + object : TermVisitor { + override fun defaultValue(term: Term): Term = term + + override fun visitStruct(term: Struct): Term = + when (term.functor) { + oldFunctor -> withFunctor(term.args.single().accept(this)) + else -> + term.args.map { it.accept(this) }.let { + if (it.none()) { + term + } else { + term.functor(it.first(), *it.drop(1).toTypedArray()) + } + } } - } } - } this@replaceAllFunctors.accept(synonymReplacer) as Struct } @@ -87,7 +107,7 @@ object TestingClauseTheories { { "g"("b") }, { "h"("a") }, { "h"("b") }, - { "h"("c") } + { "h"("c") }, ) } } @@ -104,7 +124,7 @@ object TestingClauseTheories { rule { "a"(A) `if` ("b"(A) and "d"(Z)) }, rule { "b"(B) `if` ("c"(B) and "d"(W)) }, fact { "d"(`_`) }, - fact { "c"(1) } + fact { "c"(1) }, ) } } @@ -119,21 +139,23 @@ object TestingClauseTheories { * ([f(A), f(B), f(C), f(D), f(E)]). * ``` */ - fun callsWithVariablesAndInspectorTheory(predicate: String, observe: String) = - logicProgramming { - val observeOne = "${observe}_one" - theoryOf( - rule { observeOne(X) `if` observe(listOf(X)) }, - rule { - predicate(A, B, C).`if`( - observe(listOf(A, B, C)), - observeOne(D), - observeOne(E), - observe(listOf("f"(A), "f"(B), "f"(C), "f"(D), "f"(E))) - ) - } - ) - } + fun callsWithVariablesAndInspectorTheory( + predicate: String, + observe: String, + ) = logicProgramming { + val observeOne = "${observe}_one" + theoryOf( + rule { observeOne(X) `if` observe(listOf(X)) }, + rule { + predicate(A, B, C).`if`( + observe(listOf(A, B, C)), + observeOne(D), + observeOne(E), + observe(listOf("f"(A), "f"(B), "f"(C), "f"(D), "f"(E))), + ) + }, + ) + } /** * Notable [simpleFactTheory] request goals and respective expected [Solution]s @@ -147,17 +169,17 @@ object TestingClauseTheories { logicProgramming { ktListOf( "f"("A").hasSolutions( - { yes("A" to "a") } + { yes("A" to "a") }, ), "g"("A").hasSolutions( { yes("A" to "a") }, - { yes("A" to "b") } + { yes("A" to "b") }, ), "h"("A").hasSolutions( { yes("A" to "a") }, { yes("A" to "b") }, - { yes("A" to "c") } - ) + { yes("A" to "c") }, + ), ) } } @@ -180,23 +202,22 @@ object TestingClauseTheories { * d(d). * ``` */ - val simpleCutTheory = logicProgramming { - theory( - { "f"("only") `if` "!" }, - { "f"("a") }, - - { "g"("a") }, - { "g"("only") `if` "!" }, - { "g"("b") }, - - { "h"("A") `if` "e"("A") }, - { "h"("A") `if` "d"("A") }, - { "e"("a") `if` "!" }, - { "e"("b") }, - { "d"("c") }, - { "d"("d") } - ) - } + val simpleCutTheory = + logicProgramming { + theory( + { "f"("only") `if` "!" }, + { "f"("a") }, + { "g"("a") }, + { "g"("only") `if` "!" }, + { "g"("b") }, + { "h"("A") `if` "e"("A") }, + { "h"("A") `if` "d"("A") }, + { "e"("a") `if` "!" }, + { "e"("b") }, + { "d"("c") }, + { "d"("d") }, + ) + } /** * Notable [simpleCutTheory] request goals and respective expected [Solution]s @@ -210,17 +231,17 @@ object TestingClauseTheories { logicProgramming { ktListOf( "f"("A").hasSolutions( - { yes("A" to "only") } + { yes("A" to "only") }, ), "g"("A").hasSolutions( { yes("A" to "a") }, - { yes("A" to "only") } + { yes("A" to "only") }, ), "h"("A").hasSolutions( { yes("A" to "a") }, { yes("A" to "c") }, - { yes("A" to "d") } - ) + { yes("A" to "d") }, + ), ) } } @@ -236,16 +257,17 @@ object TestingClauseTheories { * r(b1). * ``` */ - val simpleCutAndConjunctionTheory = logicProgramming { - theory( - { "f"("X", "Y") `if` ("q"("X") and "!" and "r"("Y")) }, - { "f"("X", "Y") `if` "r"("X") }, - { "q"("a") }, - { "q"("b") }, - { "r"("a1") }, - { "r"("b1") } - ) - } + val simpleCutAndConjunctionTheory = + logicProgramming { + theory( + { "f"("X", "Y") `if` ("q"("X") and "!" and "r"("Y")) }, + { "f"("X", "Y") `if` "r"("X") }, + { "q"("a") }, + { "q"("b") }, + { "r"("a1") }, + { "r"("b1") }, + ) + } /** * Notable [simpleCutAndConjunctionTheory] request goals and respective expected [Solution]s @@ -258,8 +280,8 @@ object TestingClauseTheories { ktListOf( "f"("A", "B").hasSolutions( { yes("A" to "a", "B" to "a1") }, - { yes("A" to "a", "B" to "b1") } - ) + { yes("A" to "a", "B" to "b1") }, + ), ) } } @@ -279,20 +301,21 @@ object TestingClauseTheories { * d(3). * ``` */ - val cutConjunctionAndBacktrackingTheory = logicProgramming { - theory( - { "a"("X") `if` "b"("X") }, - { "a"(6) }, - { "b"("X") `if` ("c"("X") and "d"("X")) }, - { "b"(4) `if` "!" }, - { "b"(5) }, - { "c"(1) }, - { "c"(2) `if` "!" }, - { "c"(3) }, - { "d"(2) }, - { "d"(3) } - ) - } + val cutConjunctionAndBacktrackingTheory = + logicProgramming { + theory( + { "a"("X") `if` "b"("X") }, + { "a"(6) }, + { "b"("X") `if` ("c"("X") and "d"("X")) }, + { "b"(4) `if` "!" }, + { "b"(5) }, + { "c"(1) }, + { "c"(2) `if` "!" }, + { "c"(3) }, + { "d"(2) }, + { "d"(3) }, + ) + } /** * Notable [cutConjunctionAndBacktrackingTheory] request goals and respective expected [Solution]s @@ -306,8 +329,8 @@ object TestingClauseTheories { "a"("X").hasSolutions( { yes("X" to 2) }, { yes("X" to 4) }, - { yes("X" to 6) } - ) + { yes("X" to 6) }, + ), ) } } @@ -319,12 +342,13 @@ object TestingClauseTheories { * b :- a. * ``` */ - val infiniteComputationTheory = logicProgramming { - theory( - { "a" `if` "b" }, - { "b" `if` "a" } - ) - } + val infiniteComputationTheory = + logicProgramming { + theory( + { "a" `if` "b" }, + { "b" `if` "a" }, + ) + } /** * Notable [infiniteComputationTheory] request goals and respective expected [Solution]s @@ -335,7 +359,7 @@ object TestingClauseTheories { val infiniteComputationTheoryNotableGoalToSolution by lazy { logicProgramming { ktListOf( - atomOf("a").hasSolutions({ halt(timeOutException) }) + atomOf("a").hasSolutions({ halt(timeOutException) }), ) } } @@ -358,7 +382,7 @@ object TestingClauseTheories { { "my_rev"(consOf("X", "Xs"), "L2", "Acc") `if` "my_rev"("Xs", "L2", consOf("X", "Acc")) - } + }, ) } } @@ -373,8 +397,8 @@ object TestingClauseTheories { logicProgramming { ktListOf( "my_reverse"(listOf(1, 2, 3, 4), "L").hasSolutions( - { yes("L" to listOf(4, 3, 2, 1)) } - ) + { yes("L" to listOf(4, 3, 2, 1)) }, + ), ) } } @@ -399,8 +423,8 @@ object TestingClauseTheories { "<"("M", "N") and ("M1" `is` (varOf("M") + 1)) and "range"("M1", "N", "Ns") - ) - } + ) + }, ) } } @@ -417,6 +441,7 @@ object TestingClauseTheories { * ?- range(2, A, [2, 3, 4]). * ``` */ + @Suppress("LocalVariableName", "ktlint:standard:property-naming") val customRangeListGeneratorTheoryNotableGoalToSolution by lazy { val N = customRangeListGeneratorTheory.last().head!![1] as Var logicProgramming { @@ -428,8 +453,8 @@ object TestingClauseTheories { "range"(2, 1, "L").hasSolutions({ no() }), "range"("A", 4, listOf(2, 3, 4)).hasSolutions({ yes("A" to 2) }), "range"(2, "A", listOf(2, 3, 4)).hasSolutions( - { halt(instantiationError("<", 2, N, 1)) } - ) + { halt(instantiationError("<", 2, N, 1)) }, + ), ) } } @@ -457,7 +482,7 @@ object TestingClauseTheories { call("true" and "true").hasSolutions({ yes() }), call(cut).hasSolutions({ yes() }), call("X").hasSolutions({ halt(instantiationError(errorSignature, varOf("X"))) }), - call("true" and 1).hasSolutions({ halt(typeError(errorSignature, ("true" and 1))) }) + call("true" and 1).hasSolutions({ halt(typeError(errorSignature, ("true" and 1))) }), ) } @@ -480,10 +505,10 @@ object TestingClauseTheories { catch(catch(`throw`("external"("deepBall")), "internal"("I"), false), "external"("E"), true) .hasSolutions({ yes("E" to "deepBall") }), catch(`throw`("first"), "X", `throw`("second")).hasSolutions( - { halt(systemError(atomOf("second"))) } + { halt(systemError(atomOf("second"))) }, ), catch(`throw`("hello"), "X", true).hasSolutions({ yes("X" to "hello") }), - catch(`throw`("hello") and false, "X", true).hasSolutions({ yes("X" to "hello") }) + catch(`throw`("hello") and false, "X", true).hasSolutions({ yes("X" to "hello") }), ) } } @@ -504,8 +529,8 @@ object TestingClauseTheories { halt.hasSolutions({ halt(haltException) }), catch(halt, `_`, true).hasSolutions({ halt(haltException) }), catch(catch(`throw`("something"), `_`, halt), `_`, true).hasSolutions( - { halt(haltException) } - ) + { halt(haltException) }, + ), ) } } @@ -514,7 +539,7 @@ object TestingClauseTheories { fun allPrologTestingTheoriesToRespectiveGoalsAndSolutions( callErrorSignature: Signature, nafErrorSignature: Signature, - notErrorSignature: Signature + notErrorSignature: Signature, ) = mapOf( simpleFactTheory to simpleFactTheoryNotableGoalToSolutions, simpleCutTheory to simpleCutTheoryNotableGoalToSolutions, @@ -523,10 +548,11 @@ object TestingClauseTheories { customReverseListTheory to customReverseListTheoryNotableGoalToSolution, Theory.empty() to callTestingGoalsToSolutions(callErrorSignature), Theory.empty() to catchTestingGoalsToSolutions, - Theory.empty() to haltTestingGoalsToSolutions - ) + allPrologStandardTestingTheoryToRespectiveGoalsAndSolutions( - callErrorSignature, - nafErrorSignature, - notErrorSignature - ) + Theory.empty() to haltTestingGoalsToSolutions, + ) + + allPrologStandardTestingTheoryToRespectiveGoalsAndSolutions( + callErrorSignature, + nafErrorSignature, + notErrorSignature, + ) } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestingTermOperators.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestingTermOperators.kt index 36795189f..f9764e1b9 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestingTermOperators.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TestingTermOperators.kt @@ -3,7 +3,6 @@ package it.unibo.tuprolog.solve import it.unibo.tuprolog.dsl.theory.logicProgramming object TestingTermOperators { - /** * Standard operator greater than * @@ -21,7 +20,7 @@ object TestingTermOperators { "@>"(intOf(1), realOf(1.0)).hasSolutions({ yes() }), "@>"(realOf(1.0), intOf(1)).hasSolutions({ no() }), "@>"("stringTestA", "stringTestZ").hasSolutions({ no() }), - "@>"("stringTest", intOf(1)).hasSolutions({ yes() }) + "@>"("stringTest", intOf(1)).hasSolutions({ yes() }), ) } } @@ -44,8 +43,8 @@ object TestingTermOperators { "@>="("stringTest", "stringTest").hasSolutions({ yes() }), "@>="("stringTest", "stringTest1").hasSolutions({ no() }), "@>="("stringTest", intOf(1)).hasSolutions( - { yes() } - ) + { yes() }, + ), ) } } @@ -65,7 +64,7 @@ object TestingTermOperators { ktListOf( "=@="(realOf(1.0), realOf(1.0)).hasSolutions({ yes() }), "=@="("stringTest", "stringTest").hasSolutions({ yes() }), - "=@="("stringTest", realOf(1.0)).hasSolutions({ no() }) + "=@="("stringTest", realOf(1.0)).hasSolutions({ no() }), ) } } @@ -88,7 +87,7 @@ object TestingTermOperators { "@<"(realOf(1.0), intOf(1)).hasSolutions({ yes() }), "@<"(intOf(1), realOf(1.0)).hasSolutions({ no() }), "@<"("stringTestA", "stringTestZ").hasSolutions({ yes() }), - "@<"(intOf(1), "stringTest").hasSolutions({ yes() }) + "@<"(intOf(1), "stringTest").hasSolutions({ yes() }), ) } } @@ -108,7 +107,7 @@ object TestingTermOperators { ktListOf( "@=<"(intOf(1), realOf(1.0)).hasSolutions({ no() }), "@=<"(realOf(1.0), realOf(1.0)).hasSolutions({ yes() }), - "@=<"("stringTest", "stringTest").hasSolutions({ yes() }) + "@=<"("stringTest", "stringTest").hasSolutions({ yes() }), ) } } @@ -128,7 +127,7 @@ object TestingTermOperators { ktListOf( "\\=@="(realOf(1.0), realOf(1.0)).hasSolutions({ no() }), "\\=@="("stringTest", "stringTest").hasSolutions({ no() }), - "\\=@="("stringTest", realOf(1.0)).hasSolutions({ yes() }) + "\\=@="("stringTest", realOf(1.0)).hasSolutions({ yes() }), ) } } diff --git a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TimeRelatedTheories.kt b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TimeRelatedTheories.kt index 30349a1db..364d24b45 100644 --- a/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TimeRelatedTheories.kt +++ b/test-solve/src/commonMain/kotlin/it/unibo/tuprolog/solve/TimeRelatedTheories.kt @@ -23,7 +23,7 @@ object TimeRelatedTheories { rule { "a"("X") `if` "b"("X") }, rule { "b"(500) `if` "sleep"(500) }, rule { "b"(600) `if` "sleep"(600) }, - rule { "b"(700) `if` "sleep"(700) } + rule { "b"(700) `if` "sleep"(700) }, ) } } @@ -37,8 +37,8 @@ object TimeRelatedTheories { logicProgramming { ktListOf( "a"("X").hasSolutions( - { halt(timeOutException) } - ) + { halt(timeOutException) }, + ), ) } } @@ -54,8 +54,8 @@ object TimeRelatedTheories { ktListOf( "a"("X").hasSolutions( { yes("X" to 500) }, - { halt(timeOutException) } - ) + { halt(timeOutException) }, + ), ) } } @@ -72,8 +72,8 @@ object TimeRelatedTheories { "a"("X").hasSolutions( { yes("X" to 500) }, { yes("X" to 600) }, - { halt(timeOutException) } - ) + { halt(timeOutException) }, + ), ) } } @@ -89,8 +89,8 @@ object TimeRelatedTheories { "a"("X").hasSolutions( { yes("X" to 500) }, { yes("X" to 600) }, - { yes("X" to 700) } - ) + { yes("X" to 700) }, + ), ) } } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolutionTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolutionTest.kt index 40834d864..5a8b907d2 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolutionTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolutionTest.kt @@ -19,7 +19,6 @@ import kotlin.test.assertNull * @author Enrico */ internal class SolutionTest { - @Test fun yesSolutionContainsInsertedData() { val toBeTested = Solution.yes(aQuery, aSubstitution) diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveRequestTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveRequestTest.kt index 90f64b671..d81108950 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveRequestTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveRequestTest.kt @@ -36,20 +36,20 @@ import kotlin.test.assertTrue * @author Enrico */ internal class SolveRequestTest { - companion object { private const val TOLERANCE = 10L } @Test fun requestInsertedDataCorrect() { - val toBeTested = Solve.Request( - aSignature, - anArgumentList, - anExecutionContext, - aRequestIssuingInstant, - anExecutionMaxDuration - ) + val toBeTested = + Solve.Request( + aSignature, + anArgumentList, + anExecutionContext, + aRequestIssuingInstant, + anExecutionMaxDuration, + ) assertEquals(aSignature, toBeTested.signature) assertEquals(anArgumentList, toBeTested.arguments) @@ -100,7 +100,7 @@ internal class SolveRequestTest { assertEquals(Struct.of(aSignature.name, anArgumentList), createRequest(aSignature, anArgumentList).query) assertEquals( Struct.of(aVarargSignature.name, varargArgumentList), - createRequest(aVarargSignature, varargArgumentList).query + createRequest(aVarargSignature, varargArgumentList).query, ) } @@ -116,14 +116,14 @@ internal class SolveRequestTest { assertEquals( createRequest().replyWith( it.solution, - aSideEffectManager + aSideEffectManager, ) { resetRuntime(differentLibraries) resetFlags(differentFlags) resetStaticKb(differentStaticKB) resetDynamicKb(differentDynamicKB) }, - it + it, ) } } @@ -133,14 +133,14 @@ internal class SolveRequestTest { assertEquals( createRequest().replySuccess( solutionSubstitution, - aSideEffectManager + aSideEffectManager, ) { resetRuntime(differentLibraries) resetFlags(differentFlags) resetStaticKb(differentStaticKB) resetDynamicKb(differentDynamicKB) }, - defaultRequestSuccessResponse + defaultRequestSuccessResponse, ) } @@ -148,14 +148,14 @@ internal class SolveRequestTest { fun replyFailCreatesCorrectResponse() { assertEquals( createRequest().replyFail( - aSideEffectManager + aSideEffectManager, ) { resetRuntime(differentLibraries) resetFlags(differentFlags) resetStaticKb(differentStaticKB) resetDynamicKb(differentDynamicKB) }, - defaultRequestFailedResponse + defaultRequestFailedResponse, ) } @@ -164,14 +164,14 @@ internal class SolveRequestTest { assertEquals( createRequest().replyException( solutionException, - aSideEffectManager + aSideEffectManager, ) { resetRuntime(differentLibraries) resetFlags(differentFlags) resetStaticKb(differentStaticKB) resetDynamicKb(differentDynamicKB) }, - defaultRequestHaltedResponse + defaultRequestHaltedResponse, ) } @@ -180,7 +180,7 @@ internal class SolveRequestTest { assertEquals( createRequest().replyWith( true, - aSideEffectManager + aSideEffectManager, ) { resetRuntime(differentLibraries) resetFlags(differentFlags) @@ -188,23 +188,24 @@ internal class SolveRequestTest { resetDynamicKb(differentDynamicKB) }, defaultRequestSuccessResponse.copy( - solution = (defaultRequestSuccessResponse.solution as Solution.Yes).copy( - substitution = Substitution.empty() - ) - ) + solution = + (defaultRequestSuccessResponse.solution as Solution.Yes).copy( + substitution = Substitution.empty(), + ), + ), ) assertEquals( createRequest().replyWith( false, - aSideEffectManager + aSideEffectManager, ) { resetRuntime(differentLibraries) resetFlags(differentFlags) resetStaticKb(differentStaticKB) resetDynamicKb(differentDynamicKB) }, - defaultRequestFailedResponse + defaultRequestFailedResponse, ) } } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveResponseTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveResponseTest.kt index 19116897b..620765f0d 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveResponseTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/SolveResponseTest.kt @@ -14,7 +14,6 @@ import kotlin.test.assertNull * @author Enrico */ internal class SolveResponseTest { - private val aResponse = Solve.Response(aSolution, aSideEffectManager, someSideEffects) diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/TimeRepresentationKtTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/TimeRepresentationKtTest.kt index 9f77d86cd..d368756e2 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/TimeRepresentationKtTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/TimeRepresentationKtTest.kt @@ -9,7 +9,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class TimeRepresentationKtTest { - @Test fun currentTimeBehavesAsExpected() { val startTime = currentTimeInstant() diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/UtilsTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/UtilsTest.kt index 36be9f8e0..61c63535d 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/UtilsTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/UtilsTest.kt @@ -11,7 +11,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class UtilsTest { - @Test fun foreachWithLookAheadWorksExactlyLikeNormalForeach() { // should not launch exception diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/HaltExceptionTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/HaltExceptionTest.kt index 61dc17283..b4c58eeca 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/HaltExceptionTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/HaltExceptionTest.kt @@ -15,7 +15,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class HaltExceptionTest { - private val exception = HaltException(anExitStatus, aMessage, aCause, aContext) @Test diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/LogicErrorTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/LogicErrorTest.kt index 1d6edd4c5..bdd1b74b1 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/LogicErrorTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/LogicErrorTest.kt @@ -20,23 +20,36 @@ import kotlin.test.assertNull * @author Enrico */ internal class LogicErrorTest { - /** A non specific LogicError instance */ - private val underTestPrologError = object : LogicError(aMessage, aCause, aContext, aType, someExtraData) { - override fun updateContext(newContext: ExecutionContext, index: Int): LogicError = - of(this.message, this.cause, this.contexts.setItem(index, newContext), this.type, this.extraData) + private val underTestPrologError = + object : LogicError(aMessage, aCause, aContext, aType, someExtraData) { + override fun updateContext( + newContext: ExecutionContext, + index: Int, + ): LogicError = + of( + this.message, + this.cause, + this.contexts.setItem(index, newContext), + this.type, + this.extraData, + ) - override fun updateLastContext(newContext: ExecutionContext): LogicError = - updateContext(newContext, contexts.lastIndex) + override fun updateLastContext(newContext: ExecutionContext): LogicError = + updateContext( + newContext, + contexts.lastIndex, + ) - override fun pushContext(newContext: ExecutionContext): LogicError = - of(this.message, this.cause, this.contexts.addLast(newContext), this.type, this.extraData) - } + override fun pushContext(newContext: ExecutionContext): LogicError = + of(this.message, this.cause, this.contexts.addLast(newContext), this.type, this.extraData) + } /** Specific prolog error instances */ - private val logicErrorTypeToInstanceMap = LogicErrorUtils.recognizedSubTypes.map { (typeParam, _) -> - typeParam to LogicError.of(aMessage, aCause, aContext, typeParam, someExtraData) - } + private val logicErrorTypeToInstanceMap = + LogicErrorUtils.recognizedSubTypes.map { (typeParam, _) -> + typeParam to LogicError.of(aMessage, aCause, aContext, typeParam, someExtraData) + } @Test fun holdsInsertedData() { @@ -45,16 +58,29 @@ internal class LogicErrorTest { @Test fun defaultsAreNull() { - val toBeTested = object : LogicError(context = aContext, type = aType) { - override fun updateContext(newContext: ExecutionContext, index: Int): LogicError = - of(this.message, this.cause, this.contexts.setItem(index, newContext), this.type, this.extraData) + val toBeTested = + object : LogicError(context = aContext, type = aType) { + override fun updateContext( + newContext: ExecutionContext, + index: Int, + ): LogicError = + of( + this.message, + this.cause, + this.contexts.setItem(index, newContext), + this.type, + this.extraData, + ) - override fun updateLastContext(newContext: ExecutionContext): LogicError = - updateContext(newContext, contexts.lastIndex) + override fun updateLastContext(newContext: ExecutionContext): LogicError = + updateContext( + newContext, + contexts.lastIndex, + ) - override fun pushContext(newContext: ExecutionContext): LogicError = - of(this.message, this.cause, this.contexts.addLast(newContext), this.type, this.extraData) - } + override fun pushContext(newContext: ExecutionContext): LogicError = + of(this.message, this.cause, this.contexts.addLast(newContext), this.type, this.extraData) + } assertNull(toBeTested.message) assertNull(toBeTested.cause) assertNull(toBeTested.extraData) @@ -62,16 +88,29 @@ internal class LogicErrorTest { @Test fun constructorInsertsMessageIfOnlyCauseSpecified() { - val logicError = object : LogicError(aCause, aContext, aType, someExtraData) { - override fun updateContext(newContext: ExecutionContext, index: Int): LogicError = - of(this.message, this.cause, this.contexts.setItem(index, newContext), this.type, this.extraData) + val logicError = + object : LogicError(aCause, aContext, aType, someExtraData) { + override fun updateContext( + newContext: ExecutionContext, + index: Int, + ): LogicError = + of( + this.message, + this.cause, + this.contexts.setItem(index, newContext), + this.type, + this.extraData, + ) - override fun updateLastContext(newContext: ExecutionContext): LogicError = - updateContext(newContext, contexts.lastIndex) + override fun updateLastContext(newContext: ExecutionContext): LogicError = + updateContext( + newContext, + contexts.lastIndex, + ) - override fun pushContext(newContext: ExecutionContext): LogicError = - of(this.message, this.cause, this.contexts.addLast(newContext), this.type, this.extraData) - } + override fun pushContext(newContext: ExecutionContext): LogicError = + of(this.message, this.cause, this.contexts.addLast(newContext), this.type, this.extraData) + } assertEquals(aCause.toString(), logicError.message) } @@ -81,15 +120,27 @@ internal class LogicErrorTest { assertErrorStructCorrect(underTestPrologError) assertErrorStructCorrect( object : LogicError(context = aContext, type = aType) { - override fun updateContext(newContext: ExecutionContext, index: Int): LogicError = - of(this.message, this.cause, this.contexts.setItem(index, newContext), this.type, this.extraData) + override fun updateContext( + newContext: ExecutionContext, + index: Int, + ): LogicError = + of( + this.message, + this.cause, + this.contexts.setItem(index, newContext), + this.type, + this.extraData, + ) override fun updateLastContext(newContext: ExecutionContext): LogicError = - updateContext(newContext, contexts.lastIndex) + updateContext( + newContext, + contexts.lastIndex, + ) override fun pushContext(newContext: ExecutionContext): LogicError = of(this.message, this.cause, this.contexts.addLast(newContext), this.type, this.extraData) - } + }, ) } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/ResolutionExceptionTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/ResolutionExceptionTest.kt index cd21eebe8..2e88d86c6 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/ResolutionExceptionTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/ResolutionExceptionTest.kt @@ -15,7 +15,6 @@ import kotlin.test.assertSame * @author Enrico */ internal class ResolutionExceptionTest { - private val exception = ResolutionException(aMessage, aCause, aContext) @Test diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/TimeOutExceptionTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/TimeOutExceptionTest.kt index f9500edc3..aa0b9e060 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/TimeOutExceptionTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/TimeOutExceptionTest.kt @@ -15,7 +15,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class TimeOutExceptionTest { - private val exception = TimeOutException(aMessage, aCause, aContext, anExceededTimeDuration) @Test diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/ErrorUtilsTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/ErrorUtilsTest.kt index 4e9fc3b5d..4c479a8aa 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/ErrorUtilsTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/ErrorUtilsTest.kt @@ -11,29 +11,28 @@ import kotlin.test.assertEquals * @author Enrico */ internal class ErrorUtilsTest { - private val errorDescription = Atom.of("myErrorDesc") private val errorExtraData = Atom.of("myExtra") private val defaultCustomErrorData = Atom.of("") @Test fun standardErrorWrapperFunctorCorrect() { - assertEquals("error", ErrorUtils.errorWrapperFunctor) + assertEquals("error", ErrorUtils.ERROR_FUNCTOR) } @Test fun errorStructOfWithArgsCreatesCorrectStruct() { assertEquals( - Struct.of(ErrorUtils.errorWrapperFunctor, errorDescription, errorExtraData), - ErrorUtils.errorStructOf(errorDescription, errorExtraData) + Struct.of(ErrorUtils.ERROR_FUNCTOR, errorDescription, errorExtraData), + ErrorUtils.errorStructOf(errorDescription, errorExtraData), ) } @Test fun errorStructOfWithOnlyFirstArgFillsExtraDataWithTrue() { assertEquals( - Struct.of(ErrorUtils.errorWrapperFunctor, errorDescription, defaultCustomErrorData), - ErrorUtils.errorStructOf(errorDescription) + Struct.of(ErrorUtils.ERROR_FUNCTOR, errorDescription, defaultCustomErrorData), + ErrorUtils.errorStructOf(errorDescription), ) } } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/EvaluationErrorTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/EvaluationErrorTest.kt index 8c9253acb..e23cbe2cf 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/EvaluationErrorTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/EvaluationErrorTest.kt @@ -12,12 +12,12 @@ import kotlin.test.assertEquals * @author Enrico */ internal class EvaluationErrorTest { - private val testErrorType = EvaluationError.Type.FLOAT_OVERFLOW - private val aCallableTypeError = EvaluationError( - context = LogicErrorUtils.aContext, - errorType = testErrorType - ) + private val aCallableTypeError = + EvaluationError( + context = LogicErrorUtils.aContext, + errorType = testErrorType, + ) private val correctTypeFunctor = "evaluation_error" @Test @@ -34,7 +34,7 @@ internal class EvaluationErrorTest { fun evaluationErrorTypeCorrect() { assertEquals( Struct.of(correctTypeFunctor, testErrorType.toTerm()), - aCallableTypeError.type + aCallableTypeError.type, ) } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/EvaluationErrorTypeTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/EvaluationErrorTypeTest.kt index 334057851..86bbe204d 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/EvaluationErrorTypeTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/EvaluationErrorTypeTest.kt @@ -13,7 +13,6 @@ import kotlin.test.assertNull * @author Enrico */ internal class EvaluationErrorTypeTest { - @Test fun evaluationErrorTypeEnumToAtomWorksAsExpected() { EvaluationError.Type.values().forEach { diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/InstantiationErrorTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/InstantiationErrorTest.kt index 5945371bf..fdfc1dd4d 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/InstantiationErrorTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/InstantiationErrorTest.kt @@ -11,7 +11,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class InstantiationErrorTest { - private val underTestError = InstantiationError(context = LogicErrorUtils.aContext) private val correctTypeFunctor = "instantiation_error" diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/SystemErrorTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/SystemErrorTest.kt index a138f4dac..5a23bb086 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/SystemErrorTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/SystemErrorTest.kt @@ -11,7 +11,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class SystemErrorTest { - private val underTestError = SystemError(context = LogicErrorUtils.aContext) private val correctTypeFunctor = "system_error" diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/TypeErrorExpectedTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/TypeErrorExpectedTest.kt index 35c16ff31..e7207e1a8 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/TypeErrorExpectedTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/TypeErrorExpectedTest.kt @@ -16,7 +16,6 @@ import kotlin.test.fail * @author Enrico */ internal class TypeErrorExpectedTest { - @Test fun typeErrorExpectedToAtomWorksAsExpected() { TypeErrorExpectedUtils.allNamesToInstances.forEach { (name, instance) -> diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/TypeErrorTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/TypeErrorTest.kt index 6924c8471..0657c90d3 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/TypeErrorTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/TypeErrorTest.kt @@ -13,14 +13,14 @@ import kotlin.test.assertEquals * @author Enrico */ internal class TypeErrorTest { - private val callableTypeErrorActualValue = Integer.of(1) private val testErrorType = TypeError.Expected.CALLABLE - private val aCallableTypeError = TypeError( - context = LogicErrorUtils.aContext, - expectedType = testErrorType, - culprit = callableTypeErrorActualValue - ) + private val aCallableTypeError = + TypeError( + context = LogicErrorUtils.aContext, + expectedType = testErrorType, + culprit = callableTypeErrorActualValue, + ) private val correctTypeFunctor = "type_error" @Test @@ -37,7 +37,7 @@ internal class TypeErrorTest { fun typeErrorTypeCorrect() { assertEquals( Struct.of(correctTypeFunctor, testErrorType.toTerm(), callableTypeErrorActualValue), - aCallableTypeError.type + aCallableTypeError.type, ) } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/testutils/TypeErrorExpectedUtils.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/testutils/TypeErrorExpectedUtils.kt index e490803a3..97e9c1f69 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/testutils/TypeErrorExpectedUtils.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/error/testutils/TypeErrorExpectedUtils.kt @@ -8,7 +8,6 @@ import it.unibo.tuprolog.solve.exception.error.TypeError * @author Enrico */ internal object TypeErrorExpectedUtils { - /** A map from predefined error names to predefined error instances */ internal val predefinedErrorNamesToInstances by lazy { TypeError.Expected.values().map { it.toString() to it }.toMap() diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/testutils/HaltExceptionUtils.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/testutils/HaltExceptionUtils.kt index 1815ad1ee..2ad9b47aa 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/testutils/HaltExceptionUtils.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/testutils/HaltExceptionUtils.kt @@ -9,8 +9,8 @@ import kotlin.test.assertEquals * * @author Enrico */ +@Suppress("ConstPropertyName", "ktlint:standard:property-naming") internal object HaltExceptionUtils { - internal const val aMessage = TuPrologRuntimeExceptionUtils.aMessage internal val aCause = TuPrologRuntimeExceptionUtils.aCause internal val aContext = TuPrologRuntimeExceptionUtils.aContext @@ -24,13 +24,13 @@ internal object HaltExceptionUtils { expectedCause: Throwable?, expectedContext: ExecutionContext, expectedExitStatus: Int, - actualException: HaltException + actualException: HaltException, ) { TuPrologRuntimeExceptionUtils.assertSameMessageCauseContext( expectedMessage, expectedCause, expectedContext, - actualException + actualException, ) assertEquals(expectedExitStatus, actualException.exitStatus) } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/testutils/LogicErrorUtils.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/testutils/LogicErrorUtils.kt index dbfb19c1a..216cccade 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/testutils/LogicErrorUtils.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/testutils/LogicErrorUtils.kt @@ -17,8 +17,8 @@ import kotlin.test.assertEquals * * @author Enrico */ +@Suppress("ConstPropertyName", "ktlint:standard:property-naming") internal object LogicErrorUtils { - internal const val aMessage = TuPrologRuntimeExceptionUtils.aMessage internal val aCause = TuPrologRuntimeExceptionUtils.aCause internal val aContext = TuPrologRuntimeExceptionUtils.aContext @@ -33,7 +33,7 @@ internal object LogicErrorUtils { Atom.of(InstantiationError.typeFunctor) to InstantiationError::class, Atom.of(SystemError.typeFunctor) to SystemError::class, Struct.of(TypeError.typeFunctor, Atom.of("callable"), Atom.of("someActualValue")) to TypeError::class, - Struct.of(EvaluationError.typeFunctor, Atom.of("zero_divisor")) to EvaluationError::class + Struct.of(EvaluationError.typeFunctor, Atom.of("zero_divisor")) to EvaluationError::class, ) } @@ -44,13 +44,13 @@ internal object LogicErrorUtils { expectedContext: ExecutionContext, expectedType: Struct, expectedExtraData: Term?, - actualException: LogicError + actualException: LogicError, ) { TuPrologRuntimeExceptionUtils.assertSameMessageCauseContext( expectedMessage, expectedCause, expectedContext, - actualException + actualException, ) assertEquals(expectedType, actualException.type) assertEquals(expectedExtraData, actualException.extraData) @@ -62,7 +62,7 @@ internal object LogicErrorUtils { logicError.extraData ?.let { errorStructOf(logicError.type, it) } ?: errorStructOf(logicError.type), - logicError.errorStruct + logicError.errorStruct, ) } } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/testutils/TimeOutExceptionUtils.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/testutils/TimeOutExceptionUtils.kt index 046759d91..cc2059004 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/testutils/TimeOutExceptionUtils.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/testutils/TimeOutExceptionUtils.kt @@ -10,8 +10,8 @@ import kotlin.test.assertEquals * * @author Enrico */ +@Suppress("ConstPropertyName", "ktlint:standard:property-naming") internal object TimeOutExceptionUtils { - internal const val aMessage = TuPrologRuntimeExceptionUtils.aMessage internal val aCause = TuPrologRuntimeExceptionUtils.aCause internal val aContext = TuPrologRuntimeExceptionUtils.aContext @@ -25,13 +25,13 @@ internal object TimeOutExceptionUtils { expectedCause: Throwable?, expectedContext: ExecutionContext, expectedExceededTimeDuration: TimeDuration, - actualException: TimeOutException + actualException: TimeOutException, ) { TuPrologRuntimeExceptionUtils.assertSameMessageCauseContext( expectedMessage, expectedCause, expectedContext, - actualException + actualException, ) assertEquals(expectedExceededTimeDuration, actualException.exceededDuration) } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/testutils/TuPrologRuntimeExceptionUtils.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/testutils/TuPrologRuntimeExceptionUtils.kt index b7978df21..a23b33124 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/testutils/TuPrologRuntimeExceptionUtils.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/testutils/TuPrologRuntimeExceptionUtils.kt @@ -12,26 +12,28 @@ import kotlin.test.assertSame * * @author Enrico */ +@Suppress("ConstPropertyName", "ktlint:standard:property-naming") internal object TuPrologRuntimeExceptionUtils { - internal const val aMessage = "ciao" internal val aCause = IllegalArgumentException() /** A context with emptySequence [ExecutionContext.logicStackTrace] field */ - internal val aContext = object : ExecutionContext by DummyInstances.executionContext { - override val logicStackTrace: List = emptyList() - } + internal val aContext = + object : ExecutionContext by DummyInstances.executionContext { + override val logicStackTrace: List = emptyList() + } /** Different instance from [aContext] with same behaviour */ - internal val aDifferentContext = object : ExecutionContext by aContext {} - .also { assertNotEquals(it, aContext) } + internal val aDifferentContext = + object : ExecutionContext by aContext {} + .also { assertNotEquals(it, aContext) } /** Utility function to check if exception contains same expected values */ internal fun assertSameMessageCauseContext( expectedMessage: String?, expectedCause: Throwable?, expectedContext: ExecutionContext, - actualException: ResolutionException + actualException: ResolutionException, ) { assertSame(expectedMessage, actualException.message) assertSame(expectedCause, actualException.cause) diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/ArithmeticEvaluatorTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/ArithmeticEvaluatorTest.kt index 1a31396d9..63fa540b5 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/ArithmeticEvaluatorTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/ArithmeticEvaluatorTest.kt @@ -13,7 +13,6 @@ import kotlin.test.assertFailsWith * @author Enrico */ internal class ArithmeticEvaluatorTest { - private val arithmeticEvaluator = ArithmeticEvaluator(ArithmeticEvaluatorUtils.commonFunctionsRequest) @Test diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/ComputeRequestTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/ComputeRequestTest.kt index dd6d04cba..1aed21638 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/ComputeRequestTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/ComputeRequestTest.kt @@ -25,23 +25,23 @@ import kotlin.test.assertFailsWith * @author Enrico */ internal class ComputeRequestTest { - @Test fun requestInsertedDataCorrect() { - val toBeTested = Compute.Request( - aSignature, - anArgumentList, - anExecutionContext, - aRequestIssuingInstant, - anExecutionMaxDuration - ) + val toBeTested = + Compute.Request( + aSignature, + anArgumentList, + anExecutionContext, + aRequestIssuingInstant, + anExecutionMaxDuration, + ) toBeTested.assertContainsCorrectData( aSignature, anArgumentList, anExecutionContext, aRequestIssuingInstant, - anExecutionMaxDuration + anExecutionMaxDuration, ) } @@ -54,7 +54,7 @@ internal class ComputeRequestTest { anArgumentList, anExecutionContext, currentTimeInstant(), - TimeDuration.MAX_VALUE + TimeDuration.MAX_VALUE, ) } @@ -91,7 +91,7 @@ internal class ComputeRequestTest { assertEquals(Struct.of(aSignature.name, anArgumentList), createRequest(aSignature, anArgumentList).query) assertEquals( Struct.of(aVarargSignature.name, varargArgumentList), - createRequest(aVarargSignature, varargArgumentList).query + createRequest(aVarargSignature, varargArgumentList).query, ) } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/ExpressionReducerTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/ExpressionReducerTest.kt index a2a975f74..e3a224704 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/ExpressionReducerTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/ExpressionReducerTest.kt @@ -14,7 +14,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class ExpressionReducerTest { - @Test fun doesNothingIfGivenExecutionContextDoesNotDefineFunctions() { inputFunctionOutputTriple.forEach { (input, _, _) -> diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/FunctionWrapperTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/FunctionWrapperTest.kt index 370fe960f..9051d47ff 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/FunctionWrapperTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/FunctionWrapperTest.kt @@ -16,7 +16,6 @@ import kotlin.test.assertFailsWith * @author Enrico */ internal class FunctionWrapperTest { - @Test fun functionWorksIfCorrectRequestProvided() { wrapperToMatchingSignatureRequest(::createFunctionWrapper, function, ::createFunctionRequest) diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/LogicFunctionTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/LogicFunctionTest.kt index cfc958530..9212cbea0 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/LogicFunctionTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/LogicFunctionTest.kt @@ -16,10 +16,13 @@ import kotlin.test.assertFailsWith * @author Enrico */ internal class LogicFunctionTest { - @Test fun functionOfReturnsPrologFunctionBehavingExactlyAsProvidedOne() { - wrapperToMatchingSignatureRequest(LogicFunction.Companion::enforcingSignature, function, ::createFunctionRequest).zip(allSignatures) + wrapperToMatchingSignatureRequest( + LogicFunction.Companion::enforcingSignature, + function, + ::createFunctionRequest, + ).zip(allSignatures) .forEach { (functionToGoodRequests, functionSignature) -> val (checkedFunction, goodRequests) = functionToGoodRequests goodRequests.forEach { @@ -37,7 +40,11 @@ internal class LogicFunctionTest { @Test fun functionOfComplainsIfDifferentRequestSignatureIsDetected() { - wrapperToNotMatchingSignatureRequest(LogicFunction.Companion::enforcingSignature, function, ::createFunctionRequest) + wrapperToNotMatchingSignatureRequest( + LogicFunction.Companion::enforcingSignature, + function, + ::createFunctionRequest, + ) .forEach { (checkedFunction, badRequests) -> badRequests.forEach { assertFailsWith { checkedFunction.compute(it) } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/testutils/ArithmeticEvaluatorUtils.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/testutils/ArithmeticEvaluatorUtils.kt index d62ab7470..c3995dd1e 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/testutils/ArithmeticEvaluatorUtils.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/testutils/ArithmeticEvaluatorUtils.kt @@ -21,18 +21,19 @@ import it.unibo.tuprolog.solve.stdlib.CommonBuiltins * @author Enrico */ internal object ArithmeticEvaluatorUtils { - /** A context with [CommonBuiltins] loaded */ - internal val commonFunctionsContext = object : ExecutionContext by ExpressionEvaluatorUtils.noFunctionsContext { - override val libraries: Runtime = Runtime.of(CommonBuiltins) - } + internal val commonFunctionsContext = + object : ExecutionContext by ExpressionEvaluatorUtils.noFunctionsContext { + override val libraries: Runtime = Runtime.of(CommonBuiltins) + } /** A context with [CommonBuiltins] loaded */ - internal val commonFunctionsRequest = Solve.Request( - Signature("dummy", 0), - emptyList(), - commonFunctionsContext - ) + internal val commonFunctionsRequest = + Solve.Request( + Signature("dummy", 0), + emptyList(), + commonFunctionsContext, + ) /** A map from term input to raised error type */ internal val inputToErrorType by lazy { @@ -40,7 +41,7 @@ internal object ArithmeticEvaluatorUtils { Var.of("MyVar") to InstantiationError::class, Atom.of("PI") to TypeError::class, Struct.of("ciao", Integer.of(2)) to TypeError::class, - Struct.of("/", Integer.of(2), Integer.of(0)) to EvaluationError::class + Struct.of("/", Integer.of(2), Integer.of(0)) to EvaluationError::class, ) } @@ -49,7 +50,7 @@ internal object ArithmeticEvaluatorUtils { mapOf( Struct.of("abs", Integer.of(-1)) to Integer.of(1), Struct.of("rem", Integer.of(5), Integer.of(2)) to Integer.of(1), - Struct.of("/", Integer.of(2), Integer.of(4)) to Real.of(0.5) + Struct.of("/", Integer.of(2), Integer.of(4)) to Real.of(0.5), ) } } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/testutils/ComputeUtils.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/testutils/ComputeUtils.kt index 99592c685..9f7ff6e37 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/testutils/ComputeUtils.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/testutils/ComputeUtils.kt @@ -18,8 +18,8 @@ import kotlin.test.assertTrue * * @author Enrico */ +@Suppress("ConstPropertyName", "ktlint:standard:property-naming") internal object ComputeUtils { - // Request parameters internal val aSignature = Signature("ciao", 2) internal val anArgumentList = listOf(Atom.of("a"), Truth.TRUE) @@ -36,13 +36,16 @@ internal object ComputeUtils { expectedArguments: List, expectedContext: ExecutionContext, expectedRequestIssuingInstant: TimeInstant, - expectedMaxDuration: TimeDuration + expectedMaxDuration: TimeDuration, ) { val toleranceInMillis = 10L // 10 ms assertEquals(expectedSignature, signature) assertEquals(expectedArguments, arguments) assertEquals(expectedContext, context) - assertTrue("Actual issuing instant `$requestIssuingInstant` diverges more than `$toleranceInMillis` from expected one `$expectedRequestIssuingInstant`") { + assertTrue( + "Actual issuing instant `$requestIssuingInstant` diverges more than `$toleranceInMillis` from " + + "expected one `$expectedRequestIssuingInstant`", + ) { requestIssuingInstant - expectedRequestIssuingInstant < toleranceInMillis } assertEquals(expectedMaxDuration, executionMaxDuration) @@ -60,6 +63,6 @@ internal object ComputeUtils { arguments: List = anArgumentList, executionContext: ExecutionContext = anExecutionContext, requestIssuingInstant: TimeInstant = aRequestIssuingInstant, - executionMaxDuration: TimeDuration = anExecutionMaxDuration + executionMaxDuration: TimeDuration = anExecutionMaxDuration, ) = Compute.Request(signature, arguments, executionContext, requestIssuingInstant, executionMaxDuration) } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/testutils/ExpressionEvaluatorUtils.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/testutils/ExpressionEvaluatorUtils.kt index 55817e6da..cf0b3ecff 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/testutils/ExpressionEvaluatorUtils.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/testutils/ExpressionEvaluatorUtils.kt @@ -19,17 +19,18 @@ import it.unibo.tuprolog.solve.primitive.Solve * @author Enrico */ internal object ExpressionEvaluatorUtils { - /** A context with empty functions map */ - internal val noFunctionsContext = object : ExecutionContext by DummyInstances.executionContext { - override val libraries: Runtime = Runtime.empty() - } + internal val noFunctionsContext = + object : ExecutionContext by DummyInstances.executionContext { + override val libraries: Runtime = Runtime.empty() + } - internal val noFunctionRequest = Solve.Request( - signature = Signature("dummy", 0), - arguments = emptyList(), - context = noFunctionsContext - ) + internal val noFunctionRequest = + Solve.Request( + signature = Signature("dummy", 0), + arguments = emptyList(), + context = noFunctionsContext, + ) /** Test data is in the form (input, transforming function, expected output) */ internal val inputFunctionOutputTriple by lazy { @@ -37,12 +38,12 @@ internal object ExpressionEvaluatorUtils { Triple( Atom.of("a"), LogicFunction { request -> request.replyWith(Atom.of("b")) }, - Atom.of("b") + Atom.of("b"), ), Triple( Struct.of("extractAnotherTerm", Atom.of("b")), LogicFunction { request -> with(request) { replyWith(Struct.of("resultTerm", arguments.single())) } }, - Struct.of("resultTerm", Atom.of("b")) + Struct.of("resultTerm", Atom.of("b")), ), Triple( Struct.of("concat", Atom.of("a"), Atom.of("b")), @@ -50,49 +51,53 @@ internal object ExpressionEvaluatorUtils { with(request) { replyWith( Atom.of( - arguments.first().toString() + arguments.last().toString() - ) + arguments.first().toString() + arguments.last().toString(), + ), ) } }, - Atom.of("ab") + Atom.of("ab"), ), Triple( Struct.of( "concat", Struct.of("concat", Atom.of("a"), Atom.of("b")), - Struct.of("concat", Atom.of("a"), Atom.of("b")) + Struct.of("concat", Atom.of("a"), Atom.of("b")), ), LogicFunction { request -> with(request) { replyWith( Atom.of( - arguments.first().toString() + arguments.last().toString() - ) + arguments.first().toString() + arguments.last().toString(), + ), ) } }, - Atom.of("abab") - ) + Atom.of("abab"), + ), ) } /** Creates a context with provided signature-function binding */ - private fun createContextWithFunctionBy(signature: Signature, function: LogicFunction): ExecutionContext = + private fun createContextWithFunctionBy( + signature: Signature, + function: LogicFunction, + ): ExecutionContext = object : ExecutionContext by DummyInstances.executionContext { - override val libraries: Runtime = Library.of( - alias = "test.expression.evaluator", - functions = mapOf(signature to function) - ).toRuntime() + override val libraries: Runtime = + Library.of( + alias = "test.expression.evaluator", + functions = mapOf(signature to function), + ).toRuntime() } internal fun createRequestWithFunctionBy( signature: Signature, - function: LogicFunction + function: LogicFunction, ): Solve.Request = Solve.Request( signature = Signature("dummy", 0), arguments = emptyList(), - context = createContextWithFunctionBy(signature, function) + context = createContextWithFunctionBy(signature, function), ) } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/testutils/FunctionWrapperUtils.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/testutils/FunctionWrapperUtils.kt index ab57d87a6..24e318985 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/testutils/FunctionWrapperUtils.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/function/testutils/FunctionWrapperUtils.kt @@ -18,7 +18,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal object FunctionWrapperUtils { - /** A default function result to be used in tests */ internal val defaultFunctionResult = Compute.Response(Truth.TRUE) @@ -26,13 +25,15 @@ internal object FunctionWrapperUtils { internal val function: LogicFunction = LogicFunction { defaultFunctionResult } /** A function to create a Compute.Request with provided [signature] and [argList] */ - internal fun createFunctionRequest(signature: Signature, argList: List) = - Compute.Request(signature, argList, DummyInstances.executionContext) + internal fun createFunctionRequest( + signature: Signature, + argList: List, + ) = Compute.Request(signature, argList, DummyInstances.executionContext) /** Utility function to create a function wrapper */ internal fun createFunctionWrapper( signature: Signature, - uncheckedImplementation: LogicFunction + uncheckedImplementation: LogicFunction, ): FunctionWrapper = object : FunctionWrapper(signature) { override fun uncheckedImplementation(request: Compute.Request): Compute.Response = diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/LibrariesTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/LibrariesTest.kt index 716d14cda..865ce3f63 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/LibrariesTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/LibrariesTest.kt @@ -17,7 +17,6 @@ import kotlin.test.assertNotEquals * @author Enrico */ internal class LibrariesTest { - private val emptyLibrary = makeLib(LibraryUtils.emptyLibrary, ::libraryWithAliasConstructor) private val library = makeLib(LibraryUtils.library, ::libraryWithAliasConstructor) private val overridingLibrary = makeLib(LibraryUtils.overridingLibrary, ::libraryWithAliasConstructor) @@ -38,14 +37,17 @@ internal class LibrariesTest { @Test fun sequenceConstructor() { - assertEquals(differentAliasInstances.toSet(), Runtime.of(differentAliasInstances.asSequence()).libraries.toSet()) + assertEquals( + differentAliasInstances.toSet(), + Runtime.of(differentAliasInstances.asSequence()).libraries.toSet(), + ) } @Test fun varargConstructor() { assertEquals( differentAliasInstances.toSet(), - Runtime.of(*differentAliasInstances.toTypedArray()).libraries.toSet() + Runtime.of(*differentAliasInstances.toTypedArray()).libraries.toSet(), ) } @@ -108,14 +110,15 @@ internal class LibrariesTest { assertEquals( overriddenLibrary.primitives, - toBeTested.primitives.filterKeys { !it.name.contains(Library.ALIAS_SEPARATOR) } + toBeTested.primitives.filterKeys { !it.name.contains(Library.ALIAS_SEPARATOR) }, ) } @Test fun primitivesShouldReturnAllAliasedPrimitivesEvenAfterOverriding() { - val correct = aliasLibraryMap(overridingLibrary.alias, overriddenLibrary.primitives) + - library.primitives.map { aliasPrimitiveOrFunction(library.alias, it) } + val correct = + aliasLibraryMap(overridingLibrary.alias, overriddenLibrary.primitives) + + library.primitives.map { aliasPrimitiveOrFunction(library.alias, it) } val toBeTested = Runtime.of(library, overridingLibrary) assertEquals(correct, toBeTested.primitives) @@ -137,14 +140,15 @@ internal class LibrariesTest { assertEquals( overriddenLibrary.functions, - toBeTested.functions.filterKeys { !it.name.contains(Library.ALIAS_SEPARATOR) } + toBeTested.functions.filterKeys { !it.name.contains(Library.ALIAS_SEPARATOR) }, ) } @Test fun functionsShouldReturnAllAliasedPrimitivesEvenAfterOverriding() { - val correct = aliasLibraryMap(overridingLibrary.alias, overriddenLibrary.functions) + - library.functions.map { aliasPrimitiveOrFunction(library.alias, it) } + val correct = + aliasLibraryMap(overridingLibrary.alias, overriddenLibrary.functions) + + library.functions.map { aliasPrimitiveOrFunction(library.alias, it) } val toBeTested = Runtime.of(library, overridingLibrary) assertEquals(correct, toBeTested.functions) @@ -171,7 +175,7 @@ internal class LibrariesTest { assertEquals( Runtime.of(instances), - Runtime.of(instances.take(instancesCount / 2)) + Runtime.of(instances.drop(instancesCount / 2)) + Runtime.of(instances.take(instancesCount / 2)) + Runtime.of(instances.drop(instancesCount / 2)), ) } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/LibraryAliasedTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/LibraryAliasedTest.kt index 77c6024e9..342b62570 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/LibraryAliasedTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/LibraryAliasedTest.kt @@ -11,7 +11,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class LibraryAliasedTest { - private val library = LibraryUtils.makeLib(LibraryUtils.library, ::libraryWithAliasConstructor) private val overridingLibrary = LibraryUtils.makeLib(LibraryUtils.overridingLibrary, ::libraryWithAliasConstructor) diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/LibraryTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/LibraryTest.kt index 27f3f4ab7..ecd024cd0 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/LibraryTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/LibraryTest.kt @@ -14,15 +14,15 @@ import kotlin.test.assertTrue * @author Enrico */ internal class LibraryTest { - private val correctInstances = LibraryUtils.allLibraries.map { makeLib(it, ::libraryWithoutAliasConstructor) } private val correctInstancesWithAlias = LibraryUtils.allLibraries.map { makeLib(it, ::libraryWithAliasConstructor) } @Test fun ofCreatesCorrectInstance() { - val toBeTested = LibraryUtils.allLibraries.map { (_, opSet, theory, primitives, functions) -> - Library.of(primitives, theory, opSet, functions) - } + val toBeTested = + LibraryUtils.allLibraries.map { (_, opSet, theory, primitives, functions) -> + Library.of(primitives, theory, opSet, functions) + } assertEquals(correctInstances, toBeTested) } @@ -38,18 +38,20 @@ internal class LibraryTest { @Test fun ofWithAliasCreatesCorrectInstance() { - val toBeTested = LibraryUtils.allLibraries.map { (alias, opSet, theory, primitives, functions) -> - Library.of(alias, primitives, theory, opSet, functions) - } + val toBeTested = + LibraryUtils.allLibraries.map { (alias, opSet, theory, primitives, functions) -> + Library.of(alias, primitives, theory, opSet, functions) + } assertEquals(correctInstancesWithAlias, toBeTested) } @Test fun ofLibraryAndAliasCreatesCorrectInstance() { - val toBeTested = LibraryUtils.allLibraries.map { (alias, opSet, theory, primitives, functions) -> - Library.of(alias, libraryWithoutAliasConstructor(opSet, theory, primitives, functions)) - } + val toBeTested = + LibraryUtils.allLibraries.map { (alias, opSet, theory, primitives, functions) -> + Library.of(alias, libraryWithoutAliasConstructor(opSet, theory, primitives, functions)) + } assertEquals(correctInstancesWithAlias, toBeTested) } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/impl/LibraryAliasedTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/impl/LibraryAliasedTest.kt index 8ba00191a..b09f0ae7d 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/impl/LibraryAliasedTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/impl/LibraryAliasedTest.kt @@ -13,7 +13,6 @@ import kotlin.test.assertNotEquals * @author Enrico */ internal class LibraryAliasedTest { - private val libraryAliasedInstances = LibraryUtils.allLibraries.map { makeLib(it, ::libraryWithAliasConstructor) } @Test @@ -29,7 +28,7 @@ internal class LibraryAliasedTest { LibraryUtils.allLibraries.map { (alias, opSet, theory, primitives, functions) -> assertNotEquals( libraryWithAliasConstructor(opSet, theory, primitives, functions, alias), - libraryWithAliasConstructor(opSet, theory, primitives, functions, alias + "x") + libraryWithAliasConstructor(opSet, theory, primitives, functions, alias + "x"), ) } } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/impl/LibraryImplTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/impl/LibraryImplTest.kt index f1e8b1514..80632fb20 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/impl/LibraryImplTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/impl/LibraryImplTest.kt @@ -24,7 +24,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class LibraryImplTest { - private val libraryInstances = LibraryUtils.allLibraries.map { makeLib(it, ::libraryWithoutAliasConstructor) } @Test @@ -64,8 +63,9 @@ internal class LibraryImplTest { LibraryUtils.allLibraries.zip(libraryInstances).forEach { (libraryToAlias, libraryInstance) -> val (_, _, theory, primitives) = libraryToAlias - theory.rules.map { it.head.extractSignature() } + primitives.keys - .forEach { signature -> assertTrue { signature in libraryInstance } } + theory.rules.map { it.head.extractSignature() } + + primitives.keys + .forEach { signature -> assertTrue { signature in libraryInstance } } assertFalse { Signature("ciao", 3) in libraryInstance } } @@ -73,12 +73,13 @@ internal class LibraryImplTest { @Test fun containsSignatureDiscardsVarargSignatures() { - val library = libraryWithoutAliasConstructor( - OperatorSet(), - Theory.of(Fact.of(Struct.of("f", Atom.of("a")))), - emptyMap(), - emptyMap() - ) + val library = + libraryWithoutAliasConstructor( + OperatorSet(), + Theory.of(Fact.of(Struct.of("f", Atom.of("a")))), + emptyMap(), + emptyMap(), + ) assertTrue { Signature("f", 1, false) in library } assertFalse { Signature("f", 1, true) in library } @@ -103,11 +104,12 @@ internal class LibraryImplTest { primitives.keys.forEach { signature -> assertTrue { libraryInstance.hasPrimitive(signature) } } ( - theory.rules.map { it.head.extractSignature() } + Signature( - "ciao", - 3 - ) - ).forEach { + theory.rules.map { it.head.extractSignature() } + + Signature( + "ciao", + 3, + ) + ).forEach { assertFalse { libraryInstance.hasPrimitive(it) } } } @@ -118,8 +120,9 @@ internal class LibraryImplTest { LibraryUtils.allLibraries.zip(libraryInstances).forEach { (libraryToAlias, libraryInstance) -> val (_, _, theory, primitives) = libraryToAlias - theory.rules.map { it.head.extractSignature() } + primitives.keys - .forEach { signature -> assertTrue { libraryInstance.hasProtected(signature) } } + theory.rules.map { it.head.extractSignature() } + + primitives.keys + .forEach { signature -> assertTrue { libraryInstance.hasProtected(signature) } } assertFalse { libraryInstance.hasProtected(Signature("ciao", 3)) } } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/testutils/LibraryUtils.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/testutils/LibraryUtils.kt index 380cdda5a..a1cf958ab 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/testutils/LibraryUtils.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/library/testutils/LibraryUtils.kt @@ -22,14 +22,13 @@ import it.unibo.tuprolog.theory.Theory * @author Enrico */ internal object LibraryUtils { - /** A class to represent raw library data in tests */ internal data class RawLibrary( val name: String, val opSet: OperatorSet, val theory: Theory, val primitives: Map, - val functions: Map + val functions: Map, ) private val plusOperator = Operator("+", Specifier.YFX, 500) @@ -40,20 +39,24 @@ internal object LibraryUtils { private val theory = Theory.of(Rule.of(Atom.of("a")), Rule.of(Atom.of("b"))) private val theoryWithDuplicates = Theory.of(Rule.of(Atom.of("c")), Rule.of(Atom.of("b"))) - private fun myPrimitive(@Suppress("UNUSED_PARAMETER") r: Solve.Request): Sequence = - throw NotImplementedError() + private fun myPrimitive( + @Suppress("UNUSED_PARAMETER") r: Solve.Request, + ): Sequence = throw NotImplementedError() - private fun myOtherPrimitive(@Suppress("UNUSED_PARAMETER") r: Solve.Request): Sequence = - throw NotImplementedError() + private fun myOtherPrimitive( + @Suppress("UNUSED_PARAMETER") r: Solve.Request, + ): Sequence = throw NotImplementedError() private val primitives = mapOf(Signature("myPrimitive1", 1) to Primitive(::myPrimitive)) private val primitivesOverridden = mapOf(Signature("myPrimitive1", 1) to Primitive(::myOtherPrimitive)) - private fun myFunction(@Suppress("UNUSED_PARAMETER") r: Compute.Request): Compute.Response = - throw NotImplementedError() + private fun myFunction( + @Suppress("UNUSED_PARAMETER") r: Compute.Request, + ): Compute.Response = throw NotImplementedError() - private fun myOtherFunction(@Suppress("UNUSED_PARAMETER") r: Compute.Request): Compute.Response = - throw NotImplementedError() + private fun myOtherFunction( + @Suppress("UNUSED_PARAMETER") r: Compute.Request, + ): Compute.Response = throw NotImplementedError() private val functions = mapOf(Signature("myFunc1", 1) to LogicFunction(::myFunction)) private val functionsOverridden = mapOf(Signature("myFunc1", 1) to LogicFunction(::myOtherFunction)) @@ -70,7 +73,7 @@ internal object LibraryUtils { OperatorSet(plusOperator, minusOperator), theory, primitives, - functions + functions, ) } @@ -81,7 +84,7 @@ internal object LibraryUtils { OperatorSet(minusOperatorOverridden), theoryWithDuplicates, primitivesOverridden, - functionsOverridden + functionsOverridden, ) } @@ -92,7 +95,7 @@ internal object LibraryUtils { OperatorSet(plusOperator, minusOperatorOverridden), theory + theoryWithDuplicates, primitives + primitivesOverridden, - functions + functionsOverridden + functions + functionsOverridden, ) } @@ -108,7 +111,7 @@ internal object LibraryUtils { library, overridingLibrary, overriddenLibrary, - duplicatedAliasLibrary + duplicatedAliasLibrary, ) } @@ -118,7 +121,7 @@ internal object LibraryUtils { theory: Theory, primitives: Map, functions: Map, - alias: String + alias: String, ): Library = Library.of(alias, primitives, theory, opSet, functions) /** A method to disambiguate use of Library.of reference */ @@ -126,29 +129,39 @@ internal object LibraryUtils { opSet: OperatorSet, theory: Theory, primitives: Map, - functions: Map + functions: Map, ): Library = Library.of(primitives, theory, opSet, functions) /** Utility function to construct a library from raw data */ internal inline fun makeLib( rawLibrary: RawLibrary, - constructor: (OperatorSet, Theory, Map, Map) -> Library + constructor: (OperatorSet, Theory, Map, Map) -> Library, ): Library = constructor(rawLibrary.opSet, rawLibrary.theory, rawLibrary.primitives, rawLibrary.functions) /** Utility function to construct a library with alias from raw data */ internal inline fun makeLib( rawLibrary: RawLibrary, - constructor: (OperatorSet, Theory, Map, Map, String) -> Library + constructor: (OperatorSet, Theory, Map, Map, String) -> Library, ): Library = - constructor(rawLibrary.opSet, rawLibrary.theory, rawLibrary.primitives, rawLibrary.functions, rawLibrary.name) + constructor( + rawLibrary.opSet, + rawLibrary.theory, + rawLibrary.primitives, + rawLibrary.functions, + rawLibrary.name, + ) /** Utility function to alias a primitive/function */ - internal fun aliasPrimitiveOrFunction(libAlias: String, entry: Map.Entry) = - entry.key.copy(name = libAlias + Library.ALIAS_SEPARATOR + entry.key.name) to entry.value + internal fun aliasPrimitiveOrFunction( + libAlias: String, + entry: Map.Entry, + ) = entry.key.copy(name = libAlias + Library.ALIAS_SEPARATOR + entry.key.name) to entry.value /** Utility function to duplicate all primitive/functions aliasing them in library */ - internal fun aliasLibraryMap(libAlias: String, toAliasMap: Map) = - toAliasMap.flatMap { - listOf(it.toPair(), aliasPrimitiveOrFunction(libAlias, it)) - }.toMap() + internal fun aliasLibraryMap( + libAlias: String, + toAliasMap: Map, + ) = toAliasMap.flatMap { + listOf(it.toPair(), aliasPrimitiveOrFunction(libAlias, it)) + }.toMap() } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/AbstractWrapperTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/AbstractWrapperTest.kt index 803f8b911..4fc078b97 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/AbstractWrapperTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/AbstractWrapperTest.kt @@ -11,7 +11,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class AbstractWrapperTest { - private val signature = Signature("a", 0) private val underTest1 = WrapperOfConstant(signature, 1) @@ -41,7 +40,6 @@ internal class AbstractWrapperTest { } private companion object { - /** A testing class for AbstractWrapper functionality */ private class WrapperOfConstant(signature: Signature, value: T) : AbstractWrapper(signature) { // this class was added since Kotlin/JS won't pass tests using "object literals" diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/PrimitiveTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/PrimitiveTest.kt index b4fc50e0b..aeb217e09 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/PrimitiveTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/PrimitiveTest.kt @@ -16,7 +16,6 @@ import kotlin.test.assertFailsWith * @author Enrico */ internal class PrimitiveTest { - @Test fun primitiveOfReturnsPrimitiveBehavingExactlyAsProvidedOne() { wrapperToMatchingSignatureRequest(Primitive.Companion::enforcingSignature, primitive, ::createPrimitiveRequest) @@ -38,7 +37,11 @@ internal class PrimitiveTest { @Test fun primitiveOfComplainsIfDifferentRequestSignatureIsDetected() { - wrapperToNotMatchingSignatureRequest(Primitive.Companion::enforcingSignature, primitive, ::createPrimitiveRequest) + wrapperToNotMatchingSignatureRequest( + Primitive.Companion::enforcingSignature, + primitive, + ::createPrimitiveRequest, + ) .forEach { (checkedPrimitive, badRequests) -> badRequests.forEach { assertFailsWith { checkedPrimitive.solve(it) } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/PrimitiveWrapperTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/PrimitiveWrapperTest.kt index 7cc1a979c..1a51a93b5 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/PrimitiveWrapperTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/PrimitiveWrapperTest.kt @@ -22,7 +22,6 @@ import kotlin.test.assertSame * @author Enrico */ internal class PrimitiveWrapperTest { - @Test fun primitiveWorksIfCorrectRequestProvided() { wrapperToMatchingSignatureRequest(::createPrimitiveWrapper, primitive, ::createPrimitiveRequest) diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/SignatureTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/SignatureTest.kt index 1a180923a..2f5e080b1 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/SignatureTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/SignatureTest.kt @@ -24,7 +24,6 @@ import kotlin.test.fail * @author Enrico */ internal class SignatureTest { - private val signatureName = "myFunc" private val signatureArity = 3 @@ -63,7 +62,7 @@ internal class SignatureTest { assertFailsWith { Signature( signatureName, - -1 + -1, ) } } @@ -101,8 +100,9 @@ internal class SignatureTest { @Test fun fromTermWithStructCreatesCorrectInstance() { signatures.forEach { - val reconstructed = Signature.fromSignatureTerm(it.toTerm()) - ?: fail("Cannot reconstruct signature $it from it.toTerm(): ${it.toTerm()}") + val reconstructed = + Signature.fromSignatureTerm(it.toTerm()) + ?: fail("Cannot reconstruct signature $it from it.toTerm(): ${it.toTerm()}") assertEquals(it, reconstructed) } @@ -116,39 +116,39 @@ internal class SignatureTest { assertNull(Signature.fromSignatureTerm(Struct.of("\\", Atom.of(signatureName), Integer.of(signatureArity)))) assertNull( Signature.fromSignatureTerm( - Struct.of("/", Atom.of(signatureName), Integer.of(signatureArity), Truth.TRUE) - ) + Struct.of("/", Atom.of(signatureName), Integer.of(signatureArity), Truth.TRUE), + ), ) assertNull(Signature.fromSignatureTerm(Struct.of("/", Var.anonymous(), Integer.of(signatureArity)))) assertNull(Signature.fromSignatureTerm(Struct.of("/", Atom.of(signatureName), Var.anonymous()))) assertNull( Signature.fromSignatureTerm( - Struct.of("/", Atom.of(signatureName), Struct.of("a", Integer.of(signatureArity), Atom.of("vararg"))) - ) + Struct.of("/", Atom.of(signatureName), Struct.of("a", Integer.of(signatureArity), Atom.of("vararg"))), + ), ) assertNull( Signature.fromSignatureTerm( Struct.of( "/", Atom.of(signatureName), - Struct.of("+", Integer.of(signatureArity), Atom.of("vararg"), Truth.TRUE) - ) - ) + Struct.of("+", Integer.of(signatureArity), Atom.of("vararg"), Truth.TRUE), + ), + ), ) assertNull( Signature.fromSignatureTerm( - Struct.of("/", Atom.of(signatureName), Struct.of("+", Var.anonymous(), Atom.of("vararg"))) - ) + Struct.of("/", Atom.of(signatureName), Struct.of("+", Var.anonymous(), Atom.of("vararg"))), + ), ) assertNull( Signature.fromSignatureTerm( - Struct.of("/", Atom.of(signatureName), Struct.of("+", Integer.of(signatureArity), Var.anonymous())) - ) + Struct.of("/", Atom.of(signatureName), Struct.of("+", Integer.of(signatureArity), Var.anonymous())), + ), ) assertNull( Signature.fromSignatureTerm( - Struct.of("/", Atom.of(signatureName), Struct.of("+", Integer.of(-1), Atom.of("vararg"))) - ) + Struct.of("/", Atom.of(signatureName), Struct.of("+", Integer.of(-1), Atom.of("vararg"))), + ), ) } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/testutils/PrimitiveWrapperUtils.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/testutils/PrimitiveWrapperUtils.kt index 2ebe0601b..a1c48504b 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/testutils/PrimitiveWrapperUtils.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/testutils/PrimitiveWrapperUtils.kt @@ -16,7 +16,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal object PrimitiveWrapperUtils { - /** A default primitive result to be used in tests */ internal val defaultPrimitiveResult = emptySequence() @@ -24,13 +23,15 @@ internal object PrimitiveWrapperUtils { internal val primitive: Primitive = Primitive { defaultPrimitiveResult } /** A function to create a Solve.Request with provided [signature] and [argList] */ - internal fun createPrimitiveRequest(signature: Signature, argList: List) = - Solve.Request(signature, argList, DummyInstances.executionContext) + internal fun createPrimitiveRequest( + signature: Signature, + argList: List, + ) = Solve.Request(signature, argList, DummyInstances.executionContext) /** Utility function to create a primitive wrapper */ internal fun createPrimitiveWrapper( signature: Signature, - uncheckedImplementation: Primitive + uncheckedImplementation: Primitive, ): PrimitiveWrapper = PrimitiveWrapper.wrap(signature) { uncheckedImplementation.solve(it) } /** All under test requests */ diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/testutils/WrapperUtils.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/testutils/WrapperUtils.kt index 781140fdf..02b8ed098 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/testutils/WrapperUtils.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/primitive/testutils/WrapperUtils.kt @@ -18,7 +18,6 @@ import kotlin.collections.List as KtList * @author Enrico */ internal object WrapperUtils { - /** Test data in the form of (Signature, matchingList, notMatchingList)*/ private val signaturesToMatchingAndNotMatchingStruct by lazy { listOf( @@ -27,33 +26,33 @@ internal object WrapperUtils { listOf(Atom.of("ciao")), listOf( Atom.of("ciaO"), - Atom.of("cc") - ) + Atom.of("cc"), + ), ), Triple( Signature("another", 1), listOf( Struct.of("another", Var.anonymous()), - Struct.of("another", Truth.TRUE) + Struct.of("another", Truth.TRUE), ), listOf( Atom.of("another"), Struct.of("another", Var.of("A"), Var.of("B")), - Struct.of("other", Integer.of(2)) - ) + Struct.of("other", Integer.of(2)), + ), ), Triple( Signature("aVarargOne", 1, true), listOf( Struct.of("aVarargOne", Var.of("X")), Struct.of("aVarargOne", Integer.of(1), Real.of(1.5)), - Struct.of("aVarargOne", Var.of("X"), Var.of("Y"), Truth.TRUE) + Struct.of("aVarargOne", Var.of("X"), Var.of("Y"), Truth.TRUE), ), listOf( Atom.of("aVarargOne"), - Struct.of("aVararg", Var.anonymous()) - ) - ) + Struct.of("aVararg", Var.anonymous()), + ), + ), ) } @@ -70,7 +69,7 @@ internal object WrapperUtils { internal inline fun wrapperToMatchingSignatureRequest( wrapperCreator: (Signature, WrappedType) -> WrappingType, wrapped: WrappedType, - requestCreator: (Signature, KtList) -> Request + requestCreator: (Signature, KtList) -> Request, ) = signaturesToMatchingAndNotMatchingStruct.map { (signature, good, _) -> wrapperCreator(signature, wrapped) to good.map { requestCreator(it.extractSignature(), it.args) } } @@ -79,7 +78,7 @@ internal object WrapperUtils { internal inline fun wrapperToNotMatchingSignatureRequest( wrapperCreator: (Signature, WrappedType) -> WrappingType, wrapped: WrappedType, - requestCreator: (Signature, KtList) -> Request + requestCreator: (Signature, KtList) -> Request, ) = signaturesToMatchingAndNotMatchingStruct.map { (signature, _, bad) -> wrapperCreator(signature, wrapped) to bad.map { requestCreator(it.extractSignature(), it.args) } } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/ArcTangentTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/ArcTangentTest.kt index 3c4698ada..fcc8abcc4 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/ArcTangentTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/ArcTangentTest.kt @@ -13,7 +13,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class ArcTangentTest { - @Test fun functorNameCorrect() { assertEquals(Signature("atan", 1), ArcTangent.signature) @@ -23,7 +22,7 @@ internal class ArcTangentTest { fun computationCorrect() { assertEquals( PI, - ArcTangent.computeOf(Integer.of(1)).castToReal().value.toDouble() * 4 + ArcTangent.computeOf(Integer.of(1)).castToReal().value.toDouble() * 4, ) } } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseAndTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseAndTest.kt index 9cbcac34e..7e87d1c6e 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseAndTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseAndTest.kt @@ -13,7 +13,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class BitwiseAndTest { - @Test fun functorNameCorrect() { assertEquals(Signature("/\\", 2), BitwiseAnd.signature) @@ -25,8 +24,8 @@ internal class BitwiseAndTest { Integer.of(125), BitwiseAnd.computeOf( Integer.of(17 * 256 + 125), - Integer.of(255) - ) + Integer.of(255), + ), ) } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseComplementTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseComplementTest.kt index cfe3c9eb0..9f6358bb8 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseComplementTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseComplementTest.kt @@ -13,7 +13,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class BitwiseComplementTest { - @Test fun functorNameCorrect() { assertEquals(Signature("\\", 1), BitwiseComplement.signature) @@ -23,7 +22,7 @@ internal class BitwiseComplementTest { fun computationCorrect() { assertEquals( Integer.of(10), - BitwiseComplement.computeOf(BitwiseComplement.computeOf(Integer.of(10))) + BitwiseComplement.computeOf(BitwiseComplement.computeOf(Integer.of(10))), ) } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseLeftShiftTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseLeftShiftTest.kt index 45a77e3d6..f0f121d3b 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseLeftShiftTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseLeftShiftTest.kt @@ -13,7 +13,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class BitwiseLeftShiftTest { - @Test fun functorNameCorrect() { assertEquals(Signature("<<", 2), BitwiseLeftShift.signature) @@ -25,8 +24,8 @@ internal class BitwiseLeftShiftTest { Integer.of(64), BitwiseLeftShift.computeOf( Integer.of(16), - Integer.of(2) - ) + Integer.of(2), + ), ) } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseOrTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseOrTest.kt index c8840248b..6b9ad4f20 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseOrTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseOrTest.kt @@ -13,7 +13,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class BitwiseOrTest { - @Test fun functorNameCorrect() { assertEquals(Signature("\\/", 2), BitwiseOr.signature) @@ -25,8 +24,8 @@ internal class BitwiseOrTest { Integer.of(255), BitwiseOr.computeOf( Integer.of(125), - Integer.of(255) - ) + Integer.of(255), + ), ) } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseRightShiftTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseRightShiftTest.kt index f34d470d5..0ca7fd0af 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseRightShiftTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/BitwiseRightShiftTest.kt @@ -13,7 +13,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class BitwiseRightShiftTest { - @Test fun functorNameCorrect() { assertEquals(Signature(">>", 2), BitwiseRightShift.signature) @@ -25,8 +24,8 @@ internal class BitwiseRightShiftTest { Integer.of(4), BitwiseRightShift.computeOf( Integer.of(16), - Integer.of(2) - ) + Integer.of(2), + ), ) } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/CosineTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/CosineTest.kt index a5c978985..d712a32b7 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/CosineTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/CosineTest.kt @@ -14,7 +14,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class CosineTest { - @Test fun functorNameCorrect() { assertEquals(Signature("cos", 1), Cosine.signature) diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/ExponentialTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/ExponentialTest.kt index 288c306f3..3b663de7b 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/ExponentialTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/ExponentialTest.kt @@ -15,7 +15,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class ExponentialTest { - @Test fun functorNameCorrect() { assertEquals(Signature("exp", 1), Exponential.signature) @@ -25,7 +24,7 @@ internal class ExponentialTest { fun computationCorrect() { assertAlmostEquals( Numeric.of(E), - Exponential.computeOf(Integer.of(1)).castToNumeric() + Exponential.computeOf(Integer.of(1)).castToNumeric(), ) } } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/ExponentiationTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/ExponentiationTest.kt index 556318201..7b5800e9a 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/ExponentiationTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/ExponentiationTest.kt @@ -13,7 +13,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class ExponentiationTest { - @Test fun functorNameCorrect() { assertEquals(Signature("**", 2), Exponentiation.signature) @@ -25,8 +24,8 @@ internal class ExponentiationTest { Numeric.of(-125.0), Exponentiation.computeOf( Integer.of(-5), - Integer.of(3) - ) + Integer.of(3), + ), ) } } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/FloatFractionalPartTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/FloatFractionalPartTest.kt index e323a85c4..891de7bc0 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/FloatFractionalPartTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/FloatFractionalPartTest.kt @@ -13,7 +13,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class FloatFractionalPartTest { - @Test fun functorNameCorrect() { assertEquals(Signature("float_fractional_part", 1), FloatFractionalPart.signature) @@ -25,7 +24,7 @@ internal class FloatFractionalPartTest { val (_, fractionalPart) = parts assertEquals( fractionalPart, - FloatFractionalPart.computeOf(Numeric.of(input)).castToReal().value + FloatFractionalPart.computeOf(Numeric.of(input)).castToReal().value, ) } } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/FloatIntegerPartTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/FloatIntegerPartTest.kt index 1dd281596..90068c8fb 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/FloatIntegerPartTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/FloatIntegerPartTest.kt @@ -11,11 +11,13 @@ import kotlin.test.Test * @author Enrico */ internal class FloatIntegerPartTest { - companion object { private inline val loggingOn get() = false - fun assertEquals(expected: T, actual: T) { + fun assertEquals( + expected: T, + actual: T, + ) { if (loggingOn) { println( """ @@ -23,7 +25,7 @@ internal class FloatIntegerPartTest { | $expected |got | $actual - """.trimMargin() + """.trimMargin(), ) } @@ -44,7 +46,7 @@ internal class FloatIntegerPartTest { val (integerPart, _) = parts assertEquals( integerPart, - FloatIntegerPart.computeOf(Numeric.of(input)).castToReal().value + FloatIntegerPart.computeOf(Numeric.of(input)).castToReal().value, ) } } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/NaturalLogarithmTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/NaturalLogarithmTest.kt index 179b1584d..398eb7a6c 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/NaturalLogarithmTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/NaturalLogarithmTest.kt @@ -14,7 +14,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class NaturalLogarithmTest { - @Test fun functorNameCorrect() { assertEquals(Signature("log", 1), NaturalLogarithm.signature) @@ -24,7 +23,7 @@ internal class NaturalLogarithmTest { fun computationCorrect() { assertEquals( Numeric.of(1.0), - NaturalLogarithm.computeOf(Real.of(E)) + NaturalLogarithm.computeOf(Real.of(E)), ) } } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/SineTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/SineTest.kt index 34791df98..fe56eb481 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/SineTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/SineTest.kt @@ -13,7 +13,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class SineTest { - @Test fun functorNameCorrect() { assertEquals(Signature("sin", 1), Sine.signature) @@ -23,7 +22,7 @@ internal class SineTest { fun computationCorrect() { assertEquals( Numeric.of(1.0), - Sine.computeOf(Numeric.of(PI / 2.0)) + Sine.computeOf(Numeric.of(PI / 2.0)), ) } } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/SquareRootTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/SquareRootTest.kt index e2697afca..417b1fa33 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/SquareRootTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/SquareRootTest.kt @@ -13,7 +13,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class SquareRootTest { - @Test fun functorNameCorrect() { assertEquals(Signature("sqrt", 1), SquareRoot.signature) @@ -23,7 +22,7 @@ internal class SquareRootTest { fun computationCorrect() { assertEquals( Numeric.of("1.1"), - SquareRoot.computeOf(Real.of("1.21")) + SquareRoot.computeOf(Real.of("1.21")), ) } } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/testutils/FloatFunctionUtils.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/testutils/FloatFunctionUtils.kt index cae5e8f91..89f4f9c28 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/testutils/FloatFunctionUtils.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/testutils/FloatFunctionUtils.kt @@ -8,20 +8,20 @@ import org.gciatto.kt.math.BigDecimal * @author Enrico */ internal object FloatFunctionUtils { - /** A map from an input number to the pair (integer part, fractional part) */ - internal val numbersToFloatParts = mapOf>( - 1 to (1.0 to 0.0), - 1.0 to (1.0 to 0.0), - 1.1 to (1.0 to 0.10), - 3.123456789101 to (3.0 to 0.123456789101), - 2.0000000001 to (2.0 to 0.0000000001), - -3.123456789101 to (-3.0 to -0.123456789101), - -2.0000000001 to (-2.0 to -0.0000000001), - -1984984.02 to (-1984984.0 to -0.02) - ).mapKeys { (k, _) -> BigDecimal.of(k.toString()) } - .mapValues { (_, v) -> - BigDecimal.of(v.first.toString()).stripTrailingZeros() to - BigDecimal.of(v.second.toString()).stripTrailingZeros() - } + internal val numbersToFloatParts = + mapOf>( + 1 to (1.0 to 0.0), + 1.0 to (1.0 to 0.0), + 1.1 to (1.0 to 0.10), + 3.123456789101 to (3.0 to 0.123456789101), + 2.0000000001 to (2.0 to 0.0000000001), + -3.123456789101 to (-3.0 to -0.123456789101), + -2.0000000001 to (-2.0 to -0.0000000001), + -1984984.02 to (-1984984.0 to -0.02), + ).mapKeys { (k, _) -> BigDecimal.of(k.toString()) } + .mapValues { (_, v) -> + BigDecimal.of(v.first.toString()).stripTrailingZeros() to + BigDecimal.of(v.second.toString()).stripTrailingZeros() + } } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/testutils/FunctionUtils.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/testutils/FunctionUtils.kt index c9be62343..5c06643fd 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/testutils/FunctionUtils.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/function/testutils/FunctionUtils.kt @@ -19,10 +19,11 @@ import kotlin.test.assertFailsWith * @author Enrico */ internal object FunctionUtils { - /** Utility function to create a Compute request for functions */ - private fun createComputeRequest(signature: Signature, vararg argument: Term) = - Compute.Request(signature, argument.toList(), DummyInstances.executionContext) + private fun createComputeRequest( + signature: Signature, + vararg argument: Term, + ) = Compute.Request(signature, argument.toList(), DummyInstances.executionContext) /** Helper function that invokes the function wrapper implementation with provided arguments */ internal fun FunctionWrapper.computeOf(vararg argument: Term): Term = diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticEqualTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticEqualTest.kt index fd740e87e..11fb7ec2d 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticEqualTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticEqualTest.kt @@ -10,7 +10,6 @@ import kotlin.test.Test * @author Enrico */ internal class ArithmeticEqualTest { - @Test fun computesCorrectResult() { equalQueryToResult.forEach { (input, result) -> diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticGreaterThanOrEqualToTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticGreaterThanOrEqualToTest.kt index 37b51842a..2546ff6c8 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticGreaterThanOrEqualToTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticGreaterThanOrEqualToTest.kt @@ -11,7 +11,6 @@ import kotlin.test.Test */ internal class ArithmeticGreaterThanOrEqualToTest { - @Test fun computesCorrectResult() { greaterOrEqualQueryToResult.forEach { (input, result) -> diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticGreaterThanTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticGreaterThanTest.kt index 345e4e8a2..9301ab2b2 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticGreaterThanTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticGreaterThanTest.kt @@ -10,7 +10,6 @@ import kotlin.test.Test * @author Enrico */ internal class ArithmeticGreaterThanTest { - @Test fun computesCorrectResult() { greaterQueryToResult.forEach { (input, result) -> diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticLowerThanOrEqualToTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticLowerThanOrEqualToTest.kt index 3df569c5c..b6aa69ecf 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticLowerThanOrEqualToTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticLowerThanOrEqualToTest.kt @@ -10,7 +10,6 @@ import kotlin.test.Test * @author Enrico */ internal class ArithmeticLowerThanOrEqualToTest { - @Test fun computesCorrectResult() { lowerOrEqualQueryToResult.forEach { (input, result) -> diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticLowerThanTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticLowerThanTest.kt index 665f101af..c8d3b9c02 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticLowerThanTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticLowerThanTest.kt @@ -10,7 +10,6 @@ import kotlin.test.Test * @author Enrico */ internal class ArithmeticLowerThanTest { - @Test fun computesCorrectResult() { lowerQueryToResult.forEach { (input, result) -> diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticNotEqualTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticNotEqualTest.kt index bd236f6a4..1b05e47d9 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticNotEqualTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/ArithmeticNotEqualTest.kt @@ -10,7 +10,6 @@ import kotlin.test.Test * @author Enrico */ internal class ArithmeticNotEqualTest { - @Test fun computesCorrectResult() { notEqualQueryToResult.forEach { (input, result) -> diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/HaltTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/HaltTest.kt index 38ade10ed..8243d2a2b 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/HaltTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/HaltTest.kt @@ -15,7 +15,6 @@ import kotlin.test.assertFailsWith * @author Enrico */ internal class HaltTest { - private val haltSolveRequest = createSolveRequest(Atom.of("halt")) @Test diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/IsTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/IsTest.kt index 63a70de0e..1a2478019 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/IsTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/IsTest.kt @@ -16,7 +16,6 @@ import kotlin.test.fail * @author Enrico */ internal class IsTest { - @Test fun computesCorrectly() { isQueryToResult.forEach { (input, expectedResult) -> diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/StandardNotEqualTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/StandardNotEqualTest.kt index c11524131..1870a5ca6 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/StandardNotEqualTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/StandardNotEqualTest.kt @@ -4,7 +4,6 @@ import it.unibo.tuprolog.solve.stdlib.primitive.testutils.TermOrderingUtils import kotlin.test.Test internal class StandardNotEqualTest { - @Test fun computesCorrectResult() { TermOrderingUtils.standardOrderNotEqualTest.forEach { (input, result) -> diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/StandardOrderEqualTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/StandardOrderEqualTest.kt index 3dbdbf21e..59072990b 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/StandardOrderEqualTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/StandardOrderEqualTest.kt @@ -4,7 +4,6 @@ import it.unibo.tuprolog.solve.stdlib.primitive.testutils.TermOrderingUtils import kotlin.test.Test internal class StandardOrderEqualTest { - @Test fun computesCorrectResult() { TermOrderingUtils.standardOrderEqualTest.forEach { (input, result) -> diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermGreaterThanOrEqualToTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermGreaterThanOrEqualToTest.kt index 9cce607c1..e44628ac3 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermGreaterThanOrEqualToTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermGreaterThanOrEqualToTest.kt @@ -9,7 +9,6 @@ import kotlin.test.Test * */ internal class TermGreaterThanOrEqualToTest { - @Test fun computesCorrectResult() { greaterOrEqualQueryToResult.forEach { (input, result) -> diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermGreaterThanTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermGreaterThanTest.kt index 57c0e8c9e..c8ca88e41 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermGreaterThanTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermGreaterThanTest.kt @@ -9,7 +9,6 @@ import kotlin.test.Test * */ internal class TermGreaterThanTest { - @Test fun computesCorrectResult() { greaterQueryToResult.forEach { (input, result) -> diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermIdenticalTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermIdenticalTest.kt index 1ab108619..572702b33 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermIdenticalTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermIdenticalTest.kt @@ -9,7 +9,6 @@ import kotlin.test.Test * */ internal class TermIdenticalTest { - @Test fun computesCorrectResult() { equalQueryToResult.forEach { (input, result) -> diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermLowerThanOrEqualToTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermLowerThanOrEqualToTest.kt index 968a65009..599e238fb 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermLowerThanOrEqualToTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermLowerThanOrEqualToTest.kt @@ -9,7 +9,6 @@ import kotlin.test.Test * */ internal class TermLowerThanOrEqualToTest { - @Test fun computesCorrectResult() { lowerOrEqualQueryToResult.forEach { (input, result) -> diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermLowerThanTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermLowerThanTest.kt index 310baf1c3..7b1c81b04 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermLowerThanTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermLowerThanTest.kt @@ -9,7 +9,6 @@ import kotlin.test.Test * */ internal class TermLowerThanTest { - @Test fun computesCorrectResult() { lowerQueryToResult.forEach { (input, result) -> diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermNotIdenticalTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermNotIdenticalTest.kt index 90a5d9af5..92be923a0 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermNotIdenticalTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TermNotIdenticalTest.kt @@ -9,7 +9,6 @@ import kotlin.test.Test * */ internal class TermNotIdenticalTest { - @Test fun computesCorrectResult() { notEqualQueryToResult.forEach { (input, result) -> diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TypeTestingPrimitivesTest.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TypeTestingPrimitivesTest.kt index 208ca5bd1..ac8174900 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TypeTestingPrimitivesTest.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/TypeTestingPrimitivesTest.kt @@ -36,8 +36,10 @@ import it.unibo.tuprolog.solve.stdlib.primitive.Var as VarPrimitive * [NonVar] */ internal class TypeTestingPrimitivesTest { - - private fun assertTypeTestingWorks(primitive: UnaryPredicate<*>, cases: Map, Any>) { + private fun assertTypeTestingWorks( + primitive: UnaryPredicate<*>, + cases: Map, Any>, + ) { cases.forEach { (request, result) -> assertCorrectResponse(primitive, request, result) } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/ArithmeticUtils.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/ArithmeticUtils.kt index fde96d131..a6ea4a5b2 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/ArithmeticUtils.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/ArithmeticUtils.kt @@ -19,7 +19,6 @@ import it.unibo.tuprolog.solve.stdlib.primitive.testutils.PrimitiveUtils.createS * @author Enrico */ internal object ArithmeticUtils { - /** [Is] primitive test data (input, [Substitution | ErrorType]) */ internal val isQueryToResult by lazy { logicProgramming { @@ -29,7 +28,7 @@ internal object ArithmeticUtils { Is.functor("foo", 77) to Substitution.failed(), Is.functor(numOf(1.0), numOf(1)) to Substitution.failed(), Is.functor("X", "+"("+"("N", 1), "/"(3, 0))) to InstantiationError::class, - Is.functor("C", "/"(3, 0)) to EvaluationError::class + Is.functor("C", "/"(3, 0)) to EvaluationError::class, ).mapKeys { (query, _) -> createSolveRequest(query) } } } @@ -42,7 +41,7 @@ internal object ArithmeticUtils { ArithmeticEqual.functor("*"(3, 2), "-"(7, 1)) to true, ArithmeticEqual.functor(0.333, "/"(1, 3)) to false, ArithmeticEqual.functor(0, 1) to false, - ArithmeticEqual.functor(1, "+"("N", "/"(3, 0))) to InstantiationError::class + ArithmeticEqual.functor(1, "+"("N", "/"(3, 0))) to InstantiationError::class, ).mapKeys { (query, _) -> createSolveRequest(query) } } } @@ -55,7 +54,7 @@ internal object ArithmeticUtils { ArithmeticNotEqual.functor(0.333, "/"(1, 3)) to true, ArithmeticNotEqual.functor(1.0, 1) to false, ArithmeticNotEqual.functor("*"(3, 2), "-"(7, 1)) to false, - ArithmeticNotEqual.functor(1, "+"("N", "/"(3, 0))) to InstantiationError::class + ArithmeticNotEqual.functor(1, "+"("N", "/"(3, 0))) to InstantiationError::class, ).mapKeys { (query, _) -> createSolveRequest(query) } } } @@ -69,7 +68,7 @@ internal object ArithmeticUtils { ArithmeticGreaterThan.functor(0, 1) to false, ArithmeticGreaterThan.functor(0.333, "/"(1, 3)) to false, ArithmeticGreaterThan.functor("X", 5) to InstantiationError::class, - ArithmeticGreaterThan.functor("N", "/"(3, 0)) to InstantiationError::class + ArithmeticGreaterThan.functor("N", "/"(3, 0)) to InstantiationError::class, ).mapKeys { (query, _) -> createSolveRequest(query) } } } @@ -83,7 +82,7 @@ internal object ArithmeticUtils { ArithmeticGreaterThanOrEqualTo.functor(0, 1) to false, ArithmeticGreaterThanOrEqualTo.functor(0.333, "/"(1, 3)) to false, ArithmeticGreaterThanOrEqualTo.functor("X", 5) to InstantiationError::class, - ArithmeticGreaterThanOrEqualTo.functor("N", "/"(3, 0)) to InstantiationError::class + ArithmeticGreaterThanOrEqualTo.functor("N", "/"(3, 0)) to InstantiationError::class, ).mapKeys { (query, _) -> createSolveRequest(query) } } } @@ -97,7 +96,7 @@ internal object ArithmeticUtils { ArithmeticLowerThan.functor(1.0, 1) to false, ArithmeticLowerThan.functor("*"(3, 2), "-"(7, 1)) to false, ArithmeticLowerThan.functor("X", 5) to InstantiationError::class, - ArithmeticLowerThan.functor(1, "+"("N", "/"(3, 0))) to InstantiationError::class + ArithmeticLowerThan.functor(1, "+"("N", "/"(3, 0))) to InstantiationError::class, ).mapKeys { (query, _) -> createSolveRequest(query) } } } @@ -111,7 +110,7 @@ internal object ArithmeticUtils { ArithmeticLowerThanOrEqualTo.functor(0.333, "/"(1, 3)) to true, ArithmeticLowerThanOrEqualTo.functor("*"(3, 2), "-"(6, 1)) to false, ArithmeticLowerThanOrEqualTo.functor("X", 5) to InstantiationError::class, - ArithmeticLowerThanOrEqualTo.functor("N", "/"(3, 0)) to InstantiationError::class + ArithmeticLowerThanOrEqualTo.functor("N", "/"(3, 0)) to InstantiationError::class, ).mapKeys { (query, _) -> createSolveRequest(query) } } } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/BinaryRelationUtils.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/BinaryRelationUtils.kt index 40c66ff32..e047fd974 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/BinaryRelationUtils.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/BinaryRelationUtils.kt @@ -11,20 +11,21 @@ import kotlin.test.assertTrue import kotlin.test.fail object BinaryRelationUtils { - /** Utility method to check if the term relation responses are correct */ @Suppress("IMPLICIT_CAST_TO_ANY") internal fun assertCorrectResponse( termRelation: BinaryRelation, input: Solve.Request, - expectedResult: Any + expectedResult: Any, ) = when (expectedResult) { - true -> assertTrue("Requesting ${input.query} should result in $expectedResult response!") { - termRelation.implementation.solve(input).single().solution is Solution.Yes - } - false -> assertTrue("Requesting ${input.query} should result in $expectedResult response!") { - termRelation.implementation.solve(input).single().solution is Solution.No - } + true -> + assertTrue("Requesting ${input.query} should result in $expectedResult response!") { + termRelation.implementation.solve(input).single().solution is Solution.Yes + } + false -> + assertTrue("Requesting ${input.query} should result in $expectedResult response!") { + termRelation.implementation.solve(input).single().solution is Solution.No + } else -> @Suppress("UNCHECKED_CAST") (expectedResult as? KClass) diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/PrimitiveUtils.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/PrimitiveUtils.kt index 959e94eab..86ec73ec0 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/PrimitiveUtils.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/PrimitiveUtils.kt @@ -15,20 +15,20 @@ import it.unibo.tuprolog.theory.Theory * @author Enrico */ internal object PrimitiveUtils { - - private fun contextWith(database: Theory) = object : ExecutionContext by DummyInstances.executionContext { - override val libraries: Runtime = Runtime.of(CommonBuiltins) - override val staticKb: Theory = database - } + private fun contextWith(database: Theory) = + object : ExecutionContext by DummyInstances.executionContext { + override val libraries: Runtime = Runtime.of(CommonBuiltins) + override val staticKb: Theory = database + } /** Creates a solve request with [database] and [CommonBuiltins] loaded and given query struct*/ internal fun createSolveRequest( query: Struct, - database: Theory = Theory.empty() + database: Theory = Theory.empty(), ): Solve.Request = Solve.Request( query.extractSignature(), query.args, - contextWith(database) + contextWith(database), ) } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/TermOrderingUtils.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/TermOrderingUtils.kt index 3096c12fd..553788cf1 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/TermOrderingUtils.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/TermOrderingUtils.kt @@ -18,19 +18,20 @@ import kotlin.test.assertTrue import kotlin.test.fail internal object TermOrderingUtils { - @Suppress("IMPLICIT_CAST_TO_ANY") internal fun assertCorrectResponse( standardOrderRelation: BinaryRelation.Predicative, input: Solve.Request, - expectedResult: Any + expectedResult: Any, ) = when (expectedResult) { - true -> assertTrue("Requesting ${input.query} should result in $expectedResult response!") { - standardOrderRelation.implementation.solve(input).single().solution is Solution.Yes - } - false -> assertTrue("Requesting ${input.query} should result in $expectedResult response!") { - standardOrderRelation.implementation.solve(input).single().solution is Solution.No - } + true -> + assertTrue("Requesting ${input.query} should result in $expectedResult response!") { + standardOrderRelation.implementation.solve(input).single().solution is Solution.Yes + } + false -> + assertTrue("Requesting ${input.query} should result in $expectedResult response!") { + standardOrderRelation.implementation.solve(input).single().solution is Solution.No + } else -> @Suppress("UNCHECKED_CAST") (expectedResult as? KClass) @@ -44,7 +45,7 @@ internal object TermOrderingUtils { mapOf( TermSame.functor(realOf(1.0), realOf(1.0)) to true, TermSame.functor("stringTest", "stringTest") to true, - TermSame.functor("stringTest", realOf(1.0)) to false + TermSame.functor("stringTest", realOf(1.0)) to false, ).mapKeys { (query, _) -> PrimitiveUtils.createSolveRequest(query) } } } @@ -55,7 +56,7 @@ internal object TermOrderingUtils { mapOf( TermNotSame.functor(realOf(1.0), realOf(1.0)) to false, TermNotSame.functor("stringTest", "stringTest") to false, - TermNotSame.functor("stringTest", realOf(1.0)) to true + TermNotSame.functor("stringTest", realOf(1.0)) to true, ).mapKeys { (query, _) -> PrimitiveUtils.createSolveRequest(query) } } } @@ -68,7 +69,7 @@ internal object TermOrderingUtils { TermGreaterThan.functor(realOf(1.0), intOf(1)) to false, TermGreaterThan.functor("stringTest", intOf(1)) to true, TermGreaterThan.functor("stringTesta", "stringTestb") to false, - TermGreaterThan.functor("stringTestb", "stringTesta") to true + TermGreaterThan.functor("stringTestb", "stringTesta") to true, ).mapKeys { (query, _) -> PrimitiveUtils.createSolveRequest(query) } } } @@ -80,7 +81,7 @@ internal object TermOrderingUtils { TermGreaterThanOrEqualTo.functor(intOf(1), intOf(1)) to true, TermGreaterThanOrEqualTo.functor("stringTest", "stringTest") to true, TermGreaterThanOrEqualTo.functor("stringTest", "stringTest1") to false, - TermGreaterThanOrEqualTo.functor("stringTest", intOf(1)) to true + TermGreaterThanOrEqualTo.functor("stringTest", intOf(1)) to true, ).mapKeys { (query, _) -> PrimitiveUtils.createSolveRequest(query) } } } @@ -92,7 +93,7 @@ internal object TermOrderingUtils { TermLowerThan.functor(realOf(1.0), intOf(1)) to true, TermLowerThan.functor(intOf(1), realOf(1.0)) to false, TermLowerThan.functor("stringTestA", "stringTestZ") to true, - TermLowerThan.functor(realOf(1.0), "stringTest") to true + TermLowerThan.functor(realOf(1.0), "stringTest") to true, ).mapKeys { (query, _) -> PrimitiveUtils.createSolveRequest(query) } } } @@ -103,7 +104,7 @@ internal object TermOrderingUtils { mapOf( TermLowerThanOrEqualTo.functor(intOf(1), realOf(1.0)) to false, TermLowerThanOrEqualTo.functor(realOf(1.0), realOf(1.0)) to true, - TermLowerThanOrEqualTo.functor("stringTest", "stringTest") to true + TermLowerThanOrEqualTo.functor("stringTest", "stringTest") to true, ).mapKeys { (query, _) -> PrimitiveUtils.createSolveRequest(query) } } } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/TermUtils.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/TermUtils.kt index cea373cac..cbfc312e0 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/TermUtils.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/TermUtils.kt @@ -13,21 +13,20 @@ import it.unibo.tuprolog.solve.stdlib.primitive.testutils.PrimitiveUtils.createS * Utils singleton to help testing term comparison primitives */ internal object TermUtils { - /** Equal functor test data (input, [true | false | ErrorType]) */ internal val equalQueryToResult by lazy { logicProgramming { mapOf( TermIdentical.functor( structOf("a", atomOf("c")), - structOf("a", atomOf("c")) + structOf("a", atomOf("c")), ) to true, TermIdentical.functor( structOf("a", atomOf("c")), - structOf("a", atomOf("x")) + structOf("a", atomOf("x")), ) to false, TermIdentical.functor(varOf("X"), varOf("X")) to true, - TermIdentical.functor(varOf("X"), varOf("Y")) to false + TermIdentical.functor(varOf("X"), varOf("Y")) to false, ).mapKeys { (query, _) -> createSolveRequest(query) } } } @@ -38,14 +37,14 @@ internal object TermUtils { mapOf( TermNotIdentical.functor( structOf("a", atomOf("c")), - structOf("a", atomOf("c")) + structOf("a", atomOf("c")), ) to false, TermNotIdentical.functor( structOf("a", atomOf("c")), - structOf("a", atomOf("x")) + structOf("a", atomOf("x")), ) to true, TermNotIdentical.functor(varOf("X"), varOf("X")) to false, - TermNotIdentical.functor(varOf("X"), varOf("Y")) to true + TermNotIdentical.functor(varOf("X"), varOf("Y")) to true, ).mapKeys { (query, _) -> createSolveRequest(query) } } } @@ -56,19 +55,19 @@ internal object TermUtils { mapOf( TermGreaterThan.functor( structOf("a", atomOf("a")), - structOf("a", atomOf("a")) + structOf("a", atomOf("a")), ) to false, TermGreaterThan.functor( structOf("a", atomOf("a")), - structOf("a", atomOf("b")) + structOf("a", atomOf("b")), ) to false, TermGreaterThan.functor( structOf("a", atomOf("b")), - structOf("a", atomOf("a")) + structOf("a", atomOf("a")), ) to true, TermGreaterThan.functor(varOf("X"), varOf("X")) to false, TermGreaterThan.functor(atomOf("a"), varOf("Y")) to true, - TermGreaterThan.functor(varOf("Y"), atomOf("a")) to false + TermGreaterThan.functor(varOf("Y"), atomOf("a")) to false, ).mapKeys { (query, _) -> createSolveRequest(query) } } } @@ -79,19 +78,19 @@ internal object TermUtils { mapOf( TermGreaterThanOrEqualTo.functor( structOf("a", atomOf("a")), - structOf("a", atomOf("a")) + structOf("a", atomOf("a")), ) to true, TermGreaterThanOrEqualTo.functor( structOf("a", atomOf("a")), - structOf("a", atomOf("b")) + structOf("a", atomOf("b")), ) to false, TermGreaterThanOrEqualTo.functor( structOf("a", atomOf("b")), - structOf("a", atomOf("a")) + structOf("a", atomOf("a")), ) to true, TermGreaterThanOrEqualTo.functor(varOf("X"), varOf("X")) to true, TermGreaterThanOrEqualTo.functor(atomOf("a"), varOf("Y")) to true, - TermGreaterThanOrEqualTo.functor(varOf("Y"), atomOf("a")) to false + TermGreaterThanOrEqualTo.functor(varOf("Y"), atomOf("a")) to false, ).mapKeys { (query, _) -> createSolveRequest(query) } } } @@ -102,19 +101,19 @@ internal object TermUtils { mapOf( TermLowerThan.functor( structOf("a", atomOf("a")), - structOf("a", atomOf("a")) + structOf("a", atomOf("a")), ) to false, TermLowerThan.functor( structOf("a", atomOf("a")), - structOf("a", atomOf("b")) + structOf("a", atomOf("b")), ) to true, TermLowerThan.functor( structOf("a", atomOf("b")), - structOf("a", atomOf("a")) + structOf("a", atomOf("a")), ) to false, TermLowerThan.functor(varOf("X"), varOf("X")) to false, TermLowerThan.functor(atomOf("a"), varOf("Y")) to false, - TermLowerThan.functor(varOf("Y"), atomOf("a")) to true + TermLowerThan.functor(varOf("Y"), atomOf("a")) to true, ).mapKeys { (query, _) -> createSolveRequest(query) } } } @@ -125,19 +124,19 @@ internal object TermUtils { mapOf( TermLowerThanOrEqualTo.functor( structOf("a", atomOf("a")), - structOf("a", atomOf("a")) + structOf("a", atomOf("a")), ) to true, TermLowerThanOrEqualTo.functor( structOf("a", atomOf("a")), - structOf("a", atomOf("b")) + structOf("a", atomOf("b")), ) to true, TermLowerThanOrEqualTo.functor( structOf("a", atomOf("b")), - structOf("a", atomOf("a")) + structOf("a", atomOf("a")), ) to false, TermLowerThanOrEqualTo.functor(varOf("X"), varOf("X")) to true, TermLowerThanOrEqualTo.functor(atomOf("a"), varOf("Y")) to false, - TermLowerThanOrEqualTo.functor(varOf("Y"), atomOf("a")) to true + TermLowerThanOrEqualTo.functor(varOf("Y"), atomOf("a")) to true, ).mapKeys { (query, _) -> createSolveRequest(query) } } } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/TypeTestingUtils.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/TypeTestingUtils.kt index f49425094..8fa28e7ea 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/TypeTestingUtils.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/stdlib/primitive/testutils/TypeTestingUtils.kt @@ -49,7 +49,6 @@ import it.unibo.tuprolog.solve.stdlib.primitive.Var as VarPrimitive * [NonVar] */ object TypeTestingUtils { - private val baseArgs: Sequence = logicProgramming { sequenceOf( @@ -68,21 +67,22 @@ object TypeTestingUtils { "f"(1), "f"(-1), "f"(-1.1), - "f"(2) + "f"(2), ).map { it.toTerm() } } - private val commonArgs: List = LogicProgrammingScope.empty().let { - baseArgs + - baseArgs.squared { x, y -> it.tupleOf(x, y) } + - baseArgs.squared { x, y -> it.structOf(";", x, y) } + - baseArgs.squared { x, y -> it.structOf("->", x, y) } - }.toList() + private val commonArgs: List = + LogicProgrammingScope.empty().let { + baseArgs + + baseArgs.squared { x, y -> it.tupleOf(x, y) } + + baseArgs.squared { x, y -> it.structOf(";", x, y) } + + baseArgs.squared { x, y -> it.structOf("->", x, y) } + }.toList() private inline fun typeTest( functor: String, terms: List = commonArgs, - crossinline predicate: (Term) -> Boolean + crossinline predicate: (Term) -> Boolean, ): Map, Boolean> { return logicProgramming { terms.asSequence() @@ -95,12 +95,13 @@ object TypeTestingUtils { private fun isExecutable(term: Term): Boolean { return when (term) { is Numeric -> false - is Struct -> when { - term.functor in Clause.notableFunctors && term.arity == 2 -> { - term.argsSequence.all(this::isExecutable) + is Struct -> + when { + term.functor in Clause.notableFunctors && term.arity == 2 -> { + term.argsSequence.all(this::isExecutable) + } + else -> true } - else -> true - } else -> true } } @@ -162,14 +163,16 @@ object TypeTestingUtils { fun assertCorrectResponse( unaryPredicate: UnaryPredicate<*>, input: Solve.Request<*>, - expectedResult: Any + expectedResult: Any, ) = when (expectedResult) { - true -> assertTrue("Requesting ${input.query} should result in positive response!") { - unaryPredicate.implementation.solve(input).single().solution is Solution.Yes - } - false -> assertTrue("Requesting ${input.query} should result in negative response!") { - unaryPredicate.implementation.solve(input).single().solution is Solution.No - } + true -> + assertTrue("Requesting ${input.query} should result in positive response!") { + unaryPredicate.implementation.solve(input).single().solution is Solution.Yes + } + false -> + assertTrue("Requesting ${input.query} should result in negative response!") { + unaryPredicate.implementation.solve(input).single().solution is Solution.No + } else -> @Suppress("UNCHECKED_CAST") (expectedResult as? KClass) diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/testutils/SolutionUtils.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/testutils/SolutionUtils.kt index c747a8ec5..974b99719 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/testutils/SolutionUtils.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/testutils/SolutionUtils.kt @@ -14,7 +14,6 @@ import it.unibo.tuprolog.solve.extractSignature * @author Enrico */ internal object SolutionUtils { - private val solutionScope = Scope.empty() internal val aQuery = with(solutionScope) { Struct.of("f", varOf("A")) } internal val querySignature = aQuery.extractSignature() diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/testutils/SolveUtils.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/testutils/SolveUtils.kt index 340396f49..f5969f2b6 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/testutils/SolveUtils.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/testutils/SolveUtils.kt @@ -26,8 +26,8 @@ import kotlin.collections.List as KtList * * @author Enrico */ +@Suppress("ConstPropertyName", "ktlint:standard:property-naming") internal object SolveUtils { - internal val someLibraries = Runtime.empty() internal val someFlags = emptyMap() internal val aStaticKB = Theory.empty() @@ -61,9 +61,10 @@ internal object SolveUtils { // Response parameters internal val aSolution = Solution.no(Truth.FAIL) - internal val aSideEffectManager = object : SideEffectManager { - override fun cut() = throw NotImplementedError() - } + internal val aSideEffectManager = + object : SideEffectManager { + override fun cut() = throw NotImplementedError() + } internal val someSideEffects = listOf(SideEffect.ResetDynamicKb()) /** The success response to default values request */ @@ -74,7 +75,7 @@ internal object SolveUtils { SideEffect.ResetRuntime(differentLibraries), SideEffect.ResetFlags(differentFlags), SideEffect.ResetStaticKb(differentStaticKB), - SideEffect.ResetDynamicKb(differentDynamicKB) + SideEffect.ResetDynamicKb(differentDynamicKB), ) } @@ -86,7 +87,7 @@ internal object SolveUtils { SideEffect.ResetRuntime(differentLibraries), SideEffect.ResetFlags(differentFlags), SideEffect.ResetStaticKb(differentStaticKB), - SideEffect.ResetDynamicKb(differentDynamicKB) + SideEffect.ResetDynamicKb(differentDynamicKB), ) } @@ -98,7 +99,7 @@ internal object SolveUtils { SideEffect.ResetRuntime(differentLibraries), SideEffect.ResetFlags(differentFlags), SideEffect.ResetStaticKb(differentStaticKB), - SideEffect.ResetDynamicKb(differentDynamicKB) + SideEffect.ResetDynamicKb(differentDynamicKB), ) } @@ -113,6 +114,6 @@ internal object SolveUtils { arguments: KtList = anArgumentList, executionContext: ExecutionContext = anExecutionContext, requestIssuingInstant: TimeInstant = aRequestIssuingInstant, - executionMaxDuration: TimeDuration = anExecutionMaxDuration + executionMaxDuration: TimeDuration = anExecutionMaxDuration, ) = Solve.Request(signature, arguments, executionContext, requestIssuingInstant, executionMaxDuration) } diff --git a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/test/TestingUtils.kt b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/test/TestingUtils.kt index 92da115ac..aead8bd25 100644 --- a/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/test/TestingUtils.kt +++ b/test-solve/src/commonTest/kotlin/it/unibo/tuprolog/test/TestingUtils.kt @@ -12,32 +12,33 @@ private val DEFAULT_THRESHOLD = BigDecimal.of("1E-10") fun assertAlmostEquals( expected: BigDecimal, actual: BigDecimal, - threshold: BigDecimal = DEFAULT_THRESHOLD + threshold: BigDecimal = DEFAULT_THRESHOLD, ) { val diff = (expected - actual).absoluteValue val tolerance = threshold.absoluteValue assertTrue( diff <= tolerance, - message = "expected:<$expected> but was:<$actual>, while " + - "the difference ($diff) is lower than the tolerance ($tolerance)" + message = + "expected:<$expected> but was:<$actual>, while " + + "the difference ($diff) is lower than the tolerance ($tolerance)", ) } fun assertAlmostEquals( expected: Numeric, actual: Numeric, - threshold: BigDecimal = DEFAULT_THRESHOLD + threshold: BigDecimal = DEFAULT_THRESHOLD, ) = assertAlmostEquals(expected.decimalValue, actual.decimalValue, threshold) fun assertAlmostEquals( expected: Real, actual: Real, - threshold: BigDecimal = DEFAULT_THRESHOLD + threshold: BigDecimal = DEFAULT_THRESHOLD, ) = assertAlmostEquals(expected.castToNumeric(), actual, threshold) @Suppress("UNUSED_PARAMETER") fun assertAlmostEquals( expected: Integer, actual: Integer, - threshold: BigDecimal = DEFAULT_THRESHOLD + threshold: BigDecimal = DEFAULT_THRESHOLD, ) = assertEquals(expected, actual) diff --git a/test-solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/BigListOptions.kt b/test-solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/BigListOptions.kt index 073874c8c..2519c733e 100644 --- a/test-solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/BigListOptions.kt +++ b/test-solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/BigListOptions.kt @@ -1,5 +1,6 @@ package it.unibo.tuprolog.solve +@Suppress("MagicNumber") actual object BigListOptions { actual val SIZE: Int get() = 1000 diff --git a/test-solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/TestUtils.kt b/test-solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/TestUtils.kt index ba7f6ca2c..4054c25c6 100644 --- a/test-solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/TestUtils.kt +++ b/test-solve/src/jsMain/kotlin/it/unibo/tuprolog/solve/TestUtils.kt @@ -11,6 +11,9 @@ actual fun log(x: () -> Any) { console.log(x()) } -actual fun assertClassNameIs(`class`: KClass, name: String) { - assertEquals(`class`.simpleName, name.split('.').last()) +actual fun assertClassNameIs( + klass: KClass, + name: String, +) { + assertEquals(klass.simpleName, name.split('.').last()) } diff --git a/test-solve/src/jsTest/kotlin/it/unibo/tuprolog/solve/CurrentTimeInstantKtJsTest.kt b/test-solve/src/jsTest/kotlin/it/unibo/tuprolog/solve/CurrentTimeInstantKtJsTest.kt index ef599f078..0373d1dce 100644 --- a/test-solve/src/jsTest/kotlin/it/unibo/tuprolog/solve/CurrentTimeInstantKtJsTest.kt +++ b/test-solve/src/jsTest/kotlin/it/unibo/tuprolog/solve/CurrentTimeInstantKtJsTest.kt @@ -10,8 +10,9 @@ import kotlin.test.assertTrue * @author Enrico */ internal class CurrentTimeInstantKtJsTest { - - private val TOLERANCE = 10L // 10 ms + companion object { + private const val TOLERANCE = 10L // 10 ms + } @Test fun currentTimeReturnsActualTimeInMillis() { diff --git a/test-solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/BigListOptions.kt b/test-solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/BigListOptions.kt index 50545304d..b25d2b13b 100644 --- a/test-solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/BigListOptions.kt +++ b/test-solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/BigListOptions.kt @@ -1,5 +1,6 @@ package it.unibo.tuprolog.solve +@Suppress("MagicNumber") actual object BigListOptions { actual val SIZE: Int get() = 6000 diff --git a/test-solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/TestUtils.kt b/test-solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/TestUtils.kt index f3cef5191..4eb549f10 100644 --- a/test-solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/TestUtils.kt +++ b/test-solve/src/jvmMain/kotlin/it/unibo/tuprolog/solve/TestUtils.kt @@ -11,6 +11,9 @@ actual fun log(x: () -> Any) { System.err.println(x()) } -actual fun assertClassNameIs(`class`: KClass, name: String) { - assertEquals(name, `class`.qualifiedName) +actual fun assertClassNameIs( + klass: KClass, + name: String, +) { + assertEquals(name, klass.qualifiedName) } diff --git a/test-solve/src/jvmTest/kotlin/it/unibo/tuprolog/solve/CurrentTimeInstantKtJavaTest.kt b/test-solve/src/jvmTest/kotlin/it/unibo/tuprolog/solve/CurrentTimeInstantKtJavaTest.kt index 648e7666d..79265c996 100644 --- a/test-solve/src/jvmTest/kotlin/it/unibo/tuprolog/solve/CurrentTimeInstantKtJavaTest.kt +++ b/test-solve/src/jvmTest/kotlin/it/unibo/tuprolog/solve/CurrentTimeInstantKtJavaTest.kt @@ -9,8 +9,9 @@ import kotlin.test.assertTrue * @author Enrico */ internal class CurrentTimeInstantKtJavaTest { - - private val TOLERANCE = 10L // 10 ms + companion object { + private const val TOLERANCE = 10L // 10 ms + } @Test fun currentTimeReturnsActualTimeInMillis() { diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/AbstractClauseCollection.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/AbstractClauseCollection.kt index 1d56349bb..8e49a4a4c 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/AbstractClauseCollection.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/AbstractClauseCollection.kt @@ -6,8 +6,9 @@ import it.unibo.tuprolog.core.Directive import it.unibo.tuprolog.core.Rule import it.unibo.tuprolog.unify.Unificator -internal abstract class AbstractClauseCollection> protected constructor(protected val rete: ReteTree) : ClauseCollection { - +internal abstract class AbstractClauseCollection> protected constructor( + protected val rete: ReteTree, +) : ClauseCollection { override val unificator: Unificator get() = rete.unificator diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/AbstractMutableReteClauseCollection.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/AbstractMutableReteClauseCollection.kt index 79722eed7..678fe0c53 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/AbstractMutableReteClauseCollection.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/AbstractMutableReteClauseCollection.kt @@ -3,9 +3,10 @@ package it.unibo.tuprolog.collections import it.unibo.tuprolog.collections.rete.custom.ReteTree import it.unibo.tuprolog.core.Clause -internal abstract class AbstractMutableReteClauseCollection> protected constructor( - rete: ReteTree -) : MutableClauseCollection, AbstractClauseCollection(rete) { +internal abstract class AbstractMutableReteClauseCollection> : + MutableClauseCollection, AbstractClauseCollection { + @Suppress("ConvertSecondaryConstructorToPrimary") + protected constructor(rete: ReteTree) : super(rete) override fun add(clause: Clause): Self { rete.assertZ(clause) diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/AbstractReteClauseCollection.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/AbstractReteClauseCollection.kt index e0357b7d0..fbc9d7453 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/AbstractReteClauseCollection.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/AbstractReteClauseCollection.kt @@ -5,16 +5,15 @@ import it.unibo.tuprolog.core.Clause import it.unibo.tuprolog.theory.TheoryUtils internal abstract class AbstractReteClauseCollection> protected constructor( - rete: ReteTree + rete: ReteTree, ) : AbstractClauseCollection(rete) { - protected abstract fun newCollectionBuilder(rete: ReteTree): Self override fun add(clause: Clause): Self = newCollectionBuilder( rete.deepCopy().apply { assertZ(TheoryUtils.checkClauseCorrect(clause)) - } + }, ) override fun addAll(clauses: Iterable): Self = @@ -23,7 +22,7 @@ internal abstract class AbstractReteClauseCollection { diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/ClauseCollection.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/ClauseCollection.kt index 7874fd4b1..97943e3a4 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/ClauseCollection.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/ClauseCollection.kt @@ -9,7 +9,6 @@ import kotlin.js.JsName import kotlin.jvm.JvmStatic interface ClauseCollection : Iterable { - @JsName("unificator") val unificator: Unificator @@ -59,7 +58,6 @@ interface ClauseCollection : Iterable { override fun iterator(): Iterator companion object { - /** Creates an empty [ClauseMultiSet] **/ @JvmStatic @JsName("emptyMultiSet") @@ -68,31 +66,40 @@ interface ClauseCollection : Iterable { /** Creates a [ClauseMultiSet] with given clauses */ @JvmStatic @JsName("multiSetOf") - fun multiSetOf(unificator: Unificator, vararg clause: Clause): ClauseMultiSet = - multiSetOf(unificator, clause.asIterable()) + fun multiSetOf( + unificator: Unificator, + vararg clause: Clause, + ): ClauseMultiSet = multiSetOf(unificator, clause.asIterable()) /** Let developers easily create a [ClauseMultiSet] programmatically while avoiding variables names clashing */ @JvmStatic @JsName("multiSetOfScopes") - fun multiSetOf(unificator: Unificator, vararg clause: Scope.() -> Clause): ClauseMultiSet = + fun multiSetOf( + unificator: Unificator, + vararg clause: Scope.() -> Clause, + ): ClauseMultiSet = multiSetOf( unificator, clause.map { Scope.empty(it) - } + }, ) /** Creates a [ClauseQueue] from the given [Sequence] of [Clause] */ @JvmStatic @JsName("multiSetOfSequence") - fun multiSetOf(unificator: Unificator, clauses: Sequence): ClauseMultiSet = - multiSetOf(unificator, clauses.asIterable()) + fun multiSetOf( + unificator: Unificator, + clauses: Sequence, + ): ClauseMultiSet = multiSetOf(unificator, clauses.asIterable()) /** Creates a [ClauseQueue] from the given [Iterable] of [Clause] */ @JvmStatic @JsName("multiSetOfIterable") - fun multiSetOf(unificator: Unificator, clauses: Iterable): ClauseMultiSet = - ClauseMultiSet.of(unificator, clauses) + fun multiSetOf( + unificator: Unificator, + clauses: Iterable, + ): ClauseMultiSet = ClauseMultiSet.of(unificator, clauses) /** Creates an empty [ClauseQueue] **/ @JvmStatic @@ -102,30 +109,39 @@ interface ClauseCollection : Iterable { /** Creates a [ClauseQueue] with given clauses */ @JvmStatic @JsName("queueOf") - fun queueOf(unificator: Unificator, vararg clause: Clause): ClauseQueue = - queueOf(unificator, clause.asIterable()) + fun queueOf( + unificator: Unificator, + vararg clause: Clause, + ): ClauseQueue = queueOf(unificator, clause.asIterable()) /** Let developers easily create a [ClauseQueue] programmatically while avoiding variables names clashing */ @JvmStatic @JsName("queueOfScopes") - fun queueOf(unificator: Unificator, vararg clause: Scope.() -> Clause): ClauseQueue = + fun queueOf( + unificator: Unificator, + vararg clause: Scope.() -> Clause, + ): ClauseQueue = queueOf( unificator, clause.map { Scope.empty(it) - } + }, ) /** Creates a [ClauseQueue] from the given [Sequence] of [Clause] */ @JvmStatic @JsName("queueOfSequence") - fun queueOf(unificator: Unificator, clauses: Sequence): ClauseQueue = - queueOf(unificator, clauses.asIterable()) + fun queueOf( + unificator: Unificator, + clauses: Sequence, + ): ClauseQueue = queueOf(unificator, clauses.asIterable()) /** Creates a [ClauseQueue] from the given [Iterable] of [Clause] */ @JvmStatic @JsName("queueOfIterable") - fun queueOf(unificator: Unificator, clauses: Iterable): ClauseQueue = - ClauseQueue.of(unificator, clauses) + fun queueOf( + unificator: Unificator, + clauses: Iterable, + ): ClauseQueue = ClauseQueue.of(unificator, clauses) } } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/ClauseMultiSet.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/ClauseMultiSet.kt index 0db2f5ff6..d901dde81 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/ClauseMultiSet.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/ClauseMultiSet.kt @@ -11,7 +11,6 @@ import kotlin.js.JsName import kotlin.jvm.JvmStatic interface ClauseMultiSet : ClauseCollection { - /** Gives the number of [Clause] that would unify over the given clause. **/ @JsName("count") fun count(clause: Clause): Long @@ -34,7 +33,6 @@ interface ClauseMultiSet : ClauseCollection { override fun retrieveAll(clause: Clause): RetrieveResult companion object { - /** Creates an empty [ClauseMultiSet] **/ @JvmStatic @JsName("empty") @@ -43,38 +41,50 @@ interface ClauseMultiSet : ClauseCollection { /** Creates a [ClauseMultiSet] with given clauses */ @JvmStatic @JsName("of") - fun of(unificator: Unificator, vararg clause: Clause): ClauseMultiSet = - of(unificator, clause.asIterable()) + fun of( + unificator: Unificator, + vararg clause: Clause, + ): ClauseMultiSet = of(unificator, clause.asIterable()) /** Let developers easily create a [ClauseMultiSet] programmatically while avoiding variables names clashing */ @JvmStatic @JsName("ofScopes") - fun of(unificator: Unificator, vararg clause: Scope.() -> Clause): ClauseMultiSet = + fun of( + unificator: Unificator, + vararg clause: Scope.() -> Clause, + ): ClauseMultiSet = of( unificator, clause.map { Scope.empty(it) - } + }, ) /** Creates a [ClauseMultiSet] from the given [Sequence] of [Clause] */ @JvmStatic @JsName("ofSequence") - fun of(unificator: Unificator, clauses: Sequence): ClauseMultiSet = - of(unificator, clauses.asIterable()) + fun of( + unificator: Unificator, + clauses: Sequence, + ): ClauseMultiSet = of(unificator, clauses.asIterable()) /** Creates a [ClauseMultiSet] from the given [Iterable] of [Clause] */ @JvmStatic @JsName("ofIterable") - fun of(unificator: Unificator, clauses: Iterable): ClauseMultiSet = - ReteClauseMultiSet(unificator, clauses) + fun of( + unificator: Unificator, + clauses: Iterable, + ): ClauseMultiSet = ReteClauseMultiSet(unificator, clauses) @JvmStatic @JsName("areEquals") - fun equals(multiSet1: ClauseMultiSet, multiSet2: ClauseMultiSet): Boolean { + fun equals( + multiSet1: ClauseMultiSet, + multiSet2: ClauseMultiSet, + ): Boolean { return itemWiseEquals( multiSet1.sortedWith(TermComparator.DefaultComparator), - multiSet2.sortedWith(TermComparator.DefaultComparator) + multiSet2.sortedWith(TermComparator.DefaultComparator), ) } @@ -83,7 +93,7 @@ interface ClauseMultiSet : ClauseCollection { fun hashCode(multiSet: ClauseMultiSet): Int { return itemWiseHashCode( ClauseMultiSet::class, - multiSet.sortedWith(TermComparator.DefaultComparator) + multiSet.sortedWith(TermComparator.DefaultComparator), ) } } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/ClauseQueue.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/ClauseQueue.kt index fb3520f88..32262f631 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/ClauseQueue.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/ClauseQueue.kt @@ -10,7 +10,6 @@ import kotlin.js.JsName import kotlin.jvm.JvmStatic interface ClauseQueue : ClauseCollection { - /** Gives a freshly produced [ClauseQueue] including the given [Clause] in the first position and the content * of this one **/ @JsName("addFirst") @@ -32,13 +31,11 @@ interface ClauseQueue : ClauseCollection { fun getLifoOrdered(clause: Clause): Sequence /** Produces a [Sequence] of the clauses that would unify over the given [Clause]. Analogous to [getFifoOrdered] **/ - operator fun get(clause: Clause): Sequence = - getFifoOrdered(clause) + operator fun get(clause: Clause): Sequence = getFifoOrdered(clause) /** Gives a freshly produced [ClauseQueue] including the given [Clause] and the content of this one. * Analogous to [addFirst] **/ - override fun add(clause: Clause): ClauseQueue = - addLast(clause) + override fun add(clause: Clause): ClauseQueue = addLast(clause) /** Gives a freshly produced [ClauseQueue] including all the given [Clause] and the content of this one **/ override fun addAll(clauses: Iterable): ClauseQueue @@ -48,52 +45,61 @@ interface ClauseQueue : ClauseCollection { fun retrieveFirst(clause: Clause): RetrieveResult /** Retrieve the first [Clause] unifying the given one. Analogous to [retrieveFirst] **/ - override fun retrieve(clause: Clause): RetrieveResult = - retrieveFirst(clause) + override fun retrieve(clause: Clause): RetrieveResult = retrieveFirst(clause) /** Retrieve all the [Clause] unifying the given one **/ override fun retrieveAll(clause: Clause): RetrieveResult companion object { - /** Creates an empty [ClauseQueue] **/ @JvmStatic @JsName("empty") - fun empty(unificator: Unificator): ClauseQueue = - of(unificator, emptyList()) + fun empty(unificator: Unificator): ClauseQueue = of(unificator, emptyList()) /** Creates a [ClauseQueue] with given clauses */ @JvmStatic @JsName("of") - fun of(unificator: Unificator, vararg clause: Clause): ClauseQueue = - of(unificator, clause.asIterable()) + fun of( + unificator: Unificator, + vararg clause: Clause, + ): ClauseQueue = of(unificator, clause.asIterable()) /** Let developers easily create a [ClauseQueue] programmatically while avoiding variables names clashing */ @JvmStatic @JsName("ofScopes") - fun of(unificator: Unificator, vararg clause: Scope.() -> Clause): ClauseQueue = + fun of( + unificator: Unificator, + vararg clause: Scope.() -> Clause, + ): ClauseQueue = of( unificator, clause.map { Scope.empty(it) - } + }, ) /** Creates a [ClauseQueue] from the given [Sequence] of [Clause] */ @JvmStatic @JsName("ofSequence") - fun of(unificator: Unificator, clauses: Sequence): ClauseQueue = - of(unificator, clauses.asIterable()) + fun of( + unificator: Unificator, + clauses: Sequence, + ): ClauseQueue = of(unificator, clauses.asIterable()) /** Creates a [ClauseQueue] from the given [Iterable] of [Clause] */ @JvmStatic @JsName("ofIterable") - fun of(unificator: Unificator, clauses: Iterable): ClauseQueue = - ReteClauseQueue(unificator, clauses) + fun of( + unificator: Unificator, + clauses: Iterable, + ): ClauseQueue = ReteClauseQueue(unificator, clauses) @JvmStatic @JsName("areEquals") - fun equals(queue1: ClauseQueue, queue2: ClauseQueue): Boolean { + fun equals( + queue1: ClauseQueue, + queue2: ClauseQueue, + ): Boolean { return itemWiseEquals(queue1, queue2) } @@ -102,7 +108,7 @@ interface ClauseQueue : ClauseCollection { fun hashCode(queue: ClauseQueue): Int { return itemWiseHashCode( ClauseQueue::class, - itemWiseHashCode(queue) + itemWiseHashCode(queue), ) } } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/MutableClauseCollection.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/MutableClauseCollection.kt index 9238f5659..2f5e92457 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/MutableClauseCollection.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/MutableClauseCollection.kt @@ -7,7 +7,6 @@ import kotlin.js.JsName import kotlin.jvm.JvmStatic interface MutableClauseCollection : ClauseCollection { - /** Adds the given [Clause] to this [MutableClauseCollection]. **/ override fun add(clause: Clause): MutableClauseCollection @@ -21,75 +20,90 @@ interface MutableClauseCollection : ClauseCollection { override fun retrieveAll(clause: Clause): RetrieveResult companion object { - /** Creates an empty [MutableClauseMultiSet] **/ @JvmStatic @JsName("emptyMultiSet") - fun emptyMultiSet(unificator: Unificator): MutableClauseMultiSet = - multiSetOf(unificator, emptyList()) + fun emptyMultiSet(unificator: Unificator): MutableClauseMultiSet = multiSetOf(unificator, emptyList()) /** Creates a [MutableClauseMultiSet] with given clauses */ @JvmStatic @JsName("multiSetOf") - fun multiSetOf(unificator: Unificator, vararg clause: Clause): MutableClauseMultiSet = - multiSetOf(unificator, clause.asIterable()) + fun multiSetOf( + unificator: Unificator, + vararg clause: Clause, + ): MutableClauseMultiSet = multiSetOf(unificator, clause.asIterable()) /** Let developers easily create a [MutableClauseMultiSet] programmatically while avoiding variables names clashing */ @JvmStatic @JsName("multiSetOfScopes") - fun multiSetOf(unificator: Unificator, vararg clause: Scope.() -> Clause): MutableClauseMultiSet = + fun multiSetOf( + unificator: Unificator, + vararg clause: Scope.() -> Clause, + ): MutableClauseMultiSet = multiSetOf( unificator, clause.map { Scope.empty(it) - } + }, ) /** Creates a [MutableClauseQueue] from the given [Sequence] of [Clause] */ @JvmStatic @JsName("multiSetOfSequence") - fun multiSetOf(unificator: Unificator, clauses: Sequence): MutableClauseMultiSet = - multiSetOf(unificator, clauses.asIterable()) + fun multiSetOf( + unificator: Unificator, + clauses: Sequence, + ): MutableClauseMultiSet = multiSetOf(unificator, clauses.asIterable()) /** Creates a [MutableClauseQueue] from the given [Iterable] of [Clause] */ @JvmStatic @JsName("multiSetOfIterable") - fun multiSetOf(unificator: Unificator, clauses: Iterable): MutableClauseMultiSet = - MutableClauseMultiSet.of(unificator, clauses) + fun multiSetOf( + unificator: Unificator, + clauses: Iterable, + ): MutableClauseMultiSet = MutableClauseMultiSet.of(unificator, clauses) /** Creates an empty [MutableClauseQueue] **/ @JvmStatic @JsName("emptyQueue") - fun emptyQueue(unificator: Unificator): MutableClauseQueue = - queueOf(unificator, emptyList()) + fun emptyQueue(unificator: Unificator): MutableClauseQueue = queueOf(unificator, emptyList()) /** Creates a [MutableClauseQueue] with given clauses */ @JvmStatic @JsName("queueOf") - fun queueOf(unificator: Unificator, vararg clause: Clause): MutableClauseQueue = - queueOf(unificator, clause.asIterable()) + fun queueOf( + unificator: Unificator, + vararg clause: Clause, + ): MutableClauseQueue = queueOf(unificator, clause.asIterable()) /** Let developers easily create a [MutableClauseQueue] programmatically while avoiding variables names clashing */ @JvmStatic @JsName("queueOfScopes") - fun queueOf(unificator: Unificator, vararg clause: Scope.() -> Clause): MutableClauseQueue = + fun queueOf( + unificator: Unificator, + vararg clause: Scope.() -> Clause, + ): MutableClauseQueue = queueOf( unificator, clause.map { Scope.empty(it) - } + }, ) /** Creates a [MutableClauseQueue] from the given [Sequence] of [Clause] */ @JvmStatic @JsName("queueOfSequence") - fun queueOf(unificator: Unificator, clauses: Sequence): MutableClauseQueue = - queueOf(unificator, clauses.asIterable()) + fun queueOf( + unificator: Unificator, + clauses: Sequence, + ): MutableClauseQueue = queueOf(unificator, clauses.asIterable()) /** Creates a [MutableClauseQueue] from the given [Iterable] of [Clause] */ @JvmStatic @JsName("queueOfIterable") - fun queueOf(unificator: Unificator, clauses: Iterable): MutableClauseQueue = - MutableClauseQueue.of(unificator, clauses) + fun queueOf( + unificator: Unificator, + clauses: Iterable, + ): MutableClauseQueue = MutableClauseQueue.of(unificator, clauses) } } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/MutableClauseMultiSet.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/MutableClauseMultiSet.kt index f1d2fad41..1a167936b 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/MutableClauseMultiSet.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/MutableClauseMultiSet.kt @@ -10,7 +10,6 @@ import kotlin.js.JsName import kotlin.jvm.JvmStatic interface MutableClauseMultiSet : ClauseMultiSet { - /** Adds a [Clause] to this [MutableClauseMultiSet] **/ override fun add(clause: Clause): MutableClauseMultiSet @@ -24,7 +23,6 @@ interface MutableClauseMultiSet : ClauseMultiSet { override fun retrieveAll(clause: Clause): RetrieveResult companion object { - /** Creates an empty [MutableClauseMultiSet] **/ @JvmStatic @JsName("empty") @@ -33,35 +31,47 @@ interface MutableClauseMultiSet : ClauseMultiSet { /** Creates a [MutableClauseMultiSet] with given clauses */ @JvmStatic @JsName("of") - fun of(unificator: Unificator, vararg clause: Clause): MutableClauseMultiSet = - of(unificator, clause.asIterable()) + fun of( + unificator: Unificator, + vararg clause: Clause, + ): MutableClauseMultiSet = of(unificator, clause.asIterable()) /** Let developers easily create a [MutableClauseMultiSet] programmatically while avoiding variables names clashing */ @JvmStatic @JsName("ofScopes") - fun of(unificator: Unificator, vararg clause: Scope.() -> Clause): MutableClauseMultiSet = + fun of( + unificator: Unificator, + vararg clause: Scope.() -> Clause, + ): MutableClauseMultiSet = of( unificator, clause.map { Scope.empty(it) - } + }, ) /** Creates a [MutableClauseMultiSet] from the given [Sequence] of [Clause] */ @JvmStatic @JsName("ofSequence") - fun of(unificator: Unificator, clauses: Sequence): MutableClauseMultiSet = - of(unificator, clauses.asIterable()) + fun of( + unificator: Unificator, + clauses: Sequence, + ): MutableClauseMultiSet = of(unificator, clauses.asIterable()) /** Creates a [MutableClauseMultiSet] from the given [Iterable] of [Clause] */ @JvmStatic @JsName("ofIterable") - fun of(unificator: Unificator, clauses: Iterable): MutableClauseMultiSet = - MutableReteClauseMultiSet(unificator, clauses) + fun of( + unificator: Unificator, + clauses: Iterable, + ): MutableClauseMultiSet = MutableReteClauseMultiSet(unificator, clauses) @JvmStatic @JsName("areEquals") - fun equals(multiSet1: MutableClauseMultiSet, multiSet2: MutableClauseMultiSet): Boolean { + fun equals( + multiSet1: MutableClauseMultiSet, + multiSet2: MutableClauseMultiSet, + ): Boolean { return ClauseMultiSet.equals(multiSet1, multiSet2) } @@ -70,7 +80,7 @@ interface MutableClauseMultiSet : ClauseMultiSet { fun hashCode(multiSet: MutableClauseMultiSet): Int { return itemWiseHashCode( MutableClauseMultiSet::class, - multiSet.sortedWith(TermComparator.DefaultComparator) + multiSet.sortedWith(TermComparator.DefaultComparator), ) } } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/MutableClauseQueue.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/MutableClauseQueue.kt index 501e713b0..7c5dffc18 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/MutableClauseQueue.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/MutableClauseQueue.kt @@ -9,7 +9,6 @@ import kotlin.js.JsName import kotlin.jvm.JvmStatic interface MutableClauseQueue : ClauseQueue { - /** Adds the given [Clause] as the first element in this [MutableClauseQueue] **/ override fun addFirst(clause: Clause): MutableClauseQueue @@ -32,7 +31,6 @@ interface MutableClauseQueue : ClauseQueue { override fun retrieveAll(clause: Clause): RetrieveResult companion object { - /** Creates an empty [MutableClauseQueue] **/ @JvmStatic @JsName("empty") @@ -41,34 +39,47 @@ interface MutableClauseQueue : ClauseQueue { /** Creates a [MutableClauseQueue] with given clauses */ @JvmStatic @JsName("of") - fun of(unificator: Unificator, vararg clause: Clause): MutableClauseQueue = of(unificator, clause.asIterable()) + fun of( + unificator: Unificator, + vararg clause: Clause, + ): MutableClauseQueue = of(unificator, clause.asIterable()) /** Let developers easily create a [MutableClauseQueue] programmatically while avoiding variables names clashing */ @JvmStatic @JsName("ofScopes") - fun of(unificator: Unificator, vararg clause: Scope.() -> Clause): MutableClauseQueue = + fun of( + unificator: Unificator, + vararg clause: Scope.() -> Clause, + ): MutableClauseQueue = of( unificator, clause.map { Scope.empty(it) - } + }, ) /** Creates a [MutableClauseQueue] from the given [Sequence] of [Clause] */ @JvmStatic @JsName("ofSequence") - fun of(unificator: Unificator, clauses: Sequence): MutableClauseQueue = - of(unificator, clauses.asIterable()) + fun of( + unificator: Unificator, + clauses: Sequence, + ): MutableClauseQueue = of(unificator, clauses.asIterable()) /** Creates a [MutableClauseQueue] from the given [Iterable] of [Clause] */ @JvmStatic @JsName("ofIterable") - fun of(unificator: Unificator, clauses: Iterable): MutableClauseQueue = - MutableReteClauseQueue(unificator, clauses) + fun of( + unificator: Unificator, + clauses: Iterable, + ): MutableClauseQueue = MutableReteClauseQueue(unificator, clauses) @JvmStatic @JsName("areEquals") - fun equals(queue1: MutableClauseQueue, queue2: MutableClauseQueue): Boolean { + fun equals( + queue1: MutableClauseQueue, + queue2: MutableClauseQueue, + ): Boolean { return ClauseQueue.equals(queue1, queue2) } @@ -77,7 +88,7 @@ interface MutableClauseQueue : ClauseQueue { fun hashCode(queue: MutableClauseQueue): Int { return itemWiseHashCode( MutableClauseQueue::class, - itemWiseHashCode(queue) + itemWiseHashCode(queue), ) } } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/RetrieveResult.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/RetrieveResult.kt index 8e67cdcab..f0523b49a 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/RetrieveResult.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/RetrieveResult.kt @@ -4,7 +4,6 @@ import it.unibo.tuprolog.core.Clause import kotlin.js.JsName sealed class RetrieveResult { - open val isSuccess: Boolean get() = false @@ -22,7 +21,7 @@ sealed class RetrieveResult { data class Success( override val collection: C, - override val clauses: List + override val clauses: List, ) : RetrieveResult() { override val isSuccess: Boolean get() = true diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/impl/MutableReteClauseMultiSet.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/impl/MutableReteClauseMultiSet.kt index 2325fd0cb..e04711676 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/impl/MutableReteClauseMultiSet.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/impl/MutableReteClauseMultiSet.kt @@ -8,9 +8,8 @@ import it.unibo.tuprolog.theory.TheoryUtils import it.unibo.tuprolog.unify.Unificator internal class MutableReteClauseMultiSet private constructor( - rete: ReteTree + rete: ReteTree, ) : MutableClauseMultiSet, AbstractMutableReteClauseCollection(rete) { - init { require(!rete.isOrdered) } @@ -20,11 +19,9 @@ internal class MutableReteClauseMultiSet private constructor( TheoryUtils.checkClausesCorrect(clauses) } - override fun count(clause: Clause): Long = - rete.get(clause).count().toLong() + override fun count(clause: Clause): Long = rete.get(clause).count().toLong() - override fun get(clause: Clause): Sequence = - rete.get(clause) + override fun get(clause: Clause): Sequence = rete.get(clause) override fun equals(other: Any?): Boolean { return if (other is MutableClauseMultiSet) { diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/impl/MutableReteClauseQueue.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/impl/MutableReteClauseQueue.kt index 1599659df..539af7852 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/impl/MutableReteClauseQueue.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/impl/MutableReteClauseQueue.kt @@ -9,9 +9,8 @@ import it.unibo.tuprolog.theory.TheoryUtils import it.unibo.tuprolog.unify.Unificator internal class MutableReteClauseQueue private constructor( - rete: ReteTree + rete: ReteTree, ) : MutableClauseQueue, AbstractMutableReteClauseCollection(rete) { - init { require(rete.isOrdered) } @@ -21,11 +20,12 @@ internal class MutableReteClauseQueue private constructor( TheoryUtils.checkClausesCorrect(clauses) } - override fun getFifoOrdered(clause: Clause): Sequence = - rete.get(clause) + override fun getFifoOrdered(clause: Clause): Sequence = rete.get(clause) override fun getLifoOrdered(clause: Clause): Sequence = - getFifoOrdered(clause).toList().asReversed().asSequence() + getFifoOrdered( + clause, + ).toList().asReversed().asSequence() override fun addFirst(clause: Clause): MutableReteClauseQueue { rete.assertA(clause) @@ -46,7 +46,7 @@ internal class MutableReteClauseQueue private constructor( else -> RetrieveResult.Success( this, - retracted.toList() + retracted.toList(), ) } } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/impl/ReteClauseMultiSet.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/impl/ReteClauseMultiSet.kt index 8c9e3a2be..749c23ba2 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/impl/ReteClauseMultiSet.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/impl/ReteClauseMultiSet.kt @@ -9,9 +9,8 @@ import it.unibo.tuprolog.theory.TheoryUtils import it.unibo.tuprolog.unify.Unificator internal class ReteClauseMultiSet private constructor( - rete: ReteTree + rete: ReteTree, ) : ClauseMultiSet, AbstractReteClauseCollection(rete) { - private val hashCodeCache by lazy { ClauseMultiSet.hashCode(this) } @@ -25,11 +24,9 @@ internal class ReteClauseMultiSet private constructor( TheoryUtils.checkClausesCorrect(clauses) } - override fun count(clause: Clause): Long = - rete.get(clause).count().toLong() + override fun count(clause: Clause): Long = rete.get(clause).count().toLong() - override fun get(clause: Clause): Sequence = - rete.get(clause) + override fun get(clause: Clause): Sequence = rete.get(clause) override fun newCollectionBuilder(rete: ReteTree): ReteClauseMultiSet { return ReteClauseMultiSet(rete) diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/impl/ReteClauseQueue.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/impl/ReteClauseQueue.kt index 6c727a1eb..a83c90484 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/impl/ReteClauseQueue.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/impl/ReteClauseQueue.kt @@ -10,9 +10,8 @@ import it.unibo.tuprolog.theory.TheoryUtils import it.unibo.tuprolog.unify.Unificator internal class ReteClauseQueue private constructor( - rete: ReteTree + rete: ReteTree, ) : ClauseQueue, AbstractReteClauseCollection(rete) { - private val hashCodeCache by lazy { ClauseQueue.hashCode(this) } @@ -30,33 +29,36 @@ internal class ReteClauseQueue private constructor( ReteClauseQueue( rete.deepCopy().apply { assertA(TheoryUtils.checkClauseCorrect(clause)) - } + }, ) override fun addLast(clause: Clause): ReteClauseQueue = ReteClauseQueue( rete.deepCopy().apply { assertZ(TheoryUtils.checkClauseCorrect(clause)) - } + }, ) - override fun getFifoOrdered(clause: Clause): Sequence = - rete.get(clause) + override fun getFifoOrdered(clause: Clause): Sequence = rete.get(clause) override fun getLifoOrdered(clause: Clause): Sequence = - getFifoOrdered(clause).toList().asReversed().asSequence() + getFifoOrdered( + clause, + ).toList().asReversed().asSequence() - override fun add(clause: Clause): ReteClauseQueue = - addLast(clause) + override fun add(clause: Clause): ReteClauseQueue = addLast(clause) override fun retrieve(clause: Clause): RetrieveResult = - super.retrieve(clause) + super.retrieve( + clause, + ) override fun retrieveFirst(clause: Clause): RetrieveResult = - super.retrieve(clause) + super.retrieve( + clause, + ) - override fun newCollectionBuilder(rete: ReteTree): ReteClauseQueue = - ReteClauseQueue(rete) + override fun newCollectionBuilder(rete: ReteTree): ReteClauseQueue = ReteClauseQueue(rete) override fun equals(other: Any?): Boolean { return if (other is ClauseQueue && other !is MutableClauseQueue) { diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/AbstractReteNode.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/AbstractReteNode.kt index cd1e75542..8654af1cc 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/AbstractReteNode.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/AbstractReteNode.kt @@ -5,7 +5,10 @@ import it.unibo.tuprolog.core.Clause import it.unibo.tuprolog.unify.Unificator internal abstract class AbstractReteNode(override val unificator: Unificator) : ReteNode { - fun removeAllLazily(source: MutableList, clause: Clause): Sequence = + fun removeAllLazily( + source: MutableList, + clause: Clause, + ): Sequence = sequence { val iter = source.iterator() while (iter.hasNext()) { diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/Cacheable.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/Cacheable.kt index 4be2e5ec3..5851d928a 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/Cacheable.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/Cacheable.kt @@ -4,7 +4,6 @@ import it.unibo.tuprolog.collections.rete.custom.clause.SituatedIndexedClause /**Marks a Class as capable of managing a cache of [SituatedIndexedClause].*/ internal interface Cacheable { - /** Retrieves the cache of the current level in the indexing tree */ fun getCache(): Sequence diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/IndexingLeaf.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/IndexingLeaf.kt index f2d9310ed..2583cc97f 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/IndexingLeaf.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/IndexingLeaf.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.core.Clause /**Denotes a [ReteNode] capable of managing intermediate operation upon its children, * so that the results these will provide can be more fine grained elaborated*/ internal interface IndexingLeaf : ReteNode { - /**Read the single first [SituatedIndexedClause] matching the given [Clause], returning null if * such a condition is never met. The concept of "first" may vary between implementations */ fun getFirstIndexed(clause: Clause): SituatedIndexedClause? diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/ReteNode.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/ReteNode.kt index 03bfa3e5a..eabfeecd9 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/ReteNode.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/ReteNode.kt @@ -8,7 +8,6 @@ import kotlin.js.JsName /**A data structure to manage the basic behaviour of the [ReteTree]*/ internal interface ReteNode : Cacheable { - @JsName("unificator") val unificator: Unificator diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/ReteTree.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/ReteTree.kt index e2defe679..b47b93336 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/ReteTree.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/ReteTree.kt @@ -8,7 +8,6 @@ import it.unibo.tuprolog.unify.Unificator import kotlin.js.JsName interface ReteTree { - @JsName("unificator") val unificator: Unificator @@ -46,7 +45,10 @@ interface ReteTree { fun retractFirst(clause: Clause): Sequence /**Retracts only the given number of matching clauses from this [ReteTree]*/ - fun retractOnly(clause: Clause, limit: Int): Sequence + fun retractOnly( + clause: Clause, + limit: Int, + ): Sequence /**Retracts all the matching clauses from this [ReteTree]*/ fun retractAll(clause: Clause): Sequence @@ -56,27 +58,33 @@ interface ReteTree { companion object { /**Creates an empty unordered [ReteTree]*/ - fun emptyUnordered(unificator: Unificator): ReteTree = - unordered(unificator, emptyList()) + fun emptyUnordered(unificator: Unificator): ReteTree = unordered(unificator, emptyList()) /**Creates an unordered ReteTree based on the given [Iterable]*/ - fun unordered(unificator: Unificator, clauses: Iterable): ReteTree = - RootNode(unificator, clauses, false) + fun unordered( + unificator: Unificator, + clauses: Iterable, + ): ReteTree = RootNode(unificator, clauses, false) /**Creates an unordered ReteTree based on the given vararg*/ - fun unordered(unificator: Unificator, vararg clauses: Clause): ReteTree = - unordered(unificator, listOf(*clauses)) + fun unordered( + unificator: Unificator, + vararg clauses: Clause, + ): ReteTree = unordered(unificator, listOf(*clauses)) /**Creates an empty ordered [ReteTree]*/ - fun emptyOrdered(unificator: Unificator): ReteTree = - ordered(unificator, emptyList()) + fun emptyOrdered(unificator: Unificator): ReteTree = ordered(unificator, emptyList()) /**Creates an ordered ReteTree based on the given [Iterable]*/ - fun ordered(unificator: Unificator, clauses: Iterable): ReteTree = - RootNode(unificator, clauses, true) + fun ordered( + unificator: Unificator, + clauses: Iterable, + ): ReteTree = RootNode(unificator, clauses, true) /**Creates an ordered ReteTree based on the given vararg*/ - fun ordered(unificator: Unificator, vararg clauses: Clause): ReteTree = - ordered(unificator, listOf(*clauses)) + fun ordered( + unificator: Unificator, + vararg clauses: Clause, + ): ReteTree = ordered(unificator, listOf(*clauses)) } } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/Retractable.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/Retractable.kt index de0c391b4..00af66319 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/Retractable.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/Retractable.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.collections.rete.custom.clause.SituatedIndexedClause /**Functional Interface aimed at marking a particular member of the [ReteTree] able of effectfully remove * the given [SituatedIndexedClause] from the storage*/ internal interface Retractable { - /**Removes the given [SituatedIndexedClause] from the storage of this node*/ fun retractIndexed(indexed: SituatedIndexedClause) } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/TopLevelReteNode.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/TopLevelReteNode.kt index 720f5175c..22db3e7ad 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/TopLevelReteNode.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/TopLevelReteNode.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.core.Clause * foreseeing to take strong decisions upon the actions to be performed on the subtrees it branches on */ internal interface TopLevelReteNode : ReteNode { - /**Retracts the first matching occurrence of the given [Clause] from this [ReteTree]*/ fun retractFirst(clause: Clause): Sequence } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/Utils.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/Utils.kt index 0d967deb8..a7be6b615 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/Utils.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/Utils.kt @@ -8,7 +8,6 @@ import it.unibo.tuprolog.core.Term import it.unibo.tuprolog.utils.mergeSequences internal object Utils { - /**Calculate the arity of the first argument of any [Struct], at the given nesting level. * No checks are performed upon the validity of the Struct this extension method is called upon. */ fun Struct.arityOfNestedFirstArgument(nestingLevel: Int): Int = @@ -21,8 +20,7 @@ internal object Utils { /**Calculate the [Term] representing the first argument of any [Struct], at the given nesting level. * No checks are performed upon the validity of the Struct this extension method is called upon. */ - fun Struct.nestedFirstArgument(nestingLevel: Int): Term = - this.firstArguments().takeFirstAfterSkipping(nestingLevel) + fun Struct.nestedFirstArgument(nestingLevel: Int): Term = this.firstArguments().takeFirstAfterSkipping(nestingLevel) private fun Struct.firstArguments(): Sequence = sequence { @@ -35,8 +33,7 @@ internal object Utils { } /**Sorts all the given [Sequence] of [SituatedIndexedClause]*/ - fun merge(vararg args: Sequence): Sequence = - merge(listOf(*args)) + fun merge(vararg args: Sequence): Sequence = merge(listOf(*args)) /**Sorts all the given [Sequence] of [SituatedIndexedClause]*/ fun merge(sequence: Sequence>): Sequence = @@ -59,19 +56,19 @@ internal object Utils { flattenIndexed(iterable.asSequence()) /**Composes all the given [Sequence] of [Clause], disregarding order*/ - fun flatten(vararg args: Sequence): Sequence = - flatten(sequenceOf(*args)) + fun flatten(vararg args: Sequence): Sequence = flatten(sequenceOf(*args)) /**Composes all the given [Sequence] of [Clause], disregarding order*/ - fun flatten(sequence: Sequence>): Sequence = - sequence.flatten() + fun flatten(sequence: Sequence>): Sequence = sequence.flatten() /**Composes all the given [Sequence] of [Clause], disregarding order*/ - fun flatten(iterable: Iterable>): Sequence = - flatten(iterable.asSequence()) + fun flatten(iterable: Iterable>): Sequence = flatten(iterable.asSequence()) /**Compares two nullable [SituatedIndexedClause]. If both are null, null is returned*/ - fun comparePriority(a: SituatedIndexedClause?, b: SituatedIndexedClause?): SituatedIndexedClause? = + fun comparePriority( + a: SituatedIndexedClause?, + b: SituatedIndexedClause?, + ): SituatedIndexedClause? = when { a == null && b == null -> null a == null -> b diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/clause/IndexedClause.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/clause/IndexedClause.kt index 5eec47b6a..82cb5d63f 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/clause/IndexedClause.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/clause/IndexedClause.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.core.Clause import it.unibo.tuprolog.utils.LongIndexed internal interface IndexedClause : LongIndexed { - /**Retrieves the decorated [Clause]*/ val innerClause: Clause get() = value @@ -14,11 +13,13 @@ internal interface IndexedClause : LongIndexed { fun invalidateAllCaches() - operator fun plus(traversed: Cacheable<*>): IndexedClause = - of(index, innerClause, traversedCacheables + traversed) + operator fun plus(traversed: Cacheable<*>): IndexedClause = of(index, innerClause, traversedCacheables + traversed) companion object { - fun wrap(indexedClause: LongIndexed, vararg traversed: Cacheable<*>): IndexedClause { + fun wrap( + indexedClause: LongIndexed, + vararg traversed: Cacheable<*>, + ): IndexedClause { return object : IndexedClause { override val index: Long get() = indexedClause.index @@ -32,22 +33,29 @@ internal interface IndexedClause : LongIndexed { traversedCacheables.forEach { it.invalidateCache() } } - override fun map(mapper: (Clause) -> R) = - indexedClause.map(mapper) + override fun map(mapper: (Clause) -> R) = indexedClause.map(mapper) } } - fun of(index: Long, clause: Clause, vararg traversed: Cacheable<*>): IndexedClause { + fun of( + index: Long, + clause: Clause, + vararg traversed: Cacheable<*>, + ): IndexedClause { return wrap( LongIndexed.of(index, clause), - *traversed + *traversed, ) } - fun of(index: Long, clause: Clause, traversed: List>): IndexedClause { + fun of( + index: Long, + clause: Clause, + traversed: List>, + ): IndexedClause { return wrap( LongIndexed.of(index, clause), - *traversed.toTypedArray() + *traversed.toTypedArray(), ) } } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/clause/SituatedIndexedClause.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/clause/SituatedIndexedClause.kt index 6ffd06cc7..15cfd9a21 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/clause/SituatedIndexedClause.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/clause/SituatedIndexedClause.kt @@ -5,12 +5,14 @@ import it.unibo.tuprolog.collections.rete.custom.Retractable import it.unibo.tuprolog.core.Clause internal interface SituatedIndexedClause : IndexedClause { - /**Effectfully removes this [Clause] from whatever it is situated*/ fun removeFromIndex() companion object { - fun of(indexed: IndexedClause, index: Retractable): SituatedIndexedClause { + fun of( + indexed: IndexedClause, + index: Retractable, + ): SituatedIndexedClause { return object : SituatedIndexedClause { override val index: Long get() = indexed.index @@ -18,8 +20,7 @@ internal interface SituatedIndexedClause : IndexedClause { override val value: Clause get() = indexed.value - override fun map(mapper: (Clause) -> R) = - indexed.map(mapper) + override fun map(mapper: (Clause) -> R) = indexed.map(mapper) override fun removeFromIndex() { index.retractIndexed(this) diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/AbstractIndexingLeaf.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/AbstractIndexingLeaf.kt index 49c9b75e7..951908e53 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/AbstractIndexingLeaf.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/AbstractIndexingLeaf.kt @@ -6,6 +6,6 @@ import it.unibo.tuprolog.unify.Unificator internal abstract class AbstractIndexingLeaf(unificator: Unificator) : IndexingLeaf, AbstractReteNode(unificator) { override fun invalidateCache() { - /* do nothing */ + // do nothing } } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/AtomIndex.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/AtomIndex.kt index ff912a282..185ecaa6a 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/AtomIndex.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/AtomIndex.kt @@ -16,9 +16,8 @@ import it.unibo.tuprolog.utils.dequeOf internal class AtomIndex( unificator: Unificator, private val ordered: Boolean, - private val nestingLevel: Int + private val nestingLevel: Int, ) : AbstractIndexingLeaf(unificator), Retractable { - private val index: MutableMap> = mutableMapOf() override val size: Int @@ -72,7 +71,10 @@ internal class AtomIndex( extractFirst(clause, it) }.minOrNull() - private fun extractFirst(clause: Clause, index: MutableList): SituatedIndexedClause? { + private fun extractFirst( + clause: Clause, + index: MutableList, + ): SituatedIndexedClause? { val actualIndex = index.indexOfFirst { unificator.match(it.innerClause, clause) } return if (actualIndex == -1) { @@ -107,32 +109,33 @@ internal class AtomIndex( Utils.merge( index.values.asSequence().map { removeAllLazily(it, clause) - } + }, ) }.buffered() } - override fun retractAll(clause: Clause): Sequence = - retractAllIndexed(clause).map { it.innerClause } + override fun retractAll(clause: Clause): Sequence = retractAllIndexed(clause).map { it.innerClause } override fun getCache(): Sequence = - Utils.merge(index.values.asSequence().map { it.asSequence() }) + Utils.merge( + index.values.asSequence().map { + it.asSequence() + }, + ) override fun extractGlobalIndexedSequence(clause: Clause): Sequence = getCache().filter { unificator.match(it.innerClause, clause) } private fun extractGlobalSequence(clause: Clause): Sequence = - extractGlobalIndexedSequence(clause).map { it.innerClause } + extractGlobalIndexedSequence(clause).map { + it.innerClause + } - private fun Clause.nestedFirstArgument(): Term = - this.head!!.nestedFirstArgument(nestingLevel + 1) + private fun Clause.nestedFirstArgument(): Term = this.head!!.nestedFirstArgument(nestingLevel + 1) - private fun Clause.asInnerAtom(): Atom = - this.nestedFirstArgument().castToAtom() + private fun Clause.asInnerAtom(): Atom = this.nestedFirstArgument().castToAtom() - private fun SituatedIndexedClause.asInnerAtom(): Atom = - this.innerClause.nestedFirstArgument().castToAtom() + private fun SituatedIndexedClause.asInnerAtom(): Atom = this.innerClause.nestedFirstArgument().castToAtom() - private fun IndexedClause.asInnerAtom(): Atom = - this.innerClause.nestedFirstArgument().castToAtom() + private fun IndexedClause.asInnerAtom(): Atom = this.innerClause.nestedFirstArgument().castToAtom() } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/CompoundIndex.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/CompoundIndex.kt index 0fff39cf0..42c3f7a93 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/CompoundIndex.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/CompoundIndex.kt @@ -17,9 +17,8 @@ import it.unibo.tuprolog.utils.dequeOf internal class CompoundIndex( unificator: Unificator, private val ordered: Boolean, - private val nestingLevel: Int + private val nestingLevel: Int, ) : IndexingNode, AbstractReteNode(unificator) { - private val functors: MutableMap = mutableMapOf() private val theoryCache: Cached> = Cached.of(this::regenerateCache) @@ -35,13 +34,13 @@ internal class CompoundIndex( Utils.merge( functors.values.asSequence().flatMap { it.getIndexed(clause) - } + }, ).map { it.innerClause } } else { Utils.flatten( functors.values.asSequence().flatMap { it.get(clause) - } + }, ) } } else { @@ -73,15 +72,14 @@ internal class CompoundIndex( retractAllUnordered(clause) } - override fun getCache(): Sequence = - theoryCache.value.asSequence() + override fun getCache(): Sequence = theoryCache.value.asSequence() private fun retractAllOrdered(clause: Clause): Sequence = if (clause.isGlobal()) { Utils.merge( functors.values.map { it.retractAllIndexed(clause) - } + }, ).map { it.innerClause } } else { functors[clause.nestedFunctor()] @@ -94,7 +92,7 @@ internal class CompoundIndex( Utils.flatten( functors.values.map { it.retractAll(clause) - } + }, ) } else { functors[clause.nestedFunctor()] @@ -108,8 +106,8 @@ internal class CompoundIndex( sequenceOf( functors.values.mapNotNull { it.getFirstIndexed(clause) - }.asSequence() - ) + }.asSequence(), + ), ).firstOrNull() } else { functors[clause.nestedFunctor()] @@ -121,7 +119,7 @@ internal class CompoundIndex( Utils.merge( functors.values.map { it.extractGlobalIndexedSequence(clause) - } + }, ) } else { functors[clause.nestedFunctor()] @@ -134,7 +132,7 @@ internal class CompoundIndex( Utils.merge( functors.values.map { it.retractAllIndexed(clause) - } + }, ) } else { functors[clause.nestedFunctor()] @@ -147,25 +145,25 @@ internal class CompoundIndex( Utils.merge( functors.values.map { it.extractGlobalIndexedSequence(clause) - } + }, ) } else { Utils.flattenIndexed( functors.values.map { it.extractGlobalIndexedSequence(clause) - } + }, ) } } - private fun Clause.nestedFunctor(): String = - this.head!!.functorOfNestedFirstArgument(nestingLevel) + private fun Clause.nestedFunctor(): String = this.head!!.functorOfNestedFirstArgument(nestingLevel) private fun IndexedClause.nestedFunctor(): String = - this.innerClause.head!!.functorOfNestedFirstArgument(nestingLevel) + this.innerClause.head!!.functorOfNestedFirstArgument( + nestingLevel, + ) - private fun Clause.isGlobal(): Boolean = - this.head!!.nestedFirstArgument(nestingLevel).isVar + private fun Clause.isGlobal(): Boolean = this.head!!.nestedFirstArgument(nestingLevel).isVar override fun invalidateCache() { theoryCache.invalidate() @@ -178,14 +176,14 @@ internal class CompoundIndex( Utils.merge( functors.values.map { it.getCache() - } + }, ) } else { Utils.flattenIndexed( functors.values.map { outer -> outer.getCache() - } + }, ) - } + }, ) } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/DirectiveIndex.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/DirectiveIndex.kt index 2ec837461..c639ff918 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/DirectiveIndex.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/DirectiveIndex.kt @@ -13,9 +13,8 @@ import it.unibo.tuprolog.utils.dequeOf internal class DirectiveIndex( unificator: Unificator, - private val ordered: Boolean + private val ordered: Boolean, ) : TopLevelReteNode, AbstractReteNode(unificator) { - private val directives: MutableList = dequeOf() override val size: Int @@ -46,7 +45,9 @@ internal class DirectiveIndex( removeAllLazily(directives, clause).map { it.innerClause }.take(1).buffered() override fun retractAll(clause: Clause): Sequence = - removeAllLazily(directives, clause).map { it.innerClause }.buffered() + removeAllLazily(directives, clause).map { + it.innerClause + }.buffered() override fun getCache(): Sequence = directives.asSequence().map { @@ -55,17 +56,17 @@ internal class DirectiveIndex( object : Retractable { override fun retractIndexed(indexed: SituatedIndexedClause) { TODO( - "Directives are adapted as a SituatedIndexedClause, but they are not actually stored " + - "with this type. Given their particular semantic, try retracting directly with a proper " + - "query, or opening a pull request implementing this indexing class as a proper typed data " + - "structure" + "Directives are adapted as a SituatedIndexedClause, but they are not " + + "actually stored with this type. Given their particular semantic, try retracting " + + "directly with a proper query, or opening a pull request implementing this indexing " + + "class as a proper typed data structure", ) } - } + }, ) } override fun invalidateCache() { - /* do nothing */ + // do nothing } } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/NumericIndex.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/NumericIndex.kt index 28091f77b..b7e6dc20a 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/NumericIndex.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/NumericIndex.kt @@ -16,9 +16,8 @@ import it.unibo.tuprolog.utils.dequeOf internal class NumericIndex( unificator: Unificator, private val ordered: Boolean, - private val nestingLevel: Int + private val nestingLevel: Int, ) : AbstractIndexingLeaf(unificator), Retractable { - private val index: MutableMap> = mutableMapOf() override val size: Int @@ -74,7 +73,10 @@ internal class NumericIndex( extractFirst(clause, it) }.minOrNull() - private fun extractFirst(clause: Clause, index: MutableList): SituatedIndexedClause? { + private fun extractFirst( + clause: Clause, + index: MutableList, + ): SituatedIndexedClause? { val actualIndex = index.indexOfFirst { unificator.match(it.innerClause, clause) } return if (actualIndex == -1) { @@ -109,32 +111,33 @@ internal class NumericIndex( Utils.merge( index.values.asSequence().map { removeAllLazily(it, clause) - } + }, ).buffered() } } - override fun retractAll(clause: Clause): Sequence = - retractAllIndexed(clause).map { it.innerClause } + override fun retractAll(clause: Clause): Sequence = retractAllIndexed(clause).map { it.innerClause } override fun getCache(): Sequence = - Utils.merge(index.values.asSequence().map { it.asSequence() }) + Utils.merge( + index.values.asSequence().map { + it.asSequence() + }, + ) override fun extractGlobalIndexedSequence(clause: Clause): Sequence = getCache().filter { unificator.match(it.innerClause, clause) } private fun extractGlobalSequence(clause: Clause): Sequence = - extractGlobalIndexedSequence(clause).map { it.innerClause } + extractGlobalIndexedSequence(clause).map { + it.innerClause + } - private fun Clause.nestedFirstArgument(): Term = - this.head!!.nestedFirstArgument(nestingLevel + 1) + private fun Clause.nestedFirstArgument(): Term = this.head!!.nestedFirstArgument(nestingLevel + 1) - private fun Clause.asInnerNumeric(): Numeric = - this.nestedFirstArgument().castToNumeric() + private fun Clause.asInnerNumeric(): Numeric = this.nestedFirstArgument().castToNumeric() - private fun SituatedIndexedClause.asInnerNumeric(): Numeric = - this.innerClause.nestedFirstArgument().castToNumeric() + private fun SituatedIndexedClause.asInnerNumeric(): Numeric = this.innerClause.nestedFirstArgument().castToNumeric() - private fun IndexedClause.asInnerNumeric(): Numeric = - this.innerClause.nestedFirstArgument().castToNumeric() + private fun IndexedClause.asInnerNumeric(): Numeric = this.innerClause.nestedFirstArgument().castToNumeric() } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/VariableIndex.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/VariableIndex.kt index d3a7063ea..64ccb576b 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/VariableIndex.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/leaf/VariableIndex.kt @@ -11,9 +11,8 @@ import it.unibo.tuprolog.utils.dequeOf internal class VariableIndex( unificator: Unificator, - private val ordered: Boolean + private val ordered: Boolean, ) : AbstractIndexingLeaf(unificator), Retractable { - private val variables: MutableList = dequeOf() override val size: Int @@ -22,8 +21,7 @@ internal class VariableIndex( override val isEmpty: Boolean get() = variables.isEmpty() - override fun get(clause: Clause): Sequence = - extractGlobalSequence(clause) + override fun get(clause: Clause): Sequence = extractGlobalSequence(clause) override fun assertA(clause: IndexedClause) = if (ordered) { @@ -36,27 +34,30 @@ internal class VariableIndex( variables.add(SituatedIndexedClause.of(clause + this, this)) } - override fun retractAll(clause: Clause): Sequence = - retractAllIndexed(clause).map { it.innerClause } + override fun retractAll(clause: Clause): Sequence = retractAllIndexed(clause).map { it.innerClause } - override fun getCache(): Sequence = - variables.asSequence() + override fun getCache(): Sequence = variables.asSequence() override fun getFirstIndexed(clause: Clause): SituatedIndexedClause? { return extractFirst(clause, variables) } - override fun getIndexed(clause: Clause): Sequence = - extractGlobalIndexedSequence(clause) + override fun getIndexed(clause: Clause): Sequence = extractGlobalIndexedSequence(clause) override fun retractIndexed(indexed: SituatedIndexedClause) { variables.remove(indexed) } override fun retractAllIndexed(clause: Clause): Sequence = - removeAllLazily(variables, clause).buffered() - - private fun extractFirst(clause: Clause, index: MutableList): SituatedIndexedClause? { + removeAllLazily( + variables, + clause, + ).buffered() + + private fun extractFirst( + clause: Clause, + index: MutableList, + ): SituatedIndexedClause? { val actualIndex = index.indexOfFirst { unificator.match(it.innerClause, clause) } return if (actualIndex == -1) { @@ -70,5 +71,7 @@ internal class VariableIndex( variables.asSequence().filter { unificator.match(it.innerClause, clause) } private fun extractGlobalSequence(clause: Clause): Sequence = - extractGlobalIndexedSequence(clause).map { it.innerClause } + extractGlobalIndexedSequence(clause).map { + it.innerClause + } } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/FamilyArityIndexingNode.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/FamilyArityIndexingNode.kt index 8a86e6dfe..ec6c06054 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/FamilyArityIndexingNode.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/FamilyArityIndexingNode.kt @@ -8,9 +8,8 @@ import it.unibo.tuprolog.unify.Unificator internal class FamilyArityIndexingNode( unificator: Unificator, private val ordered: Boolean, - nestingLevel: Int + nestingLevel: Int, ) : FamilyArityReteNode(unificator, ordered, nestingLevel), ArityIndexing { - override fun getFirstIndexed(clause: Clause): SituatedIndexedClause? = if (ordered) { orderedLookahead(clause) @@ -38,14 +37,14 @@ internal class FamilyArityIndexingNode( atomicIndex.extractGlobalIndexedSequence(clause), numericIndex.extractGlobalIndexedSequence(clause), variableIndex.extractGlobalIndexedSequence(clause), - compoundIndex.extractGlobalIndexedSequence(clause) + compoundIndex.extractGlobalIndexedSequence(clause), ) } else { Utils.flattenIndexed( atomicIndex.extractGlobalIndexedSequence(clause), numericIndex.extractGlobalIndexedSequence(clause), variableIndex.extractGlobalIndexedSequence(clause), - compoundIndex.extractGlobalIndexedSequence(clause) + compoundIndex.extractGlobalIndexedSequence(clause), ) } } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/FamilyArityReteNode.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/FamilyArityReteNode.kt index 42185101c..d322c1655 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/FamilyArityReteNode.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/FamilyArityReteNode.kt @@ -18,9 +18,8 @@ import it.unibo.tuprolog.utils.dequeOf internal open class FamilyArityReteNode( unificator: Unificator, private val ordered: Boolean, - private val nestingLevel: Int + private val nestingLevel: Int, ) : ArityNode(unificator), ArityRete { - protected val numericIndex: IndexingLeaf = NumericIndex(unificator, ordered, nestingLevel) @@ -37,11 +36,12 @@ internal open class FamilyArityReteNode( Cached.of(this::regenerateCache) override fun retractFirst(clause: Clause): Sequence { - val result = if (ordered) { - orderedLookahead(clause) - } else { - anyLookahead(clause) - } + val result = + if (ordered) { + orderedLookahead(clause) + } else { + anyLookahead(clause) + } return if (result == null) { emptySequence() @@ -65,14 +65,14 @@ internal open class FamilyArityReteNode( atomicIndex.extractGlobalIndexedSequence(clause), variableIndex.extractGlobalIndexedSequence(clause), numericIndex.extractGlobalIndexedSequence(clause), - compoundIndex.extractGlobalIndexedSequence(clause) + compoundIndex.extractGlobalIndexedSequence(clause), ).map { it.innerClause } } else { Utils.flattenIndexed( atomicIndex.extractGlobalIndexedSequence(clause), variableIndex.extractGlobalIndexedSequence(clause), numericIndex.extractGlobalIndexedSequence(clause), - compoundIndex.extractGlobalIndexedSequence(clause) + compoundIndex.extractGlobalIndexedSequence(clause), ).map { it.innerClause } } } else { @@ -84,11 +84,9 @@ internal open class FamilyArityReteNode( } } - override fun assertA(clause: IndexedClause) = - assertByFirstParameter(clause).assertA(clause + this) + override fun assertA(clause: IndexedClause) = assertByFirstParameter(clause).assertA(clause + this) - override fun assertZ(clause: IndexedClause) = - assertByFirstParameter(clause).assertZ(clause + this) + override fun assertZ(clause: IndexedClause) = assertByFirstParameter(clause).assertZ(clause + this) override fun retractAll(clause: Clause): Sequence = if (ordered) { @@ -97,20 +95,21 @@ internal open class FamilyArityReteNode( retractAllUnordered(clause) } - override fun getCache(): Sequence = - theoryCache.value.asSequence() + override fun getCache(): Sequence = theoryCache.value.asSequence() private fun retractAllOrdered(clause: Clause): Sequence = - retractAllOrderedIndexed(clause).map { it.innerClause } + retractAllOrderedIndexed(clause).map { + it.innerClause + } - private fun getOrdered(clause: Clause): Sequence = - getOrderedIndexed(clause).map { it.innerClause } + private fun getOrdered(clause: Clause): Sequence = getOrderedIndexed(clause).map { it.innerClause } private fun retractAllUnordered(clause: Clause): Sequence = - retractAllUnorderedIndexed(clause).map { it.innerClause } + retractAllUnorderedIndexed(clause).map { + it.innerClause + } - private fun getUnordered(clause: Clause): Sequence = - getUnorderedIndexed(clause).map { it.innerClause } + private fun getUnordered(clause: Clause): Sequence = getUnorderedIndexed(clause).map { it.innerClause } protected fun retractAllOrderedIndexed(clause: Clause): Sequence { val innerFirst = clause.nestedFirstArgument() @@ -118,13 +117,13 @@ internal open class FamilyArityReteNode( innerFirst.isNumber -> { Utils.merge( variableIndex.retractAllIndexed(clause), - numericIndex.retractAllIndexed(clause) + numericIndex.retractAllIndexed(clause), ) } innerFirst.isAtom -> { Utils.merge( variableIndex.retractAllIndexed(clause), - atomicIndex.retractAllIndexed(clause) + atomicIndex.retractAllIndexed(clause), ) } innerFirst.isVar -> { @@ -132,13 +131,13 @@ internal open class FamilyArityReteNode( variableIndex.retractAllIndexed(clause), numericIndex.retractAllIndexed(clause), atomicIndex.retractAllIndexed(clause), - compoundIndex.retractAllIndexed(clause) + compoundIndex.retractAllIndexed(clause), ) } else -> { Utils.merge( variableIndex.retractAllIndexed(clause), - compoundIndex.retractAllIndexed(clause) + compoundIndex.retractAllIndexed(clause), ) } } @@ -147,24 +146,28 @@ internal open class FamilyArityReteNode( protected fun retractAllUnorderedIndexed(clause: Clause): Sequence { val innerFirst = clause.nestedFirstArgument() return when { - innerFirst.isNumber -> Utils.flattenIndexed( - variableIndex.retractAllIndexed(clause), - numericIndex.retractAllIndexed(clause) - ) - innerFirst.isAtom -> Utils.flattenIndexed( - variableIndex.retractAllIndexed(clause), - atomicIndex.retractAllIndexed(clause) - ) - innerFirst.isVar -> Utils.flattenIndexed( - variableIndex.retractAllIndexed(clause), - numericIndex.retractAllIndexed(clause), - atomicIndex.retractAllIndexed(clause), - compoundIndex.retractAllIndexed(clause) - ) - else -> Utils.flattenIndexed( - variableIndex.retractAllIndexed(clause), - compoundIndex.retractAllIndexed(clause) - ) + innerFirst.isNumber -> + Utils.flattenIndexed( + variableIndex.retractAllIndexed(clause), + numericIndex.retractAllIndexed(clause), + ) + innerFirst.isAtom -> + Utils.flattenIndexed( + variableIndex.retractAllIndexed(clause), + atomicIndex.retractAllIndexed(clause), + ) + innerFirst.isVar -> + Utils.flattenIndexed( + variableIndex.retractAllIndexed(clause), + numericIndex.retractAllIndexed(clause), + atomicIndex.retractAllIndexed(clause), + compoundIndex.retractAllIndexed(clause), + ) + else -> + Utils.flattenIndexed( + variableIndex.retractAllIndexed(clause), + compoundIndex.retractAllIndexed(clause), + ) } } @@ -174,24 +177,24 @@ internal open class FamilyArityReteNode( innerFirst.isNumber -> Utils.merge( variableIndex.getIndexed(clause), - numericIndex.getIndexed(clause) + numericIndex.getIndexed(clause), ) innerFirst.isAtom -> Utils.merge( variableIndex.getIndexed(clause), - atomicIndex.getIndexed(clause) + atomicIndex.getIndexed(clause), ) innerFirst.isVar -> Utils.merge( variableIndex.getIndexed(clause), numericIndex.getIndexed(clause), atomicIndex.getIndexed(clause), - compoundIndex.getIndexed(clause) + compoundIndex.getIndexed(clause), ) else -> Utils.merge( variableIndex.getIndexed(clause), - compoundIndex.getIndexed(clause) + compoundIndex.getIndexed(clause), ) } } @@ -199,24 +202,28 @@ internal open class FamilyArityReteNode( protected fun getUnorderedIndexed(clause: Clause): Sequence { val innerFirst = clause.nestedFirstArgument() return when { - innerFirst.isNumber -> Utils.flattenIndexed( - variableIndex.getIndexed(clause), - numericIndex.getIndexed(clause) - ) - innerFirst.isAtom -> Utils.flattenIndexed( - variableIndex.getIndexed(clause), - atomicIndex.getIndexed(clause) - ) - innerFirst.isVar -> Utils.flattenIndexed( - variableIndex.getIndexed(clause), - numericIndex.getIndexed(clause), - atomicIndex.getIndexed(clause), - compoundIndex.getIndexed(clause) - ) - else -> Utils.flattenIndexed( - variableIndex.getIndexed(clause), - compoundIndex.getIndexed(clause) - ) + innerFirst.isNumber -> + Utils.flattenIndexed( + variableIndex.getIndexed(clause), + numericIndex.getIndexed(clause), + ) + innerFirst.isAtom -> + Utils.flattenIndexed( + variableIndex.getIndexed(clause), + atomicIndex.getIndexed(clause), + ) + innerFirst.isVar -> + Utils.flattenIndexed( + variableIndex.getIndexed(clause), + numericIndex.getIndexed(clause), + atomicIndex.getIndexed(clause), + compoundIndex.getIndexed(clause), + ) + else -> + Utils.flattenIndexed( + variableIndex.getIndexed(clause), + compoundIndex.getIndexed(clause), + ) } } @@ -250,29 +257,31 @@ internal open class FamilyArityReteNode( innerFirst.isNumber -> { Utils.comparePriority( numericIndex.getFirstIndexed(clause), - variableIndex.getFirstIndexed(clause) + variableIndex.getFirstIndexed(clause), ) } innerFirst.isAtom -> { Utils.comparePriority( atomicIndex.getFirstIndexed(clause), - variableIndex.getFirstIndexed(clause) + variableIndex.getFirstIndexed(clause), ) } - innerFirst.isVar -> Utils.comparePriority( + innerFirst.isVar -> Utils.comparePriority( - numericIndex.getFirstIndexed(clause), - atomicIndex.getFirstIndexed(clause) - ), + Utils.comparePriority( + numericIndex.getFirstIndexed(clause), + atomicIndex.getFirstIndexed(clause), + ), + Utils.comparePriority( + variableIndex.getFirstIndexed(clause), + compoundIndex.getFirstIndexed(clause), + ), + ) + else -> Utils.comparePriority( variableIndex.getFirstIndexed(clause), - compoundIndex.getFirstIndexed(clause) + compoundIndex.getFirstIndexed(clause), ) - ) - else -> Utils.comparePriority( - variableIndex.getFirstIndexed(clause), - compoundIndex.getFirstIndexed(clause) - ) } } @@ -291,20 +300,19 @@ internal open class FamilyArityReteNode( atomicIndex.getCache(), numericIndex.getCache(), variableIndex.getCache(), - compoundIndex.getCache() + compoundIndex.getCache(), ) } else { Utils.flattenIndexed( atomicIndex.getCache(), numericIndex.getCache(), variableIndex.getCache(), - compoundIndex.getCache() + compoundIndex.getCache(), ) - } + }, ) - private fun Clause.nestedFirstArgument(): Term = - this.head!!.nestedFirstArgument(nestingLevel + 1) + private fun Clause.nestedFirstArgument(): Term = this.head!!.nestedFirstArgument(nestingLevel + 1) private fun assertByFirstParameter(clause: IndexedClause): IndexingLeaf { val innerFirst = clause.innerClause.nestedFirstArgument() @@ -316,6 +324,5 @@ internal open class FamilyArityReteNode( } } - private fun Clause.isGlobal(): Boolean = - this.head!!.nestedFirstArgument(nestingLevel + 1).isVar + private fun Clause.isGlobal(): Boolean = this.head!!.nestedFirstArgument(nestingLevel + 1).isVar } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/FunctorIndexingNode.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/FunctorIndexingNode.kt index f47e04166..64293cd3e 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/FunctorIndexingNode.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/FunctorIndexingNode.kt @@ -13,9 +13,8 @@ import it.unibo.tuprolog.utils.dequeOf internal class FunctorIndexingNode( unificator: Unificator, private val ordered: Boolean, - private val nestingLevel: Int + private val nestingLevel: Int, ) : FunctorNode(unificator), FunctorIndexing { - private val arities: MutableMap = mutableMapOf() private val theoryCache: Cached> = Cached.of(this::regenerateCache) @@ -26,8 +25,7 @@ internal class FunctorIndexingNode( override val isEmpty: Boolean get() = arities.isEmpty() || arities.values.all { it.isEmpty } - override fun get(clause: Clause): Sequence = - arities[clause.nestedArity()]?.get(clause) ?: emptySequence() + override fun get(clause: Clause): Sequence = arities[clause.nestedArity()]?.get(clause) ?: emptySequence() override fun assertA(clause: IndexedClause) { arities.getOrPut(clause.nestedArity()) { @@ -45,15 +43,14 @@ internal class FunctorIndexingNode( arities[clause.nestedArity()]?.retractAll(clause) ?: emptySequence() - override fun getCache(): Sequence = - theoryCache.value.asSequence() + override fun getCache(): Sequence = theoryCache.value.asSequence() override fun getFirstIndexed(clause: Clause): SituatedIndexedClause? = if (clause.isGlobal()) { Utils.merge( arities.values.map { it.extractGlobalIndexedSequence(clause) - } + }, ).firstOrNull { unificator.match(it.innerClause, clause) } } else { arities[clause.nestedArity()]?.getFirstIndexed(clause) @@ -64,7 +61,7 @@ internal class FunctorIndexingNode( Utils.merge( arities.values.map { it.extractGlobalIndexedSequence(clause) - } + }, ) } else { arities[clause.nestedArity()]?.getIndexed(clause) ?: emptySequence() @@ -73,13 +70,14 @@ internal class FunctorIndexingNode( override fun retractAllIndexed(clause: Clause): Sequence = if (clause.isGlobal()) { - val partialResult = Utils.merge( - arities.values.map { - it.extractGlobalIndexedSequence(clause) - } - ) - .filter { unificator.match(it.innerClause, clause) } - .toList() + val partialResult = + Utils.merge( + arities.values.map { + it.extractGlobalIndexedSequence(clause) + }, + ) + .filter { unificator.match(it.innerClause, clause) } + .toList() if (partialResult.isNotEmpty()) { invalidateCache() partialResult.forEach { it.removeFromIndex() } @@ -95,13 +93,13 @@ internal class FunctorIndexingNode( Utils.merge( arities.values.map { it.extractGlobalIndexedSequence(clause) - } + }, ) } else { Utils.flattenIndexed( arities.values.map { it.extractGlobalIndexedSequence(clause) - } + }, ) } } @@ -113,8 +111,7 @@ internal class FunctorIndexingNode( asRule()?.head?.arityOfNestedFirstArgument(nestingLevel) ?: error("The nestedArity method cannot be invoked on non-rule clauses") - private fun IndexedClause.nestedArity(): Int = - this.innerClause.head!!.arityOfNestedFirstArgument(nestingLevel) + private fun IndexedClause.nestedArity(): Int = this.innerClause.head!!.arityOfNestedFirstArgument(nestingLevel) override fun invalidateCache() { theoryCache.invalidate() @@ -127,14 +124,14 @@ internal class FunctorIndexingNode( Utils.merge( arities.values.map { it.getCache() - } + }, ) } else { Utils.flattenIndexed( arities.values.map { outer -> outer.getCache() - } + }, ) - } + }, ) } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/RootNode.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/RootNode.kt index c7b15862f..87e481015 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/RootNode.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/RootNode.kt @@ -17,9 +17,8 @@ import it.unibo.tuprolog.utils.dequeOf internal class RootNode( override val unificator: Unificator, clauses: Iterable, - override val isOrdered: Boolean + override val isOrdered: Boolean, ) : ReteTree, Cacheable { - private val theoryCache: Cached> = Cached.of(this::regenerateCache) private val ruleIndex: RuleNode = RuleNode(unificator, isOrdered) @@ -63,8 +62,10 @@ internal class RootNode( ruleIndex.retractFirst(clause) } - override fun retractOnly(clause: Clause, limit: Int): Sequence = - (1..limit).asSequence().flatMap { retractFirst(clause) }.buffered() + override fun retractOnly( + clause: Clause, + limit: Int, + ): Sequence = (1..limit).asSequence().flatMap { retractFirst(clause) }.buffered() override fun retractAll(clause: Clause): Sequence = if (clause.isDirective) { @@ -73,8 +74,7 @@ internal class RootNode( ruleIndex.retractAll(clause) } - override fun deepCopy(): ReteTree = - RootNode(unificator, clauses.asIterable(), isOrdered) + override fun deepCopy(): ReteTree = RootNode(unificator, clauses.asIterable(), isOrdered) override fun assertA(clause: Clause) { val indexed = assignLowerIndex(clause) @@ -107,25 +107,23 @@ internal class RootNode( } } - private fun assignHigherIndex(clause: Clause): IndexedClause = - IndexedClause.of(++highestIndex, clause, this) + private fun assignHigherIndex(clause: Clause): IndexedClause = IndexedClause.of(++highestIndex, clause, this) - private fun assignLowerIndex(clause: Clause): IndexedClause = - IndexedClause.of(--lowestIndex, clause, this) + private fun assignLowerIndex(clause: Clause): IndexedClause = IndexedClause.of(--lowestIndex, clause, this) private fun regenerateCache(): MutableList { return dequeOf( if (isOrdered) { Utils.merge( directiveIndex.getCache(), - ruleIndex.getCache() + ruleIndex.getCache(), ).map { it.innerClause } } else { Utils.flatten( directiveIndex.getCache().map { it.innerClause }, - ruleIndex.getCache().map { it.innerClause } + ruleIndex.getCache().map { it.innerClause }, ) - } + }, ) } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/RuleNode.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/RuleNode.kt index 5afae1689..807e7a8a6 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/RuleNode.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/RuleNode.kt @@ -12,9 +12,8 @@ import it.unibo.tuprolog.utils.dequeOf internal class RuleNode( override val unificator: Unificator, - private val ordered: Boolean + private val ordered: Boolean, ) : TopLevelReteNode { - private val functors: MutableMap = mutableMapOf() private val theoryCache: Cached> = Cached.of(this::regenerateCache) @@ -55,14 +54,11 @@ internal class RuleNode( functors[clause.nestedFunctor()]?.retractAll(clause) ?: emptySequence() - override fun getCache(): Sequence = - theoryCache.value.asSequence() + override fun getCache(): Sequence = theoryCache.value.asSequence() - private fun Clause.nestedFunctor(): String = - this.head!!.functorOfNestedFirstArgument(0) + private fun Clause.nestedFunctor(): String = this.head!!.functorOfNestedFirstArgument(0) - private fun IndexedClause.nestedFunctor(): String = - this.innerClause.nestedFunctor() + private fun IndexedClause.nestedFunctor(): String = this.innerClause.nestedFunctor() override fun invalidateCache() { theoryCache.invalidate() @@ -75,14 +71,14 @@ internal class RuleNode( Utils.merge( functors.values.map { it.getCache() - } + }, ) } else { Utils.flattenIndexed( functors.values.map { it.getCache() - } + }, ) - } + }, ) } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/TopLevelFunctorReteNode.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/TopLevelFunctorReteNode.kt index a923951c2..378b7a16c 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/TopLevelFunctorReteNode.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/TopLevelFunctorReteNode.kt @@ -14,9 +14,8 @@ import it.unibo.tuprolog.utils.dequeOf internal class TopLevelFunctorReteNode( unificator: Unificator, private val ordered: Boolean, - private val nestingLevel: Int + private val nestingLevel: Int, ) : FunctorNode(unificator), FunctorRete { - private val arities: MutableMap = mutableMapOf() private val theoryCache: Cached> = Cached.of(this::regenerateCache) @@ -27,8 +26,7 @@ internal class TopLevelFunctorReteNode( override val isEmpty: Boolean get() = arities.isEmpty() || arities.values.all { it.isEmpty } - override fun get(clause: Clause): Sequence = - selectArity(clause)?.get(clause) ?: emptySequence() + override fun get(clause: Clause): Sequence = selectArity(clause)?.get(clause) ?: emptySequence() override fun assertA(clause: IndexedClause) { chooseAssertionBranch(clause + this, ReteNode::assertA) @@ -46,21 +44,24 @@ internal class TopLevelFunctorReteNode( selectArity(clause)?.retractAll(clause) ?: emptySequence() - override fun getCache(): Sequence = - theoryCache.value.asSequence() + override fun getCache(): Sequence = theoryCache.value.asSequence() - private fun selectArity(clause: Clause) = - arities[clause.head!!.arityOfNestedFirstArgument(nestingLevel)] + private fun selectArity(clause: Clause) = arities[clause.head!!.arityOfNestedFirstArgument(nestingLevel)] - private fun chooseAssertionBranch(clause: IndexedClause, op: ReteNode.(IndexedClause) -> Unit) { + private fun chooseAssertionBranch( + clause: IndexedClause, + op: ReteNode.(IndexedClause) -> Unit, + ) { clause.innerClause.head!!.arityOfNestedFirstArgument(nestingLevel).let { when (it) { - 0 -> arities.getOrPut(it) { - ZeroArityReteNode(unificator, ordered) - } - else -> arities.getOrPut(it) { - FamilyArityReteNode(unificator, ordered, nestingLevel) - } + 0 -> + arities.getOrPut(it) { + ZeroArityReteNode(unificator, ordered) + } + else -> + arities.getOrPut(it) { + FamilyArityReteNode(unificator, ordered, nestingLevel) + } } }.op(clause) } @@ -76,14 +77,14 @@ internal class TopLevelFunctorReteNode( Utils.merge( arities.values.map { it.getCache() - } + }, ) } else { Utils.flattenIndexed( arities.values.map { outer -> outer.getCache() - } + }, ) - } + }, ) } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/ZeroArityReteNode.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/ZeroArityReteNode.kt index 70c7cf940..435a0057b 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/ZeroArityReteNode.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/custom/nodes/ZeroArityReteNode.kt @@ -11,14 +11,15 @@ import it.unibo.tuprolog.utils.dequeOf internal class ZeroArityReteNode( unificator: Unificator, - private val ordered: Boolean + private val ordered: Boolean, ) : ArityNode(unificator), ArityRete, Retractable { - private val atoms: MutableList = dequeOf() override fun retractFirst(clause: Clause): Sequence = - removeAllLazily(atoms, clause).map { it.innerClause }.take(1).buffered() + removeAllLazily(atoms, clause).map { + it.innerClause + }.take(1).buffered() override val size: Int get() = atoms.size @@ -34,8 +35,8 @@ internal class ZeroArityReteNode( atoms.addFirst( SituatedIndexedClause.of( clause + this, - this - ) + this, + ), ) } else { assertZ(clause) @@ -46,20 +47,22 @@ internal class ZeroArityReteNode( atoms.add( SituatedIndexedClause.of( clause + this, - this - ) + this, + ), ) } override fun retractAll(clause: Clause): Sequence = - removeAllLazily(atoms, clause).map { it.innerClause }.buffered() + removeAllLazily(atoms, clause).map { + it.innerClause + }.buffered() override fun getCache(): Sequence { return atoms.asSequence() } override fun invalidateCache() { - /* do nothing */ + // do nothing } override fun retractIndexed(indexed: SituatedIndexedClause) { diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/AbstractIntermediateReteNode.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/AbstractIntermediateReteNode.kt index 3e875934d..4a12bb353 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/AbstractIntermediateReteNode.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/AbstractIntermediateReteNode.kt @@ -4,17 +4,15 @@ import it.unibo.tuprolog.core.Clause /** A non-leaf Rete Node */ internal abstract class AbstractIntermediateReteNode( - override val children: MutableMap> = mutableMapOf() + override val children: MutableMap> = mutableMapOf(), ) : AbstractReteNode(children) { - override val indexedElements: Sequence get() = children.asSequence().flatMap { it.value.indexedElements } /** Selects correct children, according to [element], onto which to propagate received method calls */ protected abstract fun selectChildren(element: E): Sequence?> - override fun get(element: E): Sequence = - selectChildren(element).flatMap { it?.get(element) ?: emptySequence() } + override fun get(element: E): Sequence = selectChildren(element).flatMap { it?.get(element) ?: emptySequence() } override fun removeAll(element: E): Sequence = selectChildren(element).toList().flatMap { @@ -25,12 +23,13 @@ internal abstract class AbstractIntermediateReteNode( protected fun MutableMap>.retrieve( keyFilter: (K) -> Boolean, typeChecker: (ReteNode<*, E>) -> Boolean, - caster: (ReteNode<*, E>) -> ChildNodeType - ): Sequence = filterValues(typeChecker) - .filterKeys(keyFilter) - .values - .asSequence() - .map(caster) + caster: (ReteNode<*, E>) -> ChildNodeType, + ): Sequence = + filterValues(typeChecker) + .filterKeys(keyFilter) + .values + .asSequence() + .map(caster) /** * A [Sequence.fold] function that stops when accumulated operation results' count becomes greater or equal to [limit]; @@ -40,17 +39,16 @@ internal abstract class AbstractIntermediateReteNode( protected inline fun > Sequence.foldWithLimit( initial: R, limit: Int, - operation: (acc: R, T) -> R - ) = - if (limit < 0) { - fold(initial, operation) - } else { - fold(initial) { accumulator, element -> - if (accumulator.count() < limit) { - operation(accumulator, element) - } else { - return@foldWithLimit accumulator - } + operation: (acc: R, T) -> R, + ) = if (limit < 0) { + fold(initial, operation) + } else { + fold(initial) { accumulator, element -> + if (accumulator.count() < limit) { + operation(accumulator, element) + } else { + return@foldWithLimit accumulator } } + } } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/AbstractLeafReteNode.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/AbstractLeafReteNode.kt index af6aac6ea..a6e4a4671 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/AbstractLeafReteNode.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/AbstractLeafReteNode.kt @@ -5,16 +5,18 @@ import kotlin.math.min /** A leaf Rete Node */ internal abstract class AbstractLeafReteNode( - override val children: MutableMap> = mutableMapOf() + override val children: MutableMap> = mutableMapOf(), ) : AbstractReteNode(children) { - /** Internal data structure to store leaf elements */ protected abstract val leafElements: MutableList override val indexedElements: Sequence get() = leafElements.asSequence() - override fun put(element: E, beforeOthers: Boolean) { + override fun put( + element: E, + beforeOthers: Boolean, + ) { if (beforeOthers) { leafElements.add(0, element) } else { @@ -22,7 +24,10 @@ internal abstract class AbstractLeafReteNode( } } - override fun removeWithLimit(element: E, limit: Int): Sequence = + override fun removeWithLimit( + element: E, + limit: Int, + ): Sequence = get(element) .take(if (limit > 0) min(limit, leafElements.count()) else leafElements.count()) .toList() diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/AbstractReteNode.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/AbstractReteNode.kt index bccb10716..55db93741 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/AbstractReteNode.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/AbstractReteNode.kt @@ -12,9 +12,8 @@ import kotlin.jvm.JvmStatic /** Abstract base class for Rete Tree nodes */ internal abstract class AbstractReteNode( - override val children: MutableMap> = mutableMapOf() + override val children: MutableMap> = mutableMapOf(), ) : ReteNode { - override val isFunctorNode: Boolean get() = false @@ -74,13 +73,20 @@ internal abstract class AbstractReteNode( /** Description for current Rete Tree Node */ protected abstract val header: String - override fun remove(element: E, limit: Int): Sequence = when (limit) { - 0 -> emptySequence() - else -> removeWithLimit(element, limit) - } + override fun remove( + element: E, + limit: Int, + ): Sequence = + when (limit) { + 0 -> emptySequence() + else -> removeWithLimit(element, limit) + } /** Called when a non-zero-limit removal is required inside a node */ - protected abstract fun removeWithLimit(element: E, limit: Int): Sequence + protected abstract fun removeWithLimit( + element: E, + limit: Int, + ): Sequence override fun removeAll(element: E): Sequence = remove(element, Int.MAX_VALUE) @@ -101,13 +107,11 @@ internal abstract class AbstractReteNode( } companion object { - /** Utility function to deeply copy a MutableMap */ @JvmStatic protected inline fun MutableMap.deepCopy( deepCopyKey: (K) -> K, - deepCopyValue: (V) -> V - ): MutableMap = - entries.map { deepCopyKey(it.key) to deepCopyValue(it.value) }.toMap(mutableMapOf()) + deepCopyValue: (V) -> V, + ): MutableMap = entries.map { deepCopyKey(it.key) to deepCopyValue(it.value) }.toMap(mutableMapOf()) } } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/ReteNode.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/ReteNode.kt index 032305bed..a4faa8124 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/ReteNode.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/ReteNode.kt @@ -12,7 +12,6 @@ import it.unibo.tuprolog.collections.rete.generic.set.RootNode as SetNode /** A class modeling a Rete Tree Node */ internal interface ReteNode { - val isFunctorNode: Boolean val isArgNode: Boolean @@ -62,11 +61,13 @@ internal interface ReteNode { val indexedElements: Sequence /** Indexes a new element under this node */ - fun put(element: E, beforeOthers: Boolean) + fun put( + element: E, + beforeOthers: Boolean, + ) /** Indexes a new element under this node, after the others */ - fun put(element: E) = - put(element, false) + fun put(element: E) = put(element, false) /** Indexes all the element given as input, after the others**/ fun put(clauses: Iterable) = @@ -81,13 +82,15 @@ internal interface ReteNode { * Removes elements matching given [element], respecting provided [limit], and returns them. * A negative limit will be considered as if there's no limit, i.e. all matching elements will be removed */ - fun remove(element: @UnsafeVariance E, limit: Int): Sequence + fun remove( + element: @UnsafeVariance E, + limit: Int, + ): Sequence /** * Removes one element matching given [element], and returns it; */ - fun remove(element: @UnsafeVariance E): Sequence = - remove(element, 1) + fun remove(element: @UnsafeVariance E): Sequence = remove(element, 1) /** Removes all elements matching given one */ fun removeAll(element: @UnsafeVariance E): Sequence @@ -103,12 +106,10 @@ internal interface ReteNode { companion object { /** Creates a ReteTree from give clauses */ @JvmStatic - fun ofSet(clauses: Iterable): ReteNode<*, Clause> = - SetNode().apply { clauses.forEach { put(it) } } + fun ofSet(clauses: Iterable): ReteNode<*, Clause> = SetNode().apply { clauses.forEach { put(it) } } /** Creates a ReteTree from give clauses */ @JvmStatic - fun ofSet(vararg clauses: Clause): ReteNode<*, Clause> = - ofSet(listOf(*clauses)) + fun ofSet(vararg clauses: Clause): ReteNode<*, Clause> = ofSet(listOf(*clauses)) } } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/ArgNode.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/ArgNode.kt index 0f8501311..f200d14d2 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/ArgNode.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/ArgNode.kt @@ -10,9 +10,8 @@ import it.unibo.tuprolog.unify.Unificator.Companion.matches internal data class ArgNode( private val index: Int, private val term: Term, - override val children: MutableMap> = mutableMapOf() + override val children: MutableMap> = mutableMapOf(), ) : AbstractIntermediateReteNode(children) { - init { require(index >= 0) { "ArgNode index should be greater than or equal to 0" } } @@ -24,17 +23,21 @@ internal data class ArgNode( override val header = "Argument($index, $term)" - override fun put(element: Rule, beforeOthers: Boolean) = when { + override fun put( + element: Rule, + beforeOthers: Boolean, + ) = when { index < element.head.arity - 1 -> { // if more arguments after "index" arg val nextArg = element.head[index + 1] - val child = children.getOrElse(nextArg) { - children.retrieve( - keyFilter = { head -> head != null && head structurallyEquals nextArg }, - typeChecker = { it.isArgNode }, - caster = { it.castToArgNode() } - ).singleOrNull() - } + val child = + children.getOrElse(nextArg) { + children.retrieve( + keyFilter = { head -> head != null && head structurallyEquals nextArg }, + typeChecker = { it.isArgNode }, + caster = { it.castToArgNode() }, + ).singleOrNull() + } child ?: ArgNode(index + 1, nextArg) .also { children[nextArg] = it } @@ -43,19 +46,23 @@ internal data class ArgNode( else -> children.getOrPut(null) { RuleNode() } }.put(element, beforeOthers) - override fun selectChildren(element: Rule): Sequence?> = when { - index < element.head.arity - 1 -> { - val nextArg = element.head[index + 1] - children.retrieve( - keyFilter = { head -> head != null && head matches nextArg }, - typeChecker = { it.isArgNode }, - caster = { it.castToArgNode() } - ) + override fun selectChildren(element: Rule): Sequence?> = + when { + index < element.head.arity - 1 -> { + val nextArg = element.head[index + 1] + children.retrieve( + keyFilter = { head -> head != null && head matches nextArg }, + typeChecker = { it.isArgNode }, + caster = { it.castToArgNode() }, + ) + } + else -> sequenceOf(children[null]) } - else -> sequenceOf(children[null]) - } - override fun removeWithLimit(element: Rule, limit: Int): Sequence = + override fun removeWithLimit( + element: Rule, + limit: Int, + ): Sequence = selectChildren(element) .foldWithLimit(mutableListOf(), limit) { yetRemoved, currentChild -> yetRemoved.also { @@ -77,6 +84,6 @@ internal data class ArgNode( ArgNode( index, term, - children.deepCopy({ it }, { it.deepCopy() }) + children.deepCopy({ it }, { it.deepCopy() }), ) } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/ArityNode.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/ArityNode.kt index 61dd18589..11a815094 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/ArityNode.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/ArityNode.kt @@ -9,25 +9,28 @@ import it.unibo.tuprolog.unify.Unificator.Companion.matches /** An intermediate node indexing by Rules head's arity */ internal data class ArityNode( private val arity: Int, - override val children: MutableMap> = mutableMapOf() + override val children: MutableMap> = mutableMapOf(), ) : AbstractIntermediateReteNode(children) { - init { require(arity >= 0) { "ArityNode arity should be greater than or equal to 0" } } override val header = "Arity($arity)" - override fun put(element: Rule, beforeOthers: Boolean) = when { + override fun put( + element: Rule, + beforeOthers: Boolean, + ) = when { element.head.arity > 0 -> { val headFirstArg = element.head[0] - val child = children.getOrElse(headFirstArg) { - children.retrieve( - keyFilter = { head -> head != null && head structurallyEquals headFirstArg }, - typeChecker = { it.isArgNode }, - caster = { it.castToArgNode() } - ).singleOrNull() - } + val child = + children.getOrElse(headFirstArg) { + children.retrieve( + keyFilter = { head -> head != null && head structurallyEquals headFirstArg }, + typeChecker = { it.isArgNode }, + caster = { it.castToArgNode() }, + ).singleOrNull() + } child ?: ArgNode(0, headFirstArg) .also { children[headFirstArg] = it } @@ -36,18 +39,22 @@ internal data class ArityNode( else -> children.getOrPut(null) { NoArgsNode() } }.put(element, beforeOthers) - override fun selectChildren(element: Rule) = when { - element.head.arity > 0 -> { - children.retrieve( - keyFilter = { head -> head != null && head matches element.head[0] }, - typeChecker = { it.isArgNode }, - caster = { it.castToArgNode() } - ) + override fun selectChildren(element: Rule) = + when { + element.head.arity > 0 -> { + children.retrieve( + keyFilter = { head -> head != null && head matches element.head[0] }, + typeChecker = { it.isArgNode }, + caster = { it.castToArgNode() }, + ) + } + else -> sequenceOf(children[null]) } - else -> sequenceOf(children[null]) - } - override fun removeWithLimit(element: Rule, limit: Int): Sequence = + override fun removeWithLimit( + element: Rule, + limit: Int, + ): Sequence = selectChildren(element) .foldWithLimit(mutableListOf(), limit) { yetRemoved, currentChild -> yetRemoved.also { @@ -68,6 +75,6 @@ internal data class ArityNode( override fun deepCopy(): ArityNode = ArityNode( arity, - children.deepCopy({ it }, { it.deepCopy() }) + children.deepCopy({ it }, { it.deepCopy() }), ) } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/DirectiveNode.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/DirectiveNode.kt index 7a100cc7c..26996549c 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/DirectiveNode.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/DirectiveNode.kt @@ -7,7 +7,6 @@ import it.unibo.tuprolog.unify.Unificator.Companion.matches /** A leaf node containing [Directive]s */ internal data class DirectiveNode(override val leafElements: MutableList = mutableListOf()) : AbstractLeafReteNode() { - override val isDirectiveNode: Boolean get() = true @@ -17,6 +16,5 @@ internal data class DirectiveNode(override val leafElements: MutableList = indexedElements.filter { it matches element } - override fun deepCopy(): DirectiveNode = - DirectiveNode(leafElements.toMutableList()) + override fun deepCopy(): DirectiveNode = DirectiveNode(leafElements.toMutableList()) } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/FunctorNode.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/FunctorNode.kt index abd1f5f87..8aee70f41 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/FunctorNode.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/FunctorNode.kt @@ -7,9 +7,8 @@ import it.unibo.tuprolog.core.Rule /** An intermediate node indexing by Rules head's functor */ internal data class FunctorNode( private val functor: String, - override val children: MutableMap> = mutableMapOf() + override val children: MutableMap> = mutableMapOf(), ) : AbstractIntermediateReteNode(children) { - override val isFunctorNode: Boolean get() = true @@ -17,7 +16,10 @@ internal data class FunctorNode( override val header = "Functor($functor)" - override fun put(element: Rule, beforeOthers: Boolean) { + override fun put( + element: Rule, + beforeOthers: Boolean, + ) { if (functor == element.head.functor) { val a = element.head.arity children.getOrPut(a) { ArityNode(a) }.put(element, beforeOthers) @@ -26,12 +28,14 @@ internal data class FunctorNode( override fun selectChildren(element: Rule) = sequenceOf(children[element.head.arity]) - override fun removeWithLimit(element: Rule, limit: Int): Sequence = - selectChildren(element).single()?.remove(element, limit) ?: emptySequence() + override fun removeWithLimit( + element: Rule, + limit: Int, + ): Sequence = selectChildren(element).single()?.remove(element, limit) ?: emptySequence() override fun deepCopy(): FunctorNode = FunctorNode( functor, - children.deepCopy({ it }, { it.deepCopy() }) + children.deepCopy({ it }, { it.deepCopy() }), ) } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/NoArgsNode.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/NoArgsNode.kt index 15e3b4535..0da4a2d1e 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/NoArgsNode.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/NoArgsNode.kt @@ -7,7 +7,6 @@ import it.unibo.tuprolog.core.Rule /** An intermediate node indexing Rules with no-args' heads */ internal data class NoArgsNode(override val children: MutableMap> = mutableMapOf()) : AbstractIntermediateReteNode(children) { - override val isNoArgsNode: Boolean get() = true @@ -15,21 +14,24 @@ internal data class NoArgsNode(override val children: MutableMap?> = - sequenceOf(children[null]) + override fun selectChildren(element: Rule): Sequence?> = sequenceOf(children[null]) - override fun removeWithLimit(element: Rule, limit: Int): Sequence = - selectChildren(element).single()?.remove(element, limit) ?: emptySequence() + override fun removeWithLimit( + element: Rule, + limit: Int, + ): Sequence = selectChildren(element).single()?.remove(element, limit) ?: emptySequence() override fun deepCopy(): NoArgsNode = NoArgsNode( children.deepCopy( { it }, - { it.deepCopy() } - ) + { it.deepCopy() }, + ), ) } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/RootNode.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/RootNode.kt index 06cae3b55..b790cf818 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/RootNode.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/RootNode.kt @@ -8,7 +8,6 @@ import it.unibo.tuprolog.utils.forceCast /** The root node, of the Rete Tree indexing [Clause]s */ internal data class RootNode(override val children: MutableMap> = mutableMapOf()) : AbstractIntermediateReteNode(children) { - override val isRootNode: Boolean get() = true @@ -16,7 +15,10 @@ internal data class RootNode(override val children: MutableMap { children.getOrPut(null) { DirectiveNode().forceCast>() } @@ -36,12 +38,13 @@ internal data class RootNode(override val children: MutableMap children[null] element.isRule -> children[element.castToRule().head.functor] else -> null - } + }, ) - override fun removeWithLimit(element: Clause, limit: Int): Sequence = - selectChildren(element).single()?.remove(element, limit) ?: emptySequence() + override fun removeWithLimit( + element: Clause, + limit: Int, + ): Sequence = selectChildren(element).single()?.remove(element, limit) ?: emptySequence() - override fun deepCopy(): RootNode = - RootNode(children.deepCopy({ it }, { it.deepCopy() })) + override fun deepCopy(): RootNode = RootNode(children.deepCopy({ it }, { it.deepCopy() })) } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/RuleNode.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/RuleNode.kt index b12e25fd3..931b70c87 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/RuleNode.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/collections/rete/generic/set/RuleNode.kt @@ -6,9 +6,8 @@ import it.unibo.tuprolog.unify.Unificator.Companion.matches /** A leaf node containing [Rule]s */ internal data class RuleNode( - override val leafElements: MutableList = mutableListOf() + override val leafElements: MutableList = mutableListOf(), ) : AbstractLeafReteNode() { - override val isRuleNode: Boolean get() = true @@ -18,6 +17,5 @@ internal data class RuleNode( override fun get(element: Rule): Sequence = indexedElements.filter { it matches element } - override fun deepCopy(): RuleNode = - RuleNode(leafElements.toMutableList()) + override fun deepCopy(): RuleNode = RuleNode(leafElements.toMutableList()) } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/AbstractTheory.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/AbstractTheory.kt index 4e431bc1c..1abb9b601 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/AbstractTheory.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/AbstractTheory.kt @@ -10,7 +10,6 @@ import it.unibo.tuprolog.theory.TheoryUtils.checkClausesCorrect import it.unibo.tuprolog.unify.Unificator internal abstract class AbstractTheory(override val tags: Map) : Theory { - abstract override var unificator: Unificator protected set @@ -18,14 +17,11 @@ internal abstract class AbstractTheory(override val tags: Map) : Th override fun plus(clause: Clause): Theory = super.plus(checkClauseCorrect(clause)) - override fun contains(clause: Clause): Boolean = - get(clause).any() + override fun contains(clause: Clause): Boolean = get(clause).any() - override fun contains(head: Struct): Boolean = - contains(Rule.of(head, Var.anonymous())) + override fun contains(head: Struct): Boolean = contains(Rule.of(head, Var.anonymous())) - override fun contains(indicator: Indicator): Boolean = - get(indicator).any() + override fun contains(indicator: Indicator): Boolean = get(indicator).any() override fun get(head: Struct): Sequence = get(Rule.of(head, Var.anonymous())).map { it.castToRule() } @@ -35,8 +31,8 @@ internal abstract class AbstractTheory(override val tags: Map) : Th return get( Rule.of( Struct.of(indicator.indicatedName!!, (1..indicator.indicatedArity!!).map { Var.anonymous() }), - Var.anonymous() - ) + Var.anonymous(), + ), ).map { it.castToRule() } } @@ -64,7 +60,10 @@ internal abstract class AbstractTheory(override val tags: Map) : Th return equals(other, true) } - final override fun equals(other: Theory, useVarCompleteName: Boolean): Boolean { + final override fun equals( + other: Theory, + useVarCompleteName: Boolean, + ): Boolean { if (this === other) return true val i = clauses.iterator() @@ -92,7 +91,10 @@ internal abstract class AbstractTheory(override val tags: Map) : Th get() { var i: Long = 0 val iter = iterator() - while (iter.hasNext()) { iter.next(); i++ } + while (iter.hasNext()) { + iter.next() + i++ + } return i } @@ -116,32 +118,36 @@ internal abstract class AbstractTheory(override val tags: Map) : Th this } - override fun assertA(clause: Clause): Theory = - createNewTheory(checkClausesCorrect(clause) + clauses.asSequence()) + override fun assertA(clause: Clause): Theory = createNewTheory(checkClausesCorrect(clause) + clauses.asSequence()) override fun assertA(clauses: Iterable): Theory = createNewTheory(checkClausesCorrect(clauses.asSequence()) + this.clauses.asSequence()) override fun assertA(clauses: Sequence): Theory = - createNewTheory(checkClausesCorrect(clauses) + this.clauses.asSequence()) + createNewTheory( + checkClausesCorrect(clauses) + this.clauses.asSequence(), + ) override fun assertZ(clause: Clause): Theory = - createNewTheory(clauses.asSequence() + checkClausesCorrect(sequenceOf(clause))) + createNewTheory( + clauses.asSequence() + checkClausesCorrect(sequenceOf(clause)), + ) override fun assertZ(clauses: Iterable): Theory = createNewTheory(this.clauses.asSequence() + checkClausesCorrect(clauses).asSequence()) override fun assertZ(clauses: Sequence): Theory = - createNewTheory(this.clauses.asSequence() + checkClausesCorrect(clauses)) + createNewTheory( + this.clauses.asSequence() + checkClausesCorrect(clauses), + ) protected abstract fun createNewTheory( clauses: Sequence, tags: Map = this.tags, - unificator: Unificator = this.unificator + unificator: Unificator = this.unificator, ): AbstractTheory - override fun retract(clauses: Sequence): RetractResult = - retract(clauses.asIterable()) + override fun retract(clauses: Sequence): RetractResult = retract(clauses.asIterable()) abstract override fun retract(clauses: Iterable): RetractResult diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/MutableTheory.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/MutableTheory.kt index a19cae964..6e43499a2 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/MutableTheory.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/MutableTheory.kt @@ -14,7 +14,6 @@ import kotlin.js.JsName import kotlin.jvm.JvmStatic interface MutableTheory : Theory { - override fun setUnificator(unificator: Unificator): MutableTheory override val isMutable: Boolean get() = true @@ -47,13 +46,11 @@ interface MutableTheory : Theory { override fun retract(clauses: Sequence): RetractResult - override fun retract(head: Struct): RetractResult = - retract(Rule.of(head, Var.anonymous())) + override fun retract(head: Struct): RetractResult = retract(Rule.of(head, Var.anonymous())) override fun retractAll(clause: Clause): RetractResult - override fun retractAll(head: Struct): RetractResult = - retractAll(Rule.of(head, Var.anonymous())) + override fun retractAll(head: Struct): RetractResult = retractAll(Rule.of(head, Var.anonymous())) override fun abolish(indicator: Indicator): MutableTheory @@ -62,108 +59,130 @@ interface MutableTheory : Theory { override fun clone(): MutableTheory companion object { - /** Creates an empty [MutableTheory] */ @JvmStatic @JsName("empty") - fun empty(unificator: Unificator): MutableTheory = - indexedOf(unificator, emptyList()) + fun empty(unificator: Unificator): MutableTheory = indexedOf(unificator, emptyList()) /** Creates a [MutableTheory], containing the given clauses */ @JvmStatic @JsName("of") - fun of(unificator: Unificator, vararg clause: Clause): MutableTheory = - indexedOf(unificator, *clause) + fun of( + unificator: Unificator, + vararg clause: Clause, + ): MutableTheory = indexedOf(unificator, *clause) /** Creates a [MutableTheory], containing the given clauses */ @JvmStatic @JsName("ofIterable") - fun of(unificator: Unificator, clauses: Iterable): MutableTheory = - indexedOf(unificator, clauses) + fun of( + unificator: Unificator, + clauses: Iterable, + ): MutableTheory = indexedOf(unificator, clauses) /** Creates a [MutableTheory], containing the given clauses */ @JvmStatic @JsName("ofSequence") - fun of(unificator: Unificator, clauses: Sequence): MutableTheory = - indexedOf(unificator, clauses) + fun of( + unificator: Unificator, + clauses: Sequence, + ): MutableTheory = indexedOf(unificator, clauses) /** Let developers easily create a [MutableTheory], while avoiding variables names clashing by using a * different [Scope] for each [Clause] */ @JvmStatic @JsName("ofScopes") - fun of(unificator: Unificator, vararg clauses: Scope.() -> Clause): MutableTheory = - indexedOf(unificator, *clauses) + fun of( + unificator: Unificator, + vararg clauses: Scope.() -> Clause, + ): MutableTheory = indexedOf(unificator, *clauses) /** Creates an empty [MutableTheory] backed by an indexed data structure */ @JvmStatic @JsName("emptyIndexed") - fun emptyIndexed(unificator: Unificator): MutableTheory = - indexedOf(unificator, emptyList()) + fun emptyIndexed(unificator: Unificator): MutableTheory = indexedOf(unificator, emptyList()) /** Creates a [MutableTheory] backed by an indexed data structure, containing the given clauses */ @JvmStatic @JsName("indexedOf") - fun indexedOf(unificator: Unificator, vararg clause: Clause): MutableTheory = - indexedOf(unificator, clause.asIterable()) + fun indexedOf( + unificator: Unificator, + vararg clause: Clause, + ): MutableTheory = indexedOf(unificator, clause.asIterable()) /** Let developers easily create a [MutableTheory] backed by an indexed data structure, while avoiding variables names * clashing by using a different [Scope] for each [Clause] */ @JvmStatic @JsName("indexedOfScopes") - fun indexedOf(unificator: Unificator, vararg clauses: Scope.() -> Clause): MutableTheory = + fun indexedOf( + unificator: Unificator, + vararg clauses: Scope.() -> Clause, + ): MutableTheory = indexedOf( unificator, clauses.map { Scope.empty(it) - } + }, ) /** Creates a [MutableTheory] backed by an indexed data structure, containing the given clauses */ @JvmStatic @JsName("indexedOfSequence") - fun indexedOf(unificator: Unificator, clauses: Sequence): MutableTheory = - indexedOf(unificator, clauses.asIterable()) + fun indexedOf( + unificator: Unificator, + clauses: Sequence, + ): MutableTheory = indexedOf(unificator, clauses.asIterable()) /** Creates a [MutableTheory] backed by an indexed data structure, containing the given clauses */ @JvmStatic @JsName("indexedOfIterable") - fun indexedOf(unificator: Unificator, clauses: Iterable): MutableTheory = - MutableIndexedTheory(unificator, clauses) + fun indexedOf( + unificator: Unificator, + clauses: Iterable, + ): MutableTheory = MutableIndexedTheory(unificator, clauses) /** Creates a [MutableTheory] backed by a list, containing the given clauses */ @JvmStatic @JsName("emptyListed") - fun emptyListed(unificator: Unificator): MutableTheory = - listedOf(unificator, emptySequence()) + fun emptyListed(unificator: Unificator): MutableTheory = listedOf(unificator, emptySequence()) /** Creates a [MutableTheory] backed by a list, containing the given clauses */ @JvmStatic @JsName("listedOf") - fun listedOf(unificator: Unificator, vararg clause: Clause): MutableTheory = - listedOf(unificator, clause.asIterable()) + fun listedOf( + unificator: Unificator, + vararg clause: Clause, + ): MutableTheory = listedOf(unificator, clause.asIterable()) /** Let developers easily create a [MutableTheory] backed by a list, while avoiding variables names * clashing by using a different [Scope] for each [Clause] */ @JvmStatic @JsName("listedOfScopes") - fun listedOf(unificator: Unificator, vararg clause: Scope.() -> Clause): MutableTheory = + fun listedOf( + unificator: Unificator, + vararg clause: Scope.() -> Clause, + ): MutableTheory = listedOf( unificator, clause.map { Scope.empty(it) - } + }, ) /** Creates a [MutableTheory] backed by a list, containing the given clauses */ @JvmStatic @JsName("listedOfSequence") - fun listedOf(unificator: Unificator, clauses: Sequence): MutableTheory = - listedOf(unificator, clauses.asIterable()) + fun listedOf( + unificator: Unificator, + clauses: Sequence, + ): MutableTheory = listedOf(unificator, clauses.asIterable()) /** Creates a [MutableTheory] backed by a list, containing the given clauses */ @JvmStatic @JsName("listedOfIterable") - fun listedOf(unificator: Unificator, clauses: Iterable): MutableTheory = - MutableListedTheory(unificator, clauses) + fun listedOf( + unificator: Unificator, + clauses: Iterable, + ): MutableTheory = MutableListedTheory(unificator, clauses) } } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/RetractResult.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/RetractResult.kt index af8264e6f..114f4a31c 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/RetractResult.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/RetractResult.kt @@ -5,7 +5,6 @@ import kotlin.js.JsName /** A result given after a "retract" operation */ sealed class RetractResult { - open val isSuccess: Boolean get() = false @@ -26,7 +25,7 @@ sealed class RetractResult { /** A successful "retract" operation result, carrying the new [theory] and removed [clauses] */ data class Success( override val theory: T, - override val clauses: Iterable + override val clauses: Iterable, ) : RetractResult() { override val isSuccess: Boolean get() = true diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/Theory.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/Theory.kt index 178eda8e2..6bebb69e8 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/Theory.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/Theory.kt @@ -16,7 +16,6 @@ import kotlin.js.JsName import kotlin.jvm.JvmStatic interface Theory : Iterable, Taggable { - @JsName("unificator") val unificator: Unificator @@ -137,8 +136,7 @@ interface Theory : Iterable, Taggable { /** Tries to delete a matching clause from this theory */ @JsName("retractByHead") - fun retract(head: Struct): RetractResult = - retract(Rule.of(head, Var.anonymous())) + fun retract(head: Struct): RetractResult = retract(Rule.of(head, Var.anonymous())) /** Tries to delete all matching clauses from this theory */ @JsName("retractAll") @@ -146,8 +144,7 @@ interface Theory : Iterable, Taggable { /** Tries to delete all matching clauses from this theory */ @JsName("retractAllByHead") - fun retractAll(head: Struct): RetractResult = - retractAll(Rule.of(head, Var.anonymous())) + fun retractAll(head: Struct): RetractResult = retractAll(Rule.of(head, Var.anonymous())) @JsName("abolish") fun abolish(indicator: Indicator): Theory @@ -157,18 +154,19 @@ interface Theory : Iterable, Taggable { fun toString(asPrologText: Boolean): String @JsName("equalsUsingVarCompleteNames") - fun equals(other: Theory, useVarCompleteName: Boolean): Boolean + fun equals( + other: Theory, + useVarCompleteName: Boolean, + ): Boolean @JsName("clone") fun clone(): Theory companion object { - /** Creates an empty [Theory] */ @JvmStatic @JsName("empty") - fun empty(unificator: Unificator): Theory = - indexedOf(unificator, emptySequence()) + fun empty(unificator: Unificator): Theory = indexedOf(unificator, emptySequence()) @JvmStatic @JsName("emptyWithDefaultUnificator") @@ -177,8 +175,10 @@ interface Theory : Iterable, Taggable { /** Creates a [Theory], containing the given clauses */ @JvmStatic @JsName("of") - fun of(unificator: Unificator, vararg clause: Clause): Theory = - indexedOf(unificator, *clause) + fun of( + unificator: Unificator, + vararg clause: Clause, + ): Theory = indexedOf(unificator, *clause) @JvmStatic @JsName("ofWithDefaultUnificator") @@ -187,8 +187,10 @@ interface Theory : Iterable, Taggable { /** Creates a [Theory], containing the given clauses */ @JvmStatic @JsName("ofIterable") - fun of(unificator: Unificator, clauses: Iterable): Theory = - indexedOf(unificator, clauses) + fun of( + unificator: Unificator, + clauses: Iterable, + ): Theory = indexedOf(unificator, clauses) @JvmStatic @JsName("ofIterableWithDefaultUnificator") @@ -197,8 +199,10 @@ interface Theory : Iterable, Taggable { /** Creates a [Theory], containing the given clauses */ @JvmStatic @JsName("ofSequence") - fun of(unificator: Unificator, clauses: Sequence): Theory = - indexedOf(unificator, clauses) + fun of( + unificator: Unificator, + clauses: Sequence, + ): Theory = indexedOf(unificator, clauses) @JvmStatic @JsName("ofSequenceWithDefaultUnificator") @@ -208,8 +212,10 @@ interface Theory : Iterable, Taggable { * different [Scope] for each [Clause] */ @JvmStatic @JsName("ofScopes") - fun of(unificator: Unificator, vararg clauses: Scope.() -> Clause): Theory = - indexedOf(unificator, *clauses) + fun of( + unificator: Unificator, + vararg clauses: Scope.() -> Clause, + ): Theory = indexedOf(unificator, *clauses) @JvmStatic @JsName("ofScopesWithDefaultUnificator") @@ -218,73 +224,89 @@ interface Theory : Iterable, Taggable { /** Creates an empty [Theory] backed by an indexed data structure */ @JvmStatic @JsName("emptyIndexed") - fun emptyIndexed(unificator: Unificator): Theory = - indexedOf(unificator, emptyList()) + fun emptyIndexed(unificator: Unificator): Theory = indexedOf(unificator, emptyList()) /** Creates a [Theory] backed by an indexed data structure, containing the given clauses */ @JvmStatic @JsName("indexedOf") - fun indexedOf(unificator: Unificator, vararg clause: Clause): Theory = - indexedOf(unificator, clause.asIterable()) + fun indexedOf( + unificator: Unificator, + vararg clause: Clause, + ): Theory = indexedOf(unificator, clause.asIterable()) /** Let developers easily create a [Theory] backed by an indexed data structure, while avoiding variables names * clashing by using a different [Scope] for each [Clause] */ @JvmStatic @JsName("indexedOfScopes") - fun indexedOf(unificator: Unificator, vararg clauses: Scope.() -> Clause): Theory = + fun indexedOf( + unificator: Unificator, + vararg clauses: Scope.() -> Clause, + ): Theory = indexedOf( unificator, clauses.map { Scope.empty(it) - } + }, ) /** Creates a [Theory] backed by an indexed data structure, containing the given clauses */ @JvmStatic @JsName("indexedOfSequence") - fun indexedOf(unificator: Unificator, clauses: Sequence): Theory = - indexedOf(unificator, clauses.asIterable()) + fun indexedOf( + unificator: Unificator, + clauses: Sequence, + ): Theory = indexedOf(unificator, clauses.asIterable()) /** Creates a [Theory] backed by an indexed data structure, containing the given clauses */ @JvmStatic @JsName("indexedOfIterable") - fun indexedOf(unificator: Unificator, clauses: Iterable): Theory = - IndexedTheory(unificator, clauses) + fun indexedOf( + unificator: Unificator, + clauses: Iterable, + ): Theory = IndexedTheory(unificator, clauses) /** Creates a [Theory] backed by a list, containing the given clauses */ @JvmStatic @JsName("emptyListed") - fun emptyListed(unificator: Unificator): Theory = - listedOf(unificator, emptySequence()) + fun emptyListed(unificator: Unificator): Theory = listedOf(unificator, emptySequence()) /** Creates a [Theory] backed by a list, containing the given clauses */ @JvmStatic @JsName("listedOf") - fun listedOf(unificator: Unificator, vararg clause: Clause): Theory = - listedOf(unificator, clause.asIterable()) + fun listedOf( + unificator: Unificator, + vararg clause: Clause, + ): Theory = listedOf(unificator, clause.asIterable()) /** Let developers easily create a [Theory] backed by a list, while avoiding variables names * clashing by using a different [Scope] for each [Clause] */ @JvmStatic @JsName("listedOfScopes") - fun listedOf(unificator: Unificator, vararg clause: Scope.() -> Clause): Theory = + fun listedOf( + unificator: Unificator, + vararg clause: Scope.() -> Clause, + ): Theory = listedOf( unificator, clause.map { Scope.empty(it) - } + }, ) /** Creates a [Theory] backed by a list, containing the given clauses */ @JvmStatic @JsName("listedOfSequence") - fun listedOf(unificator: Unificator, clauses: Sequence): Theory = - listedOf(unificator, clauses.asIterable()) + fun listedOf( + unificator: Unificator, + clauses: Sequence, + ): Theory = listedOf(unificator, clauses.asIterable()) /** Creates a [Theory] backed by a list, containing the given clauses */ @JvmStatic @JsName("listedOfIterable") - fun listedOf(unificator: Unificator, clauses: Iterable): Theory = - ListedTheory(unificator, clauses) + fun listedOf( + unificator: Unificator, + clauses: Iterable, + ): Theory = ListedTheory(unificator, clauses) } } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/TheoryUtils.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/TheoryUtils.kt index 5b629f996..10e458676 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/TheoryUtils.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/TheoryUtils.kt @@ -3,7 +3,6 @@ package it.unibo.tuprolog.theory import it.unibo.tuprolog.core.Clause internal object TheoryUtils { - /** Utility method to check clause well-formed property */ fun checkClauseCorrect(clause: Clause) = clause.also { @@ -13,8 +12,7 @@ internal object TheoryUtils { } } - fun checkClausesCorrect(vararg clauses: Clause) = - clauses.asSequence().also { actualCheck(it) } + fun checkClausesCorrect(vararg clauses: Clause) = clauses.asSequence().also { actualCheck(it) } private fun actualCheck(clauses: Sequence) { require(clauses.all { it.isWellFormed }) { @@ -24,9 +22,7 @@ internal object TheoryUtils { } /** Utility method to check more than one clause well-formed property */ - fun checkClausesCorrect(clauses: Iterable) = - clauses.also { actualCheck(it.asSequence()) } + fun checkClausesCorrect(clauses: Iterable) = clauses.also { actualCheck(it.asSequence()) } - fun checkClausesCorrect(clauses: Sequence) = - clauses.also { actualCheck(it) } + fun checkClausesCorrect(clauses: Sequence) = clauses.also { actualCheck(it) } } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/AbstractIndexedTheory.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/AbstractIndexedTheory.kt index dc79c837c..0b2981e73 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/AbstractIndexedTheory.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/AbstractIndexedTheory.kt @@ -9,9 +9,8 @@ import it.unibo.tuprolog.unify.Unificator internal abstract class AbstractIndexedTheory protected constructor( queue: ClauseQueue, - tags: Map + tags: Map, ) : AbstractTheory(tags) { - @Suppress("UNUSED_PARAMETER") override var unificator: Unificator get() = queue.unificator diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/AbstractListedTheory.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/AbstractListedTheory.kt index 901de6962..833f991fe 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/AbstractListedTheory.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/AbstractListedTheory.kt @@ -8,9 +8,8 @@ import kotlin.collections.List as KtList internal abstract class AbstractListedTheory protected constructor( unificator: Unificator, override val clauses: KtList, - tags: Map + tags: Map, ) : AbstractTheory(tags) { - override var unificator: Unificator = unificator final override fun get(clause: Clause): Sequence = diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/IndexedTheory.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/IndexedTheory.kt index dde1ea444..b0d25a586 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/IndexedTheory.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/IndexedTheory.kt @@ -12,14 +12,13 @@ import it.unibo.tuprolog.utils.dequeOf internal class IndexedTheory private constructor( queue: ClauseQueue, - tags: Map + tags: Map, ) : AbstractIndexedTheory(queue, tags) { - /** Construct a Clause database from given clauses */ constructor( unificator: Unificator, clauses: Iterable, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : this(ClauseQueue.of(unificator, clauses), tags) { checkClausesCorrect(clauses) } @@ -28,13 +27,13 @@ internal class IndexedTheory private constructor( constructor( unificator: Unificator, clauses: Sequence, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : this(unificator, clauses.asIterable(), tags) override fun createNewTheory( clauses: Sequence, tags: Map, - unificator: Unificator + unificator: Unificator, ) = IndexedTheory(unificator, clauses, tags) override fun retract(clause: Clause): RetractResult { @@ -42,10 +41,11 @@ internal class IndexedTheory private constructor( val retracted = newTheory.retrieveFirst(clause) return when { retracted.isFailure -> RetractResult.Failure(this) - else -> RetractResult.Success( - IndexedTheory(retracted.collection, tags), - retracted.clauses!! - ) + else -> + RetractResult.Success( + IndexedTheory(retracted.collection, tags), + retracted.clauses!!, + ) } } @@ -72,7 +72,7 @@ internal class IndexedTheory private constructor( } else { RetractResult.Success( IndexedTheory(newTheory, tags), - removed + removed, ) } } @@ -82,16 +82,19 @@ internal class IndexedTheory private constructor( val retracted = newTheory.retrieveAll(clause) return when { retracted.isFailure -> RetractResult.Failure(this) - else -> RetractResult.Success( - IndexedTheory(retracted.collection, tags), - retracted.clauses!! - ) + else -> + RetractResult.Success( + IndexedTheory(retracted.collection, tags), + retracted.clauses!!, + ) } } private val hashCodeCache: Int by lazy { super.hashCode() } - override fun hashCode(): Int { return hashCodeCache } + override fun hashCode(): Int { + return hashCodeCache + } private val sizeCache: Long by lazy { super.size } @@ -99,5 +102,12 @@ internal class IndexedTheory private constructor( get() = sizeCache override fun replaceTags(tags: Map): IndexedTheory = - if (tags === this.tags) this else IndexedTheory(queue, tags) + if (tags === this.tags) { + this + } else { + IndexedTheory( + queue, + tags, + ) + } } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/ListedTheory.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/ListedTheory.kt index a3d1b0e6f..05bb69e0e 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/ListedTheory.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/ListedTheory.kt @@ -12,13 +12,12 @@ import kotlin.collections.List as KtList internal class ListedTheory private constructor( unificator: Unificator, clauses: KtList, - tags: Map + tags: Map, ) : AbstractListedTheory(unificator, clauses, tags) { - constructor( unificator: Unificator, clauses: Iterable, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : this(unificator, clauses.toList(), tags) { checkClausesCorrect(clauses) } @@ -26,7 +25,7 @@ internal class ListedTheory private constructor( constructor( unificator: Unificator, clauses: Sequence, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : this(unificator, clauses.toList(), tags) { checkClausesCorrect(clauses) } @@ -34,7 +33,7 @@ internal class ListedTheory private constructor( override fun createNewTheory( clauses: Sequence, tags: Map, - unificator: Unificator + unificator: Unificator, ) = ListedTheory(unificator, clauses, tags) override fun retract(clause: Clause): RetractResult { @@ -46,7 +45,7 @@ internal class ListedTheory private constructor( val newTheory = clauses.filter { it != toBeActuallyRetracted } RetractResult.Success( ListedTheory(unificator, newTheory, tags), - listOf(toBeActuallyRetracted) + listOf(toBeActuallyRetracted), ) } } @@ -82,7 +81,7 @@ internal class ListedTheory private constructor( val toBeActuallyRetracted = partitionedClauses.first RetractResult.Success( ListedTheory(unificator, newTheory, tags), - toBeActuallyRetracted + toBeActuallyRetracted, ) } } diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/MutableIndexedTheory.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/MutableIndexedTheory.kt index f4412d1dc..faa658945 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/MutableIndexedTheory.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/MutableIndexedTheory.kt @@ -14,9 +14,8 @@ import it.unibo.tuprolog.unify.Unificator internal class MutableIndexedTheory private constructor( override val queue: MutableClauseQueue, - tags: Map + tags: Map, ) : AbstractIndexedTheory(queue, tags), MutableTheory { - override fun setUnificator(unificator: Unificator): MutableTheory = super.setUnificator(unificator).toMutableTheory() @@ -24,7 +23,7 @@ internal class MutableIndexedTheory private constructor( constructor( unificator: Unificator, clauses: Iterable, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : this(MutableClauseQueue.of(unificator, clauses), tags) { checkClausesCorrect(clauses) } @@ -33,7 +32,7 @@ internal class MutableIndexedTheory private constructor( constructor( unificator: Unificator, clauses: Sequence, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : this(unificator, clauses.asIterable(), tags) override fun toMutableTheory(): MutableTheory = super.toMutableTheory() @@ -45,11 +44,10 @@ internal class MutableIndexedTheory private constructor( override fun createNewTheory( clauses: Sequence, tags: Map, - unificator: Unificator + unificator: Unificator, ): MutableIndexedTheory = MutableIndexedTheory(unificator, clauses, tags) - override fun retract(clause: Clause): RetractResult = - queue.retrieve(clause).toRetractResult() + override fun retract(clause: Clause): RetractResult = queue.retrieve(clause).toRetractResult() private fun RetrieveResult.toRetractResult(): RetractResult = when { @@ -58,11 +56,12 @@ internal class MutableIndexedTheory private constructor( } override fun retract(clauses: Iterable): RetractResult { - val retracted = clauses.asSequence() - .map { queue.retrieve(it) } - .filter { it.isSuccess } - .flatMap { it.clauses!!.asSequence() } - .toList() + val retracted = + clauses.asSequence() + .map { queue.retrieve(it) } + .filter { it.isSuccess } + .flatMap { it.clauses!!.asSequence() } + .toList() return if (retracted.isEmpty()) { RetractResult.Failure(this) } else { @@ -71,7 +70,9 @@ internal class MutableIndexedTheory private constructor( } override fun retractAll(clause: Clause): RetractResult = - queue.retrieveAll(clause).toRetractResult() + queue.retrieveAll( + clause, + ).toRetractResult() override fun plus(clause: Clause): MutableIndexedTheory = assertZ(checkClauseCorrect(clause)) @@ -84,7 +85,11 @@ internal class MutableIndexedTheory private constructor( } override fun assertA(clause: Clause): MutableIndexedTheory = - this.also { it.queue.addFirst(checkClauseCorrect(clause)) } + this.also { + it.queue.addFirst( + checkClauseCorrect(clause), + ) + } override fun assertA(clauses: Iterable): MutableIndexedTheory { return this.also { @@ -97,16 +102,23 @@ internal class MutableIndexedTheory private constructor( override fun assertA(clauses: Sequence): MutableIndexedTheory = assertA(clauses.asIterable()) override fun assertZ(clause: Clause): MutableIndexedTheory = - this.also { it.queue.addLast(checkClauseCorrect(clause)) } + this.also { + it.queue.addLast( + checkClauseCorrect(clause), + ) + } override fun assertZ(clauses: Iterable): MutableIndexedTheory = - this.also { it.queue.addAll(checkClausesCorrect(clauses)) } + this.also { + it.queue.addAll(checkClausesCorrect(clauses)) + } override fun assertZ(clauses: Sequence): MutableIndexedTheory = - assertZ(checkClausesCorrect(clauses.asIterable())) + assertZ( + checkClausesCorrect(clauses.asIterable()), + ) - override fun retract(clauses: Sequence): RetractResult = - retract(clauses.asIterable()) + override fun retract(clauses: Sequence): RetractResult = retract(clauses.asIterable()) override fun abolish(indicator: Indicator): MutableTheory = super.abolish(indicator).toMutableTheory() diff --git a/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/MutableListedTheory.kt b/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/MutableListedTheory.kt index 8c2d7b623..9ec3a3dc6 100644 --- a/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/MutableListedTheory.kt +++ b/theory/src/commonMain/kotlin/it/unibo/tuprolog/theory/impl/MutableListedTheory.kt @@ -13,9 +13,8 @@ import it.unibo.tuprolog.utils.addFirst internal class MutableListedTheory private constructor( unificator: Unificator, override val clauses: MutableList, - tags: Map + tags: Map, ) : AbstractListedTheory(unificator, clauses, tags), MutableTheory { - override fun setUnificator(unificator: Unificator): MutableTheory { this.unificator = unificator return this @@ -24,7 +23,7 @@ internal class MutableListedTheory private constructor( constructor( unificator: Unificator, clauses: Iterable, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : this(unificator, clauses.toMutableList(), tags) { checkClausesCorrect(clauses) } @@ -32,7 +31,7 @@ internal class MutableListedTheory private constructor( constructor( unificator: Unificator, clauses: Sequence, - tags: Map = emptyMap() + tags: Map = emptyMap(), ) : this(unificator, clauses.toMutableList(), tags) { checkClausesCorrect(clauses) } @@ -42,7 +41,7 @@ internal class MutableListedTheory private constructor( override fun createNewTheory( clauses: Sequence, tags: Map, - unificator: Unificator + unificator: Unificator, ) = MutableListedTheory(unificator, clauses, tags) override fun retract(clause: Clause): RetractResult { @@ -104,18 +103,23 @@ internal class MutableListedTheory private constructor( } override fun assertA(clause: Clause): MutableListedTheory = - this.also { it.clauses.addFirst(checkClauseCorrect(clause)) } + this.also { + it.clauses.addFirst(checkClauseCorrect(clause)) + } override fun assertA(clauses: Iterable): MutableListedTheory = - this.also { it.clauses.addFirst(checkClausesCorrect(clauses)) } + this.also { + it.clauses.addFirst(checkClausesCorrect(clauses)) + } override fun assertA(clauses: Sequence): MutableListedTheory = assertA(clauses.asIterable()) - override fun assertZ(clause: Clause): MutableListedTheory = - this.also { it.clauses.add(checkClauseCorrect(clause)) } + override fun assertZ(clause: Clause): MutableListedTheory = this.also { it.clauses.add(checkClauseCorrect(clause)) } override fun assertZ(clauses: Iterable): MutableListedTheory = - this.also { it.clauses.addAll(checkClausesCorrect(clauses)) } + this.also { + it.clauses.addAll(checkClausesCorrect(clauses)) + } override fun assertZ(clauses: Sequence): MutableListedTheory = assertZ(clauses.asIterable()) diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/PrototypeClauseCollectionTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/PrototypeClauseCollectionTest.kt index 1115b5c1c..d1c01e852 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/PrototypeClauseCollectionTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/PrototypeClauseCollectionTest.kt @@ -1,7 +1,6 @@ package it.unibo.tuprolog.collections internal interface PrototypeClauseCollectionTest { - fun getTakesUnificationIntoAccount() fun retractTakesUnificationIntoAccount() diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/PrototypeClauseMultiSetTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/PrototypeClauseMultiSetTest.kt index fb96766e2..1a3bf8ad8 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/PrototypeClauseMultiSetTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/PrototypeClauseMultiSetTest.kt @@ -4,7 +4,6 @@ import it.unibo.tuprolog.collections.prototypes.PrototypeClauseMultiSetTestImpl import it.unibo.tuprolog.core.Clause internal interface PrototypeClauseMultiSetTest : PrototypeClauseCollectionTest { - fun countingOnPresentClauseAnswerTheRightNumber() fun countingOnAbsentClauseAnswerZero() @@ -20,11 +19,11 @@ internal interface PrototypeClauseMultiSetTest : PrototypeClauseCollectionTest { companion object { internal fun prototype( emptyGenerator: () -> ClauseMultiSet, - collectionGenerator: (Iterable) -> ClauseMultiSet + collectionGenerator: (Iterable) -> ClauseMultiSet, ): PrototypeClauseMultiSetTest = PrototypeClauseMultiSetTestImpl( emptyGenerator, - collectionGenerator + collectionGenerator, ) } } diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/PrototypeClauseQueueTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/PrototypeClauseQueueTest.kt index 67692d2f6..f40a09855 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/PrototypeClauseQueueTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/PrototypeClauseQueueTest.kt @@ -4,7 +4,6 @@ import it.unibo.tuprolog.collections.prototypes.PrototypeClauseQueueTestImpl import it.unibo.tuprolog.core.Clause internal interface PrototypeClauseQueueTest : PrototypeClauseCollectionTest { - fun getWithPresentClauseReturnsTheCorrectSequence() fun getWithAbsentClauseReturnsAnEmptySequence() @@ -32,11 +31,11 @@ internal interface PrototypeClauseQueueTest : PrototypeClauseCollectionTest { companion object { internal fun prototype( emptyGenerator: () -> ClauseQueue, - collectionGenerator: (Iterable) -> ClauseQueue + collectionGenerator: (Iterable) -> ClauseQueue, ): PrototypeClauseQueueTest = PrototypeClauseQueueTestImpl( emptyGenerator, - collectionGenerator + collectionGenerator, ) } } diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/impl/Factories.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/impl/Factories.kt index ee1049f7f..391c6d91e 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/impl/Factories.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/impl/Factories.kt @@ -14,76 +14,96 @@ object Factories { fun emptyMutableClauseMultiset(): MutableClauseMultiSet = MutableClauseMultiSet.empty(Unificator.default) fun mutableClauseMultisetOf(clauses: Iterable): MutableClauseMultiSet = - MutableClauseMultiSet.of(Unificator.default, clauses) + MutableClauseMultiSet.of( + Unificator.default, + clauses, + ) fun emptyMutableClauseQueue(): MutableClauseQueue = MutableClauseQueue.empty(Unificator.default) fun mutableClauseQueueOf(clauses: Iterable): MutableClauseQueue = - MutableClauseQueue.of(Unificator.default, clauses) + MutableClauseQueue.of( + Unificator.default, + clauses, + ) fun emptyClauseMultiset(): ClauseMultiSet = ClauseMultiSet.empty(Unificator.default) - fun clauseMultisetOf(clauses: Iterable): ClauseMultiSet = - ClauseMultiSet.of(Unificator.default, clauses) + fun clauseMultisetOf(clauses: Iterable): ClauseMultiSet = ClauseMultiSet.of(Unificator.default, clauses) fun emptyClauseQueue(): ClauseQueue = ClauseQueue.empty(Unificator.default) - fun clauseQueueOf(clauses: Iterable): ClauseQueue = - ClauseQueue.of(Unificator.default, clauses) + fun clauseQueueOf(clauses: Iterable): ClauseQueue = ClauseQueue.of(Unificator.default, clauses) fun emptyIndexedTheory(): Theory = Theory.emptyIndexed(Unificator.default) - fun indexedTheoryOf(clauses: Iterable): Theory = - Theory.indexedOf(Unificator.default, clauses) + fun indexedTheoryOf(clauses: Iterable): Theory = Theory.indexedOf(Unificator.default, clauses) - fun indexedTheoryOf(clauses: Array): Theory = - Theory.indexedOf(Unificator.default, *clauses) + fun indexedTheoryOf(clauses: Array): Theory = Theory.indexedOf(Unificator.default, *clauses) - fun indexedTheoryOf(clauses: Sequence): Theory = - Theory.indexedOf(Unificator.default, clauses) + fun indexedTheoryOf(clauses: Sequence): Theory = Theory.indexedOf(Unificator.default, clauses) - fun indexedTheoryOf(clauses: Array Clause>): Theory = - Theory.indexedOf(Unificator.default, *clauses) + fun indexedTheoryOf(clauses: Array Clause>): Theory = Theory.indexedOf(Unificator.default, *clauses) fun emptyMutableIndexedTheory(): MutableTheory = MutableTheory.emptyIndexed(Unificator.default) fun mutableIndexedTheoryOf(clauses: Iterable): MutableTheory = - MutableTheory.indexedOf(Unificator.default, clauses) + MutableTheory.indexedOf( + Unificator.default, + clauses, + ) fun mutableIndexedTheoryOf(clauses: Array): MutableTheory = - MutableTheory.indexedOf(Unificator.default, *clauses) + MutableTheory.indexedOf( + Unificator.default, + *clauses, + ) fun mutableIndexedTheoryOf(clauses: Sequence): MutableTheory = - MutableTheory.indexedOf(Unificator.default, clauses) + MutableTheory.indexedOf( + Unificator.default, + clauses, + ) fun mutableIndexedTheoryOf(clauses: Array Clause>): MutableTheory = - MutableTheory.indexedOf(Unificator.default, *clauses) + MutableTheory.indexedOf( + Unificator.default, + *clauses, + ) fun emptyListedTheory(): Theory = Theory.emptyListed(Unificator.default) - fun listedTheoryOf(clauses: Iterable): Theory = - Theory.listedOf(Unificator.default, clauses) + fun listedTheoryOf(clauses: Iterable): Theory = Theory.listedOf(Unificator.default, clauses) - fun listedTheoryOf(clauses: Array): Theory = - Theory.listedOf(Unificator.default, *clauses) + fun listedTheoryOf(clauses: Array): Theory = Theory.listedOf(Unificator.default, *clauses) - fun listedTheoryOf(clauses: Sequence): Theory = - Theory.listedOf(Unificator.default, clauses) + fun listedTheoryOf(clauses: Sequence): Theory = Theory.listedOf(Unificator.default, clauses) - fun listedTheoryOf(clauses: Array Clause>): Theory = - Theory.listedOf(Unificator.default, *clauses) + fun listedTheoryOf(clauses: Array Clause>): Theory = Theory.listedOf(Unificator.default, *clauses) fun emptyMutableListedTheory(): MutableTheory = MutableTheory.emptyListed(Unificator.default) fun mutableListedTheoryOf(clauses: Iterable): MutableTheory = - MutableTheory.listedOf(Unificator.default, clauses) + MutableTheory.listedOf( + Unificator.default, + clauses, + ) fun mutableListedTheoryOf(clauses: Array): MutableTheory = - MutableTheory.listedOf(Unificator.default, *clauses) + MutableTheory.listedOf( + Unificator.default, + *clauses, + ) fun mutableListedTheoryOf(clauses: Sequence): MutableTheory = - MutableTheory.listedOf(Unificator.default, clauses) + MutableTheory.listedOf( + Unificator.default, + clauses, + ) fun mutableListedTheoryOf(clauses: Array Clause>): MutableTheory = - MutableTheory.listedOf(Unificator.default, *clauses) + MutableTheory.listedOf( + Unificator.default, + *clauses, + ) } diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/impl/MutableReteClauseMultiSetTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/impl/MutableReteClauseMultiSetTest.kt index a60be962b..e29fe0820 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/impl/MutableReteClauseMultiSetTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/impl/MutableReteClauseMultiSetTest.kt @@ -4,11 +4,11 @@ import it.unibo.tuprolog.collections.PrototypeClauseMultiSetTest import kotlin.test.Test internal class MutableReteClauseMultiSetTest : PrototypeClauseMultiSetTest { - - private val prototype = PrototypeClauseMultiSetTest.prototype( - Factories::emptyClauseMultiset, - Factories::mutableClauseMultisetOf - ) + private val prototype = + PrototypeClauseMultiSetTest.prototype( + Factories::emptyClauseMultiset, + Factories::mutableClauseMultisetOf, + ) @Test override fun collectionHasTheCorrectSize() { diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/impl/MutableReteClauseQueueTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/impl/MutableReteClauseQueueTest.kt index dd807aae2..295fa5017 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/impl/MutableReteClauseQueueTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/impl/MutableReteClauseQueueTest.kt @@ -4,11 +4,11 @@ import it.unibo.tuprolog.collections.PrototypeClauseQueueTest import kotlin.test.Test internal class MutableReteClauseQueueTest : PrototypeClauseQueueTest { - - private val prototype = PrototypeClauseQueueTest.prototype( - Factories::emptyClauseQueue, - Factories::clauseQueueOf - ) + private val prototype = + PrototypeClauseQueueTest.prototype( + Factories::emptyClauseQueue, + Factories::clauseQueueOf, + ) @Test override fun getWithPresentClauseReturnsTheCorrectSequence() { diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/impl/ReteClauseMultiSetTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/impl/ReteClauseMultiSetTest.kt index 4db02f887..9c1f1adc4 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/impl/ReteClauseMultiSetTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/impl/ReteClauseMultiSetTest.kt @@ -4,11 +4,11 @@ import it.unibo.tuprolog.collections.PrototypeClauseMultiSetTest import kotlin.test.Test internal class ReteClauseMultiSetTest : PrototypeClauseMultiSetTest { - - private val prototype = PrototypeClauseMultiSetTest.prototype( - Factories::emptyClauseMultiset, - Factories::mutableClauseMultisetOf - ) + private val prototype = + PrototypeClauseMultiSetTest.prototype( + Factories::emptyClauseMultiset, + Factories::mutableClauseMultisetOf, + ) @Test override fun collectionHasTheCorrectSize() { diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/impl/ReteClauseQueueTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/impl/ReteClauseQueueTest.kt index a2731b943..390787ade 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/impl/ReteClauseQueueTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/impl/ReteClauseQueueTest.kt @@ -4,11 +4,11 @@ import it.unibo.tuprolog.collections.PrototypeClauseQueueTest import kotlin.test.Test internal class ReteClauseQueueTest : PrototypeClauseQueueTest { - - private val prototype = PrototypeClauseQueueTest.prototype( - Factories::emptyClauseQueue, - Factories::mutableClauseQueueOf - ) + private val prototype = + PrototypeClauseQueueTest.prototype( + Factories::emptyClauseQueue, + Factories::mutableClauseQueueOf, + ) @Test override fun getWithPresentClauseReturnsTheCorrectSequence() { diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/prototypes/PrototypeClauseCollectionTestImpl.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/prototypes/PrototypeClauseCollectionTestImpl.kt index f388facda..ab128348d 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/prototypes/PrototypeClauseCollectionTestImpl.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/prototypes/PrototypeClauseCollectionTestImpl.kt @@ -22,9 +22,8 @@ import it.unibo.tuprolog.core.List as LogicList internal abstract class PrototypeClauseCollectionTestImpl( private val emptyGenerator: () -> ClauseCollection, - private val collectionGenerator: (Iterable) -> ClauseCollection + private val collectionGenerator: (Iterable) -> ClauseCollection, ) : PrototypeClauseCollectionTest { - private val fFamilySelector = Fact.of(Struct.of("f", Var.anonymous())) @@ -41,21 +40,27 @@ internal abstract class PrototypeClauseCollectionTestImpl( listOf( Fact.of(Struct.of("f", Atom.of("a"))), Fact.of(Struct.of("f", Atom.of("b"))), - Fact.of(Struct.of("f", Atom.of("c"))) + Fact.of(Struct.of("f", Atom.of("c"))), ) private val newClauses = listOf( Fact.of(Struct.of("f", Atom.of("d"))), Fact.of(Struct.of("f", Atom.of("e"))), - Fact.of(Struct.of("f", Atom.of("f"))) + Fact.of(Struct.of("f", Atom.of("f"))), ) private val emptyCollection = emptyGenerator() - protected abstract fun getClauses(collection: ClauseCollection, query: Clause): Sequence + protected abstract fun getClauses( + collection: ClauseCollection, + query: Clause, + ): Sequence - protected abstract fun retractClauses(collection: ClauseCollection, query: Clause): Sequence + protected abstract fun retractClauses( + collection: ClauseCollection, + query: Clause, + ): Sequence override fun getTakesUnificationIntoAccount() { val collection = collectionGenerator(memberClause) @@ -66,13 +71,13 @@ internal abstract class PrototypeClauseCollectionTestImpl( collection, member( LogicList.of(Struct.of("a", Var.of("X"))), - LogicList.of(LogicList.of(Struct.of("a", Integer.of(1)))) - ) - ) + LogicList.of(LogicList.of(Struct.of("a", Integer.of(1)))), + ), + ), ) assertClausesHaveSameLengthAndContent( memberClause.asSequence(), - getClauses(collection, member(Atom.of("a"), LogicList.of(Atom.of("a")))) + getClauses(collection, member(Atom.of("a"), LogicList.of(Atom.of("a")))), ) assertClausesHaveSameLengthAndContent( sequenceOf(), @@ -80,13 +85,13 @@ internal abstract class PrototypeClauseCollectionTestImpl( collection, member( LogicList.of(Struct.of("a", Var.of("X"))), - LogicList.of(LogicList.of(Struct.of("b", Integer.of(1)))) - ) - ) + LogicList.of(LogicList.of(Struct.of("b", Integer.of(1)))), + ), + ), ) assertClausesHaveSameLengthAndContent( sequenceOf(), - getClauses(collection, member(Atom.of("a"), LogicList.of(Atom.of("b")))) + getClauses(collection, member(Atom.of("a"), LogicList.of(Atom.of("b")))), ) } @@ -99,16 +104,16 @@ internal abstract class PrototypeClauseCollectionTestImpl( collection, member( LogicList.of(Struct.of("a", Var.of("X"))), - LogicList.of(LogicList.of(Struct.of("a", Integer.of(1)))) - ) - ) + LogicList.of(LogicList.of(Struct.of("a", Integer.of(1)))), + ), + ), ) collection = collectionGenerator(memberClause) assertClausesHaveSameLengthAndContent( memberClause.asSequence(), - retractClauses(collection, member(Atom.of("a"), LogicList.of(Atom.of("a")))) + retractClauses(collection, member(Atom.of("a"), LogicList.of(Atom.of("a")))), ) collection = collectionGenerator(memberClause) @@ -119,16 +124,16 @@ internal abstract class PrototypeClauseCollectionTestImpl( collection, member( LogicList.of(Struct.of("a", Var.of("X"))), - LogicList.of(LogicList.of(Struct.of("b", Integer.of(1)))) - ) - ) + LogicList.of(LogicList.of(Struct.of("b", Integer.of(1)))), + ), + ), ) collection = collectionGenerator(memberClause) assertClausesHaveSameLengthAndContent( sequenceOf(), - retractClauses(collection, member(Atom.of("a"), LogicList.of(Atom.of("b")))) + retractClauses(collection, member(Atom.of("a"), LogicList.of(Atom.of("b")))), ) } @@ -211,7 +216,7 @@ internal abstract class PrototypeClauseCollectionTestImpl( assertClausesHaveSameLengthAndContent( collectionGenerator(clauses), - retrieveResult.collection + retrieveResult.collection, ) } @@ -222,11 +227,11 @@ internal abstract class PrototypeClauseCollectionTestImpl( assertClausesHaveSameLengthAndContent( listOf(presentClause, presentClause), - retrieveResult.clauses + retrieveResult.clauses, ) assertClausesHaveSameLengthAndContent( clauses - presentClause, - retrieveResult.collection + retrieveResult.collection, ) } diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/prototypes/PrototypeClauseMultiSetTestImpl.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/prototypes/PrototypeClauseMultiSetTestImpl.kt index 0c8c07bb4..12a0f4dfc 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/prototypes/PrototypeClauseMultiSetTestImpl.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/prototypes/PrototypeClauseMultiSetTestImpl.kt @@ -14,10 +14,9 @@ import kotlin.test.assertEquals internal class PrototypeClauseMultiSetTestImpl( private val emptyGenerator: () -> ClauseMultiSet, - private val collectionGenerator: (Iterable) -> ClauseMultiSet + private val collectionGenerator: (Iterable) -> ClauseMultiSet, ) : PrototypeClauseMultiSetTest, PrototypeClauseCollectionTestImpl(emptyGenerator, collectionGenerator) { - private val presentClause = Fact.of(Struct.of("f", Atom.of("a"))) @@ -28,16 +27,22 @@ internal class PrototypeClauseMultiSetTestImpl( listOf( Fact.of(Struct.of("f", Atom.of("a"))), Fact.of(Struct.of("f", Atom.of("b"))), - Fact.of(Struct.of("f", Atom.of("c"))) + Fact.of(Struct.of("f", Atom.of("c"))), ) private val emptyCollection = emptyGenerator() - override fun getClauses(collection: ClauseCollection, query: Clause): Sequence { + override fun getClauses( + collection: ClauseCollection, + query: Clause, + ): Sequence { return (collection as ClauseMultiSet).get(query) } - override fun retractClauses(collection: ClauseCollection, query: Clause): Sequence { + override fun retractClauses( + collection: ClauseCollection, + query: Clause, + ): Sequence { return when (val res = (collection as ClauseMultiSet).retrieve(query)) { is RetrieveResult.Success -> res.clauses.asSequence() else -> emptySequence() @@ -93,7 +98,7 @@ internal class PrototypeClauseMultiSetTestImpl( assertEquals( 1, - permutations.map { collectionGenerator(it) }.toSet().size + permutations.map { collectionGenerator(it) }.toSet().size, ) } } diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/prototypes/PrototypeClauseQueueTestImpl.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/prototypes/PrototypeClauseQueueTestImpl.kt index 243e75669..4848d7678 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/prototypes/PrototypeClauseQueueTestImpl.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/prototypes/PrototypeClauseQueueTestImpl.kt @@ -18,10 +18,9 @@ import kotlin.test.assertNotEquals internal class PrototypeClauseQueueTestImpl( private val emptyGenerator: () -> ClauseQueue, - private val collectionGenerator: (Iterable) -> ClauseQueue + private val collectionGenerator: (Iterable) -> ClauseQueue, ) : PrototypeClauseQueueTest, PrototypeClauseCollectionTestImpl(emptyGenerator, collectionGenerator) { - private val fFamilySelector = Fact.of(Struct.of("f", Var.anonymous())) @@ -38,14 +37,14 @@ internal class PrototypeClauseQueueTestImpl( listOf( Fact.of(Struct.of("f", Atom.of("a"))), Fact.of(Struct.of("f", Atom.of("b"))), - Fact.of(Struct.of("f", Atom.of("c"))) + Fact.of(Struct.of("f", Atom.of("c"))), ) private val newClauses = listOf( Fact.of(Struct.of("f", Atom.of("d"))), Fact.of(Struct.of("f", Atom.of("e"))), - Fact.of(Struct.of("f", Atom.of("f"))) + Fact.of(Struct.of("f", Atom.of("f"))), ) private val orderSensitiveClauses = @@ -55,23 +54,29 @@ internal class PrototypeClauseQueueTestImpl( Fact.of(Struct.of("f", Atom.of("b"))), Fact.of(Struct.of("g", Numeric.of(2))), Fact.of(Struct.of("f", Atom.of("c"))), - Fact.of(Struct.of("g", Numeric.of(3))) + Fact.of(Struct.of("g", Numeric.of(3))), ) private val numericClauses = listOf( Fact.of(Struct.of("g", Numeric.of(1))), Fact.of(Struct.of("g", Numeric.of(2))), - Fact.of(Struct.of("g", Numeric.of(3))) + Fact.of(Struct.of("g", Numeric.of(3))), ) private val emptyCollection = emptyGenerator() - override fun getClauses(collection: ClauseCollection, query: Clause): Sequence { + override fun getClauses( + collection: ClauseCollection, + query: Clause, + ): Sequence { return (collection as ClauseQueue).get(query) } - override fun retractClauses(collection: ClauseCollection, query: Clause): Sequence { + override fun retractClauses( + collection: ClauseCollection, + query: Clause, + ): Sequence { return when (val res = (collection as ClauseQueue).retrieve(query)) { is RetrieveResult.Success -> res.clauses.asSequence() else -> emptySequence() @@ -83,7 +88,7 @@ internal class PrototypeClauseQueueTestImpl( assertClausesHaveSameLengthAndContent( listOf(presentClause, presentClause), - sequence.toList() + sequence.toList(), ) } @@ -98,7 +103,7 @@ internal class PrototypeClauseQueueTestImpl( assertClausesHaveSameLengthAndContent( collectionGenerator(listOf(newClause) + clauses), - prependedCollectionSnapshot + prependedCollectionSnapshot, ) } @@ -107,7 +112,7 @@ internal class PrototypeClauseQueueTestImpl( assertClausesHaveSameLengthAndContent( collectionGenerator(clauses + listOf(newClause)), - appendedCollectionSnapshot + appendedCollectionSnapshot, ) } @@ -128,7 +133,7 @@ internal class PrototypeClauseQueueTestImpl( assertClausesHaveSameLengthAndContent( collectionGenerator(clauses + listOf(newClause)), - appendedCollectionSnapshot + appendedCollectionSnapshot, ) } @@ -175,7 +180,7 @@ internal class PrototypeClauseQueueTestImpl( assertEquals( permutations.size, - permutations.map { collectionGenerator(it) }.toSet().size + permutations.map { collectionGenerator(it) }.toSet().size, ) } } diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/custom/OrderedReteTreeTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/custom/OrderedReteTreeTest.kt index 5fd50a9b8..07605eb16 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/custom/OrderedReteTreeTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/custom/OrderedReteTreeTest.kt @@ -19,13 +19,10 @@ import kotlin.test.Test import kotlin.test.assertEquals class OrderedReteTreeTest { - companion object { - private fun reteTreeOf(vararg clauses: Clause): ReteTree = - ReteTree.ordered(Unificator.default, *clauses) + private fun reteTreeOf(vararg clauses: Clause): ReteTree = ReteTree.ordered(Unificator.default, *clauses) - private fun reteTreeOf(clauses: Iterable): ReteTree = - ReteTree.ordered(Unificator.default, clauses) + private fun reteTreeOf(clauses: Iterable): ReteTree = ReteTree.ordered(Unificator.default, clauses) } @Test @@ -429,11 +426,12 @@ class OrderedReteTreeTest { @Test fun anOrderedTreeFiltersClausesByBodyAsWell() { - val groundTerms = defaultClauses.asSequence() - .filterIsInstance() - .flatMap { sequenceOf(it.head) + it.head.argsSequence } - .filter { it.isGround } - .toSet() + val groundTerms = + defaultClauses.asSequence() + .filterIsInstance() + .flatMap { sequenceOf(it.head) + it.head.argsSequence } + .filter { it.isGround } + .toSet() val families = defaultClauses.filterIsInstance().map { it.head.functor to it.head.arity }.toSet() for ((functor, arity) in families) { for (args in groundTerms.allChunksOfSize(arity)) { @@ -497,15 +495,17 @@ class OrderedReteTreeTest { @Test fun nonGroundClausesAreMatchedByGroundQueries() { - val groundTerms = defaultClauses.asSequence() - .filterIsInstance() - .flatMap { sequenceOf(it.head) + it.head.argsSequence } - .filter { it.isGround } - .toSet() - val families = defaultClauses.filterIsInstance() - .map { it.head.functor to it.head.arity } - .filter { (_, arity) -> arity > 0 } - .toSet() + val groundTerms = + defaultClauses.asSequence() + .filterIsInstance() + .flatMap { sequenceOf(it.head) + it.head.argsSequence } + .filter { it.isGround } + .toSet() + val families = + defaultClauses.filterIsInstance() + .map { it.head.functor to it.head.arity } + .filter { (_, arity) -> arity > 0 } + .toSet() for ((functor, arity) in families) { for (args in groundTerms.allChunksOfSize(arity)) { diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/custom/ReteTreeAssertionUtils.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/custom/ReteTreeAssertionUtils.kt index b709e5753..e70d5e64a 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/custom/ReteTreeAssertionUtils.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/custom/ReteTreeAssertionUtils.kt @@ -26,49 +26,77 @@ import kotlin.collections.List as KtList import kotlin.collections.Set as KtSet internal object ReteTreeAssertionUtils { - fun assertItemsAreEquals(expected: KtList, actual: KtList, message: (() -> String)? = null) { + fun assertItemsAreEquals( + expected: KtList, + actual: KtList, + message: (() -> String)? = null, + ) { assertEquals(expected, actual, message?.invoke()) } - fun assertItemMultisetsAreEqual(expected: KtSet, actual: KtSet, message: (() -> String)? = null) { + fun assertItemMultisetsAreEqual( + expected: KtSet, + actual: KtSet, + message: (() -> String)? = null, + ) { assertEquals(expected, actual, message?.invoke()) } - fun assertItemsAreEquals(expected: Iterable, actual: Iterable, message: (() -> String)? = null) { + fun assertItemsAreEquals( + expected: Iterable, + actual: Iterable, + message: (() -> String)? = null, + ) { return assertItemsAreEquals( expected.toList(), actual.toList(), - message + message, ) } - fun assertItemMultisetsAreEqual(expected: Iterable, actual: Iterable, message: (() -> String)? = null) { + fun assertItemMultisetsAreEqual( + expected: Iterable, + actual: Iterable, + message: (() -> String)? = null, + ) { assertEquals(expected.count(), actual.count()) return assertItemMultisetsAreEqual( expected.toSet(), actual.toSet(), - message + message, ) } - fun assertItemsAreEquals(expected: Sequence, actual: Sequence, message: (() -> String)? = null) { + fun assertItemsAreEquals( + expected: Sequence, + actual: Sequence, + message: (() -> String)? = null, + ) { return assertItemsAreEquals( expected.toList(), actual.toList(), - message + message, ) } - fun assertItemMultisetsAreEqual(expected: Sequence, actual: Sequence, message: (() -> String)? = null) { + fun assertItemMultisetsAreEqual( + expected: Sequence, + actual: Sequence, + message: (() -> String)? = null, + ) { assertEquals(expected.count(), actual.count()) return assertItemMultisetsAreEqual( expected.toSet(), actual.toSet(), - message + message, ) } - fun assertPartialOrderIsTheSame(expected: Iterator, actual: Iterator, message: ((T) -> String)? = null) { + fun assertPartialOrderIsTheSame( + expected: Iterator, + actual: Iterator, + message: ((T) -> String)? = null, + ) { while (expected.hasNext()) { val e = expected.next() while (actual.hasNext()) { @@ -81,23 +109,35 @@ internal object ReteTreeAssertionUtils { } } - fun assertPartialOrderIsTheSame(expected: Iterable, actual: Iterable, message: ((T) -> String)? = null) { + fun assertPartialOrderIsTheSame( + expected: Iterable, + actual: Iterable, + message: ((T) -> String)? = null, + ) { return assertPartialOrderIsTheSame( expected.iterator(), actual.iterator(), - message + message, ) } - fun assertPartialOrderIsTheSame(expected: Sequence, actual: Sequence, message: ((T) -> String)? = null) { + fun assertPartialOrderIsTheSame( + expected: Sequence, + actual: Sequence, + message: ((T) -> String)? = null, + ) { return assertPartialOrderIsTheSame( expected.iterator(), actual.iterator(), - message + message, ) } - fun assertSubMultisetOf(expected: MutableList, actual: MutableList, message: ((T) -> String)? = null) { + fun assertSubMultisetOf( + expected: MutableList, + actual: MutableList, + message: ((T) -> String)? = null, + ) { val i = expected.listIterator() while (i.hasNext()) { val e = i.next() @@ -116,23 +156,35 @@ internal object ReteTreeAssertionUtils { } } - fun assertSubMultisetOf(expected: Sequence, actual: Sequence, message: ((T) -> String)? = null) { + fun assertSubMultisetOf( + expected: Sequence, + actual: Sequence, + message: ((T) -> String)? = null, + ) { return assertSubMultisetOf( expected.toMutableList(), actual.toMutableList(), - message + message, ) } - fun assertSubMultisetOf(expected: Iterable, actual: Iterable, message: ((T) -> String)? = null) { + fun assertSubMultisetOf( + expected: Iterable, + actual: Iterable, + message: ((T) -> String)? = null, + ) { return assertSubMultisetOf( expected.toMutableList(), actual.toMutableList(), - message + message, ) } - fun assertNotContainedIn(contained: KtList, container: KtList, message: ((T) -> String)? = null) { + fun assertNotContainedIn( + contained: KtList, + container: KtList, + message: ((T) -> String)? = null, + ) { for (clause in contained) { if (container.any { it == clause }) { fail(message?.invoke(clause) ?: "Item $clause is already present") @@ -140,19 +192,27 @@ internal object ReteTreeAssertionUtils { } } - fun assertNotContainedIn(contained: Sequence, container: Sequence, message: ((T) -> String)? = null) { + fun assertNotContainedIn( + contained: Sequence, + container: Sequence, + message: ((T) -> String)? = null, + ) { return assertNotContainedIn( contained.toList(), container.toList(), - message + message, ) } - fun assertNotContainedIn(contained: Iterable, container: Iterable, message: ((T) -> String)? = null) { + fun assertNotContainedIn( + contained: Iterable, + container: Iterable, + message: ((T) -> String)? = null, + ) { return assertNotContainedIn( contained.toList(), container.toList(), - message + message, ) } @@ -169,7 +229,7 @@ internal object ReteTreeAssertionUtils { fun assertIsEmpty(tree: ReteTree) { assertItemsAreEquals( emptySequence(), - tree.clauses + tree.clauses, ) assertEquals(0, tree.size) } @@ -180,32 +240,39 @@ internal object ReteTreeAssertionUtils { assertEquals(tree.size, tree.clauses.count()) } - fun assertMatches(expected: Term, actual: Term) { + fun assertMatches( + expected: Term, + actual: Term, + ) { assertTrue("$actual should match $expected") { expected matches actual } } - fun assertDoesNotMatch(expected: Term, actual: Term) { + fun assertDoesNotMatch( + expected: Term, + actual: Term, + ) { assertFalse("$actual should not match $expected") { expected matches actual } } - private fun Struct.addArguments(term: Term, vararg terms: Term): Struct = - Struct.of(functor, *args.toTypedArray(), term, *terms) + private fun Struct.addArguments( + term: Term, + vararg terms: Term, + ): Struct = Struct.of(functor, *args.toTypedArray(), term, *terms) - private fun Struct.addArguments(terms: Iterable): Struct = - Struct.of(functor, args + terms) + private fun Struct.addArguments(terms: Iterable): Struct = Struct.of(functor, args + terms) - private fun Fact.addArguments(term: Term, vararg terms: Term): Fact = - Fact.of(head.addArguments(term, *terms)) + private fun Fact.addArguments( + term: Term, + vararg terms: Term, + ): Fact = Fact.of(head.addArguments(term, *terms)) - private fun Fact.addArguments(terms: Iterable): Fact = - Fact.of(head.addArguments(terms)) + private fun Fact.addArguments(terms: Iterable): Fact = Fact.of(head.addArguments(terms)) - private fun Fact.addBody(term: Term): Rule = - Rule.of(head, term) + private fun Fact.addBody(term: Term): Rule = Rule.of(head, term) private fun KtList.addArgumentsRandomlyFrom(args: KtList): KtList { return zip(args.shuffled()).map { (f, a) -> f.addArguments(a) } @@ -225,42 +292,47 @@ internal object ReteTreeAssertionUtils { } } - private val moreArguments = listOf( - Atom.of("a"), - Integer.of(2), - Real.of(3.4), - Var.of("Five"), - Struct.of("six", Atom.of("seven"), Integer.of(8), Real.of(9.10), Var.of("Eleven")) - ) - - val simpleFacts = listOf("a", "b", "c", "d") - .map(Atom.Companion::of) - .map(Fact.Companion::of) - - val f1Facts = listOf( - Struct.of("f", Integer.of(1)), - Struct.of("f", Integer.of(2)), - Struct.of("f", Integer.of(3)), - Struct.of("f", Integer.of(4)), - Struct.of("f", Real.of(1.0)), - Struct.of("f", Real.of(2.0)), - Struct.of("f", Real.of(3.0)), - Struct.of("f", Real.of(4.0)) - ).map(Fact.Companion::of) - - val g1Facts = listOf( - Struct.of("g", Atom.of("a")), - Struct.of("g", Atom.of("b")), - Struct.of("g", Atom.of("c")), - Struct.of("g", Atom.of("d")) - ).map(Fact.Companion::of) - - val h1Facts = listOf( - Struct.of("h", Var.of("A")), - Struct.of("h", Var.of("B")), - Struct.of("h", Var.of("C")), - Struct.of("h", Var.of("D")) - ).map(Fact.Companion::of) + private val moreArguments = + listOf( + Atom.of("a"), + Integer.of(2), + Real.of(3.4), + Var.of("Five"), + Struct.of("six", Atom.of("seven"), Integer.of(8), Real.of(9.10), Var.of("Eleven")), + ) + + val simpleFacts = + listOf("a", "b", "c", "d") + .map(Atom.Companion::of) + .map(Fact.Companion::of) + + val f1Facts = + listOf( + Struct.of("f", Integer.of(1)), + Struct.of("f", Integer.of(2)), + Struct.of("f", Integer.of(3)), + Struct.of("f", Integer.of(4)), + Struct.of("f", Real.of(1.0)), + Struct.of("f", Real.of(2.0)), + Struct.of("f", Real.of(3.0)), + Struct.of("f", Real.of(4.0)), + ).map(Fact.Companion::of) + + val g1Facts = + listOf( + Struct.of("g", Atom.of("a")), + Struct.of("g", Atom.of("b")), + Struct.of("g", Atom.of("c")), + Struct.of("g", Atom.of("d")), + ).map(Fact.Companion::of) + + val h1Facts = + listOf( + Struct.of("h", Var.of("A")), + Struct.of("h", Var.of("B")), + Struct.of("h", Var.of("C")), + Struct.of("h", Var.of("D")), + ).map(Fact.Companion::of) val i1Facts = f1Facts.map { Fact.of(Struct.of("i", it.head)) } @@ -290,84 +362,88 @@ internal object ReteTreeAssertionUtils { val o2Facts = o1Facts.addArgumentsRandomlyFrom(moreArguments) - val higherArityFacts = interleaveSequences( - sequenceOf(f2Facts, g2Facts, h2Facts, i2Facts, l2Facts, m2Facts, n2Facts, o2Facts) - .flatMap { it.asSequence() } - .map { fact -> - moreArguments.subsequences().map { fact.addArguments(it.toList()) } - } - ).toList() - - val otherFacts = listOf( - Truth.TRUE, - Truth.FAIL, - Truth.FALSE, - Empty.block(), - Empty.list(), - Atom.of("!"), - Atom.of("1"), - Atom.of(""), - Atom.of("a b c"), - Atom.of("A"), - LogicList.of(Atom.of("a")), - LogicList.of(Atom.of("a"), Atom.of("b")), - LogicList.of(Atom.of("a"), Atom.of("b"), Atom.of("c")), - LogicList.from(Atom.of("a"), last = Var.anonymous()), - LogicList.from(Atom.of("a"), Atom.of("b"), last = Var.anonymous()), - LogicList.from(Atom.of("a"), Atom.of("b"), Atom.of("c"), last = Var.anonymous()), - Tuple.of(Atom.of("a"), Atom.of("b")), - Tuple.of(Atom.of("a"), Atom.of("b"), Atom.of("c")), - Block.of(Atom.of("a")), - Block.of(Atom.of("a"), Atom.of("b")), - Block.of(Atom.of("a"), Atom.of("b"), Atom.of("c")) - ).map(Fact.Companion::of) - - val facts = interleave( - simpleFacts, - f1Facts, - g1Facts, - h1Facts, - i1Facts, - j1Facts, - l1Facts, - m1Facts, - n1Facts, - o1Facts, - f2Facts, - g2Facts, - h2Facts, - i2Facts, - l2Facts, - m2Facts, - n2Facts, - o2Facts, - otherFacts, - higherArityFacts - ).toList() - - val factFamilies = mapOf( - Fact.template("a", 0) to facts.filter { it.head.functor == "a" && it.head.arity == 0 }, - Fact.template("b", 0) to facts.filter { it.head.functor == "b" && it.head.arity == 0 }, - Fact.template("c", 0) to facts.filter { it.head.functor == "c" && it.head.arity == 0 }, - Fact.template("d", 0) to facts.filter { it.head.functor == "d" && it.head.arity == 0 }, - Fact.template("f", 1) to facts.filter { it.head.functor == "f" && it.head.arity == 1 }, - Fact.template("g", 1) to facts.filter { it.head.functor == "g" && it.head.arity == 1 }, - Fact.template("h", 1) to facts.filter { it.head.functor == "h" && it.head.arity == 1 }, - Fact.template("i", 1) to facts.filter { it.head.functor == "i" && it.head.arity == 1 }, - Fact.template("j", 1) to facts.filter { it.head.functor == "j" && it.head.arity == 1 }, - Fact.template("l", 1) to facts.filter { it.head.functor == "l" && it.head.arity == 1 }, - Fact.template("m", 1) to facts.filter { it.head.functor == "m" && it.head.arity == 1 }, - Fact.template("n", 1) to facts.filter { it.head.functor == "n" && it.head.arity == 1 }, - Fact.template("o", 1) to facts.filter { it.head.functor == "o" && it.head.arity == 1 }, - Fact.template("f", 2) to facts.filter { it.head.functor == "f" && it.head.arity == 2 }, - Fact.template("g", 2) to facts.filter { it.head.functor == "g" && it.head.arity == 2 }, - Fact.template("h", 2) to facts.filter { it.head.functor == "h" && it.head.arity == 2 }, - Fact.template("i", 2) to facts.filter { it.head.functor == "i" && it.head.arity == 2 }, - Fact.template("l", 2) to facts.filter { it.head.functor == "l" && it.head.arity == 2 }, - Fact.template("m", 2) to facts.filter { it.head.functor == "m" && it.head.arity == 2 }, - Fact.template("n", 2) to facts.filter { it.head.functor == "n" && it.head.arity == 2 }, - Fact.template("o", 2) to facts.filter { it.head.functor == "o" && it.head.arity == 2 } - ) + val higherArityFacts = + interleaveSequences( + sequenceOf(f2Facts, g2Facts, h2Facts, i2Facts, l2Facts, m2Facts, n2Facts, o2Facts) + .flatMap { it.asSequence() } + .map { fact -> + moreArguments.subsequences().map { fact.addArguments(it.toList()) } + }, + ).toList() + + val otherFacts = + listOf( + Truth.TRUE, + Truth.FAIL, + Truth.FALSE, + Empty.block(), + Empty.list(), + Atom.of("!"), + Atom.of("1"), + Atom.of(""), + Atom.of("a b c"), + Atom.of("A"), + LogicList.of(Atom.of("a")), + LogicList.of(Atom.of("a"), Atom.of("b")), + LogicList.of(Atom.of("a"), Atom.of("b"), Atom.of("c")), + LogicList.from(Atom.of("a"), last = Var.anonymous()), + LogicList.from(Atom.of("a"), Atom.of("b"), last = Var.anonymous()), + LogicList.from(Atom.of("a"), Atom.of("b"), Atom.of("c"), last = Var.anonymous()), + Tuple.of(Atom.of("a"), Atom.of("b")), + Tuple.of(Atom.of("a"), Atom.of("b"), Atom.of("c")), + Block.of(Atom.of("a")), + Block.of(Atom.of("a"), Atom.of("b")), + Block.of(Atom.of("a"), Atom.of("b"), Atom.of("c")), + ).map(Fact.Companion::of) + + val facts = + interleave( + simpleFacts, + f1Facts, + g1Facts, + h1Facts, + i1Facts, + j1Facts, + l1Facts, + m1Facts, + n1Facts, + o1Facts, + f2Facts, + g2Facts, + h2Facts, + i2Facts, + l2Facts, + m2Facts, + n2Facts, + o2Facts, + otherFacts, + higherArityFacts, + ).toList() + + val factFamilies = + mapOf( + Fact.template("a", 0) to facts.filter { it.head.functor == "a" && it.head.arity == 0 }, + Fact.template("b", 0) to facts.filter { it.head.functor == "b" && it.head.arity == 0 }, + Fact.template("c", 0) to facts.filter { it.head.functor == "c" && it.head.arity == 0 }, + Fact.template("d", 0) to facts.filter { it.head.functor == "d" && it.head.arity == 0 }, + Fact.template("f", 1) to facts.filter { it.head.functor == "f" && it.head.arity == 1 }, + Fact.template("g", 1) to facts.filter { it.head.functor == "g" && it.head.arity == 1 }, + Fact.template("h", 1) to facts.filter { it.head.functor == "h" && it.head.arity == 1 }, + Fact.template("i", 1) to facts.filter { it.head.functor == "i" && it.head.arity == 1 }, + Fact.template("j", 1) to facts.filter { it.head.functor == "j" && it.head.arity == 1 }, + Fact.template("l", 1) to facts.filter { it.head.functor == "l" && it.head.arity == 1 }, + Fact.template("m", 1) to facts.filter { it.head.functor == "m" && it.head.arity == 1 }, + Fact.template("n", 1) to facts.filter { it.head.functor == "n" && it.head.arity == 1 }, + Fact.template("o", 1) to facts.filter { it.head.functor == "o" && it.head.arity == 1 }, + Fact.template("f", 2) to facts.filter { it.head.functor == "f" && it.head.arity == 2 }, + Fact.template("g", 2) to facts.filter { it.head.functor == "g" && it.head.arity == 2 }, + Fact.template("h", 2) to facts.filter { it.head.functor == "h" && it.head.arity == 2 }, + Fact.template("i", 2) to facts.filter { it.head.functor == "i" && it.head.arity == 2 }, + Fact.template("l", 2) to facts.filter { it.head.functor == "l" && it.head.arity == 2 }, + Fact.template("m", 2) to facts.filter { it.head.functor == "m" && it.head.arity == 2 }, + Fact.template("n", 2) to facts.filter { it.head.functor == "n" && it.head.arity == 2 }, + Fact.template("o", 2) to facts.filter { it.head.functor == "o" && it.head.arity == 2 }, + ) val simpleRules = simpleFacts.addBodyFrom(moreArguments) @@ -399,56 +475,58 @@ internal object ReteTreeAssertionUtils { val higherArityRules = higherArityFacts.addBodyFrom(moreArguments) - val rules = interleave( - simpleRules, - a0Rules, - b0Rules, - c0Rules, - d0Rules, - f1Rules, - g1Rules, - h1Rules, - i1Rules, - j1Rules, - l1Rules, - m1Rules, - n1Rules, - o1Rules, - f2Rules, - g2Rules, - h2Rules, - i2Rules, - l2Rules, - m2Rules, - n2Rules, - o2Rules, - otherRules, - higherArityRules - ).toList() - - val ruleFamilies = mapOf( - Rule.template("a", 0) to rules.filter { it.head.functor == "a" && it.head.arity == 0 }, - Rule.template("b", 0) to rules.filter { it.head.functor == "b" && it.head.arity == 0 }, - Rule.template("c", 0) to rules.filter { it.head.functor == "c" && it.head.arity == 0 }, - Rule.template("d", 0) to rules.filter { it.head.functor == "d" && it.head.arity == 0 }, - Rule.template("f", 1) to rules.filter { it.head.functor == "f" && it.head.arity == 1 }, - Rule.template("g", 1) to rules.filter { it.head.functor == "g" && it.head.arity == 1 }, - Rule.template("h", 1) to rules.filter { it.head.functor == "h" && it.head.arity == 1 }, - Rule.template("i", 1) to rules.filter { it.head.functor == "i" && it.head.arity == 1 }, - Rule.template("j", 1) to rules.filter { it.head.functor == "j" && it.head.arity == 1 }, - Rule.template("l", 1) to rules.filter { it.head.functor == "l" && it.head.arity == 1 }, - Rule.template("m", 1) to rules.filter { it.head.functor == "m" && it.head.arity == 1 }, - Rule.template("n", 1) to rules.filter { it.head.functor == "n" && it.head.arity == 1 }, - Rule.template("o", 1) to rules.filter { it.head.functor == "o" && it.head.arity == 1 }, - Rule.template("f", 2) to rules.filter { it.head.functor == "f" && it.head.arity == 2 }, - Rule.template("g", 2) to rules.filter { it.head.functor == "g" && it.head.arity == 2 }, - Rule.template("h", 2) to rules.filter { it.head.functor == "h" && it.head.arity == 2 }, - Rule.template("i", 2) to rules.filter { it.head.functor == "i" && it.head.arity == 2 }, - Rule.template("l", 2) to rules.filter { it.head.functor == "l" && it.head.arity == 2 }, - Rule.template("m", 2) to rules.filter { it.head.functor == "m" && it.head.arity == 2 }, - Rule.template("n", 2) to rules.filter { it.head.functor == "n" && it.head.arity == 2 }, - Rule.template("o", 2) to rules.filter { it.head.functor == "o" && it.head.arity == 2 } - ) + val rules = + interleave( + simpleRules, + a0Rules, + b0Rules, + c0Rules, + d0Rules, + f1Rules, + g1Rules, + h1Rules, + i1Rules, + j1Rules, + l1Rules, + m1Rules, + n1Rules, + o1Rules, + f2Rules, + g2Rules, + h2Rules, + i2Rules, + l2Rules, + m2Rules, + n2Rules, + o2Rules, + otherRules, + higherArityRules, + ).toList() + + val ruleFamilies = + mapOf( + Rule.template("a", 0) to rules.filter { it.head.functor == "a" && it.head.arity == 0 }, + Rule.template("b", 0) to rules.filter { it.head.functor == "b" && it.head.arity == 0 }, + Rule.template("c", 0) to rules.filter { it.head.functor == "c" && it.head.arity == 0 }, + Rule.template("d", 0) to rules.filter { it.head.functor == "d" && it.head.arity == 0 }, + Rule.template("f", 1) to rules.filter { it.head.functor == "f" && it.head.arity == 1 }, + Rule.template("g", 1) to rules.filter { it.head.functor == "g" && it.head.arity == 1 }, + Rule.template("h", 1) to rules.filter { it.head.functor == "h" && it.head.arity == 1 }, + Rule.template("i", 1) to rules.filter { it.head.functor == "i" && it.head.arity == 1 }, + Rule.template("j", 1) to rules.filter { it.head.functor == "j" && it.head.arity == 1 }, + Rule.template("l", 1) to rules.filter { it.head.functor == "l" && it.head.arity == 1 }, + Rule.template("m", 1) to rules.filter { it.head.functor == "m" && it.head.arity == 1 }, + Rule.template("n", 1) to rules.filter { it.head.functor == "n" && it.head.arity == 1 }, + Rule.template("o", 1) to rules.filter { it.head.functor == "o" && it.head.arity == 1 }, + Rule.template("f", 2) to rules.filter { it.head.functor == "f" && it.head.arity == 2 }, + Rule.template("g", 2) to rules.filter { it.head.functor == "g" && it.head.arity == 2 }, + Rule.template("h", 2) to rules.filter { it.head.functor == "h" && it.head.arity == 2 }, + Rule.template("i", 2) to rules.filter { it.head.functor == "i" && it.head.arity == 2 }, + Rule.template("l", 2) to rules.filter { it.head.functor == "l" && it.head.arity == 2 }, + Rule.template("m", 2) to rules.filter { it.head.functor == "m" && it.head.arity == 2 }, + Rule.template("n", 2) to rules.filter { it.head.functor == "n" && it.head.arity == 2 }, + Rule.template("o", 2) to rules.filter { it.head.functor == "o" && it.head.arity == 2 }, + ) val directives = listOf( @@ -468,7 +546,7 @@ internal object ReteTreeAssertionUtils { Directive.of(Struct.of("a", Atom.of("a")), Empty.block()), Directive.of(Struct.of("a", Atom.of("a")), Struct.of("other", Var.anonymous())), Directive.of(Struct.of("a", Atom.of("a")), Struct.of("a", Var.anonymous())), - Directive.of(Struct.of("a", Atom.of("a")), Var.anonymous()) + Directive.of(Struct.of("a", Atom.of("a")), Var.anonymous()), ) val defaultClauses = interleave(facts + rules, directives).toList() @@ -497,27 +575,28 @@ internal object ReteTreeAssertionUtils { val n2FactsAndRules = factsAndRules.filter { it.head.functor == "n" && it.head.arity == 2 } val o2FactsAndRules = factsAndRules.filter { it.head.functor == "o" && it.head.arity == 2 } - val factsAndRulesFamilies = mapOf( - Rule.template("a", 0) to a0FactsAndRules, - Rule.template("b", 0) to b0FactsAndRules, - Rule.template("c", 0) to c0FactsAndRules, - Rule.template("d", 0) to d0FactsAndRules, - Rule.template("f", 1) to f1FactsAndRules, - Rule.template("g", 1) to g1FactsAndRules, - Rule.template("h", 1) to h1FactsAndRules, - Rule.template("i", 1) to i1FactsAndRules, - Rule.template("j", 1) to j1FactsAndRules, - Rule.template("l", 1) to l1FactsAndRules, - Rule.template("m", 1) to m1FactsAndRules, - Rule.template("n", 1) to n1FactsAndRules, - Rule.template("o", 1) to o1FactsAndRules, - Rule.template("f", 2) to f2FactsAndRules, - Rule.template("g", 2) to g2FactsAndRules, - Rule.template("h", 2) to h2FactsAndRules, - Rule.template("i", 2) to i2FactsAndRules, - Rule.template("l", 2) to l2FactsAndRules, - Rule.template("m", 2) to m2FactsAndRules, - Rule.template("n", 2) to n2FactsAndRules, - Rule.template("o", 2) to o2FactsAndRules - ) + val factsAndRulesFamilies = + mapOf( + Rule.template("a", 0) to a0FactsAndRules, + Rule.template("b", 0) to b0FactsAndRules, + Rule.template("c", 0) to c0FactsAndRules, + Rule.template("d", 0) to d0FactsAndRules, + Rule.template("f", 1) to f1FactsAndRules, + Rule.template("g", 1) to g1FactsAndRules, + Rule.template("h", 1) to h1FactsAndRules, + Rule.template("i", 1) to i1FactsAndRules, + Rule.template("j", 1) to j1FactsAndRules, + Rule.template("l", 1) to l1FactsAndRules, + Rule.template("m", 1) to m1FactsAndRules, + Rule.template("n", 1) to n1FactsAndRules, + Rule.template("o", 1) to o1FactsAndRules, + Rule.template("f", 2) to f2FactsAndRules, + Rule.template("g", 2) to g2FactsAndRules, + Rule.template("h", 2) to h2FactsAndRules, + Rule.template("i", 2) to i2FactsAndRules, + Rule.template("l", 2) to l2FactsAndRules, + Rule.template("m", 2) to m2FactsAndRules, + Rule.template("n", 2) to n2FactsAndRules, + Rule.template("o", 2) to o2FactsAndRules, + ) } diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/custom/UnorderedReteTreeTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/custom/UnorderedReteTreeTest.kt index 9e9511d95..bdd45c338 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/custom/UnorderedReteTreeTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/custom/UnorderedReteTreeTest.kt @@ -22,13 +22,10 @@ import kotlin.test.assertEquals import kotlin.test.assertTrue class UnorderedReteTreeTest { - companion object { - private fun reteTreeOf(vararg clauses: Clause): ReteTree = - ReteTree.unordered(Unificator.default, *clauses) + private fun reteTreeOf(vararg clauses: Clause): ReteTree = ReteTree.unordered(Unificator.default, *clauses) - private fun reteTreeOf(clauses: Iterable): ReteTree = - ReteTree.unordered(Unificator.default, clauses) + private fun reteTreeOf(clauses: Iterable): ReteTree = ReteTree.unordered(Unificator.default, clauses) } @Test @@ -445,11 +442,12 @@ class UnorderedReteTreeTest { @Test fun anUnorderedTreeFiltersClausesByBodyAsWell() { - val groundTerms = defaultClauses.asSequence() - .filterIsInstance() - .flatMap { sequenceOf(it.head) + it.head.argsSequence } - .filter { it.isGround } - .toSet() + val groundTerms = + defaultClauses.asSequence() + .filterIsInstance() + .flatMap { sequenceOf(it.head) + it.head.argsSequence } + .filter { it.isGround } + .toSet() val families = defaultClauses.filterIsInstance().map { it.head.functor to it.head.arity }.toSet() for ((functor, arity) in families) { @@ -514,15 +512,17 @@ class UnorderedReteTreeTest { @Test fun nonGroundClausesAreMatchedByGroundQueries() { - val groundTerms = defaultClauses.asSequence() - .filterIsInstance() - .flatMap { sequenceOf(it.head) + it.head.argsSequence } - .filter { it.isGround } - .toSet() - val families = defaultClauses.filterIsInstance() - .map { it.head.functor to it.head.arity } - .filter { (_, arity) -> arity > 0 } - .toSet() + val groundTerms = + defaultClauses.asSequence() + .filterIsInstance() + .flatMap { sequenceOf(it.head) + it.head.argsSequence } + .filter { it.isGround } + .toSet() + val families = + defaultClauses.filterIsInstance() + .map { it.head.functor to it.head.arity } + .filter { (_, arity) -> arity > 0 } + .toSet() for ((functor, arity) in families) { for (args in groundTerms.allChunksOfSize(arity)) { diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/ArgNodeTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/ArgNodeTest.kt index 6dbad55fa..01ffcf8d9 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/ArgNodeTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/ArgNodeTest.kt @@ -22,7 +22,6 @@ import kotlin.test.assertFailsWith * @author Enrico */ internal class ArgNodeTest { - private val aAtom = Atom.of("a") private val bAtom = Atom.of("b") @@ -57,12 +56,13 @@ internal class ArgNodeTest { twoIndexEmptyArgNodes = listOf(argNodeTwoIndexAndAAtom, argNodeTwoIndexAndBAtom) allEmptyArgNodes = zeroIndexEmptyArgNodes + twoIndexEmptyArgNodes - allFilledArgNodes = listOf( - ArgNode(0, aAtom), - ArgNode(0, bAtom), - ArgNode(2, aAtom), - ArgNode(2, bAtom) - ).map { argNode -> argNode.apply { aAtomRules.forEach { put(it) } } } + allFilledArgNodes = + listOf( + ArgNode(0, aAtom), + ArgNode(0, bAtom), + ArgNode(2, aAtom), + ArgNode(2, bAtom), + ).map { argNode -> argNode.apply { aAtomRules.forEach { put(it) } } } } @Test @@ -70,7 +70,7 @@ internal class ArgNodeTest { assertFailsWith { ArgNode( -1, - Atom.of("a") + Atom.of("a"), ) } } @@ -103,10 +103,10 @@ internal class ArgNodeTest { assertEquals( RuleNode( mutableListOf( - noArgsHeadedRule - ) + noArgsHeadedRule, + ), ), - it.children[null] + it.children[null], ) } } @@ -146,10 +146,11 @@ internal class ArgNodeTest { @Test fun putClauseForwardsCorrectlyTheBeforeFlagToChildren() { zeroIndexEmptyArgNodes.forEach { - val clauses = listOf( - Fact.of(Struct.of("f", aAtom, Var.of("A"))), - Fact.of(Struct.of("f", aAtom, Var.anonymous())) - ) + val clauses = + listOf( + Fact.of(Struct.of("f", aAtom, Var.of("A"))), + Fact.of(Struct.of("f", aAtom, Var.anonymous())), + ) it.run { clauses.forEach { clause -> put(clause, true) } } diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/ArityNodeTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/ArityNodeTest.kt index c553fb25e..2f20403a0 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/ArityNodeTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/ArityNodeTest.kt @@ -27,7 +27,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class ArityNodeTest { - private lateinit var emptyArityNodes: Iterable private lateinit var filledArityNodes: Iterable @@ -36,16 +35,17 @@ internal class ArityNodeTest { @BeforeTest fun init() { emptyArityNodes = (0..3).map { ArityNode(it) } - filledArityNodes = (0..3).map { arity -> - ArityNode(arity).apply { ReteNodeUtils.rules.forEach { put(it) } } - } + filledArityNodes = + (0..3).map { arity -> + ArityNode(arity).apply { ReteNodeUtils.rules.forEach { put(it) } } + } } @Test fun arityNodeCannotAcceptNegativeArityUponConstruction() { assertFailsWith { ArityNode( - -1 + -1, ) } } diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/DirectiveNodeTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/DirectiveNodeTest.kt index b562ed2e1..1a426fdfe 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/DirectiveNodeTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/DirectiveNodeTest.kt @@ -21,7 +21,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class DirectiveNodeTest { - private lateinit var emptyDirectiveNode: DirectiveNode private lateinit var filledDirectiveNode: DirectiveNode diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/FunctorNodeTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/FunctorNodeTest.kt index a83a2736d..5e6295492 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/FunctorNodeTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/FunctorNodeTest.kt @@ -23,7 +23,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class FunctorNodeTest { - private lateinit var emptyAFunctorNode: FunctorNode private lateinit var filledAFunctorNode: FunctorNode @@ -78,7 +77,7 @@ internal class FunctorNodeTest { assertCorrectAndPartialOrderRespected( filledAFunctorNode, - ReteNodeUtils.aFunctorRules.toMutableList().apply { add(0, aRule) } + ReteNodeUtils.aFunctorRules.toMutableList().apply { add(0, aRule) }, ) } diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/NoArgsNodeTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/NoArgsNodeTest.kt index cfd11692c..863587145 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/NoArgsNodeTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/NoArgsNodeTest.kt @@ -22,7 +22,6 @@ import kotlin.test.assertSame * @author Enrico */ internal class NoArgsNodeTest { - private lateinit var emptyNoArgsNode: NoArgsNode private lateinit var filledNoArgsNode: NoArgsNode diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/RootNodeTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/RootNodeTest.kt index 17733395d..ed57769ac 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/RootNodeTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/RootNodeTest.kt @@ -25,7 +25,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class RootNodeTest { - private lateinit var emptyRootNode: RootNode private lateinit var filledRootNode: RootNode @@ -36,13 +35,14 @@ internal class RootNodeTest { listOf( ReteNodeUtils.rules, ReteNodeUtils.directives, - ReteNodeUtils.mixedClauses + ReteNodeUtils.mixedClauses, ) } - private val correctInstances = reteTreeTestContents.map { clauses -> - RootNode().apply { clauses.forEach { put(it) } } - } + private val correctInstances = + reteTreeTestContents.map { clauses -> + RootNode().apply { clauses.forEach { put(it) } } + } @BeforeTest fun init() { @@ -90,7 +90,7 @@ internal class RootNodeTest { filledRootNode, ReteNodeUtils.mixedClauses.toMutableList().apply { addAll(0, listOf(aRule, aDirective)) - } + }, ) } diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/RuleNodeTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/RuleNodeTest.kt index bbf189668..989254964 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/RuleNodeTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/collections/rete/nodes/set/RuleNodeTest.kt @@ -21,7 +21,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class RuleNodeTest { - private lateinit var emptyRuleNode: RuleNode private lateinit var filledRuleNode: RuleNode diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/testutils/ClauseAssertionUtils.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/testutils/ClauseAssertionUtils.kt index 8474e41ee..c28b8c049 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/testutils/ClauseAssertionUtils.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/testutils/ClauseAssertionUtils.kt @@ -8,12 +8,17 @@ import it.unibo.tuprolog.core.Var import kotlin.test.assertEquals internal object ClauseAssertionUtils { - - fun assertClausesHaveSameLengthAndContent(a: Sequence, b: Sequence) { + fun assertClausesHaveSameLengthAndContent( + a: Sequence, + b: Sequence, + ) { return assertClausesHaveSameLengthAndContent(a.asIterable(), b.asIterable()) } - fun assertClausesHaveSameLengthAndContent(a: Iterable, b: Iterable) { + fun assertClausesHaveSameLengthAndContent( + a: Iterable, + b: Iterable, + ) { val i = a.iterator() val j = b.iterator() @@ -24,19 +29,22 @@ internal object ClauseAssertionUtils { assertEquals(i.hasNext(), j.hasNext()) } - fun assertTermsAreEqual(expected: Term, actual: Term) { + fun assertTermsAreEqual( + expected: Term, + actual: Term, + ) { assertEquals(expected.isGround, actual.isGround) if (expected.isGround) { assertEquals( expected, actual, message = - """Comparing: + """Comparing: | actual: $actual | type: ${actual::class} | expected: $expected | type: ${expected::class} - """.trimMargin() + """.trimMargin(), ) } else { when { @@ -56,7 +64,7 @@ internal object ClauseAssertionUtils { } assertEquals( expected.variables.toSet().size, - actual.variables.toSet().size + actual.variables.toSet().size, ) } } diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/testutils/ReteNodeUtils.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/testutils/ReteNodeUtils.kt index 6edbbb182..da4eaf65c 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/testutils/ReteNodeUtils.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/testutils/ReteNodeUtils.kt @@ -24,29 +24,29 @@ import kotlin.test.fail * @author Enrico */ internal object ReteNodeUtils { - /** Contains some well-formed rules */ - internal val rules = listOf( - Fact.of(Truth.TRUE), - Fact.of(Truth.FAIL), - Fact.of(Atom.of("a")), - Fact.of(Atom.of("other")), - Fact.of(Struct.of("a", Atom.of("other"))), - Fact.of(Struct.of("other", Integer.of(1))), - Fact.of(Tuple.of(Var.of("A"), Var.of("B"))), - Rule.of(Atom.of("a"), Atom.of("other")), - Rule.of(Tuple.of(Var.of("A"), Var.of("B")), Atom.of("a")), - Rule.of(Struct.of("a", Atom.of("other")), Atom.of("a")), - Rule.of(Struct.of("f", Atom.of("a"), Struct.of("b", Var.of("X")), Atom.of("do_something_else"))), - Rule.of(Struct.of("a", Integer.of(22)), Var.anonymous()), - Rule.of(Struct.of("f", Atom.of("a")), Var.of("Variable")), - Rule.of(Struct.of("f", Atom.of("a")), Var.of("Variable")), - Rule.of(Struct.of("a", Var.anonymous()), Struct.of("b", Var.anonymous())), - Rule.of(Struct.of("a", Atom.of("a")), Empty.block()), - Rule.of(Struct.of("a", Atom.of("a")), Struct.of("other", Var.anonymous())), - Rule.of(Struct.of("a", Atom.of("a")), Struct.of("a", Var.anonymous())), - Rule.of(Struct.of("a", Atom.of("a")), Var.anonymous()) - ) + internal val rules = + listOf( + Fact.of(Truth.TRUE), + Fact.of(Truth.FAIL), + Fact.of(Atom.of("a")), + Fact.of(Atom.of("other")), + Fact.of(Struct.of("a", Atom.of("other"))), + Fact.of(Struct.of("other", Integer.of(1))), + Fact.of(Tuple.of(Var.of("A"), Var.of("B"))), + Rule.of(Atom.of("a"), Atom.of("other")), + Rule.of(Tuple.of(Var.of("A"), Var.of("B")), Atom.of("a")), + Rule.of(Struct.of("a", Atom.of("other")), Atom.of("a")), + Rule.of(Struct.of("f", Atom.of("a"), Struct.of("b", Var.of("X")), Atom.of("do_something_else"))), + Rule.of(Struct.of("a", Integer.of(22)), Var.anonymous()), + Rule.of(Struct.of("f", Atom.of("a")), Var.of("Variable")), + Rule.of(Struct.of("f", Atom.of("a")), Var.of("Variable")), + Rule.of(Struct.of("a", Var.anonymous()), Struct.of("b", Var.anonymous())), + Rule.of(Struct.of("a", Atom.of("a")), Empty.block()), + Rule.of(Struct.of("a", Atom.of("a")), Struct.of("other", Var.anonymous())), + Rule.of(Struct.of("a", Atom.of("a")), Struct.of("a", Var.anonymous())), + Rule.of(Struct.of("a", Atom.of("a")), Var.anonymous()), + ) /** Contains some well-formed rules with no args head */ internal val noArgHeadedRules = rules.filter { it.head.isAtom } @@ -71,7 +71,7 @@ internal object ReteNodeUtils { }, Rule.of(Struct.of("a", Var.anonymous()), Var.anonymous()).run { this to rules.filter { it matches this } - } + }, ) /** Contains a map of queries and results made excluding queries with non "a" functor from [rulesQueryResultsMap] */ @@ -96,7 +96,7 @@ internal object ReteNodeUtils { Directive.of(Struct.of("a", Atom.of("a")), Empty.block()), Directive.of(Struct.of("a", Atom.of("a")), Struct.of("other", Var.anonymous())), Directive.of(Struct.of("a", Atom.of("a")), Struct.of("a", Var.anonymous())), - Directive.of(Struct.of("a", Atom.of("a")), Var.anonymous()) + Directive.of(Struct.of("a", Atom.of("a")), Var.anonymous()), ) /** Contains a map of queries and results crafted watching [directives] collection (NOTE: any modifications must be reviewed by hand)*/ @@ -110,7 +110,7 @@ internal object ReteNodeUtils { }, Directive.of(Struct.of("a", Var.anonymous()), Struct.of("b", Var.anonymous())).run { this to directives.filter { it matches this } - } + }, ) /** Contains well-formed mixed [rules] and [directives] */ @@ -120,8 +120,10 @@ internal object ReteNodeUtils { internal val mixedClausesQueryResultsMap = rulesQueryResultsMap + directivesQueryResultsMap /** Asserts that rete node has correct elements count */ - internal fun assertReteNodeElementCount(reteNode: ReteNode<*, Clause>, expectedCount: Int) = - assertEquals(expectedCount, reteNode.indexedElements.count()) + internal fun assertReteNodeElementCount( + reteNode: ReteNode<*, Clause>, + expectedCount: Int, + ) = assertEquals(expectedCount, reteNode.indexedElements.count()) /** Asserts that rete node is empty */ internal fun assertReteNodeEmpty(reteNode: ReteNode<*, out Clause>) { @@ -130,13 +132,15 @@ internal object ReteNodeUtils { } /** Asserts that rete node clauses are the same as expected */ - internal fun assertReteNodeClausesCorrect(reteNode: ReteNode<*, out Clause>, expectedClauses: Iterable) = - assertEquals(expectedClauses.toList(), reteNode.indexedElements.toList()) + internal fun assertReteNodeClausesCorrect( + reteNode: ReteNode<*, out Clause>, + expectedClauses: Iterable, + ) = assertEquals(expectedClauses.toList(), reteNode.indexedElements.toList()) /** Asserts that calling [idempotentAction] onto [reteNode] results in no actual change */ internal inline fun assertNoChangesInReteNode( reteNode: ReteNode<*, out Clause>, - idempotentAction: ReteNode<*, Clause>.() -> Sequence + idempotentAction: ReteNode<*, Clause>.() -> Sequence, ) { val beforeContents = reteNode.indexedElements.toList() @@ -151,7 +155,7 @@ internal object ReteNodeUtils { internal inline fun assertRemovedFromReteNode( reteNode: ReteNode<*, out Clause>, removedExpected: Iterable, - removeAction: ReteNode<*, Clause>.() -> Sequence + removeAction: ReteNode<*, Clause>.() -> Sequence, ) { val allClauses = reteNode.indexedElements.asIterable() val allClauseCount = allClauses.count() @@ -171,7 +175,7 @@ internal object ReteNodeUtils { reteNode: ReteNode<*, out Clause>, toRemoveMatched: Iterable, removeLimit: Int = Int.MAX_VALUE, - removeAction: ReteNode<*, Clause>.() -> Sequence + removeAction: ReteNode<*, Clause>.() -> Sequence, ) { val allClauses = reteNode.indexedElements.asIterable() val allClauseCount = allClauses.count() @@ -184,23 +188,24 @@ internal object ReteNodeUtils { val removedActual = partialOrderingHeadClauseMap(removedActualSequence.asIterable()) val removeMatchExpected = partialOrderingHeadClauseMap(toRemoveMatched) - val checkerMap = removedActual.mapValues { - it.value.zip(removeMatchExpected[it.key] ?: emptyList()) - } + val checkerMap = + removedActual.mapValues { + it.value.zip(removeMatchExpected[it.key] ?: emptyList()) + } val (actualRemovedList, expectedRemovedList) = checkerMap.values.flatten().unzip() assertEquals(expectedRemovedList, actualRemovedList) assertClauseHeadPartialOrderingRespected( allClauses - expectedRemovedList, - reteNode.indexedElements.asIterable() + reteNode.indexedElements.asIterable(), ) } /** Asserts that [actualClauses] respect partial ordering (checking for Clauses head structural equality) imposed by [expectedClauses] iteration order */ internal fun assertClauseHeadPartialOrderingRespected( expectedClauses: Iterable, - actualClauses: Iterable + actualClauses: Iterable, ) { // assertEquals(expectedClauses.toList().sorted(), reteNode.indexedElements.toList().sorted()) TODO enable after solving issue #29 and delete two below assertions assertTrue("\nExpected:\t$expectedClauses\nActual:\t\t$actualClauses") { @@ -214,17 +219,20 @@ internal object ReteNodeUtils { when { entry.value.none() -> fail("Clause $clause not indexed under its head Struct") entry.value.first() == clause -> entry.setValue(entry.value - clause) - else -> fail("Partial ordering not respected: $clause should come after these ${entry.value - clause}") + else -> + fail( + "Partial ordering not respected: $clause should come after these ${entry.value - clause}", + ) } }, - onMissingEntry = { clause, _ -> fail("Clause $clause not expected among these: $expectedClauses") } + onMissingEntry = { clause, _ -> fail("Clause $clause not expected among these: $expectedClauses") }, ) } /** Asserts that ReteTree node respects partial ordering (checking for Clauses head structural equality) imposed by [expectedClauses] iteration order */ internal fun assertCorrectAndPartialOrderRespected( reteNode: ReteNode<*, out Clause>, - expectedClauses: Iterable + expectedClauses: Iterable, ) = assertClauseHeadPartialOrderingRespected(expectedClauses, reteNode.indexedElements.asIterable()) /** Creates a Map containing for each structurallyEquals Clause.head the clauses ordered (according to [clauses] iteration order), @@ -234,7 +242,7 @@ internal object ReteNodeUtils { clauses.forEachStructurallyEqualsHead( resultMap, onPresentEntry = { clause, entry -> entry.setValue(entry.value + clause) }, - onMissingEntry = { clause, map -> map[clause.head] = mutableListOf(clause) } + onMissingEntry = { clause, map -> map[clause.head] = mutableListOf(clause) }, ) }.toMap() @@ -242,7 +250,7 @@ internal object ReteNodeUtils { private inline fun Iterable.forEachStructurallyEqualsHead( partialOrderingMap: MutableMap>, onPresentEntry: (Clause, MutableMap.MutableEntry>) -> Unit, - onMissingEntry: (Clause, MutableMap>) -> Unit + onMissingEntry: (Clause, MutableMap>) -> Unit, ) { forEach { clause -> partialOrderingMap.entries.find { (clauseHead, _) -> diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/testutils/TheoryUtils.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/testutils/TheoryUtils.kt index 8c944f588..0bdd84596 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/testutils/TheoryUtils.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/testutils/TheoryUtils.kt @@ -21,15 +21,15 @@ import it.unibo.tuprolog.core.List as LogicList * @author Enrico */ internal object TheoryUtils { - /** Contains well formed clauses (the head is a [Struct] and the body doesn't contain [Numeric] values) */ internal val wellFormedClauses get() = ReteNodeUtils.mixedClauses /** Contains a pair which has in its first element half clauses from [wellFormedClauses] in the second element the other half */ - internal val wellFormedClausesHelves = Pair( - wellFormedClauses.subList(0, wellFormedClauses.count() / 2), - wellFormedClauses.subList(wellFormedClauses.count() / 2, wellFormedClauses.count()) - ) + internal val wellFormedClausesHelves = + Pair( + wellFormedClauses.subList(0, wellFormedClauses.count() / 2), + wellFormedClauses.subList(wellFormedClauses.count() / 2, wellFormedClauses.count()), + ) /** Contains well formed clauses queries based on [wellFormedClauses] and expected responses from the ClauseDatabase */ internal val clausesQueryResultsMap get() = ReteNodeUtils.mixedClausesQueryResultsMap @@ -49,52 +49,59 @@ internal object TheoryUtils { listOf( Clause.of(Struct.of("test", Var.anonymous()), Struct.of("b", Var.anonymous()), Integer.of(1)), Directive.of(Atom.of("execute_this"), Real.of(1.5)), - Rule.of(Struct.of("f2", Atom.of("a")), Atom.of("do_something"), Numeric.of(1.5f)) + Rule.of(Struct.of("f2", Atom.of("a")), Atom.of("do_something"), Numeric.of(1.5f)), ) - internal val memberClause = listOf( - Scope.empty { - factOf(structOf("member", varOf("H"), consOf(varOf("H"), anonymous()))) - } - ) + internal val memberClause = + listOf( + Scope.empty { + factOf(structOf("member", varOf("H"), consOf(varOf("H"), anonymous()))) + }, + ) - internal fun member(first: Term, second: Term): Fact = - Fact.of(Struct.of("member", first, second)) + internal fun member( + first: Term, + second: Term, + ): Fact = Fact.of(Struct.of("member", first, second)) - internal val positiveMemberQueries = listOf( - member( - LogicList.of(Struct.of("a", Var.of("X"))), - LogicList.of(LogicList.of(Struct.of("a", Integer.of(1)))) - ), - member(Atom.of("a"), LogicList.of(Atom.of("a"))) - ) + internal val positiveMemberQueries = + listOf( + member( + LogicList.of(Struct.of("a", Var.of("X"))), + LogicList.of(LogicList.of(Struct.of("a", Integer.of(1)))), + ), + member(Atom.of("a"), LogicList.of(Atom.of("a"))), + ) - internal val negativeMemberQueries = listOf( - member( - LogicList.of(Struct.of("a", Var.of("X"))), - LogicList.of(LogicList.of(Struct.of("b", Integer.of(1)))) - ), - member(Atom.of("a"), LogicList.of(Atom.of("b"))) - ) + internal val negativeMemberQueries = + listOf( + member( + LogicList.of(Struct.of("a", Var.of("X"))), + LogicList.of(LogicList.of(Struct.of("b", Integer.of(1)))), + ), + member(Atom.of("a"), LogicList.of(Atom.of("b"))), + ) - internal val deepClause = listOf( - Fact.of( - LogicList.of( + internal val deepClause = + listOf( + Fact.of( LogicList.of( LogicList.of( - Atom.of("a"), - Atom.of("b") + LogicList.of( + Atom.of("a"), + Atom.of("b"), + ), + Atom.of("c"), ), - Atom.of("c") + Atom.of("d"), ), - Atom.of("d") - ) + ), ) - ) - internal val deepQueries = sequenceOf( - LogicList.of(Var.of("ABC"), Var.of("D")), - LogicList.of(LogicList.of(Var.of("AB"), Var.of("C")), Var.of("D")), - LogicList.of(LogicList.of(LogicList.of(Var.of("A"), Var.of("B")), Var.of("C")), Var.of("D")) - ).map { Fact.of(it) }.toList() + internal val deepQueries = + sequenceOf( + LogicList.of(Var.of("ABC"), Var.of("D")), + LogicList.of(LogicList.of(Var.of("AB"), Var.of("C")), Var.of("D")), + LogicList.of(LogicList.of(LogicList.of(Var.of("A"), Var.of("B")), Var.of("C")), Var.of("D")), + ).map { Fact.of(it) }.toList() } diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/PrototypeProperIndexingTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/PrototypeProperIndexingTest.kt index 6b8e92c08..6073efae3 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/PrototypeProperIndexingTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/PrototypeProperIndexingTest.kt @@ -12,9 +12,8 @@ import it.unibo.tuprolog.testutils.ClauseAssertionUtils.assertTermsAreEqual import it.unibo.tuprolog.unify.Unificator.Companion.matches class PrototypeProperIndexingTest( - private val theoryGenerator: (Iterable) -> Theory + private val theoryGenerator: (Iterable) -> Theory, ) { - private val mixedClausesTheory = listOf( Fact.of(Struct.of("f", Atom.of("a"))), @@ -35,14 +34,14 @@ class PrototypeProperIndexingTest( Fact.of(Struct.of("g", Var.of("X"), Atom.of("a"))), Fact.of(Struct.of("g", Atom.of("a"), Var.of("X"))), Fact.of(Struct.of("g", Atom.of("b"), Atom.of("a"))), - Fact.of(Struct.of("g", Numeric.of(1))) + Fact.of(Struct.of("g", Numeric.of(1))), ) private data class FreshTheoryScope(val theory: Theory) private fun withFreshTheory( theory: Theory = theoryGenerator(mixedClausesTheory), - action: FreshTheoryScope.() -> R + action: FreshTheoryScope.() -> R, ): R = FreshTheoryScope(theory).action() private val expectedIndexingOverF1 = @@ -51,7 +50,7 @@ class PrototypeProperIndexingTest( Fact.of(Struct.of("f", Atom.of("b"))), Fact.of(Struct.of("f", Atom.of("c"))), Fact.of(Struct.of("f", Atom.of("a"))), - Fact.of(Struct.of("f", Atom.of("b"))) + Fact.of(Struct.of("f", Atom.of("b"))), ) private val expectedIndexingOverF2 = @@ -60,7 +59,7 @@ class PrototypeProperIndexingTest( Fact.of(Struct.of("f", Atom.of("b"), Atom.of("a"))), Fact.of(Struct.of("f", Atom.of("b"), Var.of("X"))), Fact.of(Struct.of("f", Var.of("X"), Atom.of("a"))), - Fact.of(Struct.of("f", Var.of("X"), Var.of("Y"))) + Fact.of(Struct.of("f", Var.of("X"), Var.of("Y"))), ) private val expectedIndexingOverG1 = @@ -69,7 +68,7 @@ class PrototypeProperIndexingTest( Fact.of(Struct.of("g", Numeric.of(2))), Fact.of(Struct.of("g", Var.of("X"))), Fact.of(Struct.of("g", Var.of("Y"))), - Fact.of(Struct.of("g", Numeric.of(1))) + Fact.of(Struct.of("g", Numeric.of(1))), ) private val expectedIndexingOverG2 = @@ -77,7 +76,7 @@ class PrototypeProperIndexingTest( Fact.of(Struct.of("g", Var.of("X"), Var.of("Y"))), Fact.of(Struct.of("g", Var.of("X"), Atom.of("a"))), Fact.of(Struct.of("g", Atom.of("a"), Var.of("X"))), - Fact.of(Struct.of("g", Atom.of("b"), Atom.of("a"))) + Fact.of(Struct.of("g", Atom.of("b"), Atom.of("a"))), ) private val newF1AtomClause = Fact.of(Struct.of("f", Numeric.of(0))) @@ -93,25 +92,26 @@ class PrototypeProperIndexingTest( fun testCornerCaseInClauseRetrieval() { // f(f(f(1), 2), 3). - val fact = Fact.of( - Struct.of( - "f", + val fact = + Fact.of( Struct.of( "f", - Struct.of("f", Integer.of(1)), - Integer.of(2) + Struct.of( + "f", + Struct.of("f", Integer.of(1)), + Integer.of(2), + ), + Integer.of(3), ), - Integer.of(3) ) - ) withFreshTheory(theoryGenerator(listOf(fact))) { assertClausesHaveSameLengthAndContent( sequenceOf(fact), - theory[Fact.of(Struct.of("f", Var.anonymous(), Var.anonymous()))] + theory[Fact.of(Struct.of("f", Var.anonymous(), Var.anonymous()))], ) assertClausesHaveSameLengthAndContent( sequenceOf(fact), - theory[Fact.of(Struct.of("f", Struct.of("f", Var.anonymous(), Var.anonymous()), Var.anonymous()))] + theory[Fact.of(Struct.of("f", Struct.of("f", Var.anonymous(), Var.anonymous()), Var.anonymous()))], ) assertClausesHaveSameLengthAndContent( sequenceOf(fact), @@ -120,10 +120,10 @@ class PrototypeProperIndexingTest( Struct.of( "f", Struct.of("f", Struct.of("f", Var.anonymous()), Var.anonymous()), - Var.anonymous() - ) - ) - ] + Var.anonymous(), + ), + ), + ], ) } } @@ -172,7 +172,7 @@ class PrototypeProperIndexingTest( assertClausesHaveSameLengthAndContent( expectedIndexingOverF1 + expectedIndexingOverF1, - generatedIndexingOverDoubledDatabaseForF1Family + generatedIndexingOverDoubledDatabaseForF1Family, ) } } @@ -184,7 +184,7 @@ class PrototypeProperIndexingTest( assertClausesHaveSameLengthAndContent( expectedIndexingOverF2 + expectedIndexingOverF2, - generatedIndexingOverDoubledDatabaseForF2Family + generatedIndexingOverDoubledDatabaseForF2Family, ) } } @@ -196,7 +196,7 @@ class PrototypeProperIndexingTest( assertClausesHaveSameLengthAndContent( expectedIndexingOverG1 + expectedIndexingOverG1, - generatedIndexingOverDoubledDatabaseForG1Family + generatedIndexingOverDoubledDatabaseForG1Family, ) } } @@ -208,7 +208,7 @@ class PrototypeProperIndexingTest( assertClausesHaveSameLengthAndContent( expectedIndexingOverG2 + expectedIndexingOverG2, - generatedIndexingOverDoubledDatabaseForG2Family + generatedIndexingOverDoubledDatabaseForG2Family, ) } } @@ -222,7 +222,10 @@ class PrototypeProperIndexingTest( .filter { it matches anonymousF1Clause } assertTermsAreEqual(newF1AtomClause, generatedIndexingAfterAssertionA.first()) - assertClausesHaveSameLengthAndContent(listOf(newF1AtomClause) + expectedIndexingOverF1, generatedIndexingAfterAssertionA) + assertClausesHaveSameLengthAndContent( + listOf(newF1AtomClause) + expectedIndexingOverF1, + generatedIndexingAfterAssertionA, + ) } } @@ -235,7 +238,10 @@ class PrototypeProperIndexingTest( .filter { it matches anonymousF1Clause } assertTermsAreEqual(newF1VarClause, generatedIndexingAfterAssertionA.first()) - assertClausesHaveSameLengthAndContent(listOf(newF1VarClause) + expectedIndexingOverF1, generatedIndexingAfterAssertionA) + assertClausesHaveSameLengthAndContent( + listOf(newF1VarClause) + expectedIndexingOverF1, + generatedIndexingAfterAssertionA, + ) } } @@ -248,7 +254,10 @@ class PrototypeProperIndexingTest( .filter { it matches anonymousF2Clause } assertTermsAreEqual(newF2AtomClause, generatedIndexingAfterAssertionA.first()) - assertClausesHaveSameLengthAndContent(listOf(newF2AtomClause) + expectedIndexingOverF2, generatedIndexingAfterAssertionA) + assertClausesHaveSameLengthAndContent( + listOf(newF2AtomClause) + expectedIndexingOverF2, + generatedIndexingAfterAssertionA, + ) } } @@ -261,7 +270,10 @@ class PrototypeProperIndexingTest( .filter { it matches anonymousF2Clause } assertTermsAreEqual(newF2VarClause, generatedIndexingAfterAssertionA.first()) - assertClausesHaveSameLengthAndContent(listOf(newF2VarClause) + expectedIndexingOverF2, generatedIndexingAfterAssertionA) + assertClausesHaveSameLengthAndContent( + listOf(newF2VarClause) + expectedIndexingOverF2, + generatedIndexingAfterAssertionA, + ) } } @@ -274,7 +286,10 @@ class PrototypeProperIndexingTest( .filter { it matches anonymousF2Clause } assertTermsAreEqual(newF2MixedClause, generatedIndexingAfterAssertionA.first()) - assertClausesHaveSameLengthAndContent(listOf(newF2MixedClause) + expectedIndexingOverF2, generatedIndexingAfterAssertionA) + assertClausesHaveSameLengthAndContent( + listOf(newF2MixedClause) + expectedIndexingOverF2, + generatedIndexingAfterAssertionA, + ) } } @@ -287,7 +302,10 @@ class PrototypeProperIndexingTest( .filter { it matches anonymousF1Clause } assertTermsAreEqual(newF1AtomClause, generatedIndexingAfterAssertionA.asReversed().first()) - assertClausesHaveSameLengthAndContent(expectedIndexingOverF1 + listOf(newF1AtomClause), generatedIndexingAfterAssertionA) + assertClausesHaveSameLengthAndContent( + expectedIndexingOverF1 + listOf(newF1AtomClause), + generatedIndexingAfterAssertionA, + ) } } @@ -300,7 +318,10 @@ class PrototypeProperIndexingTest( .filter { it matches anonymousF1Clause } assertTermsAreEqual(newF1VarClause, generatedIndexingAfterAssertionA.asReversed().first()) - assertClausesHaveSameLengthAndContent(expectedIndexingOverF1 + listOf(newF1VarClause), generatedIndexingAfterAssertionA) + assertClausesHaveSameLengthAndContent( + expectedIndexingOverF1 + listOf(newF1VarClause), + generatedIndexingAfterAssertionA, + ) } } @@ -313,7 +334,10 @@ class PrototypeProperIndexingTest( .filter { it matches anonymousF2Clause } assertTermsAreEqual(newF2AtomClause, generatedIndexingAfterAssertionA.asReversed().first()) - assertClausesHaveSameLengthAndContent(expectedIndexingOverF2 + listOf(newF2AtomClause), generatedIndexingAfterAssertionA) + assertClausesHaveSameLengthAndContent( + expectedIndexingOverF2 + listOf(newF2AtomClause), + generatedIndexingAfterAssertionA, + ) } } @@ -326,7 +350,10 @@ class PrototypeProperIndexingTest( .filter { it matches anonymousF2Clause } assertTermsAreEqual(newF2VarClause, generatedIndexingAfterAssertionA.asReversed().first()) - assertClausesHaveSameLengthAndContent(expectedIndexingOverF2 + listOf(newF2VarClause), generatedIndexingAfterAssertionA) + assertClausesHaveSameLengthAndContent( + expectedIndexingOverF2 + listOf(newF2VarClause), + generatedIndexingAfterAssertionA, + ) } } @@ -339,7 +366,10 @@ class PrototypeProperIndexingTest( .filter { it matches anonymousF2Clause } assertTermsAreEqual(newF2MixedClause, generatedIndexingAfterAssertionA.asReversed().first()) - assertClausesHaveSameLengthAndContent(expectedIndexingOverF2 + listOf(newF2MixedClause), generatedIndexingAfterAssertionA) + assertClausesHaveSameLengthAndContent( + expectedIndexingOverF2 + listOf(newF2MixedClause), + generatedIndexingAfterAssertionA, + ) } } } diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/PrototypeRetractResultTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/PrototypeRetractResultTest.kt index b724144a8..f0b2390fb 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/PrototypeRetractResultTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/PrototypeRetractResultTest.kt @@ -14,9 +14,8 @@ import kotlin.test.assertFailsWith */ internal class PrototypeRetractResultTest( private val emptyTheoryGenerator: () -> Theory, - private val theoryGenerator: (Iterable) -> Theory + private val theoryGenerator: (Iterable) -> Theory, ) { - private val clause1 = Clause.of(Struct.of("a", Var.anonymous()), Struct.of("b", Var.anonymous())) private val clause2 = Clause.of(Struct.of("p", Atom.of("john"))) diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/PrototypeTheoryCreationTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/PrototypeTheoryCreationTest.kt index ce11fa1d5..374abe9b6 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/PrototypeTheoryCreationTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/PrototypeTheoryCreationTest.kt @@ -17,9 +17,8 @@ internal class PrototypeTheoryCreationTest( private val theoryConstructorFromArray: (Array) -> Theory, private val theoryConstructorFromIterable: (Iterable) -> Theory, private val theoryConstructorFromSequence: (Sequence) -> Theory, - private val theoryConstructorFromScopes: (Array Clause>) -> Theory + private val theoryConstructorFromScopes: (Array Clause>) -> Theory, ) { - private val correctInstance = theoryConstructorFromIterable(TheoryUtils.wellFormedClauses) fun emptyCreatesEmptyTheory() { @@ -35,11 +34,12 @@ internal class PrototypeTheoryCreationTest( } fun ofVarargScopeToClauseCreatesCorrectInstance() { - val toBeTested = theoryConstructorFromScopes( - TheoryUtils.wellFormedClauses - .map Clause> { { clauseOf(it.head, it.body) } } - .toTypedArray() - ) + val toBeTested = + theoryConstructorFromScopes( + TheoryUtils.wellFormedClauses + .map Clause> { { clauseOf(it.head, it.body) } } + .toTypedArray(), + ) assertEquals(correctInstance, toBeTested) } diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/PrototypeTheoryTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/PrototypeTheoryTest.kt index 51f2019c8..5ab3a792d 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/PrototypeTheoryTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/PrototypeTheoryTest.kt @@ -34,15 +34,14 @@ import kotlin.test.assertTrue */ class PrototypeTheoryTest( private val emptyTheoryGenerator: () -> Theory, - private val theoryGenerator: (Iterable) -> Theory + private val theoryGenerator: (Iterable) -> Theory, ) { - private data class FreshTheoriesScope(var emptyTheory: Theory, var filledTheory: Theory) private fun withFreshTheories( emptyTheory: Theory = emptyTheoryGenerator(), filledTheory: Theory = theoryGenerator(wellFormedClauses), - action: FreshTheoriesScope.() -> R + action: FreshTheoriesScope.() -> R, ): R = FreshTheoriesScope(emptyTheory, filledTheory).action() private val anIndependentFact: Fact = Fact.of(Atom.of("myTestingFact")) @@ -97,12 +96,15 @@ class PrototypeTheoryTest( fun plusTheoryFailsOnBadTheory() { withFreshTheories { - val badTheory = object : Theory by emptyTheoryGenerator() { - override val clauses: Iterable = notWellFormedClauses - override fun iterator(): Iterator = notWellFormedClauses.iterator() - override val isEmpty: Boolean get() = notWellFormedClauses.isEmpty() - override val isNonEmpty: Boolean get() = !isEmpty - } + val badTheory = + object : Theory by emptyTheoryGenerator() { + override val clauses: Iterable = notWellFormedClauses + + override fun iterator(): Iterator = notWellFormedClauses.iterator() + + override val isEmpty: Boolean get() = notWellFormedClauses.isEmpty() + override val isNonEmpty: Boolean get() = !isEmpty + } assertFailsWith { filledTheory + badTheory } } } @@ -265,8 +267,9 @@ class PrototypeTheoryTest( fun assertAStruct() { withFreshTheories { - val correctPartiallyOrderedClauses = wellFormedClauses.toMutableList() - .apply { add(0, Fact.of(aRule.head)) } + val correctPartiallyOrderedClauses = + wellFormedClauses.toMutableList() + .apply { add(0, Fact.of(aRule.head)) } val toBeTested = filledTheory.assertA(aRule.head) assertClauseHeadPartialOrderingRespected(correctPartiallyOrderedClauses, toBeTested.clauses) @@ -320,7 +323,7 @@ class PrototypeTheoryTest( assertClauseHeadPartialOrderingRespected( wellFormedClauses + Fact.of(aRule.head), - toBeTested.clauses + toBeTested.clauses, ) } } @@ -449,13 +452,18 @@ class PrototypeTheoryTest( } } - private fun assertSameIfMutableNotSameOtherwise(first: Theory, second: Theory) { + private fun assertSameIfMutableNotSameOtherwise( + first: Theory, + second: Theory, + ) { if (first is MutableTheory && second is MutableTheory) { assertSame(first, second) } else if (first !is MutableTheory && second !is MutableTheory) { assertNotSame(first, second) } else { - throw IllegalStateException("There must be a problem: trying to compare a mutable theory with an immutable one") + throw IllegalStateException( + "There must be a problem: trying to compare a mutable theory with an immutable one", + ) } } @@ -482,7 +490,7 @@ class PrototypeTheoryTest( withFreshTheories { assertClausesHaveSameLengthAndContent( filledTheory.clauses.iterator().asSequence(), - filledTheory.iterator().asSequence() + filledTheory.iterator().asSequence(), ) } } @@ -493,22 +501,22 @@ class PrototypeTheoryTest( for (query in positiveMemberQueries) { assertClausesHaveSameLengthAndContent( memberClause.asSequence(), - theory[query] + theory[query], ) assertClausesHaveSameLengthAndContent( memberClause.asSequence(), - theory[query.head] + theory[query.head], ) } for (query in negativeMemberQueries) { assertClausesHaveSameLengthAndContent( emptySequence(), - theory[query] + theory[query], ) assertClausesHaveSameLengthAndContent( emptySequence(), - theory[query.head] + theory[query.head], ) } } @@ -518,12 +526,12 @@ class PrototypeTheoryTest( var theory = theoryGenerator(memberClause) assertClausesHaveSameLengthAndContent( memberClause, - (theory.retract(query) as RetractResult.Success).clauses + (theory.retract(query) as RetractResult.Success).clauses, ) theory = theoryGenerator(memberClause) assertClausesHaveSameLengthAndContent( memberClause, - (theory.retract(query.head) as RetractResult.Success).clauses + (theory.retract(query.head) as RetractResult.Success).clauses, ) } @@ -531,11 +539,11 @@ class PrototypeTheoryTest( val theory = theoryGenerator(memberClause) assertEquals( RetractResult.Failure(theory), - theory.retract(query) + theory.retract(query), ) assertEquals( RetractResult.Failure(theory), - theory.retract(query.head) + theory.retract(query.head), ) } } @@ -546,7 +554,7 @@ class PrototypeTheoryTest( for (query in deepQueries) { assertClausesHaveSameLengthAndContent( deepClause.asSequence(), - theory[query] + theory[query], ) } } @@ -556,7 +564,7 @@ class PrototypeTheoryTest( val theory = theoryGenerator(deepClause) assertClausesHaveSameLengthAndContent( deepClause, - (theory.retract(query) as RetractResult.Success).clauses + (theory.retract(query) as RetractResult.Success).clauses, ) } } diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/PrototypeTheoryUnificator.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/PrototypeTheoryUnificator.kt index 0f7628a3f..fb74f2e7d 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/PrototypeTheoryUnificator.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/PrototypeTheoryUnificator.kt @@ -12,19 +12,20 @@ import kotlin.test.assertSame import kotlin.collections.List as KtList class PrototypeTheoryUnificator( - private val theoryGenerator: (Unificator, Iterable) -> Theory + private val theoryGenerator: (Unificator, Iterable) -> Theory, ) { private val unificator1 = Unificator.strict() private val unificator2 = Unificator.naive() - private val clauses: KtList = logicProgramming { - ktListOf( - fact { "f"("a") }, - fact { "f"(intOf(1)) }, - fact { "f"(realOf(1.0)) } - ) - } + private val clauses: KtList = + logicProgramming { + ktListOf( + fact { "f"("a") }, + fact { "f"(intOf(1)) }, + fact { "f"(realOf(1.0)) }, + ) + } private lateinit var theory1: Theory private lateinit var theory2: Theory diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/TestTheoryMetadata.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/TestTheoryMetadata.kt index f7ccd9f08..58e92bb69 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/TestTheoryMetadata.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/TestTheoryMetadata.kt @@ -17,17 +17,17 @@ import kotlin.test.assertNull import kotlin.test.assertTrue class TestTheoryMetadata { - - private val theories get() = listOf( - Theory.emptyIndexed(Unificator.default), - Theory.emptyListed(Unificator.default), - Theory.indexedOf(Unificator.default, TheoryUtils.wellFormedClauses), - Theory.listedOf(Unificator.default, TheoryUtils.wellFormedClauses), - MutableTheory.emptyIndexed(Unificator.default), - MutableTheory.emptyListed(Unificator.default), - MutableTheory.indexedOf(Unificator.default, TheoryUtils.wellFormedClauses), - MutableTheory.listedOf(Unificator.default, TheoryUtils.wellFormedClauses) - ) + private val theories get() = + listOf( + Theory.emptyIndexed(Unificator.default), + Theory.emptyListed(Unificator.default), + Theory.indexedOf(Unificator.default, TheoryUtils.wellFormedClauses), + Theory.listedOf(Unificator.default, TheoryUtils.wellFormedClauses), + MutableTheory.emptyIndexed(Unificator.default), + MutableTheory.emptyListed(Unificator.default), + MutableTheory.indexedOf(Unificator.default, TheoryUtils.wellFormedClauses), + MutableTheory.listedOf(Unificator.default, TheoryUtils.wellFormedClauses), + ) private data class Metadata(val value: T) @@ -38,24 +38,26 @@ class TestTheoryMetadata { private val someValue2 = Metadata(false) private val someOtherValue = Metadata(null) - private val taggedTheories get() = TheoryUtils.wellFormedClauses - .map { it.setTags(someKey to someValue1, someOtherKey to someOtherValue) } - .let { - listOf( - Theory.emptyIndexed(Unificator.default).setTag(yetAnotherKey, someValue2), - Theory.emptyListed(Unificator.default).setTag(yetAnotherKey, someValue2), - Theory.indexedOf(Unificator.default, it).setTag(yetAnotherKey, someValue2), - Theory.listedOf(Unificator.default, it).setTag(yetAnotherKey, someValue2), - MutableTheory.emptyIndexed(Unificator.default).setTag(yetAnotherKey, someValue2), - MutableTheory.emptyListed(Unificator.default).setTag(yetAnotherKey, someValue2), - MutableTheory.indexedOf(Unificator.default, it).setTag(yetAnotherKey, someValue2), - MutableTheory.listedOf(Unificator.default, it).setTag(yetAnotherKey, someValue2) - ) - } + private val taggedTheories get() = + TheoryUtils.wellFormedClauses + .map { it.setTags(someKey to someValue1, someOtherKey to someOtherValue) } + .let { + listOf( + Theory.emptyIndexed(Unificator.default).setTag(yetAnotherKey, someValue2), + Theory.emptyListed(Unificator.default).setTag(yetAnotherKey, someValue2), + Theory.indexedOf(Unificator.default, it).setTag(yetAnotherKey, someValue2), + Theory.listedOf(Unificator.default, it).setTag(yetAnotherKey, someValue2), + MutableTheory.emptyIndexed(Unificator.default).setTag(yetAnotherKey, someValue2), + MutableTheory.emptyListed(Unificator.default).setTag(yetAnotherKey, someValue2), + MutableTheory.indexedOf(Unificator.default, it).setTag(yetAnotherKey, someValue2), + MutableTheory.listedOf(Unificator.default, it).setTag(yetAnotherKey, someValue2), + ) + } - private val missingClauses = TheoryUtils.wellFormedClauses - .filterIsInstance() - .map { Rule.of(it.head.setFunctor(it.head.functor + "'"), it.body) } + private val missingClauses = + TheoryUtils.wellFormedClauses + .filterIsInstance() + .map { Rule.of(it.head.setFunctor(it.head.functor + "'"), it.body) } private val presentClauses = TheoryUtils.wellFormedClauses @@ -188,7 +190,7 @@ class TestTheoryMetadata { private fun editingATheoryPreservesClausesTags( clausesSource: Iterable, clausesShouldBeUntaggedAfterEdit: Boolean = true, - edit: Theory.(Clause) -> Theory + edit: Theory.(Clause) -> Theory, ) { for ((untaggedTheory, taggedTheory) in theories.zip(taggedTheories)) { assertEquals(untaggedTheory, taggedTheory) diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/IndexedClauseIndexingTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/IndexedClauseIndexingTest.kt index f3e269766..988b4dc58 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/IndexedClauseIndexingTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/IndexedClauseIndexingTest.kt @@ -6,10 +6,10 @@ import kotlin.test.BeforeTest import kotlin.test.Test internal class IndexedClauseIndexingTest { - - private val prototype = PrototypeProperIndexingTest( - Factories::indexedTheoryOf - ) + private val prototype = + PrototypeProperIndexingTest( + Factories::indexedTheoryOf, + ) @BeforeTest fun init() { diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/IndexedRetractResultTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/IndexedRetractResultTest.kt index 3586958ef..1d4b6bb13 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/IndexedRetractResultTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/IndexedRetractResultTest.kt @@ -5,11 +5,10 @@ import it.unibo.tuprolog.theory.PrototypeRetractResultTest import kotlin.test.Test internal class IndexedRetractResultTest { - private val prototype: PrototypeRetractResultTest = PrototypeRetractResultTest( Factories::emptyIndexedTheory, - Factories::indexedTheoryOf + Factories::indexedTheoryOf, ) @Test diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/IndexedTheoryCreationTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/IndexedTheoryCreationTest.kt index e40fa2c50..07a250362 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/IndexedTheoryCreationTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/IndexedTheoryCreationTest.kt @@ -5,14 +5,13 @@ import it.unibo.tuprolog.theory.PrototypeTheoryCreationTest import kotlin.test.Test internal class IndexedTheoryCreationTest { - private val prototype: PrototypeTheoryCreationTest = PrototypeTheoryCreationTest( Factories::emptyIndexedTheory, Factories::indexedTheoryOf, Factories::indexedTheoryOf, Factories::indexedTheoryOf, - Factories::indexedTheoryOf + Factories::indexedTheoryOf, ) @Test diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/IndexedTheoryTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/IndexedTheoryTest.kt index a5a60153a..194d972d1 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/IndexedTheoryTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/IndexedTheoryTest.kt @@ -5,11 +5,11 @@ import it.unibo.tuprolog.theory.PrototypeTheoryTest import kotlin.test.Test internal class IndexedTheoryTest { - - private val prototype = PrototypeTheoryTest( - Factories::emptyIndexedTheory, - Factories::indexedTheoryOf - ) + private val prototype = + PrototypeTheoryTest( + Factories::emptyIndexedTheory, + Factories::indexedTheoryOf, + ) // @BeforeTest // fun init() { diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/ListedClauseIndexingTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/ListedClauseIndexingTest.kt index f592b3e83..79ea5525e 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/ListedClauseIndexingTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/ListedClauseIndexingTest.kt @@ -5,10 +5,10 @@ import it.unibo.tuprolog.theory.PrototypeProperIndexingTest import kotlin.test.Test internal class ListedClauseIndexingTest { - - private val prototype = PrototypeProperIndexingTest( - Factories::listedTheoryOf - ) + private val prototype = + PrototypeProperIndexingTest( + Factories::listedTheoryOf, + ) @Test fun testCornerCaseInClauseRetrieval() { diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/ListedRetractResultTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/ListedRetractResultTest.kt index 88ed858a6..c07a5438c 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/ListedRetractResultTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/ListedRetractResultTest.kt @@ -5,11 +5,10 @@ import it.unibo.tuprolog.theory.PrototypeRetractResultTest import kotlin.test.Test internal class ListedRetractResultTest { - private val prototype: PrototypeRetractResultTest = PrototypeRetractResultTest( Factories::emptyListedTheory, - Factories::listedTheoryOf + Factories::listedTheoryOf, ) @Test diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/ListedTheoryCreationTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/ListedTheoryCreationTest.kt index e1f37a8d7..732d807ac 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/ListedTheoryCreationTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/ListedTheoryCreationTest.kt @@ -5,14 +5,13 @@ import it.unibo.tuprolog.theory.PrototypeTheoryCreationTest import kotlin.test.Test internal class ListedTheoryCreationTest { - private val prototype: PrototypeTheoryCreationTest = PrototypeTheoryCreationTest( Factories::emptyListedTheory, Factories::listedTheoryOf, Factories::listedTheoryOf, Factories::listedTheoryOf, - Factories::listedTheoryOf + Factories::listedTheoryOf, ) @Test diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/ListedTheoryTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/ListedTheoryTest.kt index e69d49d95..b1a7708fd 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/ListedTheoryTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/ListedTheoryTest.kt @@ -5,11 +5,11 @@ import it.unibo.tuprolog.theory.PrototypeTheoryTest import kotlin.test.Test internal class ListedTheoryTest { - - private val prototype = PrototypeTheoryTest( - Factories::emptyListedTheory, - Factories::listedTheoryOf - ) + private val prototype = + PrototypeTheoryTest( + Factories::emptyListedTheory, + Factories::listedTheoryOf, + ) // @BeforeTest // fun init() { diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableIndexedClauseIndexingTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableIndexedClauseIndexingTest.kt index e8fc3244e..e4cb4f2b6 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableIndexedClauseIndexingTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableIndexedClauseIndexingTest.kt @@ -6,10 +6,10 @@ import kotlin.test.BeforeTest import kotlin.test.Test internal class MutableIndexedClauseIndexingTest { - - private val prototype = PrototypeProperIndexingTest( - Factories::mutableIndexedTheoryOf - ) + private val prototype = + PrototypeProperIndexingTest( + Factories::mutableIndexedTheoryOf, + ) @BeforeTest fun init() { diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableIndexedRetractResultTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableIndexedRetractResultTest.kt index cbb94d44c..30b0254b4 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableIndexedRetractResultTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableIndexedRetractResultTest.kt @@ -5,11 +5,10 @@ import it.unibo.tuprolog.theory.PrototypeRetractResultTest import kotlin.test.Test internal class MutableIndexedRetractResultTest { - private val prototype: PrototypeRetractResultTest = PrototypeRetractResultTest( Factories::emptyMutableIndexedTheory, - Factories::mutableIndexedTheoryOf + Factories::mutableIndexedTheoryOf, ) @Test diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableIndexedTheoryCreationTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableIndexedTheoryCreationTest.kt index f884ae1c7..6bf29814d 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableIndexedTheoryCreationTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableIndexedTheoryCreationTest.kt @@ -5,14 +5,13 @@ import it.unibo.tuprolog.theory.PrototypeTheoryCreationTest import kotlin.test.Test internal class MutableIndexedTheoryCreationTest { - private val prototype: PrototypeTheoryCreationTest = PrototypeTheoryCreationTest( Factories::emptyMutableIndexedTheory, Factories::mutableIndexedTheoryOf, Factories::mutableIndexedTheoryOf, Factories::mutableIndexedTheoryOf, - Factories::mutableIndexedTheoryOf + Factories::mutableIndexedTheoryOf, ) @Test diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableIndexedTheoryTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableIndexedTheoryTest.kt index 78eda8adf..bda0b0249 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableIndexedTheoryTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableIndexedTheoryTest.kt @@ -5,11 +5,11 @@ import it.unibo.tuprolog.theory.PrototypeTheoryTest import kotlin.test.Test internal class MutableIndexedTheoryTest { - - private val prototype = PrototypeTheoryTest( - Factories::emptyMutableIndexedTheory, - Factories::mutableIndexedTheoryOf - ) + private val prototype = + PrototypeTheoryTest( + Factories::emptyMutableIndexedTheory, + Factories::mutableIndexedTheoryOf, + ) // @BeforeTest // fun init() { diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableListedClauseIndexingTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableListedClauseIndexingTest.kt index 63c4ccb79..7c4fc45e4 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableListedClauseIndexingTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableListedClauseIndexingTest.kt @@ -5,10 +5,10 @@ import it.unibo.tuprolog.theory.PrototypeProperIndexingTest import kotlin.test.Test internal class MutableListedClauseIndexingTest { - - private val prototype = PrototypeProperIndexingTest( - Factories::mutableListedTheoryOf - ) + private val prototype = + PrototypeProperIndexingTest( + Factories::mutableListedTheoryOf, + ) @Test fun testCornerCaseInClauseRetrieval() { diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableListedRetractResultTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableListedRetractResultTest.kt index bfc979fee..946f22294 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableListedRetractResultTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableListedRetractResultTest.kt @@ -5,11 +5,10 @@ import it.unibo.tuprolog.theory.PrototypeRetractResultTest import kotlin.test.Test internal class MutableListedRetractResultTest { - private val prototype: PrototypeRetractResultTest = PrototypeRetractResultTest( Factories::emptyMutableListedTheory, - Factories::mutableListedTheoryOf + Factories::mutableListedTheoryOf, ) @Test diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableListedTheoryCreationTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableListedTheoryCreationTest.kt index 6abe32942..c204e9010 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableListedTheoryCreationTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableListedTheoryCreationTest.kt @@ -5,14 +5,13 @@ import it.unibo.tuprolog.theory.PrototypeTheoryCreationTest import kotlin.test.Test internal class MutableListedTheoryCreationTest { - private val prototype: PrototypeTheoryCreationTest = PrototypeTheoryCreationTest( Factories::emptyMutableIndexedTheory, Factories::mutableIndexedTheoryOf, Factories::mutableIndexedTheoryOf, Factories::mutableIndexedTheoryOf, - Factories::mutableIndexedTheoryOf + Factories::mutableIndexedTheoryOf, ) @Test diff --git a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableListedTheoryTest.kt b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableListedTheoryTest.kt index ba83be00e..7948ab216 100644 --- a/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableListedTheoryTest.kt +++ b/theory/src/commonTest/kotlin/it/unibo/tuprolog/theory/impl/MutableListedTheoryTest.kt @@ -5,11 +5,11 @@ import it.unibo.tuprolog.theory.PrototypeTheoryTest import kotlin.test.Test internal class MutableListedTheoryTest { - - private val prototype = PrototypeTheoryTest( - Factories::emptyMutableIndexedTheory, - Factories::mutableIndexedTheoryOf - ) + private val prototype = + PrototypeTheoryTest( + Factories::emptyMutableIndexedTheory, + Factories::mutableIndexedTheoryOf, + ) // @BeforeTest // fun init() { diff --git a/theory/src/jsMain/kotlin/it/unibo/tuprolog/collections/rete/PlatformSpecificUtils.kt b/theory/src/jsMain/kotlin/it/unibo/tuprolog/collections/rete/PlatformSpecificUtils.kt index ddcff7e00..5babd7e06 100644 --- a/theory/src/jsMain/kotlin/it/unibo/tuprolog/collections/rete/PlatformSpecificUtils.kt +++ b/theory/src/jsMain/kotlin/it/unibo/tuprolog/collections/rete/PlatformSpecificUtils.kt @@ -2,6 +2,6 @@ package it.unibo.tuprolog.collections.rete internal actual fun Sequence.takeFirstAfterSkipping(n: Int): T { val iter = this.iterator() - for (i in 0 until n) iter.next() + repeat(n) { iter.next() } return iter.next() } diff --git a/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/AbstractUnificator.kt b/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/AbstractUnificator.kt index 2063cacad..03968e314 100644 --- a/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/AbstractUnificator.kt +++ b/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/AbstractUnificator.kt @@ -7,125 +7,145 @@ import it.unibo.tuprolog.core.Term import it.unibo.tuprolog.core.Var import kotlin.jvm.JvmOverloads -abstract class AbstractUnificator @JvmOverloads constructor(override val context: Substitution = empty()) : Unificator { - - /** The context converted to equivalent equations */ - private val contextEquations: Iterable by lazy { context.toEquations() } - - /** Checks provided [Term]s for equality */ - protected abstract fun checkTermsEquality(first: Term, second: Term): Boolean - - /** Implements the so called occur-check; checks if the [variable] is present in [term] */ - private fun occurrenceCheck(variable: Var, term: Term): Boolean = - when { - term.isVar -> checkTermsEquality(variable, term) - term.isStruct -> term.variables.any { occurrenceCheck(variable, it) } - else -> false - } - - /** Returns the sequence of equations resulting from the comparison of given [Term]s */ - private fun equationsFor(term1: Term, term2: Term): Sequence = - Equation.allOf(term1, term2, this::checkTermsEquality) - - private fun equationsFor(substitution1: Substitution, substitution2: Substitution): Sequence = - Equation.from( - (substitution1.asSequence() + substitution2.asSequence()).map { it.toPair() } - ) - - /** A function to apply given [substitution] to [equations], skipping the equation at given [exceptIndex] */ - private fun applySubstitutionToEquations( - substitution: Substitution, - equations: MutableList, - exceptIndex: Int - ): Boolean { - var changed = false - - fun handleIndex(i: Int) { - if (equations[i].isContradiction || equations[i].isIdentity) return - - val currentEq = equations[i] - val (newLhs, newRhs) = currentEq.apply(substitution).toPair() - - if (currentEq.lhs != newLhs || currentEq.rhs != newRhs) { - equations[i] = Equation.of(newLhs, newRhs, this::checkTermsEquality) - changed = true +abstract class AbstractUnificator + @JvmOverloads + constructor(override val context: Substitution = empty()) : Unificator { + /** The context converted to equivalent equations */ + private val contextEquations: Iterable by lazy { context.toEquations() } + + /** Checks provided [Term]s for equality */ + protected abstract fun checkTermsEquality( + first: Term, + second: Term, + ): Boolean + + /** Implements the so called occur-check; checks if the [variable] is present in [term] */ + private fun occurrenceCheck( + variable: Var, + term: Term, + ): Boolean = + when { + term.isVar -> checkTermsEquality(variable, term) + term.isStruct -> term.variables.any { occurrenceCheck(variable, it) } + else -> false } - } - - for (i in 0 until exceptIndex) handleIndex(i) - for (i in (exceptIndex + 1) until equations.size) handleIndex(i) - return changed - } + /** Returns the sequence of equations resulting from the comparison of given [Term]s */ + private fun equationsFor( + term1: Term, + term2: Term, + ): Sequence = Equation.allOf(term1, term2, this::checkTermsEquality) + + private fun equationsFor( + substitution1: Substitution, + substitution2: Substitution, + ): Sequence = + Equation.from( + (substitution1.asSequence() + substitution2.asSequence()).map { it.toPair() }, + ) + + /** A function to apply given [substitution] to [equations], skipping the equation at given [exceptIndex] */ + private fun applySubstitutionToEquations( + substitution: Substitution, + equations: MutableList, + exceptIndex: Int, + ): Boolean { + var changed = false + + fun handleIndex(i: Int) { + if (equations[i].isContradiction || equations[i].isIdentity) return + + val currentEq = equations[i] + val (newLhs, newRhs) = currentEq.apply(substitution).toPair() + + if (currentEq.lhs != newLhs || currentEq.rhs != newRhs) { + equations[i] = Equation.of(newLhs, newRhs, this::checkTermsEquality) + changed = true + } + } - private fun mgu(equations: MutableList, occurCheckEnabled: Boolean): Substitution { - var changed = true + for (i in 0 until exceptIndex) handleIndex(i) + for (i in (exceptIndex + 1) until equations.size) handleIndex(i) - while (changed) { - changed = false - val eqIterator = equations.listIterator() + return changed + } - while (eqIterator.hasNext()) { - val eq = eqIterator.next() - when { - eq.isContradiction -> { - return failed() // short circuit - } - eq.isIdentity -> { - eqIterator.remove() - changed = true - } - eq.isAssignment -> { - val assignment = eq.castToAssignment() - if (occurCheckEnabled && occurrenceCheck(assignment.lhs, eq.rhs)) { - return failed() - } else { - changed = changed || applySubstitutionToEquations( - assignment.toSubstitution(), - equations, - eqIterator.previousIndex() - ) + private fun mgu( + equations: MutableList, + occurCheckEnabled: Boolean, + ): Substitution { + var changed = true + + while (changed) { + changed = false + val eqIterator = equations.listIterator() + + while (eqIterator.hasNext()) { + val eq = eqIterator.next() + when { + eq.isContradiction -> { + return failed() // short circuit } - } - eq.isComparison -> { - eqIterator.remove() - insertion@ for (it in equationsFor(eq.lhs, eq.rhs)) { - when { - it.isIdentity -> continue@insertion - it.isContradiction -> return failed() - else -> eqIterator.add(it) + eq.isIdentity -> { + eqIterator.remove() + changed = true + } + eq.isAssignment -> { + val assignment = eq.castToAssignment() + if (occurCheckEnabled && occurrenceCheck(assignment.lhs, eq.rhs)) { + return failed() + } else { + changed = changed || + applySubstitutionToEquations( + assignment.toSubstitution(), + equations, + eqIterator.previousIndex(), + ) + } + } + eq.isComparison -> { + eqIterator.remove() + insertion@ for (it in equationsFor(eq.lhs, eq.rhs)) { + when { + it.isIdentity -> continue@insertion + it.isContradiction -> return failed() + else -> eqIterator.add(it) + } } + changed = true } - changed = true } } } - } - return equations.filter { it.isAssignment }.toSubstitution() - } + return equations.filter { it.isAssignment }.toSubstitution() + } - override fun mgu(term1: Term, term2: Term, occurCheckEnabled: Boolean): Substitution { - if (context.isFailed) return failed() - val equations = newDeque(contextEquations.asSequence() + equationsFor(term1, term2)) - return mgu(equations, occurCheckEnabled) - } + override fun mgu( + term1: Term, + term2: Term, + occurCheckEnabled: Boolean, + ): Substitution { + if (context.isFailed) return failed() + val equations = newDeque(contextEquations.asSequence() + equationsFor(term1, term2)) + return mgu(equations, occurCheckEnabled) + } - override fun merge( - substitution1: Substitution, - substitution2: Substitution, - occurCheckEnabled: Boolean - ): Substitution { - if (context.isFailed || substitution1.isFailed || substitution2.isFailed) return failed() - if (!occurCheckEnabled) { - val quickMerge = context + substitution1 + substitution2 - if (quickMerge.isSuccess) { - return quickMerge + override fun merge( + substitution1: Substitution, + substitution2: Substitution, + occurCheckEnabled: Boolean, + ): Substitution { + if (context.isFailed || substitution1.isFailed || substitution2.isFailed) return failed() + if (!occurCheckEnabled) { + val quickMerge = context + substitution1 + substitution2 + if (quickMerge.isSuccess) { + return quickMerge + } } + val equations = newDeque(contextEquations.asSequence() + equationsFor(substitution1, substitution2)) + return mgu(equations, occurCheckEnabled) } - val equations = newDeque(contextEquations.asSequence() + equationsFor(substitution1, substitution2)) - return mgu(equations, occurCheckEnabled) - } - private fun newDeque(items: Sequence): MutableList = items.toCollection(arrayListOf()) -} + private fun newDeque(items: Sequence): MutableList = items.toCollection(arrayListOf()) + } diff --git a/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/CachedUnificator.kt b/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/CachedUnificator.kt index a47b6e913..beef4a844 100644 --- a/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/CachedUnificator.kt +++ b/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/CachedUnificator.kt @@ -11,15 +11,18 @@ private typealias MguRequest = Triple<*, *, Boolean> class CachedUnificator( val decorated: Unificator, - cacheCapacity: Int + cacheCapacity: Int, ) : Unificator { - private val mguCache: Cache = Cache.simpleLru(cacheCapacity) override val context: Substitution get() = decorated.context - override fun mgu(term1: Term, term2: Term, occurCheckEnabled: Boolean): Substitution { + override fun mgu( + term1: Term, + term2: Term, + occurCheckEnabled: Boolean, + ): Substitution { val mguRequest = MguRequestForTerms(term1, term2, occurCheckEnabled) return when (val cached = mguCache[mguRequest]) { is Optional.Some -> cached.value @@ -34,7 +37,7 @@ class CachedUnificator( override fun merge( substitution1: Substitution, substitution2: Substitution, - occurCheckEnabled: Boolean + occurCheckEnabled: Boolean, ): Substitution { val mguRequest = MguRequestForSubstitutions(substitution1, substitution2, occurCheckEnabled) return when (val cached = mguCache[mguRequest]) { diff --git a/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/Equation.kt b/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/Equation.kt index 2d76c3f26..e2b5e357b 100644 --- a/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/Equation.kt +++ b/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/Equation.kt @@ -21,9 +21,8 @@ sealed class Equation( /** The left-hand side of the equation */ @JsName("lhs") open val lhs: Term, /** The right-hand side of the equation */ - @JsName("rhs") open val rhs: Term + @JsName("rhs") open val rhs: Term, ) : TermConvertible, Castable { - open val isIdentity: Boolean get() = false @@ -110,17 +109,20 @@ sealed class Equation( @JsName("apply") fun apply( substitution: Substitution, - equalityChecker: (Term, Term) -> Boolean = Term::equals + equalityChecker: (Term, Term) -> Boolean = Term::equals, ): Equation = of(lhs[substitution], rhs[substitution], equalityChecker) /** Equation companion object */ companion object { - /** Creates an [Equation] with provided left-hand and right-hand sides */ @JvmStatic @JvmOverloads @JsName("of") - fun of(lhs: Term, rhs: Term, equalityChecker: (Term, Term) -> Boolean = Term::equals): Equation = + fun of( + lhs: Term, + rhs: Term, + equalityChecker: (Term, Term) -> Boolean = Term::equals, + ): Equation = when { lhs.isVar && rhs.isVar -> { if (equalityChecker(lhs, rhs)) { @@ -157,7 +159,7 @@ sealed class Equation( @JsName("ofPair") fun of( pair: Pair, - equalityChecker: (Term, Term) -> Boolean = Term::equals + equalityChecker: (Term, Term) -> Boolean = Term::equals, ): Equation = of(pair.first, pair.second, equalityChecker) @JvmStatic @@ -165,7 +167,7 @@ sealed class Equation( @JsName("fromSequence") fun from( pairs: Sequence>, - equalityChecker: (Term, Term) -> Boolean = Term::equals + equalityChecker: (Term, Term) -> Boolean = Term::equals, ): Sequence = pairs.flatMap { allOf(it, equalityChecker) } @JvmStatic @@ -173,7 +175,7 @@ sealed class Equation( @JsName("fromIterable") fun from( pairs: Iterable>, - equalityChecker: (Term, Term) -> Boolean = Term::equals + equalityChecker: (Term, Term) -> Boolean = Term::equals, ): Sequence = from(pairs.asSequence(), equalityChecker) @JvmStatic @@ -181,7 +183,7 @@ sealed class Equation( @JsName("from") fun from( vararg pairs: Pair, - equalityChecker: (Term, Term) -> Boolean = Term::equals + equalityChecker: (Term, Term) -> Boolean = Term::equals, ): Sequence = from(sequenceOf(*pairs), equalityChecker) /** Creates all equations resulting from the deep inspection of given [Pair] of [Term]s */ @@ -190,10 +192,14 @@ sealed class Equation( @JsName("allOfPair") fun allOf( pair: Pair, - equalityChecker: (Term, Term) -> Boolean = Term::equals + equalityChecker: (Term, Term) -> Boolean = Term::equals, ): Sequence = allOf(pair.first, pair.second, equalityChecker) - private fun allOfLists(lhs: LogicList, rhs: LogicList, equalityChecker: (Term, Term) -> Boolean = Term::equals): Sequence = + private fun allOfLists( + lhs: LogicList, + rhs: LogicList, + equalityChecker: (Term, Term) -> Boolean = Term::equals, + ): Sequence = lhs.unfold().zip(rhs.unfold()).flatMap { (l, r) -> when { l.isCons && r.isCons -> sequenceOf(of(l.castToCons().head, r.castToCons().head, equalityChecker)) @@ -202,10 +208,17 @@ sealed class Equation( } } - private fun allOfTuples(lhs: Tuple, rhs: Tuple, equalityChecker: (Term, Term) -> Boolean = Term::equals): Sequence = + private fun allOfTuples( + lhs: Tuple, + rhs: Tuple, + equalityChecker: (Term, Term) -> Boolean = Term::equals, + ): Sequence = lhs.unfold().zip(rhs.unfold()).flatMap { (l, r) -> when { - l.isTuple && r.isTuple -> sequenceOf(of(l.castToTuple().left, r.castToTuple().left, equalityChecker)) + l.isTuple && r.isTuple -> + sequenceOf( + of(l.castToTuple().left, r.castToTuple().left, equalityChecker), + ) else -> allOf(l, r, equalityChecker) } } @@ -214,7 +227,11 @@ sealed class Equation( @JvmStatic @JvmOverloads @JsName("allOf") - fun allOf(lhs: Term, rhs: Term, equalityChecker: (Term, Term) -> Boolean = Term::equals): Sequence = + fun allOf( + lhs: Term, + rhs: Term, + equalityChecker: (Term, Term) -> Boolean = Term::equals, + ): Sequence = when { lhs.isAtom && rhs.isAtom -> { sequenceOf(of(lhs, rhs, equalityChecker)) diff --git a/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/UnificationUtils.kt b/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/UnificationUtils.kt index 0d842ab47..a131259ff 100644 --- a/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/UnificationUtils.kt +++ b/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/UnificationUtils.kt @@ -16,16 +16,17 @@ fun Equation.toAssignmentPair(): Pair = } /** Transforms an [Equation] of a [Var] with a [Term] to the corresponding [Substitution] */ -fun Equation.toSubstitution(): Substitution.Unifier = - Substitution.unifier(toAssignmentPair()) +fun Equation.toSubstitution(): Substitution.Unifier = Substitution.unifier(toAssignmentPair()) /** Creates a [Substitution] out of a [Iterable] of [Equation]s assigning [Var]s to [Term]s */ -fun Iterable.toSubstitution(): Substitution = - Substitution.of(this.asSequence().map { it.toAssignmentPair() }) +fun Iterable.toSubstitution(): Substitution = Substitution.of(this.asSequence().map { it.toAssignmentPair() }) /** Transforms a [Substitution] into the list of corresponding [Equation]s */ fun Substitution.toEquations(): List = - this.entries.map { (variable, term) -> Equation.Assignment(variable, term) } + this.entries.map { + (variable, term) -> + Equation.Assignment(variable, term) + } /** Creates an equation with [this] and [that] terms */ @Suppress("unused", "FunctionName") diff --git a/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/Unificator.kt b/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/Unificator.kt index 84994afe7..ff732ba03 100644 --- a/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/Unificator.kt +++ b/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/Unificator.kt @@ -6,54 +6,75 @@ import kotlin.js.JsName import kotlin.jvm.JvmStatic interface Unificator { - /** The context (in terms of already present bindings) in which the unification is performed */ @JsName("context") val context: Substitution /** Calculates the Most General Unifier of given [Term]s, optionally enabling occur-check */ @JsName("mguWithOccurCheck") - fun mgu(term1: Term, term2: Term, occurCheckEnabled: Boolean = true): Substitution + fun mgu( + term1: Term, + term2: Term, + occurCheckEnabled: Boolean = true, + ): Substitution /** Calculates the Most General Unifier of given [Term]s, enabling occur-check */ @JsName("mgu") - fun mgu(term1: Term, term2: Term): Substitution = - mgu(term1, term2, true) + fun mgu( + term1: Term, + term2: Term, + ): Substitution = mgu(term1, term2, true) /** Tells whether two [Term]s match each other, that is there's a Most General Unifier for them */ @JsName("matchWithOccurCheck") - fun match(term1: Term, term2: Term, occurCheckEnabled: Boolean): Boolean = - mgu(term1, term2, occurCheckEnabled) !== Substitution.failed() + fun match( + term1: Term, + term2: Term, + occurCheckEnabled: Boolean, + ): Boolean = mgu(term1, term2, occurCheckEnabled) !== Substitution.failed() /** Tells whether two [Term]s match each other, that is there's a Most General Unifier for them. * It performs unification with occur check*/ @JsName("match") - fun match(term1: Term, term2: Term): Boolean = - match(term1, term2, true) + fun match( + term1: Term, + term2: Term, + ): Boolean = match(term1, term2, true) /** Unifies two [Term]s if possible */ @JsName("unifyWithOccurCheck") - fun unify(term1: Term, term2: Term, occurCheckEnabled: Boolean): Term? { + fun unify( + term1: Term, + term2: Term, + occurCheckEnabled: Boolean, + ): Term? { val substitution = mgu(term1, term2, occurCheckEnabled) return if (substitution.isFailed) null else term1[substitution] } /** Unifies two [Term]s if possible, with occurs check */ @JsName("unify") - fun unify(term1: Term, term2: Term): Term? = - unify(term1, term2, true) + fun unify( + term1: Term, + term2: Term, + ): Term? = unify(term1, term2, true) /** Merges two [Substitution]s **/ @JsName("mergeWithOccurCheck") - fun merge(substitution1: Substitution, substitution2: Substitution, occurCheckEnabled: Boolean): Substitution + fun merge( + substitution1: Substitution, + substitution2: Substitution, + occurCheckEnabled: Boolean, + ): Substitution /** Merges two [Substitution]s, with occurs check **/ @JsName("merge") - fun merge(substitution1: Substitution, substitution2: Substitution): Substitution = - merge(substitution1, substitution2, true) + fun merge( + substitution1: Substitution, + substitution2: Substitution, + ): Substitution = merge(substitution1, substitution2, true) companion object { - /** * The default unification strategy that uses plain equals to determine [Term]s identity, and exploits an * LRU cache whose capacity is [DEFAULT_CACHE_CAPACITY] @@ -87,24 +108,25 @@ interface Unificator { @JsName("naiveWithContext") fun naive(context: Substitution): Unificator = object : AbstractUnificator(context) { - override fun checkTermsEquality(first: Term, second: Term) = - when { - first.isInteger && second.isInteger -> { - first.castToInteger().value.compareTo(second.castToInteger().value) == 0 - } - first.isNumber && second.isNumber -> { - first.castToNumeric().decimalValue.compareTo(second.castToNumeric().decimalValue) == 0 - } - else -> first == second + override fun checkTermsEquality( + first: Term, + second: Term, + ) = when { + first.isInteger && second.isInteger -> { + first.castToInteger().value.compareTo(second.castToInteger().value) == 0 + } + first.isNumber && second.isNumber -> { + first.castToNumeric().decimalValue.compareTo(second.castToNumeric().decimalValue) == 0 } + else -> first == second + } } /** Creates naive, empty unification strategy, that checks [Term]s identity through their [Term.equals] * methods, except in the case of numbers which are compared by value */ @JvmStatic @JsName("naive") - fun naive(): Unificator = - naive(Substitution.empty()) + fun naive(): Unificator = naive(Substitution.empty()) /** Creates naive unification strategy, with the given [context], that checks [Term]s identity through their [Term.equals] * methods */ @@ -112,15 +134,17 @@ interface Unificator { @JsName("strictWithContext") fun strict(context: Substitution): Unificator = object : AbstractUnificator(context) { - override fun checkTermsEquality(first: Term, second: Term) = first == second + override fun checkTermsEquality( + first: Term, + second: Term, + ) = first == second } /** Creates naive unification strategy, that checks [Term]s identity through their [Term.equals] * methods */ @JvmStatic @JsName("strict") - fun strict(): Unificator = - strict(Substitution.empty()) + fun strict(): Unificator = strict(Substitution.empty()) /** * Makes another unification strategy cached, by letting memorising the most recent terms unified through it @@ -130,7 +154,10 @@ interface Unificator { */ @JvmStatic @JsName("cached") - fun cached(other: Unificator, capacity: Int = DEFAULT_CACHE_CAPACITY): Unificator = + fun cached( + other: Unificator, + capacity: Int = DEFAULT_CACHE_CAPACITY, + ): Unificator = if (other is CachedUnificator) { CachedUnificator(other.decorated, capacity) } else { diff --git a/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/exception/NoUnifyException.kt b/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/exception/NoUnifyException.kt index 0bb4fbaf1..49e3ddb95 100644 --- a/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/exception/NoUnifyException.kt +++ b/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/exception/NoUnifyException.kt @@ -5,7 +5,6 @@ import it.unibo.tuprolog.core.exception.TuPrologException open class NoUnifyException(private val term1: Term, private val term2: Term, other: Throwable?) : TuPrologException(other) { - constructor(term1: Term, term2: Term) : this(term1, term2, null) override val message: String? diff --git a/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/exception/OccurCheckException.kt b/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/exception/OccurCheckException.kt index 26a3fcc45..b9c3e39a4 100644 --- a/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/exception/OccurCheckException.kt +++ b/unify/src/commonMain/kotlin/it/unibo/tuprolog/unify/exception/OccurCheckException.kt @@ -8,9 +8,8 @@ class OccurCheckException( term2: Term, private val innerVar: Var, private val innerTerm: Term, - other: Throwable? + other: Throwable?, ) : NoUnifyException(term1, term2, other) { - constructor(term1: Term, term2: Term, innerVar: Var, innerTerm: Term) : this(term1, term2, innerVar, innerTerm, null) diff --git a/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/AbstractUnificatorTest.kt b/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/AbstractUnificatorTest.kt index c13ab1a92..1cfa4978e 100644 --- a/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/AbstractUnificatorTest.kt +++ b/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/AbstractUnificatorTest.kt @@ -26,11 +26,13 @@ import it.unibo.tuprolog.core.List.Companion as LogicList * @author Enrico */ internal class AbstractUnificatorTest { - /** A concrete strategy constructor */ private val myStrategyConstructor: (Substitution) -> Unificator = { object : AbstractUnificator(it) { - override fun checkTermsEquality(first: Term, second: Term): Boolean = first == second + override fun checkTermsEquality( + first: Term, + second: Term, + ): Boolean = first == second } } @@ -122,10 +124,11 @@ internal class AbstractUnificatorTest { val xVar = Var.of("X") val structWithX = Struct.of("f", xVar) - val correctnessMap = mapOf( - (xVar eq structWithX) to - Triple(Substitution.of(xVar, structWithX), true, structWithX) - ) + val correctnessMap = + mapOf( + (xVar eq structWithX) to + Triple(Substitution.of(xVar, structWithX), true, structWithX), + ) assertMguCorrect(correctnessMap) { term1, term2 -> myStrategy.mgu(term1, term2, false) } assertMatchCorrect(correctnessMap) { term1, term2 -> myStrategy.match(term1, term2, false) } @@ -134,24 +137,40 @@ internal class AbstractUnificatorTest { @Test fun sequenceOfEquationsSuccessUnification() { - forEquationSequence(::assertMguCorrect, UnificatorUtils.successSequenceOfUnification, myStrategyConstructor) { context, t1, t2 -> myStrategyConstructor(context).mgu(t1, t2) } + forEquationSequence( + ::assertMguCorrect, + UnificatorUtils.successSequenceOfUnification, + myStrategyConstructor, + ) { context, t1, t2 -> myStrategyConstructor(context).mgu(t1, t2) } - forEquationSequence(::assertMguCorrect, UnificatorUtils.successSequenceOfUnification, myStrategyConstructor) { context, t1, t2 -> myStrategyConstructor(context).mgu(t1, t2) } + forEquationSequence( + ::assertMguCorrect, + UnificatorUtils.successSequenceOfUnification, + myStrategyConstructor, + ) { context, t1, t2 -> myStrategyConstructor(context).mgu(t1, t2) } - forEquationSequence(::assertMatchCorrect, UnificatorUtils.successSequenceOfUnification, myStrategyConstructor) { context, t1, t2 -> myStrategyConstructor(context).match(t1, t2) } + forEquationSequence( + ::assertMatchCorrect, + UnificatorUtils.successSequenceOfUnification, + myStrategyConstructor, + ) { context, t1, t2 -> myStrategyConstructor(context).match(t1, t2) } - forEquationSequence(::assertMatchCorrect, UnificatorUtils.successSequenceOfUnification, myStrategyConstructor) { context, t1, t2 -> myStrategyConstructor(context).match(t1, t2) } + forEquationSequence( + ::assertMatchCorrect, + UnificatorUtils.successSequenceOfUnification, + myStrategyConstructor, + ) { context, t1, t2 -> myStrategyConstructor(context).match(t1, t2) } forEquationSequence( ::assertUnifiedTermCorrect, UnificatorUtils.successSequenceOfUnification, - myStrategyConstructor + myStrategyConstructor, ) { context, t1, t2 -> myStrategyConstructor(context).unify(t1, t2) } forEquationSequence( ::assertUnifiedTermCorrect, UnificatorUtils.successSequenceOfUnification, - myStrategyConstructor + myStrategyConstructor, ) { context, t1, t2 -> myStrategyConstructor(context).unify(t1, t2) } } @@ -179,24 +198,40 @@ internal class AbstractUnificatorTest { @Test fun sequenceOfEquationsFailedUnification() { - forEquationSequence(::assertMguCorrect, UnificatorUtils.failSequenceOfUnification, myStrategyConstructor) { context, t1, t2 -> myStrategyConstructor(context).mgu(t1, t2) } + forEquationSequence( + ::assertMguCorrect, + UnificatorUtils.failSequenceOfUnification, + myStrategyConstructor, + ) { context, t1, t2 -> myStrategyConstructor(context).mgu(t1, t2) } - forEquationSequence(::assertMguCorrect, UnificatorUtils.failSequenceOfUnification, myStrategyConstructor) { context, t1, t2 -> myStrategyConstructor(context).mgu(t1, t2) } + forEquationSequence( + ::assertMguCorrect, + UnificatorUtils.failSequenceOfUnification, + myStrategyConstructor, + ) { context, t1, t2 -> myStrategyConstructor(context).mgu(t1, t2) } - forEquationSequence(::assertMatchCorrect, UnificatorUtils.failSequenceOfUnification, myStrategyConstructor) { context, t1, t2 -> myStrategyConstructor(context).match(t1, t2) } + forEquationSequence( + ::assertMatchCorrect, + UnificatorUtils.failSequenceOfUnification, + myStrategyConstructor, + ) { context, t1, t2 -> myStrategyConstructor(context).match(t1, t2) } - forEquationSequence(::assertMatchCorrect, UnificatorUtils.failSequenceOfUnification, myStrategyConstructor) { context, t1, t2 -> myStrategyConstructor(context).match(t1, t2) } + forEquationSequence( + ::assertMatchCorrect, + UnificatorUtils.failSequenceOfUnification, + myStrategyConstructor, + ) { context, t1, t2 -> myStrategyConstructor(context).match(t1, t2) } forEquationSequence( ::assertUnifiedTermCorrect, UnificatorUtils.failSequenceOfUnification, - myStrategyConstructor + myStrategyConstructor, ) { context, t1, t2 -> myStrategyConstructor(context).unify(t1, t2) } forEquationSequence( ::assertUnifiedTermCorrect, UnificatorUtils.failSequenceOfUnification, - myStrategyConstructor + myStrategyConstructor, ) { context, t1, t2 -> myStrategyConstructor(context).unify(t1, t2) } } diff --git a/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/EquationTest.kt b/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/EquationTest.kt index 9b284c058..4251fc0b9 100644 --- a/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/EquationTest.kt +++ b/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/EquationTest.kt @@ -22,7 +22,6 @@ import kotlin.test.assertTrue * @author Enrico */ internal class EquationTest { - /** Correct instances of equations, whose type is recognizable without exploring in deep the components */ private val correctShallowEquationsInstances = EquationUtils.shallowIdentityEquations.map { (lhs, rhs) -> Equation.Identity(lhs, rhs) } + @@ -76,17 +75,19 @@ internal class EquationTest { fun equationOfShouldReturnCorrectNumberOfEquations() { assertEquals( EquationUtils.mixedAllEquations.count(), - EquationUtils.mixedAllEquations.map { Equation.of(it) }.count() + EquationUtils.mixedAllEquations.map { Equation.of(it) }.count(), ) } @Test fun equationOfAutomaticallySwapsAssignments() { - val correct = EquationUtils.assignmentEquations.map { (lhs, rhs) -> Equation.of(lhs, rhs) } + - EquationUtils.assignmentEquations.map { Equation.of(it) } + val correct = + EquationUtils.assignmentEquations.map { (lhs, rhs) -> Equation.of(lhs, rhs) } + + EquationUtils.assignmentEquations.map { Equation.of(it) } - val toBeTested = EquationUtils.assignmentEquationsShuffled.map { (lhs, rhs) -> Equation.of(lhs, rhs) } + - EquationUtils.assignmentEquationsShuffled.map { Equation.of(it) } + val toBeTested = + EquationUtils.assignmentEquationsShuffled.map { (lhs, rhs) -> Equation.of(lhs, rhs) } + + EquationUtils.assignmentEquationsShuffled.map { Equation.of(it) } assertEquals(correct, toBeTested) } @@ -135,8 +136,9 @@ internal class EquationTest { @Test fun equationAllOfAutomaticallySwapsAssignments() { - val correct = EquationUtils.assignmentEquations.map { (lhs, rhs) -> Equation.allOf(lhs, rhs).toList() } + - EquationUtils.assignmentEquations.map { Equation.allOf(it).toList() } + val correct = + EquationUtils.assignmentEquations.map { (lhs, rhs) -> Equation.allOf(lhs, rhs).toList() } + + EquationUtils.assignmentEquations.map { Equation.allOf(it).toList() } val toBeTested = EquationUtils.assignmentEquationsShuffled.map { (lhs, rhs) -> Equation.allOf(lhs, rhs).toList() } + @@ -168,9 +170,10 @@ internal class EquationTest { @Test fun swapCanInvertAllInvertibleEquations() { - val testableItems = EquationUtils.allIdentityEquations + - EquationUtils.allContradictionEquations + - EquationUtils.comparisonEquations + val testableItems = + EquationUtils.allIdentityEquations + + EquationUtils.allContradictionEquations + + EquationUtils.comparisonEquations val correct = testableItems.map { (lhs, rhs) -> rhs to lhs }.map { Equation.of(it) } val toBeTested = testableItems.map { Equation.of(it) }.map(Equation::swap) @@ -194,7 +197,7 @@ internal class EquationTest { assertNoIdentities( EquationUtils.mixedAllEquations.map { (lhs, rhs) -> Equation.of(lhs, rhs, { _, _ -> false }) - }.asSequence() + }.asSequence(), ) } @@ -203,7 +206,7 @@ internal class EquationTest { assertNoIdentities( EquationUtils.mixedAllEquations.map { Equation.of(it) { _, _ -> false } - }.asSequence() + }.asSequence(), ) } @@ -212,7 +215,7 @@ internal class EquationTest { assertNoIdentities( EquationUtils.mixedAllEquations.flatMap { (lhs, rhs) -> Equation.allOf(lhs, rhs, { _, _ -> false }).asIterable() - }.asSequence() + }.asSequence(), ) } @@ -221,7 +224,7 @@ internal class EquationTest { assertNoIdentities( EquationUtils.mixedAllEquations.flatMap { Equation.allOf(it) { _, _ -> false }.asIterable() - }.asSequence() + }.asSequence(), ) } @@ -256,9 +259,10 @@ internal class EquationTest { val correct = EquationUtils.assignmentEquations.map { Substitution.of(it) } @Suppress("UNCHECKED_CAST") - val toBeTested = EquationUtils.assignmentEquations - .map { Equation.of(it) } - .map { it.toSubstitution() } + val toBeTested = + EquationUtils.assignmentEquations + .map { Equation.of(it) } + .map { it.toSubstitution() } assertEquals(correct, toBeTested) } @@ -268,9 +272,10 @@ internal class EquationTest { val correct = Substitution.of(EquationUtils.assignmentEquations) @Suppress("UNCHECKED_CAST") - val toBeTested = EquationUtils.assignmentEquations - .map { Equation.of(it) } - .toSubstitution() + val toBeTested = + EquationUtils.assignmentEquations + .map { Equation.of(it) } + .toSubstitution() assertEquals(correct, toBeTested) } diff --git a/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/ListUnificationTest.kt b/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/ListUnificationTest.kt index 1cc1b2b88..a51e35006 100644 --- a/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/ListUnificationTest.kt +++ b/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/ListUnificationTest.kt @@ -10,12 +10,14 @@ class ListUnificationTest { @Test fun testListUnificationInMember() { val scope = Scope.empty() - val actual = scope.with { - structOf("member", atomOf("a"), listOf(arrayOf("a", "b", "c").map { atomOf(it) })) - } - val pattern = scope.with { - structOf("member", varOf("H"), consOf(varOf("H"), varOf("T"))) - } + val actual = + scope.with { + structOf("member", atomOf("a"), listOf(arrayOf("a", "b", "c").map { atomOf(it) })) + } + val pattern = + scope.with { + structOf("member", varOf("H"), consOf(varOf("H"), varOf("T"))) + } val mgu1 = actual mguWith pattern val mgu2 = pattern mguWith actual assertEquals(mgu1, mgu2) @@ -23,9 +25,9 @@ class ListUnificationTest { assertEquals( Substitution.unifier( varOf("H") to atomOf("a"), - varOf("T") to listOf(arrayOf("b", "c").map { atomOf(it) }) + varOf("T") to listOf(arrayOf("b", "c").map { atomOf(it) }), ), - mgu1 + mgu1, ) } } @@ -42,9 +44,9 @@ class ListUnificationTest { assertEquals( Substitution.unifier( varOf("H") to atomOf("a"), - varOf("T") to listOf(arrayOf("b", "c").map { atomOf(it) }) + varOf("T") to listOf(arrayOf("b", "c").map { atomOf(it) }), ), - mgu1 + mgu1, ) } } diff --git a/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/UnificatorTest.kt b/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/UnificatorTest.kt index a8d0b2941..93beab86e 100644 --- a/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/UnificatorTest.kt +++ b/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/UnificatorTest.kt @@ -21,7 +21,6 @@ import kotlin.test.assertEquals * @author Enrico */ internal class UnificatorTest { - private val aVar = Var.of("A") private val myExampleContext = Substitution.of("A", Atom.of("a")) diff --git a/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/testutils/EquationUtils.kt b/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/testutils/EquationUtils.kt index cba99a11f..123524b7d 100644 --- a/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/testutils/EquationUtils.kt +++ b/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/testutils/EquationUtils.kt @@ -26,7 +26,6 @@ import it.unibo.tuprolog.core.List.Companion as LogicList * @author Enrico */ internal object EquationUtils { - /** A list of equations that should immediately be interpreted as Identities, without deeper exploration */ internal val shallowIdentityEquations by lazy { listOf( @@ -41,7 +40,7 @@ internal object EquationUtils { Real.of("1.5") to Real.of("1.500"), Integer.of(0) to Integer.of(0), Var.anonymous().let { it to it }, - Scope.empty { varOf("X") to varOf("X") } + Scope.empty { varOf("X") to varOf("X") }, ) } @@ -68,7 +67,7 @@ internal object EquationUtils { }, Scope.empty { indicatorOf(atomOf("ciao"), varOf("A")) to indicatorOf(atomOf("ciao"), varOf("A")) - } + }, ) } @@ -92,7 +91,7 @@ internal object EquationUtils { Var.anonymous() to Fact.of(Struct.of("aa", Var.of("A"))), Var.anonymous() to Directive.of(Atom.of("here"), Struct.of("f", Truth.TRUE)), Var.anonymous() to Rule.of(Struct.fold("k", Var.of("A"), Var.of("A")), Truth.FALSE), - Var.anonymous() to Var.anonymous() + Var.anonymous() to Var.anonymous(), ) } @@ -116,7 +115,7 @@ internal object EquationUtils { Directive.of(Atom.of("here"), Struct.of("f", Var.of("A"))) to Directive.of(Atom.of("here"), Struct.of("f", Var.of("B"))), Rule.of(Struct.fold("k", Var.of("A"), Var.of("A")), Truth.FALSE) to - Rule.of(Struct.fold("k", Var.of("B"), Var.of("C")), Truth.FALSE) + Rule.of(Struct.fold("k", Var.of("B"), Var.of("C")), Truth.FALSE), ) } @@ -135,7 +134,7 @@ internal object EquationUtils { Atom.of("X") to Atom.of("Y"), Real.of("1.5") to Real.of("1.3"), Integer.of(0) to Integer.of(1), - Real.of(1.0) to Integer.of(1) + Real.of(1.0) to Integer.of(1), ) } @@ -151,7 +150,7 @@ internal object EquationUtils { Directive.of(Atom.of("here"), Struct.of("f", Truth.TRUE)) to Directive.of(Atom.of("here"), Struct.of("f", Truth.TRUE, Atom.of("extra"))), Rule.of(Struct.fold("k", Var.of("A"), Var.of("A")), Truth.FAIL) to - Rule.of(Struct.fold("different", Var.of("A"), Var.of("A")), Truth.FAIL) + Rule.of(Struct.fold("different", Var.of("A"), Var.of("A")), Truth.FAIL), ) } @@ -204,10 +203,11 @@ internal object EquationUtils { } /** A function to count in how many equations will be transformed a term */ - internal fun countDeepGeneratedEquations(term: Term): Int = when (term) { - is Var -> 1 - is Constant -> 1 - is Struct -> term.argsSequence.sumOf { countDeepGeneratedEquations(it) } - else -> fail("Should never be there") - } + internal fun countDeepGeneratedEquations(term: Term): Int = + when (term) { + is Var -> 1 + is Constant -> 1 + is Struct -> term.argsSequence.sumOf { countDeepGeneratedEquations(it) } + else -> fail("Should never be there") + } } diff --git a/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/testutils/UnificatorUtils.kt b/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/testutils/UnificatorUtils.kt index b6208e77b..8ec3b418c 100644 --- a/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/testutils/UnificatorUtils.kt +++ b/unify/src/commonTest/kotlin/it/unibo/tuprolog/unify/testutils/UnificatorUtils.kt @@ -36,7 +36,6 @@ private typealias CorrectnessMap = Map = Triple(Substitution.failed(), false, null) - internal val memberClause = Scope.empty { - factOf(structOf("member", varOf("H"), consOf(varOf("H"), varOf("T")))) - } + internal val memberClause = + Scope.empty { + factOf(structOf("member", varOf("H"), consOf(varOf("H"), varOf("T")))) + } - private fun member(first: Term, second: Term): kotlin.collections.List = + private fun member( + first: Term, + second: Term, + ): kotlin.collections.List = listOf( Fact.of(Struct.of("member", first, second)), - Rule.of(Struct.of("member", first, second), Var.of("B")) + Rule.of(Struct.of("member", first, second), Var.of("B")), ) internal val positiveMemberPatterns = member(Atom.of("a"), List.of(Atom.of("a"))) + member( List.of(Struct.of("a", Var.of("X"))), - List.of(List.of(Struct.of("a", Integer.of(1)))) + List.of(List.of(Struct.of("a", Integer.of(1)))), ) internal val negativeMemberPatterns = member(Atom.of("a"), List.of(Atom.of("b"))) + member( List.of(Struct.of("a", Var.of("X"))), - List.of(List.of(Struct.of("b", Integer.of(1)))) + List.of(List.of(Struct.of("b", Integer.of(1)))), ) /** Contains a mapping between equations that should have success unifying and a `Triple(mgu, isMatching, unifiedTerm)` */ @@ -75,7 +78,6 @@ internal object UnificatorUtils { *EquationUtils.allIdentityEquations.map { (lhs, rhs) -> (lhs eq rhs) to Triple(Substitution.empty(), true, lhs) }.toTypedArray(), - (aAtom eq aAtom) to Triple(Substitution.empty(), true, aAtom), (xVar eq xVar) to Triple(Substitution.empty(), true, xVar), (aAtom eq xVar) to Triple(Substitution.of(xVar, aAtom), true, aAtom), @@ -90,13 +92,13 @@ internal object UnificatorUtils { Triple( Substitution.of(yVar, Struct.of("g", xVar)), true, - Struct.of("f", Struct.of("g", xVar)) + Struct.of("f", Struct.of("g", xVar)), ), (Struct.of("f", Struct.of("g", xVar), xVar) eq Struct.of("f", yVar, aAtom)) to Triple( Substitution.of(yVar to Struct.of("g", aAtom), xVar to aAtom), true, - Struct.of("f", Struct.of("g", aAtom), aAtom) + Struct.of("f", Struct.of("g", aAtom), aAtom), ), Scope.empty { Rule.of(Struct.of("f", aAtom, Struct.of("b", varOf("X"))), bAtom) eq @@ -105,10 +107,10 @@ internal object UnificatorUtils { Substitution.of( varOf("A") to aAtom, varOf("B") to Struct.of("b", varOf("X")), - varOf("C") to bAtom + varOf("C") to bAtom, ), true, - Rule.of(Struct.of("f", aAtom, Struct.of("b", varOf("X"))), bAtom) + Rule.of(Struct.of("f", aAtom, Struct.of("b", varOf("X"))), bAtom), ) }, Scope.empty { @@ -116,10 +118,9 @@ internal object UnificatorUtils { Triple( Substitution.of(varOf("A") to Atom.of("ciao"), varOf("B") to Integer.of(2)), true, - Indicator.of("ciao", 2) + Indicator.of("ciao", 2), ) - } - + }, ) } @@ -129,11 +130,10 @@ internal object UnificatorUtils { *EquationUtils.allContradictionEquations.map { (lhs, rhs) -> (lhs eq rhs) to failedResultsTriple }.toTypedArray(), - (aAtom eq bAtom) to failedResultsTriple, (Struct.of("f", aAtom) eq Struct.of("g", aAtom)) to failedResultsTriple, (Struct.of("f", xVar) eq Struct.of("g", yVar)) to failedResultsTriple, - (Struct.of("f", xVar) eq Struct.of("f", yVar, Var.of("Z"))) to failedResultsTriple + (Struct.of("f", xVar) eq Struct.of("f", yVar, Var.of("Z"))) to failedResultsTriple, ) } @@ -141,7 +141,7 @@ internal object UnificatorUtils { internal val occurCheckFailedUnifications by lazy { mapOf( (xVar eq Struct.of("f", xVar)) to failedResultsTriple, - (xVar eq LogicList.from(listOf(aAtom, bAtom), xVar)) to failedResultsTriple + (xVar eq LogicList.from(listOf(aAtom, bAtom), xVar)) to failedResultsTriple, ) } @@ -153,7 +153,7 @@ internal object UnificatorUtils { listOf(aAtom eq yVar, xVar eq yVar) to Triple(Substitution.of(xVar to aAtom, yVar to aAtom), true, aAtom), listOf(aAtom eq yVar, xVar eq yVar, xVar eq aAtom) to - Triple(Substitution.of(xVar to aAtom, yVar to aAtom), true, aAtom) + Triple(Substitution.of(xVar to aAtom, yVar to aAtom), true, aAtom), ) } @@ -164,81 +164,95 @@ internal object UnificatorUtils { listOf(xVar eq aAtom, bAtom eq xVar, yVar eq aAtom) to failedResultsTriple, listOf(aAtom eq yVar, xVar eq yVar, xVar eq bAtom) to failedResultsTriple, listOf(xVar eq Struct.of("f", yVar, xVar), yVar eq Struct.of("f", xVar, yVar)) to failedResultsTriple, - listOf(xVar eq Struct.of("f", yVar), yVar eq Struct.of("f", xVar), aAtom eq bAtom) to failedResultsTriple + listOf(xVar eq Struct.of("f", yVar), yVar eq Struct.of("f", xVar), aAtom eq bAtom) to failedResultsTriple, ) } /** Asserts that mgu computed with [mguStrategy] over [equation] is equals to [expectedMgu] */ - internal inline fun assertMguCorrect(equation: Equation, expectedMgu: Substitution, mguStrategy: MguStrategy) { + internal inline fun assertMguCorrect( + equation: Equation, + expectedMgu: Substitution, + mguStrategy: MguStrategy, + ) { val (equationLhs, equationRhs) = equation.toPair() assertEquals( expectedMgu, mguStrategy(equationLhs, equationRhs), - "$equationLhs=$equationRhs mgu?" + "$equationLhs=$equationRhs mgu?", ) } /** Asserts that mgu computed with [mguStrategy] over [correctnessMap] keys are equals to those present in [correctnessMap] values */ - internal inline fun assertMguCorrect(correctnessMap: CorrectnessMap, mguStrategy: MguStrategy) = - correctnessMap.forEach { (equation, correctTriple) -> - assertMguCorrect( - equation, - correctTriple.first, - mguStrategy - ) - } + internal inline fun assertMguCorrect( + correctnessMap: CorrectnessMap, + mguStrategy: MguStrategy, + ) = correctnessMap.forEach { (equation, correctTriple) -> + assertMguCorrect( + equation, + correctTriple.first, + mguStrategy, + ) + } /** Asserts that match computed with [matchStrategy] over [equation] is equals to [expectedMatch] */ - internal inline fun assertMatchCorrect(equation: Equation, expectedMatch: Boolean, matchStrategy: MatchStrategy) { + internal inline fun assertMatchCorrect( + equation: Equation, + expectedMatch: Boolean, + matchStrategy: MatchStrategy, + ) { val (equationLhs, equationRhs) = equation.toPair() assertEquals( expectedMatch, matchStrategy(equationLhs, equationRhs), - "$equationLhs=$equationRhs match?" + "$equationLhs=$equationRhs match?", ) } /** Asserts that matching computed with [matchStrategy] over [correctnessMap] keys are equals to those present in [correctnessMap] values */ - internal inline fun assertMatchCorrect(correctnessMap: CorrectnessMap, matchStrategy: MatchStrategy) = - correctnessMap.forEach { (equation, correctTriple) -> - assertMatchCorrect( - equation, - correctTriple.second, - matchStrategy - ) - } + internal inline fun assertMatchCorrect( + correctnessMap: CorrectnessMap, + matchStrategy: MatchStrategy, + ) = correctnessMap.forEach { (equation, correctTriple) -> + assertMatchCorrect( + equation, + correctTriple.second, + matchStrategy, + ) + } /** Asserts that unified term computed with [unifyStrategy] over [equation] is equals to [expectedUnifiedTerm] */ internal inline fun assertUnifiedTermCorrect( equation: Equation, expectedUnifiedTerm: Term?, - unifyStrategy: UnifyStrategy + unifyStrategy: UnifyStrategy, ) { val (equationLhs, equationRhs) = equation.toPair() assertEquals( expectedUnifiedTerm, unifyStrategy(equationLhs, equationRhs), - "$equationLhs=$equationRhs unify?" + "$equationLhs=$equationRhs unify?", ) } /** Asserts that unified term computed with [unifyStrategy] over [correctnessMap] keys are equals to those present in [correctnessMap] values */ - internal inline fun assertUnifiedTermCorrect(correctnessMap: CorrectnessMap, unifyStrategy: UnifyStrategy) = - correctnessMap.forEach { (equation, correctTriple) -> - assertUnifiedTermCorrect( - equation, - correctTriple.third, - unifyStrategy - ) - } + internal inline fun assertUnifiedTermCorrect( + correctnessMap: CorrectnessMap, + unifyStrategy: UnifyStrategy, + ) = correctnessMap.forEach { (equation, correctTriple) -> + assertUnifiedTermCorrect( + equation, + correctTriple.third, + unifyStrategy, + ) + } /** Utility function to calculate the unifier for more than one equation, passing created context through different unification */ private inline fun multipleEquationMgu( equations: KtList, - unificationStrategyConstructor: (Substitution) -> Unificator + unificationStrategyConstructor: (Substitution) -> Unificator, ): Substitution { var context: Substitution = Substitution.empty() @@ -261,7 +275,7 @@ internal object UnificatorUtils { lastEquationAssertion: (CorrectnessMap, (T1, T2) -> O) -> Unit, correctnessMap: Map, Triple>, unificationStrategyConstructor: (Substitution) -> Unificator, - crossinline unificationStrategyUse: (Substitution, T1, T2) -> O + crossinline unificationStrategyUse: (Substitution, T1, T2) -> O, ) { correctnessMap.forEach { (equations, correctTriple) -> val context = multipleEquationMgu(equations.dropLast(1), unificationStrategyConstructor) diff --git a/unify/src/jvmTest/kotlin/it/unibo/tuprolog/unify/TestThreadSafety.kt b/unify/src/jvmTest/kotlin/it/unibo/tuprolog/unify/TestThreadSafety.kt index 84f460bc0..0469b5823 100644 --- a/unify/src/jvmTest/kotlin/it/unibo/tuprolog/unify/TestThreadSafety.kt +++ b/unify/src/jvmTest/kotlin/it/unibo/tuprolog/unify/TestThreadSafety.kt @@ -16,12 +16,12 @@ class TestThreadSafety { val executors = Executors.newFixedThreadPool(8) val results: MutableList> = Collections.synchronizedList(LinkedList()) val unificator = Unificator.cached(Unificator.strict()) - for (i in 1..100) { + repeat(100) { for (equation in successfulUnifications.keys) { results.add( executors.submit { unificator.mgu(equation.lhs, equation.rhs) - } + }, ) } } diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Cache.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Cache.kt index fd0f61995..3f88b1d85 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Cache.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Cache.kt @@ -9,7 +9,6 @@ import it.unibo.tuprolog.utils.impl.SimpleLRUCache * @param V is the type of the values stored in this cache */ interface Cache { - /** * Retrieves the maximum amount of items this cache may ever store */ @@ -26,7 +25,10 @@ interface Cache { * @param value is the value corresponding to [key] * @return the evicted key-value pair, if any */ - operator fun set(key: K, value: V): Optional> + operator fun set( + key: K, + value: V, + ): Optional> /** * Retrieves the cached value corresponding to the provided [key] @@ -41,7 +43,10 @@ interface Cache { * @param valueGenerator is the function aimed at generating the value to be cached * @return the value corresponding to [key], if any, or the value produced by [valueGenerator] otherwise */ - fun getOrSet(key: K, valueGenerator: () -> V): V = + fun getOrSet( + key: K, + valueGenerator: () -> V, + ): V = when (val got = get(key)) { is Optional.Some -> got.value else -> { diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Castable.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Castable.kt index 58f4a3c51..423ef0f23 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Castable.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Castable.kt @@ -16,5 +16,6 @@ interface Castable> { * Casts the current object to [U], if possible, or returns `null` otherwise * @return the current object, casted to [U], or `null`, if the current object is not an instance of [U] */ + @Suppress("ktlint:standard:function-naming") fun `as`(): U? = this as? U } diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Cursor.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Cursor.kt index c3cad36e6..029624797 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Cursor.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Cursor.kt @@ -33,7 +33,6 @@ interface Cursor { fun asSequence(): Sequence = Sequence { iterator() } companion object { - @JvmStatic @JsName("of") fun of(iterator: Iterator): Cursor { diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Deque.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Deque.kt index 3bfae08c3..70792f22e 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Deque.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Deque.kt @@ -10,6 +10,7 @@ expect fun dequeOf(items: Iterable): MutableList expect fun dequeOf(items: Sequence): MutableList +@Suppress("EXTENSION_SHADOWED_BY_MEMBER") expect fun MutableList.addFirst(item: T) expect fun MutableList.addFirst(items: Iterable) diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/IntIndexed.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/IntIndexed.kt index 8467b1ffe..f62c9ffdd 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/IntIndexed.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/IntIndexed.kt @@ -3,7 +3,6 @@ package it.unibo.tuprolog.utils import it.unibo.tuprolog.utils.impl.IntIndexedImpl interface IntIndexed : Indexed, Comparable> { - override fun compareTo(other: IntIndexed): Int { return index - other.index } @@ -11,7 +10,10 @@ interface IntIndexed : Indexed, Comparable> { override fun map(mapper: (T) -> R): IntIndexed companion object { - fun of(index: Int, value: T): IntIndexed { + fun of( + index: Int, + value: T, + ): IntIndexed { return IntIndexedImpl(index, value) } } diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/IterUtils.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/IterUtils.kt index 275e64af7..c676b261b 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/IterUtils.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/IterUtils.kt @@ -4,13 +4,17 @@ package it.unibo.tuprolog.utils import kotlin.jvm.JvmName -fun merge(comparator: Comparator, iterables: Iterable>): Sequence { +fun merge( + comparator: Comparator, + iterables: Iterable>, +): Sequence { return sequence { val pipeline = iterables.asSequence().map { it.cursor() }.filterNot { it.isOver }.toMutableList() while (pipeline.isNotEmpty()) { - val (minIndex, minValue) = pipeline.asSequence().map { it.current!! }.indexed().minWithOrNull( - Comparator { a, b -> comparator.compare(a.value, b.value) } - )!! + val (minIndex, minValue) = + pipeline.asSequence().map { it.current!! }.indexed().minWithOrNull( + Comparator { a, b -> comparator.compare(a.value, b.value) }, + )!! yield(minValue) pipeline[minIndex].next.let { if (it.isOver) { @@ -23,63 +27,96 @@ fun merge(comparator: Comparator, iterables: Iterable>): Sequ } } -fun merge(iterables: Iterable>, comparator: (T, T) -> Int): Sequence { +fun merge( + iterables: Iterable>, + comparator: (T, T) -> Int, +): Sequence { return merge(Comparator(comparator), iterables) } -fun merge(vararg iterables: Iterable, comparator: (T, T) -> Int): Sequence { +fun merge( + vararg iterables: Iterable, + comparator: (T, T) -> Int, +): Sequence { return merge(Comparator(comparator), *iterables) } -fun merge(comparator: Comparator, vararg iterables: Iterable): Sequence { +fun merge( + comparator: Comparator, + vararg iterables: Iterable, +): Sequence { return merge(comparator, listOf(*iterables)) } -fun merge(iterables: Sequence>, comparator: (T, T) -> Int): Sequence { +fun merge( + iterables: Sequence>, + comparator: (T, T) -> Int, +): Sequence { return merge(Comparator(comparator), iterables) } -fun merge(comparator: Comparator, iterables: Sequence>): Sequence { +fun merge( + comparator: Comparator, + iterables: Sequence>, +): Sequence { return merge(comparator, iterables.asIterable()) } -fun mergeSequences(iterables: Iterable>, comparator: (T, T) -> Int): Sequence { +fun mergeSequences( + iterables: Iterable>, + comparator: (T, T) -> Int, +): Sequence { return merge(Comparator(comparator), iterables.map { it.asIterable() }) } -fun mergeSequences(comparator: Comparator, iterables: Iterable>): Sequence { +fun mergeSequences( + comparator: Comparator, + iterables: Iterable>, +): Sequence { return merge(comparator, iterables.map { it.asIterable() }) } -fun mergeSequences(iterables: Sequence>, comparator: (T, T) -> Int): Sequence { +fun mergeSequences( + iterables: Sequence>, + comparator: (T, T) -> Int, +): Sequence { return merge(Comparator(comparator), iterables.map { it.asIterable() }.asIterable()) } -fun mergeSequences(comparator: Comparator, iterables: Sequence>): Sequence { +fun mergeSequences( + comparator: Comparator, + iterables: Sequence>, +): Sequence { return merge(comparator, iterables.map { it.asIterable() }.asIterable()) } -fun mergeSequences(vararg iterables: Sequence, comparator: (T, T) -> Int): Sequence { +fun mergeSequences( + vararg iterables: Sequence, + comparator: (T, T) -> Int, +): Sequence { return merge(Comparator(comparator), iterables.map { it.asIterable() }) } -fun mergeSequences(comparator: Comparator, vararg iterables: Sequence): Sequence { +fun mergeSequences( + comparator: Comparator, + vararg iterables: Sequence, +): Sequence { return merge(comparator, iterables.map { it.asIterable() }) } -fun Sequence.product(other: Sequence, combinator: (T, U) -> R): Sequence = +fun Sequence.product( + other: Sequence, + combinator: (T, U) -> R, +): Sequence = flatMap { x -> other.map { y -> combinator(x, y) } } -fun Sequence.product(other: Sequence): Sequence> = - product(other, ::Pair) +fun Sequence.product(other: Sequence): Sequence> = product(other, ::Pair) -fun Sequence.squared(combinator: (T, T) -> R): Sequence = - product(this, combinator) +fun Sequence.squared(combinator: (T, T) -> R): Sequence = product(this, combinator) -fun Sequence.squared(): Sequence> = - product(this) +fun Sequence.squared(): Sequence> = product(this) fun Sequence.longIndexed(): Sequence> = zip(LongRange(0, Long.MAX_VALUE).asSequence()) { it, i -> @@ -93,10 +130,11 @@ fun Sequence.indexed(): Sequence> = fun interleave(iterables: Iterable>): Sequence = sequence { - val pipeline = iterables.asSequence() - .map { it.iterator() } - .filter { it.hasNext() } - .toList() + val pipeline = + iterables.asSequence() + .map { it.iterator() } + .filter { it.hasNext() } + .toList() var nNonEmpty = pipeline.size while (nNonEmpty > 0) { nNonEmpty = 0 @@ -109,20 +147,26 @@ fun interleave(iterables: Iterable>): Sequence = } } -fun interleave(vararg iterables: Iterable): Sequence = - interleave(iterables.asIterable()) +fun interleave(vararg iterables: Iterable): Sequence = interleave(iterables.asIterable()) -fun interleave(iterables: Sequence>): Sequence = - interleave(iterables.asIterable()) +fun interleave(iterables: Sequence>): Sequence = interleave(iterables.asIterable()) fun interleaveSequences(vararg iterables: Sequence): Sequence = interleave(sequenceOf(*iterables).map { it.asIterable() }.asIterable()) fun interleaveSequences(iterables: Sequence>): Sequence = - interleave(iterables.map { it.asIterable() }.asIterable()) + interleave( + iterables.map { + it.asIterable() + }.asIterable(), + ) fun interleaveSequences(iterables: Iterable>): Sequence = - interleave(iterables.map { it.asIterable() }) + interleave( + iterables.map { + it.asIterable() + }, + ) fun Sequence.subsequences(): Sequence> { return sequence { @@ -140,7 +184,11 @@ fun Sequence.subsequences(): Sequence> { } } -fun itemWiseEquals(iterable1: Iterable, iterable2: Iterable, comparator: (T, T) -> Boolean): Boolean { +fun itemWiseEquals( + iterable1: Iterable, + iterable2: Iterable, + comparator: (T, T) -> Boolean, +): Boolean { val i = iterable1.iterator() val j = iterable2.iterator() while (i.hasNext() && j.hasNext()) { @@ -153,16 +201,26 @@ fun itemWiseEquals(iterable1: Iterable, iterable2: Iterable, comparato return i.hasNext() == j.hasNext() } -fun itemWiseEquals(iterable1: Iterable, iterable2: Iterable): Boolean = +fun itemWiseEquals( + iterable1: Iterable, + iterable2: Iterable, +): Boolean = itemWiseEquals(iterable1, iterable2) { a, b -> a == b } -fun itemWiseEquals(sequence1: Sequence, sequence2: Sequence, comparator: (T, T) -> Boolean): Boolean { +fun itemWiseEquals( + sequence1: Sequence, + sequence2: Sequence, + comparator: (T, T) -> Boolean, +): Boolean { return itemWiseEquals(sequence1.asIterable(), sequence2.asIterable(), comparator) } -fun itemWiseEquals(sequence1: Sequence, sequence2: Sequence): Boolean { +fun itemWiseEquals( + sequence1: Sequence, + sequence2: Sequence, +): Boolean { return itemWiseEquals(sequence1.asIterable(), sequence2.asIterable()) } @@ -215,14 +273,11 @@ fun Sequence.skipIndex(index: Int): Sequence { } } -fun permutations(vararg items: T): Sequence> = - items.toList().permutations() +fun permutations(vararg items: T): Sequence> = items.toList().permutations() -fun Iterable.permutations(): Sequence> = - toList().permutations() +fun Iterable.permutations(): Sequence> = toList().permutations() -fun Sequence.permutations(): Sequence> = - toList().permutations() +fun Sequence.permutations(): Sequence> = toList().permutations() fun List.permutations(): Sequence> = when (size) { @@ -239,22 +294,28 @@ fun List.permutations(): Sequence> = } } -fun Sequence.insertAt(index: Int, item: T, vararg items: T): Sequence = sequence { - for ((i, x) in withIndex().asIterable()) { - if (i == index) { - yield(item) - yieldAll(items.asIterable()) +fun Sequence.insertAt( + index: Int, + item: T, + vararg items: T, +): Sequence = + sequence { + for ((i, x) in withIndex().asIterable()) { + if (i == index) { + yield(item) + yieldAll(items.asIterable()) + } + yield(x) } - yield(x) } -} -fun Sequence.dropLast(): Sequence = sequence { - val i = iterator() - while (i.hasNext()) { - val current = i.next() - if (i.hasNext()) { - yield(current) +fun Sequence.dropLast(): Sequence = + sequence { + val i = iterator() + while (i.hasNext()) { + val current = i.next() + if (i.hasNext()) { + yield(current) + } } } -} diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/LongIndexed.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/LongIndexed.kt index d55a5a601..2c2a0ed8c 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/LongIndexed.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/LongIndexed.kt @@ -3,7 +3,6 @@ package it.unibo.tuprolog.utils import it.unibo.tuprolog.utils.impl.LongIndexedImpl interface LongIndexed : Indexed, Comparable> { - override fun compareTo(other: LongIndexed): Int { return (index - other.index).toInt() } @@ -11,7 +10,10 @@ interface LongIndexed : Indexed, Comparable> { override fun map(mapper: (T) -> R): LongIndexed companion object { - fun of(index: Long, value: T): LongIndexed { + fun of( + index: Long, + value: T, + ): LongIndexed { return LongIndexedImpl(index, value) } } diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Optional.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Optional.kt index 2a6f23b33..b4f414d48 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Optional.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Optional.kt @@ -1,7 +1,6 @@ package it.unibo.tuprolog.utils sealed class Optional { - companion object { fun some(value: T): Some = Some(value) @@ -19,8 +18,7 @@ sealed class Optional { override val isPresent: Boolean get() = true - override fun map(function: (T) -> R): Some = - Some(function(value)) + override fun map(function: (T) -> R): Some = Some(function(value)) override fun filter(predicate: (T) -> Boolean): Optional = when { @@ -28,11 +26,9 @@ sealed class Optional { else -> None } - override fun toSequence(): Sequence = - sequenceOf(value) + override fun toSequence(): Sequence = sequenceOf(value) - override fun toString(): String = - "Some($value)" + override fun toString(): String = "Some($value)" } object None : Optional() { @@ -42,17 +38,13 @@ sealed class Optional { override val isPresent: Boolean get() = false - override fun map(function: (Nothing) -> R): None = - None + override fun map(function: (Nothing) -> R): None = None - override fun filter(predicate: (Nothing) -> Boolean): None = - None + override fun filter(predicate: (Nothing) -> Boolean): None = None - override fun toSequence(): Sequence = - emptySequence() + override fun toSequence(): Sequence = emptySequence() - override fun toString(): String = - "None" + override fun toString(): String = "None" } abstract val value: T? diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Taggables.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Taggables.kt index 36dcb14aa..88bab0aa5 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Taggables.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/Taggables.kt @@ -7,11 +7,16 @@ import kotlin.js.JsName import kotlin.jvm.JvmName @JsName("addTag") -fun , X : Any> T.addTag(name: String, value: X): T = addTags(name to value) +fun , X : Any> T.addTag( + name: String, + value: X, +): T = addTags(name to value) @JsName("addTagPairs") -fun , X : Any> T.addTags(tag: Pair, vararg otherTags: Pair): T = - this.addTags(mapOf(tag, *otherTags)) +fun , X : Any> T.addTags( + tag: Pair, + vararg otherTags: Pair, +): T = this.addTags(mapOf(tag, *otherTags)) @JsName("plusTag") operator fun , X : Any> T.plus(tag: Pair): T = addTags(tag) @@ -26,12 +31,16 @@ operator fun , X : Any> T.plus(tags: Map): T = fun , X : Any> T.setTags(tags: Map): T = replaceTags(tags) as T @JsName("setTagPairs") -fun , X : Any> T.setTags(tag: Pair, vararg otherTags: Pair): T = - setTags(mapOf(tag, *otherTags)) +fun , X : Any> T.setTags( + tag: Pair, + vararg otherTags: Pair, +): T = setTags(mapOf(tag, *otherTags)) @JsName("setTag") -fun , X : Any> T.setTag(key: String, value: X): T = - setTags(tags.toMutableMap().also { it[key] = value }) +fun , X : Any> T.setTag( + key: String, + value: X, +): T = setTags(tags.toMutableMap().also { it[key] = value }) @JsName("clearTags") fun > T.clearTags(): T = setTags(emptyMap()) diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/ThreadSafety.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/ThreadSafety.kt index 5a77b0566..3f390ecf8 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/ThreadSafety.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/ThreadSafety.kt @@ -4,6 +4,9 @@ package it.unibo.tuprolog.utils import kotlin.jvm.JvmName -expect fun synchronizedOn(obj: Any, action: () -> T): T +expect fun synchronizedOn( + obj: Any, + action: () -> T, +): T fun T.synchronizedOnSelf(action: () -> R): R = synchronizedOn(this, action) diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/AbstractSearchStrategy.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/AbstractSearchStrategy.kt index f1cd0b596..aabf6519a 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/AbstractSearchStrategy.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/AbstractSearchStrategy.kt @@ -4,7 +4,6 @@ import it.unibo.tuprolog.utils.dequeOf import it.unibo.tuprolog.utils.takeFirst abstract class AbstractSearchStrategy(override val initialState: S) : SearchStrategy { - private class InitialNode : Node { override val value: T get() = throw NoSuchElementException() @@ -17,7 +16,7 @@ abstract class AbstractSearchStrategy(override val initialState: S) : S override val source: Node, override val destination: Node, override val weight: W?, - val visited: Boolean = false + val visited: Boolean = false, ) : Edge { constructor(state: S, edge: Edge, visited: Boolean = false) : this(state, edge.source, edge.destination, edge.weight, visited) @@ -25,11 +24,18 @@ abstract class AbstractSearchStrategy(override val initialState: S) : S fun toVisit(): Visit = Visit.of(state, destination) } - final override fun search(graph: Graph, source: Node): Sequence> = sequence { - search(graph, dequeOf(Traversal(initialState, initialNode, source, null, false))) - } + final override fun search( + graph: Graph, + source: Node, + ): Sequence> = + sequence { + search(graph, dequeOf(Traversal(initialState, initialNode, source, null, false))) + } - private suspend fun SequenceScope>.search(graph: Graph, fringe: MutableList>) { + private suspend fun SequenceScope>.search( + graph: Graph, + fringe: MutableList>, + ) { var current = fringe.takeFirst() while (current != null) { selectNextVisit(graph, current, fringe)?.let { yield(it) } @@ -40,7 +46,7 @@ abstract class AbstractSearchStrategy(override val initialState: S) : S protected abstract fun selectNextVisit( graph: Graph, lastTraversal: Traversal, - fringe: MutableList> + fringe: MutableList>, ): Visit? protected val Node.isInitial: Boolean diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/BreadthFirst.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/BreadthFirst.kt index 6f16d1b42..2b831fab8 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/BreadthFirst.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/BreadthFirst.kt @@ -4,7 +4,7 @@ class BreadthFirst(private val maxDepth: Int = -1) : AbstractSearchStrateg override fun selectNextVisit( graph: Graph, lastTraversal: Traversal, - fringe: MutableList> + fringe: MutableList>, ): Visit? { if (maxDepth > 0 && lastTraversal.state > maxDepth) return null expandFringe(graph, lastTraversal, fringe) @@ -14,12 +14,12 @@ class BreadthFirst(private val maxDepth: Int = -1) : AbstractSearchStrateg private fun expandFringe( graph: Graph, lastTraversal: Traversal, - fringe: MutableList> + fringe: MutableList>, ) { fringe.addAll( graph.outgoingEdges(lastTraversal.destination).map { Traversal(lastTraversal.state + 1, it) - } + }, ) } } diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/DepthFirst.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/DepthFirst.kt index 8e7ba17ba..7af6355a4 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/DepthFirst.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/DepthFirst.kt @@ -4,12 +4,12 @@ import it.unibo.tuprolog.utils.addFirst class DepthFirst( private val maxDepth: Int = -1, - private val postOrder: Boolean = false + private val postOrder: Boolean = false, ) : AbstractSearchStrategy(0) { override fun selectNextVisit( graph: Graph, lastTraversal: Traversal, - fringe: MutableList> + fringe: MutableList>, ): Visit? { if (maxDepth > 0 && lastTraversal.state > maxDepth) return null if (lastTraversal.visited) return lastTraversal.toVisit() @@ -26,12 +26,12 @@ class DepthFirst( graph: Graph, lastTraversal: Traversal, fringe: MutableList>, - vararg others: Traversal + vararg others: Traversal, ) { fringe.addFirst( graph.outgoingEdges(lastTraversal.destination).map { Traversal(lastTraversal.state + 1, it, false) - } + others + } + others, ) } } diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/Edge.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/Edge.kt index 2d6eabf05..71dea32b5 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/Edge.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/Edge.kt @@ -6,7 +6,6 @@ import kotlin.jvm.JvmOverloads import kotlin.jvm.JvmStatic interface Edge { - @JsName("source") val source: Node @@ -20,7 +19,10 @@ interface Edge { @JsName("of") @JvmStatic @JvmOverloads - fun of(source: Node, destination: Node, weight: W? = null): Edge = - EdgeImpl(source, destination, weight) + fun of( + source: Node, + destination: Node, + weight: W? = null, + ): Edge = EdgeImpl(source, destination, weight) } } diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/Graph.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/Graph.kt index 332f9c461..1a5468e56 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/Graph.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/Graph.kt @@ -24,7 +24,10 @@ interface Graph : Iterable> { operator fun contains(edge: Edge): Boolean @JsName("containsEdgeAmong") - fun containsEdgeAmong(node1: Node, node2: Node): Boolean + fun containsEdgeAmong( + node1: Node, + node2: Node, + ): Boolean @JsName("toMutable") fun toMutable(): MutableGraph @@ -45,10 +48,16 @@ interface Graph : Iterable> { operator fun minus(edge: Edge): Graph @JsName("asIterable") - fun asIterable(searchStrategy: SearchStrategy, initialNode: Node): Iterable> + fun asIterable( + searchStrategy: SearchStrategy, + initialNode: Node, + ): Iterable> @JsName("asSequence") - fun asSequence(searchStrategy: SearchStrategy, initialNode: Node): Sequence> + fun asSequence( + searchStrategy: SearchStrategy, + initialNode: Node, + ): Sequence> @JsName("outgoingEdges") fun outgoingEdges(from: Node): Iterable> @@ -69,7 +78,10 @@ interface Graph : Iterable> { MutableGraph.build(builder).toImmutable() @JsName("of") - fun of(edge: Edge, vararg edges: Edge): Graph = of(listOf(edge, *edges)) + fun of( + edge: Edge, + vararg edges: Edge, + ): Graph = of(listOf(edge, *edges)) @JsName("empty") fun empty(): Graph = of(emptyList()) diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/Graphs.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/Graphs.kt index 445864ccc..03773ee15 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/Graphs.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/Graphs.kt @@ -9,10 +9,17 @@ import kotlin.jvm.JvmName fun nodeOf(value: T): Node = Node.of(value) @JsName("edge") -fun edgeOf(node1: Node, node2: Node, weight: W? = null): Edge = Edge.of(node1, node2, weight) +fun edgeOf( + node1: Node, + node2: Node, + weight: W? = null, +): Edge = Edge.of(node1, node2, weight) @JsName("visitOf") -fun visitOf(state: S, node: Node): Visit = Visit.of(state, node) +fun visitOf( + state: S, + node: Node, +): Visit = Visit.of(state, node) @JsName("isLeaf") fun Graph.isLeaf(node: Node): Boolean = outdegree(node) == 0 @@ -22,12 +29,10 @@ fun Graph.map(f: (Edge) -> Edge): Graph Graph.of(this.asSequence().map(f)) @JsName("filter") -fun Graph.filter(p: (Edge) -> Boolean): Graph = - Graph.of(this.asSequence().filter(p)) +fun Graph.filter(p: (Edge) -> Boolean): Graph = Graph.of(this.asSequence().filter(p)) @JsName("copy") -fun Graph.copy(f: MutableGraph.() -> Unit): Graph = - toMutable().also(f).toImmutable() +fun Graph.copy(f: MutableGraph.() -> Unit): Graph = toMutable().also(f).toImmutable() val Graph.isTree: Boolean get() = nodes.all { indegree(it) <= 1 } diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/MutableGraph.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/MutableGraph.kt index 7dd14127e..ca7b482e7 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/MutableGraph.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/MutableGraph.kt @@ -5,7 +5,6 @@ import kotlin.js.JsName import kotlin.jvm.JvmStatic interface MutableGraph : Graph { - @JsName("clone") fun clone(): MutableGraph @@ -37,17 +36,24 @@ interface MutableGraph : Graph { override fun minus(edge: Edge): MutableGraph @JsName("set") - operator fun set(edge: Pair, Node>, weight: W) + operator fun set( + edge: Pair, Node>, + weight: W, + ) @JsName("connect") - fun connect(node1: Node, node2: Node, weight: W? = null, bidirectional: Boolean = false) + fun connect( + node1: Node, + node2: Node, + weight: W? = null, + bidirectional: Boolean = false, + ) fun remove(node: Node) fun remove(edge: Edge) companion object { - @JsName("build") @JvmStatic fun build(builder: MutableGraph.() -> Unit): MutableGraph = @@ -58,7 +64,10 @@ interface MutableGraph : Graph { fun empty(): MutableGraph = MutableGraphImpl() @JsName("of") - fun of(edge: Edge, vararg edges: Edge): MutableGraph = of(listOf(edge, *edges)) + fun of( + edge: Edge, + vararg edges: Edge, + ): MutableGraph = of(listOf(edge, *edges)) @JsName("ofIterable") fun of(edges: Iterable>): MutableGraph = MutableGraphImpl(edges) diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/SearchStrategy.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/SearchStrategy.kt index bb369092c..a97d7a1cf 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/SearchStrategy.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/SearchStrategy.kt @@ -3,10 +3,12 @@ package it.unibo.tuprolog.utils.graphs import kotlin.js.JsName interface SearchStrategy { - @JsName("initialState") val initialState: S @JsName("search") - fun search(graph: Graph, source: Node): Sequence> + fun search( + graph: Graph, + source: Node, + ): Sequence> } diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/Visit.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/Visit.kt index a03e20fa2..0feb45830 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/Visit.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/Visit.kt @@ -14,6 +14,9 @@ interface Visit { companion object { @JsName("of") @JvmStatic - fun of(state: S, node: Node): Visit = VisitImpl(state, node) + fun of( + state: S, + node: Node, + ): Visit = VisitImpl(state, node) } } diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/impl/AbstractGraph.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/impl/AbstractGraph.kt index f53f68119..69c4f55c2 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/impl/AbstractGraph.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/impl/AbstractGraph.kt @@ -8,9 +8,8 @@ import it.unibo.tuprolog.utils.graphs.SearchStrategy import it.unibo.tuprolog.utils.graphs.Visit internal abstract class AbstractGraph> protected constructor( - protected val connections: MutableMap, MutableMap, W?>> + protected val connections: MutableMap, MutableMap, W?>>, ) : Graph { - companion object { private fun MutableMap, MutableMap, W?>>.putEdge(edge: Edge) { val destination = edge.destination @@ -34,12 +33,16 @@ internal abstract class AbstractGraph> pr for (edge in edges) { it.putEdge(edge) } - } + }, ) protected fun node(value: T): Node = Node.of(value) - protected fun edge(node1: Node, node2: Node, weight: W?): Edge = Edge.of(node1, node2, weight) + protected fun edge( + node1: Node, + node2: Node, + weight: W?, + ): Edge = Edge.of(node1, node2, weight) protected fun removeEdge(edge: Edge) { connections[edge.source]?.remove(edge.destination) @@ -69,21 +72,24 @@ internal abstract class AbstractGraph> pr @Suppress("MemberVisibilityCanBePrivate") protected val lazyEdges: Sequence> - get() = sequence { - for ((node1, connectedNodes) in connections) { - for ((node2, weight) in connectedNodes) { - yield(edge(node1, node2, weight)) + get() = + sequence { + for ((node1, connectedNodes) in connections) { + for ((node2, weight) in connectedNodes) { + yield(edge(node1, node2, weight)) + } } } - } override fun get(edge: Pair, Node>): W? = connections[edge.first]?.get(edge.second) override val size: Int get() = connections.size - override fun containsEdgeAmong(node1: Node, node2: Node): Boolean = - connections[node1]?.containsKey(node2) == true + override fun containsEdgeAmong( + node1: Node, + node2: Node, + ): Boolean = connections[node1]?.containsKey(node2) == true override fun contains(edge: Edge): Boolean = connections[edge.source]?.let { @@ -110,11 +116,15 @@ internal abstract class AbstractGraph> pr "${it.source.value} -${it.weight ?: ""}-> ${it.destination.value}" } - override fun asIterable(searchStrategy: SearchStrategy, initialNode: Node): Iterable> = - asSequence(searchStrategy, initialNode).asIterable() + override fun asIterable( + searchStrategy: SearchStrategy, + initialNode: Node, + ): Iterable> = asSequence(searchStrategy, initialNode).asIterable() - override fun asSequence(searchStrategy: SearchStrategy, initialNode: Node): Sequence> = - searchStrategy.search(this, initialNode) + override fun asSequence( + searchStrategy: SearchStrategy, + initialNode: Node, + ): Sequence> = searchStrategy.search(this, initialNode) override fun toMutable(): MutableGraph = MutableGraphImpl(connections) @@ -130,8 +140,7 @@ internal abstract class AbstractGraph> pr override fun indegree(to: Node): Int = connections.asSequence().filter { (_, destinations) -> to in destinations }.count() - override fun outdegree(from: Node): Int = - connections[from]?.size ?: 0 + override fun outdegree(from: Node): Int = connections[from]?.size ?: 0 protected abstract fun newInstance(connections: MutableMap, MutableMap, W?>>): Self diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/impl/EdgeImpl.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/impl/EdgeImpl.kt index ef80c6f92..cdff6f5cf 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/impl/EdgeImpl.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/impl/EdgeImpl.kt @@ -6,5 +6,5 @@ import it.unibo.tuprolog.utils.graphs.Node internal data class EdgeImpl( override val source: Node, override val destination: Node, - override val weight: W? + override val weight: W?, ) : Edge diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/impl/GraphImpl.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/impl/GraphImpl.kt index 5cc892fdb..97a570342 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/impl/GraphImpl.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/impl/GraphImpl.kt @@ -5,12 +5,14 @@ import it.unibo.tuprolog.utils.graphs.Graph import it.unibo.tuprolog.utils.graphs.Node internal class GraphImpl : Graph, AbstractGraph> { - constructor(edges: Iterable>) : super(edges) internal constructor(connections: MutableMap, MutableMap, W?>>) : super(connections) override fun toMutable(): MutableGraphImpl = MutableGraphImpl(connections.toMutableMap()) + override fun newInstance(connections: MutableMap, MutableMap, W?>>): GraphImpl = - GraphImpl(connections) + GraphImpl( + connections, + ) } diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/impl/MutableGraphImpl.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/impl/MutableGraphImpl.kt index 23d564e34..4b941bc01 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/impl/MutableGraphImpl.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/graphs/impl/MutableGraphImpl.kt @@ -7,7 +7,6 @@ import it.unibo.tuprolog.utils.graphs.Node @Suppress("RedundantVisibilityModifier") internal class MutableGraphImpl : MutableGraph, AbstractGraph> { - constructor(edges: Iterable> = emptyList()) : super(edges) internal constructor(connections: MutableMap, MutableMap, W?>>) : super(connections) @@ -24,10 +23,17 @@ internal class MutableGraphImpl : MutableGraph, AbstractGraph) = addNode(node) - override fun set(edge: Pair, Node>, weight: W) = - add(edge(edge.first, edge.second, weight)) - - override fun connect(node1: Node, node2: Node, weight: W?, bidirectional: Boolean) { + override fun set( + edge: Pair, Node>, + weight: W, + ) = add(edge(edge.first, edge.second, weight)) + + override fun connect( + node1: Node, + node2: Node, + weight: W?, + bidirectional: Boolean, + ) { add(edge(node1, node2, weight)) if (bidirectional) { add(edge(node2, node1, weight)) diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/AbstractCursor.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/AbstractCursor.kt index 14cd92463..21de6f091 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/AbstractCursor.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/AbstractCursor.kt @@ -3,23 +3,25 @@ package it.unibo.tuprolog.utils.impl import it.unibo.tuprolog.utils.Cursor internal abstract class AbstractCursor : Cursor { - override fun toString(): String = when { - this.isOver -> "[]" - !this.hasNext -> "[$current]" - else -> "[$current, ...]" - } + override fun toString(): String = + when { + this.isOver -> "[]" + !this.hasNext -> "[$current]" + else -> "[$current, ...]" + } - override fun iterator(): Iterator = object : Iterator { - private var current: Cursor = this@AbstractCursor + override fun iterator(): Iterator = + object : Iterator { + private var current: Cursor = this@AbstractCursor - override fun hasNext(): Boolean = !current.isOver + override fun hasNext(): Boolean = !current.isOver - override fun next(): T { - val result = current.current - current = current.next - return result!! + override fun next(): T { + val result = current.current + current = current.next + return result!! + } } - } abstract override val next: AbstractCursor diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/CachedImpl.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/CachedImpl.kt index 263cbf580..b7ca05fe7 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/CachedImpl.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/CachedImpl.kt @@ -4,7 +4,6 @@ import it.unibo.tuprolog.utils.Cached import it.unibo.tuprolog.utils.Optional data class CachedImpl(private val generator: () -> T) : Cached { - private var cached: Optional = Optional.none() override val isValid: Boolean diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/ConjunctionCursor.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/ConjunctionCursor.kt index 1bc54b62a..4dac85786 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/ConjunctionCursor.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/ConjunctionCursor.kt @@ -4,7 +4,7 @@ import it.unibo.tuprolog.utils.Cursor internal class ConjunctionCursor( val first: Cursor, - val second: AbstractCursor + val second: AbstractCursor, ) : AbstractCursor() { override val isOver: Boolean get() = first.isOver && second.isOver diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/IndexedImpl.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/IndexedImpl.kt index 592a140a2..837408d5d 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/IndexedImpl.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/IndexedImpl.kt @@ -4,7 +4,7 @@ import it.unibo.tuprolog.utils.LongIndexed internal data class IndexedImpl( override val index: Long, - override val value: T + override val value: T, ) : LongIndexed { override fun map(mapper: (T) -> R): LongIndexed { return IndexedImpl(index, mapper(value)) diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/IntIndexedImpl.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/IntIndexedImpl.kt index 45e596926..40aa66829 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/IntIndexedImpl.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/IntIndexedImpl.kt @@ -4,7 +4,7 @@ import it.unibo.tuprolog.utils.IntIndexed internal data class IntIndexedImpl( override val index: Int, - override val value: T + override val value: T, ) : IntIndexed { override fun map(mapper: (T) -> R): IntIndexed { return IntIndexedImpl(index, mapper(value)) diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/LRUCache.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/LRUCache.kt index 11d609e3f..3ffa275b1 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/LRUCache.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/LRUCache.kt @@ -6,7 +6,6 @@ import it.unibo.tuprolog.utils.buffered import it.unibo.tuprolog.utils.synchronizedOnSelf internal class LRUCache(override val capacity: Int) : Cache { - init { require(capacity > 0) } @@ -19,34 +18,41 @@ internal class LRUCache(override val capacity: Int) : Cache { override val size get() = synchronizedOnSelf { cache.size } - override fun set(key: K, value: V): Optional> = synchronizedOnSelf { - val evicted: Optional> = insertionOrder[nextFreeIndex].let { evictedKey -> - if (evictedKey.isPresent) { - val evictedKeyValue = evictedKey.value!! - val evictedValue = cache[evictedKeyValue]!! - cache.remove(evictedKeyValue) - Optional.some(evictedKeyValue to evictedValue) + override fun set( + key: K, + value: V, + ): Optional> = + synchronizedOnSelf { + val evicted: Optional> = + insertionOrder[nextFreeIndex].let { evictedKey -> + if (evictedKey.isPresent) { + val evictedKeyValue = evictedKey.value!! + val evictedValue = cache[evictedKeyValue]!! + cache.remove(evictedKeyValue) + Optional.some(evictedKeyValue to evictedValue) + } else { + Optional.none() + } + } + insertionOrder[nextFreeIndex] = Optional.some(key) + cache[key] = value + nextFreeIndex = (nextFreeIndex + 1) % capacity + evicted + } + + override fun get(key: K): Optional = + synchronizedOnSelf { + if (cache.containsKey(key)) { + Optional.of(cache[key]) } else { Optional.none() } } - insertionOrder[nextFreeIndex] = Optional.some(key) - cache[key] = value - nextFreeIndex = (nextFreeIndex + 1) % capacity - evicted - } - override fun get(key: K): Optional = synchronizedOnSelf { - if (cache.containsKey(key)) { - Optional.of(cache[key]) - } else { - Optional.none() + override fun toMap(): Map = + synchronizedOnSelf { + cache.toMap() } - } - - override fun toMap(): Map = synchronizedOnSelf { - cache.toMap() - } override fun equals(other: Any?): Boolean { if (this === other) return true @@ -68,18 +74,20 @@ internal class LRUCache(override val capacity: Int) : Cache { return result } - override fun toSequence(): Sequence> = synchronizedOnSelf { - val indexes = if (size < capacity) { - (0 until size).asSequence() - } else { - (0 until capacity).asSequence().map { (it + nextFreeIndex) % capacity } + override fun toSequence(): Sequence> = + synchronizedOnSelf { + val indexes = + if (size < capacity) { + (0 until size).asSequence() + } else { + (0 until capacity).asSequence().map { (it + nextFreeIndex) % capacity } + } + indexes.map { insertionOrder[it] } + .filter { it.isPresent } + .map { it.value!! } + .map { it to cache[it]!! } + .buffered() } - indexes.map { insertionOrder[it] } - .filter { it.isPresent } - .map { it.value!! } - .map { it to cache[it]!! } - .buffered() - } override fun toString(): String { return "LRUCache(${toSequence().map { "${it.first} = ${it.second}" }.joinToString(", ")})" diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/LazyCursor.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/LazyCursor.kt index aed72a835..452edeba0 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/LazyCursor.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/LazyCursor.kt @@ -1,7 +1,6 @@ package it.unibo.tuprolog.utils.impl internal data class LazyCursor(val delegate: Iterator) : AbstractCursor() { - private val wrapped: AbstractCursor by lazy { NonLastCursor(delegate) } diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/LongIndexedImpl.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/LongIndexedImpl.kt index 0c4d6c388..167bcb201 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/LongIndexedImpl.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/LongIndexedImpl.kt @@ -4,7 +4,7 @@ import it.unibo.tuprolog.utils.LongIndexed internal data class LongIndexedImpl( override val index: Long, - override val value: T + override val value: T, ) : LongIndexed { override fun compareTo(other: LongIndexed): Int { return (index - other.index).toInt() diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/MapperCursor.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/MapperCursor.kt index 092f58b57..02d569436 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/MapperCursor.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/MapperCursor.kt @@ -2,9 +2,8 @@ package it.unibo.tuprolog.utils.impl internal class MapperCursor( private val wrapped: AbstractCursor, - private val mapper: (T) -> R + private val mapper: (T) -> R, ) : AbstractCursor() { - override val next: AbstractCursor get() = wrapped.next.map(mapper) @@ -34,6 +33,5 @@ internal class MapperCursor( return result } - override fun map(mapper: (R) -> X): AbstractCursor = - ValueCursor(mapper(current), next.map(mapper)) + override fun map(mapper: (R) -> X): AbstractCursor = ValueCursor(mapper(current), next.map(mapper)) } diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/NonLastCursor.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/NonLastCursor.kt index 738668c20..611e7f531 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/NonLastCursor.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/NonLastCursor.kt @@ -1,7 +1,6 @@ package it.unibo.tuprolog.utils.impl internal class NonLastCursor(source: Iterator) : AbstractCursor() { - private var source: Iterator? = source override val next: AbstractCursor by lazy { diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/SimpleLRUCache.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/SimpleLRUCache.kt index 06aea5487..7512bc0ac 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/SimpleLRUCache.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/SimpleLRUCache.kt @@ -6,44 +6,49 @@ import it.unibo.tuprolog.utils.buffered import it.unibo.tuprolog.utils.synchronizedOnSelf internal class SimpleLRUCache(override val capacity: Int) : Cache { - init { require(capacity > 0) } private val cache = LinkedHashMap() - override fun set(key: K, value: V): Optional> = synchronizedOnSelf { - val evicted = removeLeastRecentIfNecessary() - cache[key] = value - evicted - } + override fun set( + key: K, + value: V, + ): Optional> = + synchronizedOnSelf { + val evicted = removeLeastRecentIfNecessary() + cache[key] = value + evicted + } private fun removeLeastRecent(): Optional> { - val entry = cache.iterator().next() - cache.remove(entry.key) - return Optional.some(entry.toPair()) + val (key, value) = cache.asIterable().first() + cache.remove(key) + return Optional.some(key to value) } private fun removeLeastRecentIfNecessary(): Optional> { return if (cache.size >= capacity) { removeLeastRecent() } else { - return Optional.none() + Optional.none() } } - override fun get(key: K): Optional = synchronizedOnSelf { - if (cache.containsKey(key)) { - Optional.of(cache[key]) - } else { - Optional.none() + override fun get(key: K): Optional = + synchronizedOnSelf { + if (cache.containsKey(key)) { + Optional.of(cache[key]) + } else { + Optional.none() + } } - } - override fun toMap(): Map = synchronizedOnSelf { - cache.toMap() - } + override fun toMap(): Map = + synchronizedOnSelf { + cache.toMap() + } override fun equals(other: Any?): Boolean { if (this === other) return true @@ -63,9 +68,10 @@ internal class SimpleLRUCache(override val capacity: Int) : Cache { return result } - override fun toSequence(): Sequence> = synchronizedOnSelf { - cache.entries.asSequence().map { it.toPair() }.buffered() - } + override fun toSequence(): Sequence> = + synchronizedOnSelf { + cache.entries.asSequence().map { it.toPair() }.buffered() + } override fun toString(): String { return "SimpleLRUCache(${toSequence().map { "${it.first} = ${it.second}" }.joinToString(", ")})" diff --git a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/ValueCursor.kt b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/ValueCursor.kt index ec58398c5..f51de4517 100644 --- a/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/ValueCursor.kt +++ b/utils/src/commonMain/kotlin/it/unibo/tuprolog/utils/impl/ValueCursor.kt @@ -2,7 +2,7 @@ package it.unibo.tuprolog.utils.impl internal class ValueCursor( override val current: T, - override val next: AbstractCursor + override val next: AbstractCursor, ) : AbstractCursor() { override val hasNext: Boolean get() = true diff --git a/utils/src/commonTest/kotlin/it/unibo/tuprolog/utils/CacheTest.kt b/utils/src/commonTest/kotlin/it/unibo/tuprolog/utils/CacheTest.kt index 593024355..6ce638f94 100644 --- a/utils/src/commonTest/kotlin/it/unibo/tuprolog/utils/CacheTest.kt +++ b/utils/src/commonTest/kotlin/it/unibo/tuprolog/utils/CacheTest.kt @@ -3,9 +3,7 @@ package it.unibo.tuprolog.utils import kotlin.test.assertEquals interface CacheTest { - companion object { - fun prototype(cacheConstructor: (Int) -> Cache): CacheTest = object : CacheTest { override fun cacheFactory(capacity: Int): Cache { @@ -13,9 +11,10 @@ interface CacheTest { } } - private val ITEMS: List> = (0 until 26).asSequence() - .map { charArrayOf('a' + it).concatToString() to it } - .toList() + private val ITEMS: List> = + (0 until 26).asSequence() + .map { charArrayOf('a' + it).concatToString() to it } + .toList() private const val DEFAULT_CAPACITY = 5 } diff --git a/utils/src/commonTest/kotlin/it/unibo/tuprolog/utils/LRUCacheTest.kt b/utils/src/commonTest/kotlin/it/unibo/tuprolog/utils/LRUCacheTest.kt index 98cd050b5..3549d9d64 100644 --- a/utils/src/commonTest/kotlin/it/unibo/tuprolog/utils/LRUCacheTest.kt +++ b/utils/src/commonTest/kotlin/it/unibo/tuprolog/utils/LRUCacheTest.kt @@ -4,7 +4,6 @@ import it.unibo.tuprolog.utils.impl.LRUCache import kotlin.test.Test class LRUCacheTest : CacheTest by CacheTest.prototype(::LRUCache) { - @Test override fun testKeysCaching() { super.testKeysCaching() diff --git a/utils/src/commonTest/kotlin/it/unibo/tuprolog/utils/SimpleLRUCacheTest.kt b/utils/src/commonTest/kotlin/it/unibo/tuprolog/utils/SimpleLRUCacheTest.kt index e827ad490..aebcbe83d 100644 --- a/utils/src/commonTest/kotlin/it/unibo/tuprolog/utils/SimpleLRUCacheTest.kt +++ b/utils/src/commonTest/kotlin/it/unibo/tuprolog/utils/SimpleLRUCacheTest.kt @@ -4,7 +4,6 @@ import it.unibo.tuprolog.utils.impl.SimpleLRUCache import kotlin.test.Test class SimpleLRUCacheTest : CacheTest by CacheTest.prototype(::SimpleLRUCache) { - @Test override fun testKeysCaching() { super.testKeysCaching() diff --git a/utils/src/commonTest/kotlin/it/unibo/tuprolog/utils/TestCursor.kt b/utils/src/commonTest/kotlin/it/unibo/tuprolog/utils/TestCursor.kt index e46360482..6f74bd5ae 100644 --- a/utils/src/commonTest/kotlin/it/unibo/tuprolog/utils/TestCursor.kt +++ b/utils/src/commonTest/kotlin/it/unibo/tuprolog/utils/TestCursor.kt @@ -33,7 +33,10 @@ class TestCursor { } } - private fun assertCursorContains(actual: Cursor, expected: Iterable) { + private fun assertCursorContains( + actual: Cursor, + expected: Iterable, + ) { var i = 1 val iterActual = actual.iterator() val iterExpected = expected.iterator() @@ -44,14 +47,14 @@ class TestCursor { assertEquals( iterExpected.next(), iterActual.next(), - "Items with index ${i - 1} does not correspond" + "Items with index ${i - 1} does not correspond", ) i++ } assertEquals( iterExpected.hasNext(), iterActual.hasNext(), - "The cursor has more than $i items, while $i are expected" + "The cursor has more than $i items, while $i are expected", ) } @@ -109,7 +112,11 @@ class TestCursor { @Test fun testCursorDoNotRepeatSequence() { var x: Int = 0 - val cursor = items.asSequence().map { x++; x }.cursor().map { it * 2 } + val cursor = + items.asSequence().map { + x++ + x + }.cursor().map { it * 2 } testCursor(cursor) assertCursorContains(cursor, items.map { it * 2 }) assertEquals(items.count(), x) @@ -117,18 +124,19 @@ class TestCursor { @Test fun stressMapping() { - val N = 100000 + val n = 100000 var x: Int = 0 var cursor = items.cursor() - for (i in 0 until N) { - cursor = cursor.map { - x++ - it + 1 - } + for (i in 0 until n) { + cursor = + cursor.map { + x++ + it + 1 + } assertTrue { x <= items.count() * (i + 1) } } testCursor(cursor) - assertCursorContains(cursor, items.map { it + N }) - assertEquals(items.count() * N, x) + assertCursorContains(cursor, items.map { it + n }) + assertEquals(items.count() * n, x) } } diff --git a/utils/src/commonTest/kotlin/it/unibo/tuprolog/utils/TestGraph.kt b/utils/src/commonTest/kotlin/it/unibo/tuprolog/utils/TestGraph.kt index 463c459e9..32b3f079e 100644 --- a/utils/src/commonTest/kotlin/it/unibo/tuprolog/utils/TestGraph.kt +++ b/utils/src/commonTest/kotlin/it/unibo/tuprolog/utils/TestGraph.kt @@ -15,29 +15,31 @@ import kotlin.test.assertFalse import kotlin.test.assertTrue class TestGraph { - private val unweighted = Graph.build { - this += nodeOf("a") - this += nodeOf("b") - this -= nodeOf("a") - this += edgeOf(nodeOf("a"), nodeOf("b")) - this += edgeOf(nodeOf("a"), nodeOf("c")) - this += edgeOf(nodeOf("b"), nodeOf("d")) - this += edgeOf(nodeOf("b"), nodeOf("e")) - this += edgeOf(nodeOf("e"), nodeOf("f")) - connect(nodeOf("a"), nodeOf("f"), bidirectional = true) - } + private val unweighted = + Graph.build { + this += nodeOf("a") + this += nodeOf("b") + this -= nodeOf("a") + this += edgeOf(nodeOf("a"), nodeOf("b")) + this += edgeOf(nodeOf("a"), nodeOf("c")) + this += edgeOf(nodeOf("b"), nodeOf("d")) + this += edgeOf(nodeOf("b"), nodeOf("e")) + this += edgeOf(nodeOf("e"), nodeOf("f")) + connect(nodeOf("a"), nodeOf("f"), bidirectional = true) + } - private val weighted = Graph.build { - this += nodeOf("a") - this += nodeOf("b") - this -= nodeOf("a") - this += edgeOf(nodeOf("a"), nodeOf("b"), 1) - this += edgeOf(nodeOf("a"), nodeOf("c"), 2) - this += edgeOf(nodeOf("b"), nodeOf("d"), 4) - this += edgeOf(nodeOf("b"), nodeOf("e"), 5) - this += edgeOf(nodeOf("e"), nodeOf("f"), 6) - connect(nodeOf("a"), nodeOf("f"), bidirectional = true, weight = 3) - } + private val weighted = + Graph.build { + this += nodeOf("a") + this += nodeOf("b") + this -= nodeOf("a") + this += edgeOf(nodeOf("a"), nodeOf("b"), 1) + this += edgeOf(nodeOf("a"), nodeOf("c"), 2) + this += edgeOf(nodeOf("b"), nodeOf("d"), 4) + this += edgeOf(nodeOf("b"), nodeOf("e"), 5) + this += edgeOf(nodeOf("e"), nodeOf("f"), 6) + connect(nodeOf("a"), nodeOf("f"), bidirectional = true, weight = 3) + } @Test fun testCreationUnweighted() { @@ -54,8 +56,8 @@ class TestGraph { edgeOf(nodeOf("b"), nodeOf("e")), edgeOf(nodeOf("e"), nodeOf("f")), edgeOf(nodeOf("a"), nodeOf("f")), - edgeOf(nodeOf("f"), nodeOf("a")) - ) + edgeOf(nodeOf("f"), nodeOf("a")), + ), ) assertTrue(nodeOf("a") in unweighted) @@ -102,8 +104,8 @@ class TestGraph { edgeOf(nodeOf("b"), nodeOf("e"), 5), edgeOf(nodeOf("e"), nodeOf("f"), 6), edgeOf(nodeOf("a"), nodeOf("f"), 3), - edgeOf(nodeOf("f"), nodeOf("a"), 3) - ) + edgeOf(nodeOf("f"), nodeOf("a"), 3), + ), ) assertTrue(nodeOf("a") in weighted) @@ -137,211 +139,216 @@ class TestGraph { @Test fun testLimitedPreOrderDepthFirstSearch() { - val expected = listOf( - visitOf(0, nodeOf("a")), - visitOf(1, nodeOf("b")), - visitOf(2, nodeOf("d")), - visitOf(2, nodeOf("e")), - visitOf(3, nodeOf("f")), - visitOf(1, nodeOf("c")), - visitOf(1, nodeOf("f")), - visitOf(2, nodeOf("a")), - visitOf(3, nodeOf("b")), - visitOf(3, nodeOf("c")), - visitOf(3, nodeOf("f")) - ) + val expected = + listOf( + visitOf(0, nodeOf("a")), + visitOf(1, nodeOf("b")), + visitOf(2, nodeOf("d")), + visitOf(2, nodeOf("e")), + visitOf(3, nodeOf("f")), + visitOf(1, nodeOf("c")), + visitOf(1, nodeOf("f")), + visitOf(2, nodeOf("a")), + visitOf(3, nodeOf("b")), + visitOf(3, nodeOf("c")), + visitOf(3, nodeOf("f")), + ) assertEquals(expected, unweighted.asSequence(DepthFirst(maxDepth = 3), nodeOf("a")).toList()) assertEquals(expected, weighted.asSequence(DepthFirst(maxDepth = 3), nodeOf("a")).toList()) } @Test fun testPreOrderDepthFirstSearchOnGraphWithCycles() { - val expected = listOf( - visitOf(0, nodeOf("a")), - visitOf(1, nodeOf("b")), - visitOf(2, nodeOf("d")), - visitOf(2, nodeOf("e")), - visitOf(3, nodeOf("f")), - visitOf(4, nodeOf("a")), - visitOf(5, nodeOf("b")), - visitOf(6, nodeOf("d")), - visitOf(6, nodeOf("e")), - visitOf(7, nodeOf("f")), - visitOf(8, nodeOf("a")), - visitOf(9, nodeOf("b")), - visitOf(9, nodeOf("c")), - visitOf(9, nodeOf("f")), - visitOf(5, nodeOf("c")), - visitOf(5, nodeOf("f")), - visitOf(6, nodeOf("a")), - visitOf(7, nodeOf("b")), - visitOf(8, nodeOf("d")), - visitOf(8, nodeOf("e")), - visitOf(9, nodeOf("f")), - visitOf(7, nodeOf("c")), - visitOf(7, nodeOf("f")), - visitOf(8, nodeOf("a")), - visitOf(9, nodeOf("b")), - visitOf(9, nodeOf("c")), - visitOf(9, nodeOf("f")), - visitOf(1, nodeOf("c")), - visitOf(1, nodeOf("f")), - visitOf(2, nodeOf("a")), - visitOf(3, nodeOf("b")), - visitOf(4, nodeOf("d")), - visitOf(4, nodeOf("e")), - visitOf(5, nodeOf("f")), - visitOf(6, nodeOf("a")), - visitOf(7, nodeOf("b")), - visitOf(8, nodeOf("d")), - visitOf(8, nodeOf("e")), - visitOf(9, nodeOf("f")), - visitOf(7, nodeOf("c")), - visitOf(7, nodeOf("f")), - visitOf(8, nodeOf("a")), - visitOf(9, nodeOf("b")), - visitOf(9, nodeOf("c")), - visitOf(9, nodeOf("f")), - visitOf(3, nodeOf("c")), - visitOf(3, nodeOf("f")), - visitOf(4, nodeOf("a")), - visitOf(5, nodeOf("b")), - visitOf(6, nodeOf("d")), - visitOf(6, nodeOf("e")), - visitOf(7, nodeOf("f")), - visitOf(8, nodeOf("a")), - visitOf(9, nodeOf("b")), - visitOf(9, nodeOf("c")), - visitOf(9, nodeOf("f")), - visitOf(5, nodeOf("c")), - visitOf(5, nodeOf("f")), - visitOf(6, nodeOf("a")), - visitOf(7, nodeOf("b")), - visitOf(8, nodeOf("d")), - visitOf(8, nodeOf("e")), - visitOf(9, nodeOf("f")), - visitOf(7, nodeOf("c")), - visitOf(7, nodeOf("f")), - visitOf(8, nodeOf("a")), - visitOf(9, nodeOf("b")), - visitOf(9, nodeOf("c")), - visitOf(9, nodeOf("f")) - ) + val expected = + listOf( + visitOf(0, nodeOf("a")), + visitOf(1, nodeOf("b")), + visitOf(2, nodeOf("d")), + visitOf(2, nodeOf("e")), + visitOf(3, nodeOf("f")), + visitOf(4, nodeOf("a")), + visitOf(5, nodeOf("b")), + visitOf(6, nodeOf("d")), + visitOf(6, nodeOf("e")), + visitOf(7, nodeOf("f")), + visitOf(8, nodeOf("a")), + visitOf(9, nodeOf("b")), + visitOf(9, nodeOf("c")), + visitOf(9, nodeOf("f")), + visitOf(5, nodeOf("c")), + visitOf(5, nodeOf("f")), + visitOf(6, nodeOf("a")), + visitOf(7, nodeOf("b")), + visitOf(8, nodeOf("d")), + visitOf(8, nodeOf("e")), + visitOf(9, nodeOf("f")), + visitOf(7, nodeOf("c")), + visitOf(7, nodeOf("f")), + visitOf(8, nodeOf("a")), + visitOf(9, nodeOf("b")), + visitOf(9, nodeOf("c")), + visitOf(9, nodeOf("f")), + visitOf(1, nodeOf("c")), + visitOf(1, nodeOf("f")), + visitOf(2, nodeOf("a")), + visitOf(3, nodeOf("b")), + visitOf(4, nodeOf("d")), + visitOf(4, nodeOf("e")), + visitOf(5, nodeOf("f")), + visitOf(6, nodeOf("a")), + visitOf(7, nodeOf("b")), + visitOf(8, nodeOf("d")), + visitOf(8, nodeOf("e")), + visitOf(9, nodeOf("f")), + visitOf(7, nodeOf("c")), + visitOf(7, nodeOf("f")), + visitOf(8, nodeOf("a")), + visitOf(9, nodeOf("b")), + visitOf(9, nodeOf("c")), + visitOf(9, nodeOf("f")), + visitOf(3, nodeOf("c")), + visitOf(3, nodeOf("f")), + visitOf(4, nodeOf("a")), + visitOf(5, nodeOf("b")), + visitOf(6, nodeOf("d")), + visitOf(6, nodeOf("e")), + visitOf(7, nodeOf("f")), + visitOf(8, nodeOf("a")), + visitOf(9, nodeOf("b")), + visitOf(9, nodeOf("c")), + visitOf(9, nodeOf("f")), + visitOf(5, nodeOf("c")), + visitOf(5, nodeOf("f")), + visitOf(6, nodeOf("a")), + visitOf(7, nodeOf("b")), + visitOf(8, nodeOf("d")), + visitOf(8, nodeOf("e")), + visitOf(9, nodeOf("f")), + visitOf(7, nodeOf("c")), + visitOf(7, nodeOf("f")), + visitOf(8, nodeOf("a")), + visitOf(9, nodeOf("b")), + visitOf(9, nodeOf("c")), + visitOf(9, nodeOf("f")), + ) assertEquals(expected, unweighted.asSequence(DepthFirst(maxDepth = 9), nodeOf("a")).toList()) assertEquals(expected, weighted.asSequence(DepthFirst(maxDepth = 9), nodeOf("a")).toList()) } @Test fun testLimitedPostOrderDepthFirstSearch() { - val expected = listOf( - visitOf(2, nodeOf("d")), - visitOf(3, nodeOf("f")), - visitOf(2, nodeOf("e")), - visitOf(1, nodeOf("b")), - visitOf(1, nodeOf("c")), - visitOf(3, nodeOf("b")), - visitOf(3, nodeOf("c")), - visitOf(3, nodeOf("f")), - visitOf(2, nodeOf("a")), - visitOf(1, nodeOf("f")), - visitOf(0, nodeOf("a")) - ) + val expected = + listOf( + visitOf(2, nodeOf("d")), + visitOf(3, nodeOf("f")), + visitOf(2, nodeOf("e")), + visitOf(1, nodeOf("b")), + visitOf(1, nodeOf("c")), + visitOf(3, nodeOf("b")), + visitOf(3, nodeOf("c")), + visitOf(3, nodeOf("f")), + visitOf(2, nodeOf("a")), + visitOf(1, nodeOf("f")), + visitOf(0, nodeOf("a")), + ) assertEquals(expected, unweighted.asSequence(DepthFirst(maxDepth = 3, postOrder = true), nodeOf("a")).toList()) assertEquals(expected, weighted.asSequence(DepthFirst(maxDepth = 3, postOrder = true), nodeOf("a")).toList()) } @Test fun testLimitedBreadthFirstSearch() { - val expected = listOf( - visitOf(0, nodeOf("a")), - visitOf(1, nodeOf("b")), - visitOf(1, nodeOf("c")), - visitOf(1, nodeOf("f")), - visitOf(2, nodeOf("d")), - visitOf(2, nodeOf("e")), - visitOf(2, nodeOf("a")), - visitOf(3, nodeOf("f")), - visitOf(3, nodeOf("b")), - visitOf(3, nodeOf("c")), - visitOf(3, nodeOf("f")) - ) + val expected = + listOf( + visitOf(0, nodeOf("a")), + visitOf(1, nodeOf("b")), + visitOf(1, nodeOf("c")), + visitOf(1, nodeOf("f")), + visitOf(2, nodeOf("d")), + visitOf(2, nodeOf("e")), + visitOf(2, nodeOf("a")), + visitOf(3, nodeOf("f")), + visitOf(3, nodeOf("b")), + visitOf(3, nodeOf("c")), + visitOf(3, nodeOf("f")), + ) assertEquals(expected, unweighted.asSequence(BreadthFirst(maxDepth = 3), nodeOf("a")).toList()) assertEquals(expected, weighted.asSequence(BreadthFirst(maxDepth = 3), nodeOf("a")).toList()) } @Test fun testBreadthFirstSearchOnGraphWithCycles() { - val expected = listOf( - visitOf(0, nodeOf("a")), - visitOf(1, nodeOf("b")), - visitOf(1, nodeOf("c")), - visitOf(1, nodeOf("f")), - visitOf(2, nodeOf("d")), - visitOf(2, nodeOf("e")), - visitOf(2, nodeOf("a")), - visitOf(3, nodeOf("f")), - visitOf(3, nodeOf("b")), - visitOf(3, nodeOf("c")), - visitOf(3, nodeOf("f")), - visitOf(4, nodeOf("a")), - visitOf(4, nodeOf("d")), - visitOf(4, nodeOf("e")), - visitOf(4, nodeOf("a")), - visitOf(5, nodeOf("b")), - visitOf(5, nodeOf("c")), - visitOf(5, nodeOf("f")), - visitOf(5, nodeOf("f")), - visitOf(5, nodeOf("b")), - visitOf(5, nodeOf("c")), - visitOf(5, nodeOf("f")), - visitOf(6, nodeOf("d")), - visitOf(6, nodeOf("e")), - visitOf(6, nodeOf("a")), - visitOf(6, nodeOf("a")), - visitOf(6, nodeOf("d")), - visitOf(6, nodeOf("e")), - visitOf(6, nodeOf("a")), - visitOf(7, nodeOf("f")), - visitOf(7, nodeOf("b")), - visitOf(7, nodeOf("c")), - visitOf(7, nodeOf("f")), - visitOf(7, nodeOf("b")), - visitOf(7, nodeOf("c")), - visitOf(7, nodeOf("f")), - visitOf(7, nodeOf("f")), - visitOf(7, nodeOf("b")), - visitOf(7, nodeOf("c")), - visitOf(7, nodeOf("f")), - visitOf(8, nodeOf("a")), - visitOf(8, nodeOf("d")), - visitOf(8, nodeOf("e")), - visitOf(8, nodeOf("a")), - visitOf(8, nodeOf("d")), - visitOf(8, nodeOf("e")), - visitOf(8, nodeOf("a")), - visitOf(8, nodeOf("a")), - visitOf(8, nodeOf("d")), - visitOf(8, nodeOf("e")), - visitOf(8, nodeOf("a")), - visitOf(9, nodeOf("b")), - visitOf(9, nodeOf("c")), - visitOf(9, nodeOf("f")), - visitOf(9, nodeOf("f")), - visitOf(9, nodeOf("b")), - visitOf(9, nodeOf("c")), - visitOf(9, nodeOf("f")), - visitOf(9, nodeOf("f")), - visitOf(9, nodeOf("b")), - visitOf(9, nodeOf("c")), - visitOf(9, nodeOf("f")), - visitOf(9, nodeOf("b")), - visitOf(9, nodeOf("c")), - visitOf(9, nodeOf("f")), - visitOf(9, nodeOf("f")), - visitOf(9, nodeOf("b")), - visitOf(9, nodeOf("c")), - visitOf(9, nodeOf("f")) - ) + val expected = + listOf( + visitOf(0, nodeOf("a")), + visitOf(1, nodeOf("b")), + visitOf(1, nodeOf("c")), + visitOf(1, nodeOf("f")), + visitOf(2, nodeOf("d")), + visitOf(2, nodeOf("e")), + visitOf(2, nodeOf("a")), + visitOf(3, nodeOf("f")), + visitOf(3, nodeOf("b")), + visitOf(3, nodeOf("c")), + visitOf(3, nodeOf("f")), + visitOf(4, nodeOf("a")), + visitOf(4, nodeOf("d")), + visitOf(4, nodeOf("e")), + visitOf(4, nodeOf("a")), + visitOf(5, nodeOf("b")), + visitOf(5, nodeOf("c")), + visitOf(5, nodeOf("f")), + visitOf(5, nodeOf("f")), + visitOf(5, nodeOf("b")), + visitOf(5, nodeOf("c")), + visitOf(5, nodeOf("f")), + visitOf(6, nodeOf("d")), + visitOf(6, nodeOf("e")), + visitOf(6, nodeOf("a")), + visitOf(6, nodeOf("a")), + visitOf(6, nodeOf("d")), + visitOf(6, nodeOf("e")), + visitOf(6, nodeOf("a")), + visitOf(7, nodeOf("f")), + visitOf(7, nodeOf("b")), + visitOf(7, nodeOf("c")), + visitOf(7, nodeOf("f")), + visitOf(7, nodeOf("b")), + visitOf(7, nodeOf("c")), + visitOf(7, nodeOf("f")), + visitOf(7, nodeOf("f")), + visitOf(7, nodeOf("b")), + visitOf(7, nodeOf("c")), + visitOf(7, nodeOf("f")), + visitOf(8, nodeOf("a")), + visitOf(8, nodeOf("d")), + visitOf(8, nodeOf("e")), + visitOf(8, nodeOf("a")), + visitOf(8, nodeOf("d")), + visitOf(8, nodeOf("e")), + visitOf(8, nodeOf("a")), + visitOf(8, nodeOf("a")), + visitOf(8, nodeOf("d")), + visitOf(8, nodeOf("e")), + visitOf(8, nodeOf("a")), + visitOf(9, nodeOf("b")), + visitOf(9, nodeOf("c")), + visitOf(9, nodeOf("f")), + visitOf(9, nodeOf("f")), + visitOf(9, nodeOf("b")), + visitOf(9, nodeOf("c")), + visitOf(9, nodeOf("f")), + visitOf(9, nodeOf("f")), + visitOf(9, nodeOf("b")), + visitOf(9, nodeOf("c")), + visitOf(9, nodeOf("f")), + visitOf(9, nodeOf("b")), + visitOf(9, nodeOf("c")), + visitOf(9, nodeOf("f")), + visitOf(9, nodeOf("f")), + visitOf(9, nodeOf("b")), + visitOf(9, nodeOf("c")), + visitOf(9, nodeOf("f")), + ) assertEquals(expected, unweighted.asSequence(BreadthFirst(maxDepth = 9), nodeOf("a")).toList()) assertEquals(expected, weighted.asSequence(BreadthFirst(maxDepth = 9), nodeOf("a")).toList()) } @@ -360,19 +367,21 @@ class TestGraph { @Test fun treeCheck() { - val tree = unweighted.copy { - this -= edgeOf(nodeOf("a"), nodeOf("f")) - this -= edgeOf(nodeOf("f"), nodeOf("a")) - } + val tree = + unweighted.copy { + this -= edgeOf(nodeOf("a"), nodeOf("f")) + this -= edgeOf(nodeOf("f"), nodeOf("a")) + } assertTrue(tree.isTree) } @Test fun acyclicCheck() { - val tree = weighted.copy { - this -= edgeOf(nodeOf("f"), nodeOf("a")) - } + val tree = + weighted.copy { + this -= edgeOf(nodeOf("f"), nodeOf("a")) + } assertTrue(tree.isAcyclic) } diff --git a/utils/src/jsMain/kotlin/it/unibo/tuprolog/utils/ThreadSafetyJs.kt b/utils/src/jsMain/kotlin/it/unibo/tuprolog/utils/ThreadSafetyJs.kt index 897c58fe5..797a4f2bc 100644 --- a/utils/src/jsMain/kotlin/it/unibo/tuprolog/utils/ThreadSafetyJs.kt +++ b/utils/src/jsMain/kotlin/it/unibo/tuprolog/utils/ThreadSafetyJs.kt @@ -1,3 +1,6 @@ package it.unibo.tuprolog.utils -actual fun synchronizedOn(obj: Any, action: () -> T): T = action() +actual fun synchronizedOn( + obj: Any, + action: () -> T, +): T = action() diff --git a/utils/src/jvmMain/kotlin/it/unibo/tuprolog/utils/Deque.kt b/utils/src/jvmMain/kotlin/it/unibo/tuprolog/utils/Deque.kt index 6e6118908..b54b8a995 100644 --- a/utils/src/jvmMain/kotlin/it/unibo/tuprolog/utils/Deque.kt +++ b/utils/src/jvmMain/kotlin/it/unibo/tuprolog/utils/Deque.kt @@ -18,6 +18,7 @@ actual fun dequeOf(items: Sequence): MutableList { return items.toCollection(LinkedList()) } +@Suppress("EXTENSION_SHADOWED_BY_MEMBER") actual fun MutableList.addFirst(item: T) { if (this is LinkedList) { this.addFirst(item) diff --git a/utils/src/jvmMain/kotlin/it/unibo/tuprolog/utils/ThreadSafetyJvm.kt b/utils/src/jvmMain/kotlin/it/unibo/tuprolog/utils/ThreadSafetyJvm.kt index b16a06ff4..038e4d8f2 100644 --- a/utils/src/jvmMain/kotlin/it/unibo/tuprolog/utils/ThreadSafetyJvm.kt +++ b/utils/src/jvmMain/kotlin/it/unibo/tuprolog/utils/ThreadSafetyJvm.kt @@ -1,3 +1,6 @@ package it.unibo.tuprolog.utils -actual fun synchronizedOn(obj: Any, action: () -> T): T = synchronized(obj, action) +actual fun synchronizedOn( + obj: Any, + action: () -> T, +): T = synchronized(obj, action) diff --git a/utils/src/jvmMain/kotlin/it/unibo/tuprolog/utils/impl/IteratorWrapper.kt b/utils/src/jvmMain/kotlin/it/unibo/tuprolog/utils/impl/IteratorWrapper.kt index 864ff04bd..18e7c7eff 100644 --- a/utils/src/jvmMain/kotlin/it/unibo/tuprolog/utils/impl/IteratorWrapper.kt +++ b/utils/src/jvmMain/kotlin/it/unibo/tuprolog/utils/impl/IteratorWrapper.kt @@ -5,8 +5,9 @@ internal class IteratorWrapper(private val wrapped: Iterator) : MutableIte override fun next(): T = wrapped.next() - override fun remove() = when (wrapped) { - is MutableIterator -> wrapped.remove() - else -> throw UnsupportedOperationException() - } + override fun remove() = + when (wrapped) { + is MutableIterator -> wrapped.remove() + else -> throw UnsupportedOperationException() + } }