From b8b0cfddd5862651b507e10763e6cb3a12da9b49 Mon Sep 17 00:00:00 2001 From: Swastik Baranwal Date: Wed, 3 Jan 2024 10:39:56 +0530 Subject: [PATCH] checker: disallow `string` to `voidptr` cast entirely (#20351) --- vlib/builtin/js/builtin.v | 2 +- vlib/v/checker/checker.v | 3 +++ vlib/v/checker/tests/invalid_string_cast_to_pointers_err.out | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/vlib/builtin/js/builtin.v b/vlib/builtin/js/builtin.v index d57d2aa82..200eddd22 100644 --- a/vlib/builtin/js/builtin.v +++ b/vlib/builtin/js/builtin.v @@ -37,7 +37,7 @@ pub fn (err IError) str() string { else { // >> Hack to allow old style custom error implementations // TODO: remove once deprecation period for `IError` methods has ended - old_error_style := unsafe { voidptr(&err.msg) != voidptr(&err.code) } // if fields are not defined (new style) they don't have an offset between them + old_error_style := unsafe { voidptr(&err.msg.str) != voidptr(&err.code.str) } // if fields are not defined (new style) they don't have an offset between them if old_error_style { '${err.type_name()}: ${err.msg}' } else { diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 8c8155539..ae1187448 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -3180,6 +3180,9 @@ fn (mut c Checker) cast_expr(mut node ast.CastExpr) ast.Type { snexpr := node.expr.str() tt := c.table.type_to_str(to_type) c.error('cannot cast string to `${tt}`, use `${snexpr}[index]` instead.', node.pos) + } else if final_from_sym.kind == .string && to_type.is_voidptr() + && !node.expr_type.has_flag(.generic) && !from_type.is_ptr() { + c.error('cannot cast string to `voidptr`, use voidptr(s.str) instead', node.pos) } else if final_from_sym.kind == .string && to_type.is_pointer() && !c.inside_unsafe { tt := c.table.type_to_str(to_type) c.error('cannot cast string to `${tt}` outside `unsafe`, use ${tt}(s.str) instead', diff --git a/vlib/v/checker/tests/invalid_string_cast_to_pointers_err.out b/vlib/v/checker/tests/invalid_string_cast_to_pointers_err.out index 4a0bc4b74..e73c0a28b 100644 --- a/vlib/v/checker/tests/invalid_string_cast_to_pointers_err.out +++ b/vlib/v/checker/tests/invalid_string_cast_to_pointers_err.out @@ -1,4 +1,4 @@ -vlib/v/checker/tests/invalid_string_cast_to_pointers_err.vv:2:9: error: cannot cast string to `voidptr` outside `unsafe`, use voidptr(s.str) instead +vlib/v/checker/tests/invalid_string_cast_to_pointers_err.vv:2:9: error: cannot cast string to `voidptr`, use voidptr(s.str) instead 1 | test := 'test' 2 | println(voidptr(test)) | ~~~~~~~~~~~~~ -- 2.39.5