Skip to content

Commit

Permalink
compareTo must implement a total ordering to be useful in Arrays.sort
Browse files Browse the repository at this point in the history
  • Loading branch information
jurgenvinju committed Jan 7, 2025
1 parent 9b46d92 commit 5893841
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
17 changes: 13 additions & 4 deletions src/main/java/io/usethesource/vallang/type/Type.java
Original file line number Diff line number Diff line change
Expand Up @@ -637,28 +637,37 @@ public Type getTypeParameters() {
}

/**
* Compare against another type.
* Compare against another type, implementing a _total_ ordering for use in
* sorting operations. After sorting with this comparator, candidate matches
* are ordered by specificity (smaller types first). A total ordering is a
* precondition to using Arrays.sort(Comparator) and List.sort(Comparator).
*
* A type is 'less' than another if it is a subtype, 'greater' if the other is
* First: a type is 'less' than another if it is a subtype, 'greater' if the other is
* a subtype, or 'equal' if both are subtypes of each other.
* Second: If types are not comparable in terms of subtype, we sort them alphabetically
* by their toString() representation.
*
* Note: this class has a natural ordering that is inconsistent with equals.
* equals() on types is exact equality, which may be different from
* compareTo(o) == 0
* Note: subtypes can be expected to be less than supertypes, but
* if a type is less than another, it does not imply a sub-type relation.
*
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(Type o) {
if (isSubtypeOf(o)) {
return o.isSubtypeOf(this)
? 0
? toString().compareTo(o.toString())
: -1;
}
else if (o.isSubtypeOf(this)) {
assert !isSubtypeOf(o);
return 1;
}
else {
return 0;
assert !isSubtypeOf(o) && !o.isSubtypeOf(this);
return toString().compareTo(o.toString());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,20 +67,20 @@ public void compareTo(Type t, Type u) {
assertTrue(t.compareTo(u) == -1);
}
else {
assertTrue(t.compareTo(u) == 0);
assertTrue(t.compareTo(u) == t.toString().compareTo(u.toString()));
}
}
else if (u.isSubtypeOf(t)) {
if (!t.equivalent(u)) {
assertTrue(t.compareTo(u) == 1);
}
else {
assertTrue(t.compareTo(u) == 0);
assertTrue(t.compareTo(u) == t.toString().compareTo(u.toString()));
}
}
else {
assertTrue(t.compareTo(u) == 0);
assertTrue(u.compareTo(t) == 0);
assertTrue(t.compareTo(u) == t.toString().compareTo(u.toString()));
assertTrue(u.compareTo(t) == u.toString().compareTo(t.toString()));
}
}

Expand Down

0 comments on commit 5893841

Please sign in to comment.