checker: disallow casting strings to pointers outside unsafe (#19977)

This commit is contained in:
Swastik Baranwal 2023-11-24 13:02:05 +05:30 committed by GitHub
parent 65089eee41
commit 2884ec52de
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 25 additions and 0 deletions

View File

@ -3174,6 +3174,10 @@ 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_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',
node.pos)
} else if final_from_sym.kind == .array && !from_type.is_ptr() && to_type != ast.string_type
&& !(to_type.has_flag(.option) && from_type.idx() == to_type.idx()) {
ft := c.table.type_to_str(from_type)

View File

@ -0,0 +1,17 @@
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
1 | test := 'test'
2 | println(voidptr(test))
| ~~~~~~~~~~~~~
3 | println(byteptr(test))
4 | println(charptr(test))
vlib/v/checker/tests/invalid_string_cast_to_pointers_err.vv:3:9: error: cannot cast string to `byteptr` outside `unsafe`, use byteptr(s.str) instead
1 | test := 'test'
2 | println(voidptr(test))
3 | println(byteptr(test))
| ~~~~~~~~~~~~~
4 | println(charptr(test))
vlib/v/checker/tests/invalid_string_cast_to_pointers_err.vv:4:9: error: cannot cast string to `charptr` outside `unsafe`, use charptr(s.str) instead
2 | println(voidptr(test))
3 | println(byteptr(test))
4 | println(charptr(test))
| ~~~~~~~~~~~~~

View File

@ -0,0 +1,4 @@
test := 'test'
println(voidptr(test))
println(byteptr(test))
println(charptr(test))