From 5bc4fea9e0a3ae9afef8346ad268b58c9629d013 Mon Sep 17 00:00:00 2001 From: yuyi Date: Thu, 12 May 2022 15:04:38 +0800 Subject: [PATCH] checker: check error for cast function to string (#14375) --- vlib/v/checker/checker.v | 3 +++ vlib/v/checker/tests/cast_function_to_string_err.out | 5 +++++ vlib/v/checker/tests/cast_function_to_string_err.vv | 3 +++ 3 files changed, 11 insertions(+) create mode 100644 vlib/v/checker/tests/cast_function_to_string_err.out create mode 100644 vlib/v/checker/tests/cast_function_to_string_err.vv diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index f5680cdd9c..28a24fb855 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -3026,6 +3026,9 @@ pub fn (mut c Checker) cast_expr(mut node ast.CastExpr) ast.Type { ft := c.table.type_to_str(from_type) c.error('cannot cast sumtype `$ft` to string, use `${snexpr}.str()` instead.', node.pos) + } else if final_from_sym.kind == .function { + fnexpr := node.expr.str() + c.error('cannot cast function `$fnexpr` to string', node.pos) } else if to_type != ast.string_type && from_type == ast.string_type && (!(to_sym.kind == .alias && final_to_sym.name == 'string')) { mut error_msg := 'cannot cast a string to a type `$final_to_sym.name`, that is not an alias of string' diff --git a/vlib/v/checker/tests/cast_function_to_string_err.out b/vlib/v/checker/tests/cast_function_to_string_err.out new file mode 100644 index 0000000000..472d413527 --- /dev/null +++ b/vlib/v/checker/tests/cast_function_to_string_err.out @@ -0,0 +1,5 @@ +vlib/v/checker/tests/cast_function_to_string_err.vv:2:10: error: cannot cast function `main` to string + 1 | fn main() { + 2 | println(string(main)) + | ~~~~~~~~~~~~ + 3 | } diff --git a/vlib/v/checker/tests/cast_function_to_string_err.vv b/vlib/v/checker/tests/cast_function_to_string_err.vv new file mode 100644 index 0000000000..95384e46d4 --- /dev/null +++ b/vlib/v/checker/tests/cast_function_to_string_err.vv @@ -0,0 +1,3 @@ +fn main() { + println(string(main)) +}