Skip to content

Commit 2884ec5

Browse files
authored
checker: disallow casting strings to pointers outside unsafe (#19977)
1 parent 65089ee commit 2884ec5

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

vlib/v/checker/checker.v

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3174,6 +3174,10 @@ fn (mut c Checker) cast_expr(mut node ast.CastExpr) ast.Type {
31743174
snexpr := node.expr.str()
31753175
tt := c.table.type_to_str(to_type)
31763176
c.error('cannot cast string to `${tt}`, use `${snexpr}[index]` instead.', node.pos)
3177+
} else if final_from_sym.kind == .string && to_type.is_pointer() && !c.inside_unsafe {
3178+
tt := c.table.type_to_str(to_type)
3179+
c.error('cannot cast string to `${tt}` outside `unsafe`, use ${tt}(s.str) instead',
3180+
node.pos)
31773181
} else if final_from_sym.kind == .array && !from_type.is_ptr() && to_type != ast.string_type
31783182
&& !(to_type.has_flag(.option) && from_type.idx() == to_type.idx()) {
31793183
ft := c.table.type_to_str(from_type)
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
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
2+
1 | test := 'test'
3+
2 | println(voidptr(test))
4+
| ~~~~~~~~~~~~~
5+
3 | println(byteptr(test))
6+
4 | println(charptr(test))
7+
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
8+
1 | test := 'test'
9+
2 | println(voidptr(test))
10+
3 | println(byteptr(test))
11+
| ~~~~~~~~~~~~~
12+
4 | println(charptr(test))
13+
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
14+
2 | println(voidptr(test))
15+
3 | println(byteptr(test))
16+
4 | println(charptr(test))
17+
| ~~~~~~~~~~~~~
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
test := 'test'
2+
println(voidptr(test))
3+
println(byteptr(test))
4+
println(charptr(test))

0 commit comments

Comments
 (0)