Skip to content

Commit

Permalink
checker: disallow nil in non-nil arrays and vice versa (vlang#21786)
Browse files Browse the repository at this point in the history
  • Loading branch information
Delta456 authored Jul 2, 2024
1 parent 81b095b commit 36e31d6
Show file tree
Hide file tree
Showing 5 changed files with 32 additions and 1 deletion.
14 changes: 14 additions & 0 deletions vlib/v/checker/check_types.v
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,20 @@ fn (mut c Checker) check_types(got ast.Type, expected ast.Type) bool {
return true
}
}

if (exp_idx == ast.nil_type_idx && got_idx == ast.string_type_idx)
|| (got_idx == ast.nil_type_idx && exp_idx == ast.string_type_idx) {
got_sym := c.table.sym(got)
exp_sym := c.table.sym(expected)

if expected.is_ptr() || got.is_ptr() {
return true
}
if got_sym.language != .c || exp_sym.language != .c {
return false
}
}

// allow direct int-literal assignment for pointers for now
// maybe in the future options should be used for that
if expected.is_any_kind_of_pointer() {
Expand Down
8 changes: 8 additions & 0 deletions vlib/v/checker/tests/non_nil_array_with_nil_element_err.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
vlib/v/checker/tests/non_nil_array_with_nil_element_err.vv:1:23: error: invalid array element: expected `string`, not `voidptr`
1 | const spnames = ['f', unsafe { nil }]!
| ~~~~~~
2 | const spnames1 = [unsafe { nil }, 'f']!
vlib/v/checker/tests/non_nil_array_with_nil_element_err.vv:2:35: error: invalid array element: expected `voidptr`, not `string`
1 | const spnames = ['f', unsafe { nil }]!
2 | const spnames1 = [unsafe { nil }, 'f']!
| ~~~
2 changes: 2 additions & 0 deletions vlib/v/checker/tests/non_nil_array_with_nil_element_err.vv
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
const spnames = ['f', unsafe { nil }]!
const spnames1 = [unsafe { nil }, 'f']!
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
vlib/v/checker/tests/struct_field_assign_internal_types_nil_err.vv:15:2: error: cannot assign to field `name`: expected `string`, not `voidptr`
13 |
14 | a := &Foo{
15 | name: unsafe { nil }
| ~~~~~~~~~~~~
16 | bar: unsafe { nil }
17 | name2: unsafe { nil }
vlib/v/checker/tests/struct_field_assign_internal_types_nil_err.vv:15:8: error: cannot assign `nil` to struct field `name` with type `string`
13 |
14 | a := &Foo{
Expand Down
2 changes: 1 addition & 1 deletion vlib/v/tests/cast_fixed_array_to_ptr_ptr_test.v
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ struct Foo {
fn test_main() {
foo := Foo{
bar: unsafe {
&&char(['a', 'b', nil]!)
&&char([c'a', c'b', nil]!)
}
}
println(foo)
Expand Down

0 comments on commit 36e31d6

Please sign in to comment.