From b870f7a6f109132e68cdb317e8af86a01caf913a Mon Sep 17 00:00:00 2001 From: yuyi Date: Wed, 4 Aug 2021 11:31:57 +0800 Subject: [PATCH] cgen: fix array sort error (#11046) --- vlib/builtin/array_test.v | 18 ++++++++++++++++++ vlib/v/gen/c/array.v | 10 ++++++++-- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/vlib/builtin/array_test.v b/vlib/builtin/array_test.v index d7699ca954..288a884011 100644 --- a/vlib/builtin/array_test.v +++ b/vlib/builtin/array_test.v @@ -897,6 +897,24 @@ fn test_i64_sort() { assert f[6] == 79 } +fn test_a_b_paras_sort() { + mut arr_i := [1, 3, 2] + arr_i.sort(a < b) + println(arr_i) + assert arr_i == [1, 2, 3] + arr_i.sort(b < a) + println(arr_i) + assert arr_i == [3, 2, 1] + + mut arr_f := [1.1, 3.3, 2.2] + arr_f.sort(a < b) + println(arr_f) + assert arr_f == [1.1, 2.2, 3.3] + arr_f.sort(b < a) + println(arr_f) + assert arr_f == [3.3, 2.2, 1.1] +} + /* fn test_for_last() { numbers := [1, 2, 3, 4] diff --git a/vlib/v/gen/c/array.v b/vlib/v/gen/c/array.v index 6be4cdfcd1..c78fdbe99c 100644 --- a/vlib/v/gen/c/array.v +++ b/vlib/v/gen/c/array.v @@ -286,10 +286,16 @@ fn (mut g Gen) gen_array_sort(node ast.CallExpr) { g.definitions.writeln('\tif (${styp}__lt(*b, *a)) { return -1; } else { return 1; }}') } else { field_type := g.typ(infix_expr.left_type) + left_name := '$infix_expr.left' left_expr_str := g.expr_string(infix_expr.left) right_expr_str := g.expr_string(infix_expr.right) - g.definitions.writeln('\t$field_type a_ = $left_expr_str;') - g.definitions.writeln('\t$field_type b_ = $right_expr_str;') + if left_name.starts_with('a') { + g.definitions.writeln('\t$field_type a_ = $left_expr_str;') + g.definitions.writeln('\t$field_type b_ = $right_expr_str;') + } else { + g.definitions.writeln('\t$field_type a_ = $right_expr_str;') + g.definitions.writeln('\t$field_type b_ = $left_expr_str;') + } mut op1, mut op2 := '', '' if infix_expr.left_type == ast.string_type { if is_reverse {