Add list.pop

Also include IndexError in the __builtin__ module.
This commit is contained in:
Homer McMillan
2019-02-03 00:49:52 -05:00
parent 328f81a28e
commit 7b27fbf369
3 changed files with 21 additions and 0 deletions

View File

@@ -20,3 +20,11 @@ except ValueError:
pass
else:
assert False, "ValueError was not raised"
assert [1,2,'a'].pop() == 'a', "list pop failed"
try:
[].pop()
except IndexError:
pass
else:
assert False, "IndexError was not raised"

View File

@@ -822,6 +822,7 @@ pub fn make_module(ctx: &PyContext) -> PyObjectRef {
);
ctx.set_attr(&py_mod, "TypeError", ctx.exceptions.type_error.clone());
ctx.set_attr(&py_mod, "ValueError", ctx.exceptions.value_error.clone());
ctx.set_attr(&py_mod, "IndexError", ctx.exceptions.index_error.clone());
py_mod
}

View File

@@ -272,6 +272,17 @@ fn list_mul(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
Ok(vm.ctx.new_list(new_elements))
}
fn list_pop(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(vm, args, required = [(zelf, Some(vm.ctx.list_type()))]);
let mut elements = get_mut_elements(zelf);
if let Some(result) = elements.pop() {
Ok(result)
} else {
Err(vm.new_index_error("pop from empty list".to_string()))
}
}
pub fn init(context: &PyContext) {
let ref list_type = context.list_type;
context.set_attr(&list_type, "__add__", context.new_rustfunc(list_add));
@@ -303,4 +314,5 @@ pub fn init(context: &PyContext) {
context.set_attr(&list_type, "index", context.new_rustfunc(list_index));
context.set_attr(&list_type, "reverse", context.new_rustfunc(list_reverse));
context.set_attr(&list_type, "sort", context.new_rustfunc(list_sort));
context.set_attr(&list_type, "pop", context.new_rustfunc(list_pop));
}