From 5181031480148d15ecc2ea0fbf6309fa2f56aa5f Mon Sep 17 00:00:00 2001 From: yuyi Date: Sat, 4 Sep 2021 20:02:05 +0800 Subject: [PATCH] builtin: check array.sort_with_compare() arg mismatch (#11385) --- vlib/builtin/array.v | 4 ++-- .../checker/tests/array_sort_with_compare_err.out | 15 +++++++++++++++ .../checker/tests/array_sort_with_compare_err.vv | 13 +++++++++++++ 3 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 vlib/v/checker/tests/array_sort_with_compare_err.out create mode 100644 vlib/v/checker/tests/array_sort_with_compare_err.vv diff --git a/vlib/builtin/array.v b/vlib/builtin/array.v index 0a6f4e06ec..b6d2644de9 100644 --- a/vlib/builtin/array.v +++ b/vlib/builtin/array.v @@ -146,11 +146,11 @@ pub fn (a array) repeat_to_depth(count int, depth int) array { } // sort_with_compare sorts array in-place using given `compare` function as comparator. -pub fn (mut a array) sort_with_compare(compare voidptr) { +pub fn (mut a array) sort_with_compare(callback fn (voidptr, voidptr) int) { $if freestanding { panic('sort does not work with -freestanding') } $else { - unsafe { vqsort(a.data, size_t(a.len), size_t(a.element_size), compare) } + unsafe { vqsort(a.data, size_t(a.len), size_t(a.element_size), callback) } } } diff --git a/vlib/v/checker/tests/array_sort_with_compare_err.out b/vlib/v/checker/tests/array_sort_with_compare_err.out new file mode 100644 index 0000000000..6670e5bf4e --- /dev/null +++ b/vlib/v/checker/tests/array_sort_with_compare_err.out @@ -0,0 +1,15 @@ +vlib/v/checker/tests/array_sort_with_compare_err.vv:4:26: error: cannot use `fn (string, string) int` as `fn (voidptr, voidptr) int` in argument 1 to `[]string.sort_with_compare` + 2 | mut names := ['aaa', 'bbb', 'ccc'] + 3 | + 4 | names.sort_with_compare(sort_by_file_base) + | ~~~~~~~~~~~~~~~~~ + 5 | println(names) + 6 | +Details: ``'s expected fn argument: `` is a pointer, but the passed fn argument: `a` is NOT a pointer +vlib/v/checker/tests/array_sort_with_compare_err.vv:7:26: error: cannot use `int literal` as `fn (voidptr, voidptr) int` in argument 1 to `[]string.sort_with_compare` + 5 | println(names) + 6 | + 7 | names.sort_with_compare(22) + | ~~ + 8 | println(names) + 9 | } diff --git a/vlib/v/checker/tests/array_sort_with_compare_err.vv b/vlib/v/checker/tests/array_sort_with_compare_err.vv new file mode 100644 index 0000000000..7d9ecd74af --- /dev/null +++ b/vlib/v/checker/tests/array_sort_with_compare_err.vv @@ -0,0 +1,13 @@ +fn main() { + mut names := ['aaa', 'bbb', 'ccc'] + + names.sort_with_compare(sort_by_file_base) + println(names) + + names.sort_with_compare(22) + println(names) +} + +fn sort_by_file_base(a string, b string) int { + return int(a > b) +}