Skip to content

Commit dc222b6

Browse files
authored
checker: add missing check for casting generic type to literal values (#23915)
1 parent d6ac5b5 commit dc222b6

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

vlib/v/checker/checker.v

+6
Original file line numberDiff line numberDiff line change
@@ -3585,6 +3585,12 @@ fn (mut c Checker) cast_expr(mut node ast.CastExpr) ast.Type {
35853585
c.error('cannot cast type `${ft}` to `${tt}`', node.pos)
35863586
}
35873587

3588+
// T(0) where T is array or map
3589+
if node.typ.has_flag(.generic) && to_sym.kind in [.array, .map, .array_fixed]
3590+
&& node.expr.is_literal() {
3591+
c.error('cannot cast literal value to ${to_sym.name} type', node.pos)
3592+
}
3593+
35883594
if to_sym.kind == .enum && !(c.inside_unsafe || c.file.is_translated) && from_sym.is_int() {
35893595
c.error('casting numbers to enums, should be done inside `unsafe{}` blocks', node.pos)
35903596
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
vlib/v/checker/tests/cast_generic_err.vv:2:7: error: cannot cast literal value to [2]u8 type
2+
1 | fn decode[T]() {
3+
2 | _ := T(0)
4+
| ~~~~
5+
3 | }
6+
4 |
+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
fn decode[T]() {
2+
_ := T(0)
3+
}
4+
5+
fn main() {
6+
decode[[2]u8]()
7+
decode[[]u8]()
8+
decode[map[int]u8]()
9+
}

0 commit comments

Comments
 (0)