From 06967d929797460f45545fc5624da441315f0c22 Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Fri, 21 Aug 2020 21:17:55 +0300 Subject: [PATCH] sort: require a mutable receiver --- vlib/v/checker/checker.v | 1 + .../sort_method_called_on_immutable_receiver.out | 13 +++++++++++++ .../sort_method_called_on_immutable_receiver.vv | 9 +++++++++ 3 files changed, 23 insertions(+) create mode 100644 vlib/v/checker/tests/sort_method_called_on_immutable_receiver.out create mode 100644 vlib/v/checker/tests/sort_method_called_on_immutable_receiver.vv diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 323f6edd2c..38983f7f2d 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -872,6 +872,7 @@ pub fn (mut c Checker) call_method(mut call_expr ast.CallExpr) table.Type { if is_filter_map { scope.update_var_type('it', array_info.elem_type) } else if is_sort { + c.fail_if_immutable(call_expr.left) scope.update_var_type('a', array_info.elem_type) scope.update_var_type('b', array_info.elem_type) // Verify `.sort(a < b)` diff --git a/vlib/v/checker/tests/sort_method_called_on_immutable_receiver.out b/vlib/v/checker/tests/sort_method_called_on_immutable_receiver.out new file mode 100644 index 0000000000..213bb2b9a5 --- /dev/null +++ b/vlib/v/checker/tests/sort_method_called_on_immutable_receiver.out @@ -0,0 +1,13 @@ +vlib/v/checker/tests/sort_method_called_on_immutable_receiver.v:2:2: error: `a` is immutable, declare it with `mut` to make it mutable + 1 | fn abc (a []int) { + 2 | a.sort() + | ^ + 3 | } + 4 | +vlib/v/checker/tests/sort_method_called_on_immutable_receiver.v:7:2: error: `a` is immutable, declare it with `mut` to make it mutable + 5 | fn main() { + 6 | a := [2,30,10,20,1] + 7 | a.sort(a>b) + | ^ + 8 | eprintln(' a: $a') + 9 | } diff --git a/vlib/v/checker/tests/sort_method_called_on_immutable_receiver.vv b/vlib/v/checker/tests/sort_method_called_on_immutable_receiver.vv new file mode 100644 index 0000000000..b2dafa59c8 --- /dev/null +++ b/vlib/v/checker/tests/sort_method_called_on_immutable_receiver.vv @@ -0,0 +1,9 @@ +fn abc (a []int) { + a.sort() +} + +fn main() { + a := [2,30,10,20,1] + a.sort(a>b) + eprintln(' a: $a') +}