1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

checker: fix struct field unsign type check (fix #16457) (#16458)

This commit is contained in:
shove 2022-11-17 15:20:42 +08:00 committed by GitHub
parent 360457e021
commit 74efd2621b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 56 additions and 0 deletions

View File

@ -321,6 +321,14 @@ pub fn (mut c Checker) assign_stmt(mut node ast.AssignStmt) {
left.expr.is_setter = true left.expr.is_setter = true
} }
} }
if left_type in ast.unsigned_integer_type_idxs {
if mut right is ast.IntegerLiteral {
if right.val[0] == `-` {
c.error('Cannot assign negative value to unsigned integer type',
right.pos)
}
}
}
} }
else { else {
if mut left is ast.IndexExpr { if mut left is ast.IndexExpr {

View File

@ -124,6 +124,14 @@ pub fn (mut c Checker) struct_decl(mut node ast.StructDecl) {
} }
continue continue
} }
if field.typ in ast.unsigned_integer_type_idxs {
if field.default_expr is ast.IntegerLiteral {
if field.default_expr.val[0] == `-` {
c.error('Cannot assign negative value to unsigned integer type',
field.default_expr.pos)
}
}
}
if field.default_expr is ast.UnsafeExpr { if field.default_expr is ast.UnsafeExpr {
if field.default_expr.expr is ast.Nil && !field.typ.is_ptr() if field.default_expr.expr is ast.Nil && !field.typ.is_ptr()
&& c.table.sym(field.typ).kind != .function && !field.typ.is_pointer() { && c.table.sym(field.typ).kind != .function && !field.typ.is_pointer() {
@ -482,6 +490,14 @@ pub fn (mut c Checker) struct_init(mut node ast.StructInit) ast.Type {
} }
} }
} }
if field_info.typ in ast.unsigned_integer_type_idxs {
if mut field.expr is ast.IntegerLiteral {
if field.expr.val[0] == `-` {
c.error('Cannot assign negative value to unsigned integer type',
field.expr.pos)
}
}
}
} }
// Check uninitialized refs/sum types // Check uninitialized refs/sum types
// The variable `fields` contains two parts, the first part is the same as info.fields, // The variable `fields` contains two parts, the first part is the same as info.fields,

View File

@ -0,0 +1,20 @@
vlib/v/checker/tests/struct_field_unsign_type_check_err.vv:3:10: error: Cannot assign negative value to unsigned integer type
1 | struct Foo {
2 | mut:
3 | n u32 = -1
| ~~
4 | }
5 |
vlib/v/checker/tests/struct_field_unsign_type_check_err.vv:8:6: error: Cannot assign negative value to unsigned integer type
6 | fn main() {
7 | mut foo := Foo{
8 | n: -1
| ~~
9 | }
10 |
vlib/v/checker/tests/struct_field_unsign_type_check_err.vv:11:10: error: Cannot assign negative value to unsigned integer type
9 | }
10 |
11 | foo.n = -1
| ~~
12 | }

View File

@ -0,0 +1,12 @@
struct Foo {
mut:
n u32 = -1
}
fn main() {
mut foo := Foo{
n: -1
}
foo.n = -1
}