Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions crates/stdlib/src/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -882,10 +882,7 @@ pub mod array {
self._from_bytes(b.as_bytes(), itemsize, vm)?;

if not_enough_bytes {
Err(vm.new_exception_msg(
vm.ctx.exceptions.eof_error.to_owned(),
"read() didn't return enough bytes".into(),
))
Err(vm.new_eof_error("read() didn't return enough bytes"))
} else {
Ok(())
}
Expand Down
10 changes: 4 additions & 6 deletions crates/stdlib/src/multiprocessing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,9 +175,8 @@ mod _multiprocessing {
fn release(&self, vm: &VirtualMachine) -> PyResult<()> {
if self.kind == RECURSIVE_MUTEX {
if !ismine!(self) {
return Err(vm.new_exception_msg(
vm.ctx.exceptions.assertion_error.to_owned(),
"attempt to release recursive lock not owned by thread".into(),
return Err(vm.new_assertion_error(
"attempt to release recursive lock not owned by thread",
));
}
if self.count.load(Ordering::Acquire) > 1 {
Expand Down Expand Up @@ -597,9 +596,8 @@ mod _multiprocessing {
if self.kind == RECURSIVE_MUTEX {
// if (!ISMINE(self))
if !ismine!(self) {
return Err(vm.new_exception_msg(
vm.ctx.exceptions.assertion_error.to_owned(),
"attempt to release recursive lock not owned by thread".into(),
return Err(vm.new_assertion_error(
"attempt to release recursive lock not owned by thread",
));
}
// if (self->count > 1) { --self->count; Py_RETURN_NONE; }
Expand Down
5 changes: 1 addition & 4 deletions crates/stdlib/src/ssl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4657,10 +4657,7 @@ mod _ssl {
// It's a memoryview, check if contiguous
let is_contiguous: bool = mem_view.try_to_bool(vm)?;
if !is_contiguous {
return Err(vm.new_exception_msg(
vm.ctx.exceptions.buffer_error.to_owned(),
"non-contiguous buffer is not supported".into(),
));
return Err(vm.new_buffer_error("non-contiguous buffer is not supported"));
}
}

Expand Down
5 changes: 1 addition & 4 deletions crates/vm/src/builtins/int.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,10 +236,7 @@ fn inner_truediv(i1: &BigInt, i2: &BigInt, vm: &VirtualMachine) -> PyResult {
let float = true_div(i1, i2);

if float.is_infinite() {
Err(vm.new_exception_msg(
vm.ctx.exceptions.overflow_error.to_owned(),
"integer division result too large for a float".into(),
))
Err(vm.new_overflow_error("integer division result too large for a float"))
} else {
Ok(vm.ctx.new_float(float).into())
}
Expand Down
5 changes: 2 additions & 3 deletions crates/vm/src/builtins/interpolation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,8 @@ impl PyInterpolation {
.downcast_ref::<PyStr>()
.is_some_and(|s| matches!(s.to_str(), Some("s" | "r" | "a")));
if !is_valid {
return Err(vm.new_exception_msg(
vm.ctx.exceptions.system_error.to_owned(),
"Interpolation() argument 'conversion' must be one of 's', 'a' or 'r'".into(),
return Err(vm.new_system_error(
"Interpolation() argument 'conversion' must be one of 's', 'a' or 'r'",
));
}
Ok(Self {
Expand Down
98 changes: 34 additions & 64 deletions crates/vm/src/frame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2038,10 +2038,9 @@ impl ExecutingFrame<'_> {
} else {
// Both merged cells (LOCAL|CELL) and non-merged cells get unbound local error
let name = self.localsplus_name(localsplus_idx);
vm.new_exception_msg(
vm.ctx.exceptions.unbound_local_error.to_owned(),
format!("local variable '{name}' referenced before assignment").into(),
)
vm.new_unbound_local_error(format!(
"local variable '{name}' referenced before assignment"
))
}
}

Expand Down Expand Up @@ -2378,14 +2377,10 @@ impl ExecutingFrame<'_> {
let fastlocals = self.localsplus.fastlocals_mut();
let idx = var_num.get(arg);
if fastlocals[idx].is_none() {
return Err(vm.new_exception_msg(
vm.ctx.exceptions.unbound_local_error.to_owned(),
format!(
"local variable '{}' referenced before assignment",
self.code.varnames[idx]
)
.into(),
));
return Err(vm.new_unbound_local_error(format!(
"local variable '{}' referenced before assignment",
self.code.varnames[idx]
)));
}
fastlocals[idx] = None;
Ok(None)
Expand Down Expand Up @@ -2884,10 +2879,9 @@ impl ExecutingFrame<'_> {
varname: &'static PyStrInterned,
vm: &VirtualMachine,
) -> PyBaseExceptionRef {
vm.new_exception_msg(
vm.ctx.exceptions.unbound_local_error.to_owned(),
format!("local variable '{varname}' referenced before assignment").into(),
)
vm.new_unbound_local_error(format!(
"local variable '{varname}' referenced before assignment"
))
}
let idx = var_num.get(arg);
let x = self.localsplus.fastlocals()[idx]
Expand All @@ -2910,14 +2904,10 @@ impl ExecutingFrame<'_> {
// (LoadFast in RustPython already does this check)
let idx = var_num.get(arg);
let x = self.localsplus.fastlocals()[idx].clone().ok_or_else(|| {
vm.new_exception_msg(
vm.ctx.exceptions.unbound_local_error.to_owned(),
format!(
"local variable '{}' referenced before assignment",
self.code.varnames[idx]
)
.into(),
)
vm.new_unbound_local_error(format!(
"local variable '{}' referenced before assignment",
self.code.varnames[idx]
))
})?;
self.push_value(x);
Ok(None)
Expand All @@ -2929,24 +2919,16 @@ impl ExecutingFrame<'_> {
let (idx1, idx2) = oparg.indexes();
let fastlocals = self.localsplus.fastlocals();
let x1 = fastlocals[idx1].clone().ok_or_else(|| {
vm.new_exception_msg(
vm.ctx.exceptions.unbound_local_error.to_owned(),
format!(
"local variable '{}' referenced before assignment",
self.code.varnames[idx1]
)
.into(),
)
vm.new_unbound_local_error(format!(
"local variable '{}' referenced before assignment",
self.code.varnames[idx1]
))
})?;
let x2 = fastlocals[idx2].clone().ok_or_else(|| {
vm.new_exception_msg(
vm.ctx.exceptions.unbound_local_error.to_owned(),
format!(
"local variable '{}' referenced before assignment",
self.code.varnames[idx2]
)
.into(),
)
vm.new_unbound_local_error(format!(
"local variable '{}' referenced before assignment",
self.code.varnames[idx2]
))
})?;
self.push_value(x1);
self.push_value(x2);
Expand All @@ -2958,14 +2940,10 @@ impl ExecutingFrame<'_> {
Instruction::LoadFastBorrow { var_num } => {
let idx = var_num.get(arg);
let x = self.localsplus.fastlocals()[idx].clone().ok_or_else(|| {
vm.new_exception_msg(
vm.ctx.exceptions.unbound_local_error.to_owned(),
format!(
"local variable '{}' referenced before assignment",
self.code.varnames[idx]
)
.into(),
)
vm.new_unbound_local_error(format!(
"local variable '{}' referenced before assignment",
self.code.varnames[idx]
))
})?;
self.push_value(x);
Ok(None)
Expand All @@ -2975,24 +2953,16 @@ impl ExecutingFrame<'_> {
let (idx1, idx2) = oparg.indexes();
let fastlocals = self.localsplus.fastlocals();
let x1 = fastlocals[idx1].clone().ok_or_else(|| {
vm.new_exception_msg(
vm.ctx.exceptions.unbound_local_error.to_owned(),
format!(
"local variable '{}' referenced before assignment",
self.code.varnames[idx1]
)
.into(),
)
vm.new_unbound_local_error(format!(
"local variable '{}' referenced before assignment",
self.code.varnames[idx1]
))
})?;
let x2 = fastlocals[idx2].clone().ok_or_else(|| {
vm.new_exception_msg(
vm.ctx.exceptions.unbound_local_error.to_owned(),
format!(
"local variable '{}' referenced before assignment",
self.code.varnames[idx2]
)
.into(),
)
vm.new_unbound_local_error(format!(
"local variable '{}' referenced before assignment",
self.code.varnames[idx2]
))
})?;
self.push_value(x1);
self.push_value(x2);
Expand Down
25 changes: 10 additions & 15 deletions crates/vm/src/protocol/buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,10 @@ pub struct PyBuffer {
impl PyBuffer {
#[must_use]
pub fn new(obj: PyObjectRef, desc: BufferDescriptor, methods: &'static BufferMethods) -> Self {
let zelf = Self {
obj,
desc: desc.validate(),
methods,
};
#[cfg(debug_assertions)]
let desc = desc.validate();

let zelf = Self { obj, desc, methods };
zelf.retain();
zelf
}
Expand Down Expand Up @@ -216,30 +215,25 @@ impl BufferDescriptor {
if self.ndim() == 0 {
// Empty structures (len=0) can have itemsize=0
if self.len > 0 {
assert!(self.itemsize != 0);
debug_assert_ne!(self.itemsize, 0);
}
assert!(self.itemsize == self.len);
debug_assert_eq!(self.itemsize, self.len);
} else {
let mut shape_product = 1;
let has_zero_dim = self.dim_desc.iter().any(|(s, _, _)| *s == 0);
for (shape, stride, suboffset) in self.dim_desc.iter().copied() {
shape_product *= shape;
assert!(suboffset >= 0);
debug_assert!(suboffset >= 0);
// For empty arrays (any dimension is 0), strides can be 0
if !has_zero_dim {
assert!(stride != 0);
debug_assert_ne!(stride, 0);
}
}
assert!(shape_product * self.itemsize == self.len);
debug_assert_eq!(shape_product * self.itemsize, self.len);
}
self
}

#[cfg(not(debug_assertions))]
pub fn validate(self) -> Self {
self
}

#[must_use]
pub fn ndim(&self) -> usize {
self.dim_desc.len()
Expand Down Expand Up @@ -396,6 +390,7 @@ impl BufferDescriptor {
}
}

#[must_use]
fn is_last_dim_contiguous(&self) -> bool {
let (_, stride, suboffset) = self.dim_desc[self.ndim() - 1];
suboffset == 0 && stride == self.itemsize as isize
Expand Down
12 changes: 9 additions & 3 deletions crates/vm/src/protocol/callable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ use crate::{

impl PyObject {
#[inline]
#[must_use]
pub fn to_callable(&self) -> Option<PyCallable<'_>> {
PyCallable::new(self)
}

#[inline]
#[must_use]
pub fn is_callable(&self) -> bool {
self.to_callable().is_some()
}
Expand Down Expand Up @@ -134,6 +136,7 @@ impl<'a> PyCallable<'a> {
}

/// Trace events for sys.settrace and sys.setprofile.
#[derive(Clone, Copy, Eq, PartialEq)]
pub(crate) enum TraceEvent {
Call,
Return,
Expand All @@ -147,7 +150,8 @@ pub(crate) enum TraceEvent {

impl TraceEvent {
/// Whether sys.settrace receives this event.
fn is_trace_event(&self) -> bool {
#[must_use]
const fn is_trace_event(&self) -> bool {
matches!(
self,
Self::Call | Self::Return | Self::Exception | Self::Line | Self::Opcode
Expand All @@ -157,15 +161,17 @@ impl TraceEvent {
/// Whether sys.setprofile receives this event.
/// In legacy_tracing.c, profile callbacks are only registered for
/// PY_RETURN, PY_UNWIND, C_CALL, C_RETURN, C_RAISE.
fn is_profile_event(&self) -> bool {
#[must_use]
const fn is_profile_event(&self) -> bool {
matches!(
self,
Self::Call | Self::Return | Self::CCall | Self::CReturn | Self::CException
)
}

/// Whether this event is dispatched only when f_trace_opcodes is set.
pub(crate) fn is_opcode_event(&self) -> bool {
#[must_use]
pub(crate) const fn is_opcode_event(&self) -> bool {
matches!(self, Self::Opcode)
}
}
Expand Down
7 changes: 4 additions & 3 deletions crates/vm/src/protocol/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ use crate::{
use core::borrow::Borrow;
use core::ops::Deref;

/// Iterator Protocol
// https://docs.python.org/3/c-api/iter.html
/// [Iterator Protocol](https://docs.python.org/3/c-api/iter.html).
#[derive(Debug, Clone)]
#[repr(transparent)]
pub struct PyIter<O = PyObjectRef>(O)
Expand All @@ -31,9 +30,11 @@ impl<O> PyIter<O>
where
O: Borrow<PyObject>,
{
#[must_use]
pub const fn new(obj: O) -> Self {
Self(obj)
}

pub fn next(&self, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
let iternext = self
.0
Expand Down Expand Up @@ -193,7 +194,7 @@ impl PyIterReturn {
match self {
Self::Return(obj) => Ok(obj),
Self::StopIteration(v) => Err({
let args = if let Some(v) = v { vec![v] } else { Vec::new() };
let args = v.map_or_else(Vec::new, |v| vec![v]);
vm.new_exception(vm.ctx.exceptions.stop_async_iteration.to_owned(), args)
}),
}
Expand Down
Loading
Loading