From 7fd08eca9661654dab93b5fdb4f420e772d85a09 Mon Sep 17 00:00:00 2001 From: skurgs <73891182+skurgs@users.noreply.github.com> Date: Mon, 24 Jan 2022 05:13:22 -0500 Subject: [PATCH] checker: fix c error on improper string to rune cast (#13197) (#13257) --- vlib/v/checker/checker.v | 5 ++++ .../checker/tests/cast_string_to_rune_err.out | 26 +++++++++++++++++++ .../checker/tests/cast_string_to_rune_err.vv | 6 +++++ 3 files changed, 37 insertions(+) create mode 100644 vlib/v/checker/tests/cast_string_to_rune_err.out create mode 100644 vlib/v/checker/tests/cast_string_to_rune_err.vv diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 14dde985dc..89de87c58f 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -2732,6 +2732,11 @@ pub fn (mut c Checker) cast_expr(mut node ast.CastExpr) ast.Type { node.pos) } + if to_sym.kind == .rune && from_sym.is_string() { + snexpr := node.expr.str() + c.error('cannot cast `$from_sym.name` to rune, use `${snexpr}.runes()` instead.', node.pos) + } + if to_type == ast.string_type { if from_type in [ast.byte_type, ast.bool_type] { snexpr := node.expr.str() diff --git a/vlib/v/checker/tests/cast_string_to_rune_err.out b/vlib/v/checker/tests/cast_string_to_rune_err.out new file mode 100644 index 0000000000..f64215013d --- /dev/null +++ b/vlib/v/checker/tests/cast_string_to_rune_err.out @@ -0,0 +1,26 @@ +vlib/v/checker/tests/cast_string_to_rune_err.vv:2:7: error: cannot cast `string` to rune, use `'0'.runes()` instead. + 1 | fn main() { + 2 | _ := rune('0') + | ~~~~~~~~~ + 3 | _ := rune('012345') + 4 | _ := rune('v') +vlib/v/checker/tests/cast_string_to_rune_err.vv:3:7: error: cannot cast `string` to rune, use `'012345'.runes()` instead. + 1 | fn main() { + 2 | _ := rune('0') + 3 | _ := rune('012345') + | ~~~~~~~~~~~~~~ + 4 | _ := rune('v') + 5 | _ := rune('abcd') +vlib/v/checker/tests/cast_string_to_rune_err.vv:4:7: error: cannot cast `string` to rune, use `'v'.runes()` instead. + 2 | _ := rune('0') + 3 | _ := rune('012345') + 4 | _ := rune('v') + | ~~~~~~~~~ + 5 | _ := rune('abcd') + 6 | } +vlib/v/checker/tests/cast_string_to_rune_err.vv:5:7: error: cannot cast `string` to rune, use `'abcd'.runes()` instead. + 3 | _ := rune('012345') + 4 | _ := rune('v') + 5 | _ := rune('abcd') + | ~~~~~~~~~~~~ + 6 | } diff --git a/vlib/v/checker/tests/cast_string_to_rune_err.vv b/vlib/v/checker/tests/cast_string_to_rune_err.vv new file mode 100644 index 0000000000..d2ac2b5cc6 --- /dev/null +++ b/vlib/v/checker/tests/cast_string_to_rune_err.vv @@ -0,0 +1,6 @@ +fn main() { + _ := rune('0') + _ := rune('012345') + _ := rune('v') + _ := rune('abcd') +}