From 37d739684c942b900d8a4067c0ef94ece7458f29 Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Sat, 11 Jul 2020 17:09:15 +0300 Subject: [PATCH] checker: prevent string(byte), suggest byte.str() instead --- vlib/v/checker/checker.v | 3 +++ vlib/v/checker/tests/cast_string_with_byte_err.out | 5 +++++ vlib/v/checker/tests/cast_string_with_byte_err.vv | 3 +++ 3 files changed, 11 insertions(+) create mode 100644 vlib/v/checker/tests/cast_string_with_byte_err.out create mode 100644 vlib/v/checker/tests/cast_string_with_byte_err.vv diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 599ef708b4..a74144f0e9 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -2126,6 +2126,9 @@ pub fn (mut c Checker) expr(node ast.Expr) table.Type { node.expr_type = c.expr(node.expr) from_type_sym := c.table.get_type_symbol(node.expr_type) to_type_sym := c.table.get_type_symbol(node.typ) + if node.expr_type == table.byte_type && to_type_sym.kind == .string { + c.error('can not cast type `byte` to string, use `${node.expr.str()}.str()` instead.', node.pos) + } if to_type_sym.kind == .sum_type { if node.expr_type in [table.any_int_type, table.any_flt_type] { node.expr_type = c.promote_num(node.expr_type, if node.expr_type == table.any_int_type { table.int_type } else { table.f64_type }) diff --git a/vlib/v/checker/tests/cast_string_with_byte_err.out b/vlib/v/checker/tests/cast_string_with_byte_err.out new file mode 100644 index 0000000000..c185f6ed06 --- /dev/null +++ b/vlib/v/checker/tests/cast_string_with_byte_err.out @@ -0,0 +1,5 @@ +vlib/v/checker/tests/cast_string_with_byte_err.v:2:19: error: can not cast type `byte` to string, use `by.str()` instead. + 1 | for by in 'abc' { + 2 | println(string(by)) + | ~~ + 3 | } diff --git a/vlib/v/checker/tests/cast_string_with_byte_err.vv b/vlib/v/checker/tests/cast_string_with_byte_err.vv new file mode 100644 index 0000000000..4626e2878e --- /dev/null +++ b/vlib/v/checker/tests/cast_string_with_byte_err.vv @@ -0,0 +1,3 @@ +for by in 'abc' { + println(string(by)) +}