From 2b9ffbda4236fd38d5eb5016c22c04aad4d1dd34 Mon Sep 17 00:00:00 2001 From: yuyi Date: Thu, 4 Mar 2021 18:19:02 +0800 Subject: [PATCH] cgen: fix array_sort by different order of a/b (#9106) --- vlib/builtin/array_test.v | 12 ++++++++++++ vlib/builtin/string_test.v | 8 ++++---- vlib/v/gen/c/array.v | 6 ++++-- 3 files changed, 20 insertions(+), 6 deletions(-) diff --git a/vlib/builtin/array_test.v b/vlib/builtin/array_test.v index dbac00081c..06adc9c716 100644 --- a/vlib/builtin/array_test.v +++ b/vlib/builtin/array_test.v @@ -807,6 +807,18 @@ fn test_sort() { // assert users.map(it.name).join(' ') == 'Alice Bob Peter' } +fn test_sort_by_different_order_of_a_b() { + mut x := [1, 2, 3] + x.sort(a < b) + println(x) + assert x == [1, 2, 3] + + mut y := [1, 2, 3] + y.sort(b < a) + println(y) + assert y == [3, 2, 1] +} + fn test_f32_sort() { mut f := [f32(50.0), 15, 1, 79, 38, 0, 27] f.sort_with_compare(compare_f32) diff --git a/vlib/builtin/string_test.v b/vlib/builtin/string_test.v index 820a23ca44..ad7dec5573 100644 --- a/vlib/builtin/string_test.v +++ b/vlib/builtin/string_test.v @@ -106,10 +106,10 @@ fn test_sort_reverse() { len := vals.len vals.sort(b>a) assert len == vals.len - assert vals[3] == 'a' - assert vals[2] == 'an' - assert vals[1] == 'any' - assert vals[0] == 'arr' + assert vals[0] == 'a' + assert vals[1] == 'an' + assert vals[2] == 'any' + assert vals[3] == 'arr' } fn test_split_nth() { diff --git a/vlib/v/gen/c/array.v b/vlib/v/gen/c/array.v index 483f683e46..ab3f9e4d0c 100644 --- a/vlib/v/gen/c/array.v +++ b/vlib/v/gen/c/array.v @@ -219,8 +219,10 @@ fn (mut g Gen) gen_array_sort(node ast.CallExpr) { is_default = true } else { infix_expr := node.args[0].expr as ast.InfixExpr - is_default = '$infix_expr.left' in ['a', 'b'] && '$infix_expr.right' in ['a', 'b'] - is_reverse = infix_expr.op == .gt + left_name := '$infix_expr.left' + is_default = left_name in ['a', 'b'] && '$infix_expr.right' in ['a', 'b'] + is_reverse = (left_name.starts_with('a') && infix_expr.op == .gt) + || (left_name.starts_with('b') && infix_expr.op == .lt) } if is_default { // users.sort() or users.sort(a > b)