From 9fdb1701e0465d090a1eefa2efd020f60c09ab3e Mon Sep 17 00:00:00 2001 From: Swastik Baranwal Date: Tue, 11 Aug 2020 21:11:54 +0530 Subject: [PATCH] checker: add a check for str[i] = `a` (#6107) --- vlib/v/checker/checker.v | 3 +++ vlib/v/checker/tests/string_index_assign_error.out | 6 ++++++ vlib/v/checker/tests/string_index_assign_error.vv | 4 ++++ 3 files changed, 13 insertions(+) create mode 100644 vlib/v/checker/tests/string_index_assign_error.out create mode 100644 vlib/v/checker/tests/string_index_assign_error.vv diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 5907e102a7..c12a8ea45e 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -3076,6 +3076,9 @@ pub fn (mut c Checker) index_expr(mut node ast.IndexExpr) table.Type { typ_sym.name.ends_with('ptr')) && !typ.has_flag(.variadic) { // byteptr, charptr etc c.error('type `$typ_sym.name` does not support indexing', node.pos) } + if typ_sym.kind == .string && !typ.is_ptr() && node.is_setter { + c.error('cannot assign to s[i] (strings are immutable)', node.pos) + } if !c.inside_unsafe && (typ.is_ptr() || typ.is_pointer()) { mut is_ok := false if node.left is ast.Ident { diff --git a/vlib/v/checker/tests/string_index_assign_error.out b/vlib/v/checker/tests/string_index_assign_error.out new file mode 100644 index 0000000000..26f1c610b4 --- /dev/null +++ b/vlib/v/checker/tests/string_index_assign_error.out @@ -0,0 +1,6 @@ +vlib/v/checker/tests/string_index_assign_error.v:3:6: error: cannot assign to s[i] (strings are immutable) + 1 | fn main() { + 2 | mut a := 'V is great!!' + 3 | a[0] = `R` + | ~~~ + 4 | } diff --git a/vlib/v/checker/tests/string_index_assign_error.vv b/vlib/v/checker/tests/string_index_assign_error.vv new file mode 100644 index 0000000000..161b2151a5 --- /dev/null +++ b/vlib/v/checker/tests/string_index_assign_error.vv @@ -0,0 +1,4 @@ +fn main() { + mut a := 'V is great!!' + a[0] = `R` +}