Skip to content

Commit 9921692

Browse files
authored
checker: fix missing struct cast validation (fix #23748) (#23788)
1 parent e5e9b5d commit 9921692

3 files changed

Lines changed: 32 additions & 3 deletions

File tree

‎vlib/v/checker/checker.v‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3568,12 +3568,16 @@ fn (mut c Checker) cast_expr(mut node ast.CastExpr) ast.Type {
35683568
tt := c.table.type_to_str(to_type)
35693569
c.error('cannot cast incompatible option ${final_to_sym.name} `${ft}` to `${tt}`',
35703570
node.pos)
3571-
}
3572-
3573-
if to_sym.kind == .rune && from_sym.is_string() {
3571+
} else if to_sym.kind == .rune && from_sym.is_string() {
35743572
snexpr := node.expr.str()
35753573
ft := c.table.type_to_str(from_type)
35763574
c.error('cannot cast `${ft}` to rune, use `${snexpr}.runes()` instead.', node.pos)
3575+
} else if !from_type.is_ptr() && from_type != ast.string_type
3576+
&& final_from_sym.info is ast.Struct && !final_from_sym.info.is_empty_struct()
3577+
&& (final_to_sym.is_int() || final_to_sym.is_float()) {
3578+
ft := c.table.type_to_str(from_type)
3579+
tt := c.table.type_to_str(to_type)
3580+
c.error('cannot cast type `${ft}` to `${tt}`', node.pos)
35773581
}
35783582

35793583
if to_sym.kind == .enum && !(c.inside_unsafe || c.file.is_translated) && from_sym.is_int() {
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
vlib/v/checker/tests/c_struct_cast.vv:18:7: error: cannot cast type `Vector3` to `int`
2+
16 | }
3+
17 | dump(v)
4+
18 | dump(int(v))
5+
| ~~~~~~
6+
19 | }
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
module main
2+
3+
pub struct C.Vector3 {
4+
x f32
5+
y f32
6+
z f32
7+
}
8+
9+
pub type Vector3 = C.Vector3
10+
11+
fn main() {
12+
v := Vector3{
13+
x: 0.0
14+
y: 1.7
15+
z: 0.0
16+
}
17+
dump(v)
18+
dump(int(v))
19+
}

0 commit comments

Comments
 (0)