From f8ba4ba1fef7b45a042a5c836f6872c4e2b22d7d Mon Sep 17 00:00:00 2001 From: Swastik Baranwal Date: Wed, 13 Sep 2023 14:10:10 +0530 Subject: [PATCH] checker: disallow alias ptr cast of a map value (#19336) --- vlib/v/checker/checker.v | 5 ++++- vlib/v/checker/tests/invalid_alias_ptr_cast_on_map_err.out | 6 ++++++ vlib/v/checker/tests/invalid_alias_ptr_cast_on_map_err.vv | 5 +++++ 3 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 vlib/v/checker/tests/invalid_alias_ptr_cast_on_map_err.out create mode 100644 vlib/v/checker/tests/invalid_alias_ptr_cast_on_map_err.vv diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 6ba7795ba..153514fca 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -3177,6 +3177,10 @@ fn (mut c Checker) cast_expr(mut node ast.CastExpr) ast.Type { c.error('casting a function value from one function signature, to another function signature, should be done inside `unsafe{}` blocks', node.pos) } + if to_type.is_ptr() && to_sym.kind == .alias && from_sym.kind == .map { + c.error('cannot cast to alias pointer `${c.table.type_to_str(to_type)}` because `${c.table.type_to_str(from_type)}` is a value', + node.pos) + } if to_type == ast.string_type { if from_type in [ast.u8_type, ast.bool_type] { @@ -3281,7 +3285,6 @@ fn (mut c Checker) cast_expr(mut node ast.CastExpr) ast.Type { } } } - // don't allow casting `string` to `enum`, and suggest using `enum_name.type_to_string(str)` instead if mut node.expr is ast.StringLiteral { c.add_error_detail('use ${c.table.type_to_str(node.typ)}.from_string(\'${node.expr.val}\') instead') c.error('cannot cast `string` to `enum`', node.pos) diff --git a/vlib/v/checker/tests/invalid_alias_ptr_cast_on_map_err.out b/vlib/v/checker/tests/invalid_alias_ptr_cast_on_map_err.out new file mode 100644 index 000000000..cee24aaee --- /dev/null +++ b/vlib/v/checker/tests/invalid_alias_ptr_cast_on_map_err.out @@ -0,0 +1,6 @@ +vlib/v/checker/tests/invalid_alias_ptr_cast_on_map_err.vv:4:7: error: cannot cast to alias pointer `&FooMap` because `map[string]int` is a value + 2 | + 3 | fn main() { + 4 | _ := &FooMap(map[string]int{}) + | ~~~~~~~~~~~~~~~~~~~~~~~~~ + 5 | } diff --git a/vlib/v/checker/tests/invalid_alias_ptr_cast_on_map_err.vv b/vlib/v/checker/tests/invalid_alias_ptr_cast_on_map_err.vv new file mode 100644 index 000000000..a76977478 --- /dev/null +++ b/vlib/v/checker/tests/invalid_alias_ptr_cast_on_map_err.vv @@ -0,0 +1,5 @@ +type FooMap = map[string]int + +fn main() { + _ := &FooMap(map[string]int{}) +} -- 2.39.5