checker: require .sort() body for some types (#10550)

pull/10594/head
shadowninja55 2021-06-27 10:17:03 -04:00 committed by GitHub
parent bafea57622
commit ea3983a91b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 37 additions and 0 deletions

View File

@ -2196,6 +2196,10 @@ fn (mut c Checker) array_builtin_method_call(mut call_expr ast.CallExpr, left_ty
'`.sort()` requires a `<` or `>` comparison as the first and only argument' +
'\ne.g. `users.sort(a.id < b.id)`', call_expr.pos)
}
} else if !(c.table.get_type_symbol(elem_typ).has_method('<')
|| c.table.unalias_num_type(elem_typ) in [ast.int_type, ast.int_type.to_ptr(), ast.string_type, ast.string_type.to_ptr(), ast.i8_type, ast.i16_type, ast.i64_type, ast.byte_type, ast.rune_type, ast.u16_type, ast.u32_type, ast.u64_type, ast.f32_type, ast.f64_type, ast.char_type, ast.bool_type, ast.float_literal_type, ast.int_literal_type, ast.size_t_type_idx]) {
c.error('custom sorting condition must be supplied for type `${c.table.type_to_str(elem_typ)}`',
call_expr.pos)
}
} else if method_name == 'wait' {
elem_sym := c.table.get_type_symbol(elem_typ)

View File

@ -0,0 +1,5 @@
vlib/v/checker/tests/array_sort_struct_no_body_err.vv:6:5: error: custom sorting condition must be supplied for type `Foo`
4 |
5 | mut arr := []Foo{}
6 | arr.sort()
| ~~~~~~

View File

@ -0,0 +1,6 @@
struct Foo {
bar int
}
mut arr := []Foo{}
arr.sort()

View File

@ -0,0 +1,22 @@
struct Num {
value int
}
fn (a Num) < (b Num) bool {
return a.value < b.value
}
fn test_sort_lt_overloaded_struct_array() {
mut arr := []Num{}
arr << {
value: 10
}
arr << {
value: 5
}
arr << {
value: 7
}
arr.sort()
assert arr[0].value == 5
}