commit ea8aa9f63cf6cb3383092245ef716271da2db3ff Author: eater <=@eater.me> Date: Fri Sep 27 17:43:41 2019 +0200 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..239a4ff --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.idea +.gradle +/build/ diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..bbf217d --- /dev/null +++ b/build.gradle @@ -0,0 +1,53 @@ +plugins { + id 'org.jetbrains.kotlin.multiplatform' version '1.3.50' +} +repositories { + mavenCentral() +} +group 'net.cijber' +version '0.0.1' + +apply plugin: 'maven-publish' + +kotlin { + jvm() + js { + browser { + } + nodejs { + } + } + // For ARM, should be changed to iosArm32 or iosArm64 + // For Linux, should be changed to e.g. linuxX64 + // For MacOS, should be changed to e.g. macosX64 + // For Windows, should be changed to e.g. mingwX64 + linuxX64("linux") + sourceSets { + commonMain { + dependencies { + implementation kotlin('stdlib-common') + } + } + commonTest { + dependencies { + implementation kotlin('test-common') + implementation kotlin('test-annotations-common') + } + } + jvmMain { + dependencies { + implementation kotlin('stdlib-jdk8') + } + } + jvmTest { + dependencies { + implementation kotlin('test') + implementation kotlin('test-junit') + } + } + linuxMain { + } + linuxTest { + } + } +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..29e08e8 --- /dev/null +++ b/gradle.properties @@ -0,0 +1 @@ +kotlin.code.style=official \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..94336fc Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ca9d628 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-all.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..cccdd3d --- /dev/null +++ b/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..e95643d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..38dc43d --- /dev/null +++ b/settings.gradle @@ -0,0 +1,4 @@ +rootProject.name = 'pubgrub' + + +enableFeaturePreview('GRADLE_METADATA') diff --git a/src/commonMain/kotlin/Assignment.kt b/src/commonMain/kotlin/Assignment.kt new file mode 100644 index 0000000..08bd58b --- /dev/null +++ b/src/commonMain/kotlin/Assignment.kt @@ -0,0 +1,16 @@ +package net.cijber.pubgrub + +import net.cijber.pubgrub.packages.PackageSelection +import net.cijber.pubgrub.stubs.PackageId +import net.cijber.pubgrub.stubs.Version + +class Assignment
>( + selection: PackageSelection
, + exclusive: Boolean, + val cause: Incompatibility
? = null, + val decisionLevel: Int = 0, + val index: Int = 0 +) : Term
(selection, exclusive) { + val isDecision: Boolean + get() = cause == null +} \ No newline at end of file diff --git a/src/commonMain/kotlin/Incompatibility.kt b/src/commonMain/kotlin/Incompatibility.kt new file mode 100644 index 0000000..09a4a93 --- /dev/null +++ b/src/commonMain/kotlin/Incompatibility.kt @@ -0,0 +1,9 @@ +package net.cijber.pubgrub + +import net.cijber.pubgrub.stubs.PackageId +import net.cijber.pubgrub.stubs.Version + +data class Incompatibility
>(val terms: List ) {
+ val isFailure: Boolean
+ get() = terms.isEmpty() || (terms.count() == 1 && terms.first().pkg.isRoot);
+}
\ No newline at end of file
diff --git a/src/commonMain/kotlin/IncompatibilityCause.kt b/src/commonMain/kotlin/IncompatibilityCause.kt
new file mode 100644
index 0000000..e70b34f
--- /dev/null
+++ b/src/commonMain/kotlin/IncompatibilityCause.kt
@@ -0,0 +1,20 @@
+package net.cijber.pubgrub
+
+import net.cijber.pubgrub.stubs.PackageId
+import net.cijber.pubgrub.stubs.Version
+
+sealed class IncompatibilityCause > {
+ enum class SimpleCause {
+ Root,
+ Dependency,
+ UseLatest,
+ NoVersions,
+ UnknownSource
+ }
+
+ data class Simple >(val cause: SimpleCause) : IncompatibilityCause ()
+ data class ConflictCause >(
+ val conflict: Incompatibility ,
+ val other: Incompatibility
+ ) : IncompatibilityCause ()
+}
\ No newline at end of file
diff --git a/src/commonMain/kotlin/PartialSolution.kt b/src/commonMain/kotlin/PartialSolution.kt
new file mode 100644
index 0000000..32c2fee
--- /dev/null
+++ b/src/commonMain/kotlin/PartialSolution.kt
@@ -0,0 +1,105 @@
+package net.cijber.pubgrub
+
+import net.cijber.pubgrub.packages.PackageSelection
+import net.cijber.pubgrub.stubs.PackageId
+import net.cijber.pubgrub.stubs.Version
+
+class PartialSolution > {
+ private var decisionLevel = 0
+ private val assignments = mutableListOf >()
+ private val negative = mutableMapOf >()
+
+ infix fun relation(term: Term ): SetRelation {
+ positive.get(term.pkg)?.let {
+ return it relation term
+ }
+
+ negative.get(term.pkg)?.let {
+ return it relation term
+ }
+
+ return SetRelation.Overlaps
+ }
+
+ fun derive(pkg: PackageSelection , exclusive: Boolean, incompatibility: Incompatibility ) {
+ assign(Assignment(pkg, !exclusive, incompatibility, decisionLevel, assignments.count()))
+ }
+
+ private fun assign(assignment: Assignment ) {
+ assignments.add(assignment)
+ register(assignment)
+ }
+
+ private fun register(assignment: Assignment ) {
+ val pkg = assignment.pkg
+ val oldPositive = positive[pkg]
+ if (oldPositive != null) {
+ positive.remove(pkg)
+ oldPositive.intersect(assignment)?.let {
+ positive[pkg] = it
+ }
+ }
+
+ val oldNegative = negative[pkg]
+ val term = if (oldNegative == null) {
+ assignment
+ } else {
+ assignment.intersect(oldNegative)!!
+ }
+
+ if (!term.exclusive) {
+ negative.remove(pkg)
+ positive[pkg] = term
+ } else {
+ negative[pkg] = term
+ }
+ }
+
+ fun satisfier(term: Term ): Assignment {
+ var assignedTerm: Term ? = null;
+ for (assignment in assignments) {
+ if (assignment.pkg != term.pkg) continue
+
+ assignedTerm = if (assignedTerm == null) {
+ assignment
+ } else {
+ assignedTerm.intersect(assignment)
+ }
+
+ if (assignedTerm?.satisfies(term) == true) {
+ return assignment
+ }
+ }
+
+ error("[BUG] $term is not satisfied")
+ }
+
+ fun backtrack(decisionLevel: Int) {
+ backtracking = true
+ val packages = mutableSetOf ()
+ while (assignments.lastOrNull()?.decisionLevel?.let { it > decisionLevel } == true) {
+ val removed = assignments.removeAt(assignments.lastIndex)
+ packages.add(removed.pkg)
+
+ if (removed.isDecision) {
+ decisions.remove(removed)
+ }
+ }
+
+ for (pkg in packages) {
+ positive.remove(pkg)
+ negative.remove(pkg)
+ }
+
+ for (assignment in assignments) {
+ if (packages.contains(assignment.pkg)) {
+ register(assignment)
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/commonMain/kotlin/SetRelation.kt b/src/commonMain/kotlin/SetRelation.kt
new file mode 100644
index 0000000..c665cc1
--- /dev/null
+++ b/src/commonMain/kotlin/SetRelation.kt
@@ -0,0 +1,9 @@
+package net.cijber.pubgrub
+
+enum class SetRelation {
+ Disjoint,
+ Overlaps,
+ Equal,
+ Superset,
+ Subset;
+}
\ No newline at end of file
diff --git a/src/commonMain/kotlin/Solver.kt b/src/commonMain/kotlin/Solver.kt
new file mode 100644
index 0000000..5c6e1f4
--- /dev/null
+++ b/src/commonMain/kotlin/Solver.kt
@@ -0,0 +1,164 @@
+package net.cijber.pubgrub
+
+import net.cijber.pubgrub.packages.PackageSelection
+import net.cijber.pubgrub.packages.PackageVersion
+import net.cijber.pubgrub.stubs.PackageId
+import net.cijber.pubgrub.stubs.PackageRetriever
+import net.cijber.pubgrub.stubs.Version
+import net.cijber.pubgrub.version.VersionRange
+
+class Solver >(
+ val packageRetriever: PackageRetriever ,
+ private val root: PackageVersion
+) {
+ private val incompatibilities: MutableMap >> = mutableMapOf(
+ root.pkg to mutableListOf(
+ Incompatibility(
+ listOf(Term(PackageSelection(root.pkg, VersionRange.single(root.version)), true)),
+ IncompatibilityCause.Simple(IncompatibilityCause.SimpleCause.Root)
+ )
+ )
+ )
+
+ private val solution = PartialSolution ()
+
+ suspend fun solve() {
+ var next: P? = root.pkg
+ while (next != null) {
+ propagate(next)
+ next = choosePackageVersion()
+ }
+ }
+
+ private fun propagate(pkg: P) {
+ val changed = mutableSetOf(pkg)
+
+ while (changed.isNotEmpty()) {
+ val currentPkg = changed.first()
+ changed.remove(currentPkg)
+
+ for (incompat in incompatibilities.getOrPut(currentPkg, ::mutableListOf).reversed()) {
+ val result = propagateIncompatibility(incompat)
+
+ if (result == PropagationResult.Conflict) {
+ val rootCause = resolveConflict(incompat)
+ changed.clear()
+ @Suppress("UNCHECKED_CAST")
+ changed.add((propagateIncompatibility(rootCause) as? PropagationResult.Unsatisfied )!!.pkg)
+ break
+ }
+
+ if (result is PropagationResult.Unsatisfied<*>) {
+ @Suppress("UNCHECKED_CAST")
+ changed.add(result.pkg as P)
+ }
+ }
+ }
+ }
+
+ private fun resolveConflict(incompat: Incompatibility ): Incompatibility {
+ var workingIncompatibility = incompat
+ var newIncompatibility = false
+ while (!incompat.isFailure) {
+ var mostRecentTerm: Term ? = null
+ var mostRecentSatisfier: Assignment ? = null
+ var difference: Term ? = null
+
+ var previousSatisfierLevel = 1
+
+ for (term in workingIncompatibility.terms) {
+ val satisfier = solution.satisfier(term)
+
+ if (mostRecentSatisfier == null) {
+ mostRecentTerm = term
+ mostRecentSatisfier = satisfier
+ } else if (mostRecentSatisfier.index < satisfier.index) {
+ previousSatisfierLevel = maxOf(previousSatisfierLevel, mostRecentSatisfier.decisionLevel)
+ mostRecentTerm = term;
+ mostRecentSatisfier = satisfier;
+ difference = null;
+ } else {
+ previousSatisfierLevel = maxOf(previousSatisfierLevel, satisfier.decisionLevel)
+ }
+
+ if (mostRecentTerm == term) {
+ difference = mostRecentSatisfier.difference(mostRecentTerm)
+ if (difference != null) {
+ previousSatisfierLevel = maxOf(
+ previousSatisfierLevel,
+ solution.satisfier(difference.inverse).decisionLevel
+ )
+ }
+ }
+ }
+
+ if (previousSatisfierLevel < mostRecentSatisfier!!.decisionLevel ||
+ mostRecentSatisfier.cause == null
+ ) {
+ solution.backtrack(previousSatisfierLevel);
+ if (newIncompatibility) {
+ addIncompatibility(workingIncompatibility)
+ }
+
+ return workingIncompatibility
+ }
+
+ val newTerms = workingIncompatibility.terms.filter { it != mostRecentTerm }.toMutableList()
+
+ mostRecentSatisfier.cause?.let {
+ newTerms.addAll(it.terms.filter { term -> term.pkg != mostRecentSatisfier.pkg })
+ }
+
+ if (difference != null) {
+ newTerms.add(difference.inverse)
+ }
+
+ workingIncompatibility = Incompatibility(
+ newTerms,
+ IncompatibilityCause.ConflictCause(workingIncompatibility, mostRecentSatisfier.cause!!)
+ )
+ }
+
+ error("Failed")
+ }
+
+ private fun addIncompatibility(incompat: Incompatibility ) {
+ for (term in incompat.terms) {
+ incompatibilities.getOrPut(term.pkg, { mutableListOf() }).add(incompat)
+ }
+ }
+
+ private fun propagateIncompatibility(incompatibility: Incompatibility ): PropagationResult {
+ val unsatisfied = run {
+ var unsatisfied: Term ? = null;
+
+ for (term in incompatibility.terms) {
+ when (val relation = solution.relation(term)) {
+ SetRelation.Disjoint -> return PropagationResult.None
+ SetRelation.Overlaps, SetRelation.Subset, SetRelation.Superset -> {
+ if (unsatisfied != null) {
+ return PropagationResult.None
+ }
+
+ unsatisfied = term
+ }
+ }
+ }
+
+ unsatisfied
+ } ?: return PropagationResult.Conflict
+
+ solution.derive(unsatisfied.pkgSelection, !unsatisfied.exclusive, incompatibility)
+ return PropagationResult.Unsatisfied(unsatisfied.pkg)
+ }
+
+ private sealed class PropagationResult {
+ object None : PropagationResult()
+ object Conflict : PropagationResult()
+ class Unsatisfied (val pkg: P) : PropagationResult()
+ }
+
+ private fun choosePackageVersion(): P? {
+ return null
+ }
+}
\ No newline at end of file
diff --git a/src/commonMain/kotlin/Term.kt b/src/commonMain/kotlin/Term.kt
new file mode 100644
index 0000000..780dc0d
--- /dev/null
+++ b/src/commonMain/kotlin/Term.kt
@@ -0,0 +1,63 @@
+package net.cijber.pubgrub
+
+import net.cijber.pubgrub.packages.PackageSelection
+import net.cijber.pubgrub.stubs.PackageId
+import net.cijber.pubgrub.stubs.Version
+import net.cijber.pubgrub.version.VersionConstraint
+
+
+open class Term >(val pkgSelection: PackageSelection , val exclusive: Boolean) {
+ val constraint
+ get() = pkgSelection.constraint
+
+ val pkg
+ get() = pkgSelection.pkg
+
+ val inverse by lazy {
+ Term(pkgSelection, !exclusive)
+ }
+
+ infix fun relation(rhs: Term ): SetRelation {
+ if (rhs.pkg !== pkg) {
+ throw RuntimeException("Relations between terms can only be compared if they have the same package id")
+ }
+
+ val rhsConstraint = rhs.constraint
+ if (!rhs.exclusive) {
+ if (exclusive) {
+ if (rhsConstraint.allowsAll(constraint))
+ return SetRelation.Subset
+ }
+ }
+
+ return SetRelation.Disjoint
+ }
+
+ fun intersect(rhs: Term ): Term ? {
+ if (rhs.pkg !== pkg) {
+ throw RuntimeException("Relations between terms can only be compared if they have the same package id")
+ }
+
+ return if (exclusive != rhs.exclusive) {
+ val positive = if (!exclusive) this else rhs
+ val negative = if (!exclusive) rhs else this
+
+ nonEmptyTerm(positive.constraint.difference(negative.constraint), false)
+ } else if (!exclusive) {
+ nonEmptyTerm(constraint.intersect(rhs.constraint), false)
+ } else {
+ nonEmptyTerm(constraint.union(rhs.constraint), true)
+ }
+ }
+
+ private fun nonEmptyTerm(constraint: VersionConstraint ? {
+ if (constraint.isEmpty) return null
+
+ return Term(PackageSelection(pkg, constraint), exclusive)
+ }
+
+ fun satisfies(term: Term ): Boolean = term.pkg == pkg &&
+ (relation(term) == SetRelation.Subset || relation(term) == SetRelation.Equal)
+
+ fun difference(rhs: Term ) = intersect(rhs.inverse)
+}
\ No newline at end of file
diff --git a/src/commonMain/kotlin/packages/PackageSelection.kt b/src/commonMain/kotlin/packages/PackageSelection.kt
new file mode 100644
index 0000000..800c730
--- /dev/null
+++ b/src/commonMain/kotlin/packages/PackageSelection.kt
@@ -0,0 +1,13 @@
+package net.cijber.pubgrub.packages
+
+import net.cijber.pubgrub.stubs.PackageId
+import net.cijber.pubgrub.stubs.Version
+import net.cijber.pubgrub.version.VersionConstraint
+
+data class PackageSelection >(
+ val pkg: P,
+ val constraint: VersionConstraint ): PackageSelection =
+ PackageSelection(pkg, constraint.intersect(rhs.constraint))
+}
\ No newline at end of file
diff --git a/src/commonMain/kotlin/packages/PackageVersion.kt b/src/commonMain/kotlin/packages/PackageVersion.kt
new file mode 100644
index 0000000..325d9b7
--- /dev/null
+++ b/src/commonMain/kotlin/packages/PackageVersion.kt
@@ -0,0 +1,6 @@
+package net.cijber.pubgrub.packages
+
+import net.cijber.pubgrub.stubs.PackageId
+import net.cijber.pubgrub.stubs.Version
+
+data class PackageVersion >(val pkg: P, val version: V)
\ No newline at end of file
diff --git a/src/commonMain/kotlin/stubs/PackageId.kt b/src/commonMain/kotlin/stubs/PackageId.kt
new file mode 100644
index 0000000..6a08f2f
--- /dev/null
+++ b/src/commonMain/kotlin/stubs/PackageId.kt
@@ -0,0 +1,5 @@
+package net.cijber.pubgrub.stubs
+
+interface PackageId {
+ val isRoot: Boolean
+}
\ No newline at end of file
diff --git a/src/commonMain/kotlin/stubs/PackageRetriever.kt b/src/commonMain/kotlin/stubs/PackageRetriever.kt
new file mode 100644
index 0000000..2ac3ffd
--- /dev/null
+++ b/src/commonMain/kotlin/stubs/PackageRetriever.kt
@@ -0,0 +1,8 @@
+package net.cijber.pubgrub.stubs
+
+import net.cijber.pubgrub.Term
+
+interface PackageRetriever