mirror of
https://github.com/RustPython/RustPython.git
synced 2026-10-28 18:59:04 +08:00
Remove unnecessary to_{owned,string}() calls (#7367)
This commit is contained in:
1 parent
a27d812286
commit
fc1c27896b
71 files changed
+411
-552
No files matched your search
@@ -151,7 +151,7 @@ pub(crate) mod _asyncio {
|
||||
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
|
||||
// Future does not accept positional arguments
|
||||
if !args.args.is_empty() {
|
||||
return Err(vm.new_type_error("Future() takes no positional arguments".to_string()));
|
||||
return Err(vm.new_type_error("Future() takes no positional arguments"));
|
||||
}
|
||||
// Extract only 'loop' keyword argument
|
||||
let loop_ = args.kwargs.get("loop").cloned();
|
||||
@@ -265,7 +265,7 @@ pub(crate) mod _asyncio {
|
||||
#[pymethod]
|
||||
fn set_result(zelf: PyRef<Self>, result: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
if zelf.fut_loop.read().is_none() {
|
||||
return Err(vm.new_runtime_error("Future object is not initialized.".to_string()));
|
||||
return Err(vm.new_runtime_error("Future object is not initialized."));
|
||||
}
|
||||
if zelf.fut_state.load() != FutureState::Pending {
|
||||
return Err(new_invalid_state_error(vm, "invalid state"));
|
||||
@@ -283,7 +283,7 @@ pub(crate) mod _asyncio {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<()> {
|
||||
if zelf.fut_loop.read().is_none() {
|
||||
return Err(vm.new_runtime_error("Future object is not initialized.".to_string()));
|
||||
return Err(vm.new_runtime_error("Future object is not initialized."));
|
||||
}
|
||||
if zelf.fut_state.load() != FutureState::Pending {
|
||||
return Err(new_invalid_state_error(vm, "invalid state"));
|
||||
@@ -336,7 +336,7 @@ pub(crate) mod _asyncio {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<()> {
|
||||
if zelf.fut_loop.read().is_none() {
|
||||
return Err(vm.new_runtime_error("Future object is not initialized.".to_string()));
|
||||
return Err(vm.new_runtime_error("Future object is not initialized."));
|
||||
}
|
||||
let ctx = match args.context.flatten() {
|
||||
Some(c) => c,
|
||||
@@ -364,7 +364,7 @@ pub(crate) mod _asyncio {
|
||||
#[pymethod]
|
||||
fn remove_done_callback(&self, func: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> {
|
||||
if self.fut_loop.read().is_none() {
|
||||
return Err(vm.new_runtime_error("Future object is not initialized.".to_string()));
|
||||
return Err(vm.new_runtime_error("Future object is not initialized."));
|
||||
}
|
||||
let mut cleared_callback0 = 0usize;
|
||||
|
||||
@@ -461,7 +461,7 @@ pub(crate) mod _asyncio {
|
||||
#[pymethod]
|
||||
fn cancel(zelf: PyRef<Self>, args: CancelArgs, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
if zelf.fut_loop.read().is_none() {
|
||||
return Err(vm.new_runtime_error("Future object is not initialized.".to_string()));
|
||||
return Err(vm.new_runtime_error("Future object is not initialized."));
|
||||
}
|
||||
if zelf.fut_state.load() != FutureState::Pending {
|
||||
// Clear log_tb even when cancel fails
|
||||
@@ -598,9 +598,7 @@ pub(crate) mod _asyncio {
|
||||
self.fut_blocking.store(v, Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
PySetterValue::Delete => {
|
||||
Err(vm.new_attribute_error("cannot delete attribute".to_string()))
|
||||
}
|
||||
PySetterValue::Delete => Err(vm.new_attribute_error("cannot delete attribute")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -670,16 +668,12 @@ pub(crate) mod _asyncio {
|
||||
match value {
|
||||
PySetterValue::Assign(v) => {
|
||||
if v {
|
||||
return Err(vm.new_value_error(
|
||||
"_log_traceback can only be set to False".to_string(),
|
||||
));
|
||||
return Err(vm.new_value_error("_log_traceback can only be set to False"));
|
||||
}
|
||||
self.fut_log_tb.store(false, Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
PySetterValue::Delete => {
|
||||
Err(vm.new_attribute_error("cannot delete attribute".to_string()))
|
||||
}
|
||||
PySetterValue::Delete => Err(vm.new_attribute_error("cannot delete attribute")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1055,7 +1049,7 @@ pub(crate) mod _asyncio {
|
||||
// Must be a subclass of BaseException
|
||||
if !exc_class.fast_issubclass(vm.ctx.exceptions.base_exception_type) {
|
||||
return Err(vm.new_type_error(
|
||||
"exceptions must be classes or instances deriving from BaseException, not type".to_string()
|
||||
"exceptions must be classes or instances deriving from BaseException, not type"
|
||||
));
|
||||
}
|
||||
|
||||
@@ -1072,9 +1066,9 @@ pub(crate) mod _asyncio {
|
||||
if let OptionalArg::Present(ref val) = exc_val
|
||||
&& !vm.is_none(val)
|
||||
{
|
||||
return Err(vm.new_type_error(
|
||||
"instance exception may not have a separate value".to_string(),
|
||||
));
|
||||
return Err(
|
||||
vm.new_type_error("instance exception may not have a separate value")
|
||||
);
|
||||
}
|
||||
exc_type
|
||||
} else {
|
||||
@@ -1339,7 +1333,7 @@ pub(crate) mod _asyncio {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<()> {
|
||||
if zelf.base.fut_loop.read().is_none() {
|
||||
return Err(vm.new_runtime_error("Future object is not initialized.".to_string()));
|
||||
return Err(vm.new_runtime_error("Future object is not initialized."));
|
||||
}
|
||||
let ctx = match args.context.flatten() {
|
||||
Some(c) => c,
|
||||
@@ -1367,7 +1361,7 @@ pub(crate) mod _asyncio {
|
||||
#[pymethod]
|
||||
fn remove_done_callback(&self, func: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> {
|
||||
if self.base.fut_loop.read().is_none() {
|
||||
return Err(vm.new_runtime_error("Future object is not initialized.".to_string()));
|
||||
return Err(vm.new_runtime_error("Future object is not initialized."));
|
||||
}
|
||||
let mut cleared_callback0 = 0usize;
|
||||
|
||||
@@ -1686,9 +1680,7 @@ pub(crate) mod _asyncio {
|
||||
self.base.fut_blocking.store(v, Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
PySetterValue::Delete => {
|
||||
Err(vm.new_attribute_error("cannot delete attribute".to_string()))
|
||||
}
|
||||
PySetterValue::Delete => Err(vm.new_attribute_error("cannot delete attribute")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1718,7 +1710,7 @@ pub(crate) mod _asyncio {
|
||||
Ok(())
|
||||
}
|
||||
PySetterValue::Delete => {
|
||||
Err(vm.new_attribute_error("can't delete _log_destroy_pending".to_owned()))
|
||||
Err(vm.new_attribute_error("can't delete _log_destroy_pending"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1737,16 +1729,12 @@ pub(crate) mod _asyncio {
|
||||
match value {
|
||||
PySetterValue::Assign(v) => {
|
||||
if v {
|
||||
return Err(vm.new_value_error(
|
||||
"_log_traceback can only be set to False".to_string(),
|
||||
));
|
||||
return Err(vm.new_value_error("_log_traceback can only be set to False"));
|
||||
}
|
||||
self.base.fut_log_tb.store(false, Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
PySetterValue::Delete => {
|
||||
Err(vm.new_attribute_error("cannot delete attribute".to_string()))
|
||||
}
|
||||
PySetterValue::Delete => Err(vm.new_attribute_error("cannot delete attribute")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2532,14 +2520,10 @@ pub(crate) mod _asyncio {
|
||||
let running_task = vm.asyncio_running_task.borrow();
|
||||
match running_task.as_ref() {
|
||||
None => {
|
||||
return Err(vm.new_runtime_error(
|
||||
"_leave_task: task is not the current task".to_owned(),
|
||||
));
|
||||
return Err(vm.new_runtime_error("_leave_task: task is not the current task"));
|
||||
}
|
||||
Some(current) if !current.is(&task) => {
|
||||
return Err(vm.new_runtime_error(
|
||||
"_leave_task: task is not the current task".to_owned(),
|
||||
));
|
||||
return Err(vm.new_runtime_error("_leave_task: task is not the current task"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -2777,7 +2761,7 @@ pub(crate) mod _asyncio {
|
||||
.ok_or_else(|| vm.new_attribute_error("CancelledError not found"))?;
|
||||
exc_type
|
||||
.downcast()
|
||||
.map_err(|_| vm.new_type_error("CancelledError is not a type".to_string()))
|
||||
.map_err(|_| vm.new_type_error("CancelledError is not a type"))
|
||||
}
|
||||
|
||||
fn is_cancelled_error(exc: &PyBaseExceptionRef, vm: &VirtualMachine) -> bool {
|
||||
|
||||
@@ -98,7 +98,7 @@ mod _remote_debugging {
|
||||
type Args = FuncArgs;
|
||||
|
||||
fn py_new(_cls: &Py<PyType>, _args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
Err(vm.new_not_implemented_error("_remote_debugging is not available".to_owned()))
|
||||
Err(vm.new_not_implemented_error("_remote_debugging is not available"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1512,9 +1512,9 @@ mod _sqlite3 {
|
||||
let _ = unsafe { self.isolation_level.swap(value) };
|
||||
Ok(())
|
||||
}
|
||||
PySetterValue::Delete => Err(vm.new_attribute_error(
|
||||
"'isolation_level' attribute cannot be deleted".to_owned(),
|
||||
)),
|
||||
PySetterValue::Delete => {
|
||||
Err(vm.new_attribute_error("'isolation_level' attribute cannot be deleted"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -463,7 +463,7 @@ mod decl {
|
||||
|
||||
// Install signal handlers
|
||||
if !faulthandler_enable_internal() {
|
||||
return Err(vm.new_runtime_error("Failed to enable faulthandler".to_owned()));
|
||||
return Err(vm.new_runtime_error("Failed to enable faulthandler"));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -802,9 +802,7 @@ mod decl {
|
||||
// Check if it's an integer (file descriptor)
|
||||
if let Ok(fd) = f.try_to_value::<i32>(vm) {
|
||||
if fd < 0 {
|
||||
return Err(
|
||||
vm.new_value_error("file is not a valid file descriptor".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("file is not a valid file descriptor"));
|
||||
}
|
||||
return Ok(fd);
|
||||
}
|
||||
@@ -812,9 +810,7 @@ mod decl {
|
||||
let fileno = vm.call_method(&f, "fileno", ())?;
|
||||
let fd: i32 = fileno.try_to_value(vm)?;
|
||||
if fd < 0 {
|
||||
return Err(
|
||||
vm.new_value_error("file is not a valid file descriptor".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("file is not a valid file descriptor"));
|
||||
}
|
||||
// Try to flush the file
|
||||
let _ = vm.call_method(&f, "flush", ());
|
||||
@@ -824,7 +820,7 @@ mod decl {
|
||||
// file=None or file not passed: fall back to sys.stderr
|
||||
let stderr = vm.sys_module.get_attr("stderr", vm)?;
|
||||
if vm.is_none(&stderr) {
|
||||
return Err(vm.new_runtime_error("sys.stderr is None".to_owned()));
|
||||
return Err(vm.new_runtime_error("sys.stderr is None"));
|
||||
}
|
||||
let fileno = vm.call_method(&stderr, "fileno", ())?;
|
||||
let fd: i32 = fileno.try_to_value(vm)?;
|
||||
@@ -912,7 +908,7 @@ mod decl {
|
||||
let timeout: f64 = args.timeout.into_float();
|
||||
|
||||
if timeout <= 0.0 {
|
||||
return Err(vm.new_value_error("timeout must be greater than 0".to_owned()));
|
||||
return Err(vm.new_value_error("timeout must be greater than 0"));
|
||||
}
|
||||
|
||||
let fd = get_fd_from_file_opt(args.file, vm)?;
|
||||
@@ -920,7 +916,7 @@ mod decl {
|
||||
// Convert timeout to microseconds
|
||||
let timeout_us = (timeout * 1_000_000.0) as u64;
|
||||
if timeout_us == 0 {
|
||||
return Err(vm.new_value_error("timeout must be greater than 0".to_owned()));
|
||||
return Err(vm.new_value_error("timeout must be greater than 0"));
|
||||
}
|
||||
|
||||
let header = format_timeout(timeout_us);
|
||||
@@ -1098,7 +1094,7 @@ mod decl {
|
||||
|
||||
// Check if signal is in valid range
|
||||
if !(1..64).contains(&signum) {
|
||||
return Err(vm.new_value_error("signal number out of range".to_owned()));
|
||||
return Err(vm.new_value_error("signal number out of range"));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -210,8 +210,7 @@ pub mod _hashlib {
|
||||
(Some(_), Some(_)) => Err(vm.new_type_error(
|
||||
"'data' and 'string' are mutually exclusive \
|
||||
and support for 'string' keyword parameter \
|
||||
is slated for removal in a future version."
|
||||
.to_owned(),
|
||||
is slated for removal in a future version.",
|
||||
)),
|
||||
}
|
||||
}
|
||||
@@ -306,7 +305,7 @@ pub mod _hashlib {
|
||||
impl PyHmac {
|
||||
#[pyslot]
|
||||
fn slot_new(_cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_type_error("cannot create '_hashlib.HMAC' instances".to_owned()))
|
||||
Err(vm.new_type_error("cannot create '_hashlib.HMAC' instances"))
|
||||
}
|
||||
|
||||
#[pygetset]
|
||||
@@ -758,9 +757,10 @@ pub mod _hashlib {
|
||||
|
||||
#[pyfunction]
|
||||
fn hmac_new(args: NewHMACHashArgs, vm: &VirtualMachine) -> PyResult<PyHmac> {
|
||||
let digestmod = args.digestmod.into_option().ok_or_else(|| {
|
||||
vm.new_type_error("Missing required parameter 'digestmod'.".to_owned())
|
||||
})?;
|
||||
let digestmod = args
|
||||
.digestmod
|
||||
.into_option()
|
||||
.ok_or_else(|| vm.new_type_error("Missing required parameter 'digestmod'."))?;
|
||||
let name = resolve_digestmod(&digestmod, vm)?;
|
||||
|
||||
let key_buf = args.key.borrow_buf();
|
||||
@@ -833,10 +833,10 @@ pub mod _hashlib {
|
||||
let name = args.hash_name.as_str().to_lowercase();
|
||||
|
||||
if args.iterations < 1 {
|
||||
return Err(vm.new_value_error("iteration value must be greater than 0.".to_owned()));
|
||||
return Err(vm.new_value_error("iteration value must be greater than 0."));
|
||||
}
|
||||
let rounds = u32::try_from(args.iterations)
|
||||
.map_err(|_| vm.new_overflow_error("iteration value is too great.".to_owned()))?;
|
||||
.map_err(|_| vm.new_overflow_error("iteration value is too great."))?;
|
||||
|
||||
let dklen: usize = match args.dklen.into_option() {
|
||||
Some(obj) if vm.is_none(&obj) => {
|
||||
@@ -845,10 +845,10 @@ pub mod _hashlib {
|
||||
Some(obj) => {
|
||||
let len: i64 = obj.try_into_value(vm)?;
|
||||
if len < 1 {
|
||||
return Err(vm.new_value_error("key length must be greater than 0.".to_owned()));
|
||||
return Err(vm.new_value_error("key length must be greater than 0."));
|
||||
}
|
||||
usize::try_from(len)
|
||||
.map_err(|_| vm.new_overflow_error("key length is too great.".to_owned()))?
|
||||
.map_err(|_| vm.new_overflow_error("key length is too great."))?
|
||||
}
|
||||
None => hash_digest_size(&name).ok_or_else(|| unsupported_hash(&name, vm))?,
|
||||
};
|
||||
|
||||
@@ -102,13 +102,13 @@ mod math {
|
||||
)));
|
||||
}
|
||||
if b == 1.0 {
|
||||
return Err(vm.new_value_error("math domain error".to_owned()));
|
||||
return Err(vm.new_value_error("math domain error"));
|
||||
}
|
||||
}
|
||||
// Handle BigInt specially for large values (only for actual int type, not float)
|
||||
if let Some(i) = x.downcast_ref::<PyInt>() {
|
||||
return pymath::math::log_bigint(i.as_bigint(), base).map_err(|err| match err {
|
||||
pymath::Error::EDOM => vm.new_value_error("expected a positive input".to_owned()),
|
||||
pymath::Error::EDOM => vm.new_value_error("expected a positive input"),
|
||||
_ => pymath_exception(err, vm),
|
||||
});
|
||||
}
|
||||
@@ -132,7 +132,7 @@ mod math {
|
||||
// Handle BigInt specially for large values (only for actual int type, not float)
|
||||
if let Some(i) = x.downcast_ref::<PyInt>() {
|
||||
return pymath::math::log2_bigint(i.as_bigint()).map_err(|err| match err {
|
||||
pymath::Error::EDOM => vm.new_value_error("expected a positive input".to_owned()),
|
||||
pymath::Error::EDOM => vm.new_value_error("expected a positive input"),
|
||||
_ => pymath_exception(err, vm),
|
||||
});
|
||||
}
|
||||
@@ -151,7 +151,7 @@ mod math {
|
||||
// Handle BigInt specially for large values (only for actual int type, not float)
|
||||
if let Some(i) = x.downcast_ref::<PyInt>() {
|
||||
return pymath::math::log10_bigint(i.as_bigint()).map_err(|err| match err {
|
||||
pymath::Error::EDOM => vm.new_value_error("expected a positive input".to_owned()),
|
||||
pymath::Error::EDOM => vm.new_value_error("expected a positive input"),
|
||||
_ => pymath_exception(err, vm),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -557,13 +557,11 @@ mod mmap {
|
||||
// Parse tagname: None or a string
|
||||
let tag_str: Option<String> = match tagname {
|
||||
Some(ref obj) if !vm.is_none(obj) => {
|
||||
let s = obj.try_to_value::<String>(vm).map_err(|_| {
|
||||
vm.new_type_error("tagname must be a string or None".to_owned())
|
||||
})?;
|
||||
let s = obj
|
||||
.try_to_value::<String>(vm)
|
||||
.map_err(|_| vm.new_type_error("tagname must be a string or None"))?;
|
||||
if s.contains('\0') {
|
||||
return Err(vm.new_value_error(
|
||||
"tagname must not contain null characters".to_owned(),
|
||||
));
|
||||
return Err(vm.new_value_error("tagname must not contain null characters"));
|
||||
}
|
||||
Some(s)
|
||||
}
|
||||
|
||||
@@ -154,7 +154,7 @@ mod _multiprocessing {
|
||||
if timeout < 0.0 {
|
||||
0
|
||||
} else if timeout >= 0.5 * INFINITE as f64 {
|
||||
return Err(vm.new_overflow_error("timeout is too large".to_owned()));
|
||||
return Err(vm.new_overflow_error("timeout is too large"));
|
||||
} else {
|
||||
(timeout + 0.5) as u32
|
||||
}
|
||||
@@ -236,9 +236,7 @@ mod _multiprocessing {
|
||||
if unsafe { ReleaseSemaphore(self.handle.as_raw(), 1, core::ptr::null_mut()) } == 0 {
|
||||
let err = unsafe { windows_sys::Win32::Foundation::GetLastError() };
|
||||
if err == ERROR_TOO_MANY_POSTS {
|
||||
return Err(
|
||||
vm.new_value_error("semaphore or lock released too many times".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("semaphore or lock released too many times"));
|
||||
}
|
||||
return Err(vm.new_last_os_error());
|
||||
}
|
||||
@@ -294,7 +292,7 @@ mod _multiprocessing {
|
||||
|
||||
#[pymethod]
|
||||
fn __reduce__(&self, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_type_error("cannot pickle 'SemLock' object".to_owned()))
|
||||
Err(vm.new_type_error("cannot pickle 'SemLock' object"))
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
@@ -338,13 +336,13 @@ mod _multiprocessing {
|
||||
|
||||
fn py_new(_cls: &Py<PyType>, args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
if args.kind != RECURSIVE_MUTEX && args.kind != SEMAPHORE {
|
||||
return Err(vm.new_value_error("unrecognized kind".to_owned()));
|
||||
return Err(vm.new_value_error("unrecognized kind"));
|
||||
}
|
||||
if args.maxvalue <= 0 {
|
||||
return Err(vm.new_value_error("maxvalue must be positive".to_owned()));
|
||||
return Err(vm.new_value_error("maxvalue must be positive"));
|
||||
}
|
||||
if args.value < 0 || args.value > args.maxvalue {
|
||||
return Err(vm.new_value_error("invalid value".to_owned()));
|
||||
return Err(vm.new_value_error("invalid value"));
|
||||
}
|
||||
|
||||
let handle = SemHandle::create(args.value, args.maxvalue, vm)?;
|
||||
@@ -816,9 +814,7 @@ mod _multiprocessing {
|
||||
return Err(os_error(vm, Errno::last()));
|
||||
}
|
||||
if sval >= self.maxvalue {
|
||||
return Err(vm.new_value_error(
|
||||
"semaphore or lock released too many times".to_owned(),
|
||||
));
|
||||
return Err(vm.new_value_error("semaphore or lock released too many times"));
|
||||
}
|
||||
}
|
||||
#[cfg(target_vendor = "apple")]
|
||||
@@ -837,9 +833,9 @@ mod _multiprocessing {
|
||||
if unsafe { libc::sem_post(self.handle.as_ptr()) } < 0 {
|
||||
return Err(os_error(vm, Errno::last()));
|
||||
}
|
||||
return Err(vm.new_value_error(
|
||||
"semaphore or lock released too many times".to_owned(),
|
||||
));
|
||||
return Err(
|
||||
vm.new_value_error("semaphore or lock released too many times")
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -887,7 +883,7 @@ mod _multiprocessing {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult {
|
||||
let Some(ref name_str) = name else {
|
||||
return Err(vm.new_value_error("cannot rebuild SemLock without name".to_owned()));
|
||||
return Err(vm.new_value_error("cannot rebuild SemLock without name"));
|
||||
};
|
||||
let handle = SemHandle::open_existing(name_str, vm)?;
|
||||
// return newsemlockobject(type, handle, kind, maxvalue, name_copy);
|
||||
@@ -915,7 +911,7 @@ mod _multiprocessing {
|
||||
/// Use multiprocessing.synchronize.SemLock wrapper which handles pickling.
|
||||
#[pymethod]
|
||||
fn __reduce__(&self, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_type_error("cannot pickle 'SemLock' object".to_owned()))
|
||||
Err(vm.new_type_error("cannot pickle 'SemLock' object"))
|
||||
}
|
||||
|
||||
/// Num of `acquire()`s minus num of `release()`s for this process.
|
||||
@@ -1012,11 +1008,11 @@ mod _multiprocessing {
|
||||
// _multiprocessing_SemLock_impl
|
||||
fn py_new(_cls: &Py<PyType>, args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
if args.kind != RECURSIVE_MUTEX && args.kind != SEMAPHORE {
|
||||
return Err(vm.new_value_error("unrecognized kind".to_owned()));
|
||||
return Err(vm.new_value_error("unrecognized kind"));
|
||||
}
|
||||
// Value validation
|
||||
if args.value < 0 || args.value > args.maxvalue {
|
||||
return Err(vm.new_value_error("invalid value".to_owned()));
|
||||
return Err(vm.new_value_error("invalid value"));
|
||||
}
|
||||
|
||||
let value = args.value as u32;
|
||||
@@ -1081,7 +1077,7 @@ mod _multiprocessing {
|
||||
full.push('/');
|
||||
}
|
||||
full.push_str(name);
|
||||
CString::new(full).map_err(|_| vm.new_value_error("embedded null character".to_owned()))
|
||||
CString::new(full).map_err(|_| vm.new_value_error("embedded null character"))
|
||||
}
|
||||
|
||||
fn os_error(vm: &VirtualMachine, err: Errno) -> PyBaseExceptionRef {
|
||||
|
||||
@@ -394,11 +394,11 @@ mod _ssl {
|
||||
let nid = obj.nid();
|
||||
let short_name = nid
|
||||
.short_name()
|
||||
.map_err(|_| vm.new_value_error("NID has no short name".to_owned()))?
|
||||
.map_err(|_| vm.new_value_error("NID has no short name"))?
|
||||
.to_owned();
|
||||
let long_name = nid
|
||||
.long_name()
|
||||
.map_err(|_| vm.new_value_error("NID has no long name".to_owned()))?
|
||||
.map_err(|_| vm.new_value_error("NID has no long name"))?
|
||||
.to_owned();
|
||||
Ok((
|
||||
nid.as_raw(),
|
||||
@@ -1135,7 +1135,7 @@ mod _ssl {
|
||||
#[pygetset(setter)]
|
||||
fn set_options(&self, new_opts: i64, vm: &VirtualMachine) -> PyResult<()> {
|
||||
if new_opts < 0 {
|
||||
return Err(vm.new_value_error("invalid options value".to_owned()));
|
||||
return Err(vm.new_value_error("invalid options value"));
|
||||
}
|
||||
let new_opts = new_opts as libc::c_ulong;
|
||||
let mut ctx = self.builder();
|
||||
@@ -1321,14 +1321,12 @@ mod _ssl {
|
||||
fn set_num_tickets(&self, value: isize, vm: &VirtualMachine) -> PyResult<()> {
|
||||
// Check for negative values
|
||||
if value < 0 {
|
||||
return Err(
|
||||
vm.new_value_error("num_tickets must be a non-negative integer".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("num_tickets must be a non-negative integer"));
|
||||
}
|
||||
|
||||
// Check that this is a server context
|
||||
if self.protocol != SslVersion::TlsServer {
|
||||
return Err(vm.new_value_error("SSLContext is not a server context.".to_owned()));
|
||||
return Err(vm.new_value_error("SSLContext is not a server context."));
|
||||
}
|
||||
|
||||
#[cfg(ossl110)]
|
||||
@@ -1421,7 +1419,7 @@ mod _ssl {
|
||||
}
|
||||
} else {
|
||||
if !callback.is_callable() {
|
||||
return Err(vm.new_type_error("callback must be callable".to_owned()));
|
||||
return Err(vm.new_type_error("callback must be callable"));
|
||||
}
|
||||
*self.psk_client_callback.lock() = Some(callback);
|
||||
// Note: The actual callback will be invoked via SSL app_data mechanism
|
||||
@@ -1457,7 +1455,7 @@ mod _ssl {
|
||||
}
|
||||
} else {
|
||||
if !callback.is_callable() {
|
||||
return Err(vm.new_type_error("callback must be callable".to_owned()));
|
||||
return Err(vm.new_type_error("callback must be callable"));
|
||||
}
|
||||
*self.psk_server_callback.lock() = Some(callback);
|
||||
if let OptionalArg::Present(hint) = identity_hint {
|
||||
@@ -1588,12 +1586,12 @@ mod _ssl {
|
||||
let store_ptr = unsafe { sys::SSL_CTX_get_cert_store(ctx.as_ptr()) };
|
||||
|
||||
if store_ptr.is_null() {
|
||||
return Err(vm.new_memory_error("failed to get cert store".to_owned()));
|
||||
return Err(vm.new_memory_error("failed to get cert store"));
|
||||
}
|
||||
|
||||
let objs_ptr = unsafe { sys::X509_STORE_get0_objects(store_ptr) };
|
||||
if objs_ptr.is_null() {
|
||||
return Err(vm.new_memory_error("failed to query cert store".to_owned()));
|
||||
return Err(vm.new_memory_error("failed to query cert store"));
|
||||
}
|
||||
|
||||
let mut x509_count = 0;
|
||||
@@ -1727,9 +1725,7 @@ mod _ssl {
|
||||
) -> PyResult<()> {
|
||||
// Check if this is a server context
|
||||
if self.protocol == SslVersion::TlsClient {
|
||||
return Err(vm.new_value_error(
|
||||
"sni_callback cannot be set on TLS_CLIENT context".to_owned(),
|
||||
));
|
||||
return Err(vm.new_value_error("sni_callback cannot be set on TLS_CLIENT context"));
|
||||
}
|
||||
|
||||
let mut callback_guard = self.sni_callback.lock();
|
||||
@@ -1738,7 +1734,7 @@ mod _ssl {
|
||||
if !vm.is_none(&callback_obj) {
|
||||
// Check if callable
|
||||
if !callback_obj.is_callable() {
|
||||
return Err(vm.new_type_error("not a callable object".to_owned()));
|
||||
return Err(vm.new_type_error("not a callable object"));
|
||||
}
|
||||
|
||||
// Set the callback
|
||||
@@ -1805,7 +1801,7 @@ mod _ssl {
|
||||
if !vm.is_none(&callback_obj) {
|
||||
// Check if callable
|
||||
if !callback_obj.is_callable() {
|
||||
return Err(vm.new_type_error("not a callable object".to_owned()));
|
||||
return Err(vm.new_type_error("not a callable object"));
|
||||
}
|
||||
|
||||
// Set the callback
|
||||
@@ -2521,7 +2517,7 @@ mod _ssl {
|
||||
unsafe {
|
||||
let result = SSL_set_SSL_CTX(ssl_ptr, value.ctx().as_ptr());
|
||||
if result.is_null() {
|
||||
return Err(vm.new_runtime_error("Failed to set SSL context".to_owned()));
|
||||
return Err(vm.new_runtime_error("Failed to set SSL context"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2806,7 +2802,7 @@ mod _ssl {
|
||||
#[cfg(not(ossl111))]
|
||||
{
|
||||
Err(vm.new_not_implemented_error(
|
||||
"Post-handshake auth is not supported by your OpenSSL version.".to_owned(),
|
||||
"Post-handshake auth is not supported by your OpenSSL version.",
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -3116,32 +3112,26 @@ mod _ssl {
|
||||
// Check if value is SSLSession type
|
||||
let session = value
|
||||
.downcast_ref::<PySslSession>()
|
||||
.ok_or_else(|| vm.new_type_error("Value is not a SSLSession.".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_type_error("Value is not a SSLSession."))?;
|
||||
|
||||
// Check if session refers to the same SSLContext
|
||||
if !std::ptr::eq(
|
||||
self.ctx.read().ctx.read().as_ptr(),
|
||||
session.ctx.ctx.read().as_ptr(),
|
||||
) {
|
||||
return Err(
|
||||
vm.new_value_error("Session refers to a different SSLContext.".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("Session refers to a different SSLContext."));
|
||||
}
|
||||
|
||||
// Check if this is a client socket
|
||||
if self.socket_type != SslServerOrClient::Client {
|
||||
return Err(
|
||||
vm.new_value_error("Cannot set session for server-side SSLSocket.".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("Cannot set session for server-side SSLSocket."));
|
||||
}
|
||||
|
||||
// Check if handshake is not finished
|
||||
let stream = self.connection.read();
|
||||
unsafe {
|
||||
if sys::SSL_is_init_finished(stream.ssl().as_ptr()) != 0 {
|
||||
return Err(
|
||||
vm.new_value_error("Cannot set session after handshake.".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("Cannot set session after handshake."));
|
||||
}
|
||||
|
||||
let ret = sys::SSL_set_session(stream.ssl().as_ptr(), session.session);
|
||||
@@ -3182,7 +3172,7 @@ mod _ssl {
|
||||
}
|
||||
OptionalArg::Missing => {
|
||||
if n < 0 {
|
||||
return Err(vm.new_value_error("size should not be negative".to_owned()));
|
||||
return Err(vm.new_value_error("size should not be negative"));
|
||||
}
|
||||
n as usize
|
||||
}
|
||||
@@ -3602,7 +3592,7 @@ mod _ssl {
|
||||
unsafe {
|
||||
let bio = sys::BIO_new(sys::BIO_s_mem());
|
||||
if bio.is_null() {
|
||||
return Err(vm.new_memory_error("failed to allocate BIO".to_owned()));
|
||||
return Err(vm.new_memory_error("failed to allocate BIO"));
|
||||
}
|
||||
|
||||
sys::BIO_set_retry_read(bio);
|
||||
|
||||
@@ -379,7 +379,7 @@ mod _overlapped {
|
||||
};
|
||||
Ok((bytes.to_vec(), addr_len))
|
||||
}
|
||||
_ => Err(vm.new_value_error("illegal address_as_bytes argument".to_owned())),
|
||||
_ => Err(vm.new_value_error("illegal address_as_bytes argument")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -407,7 +407,7 @@ mod _overlapped {
|
||||
let scope_id = addr.Anonymous.sin6_scope_id;
|
||||
Ok((ip_str, port, flowinfo, scope_id).to_pyobject(vm))
|
||||
} else {
|
||||
Err(vm.new_value_error("recvfrom returned unsupported address family".to_owned()))
|
||||
Err(vm.new_value_error("recvfrom returned unsupported address family"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -473,10 +473,10 @@ mod _overlapped {
|
||||
|
||||
// Check operation state
|
||||
if matches!(inner.data, OverlappedData::None) {
|
||||
return Err(vm.new_value_error("operation not yet attempted".to_owned()));
|
||||
return Err(vm.new_value_error("operation not yet attempted"));
|
||||
}
|
||||
if matches!(inner.data, OverlappedData::NotStarted) {
|
||||
return Err(vm.new_value_error("operation failed to start".to_owned()));
|
||||
return Err(vm.new_value_error("operation failed to start"));
|
||||
}
|
||||
|
||||
// Get the result
|
||||
@@ -573,7 +573,7 @@ mod _overlapped {
|
||||
|
||||
let mut inner = zelf.inner.lock();
|
||||
if !matches!(inner.data, OverlappedData::None) {
|
||||
return Err(vm.new_value_error("operation already attempted".to_owned()));
|
||||
return Err(vm.new_value_error("operation already attempted"));
|
||||
}
|
||||
|
||||
#[cfg(target_pointer_width = "32")]
|
||||
@@ -630,19 +630,19 @@ mod _overlapped {
|
||||
|
||||
let mut inner = zelf.inner.lock();
|
||||
if !matches!(inner.data, OverlappedData::None) {
|
||||
return Err(vm.new_value_error("operation already attempted".to_owned()));
|
||||
return Err(vm.new_value_error("operation already attempted"));
|
||||
}
|
||||
|
||||
inner.handle = handle as HANDLE;
|
||||
let buf_len = buf.desc.len;
|
||||
if buf_len > u32::MAX as usize {
|
||||
return Err(vm.new_value_error("buffer too large".to_owned()));
|
||||
return Err(vm.new_value_error("buffer too large"));
|
||||
}
|
||||
|
||||
// For async read, buffer must be contiguous - we can't use a temporary copy
|
||||
// because Windows writes data directly to the buffer after this call returns
|
||||
let Some(contiguous) = buf.as_contiguous_mut() else {
|
||||
return Err(vm.new_buffer_error("buffer is not contiguous".to_owned()));
|
||||
return Err(vm.new_buffer_error("buffer is not contiguous"));
|
||||
};
|
||||
|
||||
inner.data = OverlappedData::ReadInto(buf.clone());
|
||||
@@ -694,7 +694,7 @@ mod _overlapped {
|
||||
|
||||
let mut inner = zelf.inner.lock();
|
||||
if !matches!(inner.data, OverlappedData::None) {
|
||||
return Err(vm.new_value_error("operation already attempted".to_owned()));
|
||||
return Err(vm.new_value_error("operation already attempted"));
|
||||
}
|
||||
|
||||
let mut flags = flags.unwrap_or(0);
|
||||
@@ -761,18 +761,18 @@ mod _overlapped {
|
||||
|
||||
let mut inner = zelf.inner.lock();
|
||||
if !matches!(inner.data, OverlappedData::None) {
|
||||
return Err(vm.new_value_error("operation already attempted".to_owned()));
|
||||
return Err(vm.new_value_error("operation already attempted"));
|
||||
}
|
||||
|
||||
let mut flags = flags;
|
||||
inner.handle = handle as HANDLE;
|
||||
let buf_len = buf.desc.len;
|
||||
if buf_len > u32::MAX as usize {
|
||||
return Err(vm.new_value_error("buffer too large".to_owned()));
|
||||
return Err(vm.new_value_error("buffer too large"));
|
||||
}
|
||||
|
||||
let Some(contiguous) = buf.as_contiguous_mut() else {
|
||||
return Err(vm.new_buffer_error("buffer is not contiguous".to_owned()));
|
||||
return Err(vm.new_buffer_error("buffer is not contiguous"));
|
||||
};
|
||||
|
||||
inner.data = OverlappedData::ReadInto(buf.clone());
|
||||
@@ -828,19 +828,19 @@ mod _overlapped {
|
||||
|
||||
let mut inner = zelf.inner.lock();
|
||||
if !matches!(inner.data, OverlappedData::None) {
|
||||
return Err(vm.new_value_error("operation already attempted".to_owned()));
|
||||
return Err(vm.new_value_error("operation already attempted"));
|
||||
}
|
||||
|
||||
inner.handle = handle as HANDLE;
|
||||
let buf_len = buf.desc.len;
|
||||
if buf_len > u32::MAX as usize {
|
||||
return Err(vm.new_value_error("buffer too large".to_owned()));
|
||||
return Err(vm.new_value_error("buffer too large"));
|
||||
}
|
||||
|
||||
// For async write, buffer must be contiguous - we can't use a temporary copy
|
||||
// because Windows reads from the buffer after this call returns
|
||||
let Some(contiguous) = buf.as_contiguous() else {
|
||||
return Err(vm.new_buffer_error("buffer is not contiguous".to_owned()));
|
||||
return Err(vm.new_buffer_error("buffer is not contiguous"));
|
||||
};
|
||||
|
||||
inner.data = OverlappedData::Write(buf.clone());
|
||||
@@ -886,17 +886,17 @@ mod _overlapped {
|
||||
|
||||
let mut inner = zelf.inner.lock();
|
||||
if !matches!(inner.data, OverlappedData::None) {
|
||||
return Err(vm.new_value_error("operation already attempted".to_owned()));
|
||||
return Err(vm.new_value_error("operation already attempted"));
|
||||
}
|
||||
|
||||
inner.handle = handle as HANDLE;
|
||||
let buf_len = buf.desc.len;
|
||||
if buf_len > u32::MAX as usize {
|
||||
return Err(vm.new_value_error("buffer too large".to_owned()));
|
||||
return Err(vm.new_value_error("buffer too large"));
|
||||
}
|
||||
|
||||
let Some(contiguous) = buf.as_contiguous() else {
|
||||
return Err(vm.new_buffer_error("buffer is not contiguous".to_owned()));
|
||||
return Err(vm.new_buffer_error("buffer is not contiguous"));
|
||||
};
|
||||
|
||||
inner.data = OverlappedData::Write(buf.clone());
|
||||
@@ -948,7 +948,7 @@ mod _overlapped {
|
||||
|
||||
let mut inner = zelf.inner.lock();
|
||||
if !matches!(inner.data, OverlappedData::None) {
|
||||
return Err(vm.new_value_error("operation already attempted".to_owned()));
|
||||
return Err(vm.new_value_error("operation already attempted"));
|
||||
}
|
||||
|
||||
// Buffer size: local address + remote address
|
||||
@@ -1016,7 +1016,7 @@ mod _overlapped {
|
||||
|
||||
let mut inner = zelf.inner.lock();
|
||||
if !matches!(inner.data, OverlappedData::None) {
|
||||
return Err(vm.new_value_error("operation already attempted".to_owned()));
|
||||
return Err(vm.new_value_error("operation already attempted"));
|
||||
}
|
||||
|
||||
let (addr_bytes, addr_len) = parse_address(&address, vm)?;
|
||||
@@ -1085,7 +1085,7 @@ mod _overlapped {
|
||||
|
||||
let mut inner = zelf.inner.lock();
|
||||
if !matches!(inner.data, OverlappedData::None) {
|
||||
return Err(vm.new_value_error("operation already attempted".to_owned()));
|
||||
return Err(vm.new_value_error("operation already attempted"));
|
||||
}
|
||||
|
||||
inner.handle = socket as HANDLE;
|
||||
@@ -1141,7 +1141,7 @@ mod _overlapped {
|
||||
|
||||
let mut inner = zelf.inner.lock();
|
||||
if !matches!(inner.data, OverlappedData::None) {
|
||||
return Err(vm.new_value_error("operation already attempted".to_owned()));
|
||||
return Err(vm.new_value_error("operation already attempted"));
|
||||
}
|
||||
|
||||
inner.handle = socket as HANDLE;
|
||||
@@ -1200,7 +1200,7 @@ mod _overlapped {
|
||||
|
||||
let mut inner = zelf.inner.lock();
|
||||
if !matches!(inner.data, OverlappedData::None) {
|
||||
return Err(vm.new_value_error("operation already attempted".to_owned()));
|
||||
return Err(vm.new_value_error("operation already attempted"));
|
||||
}
|
||||
|
||||
inner.handle = pipe as HANDLE;
|
||||
@@ -1243,7 +1243,7 @@ mod _overlapped {
|
||||
|
||||
let mut inner = zelf.inner.lock();
|
||||
if !matches!(inner.data, OverlappedData::None) {
|
||||
return Err(vm.new_value_error("operation already attempted".to_owned()));
|
||||
return Err(vm.new_value_error("operation already attempted"));
|
||||
}
|
||||
|
||||
let (addr_bytes, addr_len) = parse_address(&address, vm)?;
|
||||
@@ -1251,11 +1251,11 @@ mod _overlapped {
|
||||
inner.handle = handle as HANDLE;
|
||||
let buf_len = buf.desc.len;
|
||||
if buf_len > u32::MAX as usize {
|
||||
return Err(vm.new_value_error("buffer too large".to_owned()));
|
||||
return Err(vm.new_value_error("buffer too large"));
|
||||
}
|
||||
|
||||
let Some(contiguous) = buf.as_contiguous() else {
|
||||
return Err(vm.new_buffer_error("buffer is not contiguous".to_owned()));
|
||||
return Err(vm.new_buffer_error("buffer is not contiguous"));
|
||||
};
|
||||
|
||||
// Store both buffer and address in OverlappedData to keep them alive
|
||||
@@ -1322,7 +1322,7 @@ mod _overlapped {
|
||||
|
||||
let mut inner = zelf.inner.lock();
|
||||
if !matches!(inner.data, OverlappedData::None) {
|
||||
return Err(vm.new_value_error("operation already attempted".to_owned()));
|
||||
return Err(vm.new_value_error("operation already attempted"));
|
||||
}
|
||||
|
||||
let mut flags = flags.unwrap_or(0);
|
||||
@@ -1410,19 +1410,19 @@ mod _overlapped {
|
||||
|
||||
let mut inner = zelf.inner.lock();
|
||||
if !matches!(inner.data, OverlappedData::None) {
|
||||
return Err(vm.new_value_error("operation already attempted".to_owned()));
|
||||
return Err(vm.new_value_error("operation already attempted"));
|
||||
}
|
||||
|
||||
let mut flags = flags.unwrap_or(0);
|
||||
inner.handle = handle as HANDLE;
|
||||
|
||||
let Some(contiguous) = buf.as_contiguous_mut() else {
|
||||
return Err(vm.new_buffer_error("buffer is not contiguous".to_owned()));
|
||||
return Err(vm.new_buffer_error("buffer is not contiguous"));
|
||||
};
|
||||
|
||||
let buf_len = buf.desc.len;
|
||||
if buf_len > u32::MAX as usize {
|
||||
return Err(vm.new_value_error("buffer too large".to_owned()));
|
||||
return Err(vm.new_value_error("buffer too large"));
|
||||
}
|
||||
|
||||
let address: SOCKADDR_IN6 = unsafe { core::mem::zeroed() };
|
||||
@@ -1856,7 +1856,7 @@ mod _overlapped {
|
||||
)
|
||||
}
|
||||
} else {
|
||||
return Err(vm.new_value_error("expected tuple of length 2 or 4".to_owned()));
|
||||
return Err(vm.new_value_error("expected tuple of length 2 or 4"));
|
||||
};
|
||||
|
||||
if ret == SOCKET_ERROR {
|
||||
@@ -1944,7 +1944,7 @@ mod _overlapped {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<isize> {
|
||||
if !vm.is_none(&event_attributes) {
|
||||
return Err(vm.new_value_error("EventAttributes must be None".to_owned()));
|
||||
return Err(vm.new_value_error("EventAttributes must be None"));
|
||||
}
|
||||
|
||||
let name_wide: Option<Vec<u16>> =
|
||||
|
||||
+16
-23
@@ -1300,10 +1300,10 @@ mod _socket {
|
||||
|
||||
// salg_type is 14 bytes, salg_name is 64 bytes
|
||||
if type_str.len() >= 14 {
|
||||
return Err(vm.new_value_error("type too long".to_owned()).into());
|
||||
return Err(vm.new_value_error("type too long").into());
|
||||
}
|
||||
if name_str.len() >= 64 {
|
||||
return Err(vm.new_value_error("name too long".to_owned()).into());
|
||||
return Err(vm.new_value_error("name too long").into());
|
||||
}
|
||||
|
||||
// Create sockaddr_alg
|
||||
@@ -1627,9 +1627,9 @@ mod _socket {
|
||||
|
||||
// Handle nbytes parameter
|
||||
let read_len = if let OptionalArg::Present(nbytes) = nbytes {
|
||||
let nbytes = nbytes.to_usize().ok_or_else(|| {
|
||||
vm.new_value_error("negative buffersize in recv_into".to_owned())
|
||||
})?;
|
||||
let nbytes = nbytes
|
||||
.to_usize()
|
||||
.ok_or_else(|| vm.new_value_error("negative buffersize in recv_into"))?;
|
||||
nbytes.min(buf.len())
|
||||
} else {
|
||||
buf.len()
|
||||
@@ -1836,7 +1836,7 @@ mod _socket {
|
||||
// Validate assoclen - must be non-negative if provided
|
||||
let assoclen: Option<u32> = match args.assoclen {
|
||||
OptionalArg::Present(val) if val < 0 => {
|
||||
return Err(vm.new_type_error("assoclen must be non-negative".to_owned()));
|
||||
return Err(vm.new_type_error("assoclen must be non-negative"));
|
||||
}
|
||||
OptionalArg::Present(val) => Some(val as u32),
|
||||
OptionalArg::Missing => None,
|
||||
@@ -1955,15 +1955,13 @@ mod _socket {
|
||||
use core::mem::MaybeUninit;
|
||||
|
||||
if bufsize < 0 {
|
||||
return Err(vm.new_value_error("negative buffer size in recvmsg".to_owned()));
|
||||
return Err(vm.new_value_error("negative buffer size in recvmsg"));
|
||||
}
|
||||
let bufsize = bufsize as usize;
|
||||
|
||||
let ancbufsize = ancbufsize.unwrap_or(0);
|
||||
if ancbufsize < 0 {
|
||||
return Err(
|
||||
vm.new_value_error("negative ancillary buffer size in recvmsg".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("negative ancillary buffer size in recvmsg"));
|
||||
}
|
||||
let ancbufsize = ancbufsize as usize;
|
||||
let flags = flags.unwrap_or(0);
|
||||
@@ -2214,12 +2212,10 @@ mod _socket {
|
||||
Some(t) => {
|
||||
let f = t.into_float();
|
||||
if f.is_nan() {
|
||||
return Err(
|
||||
vm.new_value_error("Invalid value NaN (not a number)".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("Invalid value NaN (not a number)"));
|
||||
}
|
||||
if f < 0.0 || !f.is_finite() {
|
||||
return Err(vm.new_value_error("Timeout value out of range".to_owned()));
|
||||
return Err(vm.new_value_error("Timeout value out of range"));
|
||||
}
|
||||
Some(f)
|
||||
}
|
||||
@@ -2846,14 +2842,13 @@ mod _socket {
|
||||
.codec_registry
|
||||
.encode_text(s.to_owned(), "idna", None, vm)?;
|
||||
let host_str = core::str::from_utf8(encoded.as_bytes())
|
||||
.map_err(|_| vm.new_runtime_error("idna output is not utf8".to_owned()))?;
|
||||
.map_err(|_| vm.new_runtime_error("idna output is not utf8"))?;
|
||||
Some(host_str.to_owned())
|
||||
}
|
||||
Some(ArgStrOrBytesLike::Buf(b)) => {
|
||||
let bytes = b.borrow_buf();
|
||||
let host_str = core::str::from_utf8(&bytes).map_err(|_| {
|
||||
vm.new_unicode_decode_error("host bytes is not utf8".to_owned())
|
||||
})?;
|
||||
let host_str = core::str::from_utf8(&bytes)
|
||||
.map_err(|_| vm.new_unicode_decode_error("host bytes is not utf8"))?;
|
||||
Some(host_str.to_owned())
|
||||
}
|
||||
None => None,
|
||||
@@ -2874,9 +2869,7 @@ mod _socket {
|
||||
// For bytes, check if it's valid UTF-8
|
||||
let bytes = b.borrow_buf();
|
||||
core::str::from_utf8(&bytes)
|
||||
.map_err(|_| {
|
||||
vm.new_unicode_decode_error("port is not utf8".to_owned())
|
||||
})?
|
||||
.map_err(|_| vm.new_unicode_decode_error("port is not utf8"))?
|
||||
.to_owned()
|
||||
}
|
||||
};
|
||||
@@ -3396,10 +3389,10 @@ mod _socket {
|
||||
Some(t) => {
|
||||
let f = t.into_float();
|
||||
if f.is_nan() {
|
||||
return Err(vm.new_value_error("Invalid value NaN (not a number)".to_owned()));
|
||||
return Err(vm.new_value_error("Invalid value NaN (not a number)"));
|
||||
}
|
||||
if f < 0.0 || !f.is_finite() {
|
||||
return Err(vm.new_value_error("Timeout value out of range".to_owned()));
|
||||
return Err(vm.new_value_error("Timeout value out of range"));
|
||||
}
|
||||
f
|
||||
}
|
||||
|
||||
+13
-17
@@ -959,7 +959,7 @@ mod _ssl {
|
||||
fn set_options(&self, value: i32, vm: &VirtualMachine) -> PyResult<()> {
|
||||
// Validate that the value is non-negative
|
||||
if value < 0 {
|
||||
return Err(vm.new_value_error("options must be non-negative".to_owned()));
|
||||
return Err(vm.new_value_error("options must be non-negative"));
|
||||
}
|
||||
|
||||
// Deprecated SSL/TLS protocol version options
|
||||
@@ -1094,14 +1094,12 @@ mod _ssl {
|
||||
pwd_str.as_str().to_owned()
|
||||
} else if let Ok(pwd_bytes_like) = ArgBytesLike::try_from_object(vm, pwd_result) {
|
||||
String::from_utf8(pwd_bytes_like.borrow_buf().to_vec()).map_err(|_| {
|
||||
vm.new_type_error(
|
||||
"password callback returned invalid UTF-8 bytes".to_owned(),
|
||||
)
|
||||
vm.new_type_error("password callback returned invalid UTF-8 bytes")
|
||||
})?
|
||||
} else {
|
||||
return Err(vm.new_type_error(
|
||||
"password callback must return a string or bytes".to_owned(),
|
||||
));
|
||||
return Err(
|
||||
vm.new_type_error("password callback must return a string or bytes")
|
||||
);
|
||||
};
|
||||
|
||||
// Validate callable password length
|
||||
@@ -1244,9 +1242,7 @@ mod _ssl {
|
||||
let has_cadata = matches!(&args.cadata, OptionalArg::Present(Some(_)));
|
||||
|
||||
if !has_cafile && !has_capath && !has_cadata {
|
||||
return Err(
|
||||
vm.new_type_error("cafile, capath and cadata cannot be all omitted".to_owned())
|
||||
);
|
||||
return Err(vm.new_type_error("cafile, capath and cadata cannot be all omitted"));
|
||||
}
|
||||
|
||||
// Parse arguments BEFORE acquiring locks to reduce lock scope
|
||||
@@ -1745,7 +1741,7 @@ mod _ssl {
|
||||
fn load_dh_params(&self, filepath: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
// Validate filepath is not None
|
||||
if vm.is_none(&filepath) {
|
||||
return Err(vm.new_type_error("DH params filepath cannot be None".to_owned()));
|
||||
return Err(vm.new_type_error("DH params filepath cannot be None"));
|
||||
}
|
||||
|
||||
// Validate filepath is str or bytes
|
||||
@@ -1753,9 +1749,9 @@ mod _ssl {
|
||||
s.as_str().to_owned()
|
||||
} else if let Ok(b) = ArgBytesLike::try_from_object(vm, filepath) {
|
||||
String::from_utf8(b.borrow_buf().to_vec())
|
||||
.map_err(|_| vm.new_value_error("Invalid path encoding".to_owned()))?
|
||||
.map_err(|_| vm.new_value_error("Invalid path encoding"))?
|
||||
} else {
|
||||
return Err(vm.new_type_error("DH params filepath must be str or bytes".to_owned()));
|
||||
return Err(vm.new_type_error("DH params filepath must be str or bytes"));
|
||||
};
|
||||
|
||||
// Check if file exists
|
||||
@@ -1800,7 +1796,7 @@ mod _ssl {
|
||||
fn set_ecdh_curve(&self, name: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
// Validate name is not None
|
||||
if vm.is_none(&name) {
|
||||
return Err(vm.new_type_error("ECDH curve name cannot be None".to_owned()));
|
||||
return Err(vm.new_type_error("ECDH curve name cannot be None"));
|
||||
}
|
||||
|
||||
// Validate name is str or bytes
|
||||
@@ -1808,9 +1804,9 @@ mod _ssl {
|
||||
s.as_str().to_owned()
|
||||
} else if let Ok(b) = ArgBytesLike::try_from_object(vm, name) {
|
||||
String::from_utf8(b.borrow_buf().to_vec())
|
||||
.map_err(|_| vm.new_value_error("Invalid curve name encoding".to_owned()))?
|
||||
.map_err(|_| vm.new_value_error("Invalid curve name encoding"))?
|
||||
} else {
|
||||
return Err(vm.new_type_error("ECDH curve name must be str or bytes".to_owned()));
|
||||
return Err(vm.new_type_error("ECDH curve name must be str or bytes"));
|
||||
};
|
||||
|
||||
// Validate curve name (common curves for compatibility)
|
||||
@@ -2005,7 +2001,7 @@ mod _ssl {
|
||||
match arg {
|
||||
Either::A(s) => Ok(s.clone().try_into_utf8(vm)?.as_str().to_owned()),
|
||||
Either::B(b) => String::from_utf8(b.borrow_buf().to_vec())
|
||||
.map_err(|_| vm.new_value_error("path contains invalid UTF-8".to_owned())),
|
||||
.map_err(|_| vm.new_value_error("path contains invalid UTF-8")),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -541,7 +541,7 @@ impl PyByteArray {
|
||||
#[pymethod]
|
||||
fn resize(&self, size: isize, vm: &VirtualMachine) -> PyResult<()> {
|
||||
if size < 0 {
|
||||
return Err(vm.new_value_error("bytearray.resize(): new size must be >= 0".to_owned()));
|
||||
return Err(vm.new_value_error("bytearray.resize(): new size must be >= 0"));
|
||||
}
|
||||
self.try_resizable(vm)?.elements.resize(size as usize, 0);
|
||||
Ok(())
|
||||
|
||||
@@ -479,9 +479,9 @@ impl Constructor for PyCode {
|
||||
.names
|
||||
.iter()
|
||||
.map(|obj| {
|
||||
let s = obj.downcast_ref::<super::pystr::PyStr>().ok_or_else(|| {
|
||||
vm.new_type_error("names must be tuple of strings".to_owned())
|
||||
})?;
|
||||
let s = obj
|
||||
.downcast_ref::<super::pystr::PyStr>()
|
||||
.ok_or_else(|| vm.new_type_error("names must be tuple of strings"))?;
|
||||
Ok(vm.ctx.intern_str(s.as_wtf8()))
|
||||
})
|
||||
.collect::<PyResult<Vec<_>>>()?
|
||||
@@ -491,9 +491,9 @@ impl Constructor for PyCode {
|
||||
.varnames
|
||||
.iter()
|
||||
.map(|obj| {
|
||||
let s = obj.downcast_ref::<super::pystr::PyStr>().ok_or_else(|| {
|
||||
vm.new_type_error("varnames must be tuple of strings".to_owned())
|
||||
})?;
|
||||
let s = obj
|
||||
.downcast_ref::<super::pystr::PyStr>()
|
||||
.ok_or_else(|| vm.new_type_error("varnames must be tuple of strings"))?;
|
||||
Ok(vm.ctx.intern_str(s.as_wtf8()))
|
||||
})
|
||||
.collect::<PyResult<Vec<_>>>()?
|
||||
@@ -503,9 +503,9 @@ impl Constructor for PyCode {
|
||||
.cellvars
|
||||
.iter()
|
||||
.map(|obj| {
|
||||
let s = obj.downcast_ref::<super::pystr::PyStr>().ok_or_else(|| {
|
||||
vm.new_type_error("cellvars must be tuple of strings".to_owned())
|
||||
})?;
|
||||
let s = obj
|
||||
.downcast_ref::<super::pystr::PyStr>()
|
||||
.ok_or_else(|| vm.new_type_error("cellvars must be tuple of strings"))?;
|
||||
Ok(vm.ctx.intern_str(s.as_wtf8()))
|
||||
})
|
||||
.collect::<PyResult<Vec<_>>>()?
|
||||
@@ -515,9 +515,9 @@ impl Constructor for PyCode {
|
||||
.freevars
|
||||
.iter()
|
||||
.map(|obj| {
|
||||
let s = obj.downcast_ref::<super::pystr::PyStr>().ok_or_else(|| {
|
||||
vm.new_type_error("freevars must be tuple of strings".to_owned())
|
||||
})?;
|
||||
let s = obj
|
||||
.downcast_ref::<super::pystr::PyStr>()
|
||||
.ok_or_else(|| vm.new_type_error("freevars must be tuple of strings"))?;
|
||||
Ok(vm.ctx.intern_str(s.as_wtf8()))
|
||||
})
|
||||
.collect::<PyResult<Vec<_>>>()?
|
||||
|
||||
@@ -418,7 +418,7 @@ impl AsNumber for PyComplex {
|
||||
let result = value.norm();
|
||||
// Check for overflow: hypot returns inf for finite inputs that overflow
|
||||
if result.is_infinite() && value.re.is_finite() && value.im.is_finite() {
|
||||
return Err(vm.new_overflow_error("absolute value too large".to_owned()));
|
||||
return Err(vm.new_overflow_error("absolute value too large"));
|
||||
}
|
||||
result.to_pyresult(vm)
|
||||
}),
|
||||
|
||||
@@ -372,7 +372,7 @@ fn set_slot_at_object(
|
||||
obj.set_slot(offset, Some(v))
|
||||
}
|
||||
PySetterValue::Delete => {
|
||||
return Err(vm.new_type_error("can't delete numeric/char attribute".to_owned()));
|
||||
return Err(vm.new_type_error("can't delete numeric/char attribute"));
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -592,9 +592,7 @@ impl SlotFunc {
|
||||
}
|
||||
SlotFunc::Hash(func) => {
|
||||
if !args.args.is_empty() || !args.kwargs.is_empty() {
|
||||
return Err(
|
||||
vm.new_type_error("__hash__() takes no arguments (1 given)".to_owned())
|
||||
);
|
||||
return Err(vm.new_type_error("__hash__() takes no arguments (1 given)"));
|
||||
}
|
||||
let hash = func(&obj, vm)?;
|
||||
Ok(vm.ctx.new_int(hash).into())
|
||||
@@ -613,26 +611,20 @@ impl SlotFunc {
|
||||
}
|
||||
SlotFunc::Iter(func) => {
|
||||
if !args.args.is_empty() || !args.kwargs.is_empty() {
|
||||
return Err(
|
||||
vm.new_type_error("__iter__() takes no arguments (1 given)".to_owned())
|
||||
);
|
||||
return Err(vm.new_type_error("__iter__() takes no arguments (1 given)"));
|
||||
}
|
||||
func(obj, vm)
|
||||
}
|
||||
SlotFunc::IterNext(func) => {
|
||||
if !args.args.is_empty() || !args.kwargs.is_empty() {
|
||||
return Err(
|
||||
vm.new_type_error("__next__() takes no arguments (1 given)".to_owned())
|
||||
);
|
||||
return Err(vm.new_type_error("__next__() takes no arguments (1 given)"));
|
||||
}
|
||||
func(&obj, vm).to_pyresult(vm)
|
||||
}
|
||||
SlotFunc::Call(func) => func(&obj, args, vm),
|
||||
SlotFunc::Del(func) => {
|
||||
if !args.args.is_empty() || !args.kwargs.is_empty() {
|
||||
return Err(
|
||||
vm.new_type_error("__del__() takes no arguments (1 given)".to_owned())
|
||||
);
|
||||
return Err(vm.new_type_error("__del__() takes no arguments (1 given)"));
|
||||
}
|
||||
func(&obj, vm)?;
|
||||
Ok(vm.ctx.none())
|
||||
|
||||
@@ -488,13 +488,13 @@ impl Frame {
|
||||
PySetterValue::Assign(val) => {
|
||||
let line_ref: PyIntRef = val
|
||||
.downcast()
|
||||
.map_err(|_| vm.new_value_error("lineno must be an integer".to_owned()))?;
|
||||
.map_err(|_| vm.new_value_error("lineno must be an integer"))?;
|
||||
line_ref
|
||||
.try_to_primitive::<i32>(vm)
|
||||
.map_err(|_| vm.new_value_error("lineno must be an integer".to_owned()))?
|
||||
.map_err(|_| vm.new_value_error("lineno must be an integer"))?
|
||||
}
|
||||
PySetterValue::Delete => {
|
||||
return Err(vm.new_type_error("can't delete f_lineno attribute".to_owned()));
|
||||
return Err(vm.new_type_error("can't delete f_lineno attribute"));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -677,12 +677,12 @@ impl Py<Frame> {
|
||||
// FRAME_SUSPENDED). lasti == 0 means FRAME_CREATED and
|
||||
// can be cleared.
|
||||
if self.lasti() != 0 {
|
||||
return Err(vm.new_runtime_error("cannot clear a suspended frame".to_owned()));
|
||||
return Err(vm.new_runtime_error("cannot clear a suspended frame"));
|
||||
}
|
||||
}
|
||||
FrameOwner::Thread => {
|
||||
// Thread-owned frame: always executing, cannot clear.
|
||||
return Err(vm.new_runtime_error("cannot clear an executing frame".to_owned()));
|
||||
return Err(vm.new_runtime_error("cannot clear an executing frame"));
|
||||
}
|
||||
FrameOwner::FrameObject => {
|
||||
// Detached frame: safe to clear.
|
||||
|
||||
@@ -518,7 +518,7 @@ impl PyFunction {
|
||||
} else if attr == bytecode::MakeFunctionFlags::ANNOTATE {
|
||||
// PEP 649: Store the __annotate__ function closure
|
||||
if !attr_value.is_callable() {
|
||||
return Err(vm.new_type_error("__annotate__ must be callable".to_owned()));
|
||||
return Err(vm.new_type_error("__annotate__ must be callable"));
|
||||
}
|
||||
*self.annotate.lock() = Some(attr_value);
|
||||
} else {
|
||||
|
||||
@@ -155,10 +155,11 @@ impl PyGenericAlias {
|
||||
let mut parts = Vec::with_capacity(len);
|
||||
// Use indexed access so list mutation during repr causes IndexError
|
||||
for i in 0..len {
|
||||
let item =
|
||||
list.borrow_vec().get(i).cloned().ok_or_else(|| {
|
||||
vm.new_index_error("list index out of range".to_owned())
|
||||
})?;
|
||||
let item = list
|
||||
.borrow_vec()
|
||||
.get(i)
|
||||
.cloned()
|
||||
.ok_or_else(|| vm.new_index_error("list index out of range"))?;
|
||||
parts.push(repr_item(item, vm)?);
|
||||
}
|
||||
Ok(format!("[{}]", parts.join(", ")))
|
||||
@@ -712,9 +713,9 @@ impl crate::types::IterNext for PyGenericAliasIterator {
|
||||
None => return Ok(PyIterReturn::StopIteration(None)),
|
||||
};
|
||||
// Create a starred GenericAlias from the original
|
||||
let alias = obj.downcast_ref::<PyGenericAlias>().ok_or_else(|| {
|
||||
vm.new_type_error("generic_alias_iterator expected GenericAlias".to_owned())
|
||||
})?;
|
||||
let alias = obj
|
||||
.downcast_ref::<PyGenericAlias>()
|
||||
.ok_or_else(|| vm.new_type_error("generic_alias_iterator expected GenericAlias"))?;
|
||||
let starred = PyGenericAlias::new(alias.origin.clone(), alias.args.clone(), true, vm);
|
||||
Ok(PyIterReturn::Return(starred.into_pyobject(vm)))
|
||||
}
|
||||
|
||||
@@ -700,7 +700,7 @@ impl PyMemoryView {
|
||||
self.try_not_released(vm)?;
|
||||
if self.desc.ndim() == 0 {
|
||||
// 0-dimensional memoryview has no length
|
||||
Err(vm.new_type_error("0-dim memory has no length".to_owned()))
|
||||
Err(vm.new_type_error("0-dim memory has no length"))
|
||||
} else {
|
||||
// shape for dim[0]
|
||||
Ok(self.desc.dim_desc[0].0)
|
||||
|
||||
@@ -408,7 +408,7 @@ impl PyModule {
|
||||
}
|
||||
PySetterValue::Delete => {
|
||||
if dict.del_item(identifier!(vm, __annotations__), vm).is_err() {
|
||||
return Err(vm.new_attribute_error("__annotations__".to_owned()));
|
||||
return Err(vm.new_attribute_error("__annotations__"));
|
||||
}
|
||||
// Also clear __annotate__
|
||||
dict.del_item(identifier!(vm, __annotate__), vm).ok();
|
||||
|
||||
@@ -43,8 +43,7 @@ impl Constructor for PyBaseObject {
|
||||
// Type has its own __new__, so object.__new__ is being called
|
||||
// with excess args. This is the first error case in CPython
|
||||
return Err(vm.new_type_error(
|
||||
"object.__new__() takes exactly one argument (the type to instantiate)"
|
||||
.to_owned(),
|
||||
"object.__new__() takes exactly one argument (the type to instantiate)",
|
||||
));
|
||||
}
|
||||
|
||||
@@ -136,8 +135,7 @@ impl Initializer for PyBaseObject {
|
||||
// if (type->tp_init != object_init) → first error
|
||||
if typ_init != object_init {
|
||||
return Err(vm.new_type_error(
|
||||
"object.__init__() takes exactly one argument (the instance to initialize)"
|
||||
.to_owned(),
|
||||
"object.__init__() takes exactly one argument (the instance to initialize)",
|
||||
));
|
||||
}
|
||||
|
||||
@@ -250,9 +248,7 @@ fn object_getstate_default(obj: &PyObject, required: bool, vm: &VirtualMachine)
|
||||
let borrowed_names = slot_names.borrow_vec();
|
||||
// Check if slotnames changed during iteration
|
||||
if borrowed_names.len() != slot_names_len {
|
||||
return Err(vm.new_runtime_error(
|
||||
"__slotnames__ changed size during iteration".to_owned(),
|
||||
));
|
||||
return Err(vm.new_runtime_error("__slotnames__ changed size during iteration"));
|
||||
}
|
||||
let name = borrowed_names[i].downcast_ref::<PyStr>().unwrap();
|
||||
let Ok(value) = obj.get_attr(name, vm) else {
|
||||
@@ -718,7 +714,7 @@ fn reduce_newobj(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
} else {
|
||||
// args == NULL with non-empty kwargs is BadInternalCall
|
||||
let Some(args) = args else {
|
||||
return Err(vm.new_system_error("bad internal call".to_owned()));
|
||||
return Err(vm.new_system_error("bad internal call"));
|
||||
};
|
||||
// Use copyreg.__newobj_ex__
|
||||
let newobj = copyreg.get_attr("__newobj_ex__", vm)?;
|
||||
|
||||
@@ -154,9 +154,7 @@ impl PyProperty {
|
||||
fn name_getter(&self, vm: &VirtualMachine) -> PyResult {
|
||||
match self.get_property_name(vm)? {
|
||||
Some(name) => Ok(name),
|
||||
None => Err(
|
||||
vm.new_attribute_error("'property' object has no attribute '__name__'".to_owned())
|
||||
),
|
||||
None => Err(vm.new_attribute_error("'property' object has no attribute '__name__'")),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -110,9 +110,7 @@ impl AsNumber for PyNotImplemented {
|
||||
fn as_number() -> &'static PyNumberMethods {
|
||||
static AS_NUMBER: PyNumberMethods = PyNumberMethods {
|
||||
boolean: Some(|_number, vm| {
|
||||
Err(vm.new_type_error(
|
||||
"NotImplemented should not be used in a boolean context".to_owned(),
|
||||
))
|
||||
Err(vm.new_type_error("NotImplemented should not be used in a boolean context"))
|
||||
}),
|
||||
..PyNumberMethods::NOT_IMPLEMENTED
|
||||
};
|
||||
|
||||
@@ -81,14 +81,14 @@ impl PyTraceback {
|
||||
let value = match value {
|
||||
PySetterValue::Assign(v) => v,
|
||||
PySetterValue::Delete => {
|
||||
return Err(vm.new_type_error("can't delete tb_next attribute".to_owned()));
|
||||
return Err(vm.new_type_error("can't delete tb_next attribute"));
|
||||
}
|
||||
};
|
||||
if let Some(ref new_next) = value {
|
||||
let mut cursor = new_next.clone();
|
||||
loop {
|
||||
if cursor.is(zelf) {
|
||||
return Err(vm.new_value_error("traceback loop detected".to_owned()));
|
||||
return Err(vm.new_value_error("traceback loop detected"));
|
||||
}
|
||||
let next = cursor.next.lock().clone();
|
||||
match next {
|
||||
@@ -107,8 +107,8 @@ impl Constructor for PyTraceback {
|
||||
|
||||
fn py_new(_cls: &Py<PyType>, args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
let (next, frame, lasti, lineno) = args;
|
||||
let lineno = OneIndexed::new(lineno)
|
||||
.ok_or_else(|| vm.new_value_error("lineno must be positive".to_owned()))?;
|
||||
let lineno =
|
||||
OneIndexed::new(lineno).ok_or_else(|| vm.new_value_error("lineno must be positive"))?;
|
||||
Ok(Self::new(next, frame, lasti, lineno))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1275,7 +1275,7 @@ impl PyType {
|
||||
fn set___annotate__(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let value = match value {
|
||||
PySetterValue::Delete => {
|
||||
return Err(vm.new_type_error("cannot delete __annotate__ attribute".to_owned()));
|
||||
return Err(vm.new_type_error("cannot delete __annotate__ attribute"));
|
||||
}
|
||||
PySetterValue::Assign(v) => v,
|
||||
};
|
||||
@@ -1288,7 +1288,7 @@ impl PyType {
|
||||
}
|
||||
|
||||
if !vm.is_none(&value) && !value.is_callable() {
|
||||
return Err(vm.new_type_error("__annotate__ must be callable or None".to_owned()));
|
||||
return Err(vm.new_type_error("__annotate__ must be callable or None"));
|
||||
}
|
||||
|
||||
let mut attrs = self.attributes.write();
|
||||
@@ -1405,7 +1405,7 @@ impl PyType {
|
||||
.is_some()
|
||||
};
|
||||
if !removed {
|
||||
return Err(vm.new_attribute_error("__annotations__".to_owned()));
|
||||
return Err(vm.new_attribute_error("__annotations__"));
|
||||
}
|
||||
if has_annotations {
|
||||
attrs.swap_remove(identifier!(vm, __annotations_cache__));
|
||||
@@ -1902,9 +1902,9 @@ impl Constructor for PyType {
|
||||
let class_name = typ.name().to_string();
|
||||
for member in slots.as_slice() {
|
||||
// Apply name mangling for private attributes (__x -> _ClassName__x)
|
||||
let member_str = member.to_str().ok_or_else(|| {
|
||||
vm.new_type_error("__slots__ must be valid UTF-8 strings".to_owned())
|
||||
})?;
|
||||
let member_str = member
|
||||
.to_str()
|
||||
.ok_or_else(|| vm.new_type_error("__slots__ must be valid UTF-8 strings"))?;
|
||||
let mangled_name = mangle_name(&class_name, member_str);
|
||||
let member_def = PyMemberDef {
|
||||
name: mangled_name.clone(),
|
||||
@@ -2082,10 +2082,10 @@ impl Initializer for PyType {
|
||||
fn slot_init(_zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
|
||||
// type.__init__() takes 1 or 3 arguments
|
||||
if args.args.len() == 1 && !args.kwargs.is_empty() {
|
||||
return Err(vm.new_type_error("type.__init__() takes no keyword arguments".to_owned()));
|
||||
return Err(vm.new_type_error("type.__init__() takes no keyword arguments"));
|
||||
}
|
||||
if args.args.len() != 1 && args.args.len() != 3 {
|
||||
return Err(vm.new_type_error("type.__init__() takes 1 or 3 arguments".to_owned()));
|
||||
return Err(vm.new_type_error("type.__init__() takes 1 or 3 arguments"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -2299,7 +2299,7 @@ impl Callable for PyType {
|
||||
return Ok(args.args[0].obj_type());
|
||||
}
|
||||
if num_args != 3 {
|
||||
return Err(vm.new_type_error("type() takes 1 or 3 arguments".to_owned()));
|
||||
return Err(vm.new_type_error("type() takes 1 or 3 arguments"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -45,9 +45,9 @@ impl Constructor for PyWeak {
|
||||
// PyArg_UnpackTuple: only process positional args, ignore kwargs.
|
||||
// Subclass __init__ will handle extra kwargs.
|
||||
let mut positional = args.args.into_iter();
|
||||
let referent = positional.next().ok_or_else(|| {
|
||||
vm.new_type_error("__new__ expected at least 1 argument, got 0".to_owned())
|
||||
})?;
|
||||
let referent = positional
|
||||
.next()
|
||||
.ok_or_else(|| vm.new_type_error("__new__ expected at least 1 argument, got 0"))?;
|
||||
let callback = positional.next();
|
||||
if let Some(_extra) = positional.next() {
|
||||
return Err(vm.new_type_error(format!(
|
||||
|
||||
@@ -461,7 +461,7 @@ impl PyBytesInner {
|
||||
|
||||
match invalid_char {
|
||||
None => Err(vm.new_value_error(
|
||||
"fromhex() arg must contain an even number of hexadecimal digits".to_owned(),
|
||||
"fromhex() arg must contain an even number of hexadecimal digits",
|
||||
)),
|
||||
Some(i) => Err(vm.new_value_error(format!(
|
||||
"non-hexadecimal number found in fromhex() arg at position {i}"
|
||||
@@ -474,9 +474,9 @@ impl PyBytesInner {
|
||||
if let Some(s) = string.downcast_ref::<PyStr>() {
|
||||
Self::fromhex(s.as_bytes(), vm)
|
||||
} else if let Ok(buffer) = PyBuffer::try_from_borrowed_object(vm, &string) {
|
||||
let borrowed = buffer.as_contiguous().ok_or_else(|| {
|
||||
vm.new_buffer_error("fromhex() requires a contiguous buffer".to_owned())
|
||||
})?;
|
||||
let borrowed = buffer
|
||||
.as_contiguous()
|
||||
.ok_or_else(|| vm.new_buffer_error("fromhex() requires a contiguous buffer"))?;
|
||||
Self::fromhex(&borrowed, vm)
|
||||
} else {
|
||||
Err(vm.new_type_error(format!(
|
||||
|
||||
@@ -127,15 +127,13 @@ impl TryFromObject for core::time::Duration {
|
||||
if let Some(float) = obj.downcast_ref::<PyFloat>() {
|
||||
let f = float.to_f64();
|
||||
if f.is_nan() {
|
||||
return Err(vm.new_value_error("Invalid value NaN (not a number)".to_owned()));
|
||||
return Err(vm.new_value_error("Invalid value NaN (not a number)"));
|
||||
}
|
||||
if f < 0.0 {
|
||||
return Err(vm.new_value_error("negative duration".to_owned()));
|
||||
return Err(vm.new_value_error("negative duration"));
|
||||
}
|
||||
if !f.is_finite() || f > u64::MAX as f64 {
|
||||
return Err(vm.new_overflow_error(
|
||||
"timestamp too large to convert to C PyTime_t".to_owned(),
|
||||
));
|
||||
return Err(vm.new_overflow_error("timestamp too large to convert to C PyTime_t"));
|
||||
}
|
||||
// Convert float to Duration using floor rounding (_PyTime_ROUND_FLOOR)
|
||||
let secs = f.trunc() as u64;
|
||||
|
||||
@@ -192,14 +192,10 @@ impl Coro {
|
||||
// Validate throw arguments (matching CPython _gen_throw)
|
||||
if exc_type.fast_isinstance(vm.ctx.exceptions.base_exception_type) && !vm.is_none(&exc_val)
|
||||
{
|
||||
return Err(
|
||||
vm.new_type_error("instance exception may not have a separate value".to_owned())
|
||||
);
|
||||
return Err(vm.new_type_error("instance exception may not have a separate value"));
|
||||
}
|
||||
if !vm.is_none(&exc_tb) && !exc_tb.fast_isinstance(vm.ctx.types.traceback_type) {
|
||||
return Err(
|
||||
vm.new_type_error("throw() third argument must be a traceback object".to_owned())
|
||||
);
|
||||
return Err(vm.new_type_error("throw() third argument must be a traceback object"));
|
||||
}
|
||||
if self.closed.load() {
|
||||
return Err(vm.normalize_exception(exc_type, exc_val, exc_tb)?);
|
||||
@@ -322,7 +318,7 @@ pub fn get_awaitable_iter(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
.contains(crate::bytecode::CodeFlags::ITERABLE_COROUTINE)
|
||||
})
|
||||
{
|
||||
return Err(vm.new_type_error("__await__() returned a coroutine".to_owned()));
|
||||
return Err(vm.new_type_error("__await__() returned a coroutine"));
|
||||
}
|
||||
if !PyIter::check(&result) {
|
||||
return Err(vm.new_type_error(format!(
|
||||
|
||||
@@ -276,9 +276,9 @@ pub(super) mod types {
|
||||
|
||||
// Validate non-empty
|
||||
if exceptions.is_empty() {
|
||||
return Err(vm.new_value_error(
|
||||
"second argument (exceptions) must be a non-empty sequence".to_owned(),
|
||||
));
|
||||
return Err(
|
||||
vm.new_value_error("second argument (exceptions) must be a non-empty sequence")
|
||||
);
|
||||
}
|
||||
|
||||
// Validate all items are BaseException instances
|
||||
|
||||
@@ -2171,7 +2171,7 @@ pub(super) mod types {
|
||||
fn characters_written(&self, vm: &VirtualMachine) -> PyResult<isize> {
|
||||
let written = self.written.load();
|
||||
if written == -1 {
|
||||
Err(vm.new_attribute_error("characters_written".to_owned()))
|
||||
Err(vm.new_attribute_error("characters_written"))
|
||||
} else {
|
||||
Ok(written)
|
||||
}
|
||||
@@ -2187,7 +2187,7 @@ pub(super) mod types {
|
||||
None => {
|
||||
// Deleting the attribute
|
||||
if self.written.load() == -1 {
|
||||
Err(vm.new_attribute_error("characters_written".to_owned()))
|
||||
Err(vm.new_attribute_error("characters_written"))
|
||||
} else {
|
||||
self.written.store(-1);
|
||||
Ok(())
|
||||
@@ -2198,9 +2198,7 @@ pub(super) mod types {
|
||||
.try_index(vm)?
|
||||
.try_to_primitive::<isize>(vm)
|
||||
.map_err(|_| {
|
||||
vm.new_value_error(
|
||||
"cannot convert characters_written value to isize".to_owned(),
|
||||
)
|
||||
vm.new_value_error("cannot convert characters_written value to isize")
|
||||
})?;
|
||||
self.written.store(n);
|
||||
Ok(())
|
||||
@@ -2714,14 +2712,13 @@ fn check_except_star_type_valid(match_type: &PyObjectRef, vm: &VirtualMachine) -
|
||||
// Must be a subclass of BaseException
|
||||
if !exc_type.is_subclass(&base_exc, vm)? {
|
||||
return Err(vm.new_type_error(
|
||||
"catching classes that do not inherit from BaseException is not allowed".to_owned(),
|
||||
"catching classes that do not inherit from BaseException is not allowed",
|
||||
));
|
||||
}
|
||||
// Must not be a subclass of BaseExceptionGroup
|
||||
if exc_type.is_subclass(&base_eg, vm)? {
|
||||
return Err(vm.new_type_error(
|
||||
"catching ExceptionGroup with except* is not allowed. Use except instead."
|
||||
.to_owned(),
|
||||
"catching ExceptionGroup with except* is not allowed. Use except instead.",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
|
||||
+14
-22
@@ -2135,9 +2135,7 @@ impl ExecutingFrame<'_> {
|
||||
if let Some(coro) = iter.downcast_ref::<PyCoroutine>()
|
||||
&& coro.as_coro().frame().yield_from_target().is_some()
|
||||
{
|
||||
return Err(
|
||||
vm.new_runtime_error("coroutine is being awaited already".to_owned())
|
||||
);
|
||||
return Err(vm.new_runtime_error("coroutine is being awaited already"));
|
||||
}
|
||||
|
||||
self.push_value(iter);
|
||||
@@ -2161,8 +2159,7 @@ impl ExecutingFrame<'_> {
|
||||
bytecode::CodeFlags::COROUTINE | bytecode::CodeFlags::ITERABLE_COROUTINE,
|
||||
) {
|
||||
return Err(vm.new_type_error(
|
||||
"cannot 'yield from' a coroutine object in a non-coroutine generator"
|
||||
.to_owned(),
|
||||
"cannot 'yield from' a coroutine object in a non-coroutine generator",
|
||||
));
|
||||
}
|
||||
iterable
|
||||
@@ -2276,7 +2273,7 @@ impl ExecutingFrame<'_> {
|
||||
.get_item_opt(identifier!(vm, __build_class__), vm)?
|
||||
.ok_or_else(|| {
|
||||
vm.new_name_error(
|
||||
"__build_class__ not found".to_owned(),
|
||||
"__build_class__ not found",
|
||||
identifier!(vm, __build_class__).to_owned(),
|
||||
)
|
||||
})?
|
||||
@@ -2286,7 +2283,7 @@ impl ExecutingFrame<'_> {
|
||||
.map_err(|e| {
|
||||
if e.fast_isinstance(vm.ctx.exceptions.key_error) {
|
||||
vm.new_name_error(
|
||||
"__build_class__ not found".to_owned(),
|
||||
"__build_class__ not found",
|
||||
identifier!(vm, __build_class__).to_owned(),
|
||||
)
|
||||
} else {
|
||||
@@ -2647,7 +2644,7 @@ impl ExecutingFrame<'_> {
|
||||
Some(s) => s,
|
||||
None => {
|
||||
return Err(vm.new_type_error(
|
||||
"__match_args__ elements must be strings".to_string(),
|
||||
"__match_args__ elements must be strings",
|
||||
));
|
||||
}
|
||||
};
|
||||
@@ -2678,16 +2675,14 @@ impl ExecutingFrame<'_> {
|
||||
} else if nargs_val > 1 {
|
||||
// Too many positional arguments for MATCH_SELF
|
||||
return Err(vm.new_type_error(
|
||||
"class pattern accepts at most 1 positional sub-pattern for MATCH_SELF types"
|
||||
.to_string(),
|
||||
"class pattern accepts at most 1 positional sub-pattern for MATCH_SELF types",
|
||||
));
|
||||
}
|
||||
} else {
|
||||
// No __match_args__ and not a MATCH_SELF type
|
||||
if nargs_val > 0 {
|
||||
return Err(vm.new_type_error(
|
||||
"class pattern defines no positional sub-patterns (__match_args__ missing)"
|
||||
.to_string(),
|
||||
"class pattern defines no positional sub-patterns (__match_args__ missing)",
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -3300,7 +3295,7 @@ impl ExecutingFrame<'_> {
|
||||
|
||||
let exc = exc
|
||||
.downcast::<PyBaseException>()
|
||||
.map_err(|_| vm.new_type_error("exception expected".to_owned()))?;
|
||||
.map_err(|_| vm.new_type_error("exception expected"))?;
|
||||
Err(exc)
|
||||
}
|
||||
Instruction::UnaryInvert => {
|
||||
@@ -4621,9 +4616,7 @@ impl ExecutingFrame<'_> {
|
||||
|
||||
// EXIT_INIT_CHECK: __init__ must return None
|
||||
if !vm.is_none(&init_result) {
|
||||
return Err(
|
||||
vm.new_type_error("__init__() should return None".to_owned())
|
||||
);
|
||||
return Err(vm.new_type_error("__init__() should return None"));
|
||||
}
|
||||
|
||||
self.push_value(new_obj);
|
||||
@@ -6498,9 +6491,8 @@ impl ExecutingFrame<'_> {
|
||||
bytecode::RaiseKind::BareRaise => {
|
||||
// RAISE_VARARGS 0: bare `raise` gets exception from VM state
|
||||
// This is the current exception set by PUSH_EXC_INFO
|
||||
vm.topmost_exception().ok_or_else(|| {
|
||||
vm.new_runtime_error("No active exception to reraise".to_owned())
|
||||
})?
|
||||
vm.topmost_exception()
|
||||
.ok_or_else(|| vm.new_runtime_error("No active exception to reraise"))?
|
||||
}
|
||||
bytecode::RaiseKind::ReraiseFromStack => {
|
||||
// RERAISE: gets exception from stack top
|
||||
@@ -8823,9 +8815,9 @@ impl ExecutingFrame<'_> {
|
||||
.map_err(|_| vm.new_type_error("Type params must be a tuple."))?
|
||||
};
|
||||
|
||||
let name = name.downcast::<crate::builtins::PyStr>().map_err(|_| {
|
||||
vm.new_type_error("TypeAliasType name must be a string".to_owned())
|
||||
})?;
|
||||
let name = name
|
||||
.downcast::<crate::builtins::PyStr>()
|
||||
.map_err(|_| vm.new_type_error("TypeAliasType name must be a string"))?;
|
||||
let type_alias = typing::TypeAliasType::new(name, type_params, compute_value);
|
||||
Ok(type_alias.into_ref(&vm.ctx).into())
|
||||
}
|
||||
|
||||
@@ -374,7 +374,7 @@ pub(crate) fn import_module_level(
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult {
|
||||
if level < 0 {
|
||||
return Err(vm.new_value_error("level must be >= 0".to_owned()));
|
||||
return Err(vm.new_value_error("level must be >= 0"));
|
||||
}
|
||||
|
||||
let name_str = match name.to_str() {
|
||||
@@ -411,14 +411,14 @@ pub(crate) fn import_module_level(
|
||||
let package = calc_package(Some(globals_ref), vm)?;
|
||||
if package.is_empty() {
|
||||
return Err(vm.new_import_error(
|
||||
"attempted relative import with no known parent package".to_owned(),
|
||||
"attempted relative import with no known parent package",
|
||||
vm.ctx.new_utf8_str(""),
|
||||
));
|
||||
}
|
||||
resolve_name(name_str, &package, level as usize, vm)?
|
||||
} else {
|
||||
if name_str.is_empty() {
|
||||
return Err(vm.new_value_error("Empty module name".to_owned()));
|
||||
return Err(vm.new_value_error("Empty module name"));
|
||||
}
|
||||
name_str.to_owned()
|
||||
};
|
||||
@@ -500,7 +500,7 @@ fn resolve_name(name: &str, package: &str, level: usize, vm: &VirtualMachine) ->
|
||||
let parts: Vec<&str> = package.rsplitn(level, '.').collect();
|
||||
if parts.len() < level {
|
||||
return Err(vm.new_import_error(
|
||||
"attempted relative import beyond top-level package".to_owned(),
|
||||
"attempted relative import beyond top-level package",
|
||||
vm.ctx.new_utf8_str(name),
|
||||
));
|
||||
}
|
||||
@@ -517,7 +517,7 @@ fn resolve_name(name: &str, package: &str, level: usize, vm: &VirtualMachine) ->
|
||||
fn calc_package(globals: Option<&PyObjectRef>, vm: &VirtualMachine) -> PyResult<String> {
|
||||
let globals = globals.ok_or_else(|| {
|
||||
vm.new_import_error(
|
||||
"attempted relative import with no known parent package".to_owned(),
|
||||
"attempted relative import with no known parent package",
|
||||
vm.ctx.new_utf8_str(""),
|
||||
)
|
||||
})?;
|
||||
@@ -531,7 +531,7 @@ fn calc_package(globals: Option<&PyObjectRef>, vm: &VirtualMachine) -> PyResult<
|
||||
let pkg_str: PyUtf8StrRef = pkg
|
||||
.clone()
|
||||
.downcast()
|
||||
.map_err(|_| vm.new_type_error("package must be a string".to_owned()))?;
|
||||
.map_err(|_| vm.new_type_error("package must be a string"))?;
|
||||
// Warn if __package__ != __spec__.parent
|
||||
if let Some(ref spec) = spec
|
||||
&& !vm.is_none(spec)
|
||||
@@ -572,7 +572,7 @@ fn calc_package(globals: Option<&PyObjectRef>, vm: &VirtualMachine) -> PyResult<
|
||||
{
|
||||
let parent_str: PyUtf8StrRef = parent
|
||||
.downcast()
|
||||
.map_err(|_| vm.new_type_error("package set to non-string".to_owned()))?;
|
||||
.map_err(|_| vm.new_type_error("package set to non-string"))?;
|
||||
return Ok(parent_str.as_str().to_owned());
|
||||
}
|
||||
|
||||
@@ -592,13 +592,13 @@ fn calc_package(globals: Option<&PyObjectRef>, vm: &VirtualMachine) -> PyResult<
|
||||
|
||||
let mod_name = globals.get_item("__name__", vm).map_err(|_| {
|
||||
vm.new_import_error(
|
||||
"attempted relative import with no known parent package".to_owned(),
|
||||
"attempted relative import with no known parent package",
|
||||
vm.ctx.new_utf8_str(""),
|
||||
)
|
||||
})?;
|
||||
let mod_name_str: PyUtf8StrRef = mod_name
|
||||
.downcast()
|
||||
.map_err(|_| vm.new_type_error("__name__ must be a string".to_owned()))?;
|
||||
.map_err(|_| vm.new_type_error("__name__ must be a string"))?;
|
||||
let mut package = mod_name_str.as_str().to_owned();
|
||||
// If not a package (no __path__), strip last component.
|
||||
// Uses rpartition('.')[0] semantics: returns empty string when no dot.
|
||||
|
||||
@@ -77,7 +77,7 @@ mod _abc {
|
||||
let impl_obj = cls.get_attr("_abc_impl", vm)?;
|
||||
impl_obj
|
||||
.downcast::<AbcData>()
|
||||
.map_err(|_| vm.new_type_error("_abc_impl is set to a wrong type".to_owned()))
|
||||
.map_err(|_| vm.new_type_error("_abc_impl is set to a wrong type"))
|
||||
}
|
||||
|
||||
/// Check if obj is in the weak set
|
||||
@@ -152,12 +152,10 @@ mod _abc {
|
||||
while let PyIterReturn::Return(item) = iter.next(vm)? {
|
||||
let tuple: PyTupleRef = item
|
||||
.downcast()
|
||||
.map_err(|_| vm.new_type_error("items() returned non-tuple".to_owned()))?;
|
||||
.map_err(|_| vm.new_type_error("items() returned non-tuple"))?;
|
||||
let elements = tuple.as_slice();
|
||||
if elements.len() != 2 {
|
||||
return Err(
|
||||
vm.new_type_error("items() returned item which size is not 2".to_owned())
|
||||
);
|
||||
return Err(vm.new_type_error("items() returned item which size is not 2"));
|
||||
}
|
||||
let key = &elements[0];
|
||||
let value = &elements[1];
|
||||
@@ -174,7 +172,7 @@ mod _abc {
|
||||
let bases: PyTupleRef = cls
|
||||
.get_attr("__bases__", vm)?
|
||||
.downcast()
|
||||
.map_err(|_| vm.new_type_error("__bases__ is not a tuple".to_owned()))?;
|
||||
.map_err(|_| vm.new_type_error("__bases__ is not a tuple"))?;
|
||||
|
||||
for base in bases.iter() {
|
||||
if let Ok(base_abstracts) = base.get_attr("__abstractmethods__", vm) {
|
||||
@@ -220,7 +218,7 @@ mod _abc {
|
||||
) -> PyResult<PyObjectRef> {
|
||||
// Type check
|
||||
if !subclass.class().fast_issubclass(vm.ctx.types.type_type) {
|
||||
return Err(vm.new_type_error("Can only register classes".to_owned()));
|
||||
return Err(vm.new_type_error("Can only register classes"));
|
||||
}
|
||||
|
||||
// Check if already a subclass
|
||||
@@ -230,7 +228,7 @@ mod _abc {
|
||||
|
||||
// Check for cycles
|
||||
if cls.is_subclass(&subclass, vm)? {
|
||||
return Err(vm.new_runtime_error("Refusing to create an inheritance cycle".to_owned()));
|
||||
return Err(vm.new_runtime_error("Refusing to create an inheritance cycle"));
|
||||
}
|
||||
|
||||
// Add to registry
|
||||
@@ -328,7 +326,7 @@ mod _abc {
|
||||
) -> PyResult<bool> {
|
||||
// Type check
|
||||
if !subclass.class().fast_issubclass(vm.ctx.types.type_type) {
|
||||
return Err(vm.new_type_error("issubclass() arg 1 must be a class".to_owned()));
|
||||
return Err(vm.new_type_error("issubclass() arg 1 must be a class"));
|
||||
}
|
||||
|
||||
let impl_data = get_impl(&cls, vm)?;
|
||||
@@ -373,11 +371,11 @@ mod _abc {
|
||||
let subclass_type: PyTypeRef = subclass
|
||||
.clone()
|
||||
.downcast()
|
||||
.map_err(|_| vm.new_type_error("expected a type object".to_owned()))?;
|
||||
.map_err(|_| vm.new_type_error("expected a type object"))?;
|
||||
let cls_type: PyTypeRef = cls
|
||||
.clone()
|
||||
.downcast()
|
||||
.map_err(|_| vm.new_type_error("expected a type object".to_owned()))?;
|
||||
.map_err(|_| vm.new_type_error("expected a type object"))?;
|
||||
if subclass_type.fast_issubclass(&cls_type) {
|
||||
add_to_weak_set(&impl_data.cache, &subclass, vm)?;
|
||||
return Ok(true);
|
||||
@@ -392,7 +390,7 @@ mod _abc {
|
||||
let subclasses: PyRef<PyList> = vm
|
||||
.call_method(&cls, "__subclasses__", ())?
|
||||
.downcast()
|
||||
.map_err(|_| vm.new_type_error("__subclasses__() must return a list".to_owned()))?;
|
||||
.map_err(|_| vm.new_type_error("__subclasses__() must return a list"))?;
|
||||
|
||||
for scls in subclasses.borrow_vec().iter() {
|
||||
if subclass.is_subclass(scls, vm)? {
|
||||
|
||||
@@ -538,7 +538,7 @@ mod _winapi {
|
||||
let ms = if ms < 0 {
|
||||
windows_sys::Win32::System::Threading::INFINITE
|
||||
} else if ms > u32::MAX as i64 {
|
||||
return Err(vm.new_overflow_error("timeout value is too large".to_owned()));
|
||||
return Err(vm.new_overflow_error("timeout value is too large"));
|
||||
} else {
|
||||
ms as u32
|
||||
};
|
||||
@@ -567,13 +567,11 @@ mod _winapi {
|
||||
.collect();
|
||||
|
||||
if handles.is_empty() {
|
||||
return Err(vm.new_value_error("handle_seq must not be empty".to_owned()));
|
||||
return Err(vm.new_value_error("handle_seq must not be empty"));
|
||||
}
|
||||
|
||||
if handles.len() > 64 {
|
||||
return Err(
|
||||
vm.new_value_error("WaitForMultipleObjects supports at most 64 handles".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("WaitForMultipleObjects supports at most 64 handles"));
|
||||
}
|
||||
|
||||
let ret = unsafe {
|
||||
@@ -693,7 +691,7 @@ mod _winapi {
|
||||
let src_wide = src.as_wtf8().to_wide();
|
||||
|
||||
if src_wide.len() > i32::MAX as usize {
|
||||
return Err(vm.new_overflow_error("input string is too long".to_string()));
|
||||
return Err(vm.new_overflow_error("input string is too long"));
|
||||
}
|
||||
|
||||
// First call to get required buffer size
|
||||
@@ -901,8 +899,7 @@ mod _winapi {
|
||||
let inner = self.inner.lock();
|
||||
if !inner.completed {
|
||||
return Err(vm.new_value_error(
|
||||
"can't get read buffer before GetOverlappedResult() signals the operation completed"
|
||||
.to_owned(),
|
||||
"can't get read buffer before GetOverlappedResult() signals the operation completed",
|
||||
));
|
||||
}
|
||||
Ok(inner
|
||||
@@ -1100,7 +1097,7 @@ mod _winapi {
|
||||
let size = size.unwrap_or(0);
|
||||
|
||||
if size < 0 {
|
||||
return Err(vm.new_value_error("negative size".to_string()));
|
||||
return Err(vm.new_value_error("negative size"));
|
||||
}
|
||||
|
||||
let mut navail: u32 = 0;
|
||||
@@ -1808,9 +1805,9 @@ mod _winapi {
|
||||
if let Some(ref n) = name
|
||||
&& n.as_bytes().contains(&0)
|
||||
{
|
||||
return Err(vm.new_value_error(
|
||||
"CreateFileMapping: name must not contain null characters".to_owned(),
|
||||
));
|
||||
return Err(
|
||||
vm.new_value_error("CreateFileMapping: name must not contain null characters")
|
||||
);
|
||||
}
|
||||
let name_wide = name.as_ref().map(|n| n.as_wtf8().to_wide_with_nul());
|
||||
let name_ptr = name_wide.as_ref().map_or(null(), |n| n.as_ptr());
|
||||
@@ -1843,9 +1840,9 @@ mod _winapi {
|
||||
use windows_sys::Win32::System::Memory::OpenFileMappingW;
|
||||
|
||||
if name.as_bytes().contains(&0) {
|
||||
return Err(vm.new_value_error(
|
||||
"OpenFileMapping: name must not contain null characters".to_owned(),
|
||||
));
|
||||
return Err(
|
||||
vm.new_value_error("OpenFileMapping: name must not contain null characters")
|
||||
);
|
||||
}
|
||||
let name_wide = name.as_wtf8().to_wide_with_nul();
|
||||
let handle = unsafe {
|
||||
|
||||
@@ -567,7 +567,7 @@ mod _wmi {
|
||||
.get(..7)
|
||||
.is_some_and(|s| s.eq_ignore_ascii_case("select "))
|
||||
{
|
||||
return Err(vm.new_value_error("only SELECT queries are supported".to_owned()));
|
||||
return Err(vm.new_value_error("only SELECT queries are supported"));
|
||||
}
|
||||
|
||||
let query_wide = wide_str(query_str);
|
||||
|
||||
@@ -398,7 +398,7 @@ pub(crate) fn parse(
|
||||
#[cfg(feature = "parser")]
|
||||
pub(crate) fn wrap_interactive(vm: &VirtualMachine, module_obj: PyObjectRef) -> PyResult {
|
||||
if !module_obj.class().is(pyast::NodeModModule::static_type()) {
|
||||
return Err(vm.new_type_error("expected Module node".to_owned()));
|
||||
return Err(vm.new_type_error("expected Module node"));
|
||||
}
|
||||
let body = get_node_field(vm, &module_obj, "body", "Module")?;
|
||||
let node = NodeAst
|
||||
|
||||
@@ -463,9 +463,7 @@ impl Node for ast::ExprDict {
|
||||
get_node_field(vm, &object, "values", "Dict")?,
|
||||
)?;
|
||||
if keys.len() != values.len() {
|
||||
return Err(vm.new_value_error(
|
||||
"Dict doesn't have the same number of keys as values".to_owned(),
|
||||
));
|
||||
return Err(vm.new_value_error("Dict doesn't have the same number of keys as values"));
|
||||
}
|
||||
let items = keys
|
||||
.into_iter()
|
||||
|
||||
@@ -365,9 +365,7 @@ impl Node for ast::PatternMatchClass {
|
||||
get_node_field(vm, &object, "kwd_patterns", "MatchClass")?,
|
||||
)?;
|
||||
if kwd_attrs.0.len() != kwd_patterns.0.len() {
|
||||
return Err(vm.new_value_error(
|
||||
"MatchClass has mismatched kwd_attrs and kwd_patterns".to_owned(),
|
||||
));
|
||||
return Err(vm.new_value_error("MatchClass has mismatched kwd_attrs and kwd_patterns"));
|
||||
}
|
||||
let (patterns, keywords) = merge_pattern_match_class(patterns, kwd_attrs, kwd_patterns);
|
||||
|
||||
|
||||
@@ -118,7 +118,7 @@ pub(crate) mod _ast {
|
||||
|
||||
pub(crate) fn ast_replace(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
if !args.args.is_empty() {
|
||||
return Err(vm.new_type_error("__replace__() takes no positional arguments".to_owned()));
|
||||
return Err(vm.new_type_error("__replace__() takes no positional arguments"));
|
||||
}
|
||||
|
||||
let cls = zelf.class();
|
||||
@@ -225,7 +225,7 @@ pub(crate) mod _ast {
|
||||
.map(|(key, value)| {
|
||||
let key = key
|
||||
.downcast::<PyUtf8Str>()
|
||||
.map_err(|_| vm.new_type_error("keywords must be strings".to_owned()))?;
|
||||
.map_err(|_| vm.new_type_error("keywords must be strings"))?;
|
||||
Ok((key.as_str().to_owned(), value))
|
||||
})
|
||||
.collect::<PyResult<IndexMap<String, PyObjectRef>>>()?;
|
||||
@@ -450,7 +450,7 @@ Support for arbitrary keyword arguments is deprecated and will be removed in Pyt
|
||||
let ast_type = module
|
||||
.get_attr("AST", vm)?
|
||||
.downcast::<PyType>()
|
||||
.map_err(|_| vm.new_type_error("AST is not a type".to_owned()))?;
|
||||
.map_err(|_| vm.new_type_error("AST is not a type"))?;
|
||||
let ctx = &vm.ctx;
|
||||
let empty_tuple = ctx.empty_tuple.clone();
|
||||
ast_type.set_str_attr("_fields", empty_tuple.clone(), ctx);
|
||||
|
||||
@@ -1112,11 +1112,10 @@ impl Node for ast::StmtImportFrom {
|
||||
let int: PyRef<PyInt> = obj.try_into_value(vm)?;
|
||||
let value: i64 = int.try_to_primitive(vm)?;
|
||||
if value < 0 {
|
||||
return Err(vm.new_value_error("Negative ImportFrom level".to_owned()));
|
||||
return Err(vm.new_value_error("Negative ImportFrom level"));
|
||||
}
|
||||
u32::try_from(value).map_err(|_| {
|
||||
vm.new_overflow_error("ImportFrom level out of range".to_owned())
|
||||
})
|
||||
u32::try_from(value)
|
||||
.map_err(|_| vm.new_overflow_error("ImportFrom level out of range"))
|
||||
})
|
||||
.transpose()?
|
||||
.unwrap_or(0),
|
||||
|
||||
@@ -754,9 +754,7 @@ fn template_part_to_element(
|
||||
match part {
|
||||
TemplateStrPart::Constant(constant) => {
|
||||
let ConstantLiteral::Str { value, .. } = constant.value else {
|
||||
return Err(
|
||||
vm.new_type_error("TemplateStr constant values must be strings".to_owned())
|
||||
);
|
||||
return Err(vm.new_type_error("TemplateStr constant values must be strings"));
|
||||
};
|
||||
Ok(ast::InterpolatedStringElement::Literal(
|
||||
ast::InterpolatedStringLiteralElement {
|
||||
|
||||
@@ -25,7 +25,7 @@ fn validate_name(vm: &VirtualMachine, name: &ast::name::Name) -> PyResult<()> {
|
||||
|
||||
fn validate_comprehension(vm: &VirtualMachine, gens: &[ast::Comprehension]) -> PyResult<()> {
|
||||
if gens.is_empty() {
|
||||
return Err(vm.new_value_error("comprehension with no generators".to_owned()));
|
||||
return Err(vm.new_value_error("comprehension with no generators"));
|
||||
}
|
||||
for comp in gens {
|
||||
validate_expr(vm, &comp.target, ast::ExprContext::Store)?;
|
||||
@@ -133,31 +133,25 @@ fn validate_pattern_match_value(vm: &VirtualMachine, expr: &ast::Expr) -> PyResu
|
||||
ast::Expr::Attribute(_) => Ok(()),
|
||||
ast::Expr::UnaryOp(op) => match &*op.operand {
|
||||
ast::Expr::NumberLiteral(_) => Ok(()),
|
||||
_ => Err(vm.new_value_error(
|
||||
"patterns may only match literals and attribute lookups".to_owned(),
|
||||
)),
|
||||
_ => Err(vm.new_value_error("patterns may only match literals and attribute lookups")),
|
||||
},
|
||||
ast::Expr::BinOp(bin) => match (&*bin.left, &*bin.right) {
|
||||
(ast::Expr::NumberLiteral(_), ast::Expr::NumberLiteral(_)) => Ok(()),
|
||||
_ => Err(vm.new_value_error(
|
||||
"patterns may only match literals and attribute lookups".to_owned(),
|
||||
)),
|
||||
_ => Err(vm.new_value_error("patterns may only match literals and attribute lookups")),
|
||||
},
|
||||
ast::Expr::FString(_) | ast::Expr::TString(_) => Ok(()),
|
||||
ast::Expr::BooleanLiteral(_)
|
||||
| ast::Expr::NoneLiteral(_)
|
||||
| ast::Expr::EllipsisLiteral(_) => {
|
||||
Err(vm.new_value_error("unexpected constant inside of a literal pattern".to_owned()))
|
||||
Err(vm.new_value_error("unexpected constant inside of a literal pattern"))
|
||||
}
|
||||
_ => Err(
|
||||
vm.new_value_error("patterns may only match literals and attribute lookups".to_owned())
|
||||
),
|
||||
_ => Err(vm.new_value_error("patterns may only match literals and attribute lookups")),
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_capture(vm: &VirtualMachine, name: &ast::Identifier) -> PyResult<()> {
|
||||
if name.as_str() == "_" {
|
||||
return Err(vm.new_value_error("can't capture name '_' in patterns".to_owned()));
|
||||
return Err(vm.new_value_error("can't capture name '_' in patterns"));
|
||||
}
|
||||
validate_name(vm, name.id())
|
||||
}
|
||||
@@ -172,7 +166,7 @@ fn validate_pattern(vm: &VirtualMachine, pattern: &ast::Pattern, star_ok: bool)
|
||||
ast::Pattern::MatchMapping(mapping) => {
|
||||
if mapping.keys.len() != mapping.patterns.len() {
|
||||
return Err(vm.new_value_error(
|
||||
"MatchMapping doesn't have the same number of keys as patterns".to_owned(),
|
||||
"MatchMapping doesn't have the same number of keys as patterns",
|
||||
));
|
||||
}
|
||||
if let Some(rest) = &mapping.rest {
|
||||
@@ -197,8 +191,7 @@ fn validate_pattern(vm: &VirtualMachine, pattern: &ast::Pattern, star_ok: bool)
|
||||
}
|
||||
_ => {
|
||||
return Err(vm.new_value_error(
|
||||
"MatchClass cls field can only contain Name or Attribute nodes."
|
||||
.to_owned(),
|
||||
"MatchClass cls field can only contain Name or Attribute nodes.",
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -214,7 +207,7 @@ fn validate_pattern(vm: &VirtualMachine, pattern: &ast::Pattern, star_ok: bool)
|
||||
}
|
||||
ast::Pattern::MatchStar(star) => {
|
||||
if !star_ok {
|
||||
return Err(vm.new_value_error("can't use MatchStar here".to_owned()));
|
||||
return Err(vm.new_value_error("can't use MatchStar here"));
|
||||
}
|
||||
if let Some(name) = &star.name {
|
||||
validate_capture(vm, name)?;
|
||||
@@ -230,7 +223,7 @@ fn validate_pattern(vm: &VirtualMachine, pattern: &ast::Pattern, star_ok: bool)
|
||||
Some(pattern) => {
|
||||
if match_as.name.is_none() {
|
||||
return Err(vm.new_value_error(
|
||||
"MatchAs must specify a target name if a pattern is given".to_owned(),
|
||||
"MatchAs must specify a target name if a pattern is given",
|
||||
));
|
||||
}
|
||||
validate_pattern(vm, pattern, false)
|
||||
@@ -239,7 +232,7 @@ fn validate_pattern(vm: &VirtualMachine, pattern: &ast::Pattern, star_ok: bool)
|
||||
}
|
||||
ast::Pattern::MatchOr(match_or) => {
|
||||
if match_or.patterns.len() < 2 {
|
||||
return Err(vm.new_value_error("MatchOr requires at least 2 patterns".to_owned()));
|
||||
return Err(vm.new_value_error("MatchOr requires at least 2 patterns"));
|
||||
}
|
||||
validate_patterns(vm, &match_or.patterns, false)
|
||||
}
|
||||
@@ -342,13 +335,13 @@ fn validate_expr(vm: &VirtualMachine, expr: &ast::Expr, ctx: ast::ExprContext) -
|
||||
match expr {
|
||||
ast::Expr::BoolOp(op) => {
|
||||
if op.values.len() < 2 {
|
||||
return Err(vm.new_value_error("BoolOp with less than 2 values".to_owned()));
|
||||
return Err(vm.new_value_error("BoolOp with less than 2 values"));
|
||||
}
|
||||
validate_exprs(vm, &op.values, ast::ExprContext::Load, false)
|
||||
}
|
||||
ast::Expr::Named(named) => {
|
||||
if !matches!(&*named.target, ast::Expr::Name(_)) {
|
||||
return Err(vm.new_type_error("NamedExpr target must be a Name".to_owned()));
|
||||
return Err(vm.new_type_error("NamedExpr target must be a Name"));
|
||||
}
|
||||
validate_expr(vm, &named.value, ast::ExprContext::Load)
|
||||
}
|
||||
@@ -409,11 +402,11 @@ fn validate_expr(vm: &VirtualMachine, expr: &ast::Expr, ctx: ast::ExprContext) -
|
||||
}
|
||||
ast::Expr::Compare(compare) => {
|
||||
if compare.comparators.is_empty() {
|
||||
return Err(vm.new_value_error("Compare with no comparators".to_owned()));
|
||||
return Err(vm.new_value_error("Compare with no comparators"));
|
||||
}
|
||||
if compare.comparators.len() != compare.ops.len() {
|
||||
return Err(vm.new_value_error(
|
||||
"Compare has a different number of comparators and operands".to_owned(),
|
||||
"Compare has a different number of comparators and operands",
|
||||
));
|
||||
}
|
||||
validate_exprs(vm, &compare.comparators, ast::ExprContext::Load, false)?;
|
||||
@@ -519,7 +512,7 @@ fn validate_stmt(vm: &VirtualMachine, stmt: &ast::Stmt) -> PyResult<()> {
|
||||
}
|
||||
ast::Stmt::AnnAssign(assign) => {
|
||||
if assign.simple && !matches!(&*assign.target, ast::Expr::Name(_)) {
|
||||
return Err(vm.new_type_error("AnnAssign with simple non-Name target".to_owned()));
|
||||
return Err(vm.new_type_error("AnnAssign with simple non-Name target"));
|
||||
}
|
||||
validate_expr(vm, &assign.target, ast::ExprContext::Store)?;
|
||||
if let Some(value) = &assign.value {
|
||||
@@ -529,7 +522,7 @@ fn validate_stmt(vm: &VirtualMachine, stmt: &ast::Stmt) -> PyResult<()> {
|
||||
}
|
||||
ast::Stmt::TypeAlias(alias) => {
|
||||
if !matches!(&*alias.name, ast::Expr::Name(_)) {
|
||||
return Err(vm.new_type_error("TypeAlias with non-Name name".to_owned()));
|
||||
return Err(vm.new_type_error("TypeAlias with non-Name name"));
|
||||
}
|
||||
validate_expr(vm, &alias.name, ast::ExprContext::Store)?;
|
||||
validate_type_params(vm, &alias.type_params)?;
|
||||
@@ -592,7 +585,7 @@ fn validate_stmt(vm: &VirtualMachine, stmt: &ast::Stmt) -> PyResult<()> {
|
||||
validate_expr(vm, cause, ast::ExprContext::Load)?;
|
||||
}
|
||||
} else if raise.cause.is_some() {
|
||||
return Err(vm.new_value_error("Raise with cause but no exception".to_owned()));
|
||||
return Err(vm.new_value_error("Raise with cause but no exception"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -285,7 +285,7 @@ mod builtins {
|
||||
// func_type mode requires PyCF_ONLY_AST
|
||||
if mode_str == "func_type" && !is_ast_only {
|
||||
return Err(vm.new_value_error(
|
||||
"compile() mode 'func_type' requires flag PyCF_ONLY_AST".to_owned(),
|
||||
"compile() mode 'func_type' requires flag PyCF_ONLY_AST",
|
||||
));
|
||||
}
|
||||
|
||||
@@ -294,8 +294,7 @@ mod builtins {
|
||||
let (expected_type, expected_name) = ast::mode_type_and_name(mode_str)
|
||||
.ok_or_else(|| {
|
||||
vm.new_value_error(
|
||||
"compile() mode must be 'exec', 'eval', 'single' or 'func_type'"
|
||||
.to_owned(),
|
||||
"compile() mode must be 'exec', 'eval', 'single' or 'func_type'",
|
||||
)
|
||||
})?;
|
||||
if !args.source.fast_isinstance(&expected_type) {
|
||||
@@ -500,7 +499,7 @@ mod builtins {
|
||||
"exec() globals must be a dict, not {}",
|
||||
globals.class().name()
|
||||
)),
|
||||
_ => vm.new_type_error("globals must be a dict".to_owned()),
|
||||
_ => vm.new_type_error("globals must be a dict"),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -96,7 +96,7 @@ mod _codecs {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<()> {
|
||||
if !handler.is_callable() {
|
||||
return Err(vm.new_type_error("handler must be callable".to_owned()));
|
||||
return Err(vm.new_type_error("handler must be callable"));
|
||||
}
|
||||
vm.state
|
||||
.codec_registry
|
||||
@@ -398,7 +398,7 @@ mod _codecs_windows {
|
||||
None => {
|
||||
// String contains surrogates - not encodable with mbcs
|
||||
return Err(vm.new_unicode_encode_error(
|
||||
"'mbcs' codec can't encode character: surrogates not allowed".to_string(),
|
||||
"'mbcs' codec can't encode character: surrogates not allowed",
|
||||
));
|
||||
}
|
||||
};
|
||||
@@ -584,7 +584,7 @@ mod _codecs_windows {
|
||||
None => {
|
||||
// String contains surrogates - not encodable with oem
|
||||
return Err(vm.new_unicode_encode_error(
|
||||
"'oem' codec can't encode character: surrogates not allowed".to_string(),
|
||||
"'oem' codec can't encode character: surrogates not allowed",
|
||||
));
|
||||
}
|
||||
};
|
||||
@@ -1052,7 +1052,7 @@ mod _codecs_windows {
|
||||
use crate::common::windows::ToWideString;
|
||||
|
||||
if args.code_page < 0 {
|
||||
return Err(vm.new_value_error("invalid code page number".to_owned()));
|
||||
return Err(vm.new_value_error("invalid code page number"));
|
||||
}
|
||||
let errors = args.errors.as_ref().map(|s| s.as_str()).unwrap_or("strict");
|
||||
let code_page = args.code_page as u32;
|
||||
@@ -1365,7 +1365,7 @@ mod _codecs_windows {
|
||||
use crate::common::wtf8::Wtf8Buf;
|
||||
|
||||
if args.code_page < 0 {
|
||||
return Err(vm.new_value_error("invalid code page number".to_owned()));
|
||||
return Err(vm.new_value_error("invalid code page number"));
|
||||
}
|
||||
let errors = args.errors.as_ref().map(|s| s.as_str()).unwrap_or("strict");
|
||||
let code_page = args.code_page as u32;
|
||||
|
||||
@@ -930,7 +930,7 @@ pub(crate) mod _ctypes {
|
||||
let buffer = cdata.buffer.read();
|
||||
if matches!(&*buffer, Cow::Borrowed(_)) {
|
||||
return Err(vm.new_value_error(
|
||||
"Memory cannot be resized because this object doesn't own it".to_owned(),
|
||||
"Memory cannot be resized because this object doesn't own it",
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -798,9 +798,9 @@ impl PyCArray {
|
||||
} else if let Ok(int_val) = value.try_index(vm) {
|
||||
(int_val.as_bigint().to_usize().unwrap_or(0), None)
|
||||
} else {
|
||||
return Err(vm.new_type_error(
|
||||
"bytes or integer address expected instead of {}".to_owned(),
|
||||
));
|
||||
return Err(
|
||||
vm.new_type_error("bytes or integer address expected instead of {}")
|
||||
);
|
||||
};
|
||||
if offset + element_size <= buffer.len() {
|
||||
buffer[offset..offset + element_size].copy_from_slice(&ptr_val.to_ne_bytes());
|
||||
|
||||
@@ -1433,8 +1433,7 @@ impl Constructor for PyCField {
|
||||
|
||||
if !internal_use {
|
||||
return Err(vm.new_type_error(
|
||||
"CField is not intended to be used directly; use it via Structure or Union fields"
|
||||
.to_string(),
|
||||
"CField is not intended to be used directly; use it via Structure or Union fields",
|
||||
));
|
||||
}
|
||||
|
||||
@@ -1493,11 +1492,11 @@ impl Constructor for PyCField {
|
||||
|
||||
if let Some(bs) = bit_size_val {
|
||||
if bs < 0 {
|
||||
return Err(vm.new_value_error("number of bits invalid for bit field".to_string()));
|
||||
return Err(vm.new_value_error("number of bits invalid for bit field"));
|
||||
}
|
||||
let bo = bit_offset_val.unwrap_or(0);
|
||||
if bo < 0 {
|
||||
return Err(vm.new_value_error("bit_offset must be >= 0".to_string()));
|
||||
return Err(vm.new_value_error("bit_offset must be >= 0"));
|
||||
}
|
||||
let type_bits = byte_size * 8;
|
||||
if bo + bs > type_bits {
|
||||
|
||||
@@ -232,7 +232,7 @@ fn convert_to_pointer(value: &PyObject, vm: &VirtualMachine) -> PyResult<FfiArgV
|
||||
return Ok(FfiArgValue::Pointer(unsigned_val));
|
||||
}
|
||||
// Value out of range - raise OverflowError
|
||||
return Err(vm.new_overflow_error("int too large to convert to pointer".to_string()));
|
||||
return Err(vm.new_overflow_error("int too large to convert to pointer"));
|
||||
}
|
||||
|
||||
// 8. Check _as_parameter_ attribute ( recursive ConvParam)
|
||||
@@ -1308,9 +1308,7 @@ fn resolve_com_method(
|
||||
|
||||
// First arg must be the COM object pointer
|
||||
if args.args.is_empty() {
|
||||
return Err(
|
||||
vm.new_type_error("COM method requires at least one argument (self)".to_string())
|
||||
);
|
||||
return Err(vm.new_type_error("COM method requires at least one argument (self)"));
|
||||
}
|
||||
|
||||
// Extract COM pointer value from first argument
|
||||
@@ -1325,9 +1323,7 @@ fn resolve_com_method(
|
||||
} else if let Ok(int_val) = self_arg.try_int(vm) {
|
||||
int_val.as_bigint().to_usize().unwrap_or(0)
|
||||
} else {
|
||||
return Err(
|
||||
vm.new_type_error("COM method first argument must be a COM pointer".to_string())
|
||||
);
|
||||
return Err(vm.new_type_error("COM method first argument must be a COM pointer"));
|
||||
};
|
||||
|
||||
if com_ptr == 0 {
|
||||
@@ -1467,9 +1463,8 @@ fn build_callargs_with_paramflags(
|
||||
if is_out && !is_in {
|
||||
// Pure OUT parameter: create buffer, don't consume caller arg
|
||||
let buffer = create_out_buffer(arg_type, vm)?;
|
||||
let addr = get_buffer_addr(&buffer).ok_or_else(|| {
|
||||
vm.new_type_error("Cannot create OUT buffer for this type".to_string())
|
||||
})?;
|
||||
let addr = get_buffer_addr(&buffer)
|
||||
.ok_or_else(|| vm.new_type_error("Cannot create OUT buffer for this type"))?;
|
||||
arguments.push(Argument {
|
||||
ffi_type,
|
||||
keep: None,
|
||||
|
||||
@@ -733,9 +733,7 @@ impl PyCPointer {
|
||||
} else if let Ok(int_val) = value.try_index(vm) {
|
||||
int_val.as_bigint().to_usize().unwrap_or(0)
|
||||
} else {
|
||||
return Err(vm.new_type_error(
|
||||
"bytes/string or integer address expected".to_owned(),
|
||||
));
|
||||
return Err(vm.new_type_error("bytes/string or integer address expected"));
|
||||
};
|
||||
core::ptr::write_unaligned(ptr as *mut usize, ptr_val);
|
||||
return Ok(());
|
||||
|
||||
@@ -324,9 +324,7 @@ impl PyCSimpleType {
|
||||
{
|
||||
return create_simple_with_value("c", &value);
|
||||
}
|
||||
return Err(vm.new_type_error(
|
||||
"one character bytes, bytearray or integer expected".to_string(),
|
||||
));
|
||||
return Err(vm.new_type_error("one character bytes, bytearray or integer expected"));
|
||||
}
|
||||
// c_wchar: 1 unicode character
|
||||
Some("u") => {
|
||||
@@ -559,8 +557,7 @@ impl Initializer for PyCSimpleType {
|
||||
// Validate _type_ is a single character
|
||||
if type_str.len() != 1 {
|
||||
return Err(vm.new_value_error(
|
||||
"class must define a '_type_' attribute which must be a string of length 1"
|
||||
.to_owned(),
|
||||
"class must define a '_type_' attribute which must be a string of length 1",
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
@@ -310,9 +310,9 @@ impl PyCStructType {
|
||||
.ok_or_else(|| vm.new_type_error("_fields_ must contain tuples"))?;
|
||||
|
||||
if field_tuple.len() < 2 {
|
||||
return Err(vm.new_type_error(
|
||||
"_fields_ tuple must have at least 2 elements (name, type)".to_string(),
|
||||
));
|
||||
return Err(
|
||||
vm.new_type_error("_fields_ tuple must have at least 2 elements (name, type)")
|
||||
);
|
||||
}
|
||||
|
||||
let name = field_tuple
|
||||
@@ -428,9 +428,7 @@ impl PyCStructType {
|
||||
.try_int(vm)?
|
||||
.as_bigint()
|
||||
.to_u16()
|
||||
.ok_or_else(|| {
|
||||
vm.new_value_error("number of bits invalid for bit field".to_string())
|
||||
})?;
|
||||
.ok_or_else(|| vm.new_value_error("number of bits invalid for bit field"))?;
|
||||
has_bitfield = true;
|
||||
|
||||
let type_bits = (size * 8) as u16;
|
||||
@@ -534,9 +532,7 @@ impl PyCStructType {
|
||||
if let Some(stg_info) = cls.get_type_data::<StgInfo>()
|
||||
&& stg_info.is_final()
|
||||
{
|
||||
return Err(
|
||||
vm.new_attribute_error("Structure or union cannot contain itself".to_string())
|
||||
);
|
||||
return Err(vm.new_attribute_error("Structure or union cannot contain itself"));
|
||||
}
|
||||
|
||||
// Store StgInfo with aligned size and total alignment
|
||||
|
||||
@@ -209,9 +209,9 @@ impl PyCUnionType {
|
||||
.ok_or_else(|| vm.new_type_error("_fields_ must contain tuples"))?;
|
||||
|
||||
if field_tuple.len() < 2 {
|
||||
return Err(vm.new_type_error(
|
||||
"_fields_ tuple must have at least 2 elements (name, type)".to_string(),
|
||||
));
|
||||
return Err(
|
||||
vm.new_type_error("_fields_ tuple must have at least 2 elements (name, type)")
|
||||
);
|
||||
}
|
||||
|
||||
let name = field_tuple
|
||||
@@ -286,9 +286,7 @@ impl PyCUnionType {
|
||||
.try_int(vm)?
|
||||
.as_bigint()
|
||||
.to_u16()
|
||||
.ok_or_else(|| {
|
||||
vm.new_value_error("number of bits invalid for bit field".to_string())
|
||||
})?;
|
||||
.ok_or_else(|| vm.new_value_error("number of bits invalid for bit field"))?;
|
||||
has_bitfield = true;
|
||||
|
||||
// Union fields all start at offset 0, so bit_offset = 0
|
||||
@@ -329,9 +327,7 @@ impl PyCUnionType {
|
||||
if let Some(stg_info) = cls.get_type_data::<StgInfo>()
|
||||
&& stg_info.is_final()
|
||||
{
|
||||
return Err(
|
||||
vm.new_attribute_error("Structure or union cannot contain itself".to_string())
|
||||
);
|
||||
return Err(vm.new_attribute_error("Structure or union cannot contain itself"));
|
||||
}
|
||||
|
||||
// Store StgInfo with aligned size
|
||||
|
||||
@@ -79,7 +79,7 @@ mod _functools {
|
||||
|
||||
fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
if !args.args.is_empty() || !args.kwargs.is_empty() {
|
||||
return Err(vm.new_type_error("_PlaceholderType takes no arguments".to_owned()));
|
||||
return Err(vm.new_type_error("_PlaceholderType takes no arguments"));
|
||||
}
|
||||
// Return the singleton stored on the type class
|
||||
if let Some(instance) = cls.get_attr(vm.ctx.intern_str("_instance")) {
|
||||
@@ -104,7 +104,7 @@ mod _functools {
|
||||
|
||||
#[pymethod]
|
||||
fn __init_subclass__(_cls: PyTypeRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
Err(vm.new_type_error("cannot subclass '_PlaceholderType'".to_owned()))
|
||||
Err(vm.new_type_error("cannot subclass '_PlaceholderType'"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,7 +245,7 @@ mod _functools {
|
||||
// Validate no trailing placeholders
|
||||
let args_slice = args_tuple.as_slice();
|
||||
if !args_slice.is_empty() && is_placeholder(args_slice.last().unwrap()) {
|
||||
return Err(vm.new_type_error("trailing Placeholders are not allowed".to_owned()));
|
||||
return Err(vm.new_type_error("trailing Placeholders are not allowed"));
|
||||
}
|
||||
let phcount = count_placeholders(args_slice);
|
||||
|
||||
@@ -354,7 +354,7 @@ mod _functools {
|
||||
|
||||
// Trailing placeholders are not allowed
|
||||
if !final_args.is_empty() && is_placeholder(final_args.last().unwrap()) {
|
||||
return Err(vm.new_type_error("trailing Placeholders are not allowed".to_owned()));
|
||||
return Err(vm.new_type_error("trailing Placeholders are not allowed"));
|
||||
}
|
||||
|
||||
let phcount = count_placeholders(&final_args);
|
||||
|
||||
@@ -51,7 +51,7 @@ mod gc {
|
||||
let generation = args.generation;
|
||||
let generation_num = generation.unwrap_or(2);
|
||||
if !(0..=2).contains(&generation_num) {
|
||||
return Err(vm.new_value_error("invalid generation".to_owned()));
|
||||
return Err(vm.new_value_error("invalid generation"));
|
||||
}
|
||||
|
||||
// Invoke callbacks with "start" phase
|
||||
|
||||
+10
-10
@@ -2032,7 +2032,7 @@ mod _io {
|
||||
// Yield to other threads
|
||||
std::thread::yield_now();
|
||||
}
|
||||
return Err(vm.new_value_error("write to closed file".to_owned()));
|
||||
return Err(vm.new_value_error("write to closed file"));
|
||||
}
|
||||
let mut data = self.writer().lock(vm)?;
|
||||
let raw = data.check_init(vm)?;
|
||||
@@ -4019,7 +4019,7 @@ mod _io {
|
||||
return Ok(vm.ctx.new_str(Wtf8Buf::from(format!("<{type_name}>"))));
|
||||
};
|
||||
let Some(data) = data.as_ref() else {
|
||||
return Err(vm.new_value_error("I/O operation on uninitialized object".to_owned()));
|
||||
return Err(vm.new_value_error("I/O operation on uninitialized object"));
|
||||
};
|
||||
|
||||
let mut result = Wtf8Buf::from(format!("<{type_name}"));
|
||||
@@ -4572,9 +4572,9 @@ mod _io {
|
||||
|
||||
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
|
||||
if zelf.exports.load() > 0 {
|
||||
return Err(vm.new_buffer_error(
|
||||
"Existing exports of data: object cannot be re-sized".to_owned(),
|
||||
));
|
||||
return Err(
|
||||
vm.new_buffer_error("Existing exports of data: object cannot be re-sized")
|
||||
);
|
||||
}
|
||||
|
||||
let raw_bytes = args
|
||||
@@ -4712,9 +4712,9 @@ mod _io {
|
||||
#[pymethod]
|
||||
fn close(&self, vm: &VirtualMachine) -> PyResult<()> {
|
||||
if self.exports.load() > 0 {
|
||||
return Err(vm.new_buffer_error(
|
||||
"Existing exports of data: object cannot be closed".to_owned(),
|
||||
));
|
||||
return Err(
|
||||
vm.new_buffer_error("Existing exports of data: object cannot be closed")
|
||||
);
|
||||
}
|
||||
self.closed.store(true);
|
||||
Ok(())
|
||||
@@ -4794,7 +4794,7 @@ mod _io {
|
||||
#[pymethod]
|
||||
fn getbuffer(self, vm: &VirtualMachine) -> PyResult<PyMemoryView> {
|
||||
if self.closed.load() {
|
||||
return Err(vm.new_value_error("I/O operation on closed file.".to_owned()));
|
||||
return Err(vm.new_value_error("I/O operation on closed file."));
|
||||
}
|
||||
let len = self.buffer.read().cursor.get_ref().len();
|
||||
let buffer = PyBuffer::new(
|
||||
@@ -6976,7 +6976,7 @@ mod winconsoleio {
|
||||
|
||||
#[pymethod(name = "__reduce__")]
|
||||
fn reduce(_zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_type_error("cannot pickle '_WindowsConsoleIO' instances".to_owned()))
|
||||
Err(vm.new_type_error("cannot pickle '_WindowsConsoleIO' instances"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -364,9 +364,9 @@ pub(crate) mod module {
|
||||
// If path is a file descriptor, use fchmod
|
||||
if let OsPathOrFd::Fd(fd) = path {
|
||||
if follow_symlinks.into_option().is_some() {
|
||||
return Err(vm.new_value_error(
|
||||
"chmod: follow_symlinks is not supported with fd argument".to_owned(),
|
||||
));
|
||||
return Err(
|
||||
vm.new_value_error("chmod: follow_symlinks is not supported with fd argument")
|
||||
);
|
||||
}
|
||||
return fchmod_impl(fd.as_raw(), mode, vm);
|
||||
}
|
||||
@@ -1377,7 +1377,7 @@ pub(crate) mod module {
|
||||
let wide = path.to_wide_cstring(vm)?;
|
||||
let buflen = core::cmp::max(wide.len(), Foundation::MAX_PATH as usize);
|
||||
if buflen > u32::MAX as usize {
|
||||
return Err(vm.new_overflow_error("path too long".to_owned()));
|
||||
return Err(vm.new_overflow_error("path too long"));
|
||||
}
|
||||
let mut buffer = vec![0u16; buflen];
|
||||
let ret = unsafe {
|
||||
@@ -2251,7 +2251,7 @@ pub(crate) mod module {
|
||||
// PathBuffer starts at offset 16
|
||||
(sub_offset, sub_length, 16usize)
|
||||
} else {
|
||||
return Err(vm.new_value_error("not a symbolic link".to_owned()));
|
||||
return Err(vm.new_value_error("not a symbolic link"));
|
||||
};
|
||||
|
||||
// Extract the substitute name
|
||||
|
||||
@@ -864,7 +864,7 @@ pub(super) mod _os {
|
||||
|
||||
#[pymethod]
|
||||
fn __reduce__(&self, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_type_error("cannot pickle 'DirEntry' object".to_owned()))
|
||||
Err(vm.new_type_error("cannot pickle 'DirEntry' object"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -927,7 +927,7 @@ pub(super) mod _os {
|
||||
|
||||
#[pymethod]
|
||||
fn __reduce__(&self, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_type_error("cannot pickle 'ScandirIterator' object".to_owned()))
|
||||
Err(vm.new_type_error("cannot pickle 'ScandirIterator' object"))
|
||||
}
|
||||
}
|
||||
impl Destructor for ScandirIterator {
|
||||
@@ -1089,7 +1089,7 @@ pub(super) mod _os {
|
||||
|
||||
#[pymethod]
|
||||
fn __reduce__(&self, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_type_error("cannot pickle 'ScandirIterator' object".to_owned()))
|
||||
Err(vm.new_type_error("cannot pickle 'ScandirIterator' object"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2061,9 +2061,7 @@ pub mod module {
|
||||
Ok(int) => int.try_to_primitive(vm)?,
|
||||
Err(obj) => {
|
||||
let s = obj.downcast::<PyUtf8Str>().map_err(|_| {
|
||||
vm.new_type_error(
|
||||
"configuration names must be strings or integers".to_owned(),
|
||||
)
|
||||
vm.new_type_error("configuration names must be strings or integers")
|
||||
})?;
|
||||
s.as_str()
|
||||
.parse::<PathconfVar>()
|
||||
@@ -2456,9 +2454,7 @@ pub mod module {
|
||||
Ok(int) => int.try_to_primitive(vm)?,
|
||||
Err(obj) => {
|
||||
let s = obj.downcast::<PyUtf8Str>().map_err(|_| {
|
||||
vm.new_type_error(
|
||||
"configuration names must be strings or integers".to_owned(),
|
||||
)
|
||||
vm.new_type_error("configuration names must be strings or integers")
|
||||
})?;
|
||||
{
|
||||
let name = s.as_str();
|
||||
@@ -2704,7 +2700,7 @@ mod posix_sched {
|
||||
class::StaticType,
|
||||
};
|
||||
if !obj.fast_isinstance(PySchedParam::static_type()) {
|
||||
return Err(vm.new_type_error("must have a sched_param object".to_owned()));
|
||||
return Err(vm.new_type_error("must have a sched_param object"));
|
||||
}
|
||||
let tuple = obj.downcast_ref::<PyTuple>().unwrap();
|
||||
let priority = tuple[0].clone();
|
||||
|
||||
@@ -401,8 +401,7 @@ pub(crate) mod _signal {
|
||||
}
|
||||
// Validate that fd is a valid file descriptor using fstat
|
||||
// First check if SOCKET can be safely cast to i32 (file descriptor)
|
||||
let fd_i32 =
|
||||
i32::try_from(fd).map_err(|_| vm.new_value_error("invalid fd".to_owned()))?;
|
||||
let fd_i32 = i32::try_from(fd).map_err(|_| vm.new_value_error("invalid fd"))?;
|
||||
// Verify the fd is valid by trying to fstat it
|
||||
let borrowed_fd =
|
||||
unsafe { crate::common::crt_fd::Borrowed::try_borrow_raw(fd_i32) }
|
||||
@@ -458,7 +457,7 @@ pub(crate) mod _signal {
|
||||
if let OptionalArg::Present(obj) = siginfo
|
||||
&& !vm.is_none(&obj)
|
||||
{
|
||||
return Err(vm.new_type_error("siginfo must be None".to_owned()));
|
||||
return Err(vm.new_type_error("siginfo must be None"));
|
||||
}
|
||||
|
||||
let flags = flags.unwrap_or(0);
|
||||
|
||||
@@ -1430,7 +1430,7 @@ mod sys {
|
||||
|
||||
// Check if type is immutable
|
||||
if type_obj.slots.flags.has_feature(PyTypeFlags::IMMUTABLETYPE) {
|
||||
return Err(vm.new_type_error("argument is immutable".to_owned()));
|
||||
return Err(vm.new_type_error("argument is immutable"));
|
||||
}
|
||||
|
||||
let mut attributes = type_obj.attributes.write();
|
||||
|
||||
@@ -699,9 +699,7 @@ pub(crate) mod _thread {
|
||||
fn _excepthook(args: crate::PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
// Type check: args must be _ExceptHookArgs
|
||||
let args = args.downcast::<ExceptHookArgs>().map_err(|_| {
|
||||
vm.new_type_error(
|
||||
"_thread._excepthook argument type must be _ExceptHookArgs".to_owned(),
|
||||
)
|
||||
vm.new_type_error("_thread._excepthook argument type must be _ExceptHookArgs")
|
||||
})?;
|
||||
|
||||
let exc_type = args.exc_type.clone();
|
||||
@@ -1126,7 +1124,7 @@ pub(crate) mod _thread {
|
||||
let inner = self.inner.lock();
|
||||
let current_ident = get_ident();
|
||||
if inner.ident == current_ident && inner.state == ThreadHandleState::Running {
|
||||
return Err(vm.new_runtime_error("cannot join current thread".to_owned()));
|
||||
return Err(vm.new_runtime_error("cannot join current thread"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -630,7 +630,7 @@ mod decl {
|
||||
{
|
||||
let year = tm.tm_year + 1900;
|
||||
if !(1..=9999).contains(&year) {
|
||||
return Err(vm.new_value_error("strftime() requires year in [1; 9999]".to_owned()));
|
||||
return Err(vm.new_value_error("strftime() requires year in [1; 9999]"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -99,7 +99,7 @@ pub(crate) mod decl {
|
||||
type Args = FuncArgs;
|
||||
|
||||
fn slot_new(_cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_type_error("cannot create '_typing._ConstEvaluator' instances".to_owned()))
|
||||
Err(vm.new_type_error("cannot create '_typing._ConstEvaluator' instances"))
|
||||
}
|
||||
|
||||
fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> {
|
||||
@@ -276,9 +276,7 @@ pub(crate) mod decl {
|
||||
|
||||
fn __getitem__(zelf: PyRef<Self>, args: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
if zelf.type_params.is_empty() {
|
||||
return Err(
|
||||
vm.new_type_error("Only generic type aliases are subscriptable".to_owned())
|
||||
);
|
||||
return Err(vm.new_type_error("Only generic type aliases are subscriptable"));
|
||||
}
|
||||
let args_tuple = if let Ok(tuple) = args.try_to_ref::<PyTuple>(vm) {
|
||||
tuple.to_owned()
|
||||
@@ -373,16 +371,13 @@ pub(crate) mod decl {
|
||||
let name = if !args.args.is_empty() {
|
||||
if args.kwargs.contains_key("name") {
|
||||
return Err(vm.new_type_error(
|
||||
"argument for typealias() given by name ('name') and position (1)"
|
||||
.to_owned(),
|
||||
"argument for typealias() given by name ('name') and position (1)",
|
||||
));
|
||||
}
|
||||
args.args[0].clone()
|
||||
} else {
|
||||
args.kwargs.get("name").cloned().ok_or_else(|| {
|
||||
vm.new_type_error(
|
||||
"typealias() missing required argument 'name' (pos 1)".to_owned(),
|
||||
)
|
||||
vm.new_type_error("typealias() missing required argument 'name' (pos 1)")
|
||||
})?
|
||||
};
|
||||
|
||||
@@ -390,16 +385,13 @@ pub(crate) mod decl {
|
||||
let value = if args.args.len() >= 2 {
|
||||
if args.kwargs.contains_key("value") {
|
||||
return Err(vm.new_type_error(
|
||||
"argument for typealias() given by name ('value') and position (2)"
|
||||
.to_owned(),
|
||||
"argument for typealias() given by name ('value') and position (2)",
|
||||
));
|
||||
}
|
||||
args.args[1].clone()
|
||||
} else {
|
||||
args.kwargs.get("value").cloned().ok_or_else(|| {
|
||||
vm.new_type_error(
|
||||
"typealias() missing required argument 'value' (pos 2)".to_owned(),
|
||||
)
|
||||
vm.new_type_error("typealias() missing required argument 'value' (pos 2)")
|
||||
})?
|
||||
};
|
||||
|
||||
@@ -414,7 +406,7 @@ pub(crate) mod decl {
|
||||
let tp = tp
|
||||
.clone()
|
||||
.downcast::<crate::builtins::PyTuple>()
|
||||
.map_err(|_| vm.new_type_error("type_params must be a tuple".to_owned()))?;
|
||||
.map_err(|_| vm.new_type_error("type_params must be a tuple"))?;
|
||||
Self::check_type_params(&tp, vm)?;
|
||||
tp
|
||||
} else {
|
||||
|
||||
@@ -71,7 +71,7 @@ mod _warnings {
|
||||
#[pyfunction]
|
||||
fn _release_lock(vm: &VirtualMachine) -> PyResult<()> {
|
||||
if !vm.state.warnings.release_lock() {
|
||||
return Err(vm.new_runtime_error("cannot release un-acquired lock".to_owned()));
|
||||
return Err(vm.new_runtime_error("cannot release un-acquired lock"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -140,9 +140,7 @@ mod _warnings {
|
||||
if let Some(ref prefixes) = skip_prefixes {
|
||||
for item in prefixes.iter() {
|
||||
if !item.class().is(vm.ctx.types.str_type) {
|
||||
return Err(
|
||||
vm.new_type_error("skip_file_prefixes must be a tuple of strs".to_owned())
|
||||
);
|
||||
return Err(vm.new_type_error("skip_file_prefixes must be a tuple of strs"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -188,17 +186,17 @@ mod _warnings {
|
||||
&& !vm.is_none(mg)
|
||||
&& !mg.class().is(vm.ctx.types.dict_type)
|
||||
{
|
||||
return Err(vm.new_type_error("module_globals must be a dict".to_owned()));
|
||||
return Err(vm.new_type_error("module_globals must be a dict"));
|
||||
}
|
||||
|
||||
let category =
|
||||
if vm.is_none(&args.category) {
|
||||
None
|
||||
} else {
|
||||
Some(PyTypeRef::try_from_object(vm, args.category).map_err(|_| {
|
||||
vm.new_type_error("category must be a Warning subclass".to_owned())
|
||||
})?)
|
||||
};
|
||||
let category = if vm.is_none(&args.category) {
|
||||
None
|
||||
} else {
|
||||
Some(
|
||||
PyTypeRef::try_from_object(vm, args.category)
|
||||
.map_err(|_| vm.new_type_error("category must be a Warning subclass"))?,
|
||||
)
|
||||
};
|
||||
|
||||
crate::warn::warn_explicit(
|
||||
category,
|
||||
|
||||
@@ -958,15 +958,15 @@ mod winreg {
|
||||
}
|
||||
let val = value
|
||||
.downcast_ref::<PyInt>()
|
||||
.ok_or_else(|| vm.new_type_error("value must be an integer".to_string()))?;
|
||||
.ok_or_else(|| vm.new_type_error("value must be an integer"))?;
|
||||
let bigint = val.as_bigint();
|
||||
// Check for negative value - raise OverflowError
|
||||
if bigint.sign() == Sign::Minus {
|
||||
return Err(vm.new_overflow_error("int too big to convert".to_string()));
|
||||
return Err(vm.new_overflow_error("int too big to convert"));
|
||||
}
|
||||
let val = bigint
|
||||
.to_u32()
|
||||
.ok_or_else(|| vm.new_overflow_error("int too big to convert".to_string()))?;
|
||||
.ok_or_else(|| vm.new_overflow_error("int too big to convert"))?;
|
||||
Ok(Some(val.to_le_bytes().to_vec()))
|
||||
}
|
||||
REG_QWORD => {
|
||||
@@ -975,15 +975,15 @@ mod winreg {
|
||||
}
|
||||
let val = value
|
||||
.downcast_ref::<PyInt>()
|
||||
.ok_or_else(|| vm.new_type_error("value must be an integer".to_string()))?;
|
||||
.ok_or_else(|| vm.new_type_error("value must be an integer"))?;
|
||||
let bigint = val.as_bigint();
|
||||
// Check for negative value - raise OverflowError
|
||||
if bigint.sign() == Sign::Minus {
|
||||
return Err(vm.new_overflow_error("int too big to convert".to_string()));
|
||||
return Err(vm.new_overflow_error("int too big to convert"));
|
||||
}
|
||||
let val = bigint
|
||||
.to_u64()
|
||||
.ok_or_else(|| vm.new_overflow_error("int too big to convert".to_string()))?;
|
||||
.ok_or_else(|| vm.new_overflow_error("int too big to convert"))?;
|
||||
Ok(Some(val.to_le_bytes().to_vec()))
|
||||
}
|
||||
REG_SZ | REG_EXPAND_SZ => {
|
||||
@@ -993,7 +993,7 @@ mod winreg {
|
||||
}
|
||||
let s = value
|
||||
.downcast::<PyStr>()
|
||||
.map_err(|_| vm.new_type_error("value must be a string".to_string()))?;
|
||||
.map_err(|_| vm.new_type_error("value must be a string"))?;
|
||||
let wide = s.as_wtf8().to_wide_with_nul();
|
||||
// Convert Vec<u16> to Vec<u8>
|
||||
let bytes: Vec<u8> = wide.iter().flat_map(|&c| c.to_le_bytes()).collect();
|
||||
@@ -1004,15 +1004,15 @@ mod winreg {
|
||||
// Empty list = double null terminator
|
||||
return Ok(Some(vec![0u8, 0u8, 0u8, 0u8]));
|
||||
}
|
||||
let list = value.downcast::<crate::builtins::PyList>().map_err(|_| {
|
||||
vm.new_type_error("value must be a list of strings".to_string())
|
||||
})?;
|
||||
let list = value
|
||||
.downcast::<crate::builtins::PyList>()
|
||||
.map_err(|_| vm.new_type_error("value must be a list of strings"))?;
|
||||
|
||||
let mut bytes: Vec<u8> = Vec::new();
|
||||
for item in list.borrow_vec().iter() {
|
||||
let s = item.downcast_ref::<PyStr>().ok_or_else(|| {
|
||||
vm.new_type_error("list items must be strings".to_string())
|
||||
})?;
|
||||
let s = item
|
||||
.downcast_ref::<PyStr>()
|
||||
.ok_or_else(|| vm.new_type_error("list items must be strings"))?;
|
||||
let wide = s.as_wtf8().to_wide_with_nul();
|
||||
bytes.extend(wide.iter().flat_map(|&c| c.to_le_bytes()));
|
||||
}
|
||||
|
||||
@@ -87,24 +87,22 @@ mod winsound {
|
||||
if vm.is_none(&sound) {
|
||||
let ok = unsafe { super::win32::PlaySoundW(core::ptr::null(), 0, flags) };
|
||||
if ok == 0 {
|
||||
return Err(vm.new_runtime_error("Failed to play sound".to_owned()));
|
||||
return Err(vm.new_runtime_error("Failed to play sound"));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if flags & SND_MEMORY != 0 {
|
||||
if flags & SND_ASYNC != 0 {
|
||||
return Err(
|
||||
vm.new_runtime_error("Cannot play asynchronously from memory".to_owned())
|
||||
);
|
||||
return Err(vm.new_runtime_error("Cannot play asynchronously from memory"));
|
||||
}
|
||||
let buffer = PyBuffer::try_from_borrowed_object(vm, &sound)?;
|
||||
let buf = buffer.as_contiguous().ok_or_else(|| {
|
||||
vm.new_type_error("a bytes-like object is required, not 'str'".to_owned())
|
||||
})?;
|
||||
let buf = buffer
|
||||
.as_contiguous()
|
||||
.ok_or_else(|| vm.new_type_error("a bytes-like object is required, not 'str'"))?;
|
||||
let ok = unsafe { super::win32::PlaySoundW(buf.as_ptr() as *const u16, 0, flags) };
|
||||
if ok == 0 {
|
||||
return Err(vm.new_runtime_error("Failed to play sound".to_owned()));
|
||||
return Err(vm.new_runtime_error("Failed to play sound"));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
@@ -138,9 +136,7 @@ mod winsound {
|
||||
let result = fspath.call((), vm)?;
|
||||
|
||||
if result.downcastable::<PyBytes>() {
|
||||
return Err(
|
||||
vm.new_type_error("'sound' must resolve to str, not bytes".to_owned())
|
||||
);
|
||||
return Err(vm.new_type_error("'sound' must resolve to str, not bytes"));
|
||||
}
|
||||
|
||||
let s: &PyStr = result.downcast_ref().ok_or_else(|| {
|
||||
@@ -157,13 +153,13 @@ mod winsound {
|
||||
|
||||
// Check for embedded null characters
|
||||
if path.as_bytes().contains(&0) {
|
||||
return Err(vm.new_value_error("embedded null character".to_owned()));
|
||||
return Err(vm.new_value_error("embedded null character"));
|
||||
}
|
||||
|
||||
let wide = path.to_wide_with_nul();
|
||||
let ok = unsafe { super::win32::PlaySoundW(wide.as_ptr(), 0, flags) };
|
||||
if ok == 0 {
|
||||
return Err(vm.new_runtime_error("Failed to play sound".to_owned()));
|
||||
return Err(vm.new_runtime_error("Failed to play sound"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -179,12 +175,12 @@ mod winsound {
|
||||
#[pyfunction]
|
||||
fn Beep(args: BeepArgs, vm: &VirtualMachine) -> PyResult<()> {
|
||||
if !(37..=32767).contains(&args.frequency) {
|
||||
return Err(vm.new_value_error("frequency must be in 37 thru 32767".to_owned()));
|
||||
return Err(vm.new_value_error("frequency must be in 37 thru 32767"));
|
||||
}
|
||||
|
||||
let ok = unsafe { super::win32::Beep(args.frequency as u32, args.duration as u32) };
|
||||
if ok == 0 {
|
||||
return Err(vm.new_runtime_error("Failed to beep".to_owned()));
|
||||
return Err(vm.new_runtime_error("Failed to beep"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -251,7 +251,7 @@ pub trait PyStructSequence: StaticType + PyClassImpl + Sized + 'static {
|
||||
#[pymethod]
|
||||
fn __replace__(zelf: PyRef<PyTuple>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
if !args.args.is_empty() {
|
||||
return Err(vm.new_type_error("__replace__() takes no positional arguments".to_owned()));
|
||||
return Err(vm.new_type_error("__replace__() takes no positional arguments"));
|
||||
}
|
||||
|
||||
if Self::Data::UNNAMED_FIELDS_LEN > 0 {
|
||||
|
||||
@@ -97,9 +97,9 @@ mod file_run {
|
||||
let loader = module_dict.get_item("__loader__", self)?;
|
||||
let get_code = loader.get_attr("get_code", self)?;
|
||||
let code_obj = get_code.call((identifier!(self, __main__).to_owned(),), self)?;
|
||||
let code = code_obj.downcast::<PyCode>().map_err(|_| {
|
||||
self.new_runtime_error("Bad code object in .pyc file".to_owned())
|
||||
})?;
|
||||
let code = code_obj
|
||||
.downcast::<PyCode>()
|
||||
.map_err(|_| self.new_runtime_error("Bad code object in .pyc file"))?;
|
||||
self.run_code_obj(code, scope)?;
|
||||
} else {
|
||||
if path != "<stdin>" {
|
||||
|
||||
@@ -390,7 +390,7 @@ pub(crate) fn warn_explicit(
|
||||
vm,
|
||||
)?;
|
||||
let action_str = PyStrRef::try_from_object(vm, action)
|
||||
.map_err(|_| vm.new_type_error("action must be a string".to_owned()))?;
|
||||
.map_err(|_| vm.new_type_error("action must be a string"))?;
|
||||
|
||||
if action_str.as_bytes() == b"error" {
|
||||
let exc = PyBaseExceptionRef::try_from_object(vm, message)?;
|
||||
@@ -470,13 +470,11 @@ fn call_show_warning(
|
||||
return show_warning(filename, lineno, text, category, source_line, vm);
|
||||
};
|
||||
if !show_fn.is_callable() {
|
||||
return Err(
|
||||
vm.new_type_error("warnings._showwarnmsg() must be set to a callable".to_owned())
|
||||
);
|
||||
return Err(vm.new_type_error("warnings._showwarnmsg() must be set to a callable"));
|
||||
}
|
||||
let Some(warnmsg_cls) = get_warnings_attr(vm, identifier!(&vm.ctx, WarningMessage), false)?
|
||||
else {
|
||||
return Err(vm.new_runtime_error("unable to get warnings.WarningMessage".to_owned()));
|
||||
return Err(vm.new_runtime_error("unable to get warnings.WarningMessage"));
|
||||
};
|
||||
|
||||
let msg = warnmsg_cls.call(
|
||||
@@ -591,7 +589,7 @@ fn setup_context(
|
||||
.get_attr(identifier!(vm, __dict__), vm)
|
||||
.and_then(|d| {
|
||||
d.downcast::<crate::builtins::PyDict>()
|
||||
.map_err(|_| vm.new_type_error("sys.__dict__ is not a dictionary".to_owned()))
|
||||
.map_err(|_| vm.new_type_error("sys.__dict__ is not a dictionary"))
|
||||
})?;
|
||||
(globals, vm.ctx.intern_str("<sys>"), 0)
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user