builtin: check array.sort_with_compare() arg mismatch (#11385)

pull/11400/head
yuyi 2021-09-04 20:02:05 +08:00 committed by GitHub
parent 9b983bdd95
commit 5181031480
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 30 additions and 2 deletions

View File

@ -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) }
}
}

View File

@ -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 | }

View File

@ -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)
}