Skip to content

Commit

Permalink
checker: fix missing struct cast validation (fix #23748) (#23788)
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp authored Feb 23, 2025
1 parent e5e9b5d commit 9921692
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 3 deletions.
10 changes: 7 additions & 3 deletions vlib/v/checker/checker.v
Original file line number Diff line number Diff line change
Expand Up @@ -3568,12 +3568,16 @@ fn (mut c Checker) cast_expr(mut node ast.CastExpr) ast.Type {
tt := c.table.type_to_str(to_type)
c.error('cannot cast incompatible option ${final_to_sym.name} `${ft}` to `${tt}`',
node.pos)
}

if to_sym.kind == .rune && from_sym.is_string() {
} else if to_sym.kind == .rune && from_sym.is_string() {
snexpr := node.expr.str()
ft := c.table.type_to_str(from_type)
c.error('cannot cast `${ft}` to rune, use `${snexpr}.runes()` instead.', node.pos)
} else if !from_type.is_ptr() && from_type != ast.string_type
&& final_from_sym.info is ast.Struct && !final_from_sym.info.is_empty_struct()
&& (final_to_sym.is_int() || final_to_sym.is_float()) {
ft := c.table.type_to_str(from_type)
tt := c.table.type_to_str(to_type)
c.error('cannot cast type `${ft}` to `${tt}`', node.pos)
}

if to_sym.kind == .enum && !(c.inside_unsafe || c.file.is_translated) && from_sym.is_int() {
Expand Down
6 changes: 6 additions & 0 deletions vlib/v/checker/tests/c_struct_cast.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
vlib/v/checker/tests/c_struct_cast.vv:18:7: error: cannot cast type `Vector3` to `int`
16 | }
17 | dump(v)
18 | dump(int(v))
| ~~~~~~
19 | }
19 changes: 19 additions & 0 deletions vlib/v/checker/tests/c_struct_cast.vv
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
module main

pub struct C.Vector3 {
x f32
y f32
z f32
}

pub type Vector3 = C.Vector3

fn main() {
v := Vector3{
x: 0.0
y: 1.7
z: 0.0
}
dump(v)
dump(int(v))
}

0 comments on commit 9921692

Please sign in to comment.