Skip to content

Commit

Permalink
fixes #2139 by catching the IndexOutOfBoundsException and searching f…
Browse files Browse the repository at this point in the history
…or a reflexive element that may have caused it. Tests for this error case are very hard to write to the randomized shuffling in the sort algorithm
  • Loading branch information
jurgenvinju committed Feb 4, 2025
1 parent a4d16d9 commit 14e8d7b
Showing 1 changed file with 27 additions and 12 deletions.
39 changes: 27 additions & 12 deletions src/org/rascalmpl/library/Prelude.java
Original file line number Diff line number Diff line change
Expand Up @@ -1578,7 +1578,7 @@ public Sorting sort() {
}
if (less.less(array[0], array[0])) {
throw RuntimeExceptionFactory.illegalArgument(less.less,
"Bad comparator: Did you use less-or-equals instead of less-than?");
"A reflexive comparator can not be used for sorting. At least one element is less than itself: " + less);
}
sort(0, size - 1);

Expand All @@ -1597,16 +1597,33 @@ private void sort(int low, int high) {
int oldLow = low;
int oldHigh = high;

while (low < high) {
for (; less.less(array[low], pivot); low++);
for (; less.less(pivot, array[high]); high--);

if (low <= high) {
swap(low, high);
low++;
high--;
try {
while (low < high) {
for (; less.less(array[low], pivot); low++);
for (; less.less(pivot, array[high]); high--);

if (low <= high) {
swap(low, high);
low++;
high--;
}
}
}
catch (IndexOutOfBoundsException e) {
// now that we are crashing anyway, we can do some diagnostics.
// the hypothesis is that at least one element was not irreflexive, making
// one of the bounds pointers (low or high) shift beyond the edge of the array

for (IValue elem : array) {
if (less.less(elem, elem)) {
throw RuntimeExceptionFactory.illegalArgument(less.less,
"A reflexive comparator can not be used for sorting. At least one element is less than itself with the given comparator: " + elem);
}
}

// another cause for the same exception?
throw e;
}

if (oldLow < high)
sort(oldLow, high);
Expand Down Expand Up @@ -1665,9 +1682,7 @@ public IList sort(ISet l, IFunction cmpv) {
new Sorting(tmpArr, new Less(cmpv)).sort();

IListWriter writer = values.listWriter();
for(IValue v : tmpArr){
writer.append(v);
}
writer.append(tmpArr);

return writer.done();
}
Expand Down

0 comments on commit 14e8d7b

Please sign in to comment.