From dc222b6ca61eda64830eb02709fdfc5a5e301388 Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Fri, 14 Mar 2025 04:22:54 -0300 Subject: [PATCH] checker: add missing check for casting generic type to literal values (#23915) --- vlib/v/checker/checker.v | 6 ++++++ vlib/v/checker/tests/cast_generic_err.out | 6 ++++++ vlib/v/checker/tests/cast_generic_err.vv | 9 +++++++++ 3 files changed, 21 insertions(+) create mode 100644 vlib/v/checker/tests/cast_generic_err.out create mode 100644 vlib/v/checker/tests/cast_generic_err.vv diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 591da61af..c434fa09f 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -3585,6 +3585,12 @@ fn (mut c Checker) cast_expr(mut node ast.CastExpr) ast.Type { c.error('cannot cast type `${ft}` to `${tt}`', node.pos) } + // T(0) where T is array or map + if node.typ.has_flag(.generic) && to_sym.kind in [.array, .map, .array_fixed] + && node.expr.is_literal() { + c.error('cannot cast literal value to ${to_sym.name} type', node.pos) + } + if to_sym.kind == .enum && !(c.inside_unsafe || c.file.is_translated) && from_sym.is_int() { c.error('casting numbers to enums, should be done inside `unsafe{}` blocks', node.pos) } diff --git a/vlib/v/checker/tests/cast_generic_err.out b/vlib/v/checker/tests/cast_generic_err.out new file mode 100644 index 000000000..87913890f --- /dev/null +++ b/vlib/v/checker/tests/cast_generic_err.out @@ -0,0 +1,6 @@ +vlib/v/checker/tests/cast_generic_err.vv:2:7: error: cannot cast literal value to [2]u8 type + 1 | fn decode[T]() { + 2 | _ := T(0) + | ~~~~ + 3 | } + 4 | diff --git a/vlib/v/checker/tests/cast_generic_err.vv b/vlib/v/checker/tests/cast_generic_err.vv new file mode 100644 index 000000000..47ecb119d --- /dev/null +++ b/vlib/v/checker/tests/cast_generic_err.vv @@ -0,0 +1,9 @@ +fn decode[T]() { + _ := T(0) +} + +fn main() { + decode[[2]u8]() + decode[[]u8]() + decode[map[int]u8]() +} -- 2.39.5