Implement stepped slicing for tuples

This commit is contained in:
Daniel Watkins
2018-08-05 16:09:06 -04:00
parent a0844f1f39
commit dbd65071fe
3 changed files with 22 additions and 24 deletions

View File

@@ -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]

View File

@@ -9,7 +9,7 @@ fn get_pos(l: &Vec<PyObjectRef>, p: i32) -> usize {
}
}
fn get_slice_items(l: &Vec<PyObjectRef>, slice: &PyObjectRef) -> Vec<PyObjectRef> {
pub fn get_slice_items(l: &Vec<PyObjectRef>, slice: &PyObjectRef) -> Vec<PyObjectRef> {
// TODO: we could potentially avoid this copy and use slice
match &(slice.borrow()).kind {
PyObjectKind::Slice { start, stop, step } => {

View File

@@ -20,29 +20,16 @@ pub fn get_item(vm: &mut VirtualMachine, l: &Vec<PyObjectRef>, 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