From dbd65071fe09ac5364650c4044d647fcd77564d6 Mon Sep 17 00:00:00 2001 From: Daniel Watkins Date: Sun, 5 Aug 2018 16:09:06 -0400 Subject: [PATCH] Implement stepped slicing for tuples --- tests/snippets/3.1.3.2.py | 11 +++++++++++ vm/src/objlist.rs | 2 +- vm/src/objtuple.rs | 33 ++++++++++----------------------- 3 files changed, 22 insertions(+), 24 deletions(-) diff --git a/tests/snippets/3.1.3.2.py b/tests/snippets/3.1.3.2.py index 2d107e6b2..393e589ea 100644 --- a/tests/snippets/3.1.3.2.py +++ b/tests/snippets/3.1.3.2.py @@ -8,3 +8,14 @@ assert squares == squares[:] assert [1, 9, 25] == squares[::2] assert [4, 16] == squares[1::2] assert [4] == squares[1:2:2] + +squares_tuple = (1, 4, 9, 16, 25) + +assert 1 == squares_tuple[0] +assert 25 == squares_tuple[-1] +assert (9, 16, 25) == squares_tuple[-3:] +assert squares_tuple == squares_tuple[:] + +assert (1, 9, 25) == squares_tuple[::2] +assert (4, 16) == squares_tuple[1::2] +assert (4,) == squares_tuple[1:2:2] diff --git a/vm/src/objlist.rs b/vm/src/objlist.rs index d7cd39f50..786953266 100644 --- a/vm/src/objlist.rs +++ b/vm/src/objlist.rs @@ -9,7 +9,7 @@ fn get_pos(l: &Vec, p: i32) -> usize { } } -fn get_slice_items(l: &Vec, slice: &PyObjectRef) -> Vec { +pub fn get_slice_items(l: &Vec, slice: &PyObjectRef) -> Vec { // TODO: we could potentially avoid this copy and use slice match &(slice.borrow()).kind { PyObjectKind::Slice { start, stop, step } => { diff --git a/vm/src/objtuple.rs b/vm/src/objtuple.rs index 3dd4c28d4..f3da2a052 100644 --- a/vm/src/objtuple.rs +++ b/vm/src/objtuple.rs @@ -20,29 +20,16 @@ pub fn get_item(vm: &mut VirtualMachine, l: &Vec, b: PyObjectRef) - Err(vm.new_exception("Index out of bounds!".to_string())) } } - PyObjectKind::Slice { start, stop, step } => { - let start = match start { - &Some(start) => get_pos(l, start), - &None => 0, - }; - let stop = match stop { - &Some(stop) => get_pos(l, stop), - &None => l.len() as usize, - }; - let step = match step { - //Some(step) => step as usize, - &None => 1 as usize, - _ => unimplemented!("stepped slicing not supported for type {:?}", l), - }; - // TODO: we could potentially avoid this copy and use slice - let obj = PyObject::new( - PyObjectKind::Tuple { - elements: l[start..stop].to_vec(), - }, - vm.get_type(), - ); - Ok(obj) - } + PyObjectKind::Slice { + start: _, + stop: _, + step: _, + } => Ok(PyObject::new( + PyObjectKind::Tuple { + elements: super::objlist::get_slice_items(l, &b), + }, + vm.get_type(), + )), _ => Err(vm.new_exception(format!( "TypeError: indexing type {:?} with index {:?} is not supported (yet?)", l, b