Skip to content

Commit

Permalink
format code in :solve-streams
Browse files Browse the repository at this point in the history
  • Loading branch information
gciatto committed Sep 14, 2020
1 parent 63c3396 commit b8b465e
Show file tree
Hide file tree
Showing 74 changed files with 363 additions and 342 deletions.
3 changes: 1 addition & 2 deletions solve-streams/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,10 @@ kotlin {
dependsOn(main.defaultSourceSet)
}
}

}
}

tasks.withType<KotlinJvmTest> {
maxHeapSize = jvmMaxHeapSize
jvmArgs("-Xss$jvmStackSize")
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
@file:JvmName("SolverExtensions")

package it.unibo.tuprolog.solve

import it.unibo.tuprolog.solve.channel.InputChannel
Expand Down Expand Up @@ -54,4 +55,4 @@ fun MutableSolver.Companion.streamsWithDefaultBuiltins(
stdErr: OutputChannel<String> = StreamsSolverFactory.defaultErrorChannel,
warnings: OutputChannel<PrologWarning> = StreamsSolverFactory.defaultWarningsChannel
): MutableSolver =
StreamsSolverFactory.mutableSolverWithDefaultBuiltins(libraries, flags, staticKb, dynamicKb, stdIn, stdOut, stdErr, warnings)
StreamsSolverFactory.mutableSolverWithDefaultBuiltins(libraries, flags, staticKb, dynamicKb, stdIn, stdOut, stdErr, warnings)
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,4 @@ object StreamsSolverFactory : SolverFactory {
): MutableSolver {
TODO("Not yet implemented")
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,8 @@ internal data class SideEffectManagerImpl(
* - if cut was called, and the first "scoped" choice point context is to be cut
*/
internal fun shouldCutExecuteInRuleSelection() =
clauseScopedParents.lastOrNull() in toCutContextsParent
|| shouldExecuteThrowCut()
clauseScopedParents.lastOrNull() in toCutContextsParent ||
shouldExecuteThrowCut()

/** 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<StreamsExecutionContext>? {
Expand Down Expand Up @@ -120,7 +120,6 @@ internal data class SideEffectManagerImpl(
// opaque behaviour of call/1 w.r.t cut/0, results in cancellation of sub-goal work onto "cut"'s data structures
copy(toCutContextsParent = toRecoverSituation.toCutContextsParent)


/**
* Method to query if the throw Cut should execute; the throw cut can exit clause Scope, so it uses different data structures
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@

package it.unibo.tuprolog.solve.solver

import it.unibo.tuprolog.core.*
import it.unibo.tuprolog.core.Clause
import it.unibo.tuprolog.core.Directive
import it.unibo.tuprolog.core.Struct
import it.unibo.tuprolog.core.Substitution
import it.unibo.tuprolog.core.Term
import it.unibo.tuprolog.core.prepareForExecution
import it.unibo.tuprolog.solve.ExecutionContext
import it.unibo.tuprolog.solve.SideEffect
import it.unibo.tuprolog.solve.TimeInstant
Expand Down Expand Up @@ -104,8 +109,9 @@ fun Solve.Request<ExecutionContext>.replyWith(otherResponse: Solve.Response): So
fun KtList<SideEffect>.addWithNoDuplicates(toAddSideEffects: KtList<SideEffect>): KtList<SideEffect> {
var duplicatedCount = 0
forEach { sideEffect ->
if (toAddSideEffects.find { toAddSideEffect -> sideEffect === toAddSideEffect } !== null)
if (toAddSideEffects.find { toAddSideEffect -> sideEffect === toAddSideEffect } !== null) {
duplicatedCount++
}
}
return this + toAddSideEffects.drop(duplicatedCount)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,21 @@ package it.unibo.tuprolog.solve.solver
import it.unibo.tuprolog.core.Struct
import it.unibo.tuprolog.core.Substitution
import it.unibo.tuprolog.core.operators.OperatorSet
import it.unibo.tuprolog.solve.*
import it.unibo.tuprolog.solve.ExecutionContext
import it.unibo.tuprolog.solve.ExecutionContextAware
import it.unibo.tuprolog.solve.FlagStore
import it.unibo.tuprolog.solve.InputStore
import it.unibo.tuprolog.solve.OutputStore
import it.unibo.tuprolog.solve.SideEffect
import it.unibo.tuprolog.solve.SolverStrategies
import it.unibo.tuprolog.solve.StreamsSolver
import it.unibo.tuprolog.solve.StreamsSolverFactory
import it.unibo.tuprolog.solve.channel.InputChannel
import it.unibo.tuprolog.solve.channel.OutputChannel
import it.unibo.tuprolog.solve.exception.PrologWarning
import it.unibo.tuprolog.solve.getAllOperators
import it.unibo.tuprolog.solve.library.Libraries
import it.unibo.tuprolog.solve.toOperatorSet
import it.unibo.tuprolog.theory.Theory

/**
Expand Down Expand Up @@ -100,7 +110,6 @@ internal data class StreamsExecutionContext(
outputChannels = outputChannels
)
}

}

/** Extension method to get [SideEffectManagerImpl], if this context is of right type*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,4 @@ interface FinalState : State {

/** The [Solve.Response] characterizing this Final State */
override val solve: Solve.Response

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,4 @@ interface IntermediateState : State {

override val context: ExecutionContext
get() = solve.context

}
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,8 @@ internal class StateGoalEvaluation(
var responses: Sequence<Solve.Response>? = null
try {
responses = primitive(solve) // execute primitive

} catch (exception: HaltException) {

yield(stateEndHalt(exception))

} catch (prologError: PrologError) {
// if primitive throws PrologError try to solve corresponding throw/1 request

Expand All @@ -45,14 +42,12 @@ internal class StateGoalEvaluation(

var allSideEffectsSoFar = emptyList<SideEffect>()
responses?.forEach {

allSideEffectsSoFar = allSideEffectsSoFar.addWithNoDuplicates(it.sideEffects)

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))
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,15 @@ internal class StateInit(
else -> when {
currentGoal.isWellFormed() -> currentGoal.prepareForExecutionAsGoal().also { preparedGoal ->
// a primitive call or well-formed goal
yield(StateGoalEvaluation(
solve.copy(
signature = preparedGoal.extractSignature(),
arguments = preparedGoal.argsList,
context = with(solve.context) { copy(sideEffectManager = initializedSideEffectsManager) }
yield(
StateGoalEvaluation(
solve.copy(
signature = preparedGoal.extractSignature(),
arguments = preparedGoal.argsList,
context = with(solve.context) { copy(sideEffectManager = initializedSideEffectsManager) }
)
)
))
)
}

// goal non well-formed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,17 @@ import it.unibo.tuprolog.solve.Solution
import it.unibo.tuprolog.solve.currentTimeInstant
import it.unibo.tuprolog.solve.forEachWithLookahead
import it.unibo.tuprolog.solve.primitive.Solve
import it.unibo.tuprolog.solve.solver.*
import it.unibo.tuprolog.solve.solver.fsm.*
import it.unibo.tuprolog.solve.solver.StreamsExecutionContext
import it.unibo.tuprolog.solve.solver.extendParentScopeWith
import it.unibo.tuprolog.solve.solver.fsm.AlreadyExecutedState
import it.unibo.tuprolog.solve.solver.fsm.FinalState
import it.unibo.tuprolog.solve.solver.fsm.State
import it.unibo.tuprolog.solve.solver.fsm.StateMachineExecutor
import it.unibo.tuprolog.solve.solver.fsm.asAlreadyExecuted
import it.unibo.tuprolog.solve.solver.moreThanOne
import it.unibo.tuprolog.solve.solver.newSolveRequest
import it.unibo.tuprolog.solve.solver.orderWithStrategy
import it.unibo.tuprolog.solve.solver.shouldCutExecuteInRuleSelection
import it.unibo.tuprolog.unify.Unificator.Companion.mguWith

/**
Expand All @@ -33,58 +42,58 @@ internal class StateRuleSelection(
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 = currentGoal mguWith 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
else ->
with(solve.context) {
matchingRules.orderWithStrategy(this, solverStrategies::clauseChoiceStrategy)
}.map { it.prepareForExecution().freshCopy() as Rule }
.forEachWithLookahead { refreshedRule, hasAlternatives ->
val unifyingSubstitution = currentGoal mguWith 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 (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 (cutNextSiblings) return@sequence // cut here other matching rules trial
}
if (cutNextSiblings) return@sequence // cut here other matching rules trial
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@ package it.unibo.tuprolog.solve.stdlib
import it.unibo.tuprolog.solve.Signature
import it.unibo.tuprolog.solve.library.AliasedLibrary
import it.unibo.tuprolog.solve.primitive.Primitive
import it.unibo.tuprolog.solve.stdlib.primitive.*
import it.unibo.tuprolog.solve.stdlib.primitive.Call
import it.unibo.tuprolog.solve.stdlib.primitive.Catch
import it.unibo.tuprolog.solve.stdlib.primitive.Conjunction
import it.unibo.tuprolog.solve.stdlib.primitive.Cut
import it.unibo.tuprolog.solve.stdlib.primitive.Not
import it.unibo.tuprolog.solve.stdlib.primitive.Throw

object DefaultBuiltins : AliasedLibrary by CommonBuiltins {

Expand All @@ -17,4 +22,4 @@ object DefaultBuiltins : AliasedLibrary by CommonBuiltins {
Not
).map { it.descriptionPair }.toMap()
}
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
package it.unibo.tuprolog.solve.stdlib.primitive

import it.unibo.tuprolog.solve.primitive.Solve
import it.unibo.tuprolog.solve.StreamsSolver
import it.unibo.tuprolog.solve.exception.error.TypeError
import it.unibo.tuprolog.solve.primitive.PrimitiveWrapper
import it.unibo.tuprolog.solve.solver.*
import it.unibo.tuprolog.solve.primitive.Solve
import it.unibo.tuprolog.solve.solver.StreamsExecutionContext
import it.unibo.tuprolog.solve.solver.isWellFormed
import it.unibo.tuprolog.solve.solver.newSolveRequest
import it.unibo.tuprolog.solve.solver.prepareForExecutionAsGoal
import it.unibo.tuprolog.solve.solver.replyWith
import it.unibo.tuprolog.solve.solver.resetCutWorkChanges

/**
* Implementation of primitive handling `call/1` behaviour
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@ package it.unibo.tuprolog.solve.stdlib.primitive

import it.unibo.tuprolog.core.Struct
import it.unibo.tuprolog.core.Term
import it.unibo.tuprolog.solve.primitive.Solve
import it.unibo.tuprolog.solve.StreamsSolver
import it.unibo.tuprolog.solve.currentTimeInstant
import it.unibo.tuprolog.solve.primitive.PrimitiveWrapper
import it.unibo.tuprolog.solve.solver.*
import it.unibo.tuprolog.solve.primitive.Solve
import it.unibo.tuprolog.solve.solver.SideEffectManagerImpl
import it.unibo.tuprolog.solve.solver.StreamsExecutionContext
import it.unibo.tuprolog.solve.solver.isSelectedThrowCatch
import it.unibo.tuprolog.solve.solver.newSolveRequest
import it.unibo.tuprolog.solve.solver.replyWith

/**
* Implementation of primitive handling `catch/3` behaviour
Expand All @@ -23,7 +27,6 @@ internal object Catch : PrimitiveWrapper<StreamsExecutionContext>("catch", 3) {
when {
// if i'm the catch selected by throw/1 primitive
goalResponse.sideEffectManager.isSelectedThrowCatch(request.context) -> {

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
Expand Down
Loading

0 comments on commit b8b465e

Please sign in to comment.