Skip to content

Commit

Permalink
jsonnet does not support sorting with booleans
Browse files Browse the repository at this point in the history
  • Loading branch information
JoshRosen committed Dec 28, 2024
1 parent 24b5b38 commit 6d00ac1
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
10 changes: 6 additions & 4 deletions sjsonnet/src/sjsonnet/Std.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1702,6 +1702,9 @@ class Std(private val additionalNativeFunctions: Map[String, Val.Builtin] = Map.
new Val.Arr(pos, if (keyFFunc != null) {
val keys: Array[Val] = vs.map(v => keyFFunc(Array(v.force), null, pos.noOffset)(ev).force)
val keyType = keys(0).getClass
if (classOf[Val.Bool].isAssignableFrom(keyType)) {
Error.fail("Cannot sort with key values that are booleans")
}
if (!keys.forall(_.getClass == keyType)) {
Error.fail("Cannot sort with key values that are not all the same type")
}
Expand All @@ -1712,24 +1715,23 @@ class Std(private val additionalNativeFunctions: Map[String, Val.Builtin] = Map.
indices.sortBy(i => keys(i).cast[Val.Str].asString)
} else if (keyType == classOf[Val.Num]) {
indices.sortBy(i => keys(i).cast[Val.Num].asDouble)
} else if (keyType == classOf[Val.Bool]) {
indices.sortBy(i => keys(i).cast[Val.Bool].asBoolean)
} else {
Error.fail("Cannot sort with key values that are " + keys(0).prettyName + "s")
}

sortedIndices.map(i => vs(i))
} else {
val keyType = vs(0).force.getClass
if (classOf[Val.Bool].isAssignableFrom(keyType)) {
Error.fail("Cannot sort with values that are booleans")
}
if (!vs.forall(_.force.getClass == keyType))
Error.fail("Cannot sort with values that are not all the same type")

if (keyType == classOf[Val.Str]) {
vs.map(_.force.cast[Val.Str]).sortBy(_.asString)
} else if (keyType == classOf[Val.Num]) {
vs.map(_.force.cast[Val.Num]).sortBy(_.asDouble)
} else if (keyType == classOf[Val.Bool]) {
vs.map(_.force.cast[Val.Bool]).sortBy(_.asBoolean)
} else if (keyType == classOf[Val.Obj]) {
Error.fail("Unable to sort array of objects without key function")
} else {
Expand Down
5 changes: 5 additions & 0 deletions sjsonnet/test/src/sjsonnet/StdWithKeyFTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ object StdWithKeyFTests extends TestSuite {
evalErr("""std.sort([1,2, error "foo"])""").startsWith("sjsonnet.Error: foo"))
assert(
evalErr("""std.sort([1, [error "foo"]])""").startsWith("sjsonnet.Error: Cannot sort with values that are not all the same type"))
// google/go-jsonnet and google/jsonnet also error on sorting of booleans:
assert(
evalErr("""std.sort([false, true])""").startsWith("sjsonnet.Error: Cannot sort with values that are booleans"))
assert(
evalErr("""std.sort([1, 2], keyF=function(x) x == 1)""").startsWith("sjsonnet.Error: Cannot sort with key values that are booleans"))

eval(
"""local arr = [
Expand Down

0 comments on commit 6d00ac1

Please sign in to comment.