From dd6febf6fa0573a88151ec436022f0a62ef00a84 Mon Sep 17 00:00:00 2001 From: yuyi Date: Wed, 13 Jan 2021 13:12:22 +0800 Subject: [PATCH] cgen: fix gen_array_sort() (#8077) --- vlib/v/gen/array.v | 4 ++-- vlib/v/tests/sorting_by_different_criteria_test.v | 6 ++++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/vlib/v/gen/array.v b/vlib/v/gen/array.v index 4e9ea5a594..584502415a 100644 --- a/vlib/v/gen/array.v +++ b/vlib/v/gen/array.v @@ -254,9 +254,9 @@ fn (mut g Gen) gen_array_sort(node ast.CallExpr) { // when generating the function as long as the args are named the same. g.definitions.writeln('int $compare_fn ($styp* a, $styp* b) {') sym := g.table.get_type_symbol(typ) - if sym.has_method('<') && infix_expr.left.str().len == 1 { + if !is_reverse && sym.has_method('<') && infix_expr.left.str().len == 1 { g.definitions.writeln('\tif (${styp}__lt(*a, *b)) { return -1; } else { return 1; }}') - } else if sym.has_method('>') && infix_expr.left.str().len == 1 { + } else if is_reverse && sym.has_method('>') && infix_expr.left.str().len == 1 { g.definitions.writeln('\tif (${styp}__gt(*a, *b)) { return -1; } else { return 1; }}') } else { field_type := g.typ(infix_expr.left_type) diff --git a/vlib/v/tests/sorting_by_different_criteria_test.v b/vlib/v/tests/sorting_by_different_criteria_test.v index b40297d3a3..8b6e679dc1 100644 --- a/vlib/v/tests/sorting_by_different_criteria_test.v +++ b/vlib/v/tests/sorting_by_different_criteria_test.v @@ -11,6 +11,10 @@ fn (p Parent) < (p1 Parent) bool { return p.name < p1.name } +fn (p Parent) > (p1 Parent) bool { + return p.name > p1.name +} + fn test_sorting_by_different_criteria_in_same_function() { mut arr := [ Parent{Child{0.2}, 'def'}, @@ -26,4 +30,6 @@ fn test_sorting_by_different_criteria_in_same_function() { assert arr[0].name == 'xyz' arr.sort(a < b) assert arr[0].name == 'abc' + arr.sort(a > b) + assert arr[0].name == 'xyz' }