mirror of
https://github.com/RustPython/RustPython.git
synced 2026-10-28 18:59:04 +08:00
Remove redundent to_owned() and to_string() calls (#5836)
* Remove redundent String conversion for errors * cargo fmt
This commit is contained in:
1 parent
f9d9307503
commit
1ae07813ee
107 files changed
+704
-929
No files matched your search
+6
-12
@@ -656,15 +656,11 @@ mod array {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult {
|
||||
let spec = spec.as_str().chars().exactly_one().map_err(|_| {
|
||||
vm.new_type_error(
|
||||
"array() argument 1 must be a unicode character, not str".to_owned(),
|
||||
)
|
||||
vm.new_type_error("array() argument 1 must be a unicode character, not str")
|
||||
})?;
|
||||
|
||||
if cls.is(PyArray::class(&vm.ctx)) && !kwargs.is_empty() {
|
||||
return Err(
|
||||
vm.new_type_error("array.array() takes no keyword arguments".to_owned())
|
||||
);
|
||||
return Err(vm.new_type_error("array.array() takes no keyword arguments"));
|
||||
}
|
||||
|
||||
let mut array =
|
||||
@@ -856,9 +852,7 @@ mod array {
|
||||
|
||||
fn _from_bytes(&self, b: &[u8], itemsize: usize, vm: &VirtualMachine) -> PyResult<()> {
|
||||
if b.len() % itemsize != 0 {
|
||||
return Err(
|
||||
vm.new_value_error("bytes length not a multiple of item size".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("bytes length not a multiple of item size"));
|
||||
}
|
||||
if b.len() / itemsize > 0 {
|
||||
self.try_resizable(vm)?.frombytes(b);
|
||||
@@ -877,7 +871,7 @@ mod array {
|
||||
fn fromfile(&self, f: PyObjectRef, n: isize, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let itemsize = self.itemsize();
|
||||
if n < 0 {
|
||||
return Err(vm.new_value_error("negative count".to_owned()));
|
||||
return Err(vm.new_value_error("negative count"));
|
||||
}
|
||||
let n = vm.check_repeat_or_overflow_error(itemsize, n)?;
|
||||
let n_bytes = n * itemsize;
|
||||
@@ -885,7 +879,7 @@ mod array {
|
||||
let b = vm.call_method(&f, "read", (n_bytes,))?;
|
||||
let b = b
|
||||
.downcast::<PyBytes>()
|
||||
.map_err(|_| vm.new_type_error("read() didn't return bytes".to_owned()))?;
|
||||
.map_err(|_| vm.new_type_error("read() didn't return bytes"))?;
|
||||
|
||||
let not_enough_bytes = b.len() != n_bytes;
|
||||
|
||||
@@ -927,7 +921,7 @@ mod array {
|
||||
fn pop(zelf: &Py<Self>, i: OptionalArg<isize>, vm: &VirtualMachine) -> PyResult {
|
||||
let mut w = zelf.try_resizable(vm)?;
|
||||
if w.len() == 0 {
|
||||
Err(vm.new_index_error("pop from empty array".to_owned()))
|
||||
Err(vm.new_index_error("pop from empty array"))
|
||||
} else {
|
||||
w.pop(i.unwrap_or(-1), vm)
|
||||
}
|
||||
|
||||
@@ -56,11 +56,11 @@ mod decl {
|
||||
let sep_char = if let OptionalArg::Present(sep_buf) = sep {
|
||||
sep_buf.with_ref(|sep_bytes| {
|
||||
if sep_bytes.len() != 1 {
|
||||
return Err(vm.new_value_error("sep must be length 1.".to_owned()));
|
||||
return Err(vm.new_value_error("sep must be length 1."));
|
||||
}
|
||||
let sep_char = sep_bytes[0];
|
||||
if !sep_char.is_ascii() {
|
||||
return Err(vm.new_value_error("sep must be ASCII.".to_owned()));
|
||||
return Err(vm.new_value_error("sep must be ASCII."));
|
||||
}
|
||||
Ok(Some(sep_char))
|
||||
})?
|
||||
|
||||
@@ -46,8 +46,7 @@ mod _bisect {
|
||||
// Default is always a Some so we can safely unwrap.
|
||||
let lo = handle_default(lo, vm)?
|
||||
.map(|value| {
|
||||
usize::try_from(value)
|
||||
.map_err(|_| vm.new_value_error("lo must be non-negative".to_owned()))
|
||||
usize::try_from(value).map_err(|_| vm.new_value_error("lo must be non-negative"))
|
||||
})
|
||||
.unwrap_or(Ok(0))?;
|
||||
let hi = handle_default(hi, vm)?
|
||||
|
||||
+5
-7
@@ -105,7 +105,7 @@ mod _bz2 {
|
||||
|
||||
#[pymethod(name = "__reduce__")]
|
||||
fn reduce(&self, vm: &VirtualMachine) -> PyResult<()> {
|
||||
Err(vm.new_type_error("cannot pickle '_bz2.BZ2Decompressor' object".to_owned()))
|
||||
Err(vm.new_type_error("cannot pickle '_bz2.BZ2Decompressor' object"))
|
||||
}
|
||||
|
||||
// TODO: mro()?
|
||||
@@ -140,9 +140,7 @@ mod _bz2 {
|
||||
let level = match compresslevel {
|
||||
valid_level @ 1..=9 => bzip2::Compression::new(valid_level as u32),
|
||||
_ => {
|
||||
return Err(
|
||||
vm.new_value_error("compresslevel must be between 1 and 9".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("compresslevel must be between 1 and 9"));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -164,7 +162,7 @@ mod _bz2 {
|
||||
fn compress(&self, data: ArgBytesLike, vm: &VirtualMachine) -> PyResult<PyBytesRef> {
|
||||
let mut state = self.state.lock();
|
||||
if state.flushed {
|
||||
return Err(vm.new_value_error("Compressor has been flushed".to_owned()));
|
||||
return Err(vm.new_value_error("Compressor has been flushed"));
|
||||
}
|
||||
|
||||
// let CompressorState { flushed, encoder } = &mut *state;
|
||||
@@ -179,7 +177,7 @@ mod _bz2 {
|
||||
fn flush(&self, vm: &VirtualMachine) -> PyResult<PyBytesRef> {
|
||||
let mut state = self.state.lock();
|
||||
if state.flushed {
|
||||
return Err(vm.new_value_error("Repeated call to flush()".to_owned()));
|
||||
return Err(vm.new_value_error("Repeated call to flush()"));
|
||||
}
|
||||
|
||||
// let CompressorState { flushed, encoder } = &mut *state;
|
||||
@@ -193,7 +191,7 @@ mod _bz2 {
|
||||
|
||||
#[pymethod(name = "__reduce__")]
|
||||
fn reduce(&self, vm: &VirtualMachine) -> PyResult<()> {
|
||||
Err(vm.new_type_error("cannot pickle '_bz2.BZ2Compressor' object".to_owned()))
|
||||
Err(vm.new_type_error("cannot pickle '_bz2.BZ2Compressor' object"))
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -162,7 +162,7 @@ mod cmath {
|
||||
let abs_tol = args.abs_tol.map_or(0.0, Into::into);
|
||||
|
||||
if rel_tol < 0.0 || abs_tol < 0.0 {
|
||||
return Err(vm.new_value_error("tolerances must be non-negative".to_owned()));
|
||||
return Err(vm.new_value_error("tolerances must be non-negative"));
|
||||
}
|
||||
|
||||
if a == b {
|
||||
@@ -201,7 +201,7 @@ mod cmath {
|
||||
if !result.is_finite() && value.is_finite() {
|
||||
// CPython doesn't return `inf` when called with finite
|
||||
// values, it raises OverflowError instead.
|
||||
Err(vm.new_overflow_error("math range error".to_owned()))
|
||||
Err(vm.new_overflow_error("math range error"))
|
||||
} else {
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
@@ -369,6 +369,6 @@ pub struct EofError;
|
||||
|
||||
impl ToPyException for EofError {
|
||||
fn to_pyexception(&self, vm: &VirtualMachine) -> PyBaseExceptionRef {
|
||||
vm.new_eof_error("End of stream already reached".to_owned())
|
||||
vm.new_eof_error("End of stream already reached")
|
||||
}
|
||||
}
|
||||
@@ -567,7 +567,7 @@ mod _contextvars {
|
||||
type Args = FuncArgs;
|
||||
|
||||
fn slot_new(_cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_runtime_error("Tokens can only be created by ContextVars".to_owned()))
|
||||
Err(vm.new_runtime_error("Tokens can only be created by ContextVars"))
|
||||
}
|
||||
fn py_new(_cls: PyTypeRef, _args: Self::Args, _vm: &VirtualMachine) -> PyResult {
|
||||
unreachable!()
|
||||
|
||||
+8
-10
@@ -270,11 +270,11 @@ mod _csv {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<()> {
|
||||
let Some(name) = name.payload_if_subclass::<PyStr>(vm) else {
|
||||
return Err(vm.new_type_error("argument 0 must be a string".to_string()));
|
||||
return Err(vm.new_type_error("argument 0 must be a string"));
|
||||
};
|
||||
let dialect = match dialect {
|
||||
OptionalArg::Present(d) => PyDialect::try_from_object(vm, d)
|
||||
.map_err(|_| vm.new_type_error("argument 1 must be a dialect object".to_owned()))?,
|
||||
.map_err(|_| vm.new_type_error("argument 1 must be a dialect object"))?,
|
||||
OptionalArg::Missing => opts.result(vm)?,
|
||||
};
|
||||
let dialect = opts.update_py_dialect(dialect);
|
||||
@@ -328,7 +328,7 @@ mod _csv {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<rustpython_vm::builtins::PyListRef> {
|
||||
if !rest.args.is_empty() || !rest.kwargs.is_empty() {
|
||||
return Err(vm.new_type_error("too many argument".to_string()));
|
||||
return Err(vm.new_type_error("too many argument"));
|
||||
}
|
||||
let g = GLOBAL_HASHMAP.lock();
|
||||
let t = g
|
||||
@@ -351,7 +351,7 @@ mod _csv {
|
||||
)));
|
||||
}
|
||||
let Ok(new_size) = rest.args.first().unwrap().try_int(vm) else {
|
||||
return Err(vm.new_type_error("limit must be an integer".to_string()));
|
||||
return Err(vm.new_type_error("limit must be an integer"));
|
||||
};
|
||||
*GLOBAL_FIELD_LIMIT.lock() = new_size.try_to_primitive::<isize>(vm)?;
|
||||
}
|
||||
@@ -392,7 +392,7 @@ mod _csv {
|
||||
Some(write_meth) => write_meth,
|
||||
None if file.is_callable() => file,
|
||||
None => {
|
||||
return Err(vm.new_type_error("argument 1 must have a \"write\" method".to_owned()));
|
||||
return Err(vm.new_type_error("argument 1 must have a \"write\" method"));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -438,9 +438,7 @@ mod _csv {
|
||||
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
|
||||
let num = obj.try_int(vm)?.try_to_primitive::<isize>(vm)?;
|
||||
num.try_into().map_err(|_| {
|
||||
vm.new_value_error(
|
||||
"can not convert to QuoteStyle enum from input argument".to_string(),
|
||||
)
|
||||
vm.new_value_error("can not convert to QuoteStyle enum from input argument")
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1016,7 +1014,7 @@ mod _csv {
|
||||
prev_end = end;
|
||||
let s = std::str::from_utf8(&buffer[range.clone()])
|
||||
// not sure if this is possible - the input was all strings
|
||||
.map_err(|_e| vm.new_unicode_decode_error("csv not utf8".to_owned()))?;
|
||||
.map_err(|_e| vm.new_unicode_decode_error("csv not utf8"))?;
|
||||
// Rustpython TODO!
|
||||
// Incomplete implementation
|
||||
if let QuoteStyle::Nonnumeric = zelf.dialect.quoting {
|
||||
@@ -1125,7 +1123,7 @@ mod _csv {
|
||||
handle_res!(writer.terminator(&mut buffer[buffer_offset..]));
|
||||
}
|
||||
let s = std::str::from_utf8(&buffer[..buffer_offset])
|
||||
.map_err(|_| vm.new_unicode_decode_error("csv not utf8".to_owned()))?;
|
||||
.map_err(|_| vm.new_unicode_decode_error("csv not utf8"))?;
|
||||
|
||||
self.write.call((s,), vm)
|
||||
}
|
||||
|
||||
+3
-3
@@ -17,9 +17,9 @@ mod decl {
|
||||
#[cfg(not(feature = "compiler"))]
|
||||
{
|
||||
let _ = co_str;
|
||||
return Err(vm.new_runtime_error(
|
||||
"dis.dis() with str argument requires `compiler` feature".to_owned(),
|
||||
));
|
||||
return Err(
|
||||
vm.new_runtime_error("dis.dis() with str argument requires `compiler` feature")
|
||||
);
|
||||
}
|
||||
#[cfg(feature = "compiler")]
|
||||
{
|
||||
|
||||
+3
-3
@@ -70,7 +70,7 @@ mod fcntl {
|
||||
let s = arg.borrow_bytes();
|
||||
arg_len = s.len();
|
||||
buf.get_mut(..arg_len)
|
||||
.ok_or_else(|| vm.new_value_error("fcntl string arg too long".to_owned()))?
|
||||
.ok_or_else(|| vm.new_value_error("fcntl string arg too long"))?
|
||||
.copy_from_slice(&s)
|
||||
}
|
||||
let ret = unsafe { libc::fcntl(fd, cmd, buf.as_mut_ptr()) };
|
||||
@@ -104,7 +104,7 @@ mod fcntl {
|
||||
let mut buf = [0u8; BUF_SIZE + 1]; // nul byte
|
||||
let mut fill_buf = |b: &[u8]| {
|
||||
if b.len() > BUF_SIZE {
|
||||
return Err(vm.new_value_error("fcntl string arg too long".to_owned()));
|
||||
return Err(vm.new_value_error("fcntl string arg too long"));
|
||||
}
|
||||
buf[..b.len()].copy_from_slice(b);
|
||||
Ok(b.len())
|
||||
@@ -181,7 +181,7 @@ mod fcntl {
|
||||
} else if (cmd & libc::LOCK_EX) != 0 {
|
||||
try_into_l_type!(libc::F_WRLCK)
|
||||
} else {
|
||||
return Err(vm.new_value_error("unrecognized lockf argument".to_owned()));
|
||||
return Err(vm.new_value_error("unrecognized lockf argument"));
|
||||
}?;
|
||||
l.l_start = match start {
|
||||
OptionalArg::Present(s) => s.try_to_primitive(vm)?,
|
||||
|
||||
+12
-12
@@ -16,61 +16,61 @@ mod gc {
|
||||
|
||||
#[pyfunction]
|
||||
fn enable(_args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_not_implemented_error("".to_owned()))
|
||||
Err(vm.new_not_implemented_error(""))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn disable(_args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_not_implemented_error("".to_owned()))
|
||||
Err(vm.new_not_implemented_error(""))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn get_count(_args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_not_implemented_error("".to_owned()))
|
||||
Err(vm.new_not_implemented_error(""))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn get_debug(_args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_not_implemented_error("".to_owned()))
|
||||
Err(vm.new_not_implemented_error(""))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn get_objects(_args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_not_implemented_error("".to_owned()))
|
||||
Err(vm.new_not_implemented_error(""))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn get_refererts(_args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_not_implemented_error("".to_owned()))
|
||||
Err(vm.new_not_implemented_error(""))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn get_referrers(_args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_not_implemented_error("".to_owned()))
|
||||
Err(vm.new_not_implemented_error(""))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn get_stats(_args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_not_implemented_error("".to_owned()))
|
||||
Err(vm.new_not_implemented_error(""))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn get_threshold(_args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_not_implemented_error("".to_owned()))
|
||||
Err(vm.new_not_implemented_error(""))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn is_tracked(_args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_not_implemented_error("".to_owned()))
|
||||
Err(vm.new_not_implemented_error(""))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn set_debug(_args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_not_implemented_error("".to_owned()))
|
||||
Err(vm.new_not_implemented_error(""))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn set_threshold(_args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_not_implemented_error("".to_owned()))
|
||||
Err(vm.new_not_implemented_error(""))
|
||||
}
|
||||
}
|
||||
@@ -79,7 +79,7 @@ pub mod _hashlib {
|
||||
impl XofDigestArgs {
|
||||
fn length(&self, vm: &VirtualMachine) -> PyResult<usize> {
|
||||
usize::try_from(self.length)
|
||||
.map_err(|_| vm.new_value_error("length must be non-negative".to_owned()))
|
||||
.map_err(|_| vm.new_value_error("length must be non-negative"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -195,7 +195,7 @@ mod _json {
|
||||
type Args = (PyStrRef, isize);
|
||||
fn call(zelf: &Py<Self>, (pystr, idx): Self::Args, vm: &VirtualMachine) -> PyResult {
|
||||
if idx < 0 {
|
||||
return Err(vm.new_value_error("idx cannot be negative".to_owned()));
|
||||
return Err(vm.new_value_error("idx cannot be negative"));
|
||||
}
|
||||
let idx = idx as usize;
|
||||
let mut chars = pystr.as_str().chars();
|
||||
|
||||
+3
-5
@@ -150,9 +150,7 @@ mod _lzma {
|
||||
|
||||
fn py_new(cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult {
|
||||
if args.format == FORMAT_RAW && args.memlimit.is_some() {
|
||||
return Err(
|
||||
vm.new_value_error("Cannot specify memory limit with FORMAT_RAW".to_string())
|
||||
);
|
||||
return Err(vm.new_value_error("Cannot specify memory limit with FORMAT_RAW"));
|
||||
}
|
||||
let memlimit = args.memlimit.unwrap_or(u64::MAX);
|
||||
let filters = args.filters.unwrap_or(0);
|
||||
@@ -316,8 +314,8 @@ mod _lzma {
|
||||
filters: Option<Vec<PyObjectRef>>,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<Stream> {
|
||||
let real_check = int_to_check(check)
|
||||
.ok_or_else(|| vm.new_type_error("Invalid check value".to_string()))?;
|
||||
let real_check =
|
||||
int_to_check(check).ok_or_else(|| vm.new_type_error("Invalid check value"))?;
|
||||
if let Some(filters) = filters {
|
||||
let filters = parse_filter_chain_spec(filters, vm)?;
|
||||
Ok(Stream::new_stream_encoder(&filters, real_check)
|
||||
|
||||
+33
-41
@@ -40,7 +40,7 @@ mod math {
|
||||
if !result.is_finite() && value.is_finite() {
|
||||
// CPython doesn't return `inf` when called with finite
|
||||
// values, it raises OverflowError instead.
|
||||
Err(vm.new_overflow_error("math range error".to_owned()))
|
||||
Err(vm.new_overflow_error("math range error"))
|
||||
} else {
|
||||
Ok(result)
|
||||
}
|
||||
@@ -87,7 +87,7 @@ mod math {
|
||||
let abs_tol = args.abs_tol.map_or(0.0, |value| value.into());
|
||||
|
||||
if rel_tol < 0.0 || abs_tol < 0.0 {
|
||||
return Err(vm.new_value_error("tolerances must be non-negative".to_owned()));
|
||||
return Err(vm.new_value_error("tolerances must be non-negative"));
|
||||
}
|
||||
|
||||
if a == b {
|
||||
@@ -138,7 +138,7 @@ mod math {
|
||||
fn log(x: PyObjectRef, base: OptionalArg<ArgIntoFloat>, vm: &VirtualMachine) -> PyResult<f64> {
|
||||
let base = base.map(|b| *b).unwrap_or(std::f64::consts::E);
|
||||
if base.is_sign_negative() {
|
||||
return Err(vm.new_value_error("math domain error".to_owned()));
|
||||
return Err(vm.new_value_error("math domain error"));
|
||||
}
|
||||
log2(x, vm).map(|log_x| log_x / base.log2())
|
||||
}
|
||||
@@ -149,7 +149,7 @@ mod math {
|
||||
if x.is_nan() || x > -1.0_f64 {
|
||||
Ok(x.ln_1p())
|
||||
} else {
|
||||
Err(vm.new_value_error("math domain error".to_owned()))
|
||||
Err(vm.new_value_error("math domain error"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,7 +171,7 @@ mod math {
|
||||
if x.is_nan() || x > 0.0_f64 {
|
||||
Ok(x.log2())
|
||||
} else {
|
||||
Err(vm.new_value_error("math domain error".to_owned()))
|
||||
Err(vm.new_value_error("math domain error"))
|
||||
}
|
||||
}
|
||||
Err(float_err) => {
|
||||
@@ -180,7 +180,7 @@ mod math {
|
||||
if x.is_positive() {
|
||||
Ok(int_log2(x))
|
||||
} else {
|
||||
Err(vm.new_value_error("math domain error".to_owned()))
|
||||
Err(vm.new_value_error("math domain error"))
|
||||
}
|
||||
} else {
|
||||
// Return the float error, as it will be more intuitive to users
|
||||
@@ -203,13 +203,13 @@ mod math {
|
||||
if x < 0.0 && x.is_finite() && y.fract() != 0.0 && y.is_finite()
|
||||
|| x == 0.0 && y < 0.0 && y != f64::NEG_INFINITY
|
||||
{
|
||||
return Err(vm.new_value_error("math domain error".to_owned()));
|
||||
return Err(vm.new_value_error("math domain error"));
|
||||
}
|
||||
|
||||
let value = x.powf(y);
|
||||
|
||||
if x.is_finite() && y.is_finite() && value.is_infinite() {
|
||||
return Err(vm.new_overflow_error("math range error".to_string()));
|
||||
return Err(vm.new_overflow_error("math range error"));
|
||||
}
|
||||
|
||||
Ok(value)
|
||||
@@ -225,7 +225,7 @@ mod math {
|
||||
if value.is_zero() {
|
||||
return Ok(-0.0f64);
|
||||
}
|
||||
return Err(vm.new_value_error("math domain error".to_owned()));
|
||||
return Err(vm.new_value_error("math domain error"));
|
||||
}
|
||||
Ok(value.sqrt())
|
||||
}
|
||||
@@ -235,7 +235,7 @@ mod math {
|
||||
let value = x.as_bigint();
|
||||
|
||||
if value.is_negative() {
|
||||
return Err(vm.new_value_error("isqrt() argument must be nonnegative".to_owned()));
|
||||
return Err(vm.new_value_error("isqrt() argument must be nonnegative"));
|
||||
}
|
||||
Ok(value.sqrt())
|
||||
}
|
||||
@@ -247,7 +247,7 @@ mod math {
|
||||
if x.is_nan() || (-1.0_f64..=1.0_f64).contains(&x) {
|
||||
Ok(x.acos())
|
||||
} else {
|
||||
Err(vm.new_value_error("math domain error".to_owned()))
|
||||
Err(vm.new_value_error("math domain error"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -257,7 +257,7 @@ mod math {
|
||||
if x.is_nan() || (-1.0_f64..=1.0_f64).contains(&x) {
|
||||
Ok(x.asin())
|
||||
} else {
|
||||
Err(vm.new_value_error("math domain error".to_owned()))
|
||||
Err(vm.new_value_error("math domain error"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,7 +274,7 @@ mod math {
|
||||
#[pyfunction]
|
||||
fn cos(x: ArgIntoFloat, vm: &VirtualMachine) -> PyResult<f64> {
|
||||
if x.is_infinite() {
|
||||
return Err(vm.new_value_error("math domain error".to_owned()));
|
||||
return Err(vm.new_value_error("math domain error"));
|
||||
}
|
||||
call_math_func!(cos, x, vm)
|
||||
}
|
||||
@@ -378,9 +378,7 @@ mod math {
|
||||
let mut diffs = vec![];
|
||||
|
||||
if p.len() != q.len() {
|
||||
return Err(vm.new_value_error(
|
||||
"both points must have the same number of dimensions".to_owned(),
|
||||
));
|
||||
return Err(vm.new_value_error("both points must have the same number of dimensions"));
|
||||
}
|
||||
|
||||
for i in 0..p.len() {
|
||||
@@ -411,7 +409,7 @@ mod math {
|
||||
#[pyfunction]
|
||||
fn sin(x: ArgIntoFloat, vm: &VirtualMachine) -> PyResult<f64> {
|
||||
if x.is_infinite() {
|
||||
return Err(vm.new_value_error("math domain error".to_owned()));
|
||||
return Err(vm.new_value_error("math domain error"));
|
||||
}
|
||||
call_math_func!(sin, x, vm)
|
||||
}
|
||||
@@ -419,7 +417,7 @@ mod math {
|
||||
#[pyfunction]
|
||||
fn tan(x: ArgIntoFloat, vm: &VirtualMachine) -> PyResult<f64> {
|
||||
if x.is_infinite() {
|
||||
return Err(vm.new_value_error("math domain error".to_owned()));
|
||||
return Err(vm.new_value_error("math domain error"));
|
||||
}
|
||||
call_math_func!(tan, x, vm)
|
||||
}
|
||||
@@ -440,7 +438,7 @@ mod math {
|
||||
fn acosh(x: ArgIntoFloat, vm: &VirtualMachine) -> PyResult<f64> {
|
||||
let x = *x;
|
||||
if x.is_sign_negative() || x.is_zero() {
|
||||
Err(vm.new_value_error("math domain error".to_owned()))
|
||||
Err(vm.new_value_error("math domain error"))
|
||||
} else {
|
||||
Ok(x.acosh())
|
||||
}
|
||||
@@ -455,7 +453,7 @@ mod math {
|
||||
fn atanh(x: ArgIntoFloat, vm: &VirtualMachine) -> PyResult<f64> {
|
||||
let x = *x;
|
||||
if x >= 1.0_f64 || x <= -1.0_f64 {
|
||||
Err(vm.new_value_error("math domain error".to_owned()))
|
||||
Err(vm.new_value_error("math domain error"))
|
||||
} else {
|
||||
Ok(x.atanh())
|
||||
}
|
||||
@@ -645,9 +643,7 @@ mod math {
|
||||
// as a result of a nan or inf in the
|
||||
// summands
|
||||
if xsave.is_finite() {
|
||||
return Err(
|
||||
vm.new_overflow_error("intermediate overflow in fsum".to_owned())
|
||||
);
|
||||
return Err(vm.new_overflow_error("intermediate overflow in fsum"));
|
||||
}
|
||||
if xsave.is_infinite() {
|
||||
inf_sum += xsave;
|
||||
@@ -662,7 +658,7 @@ mod math {
|
||||
}
|
||||
if special_sum != 0.0 {
|
||||
return if inf_sum.is_nan() {
|
||||
Err(vm.new_value_error("-inf + inf in fsum".to_owned()))
|
||||
Err(vm.new_value_error("-inf + inf in fsum"))
|
||||
} else {
|
||||
Ok(special_sum)
|
||||
};
|
||||
@@ -712,9 +708,7 @@ mod math {
|
||||
let value = x.as_bigint();
|
||||
let one = BigInt::one();
|
||||
if value.is_negative() {
|
||||
return Err(
|
||||
vm.new_value_error("factorial() not defined for negative values".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("factorial() not defined for negative values"));
|
||||
} else if *value <= one {
|
||||
return Ok(one);
|
||||
}
|
||||
@@ -745,7 +739,7 @@ mod math {
|
||||
};
|
||||
|
||||
if n.is_negative() || v.is_negative() {
|
||||
return Err(vm.new_value_error("perm() not defined for negative values".to_owned()));
|
||||
return Err(vm.new_value_error("perm() not defined for negative values"));
|
||||
}
|
||||
if v > n {
|
||||
return Ok(BigInt::zero());
|
||||
@@ -768,7 +762,7 @@ mod math {
|
||||
let zero = BigInt::zero();
|
||||
|
||||
if n.is_negative() || k.is_negative() {
|
||||
return Err(vm.new_value_error("comb() not defined for negative values".to_owned()));
|
||||
return Err(vm.new_value_error("comb() not defined for negative values"));
|
||||
}
|
||||
|
||||
let temp = n - k;
|
||||
@@ -832,9 +826,7 @@ mod math {
|
||||
match steps {
|
||||
Some(steps) => {
|
||||
if steps < 0 {
|
||||
return Err(
|
||||
vm.new_value_error("steps must be a non-negative integer".to_string())
|
||||
);
|
||||
return Err(vm.new_value_error("steps must be a non-negative integer"));
|
||||
}
|
||||
Ok(float_ops::nextafter_with_steps(
|
||||
*arg.x,
|
||||
@@ -867,7 +859,7 @@ mod math {
|
||||
let r = fmod(x, y);
|
||||
|
||||
if r.is_nan() && !x.is_nan() && !y.is_nan() {
|
||||
return Err(vm.new_value_error("math domain error".to_owned()));
|
||||
return Err(vm.new_value_error("math domain error"));
|
||||
}
|
||||
|
||||
Ok(r)
|
||||
@@ -880,7 +872,7 @@ mod math {
|
||||
|
||||
if x.is_finite() && y.is_finite() {
|
||||
if y == 0.0 {
|
||||
return Err(vm.new_value_error("math domain error".to_owned()));
|
||||
return Err(vm.new_value_error("math domain error"));
|
||||
}
|
||||
|
||||
let abs_x = x.abs();
|
||||
@@ -897,7 +889,7 @@ mod math {
|
||||
return Ok(1.0_f64.copysign(x) * r);
|
||||
}
|
||||
if x.is_infinite() && !y.is_nan() {
|
||||
return Err(vm.new_value_error("math domain error".to_owned()));
|
||||
return Err(vm.new_value_error("math domain error"));
|
||||
}
|
||||
if x.is_nan() || y.is_nan() {
|
||||
return Ok(f64::NAN);
|
||||
@@ -905,7 +897,7 @@ mod math {
|
||||
if y.is_infinite() {
|
||||
Ok(x)
|
||||
} else {
|
||||
Err(vm.new_value_error("math domain error".to_owned()))
|
||||
Err(vm.new_value_error("math domain error"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -956,7 +948,7 @@ mod math {
|
||||
}
|
||||
(None, None) => break,
|
||||
_ => {
|
||||
return Err(vm.new_value_error("Inputs are not the same length".to_string()));
|
||||
return Err(vm.new_value_error("Inputs are not the same length"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -979,10 +971,10 @@ mod math {
|
||||
|
||||
if result.is_nan() {
|
||||
if !x.is_nan() && !y.is_nan() && !z.is_nan() {
|
||||
return Err(vm.new_value_error("invalid operation in fma".to_string()));
|
||||
return Err(vm.new_value_error("invalid operation in fma"));
|
||||
}
|
||||
} else if x.is_finite() && y.is_finite() && z.is_finite() {
|
||||
return Err(vm.new_overflow_error("overflow in fma".to_string()));
|
||||
return Err(vm.new_overflow_error("overflow in fma"));
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
@@ -991,7 +983,7 @@ mod math {
|
||||
|
||||
fn pymath_error_to_exception(err: pymath::Error, vm: &VirtualMachine) -> PyBaseExceptionRef {
|
||||
match err {
|
||||
pymath::Error::EDOM => vm.new_value_error("math domain error".to_owned()),
|
||||
pymath::Error::ERANGE => vm.new_overflow_error("math range error".to_owned()),
|
||||
pymath::Error::EDOM => vm.new_value_error("math domain error"),
|
||||
pymath::Error::ERANGE => vm.new_overflow_error("math range error"),
|
||||
}
|
||||
}
|
||||
+31
-48
@@ -62,7 +62,7 @@ mod mmap {
|
||||
libc::MADV_DODUMP => Advice::DoDump,
|
||||
#[cfg(target_os = "linux")]
|
||||
libc::MADV_HWPOISON => Advice::HwPoison,
|
||||
_ => return Err(vm.new_value_error("Not a valid Advice value".to_owned())),
|
||||
_ => return Err(vm.new_value_error("Not a valid Advice value")),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -83,7 +83,7 @@ mod mmap {
|
||||
1 => Self::Read,
|
||||
2 => Self::Write,
|
||||
3 => Self::Copy,
|
||||
_ => return Err(vm.new_value_error("Not a valid AccessMode value".to_owned())),
|
||||
_ => return Err(vm.new_value_error("Not a valid AccessMode value")),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -266,7 +266,7 @@ mod mmap {
|
||||
s.try_to_primitive::<usize>(vm)
|
||||
.ok()
|
||||
.filter(|s| *s < len)
|
||||
.ok_or_else(|| vm.new_value_error("madvise start out of bounds".to_owned()))
|
||||
.ok_or_else(|| vm.new_value_error("madvise start out of bounds"))
|
||||
})
|
||||
.transpose()?
|
||||
.unwrap_or(0);
|
||||
@@ -274,13 +274,13 @@ mod mmap {
|
||||
.length
|
||||
.map(|s| {
|
||||
s.try_to_primitive::<usize>(vm)
|
||||
.map_err(|_| vm.new_value_error("madvise length invalid".to_owned()))
|
||||
.map_err(|_| vm.new_value_error("madvise length invalid"))
|
||||
})
|
||||
.transpose()?
|
||||
.unwrap_or(len);
|
||||
|
||||
if isize::MAX as usize - start < length {
|
||||
return Err(vm.new_overflow_error("madvise length too large".to_owned()));
|
||||
return Err(vm.new_overflow_error("madvise length too large"));
|
||||
}
|
||||
|
||||
let length = if start + length > len {
|
||||
@@ -312,24 +312,18 @@ mod mmap {
|
||||
) -> PyResult {
|
||||
let map_size = length;
|
||||
if map_size < 0 {
|
||||
return Err(
|
||||
vm.new_overflow_error("memory mapped length must be positive".to_owned())
|
||||
);
|
||||
return Err(vm.new_overflow_error("memory mapped length must be positive"));
|
||||
}
|
||||
let mut map_size = map_size as usize;
|
||||
|
||||
if offset < 0 {
|
||||
return Err(
|
||||
vm.new_overflow_error("memory mapped offset must be positive".to_owned())
|
||||
);
|
||||
return Err(vm.new_overflow_error("memory mapped offset must be positive"));
|
||||
}
|
||||
|
||||
if (access != AccessMode::Default)
|
||||
&& ((flags != MAP_SHARED) || (prot != (PROT_WRITE | PROT_READ)))
|
||||
{
|
||||
return Err(vm.new_value_error(
|
||||
"mmap can't specify both access and flags, prot.".to_owned(),
|
||||
));
|
||||
return Err(vm.new_value_error("mmap can't specify both access and flags, prot."));
|
||||
}
|
||||
|
||||
// TODO: memmap2 doesn't support mapping with pro and flags right now
|
||||
@@ -356,22 +350,18 @@ mod mmap {
|
||||
|
||||
if map_size == 0 {
|
||||
if file_len == 0 {
|
||||
return Err(vm.new_value_error("cannot mmap an empty file".to_owned()));
|
||||
return Err(vm.new_value_error("cannot mmap an empty file"));
|
||||
}
|
||||
|
||||
if offset > file_len {
|
||||
return Err(
|
||||
vm.new_value_error("mmap offset is greater than file size".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("mmap offset is greater than file size"));
|
||||
}
|
||||
|
||||
map_size = (file_len - offset)
|
||||
.try_into()
|
||||
.map_err(|_| vm.new_value_error("mmap length is too large".to_owned()))?;
|
||||
.map_err(|_| vm.new_value_error("mmap length is too large"))?;
|
||||
} else if offset > file_len || file_len - offset < map_size as libc::off_t {
|
||||
return Err(
|
||||
vm.new_value_error("mmap length is greater than file size".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("mmap length is greater than file size"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -526,9 +516,7 @@ mod mmap {
|
||||
f: impl FnOnce(&mut MmapMut) -> R,
|
||||
) -> PyResult<R> {
|
||||
if matches!(self.access, AccessMode::Read) {
|
||||
return Err(
|
||||
vm.new_type_error("mmap can't modify a readonly memory map.".to_owned())
|
||||
);
|
||||
return Err(vm.new_type_error("mmap can't modify a readonly memory map."));
|
||||
}
|
||||
|
||||
match self.check_valid(vm)?.deref_mut().as_mut().unwrap() {
|
||||
@@ -541,7 +529,7 @@ mod mmap {
|
||||
let m = self.mmap.lock();
|
||||
|
||||
if m.is_none() {
|
||||
return Err(vm.new_value_error("mmap closed or invalid".to_owned()));
|
||||
return Err(vm.new_value_error("mmap closed or invalid"));
|
||||
}
|
||||
|
||||
Ok(m)
|
||||
@@ -551,18 +539,14 @@ mod mmap {
|
||||
#[allow(dead_code)]
|
||||
fn check_resizeable(&self, vm: &VirtualMachine) -> PyResult<()> {
|
||||
if self.exports.load() > 0 {
|
||||
return Err(vm.new_buffer_error(
|
||||
"mmap can't resize with extant buffers exported.".to_owned(),
|
||||
));
|
||||
return Err(vm.new_buffer_error("mmap can't resize with extant buffers exported."));
|
||||
}
|
||||
|
||||
if self.access == AccessMode::Write || self.access == AccessMode::Default {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
Err(vm.new_type_error(
|
||||
"mmap can't resize a readonly or copy-on-write memory map.".to_owned(),
|
||||
))
|
||||
Err(vm.new_type_error("mmap can't resize a readonly or copy-on-write memory map."))
|
||||
}
|
||||
|
||||
#[pygetset]
|
||||
@@ -577,7 +561,7 @@ mod mmap {
|
||||
}
|
||||
|
||||
if self.exports.load() > 0 {
|
||||
return Err(vm.new_buffer_error("cannot close exported pointers exist.".to_owned()));
|
||||
return Err(vm.new_buffer_error("cannot close exported pointers exist."));
|
||||
}
|
||||
let mut mmap = self.mmap.lock();
|
||||
self.closed.store(true);
|
||||
@@ -642,7 +626,7 @@ mod mmap {
|
||||
fn flush(&self, options: FlushOptions, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let (offset, size) = options
|
||||
.values(self.len())
|
||||
.ok_or_else(|| vm.new_value_error("flush values out of range".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_value_error("flush values out of range"))?;
|
||||
|
||||
if self.access == AccessMode::Read || self.access == AccessMode::Copy {
|
||||
return Ok(());
|
||||
@@ -707,9 +691,8 @@ mod mmap {
|
||||
}
|
||||
|
||||
let size = self.len();
|
||||
let (dest, src, cnt) = args(dest, src, cnt, size, vm).ok_or_else(|| {
|
||||
vm.new_value_error("source, destination, or count out of range".to_owned())
|
||||
})?;
|
||||
let (dest, src, cnt) = args(dest, src, cnt, size, vm)
|
||||
.ok_or_else(|| vm.new_value_error("source, destination, or count out of range"))?;
|
||||
|
||||
let dest_end = dest + cnt;
|
||||
let src_end = src + cnt;
|
||||
@@ -762,7 +745,7 @@ mod mmap {
|
||||
fn read_byte(&self, vm: &VirtualMachine) -> PyResult<PyIntRef> {
|
||||
let pos = self.pos();
|
||||
if pos >= self.len() {
|
||||
return Err(vm.new_value_error("read byte out of range".to_owned()));
|
||||
return Err(vm.new_value_error("read byte out of range"));
|
||||
}
|
||||
|
||||
let b = match self.check_valid(vm)?.deref().as_ref().unwrap() {
|
||||
@@ -814,7 +797,7 @@ mod mmap {
|
||||
#[pymethod]
|
||||
fn resize(&self, _newsize: PyIntRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
self.check_resizeable(vm)?;
|
||||
Err(vm.new_system_error("mmap: resizing not available--no mremap()".to_owned()))
|
||||
Err(vm.new_system_error("mmap: resizing not available--no mremap()"))
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
@@ -833,22 +816,22 @@ mod mmap {
|
||||
// relative to current position
|
||||
let pos = self.pos();
|
||||
if (((isize::MAX as usize) - pos) as isize) < dist {
|
||||
return Err(vm.new_value_error("seek out of range".to_owned()));
|
||||
return Err(vm.new_value_error("seek out of range"));
|
||||
}
|
||||
pos as isize + dist
|
||||
}
|
||||
2 => {
|
||||
// relative to end
|
||||
if (((isize::MAX as usize) - size) as isize) < dist {
|
||||
return Err(vm.new_value_error("seek out of range".to_owned()));
|
||||
return Err(vm.new_value_error("seek out of range"));
|
||||
}
|
||||
size as isize + dist
|
||||
}
|
||||
_ => return Err(vm.new_value_error("unknown seek type".to_owned())),
|
||||
_ => return Err(vm.new_value_error("unknown seek type")),
|
||||
};
|
||||
|
||||
if new_pos < 0 || (new_pos as usize) > size {
|
||||
return Err(vm.new_value_error("seek out of range".to_owned()));
|
||||
return Err(vm.new_value_error("seek out of range"));
|
||||
}
|
||||
|
||||
self.pos.store(new_pos as usize);
|
||||
@@ -877,7 +860,7 @@ mod mmap {
|
||||
let data = bytes.borrow_buf();
|
||||
|
||||
if pos > size || size - pos < data.len() {
|
||||
return Err(vm.new_value_error("data out of range".to_owned()));
|
||||
return Err(vm.new_value_error("data out of range"));
|
||||
}
|
||||
|
||||
let len = self.try_writable(vm, |mmap| {
|
||||
@@ -900,7 +883,7 @@ mod mmap {
|
||||
let size = self.len();
|
||||
|
||||
if pos >= size {
|
||||
return Err(vm.new_value_error("write byte out of range".to_owned()));
|
||||
return Err(vm.new_value_error("write byte out of range"));
|
||||
}
|
||||
|
||||
self.try_writable(vm, |mmap| {
|
||||
@@ -943,7 +926,7 @@ mod mmap {
|
||||
fn getitem_by_index(&self, i: isize, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
|
||||
let i = i
|
||||
.wrapped_at(self.len())
|
||||
.ok_or_else(|| vm.new_index_error("mmap index out of range".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_index_error("mmap index out of range"))?;
|
||||
|
||||
let b = match self.check_valid(vm)?.deref().as_ref().unwrap() {
|
||||
MmapObj::Read(mmap) => mmap[i],
|
||||
@@ -1020,7 +1003,7 @@ mod mmap {
|
||||
) -> PyResult<()> {
|
||||
let i: usize = i
|
||||
.wrapped_at(self.len())
|
||||
.ok_or_else(|| vm.new_index_error("mmap index out of range".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_index_error("mmap index out of range"))?;
|
||||
|
||||
let b = value_from_object(vm, &value)?;
|
||||
|
||||
@@ -1042,7 +1025,7 @@ mod mmap {
|
||||
let bytes = bytes_from_object(vm, &value)?;
|
||||
|
||||
if bytes.len() != slice_len {
|
||||
return Err(vm.new_index_error("mmap slice assignment is wrong size".to_owned()));
|
||||
return Err(vm.new_index_error("mmap slice assignment is wrong size"));
|
||||
}
|
||||
|
||||
if slice_len == 0 {
|
||||
|
||||
@@ -223,7 +223,7 @@ mod _overlapped {
|
||||
) -> PyResult {
|
||||
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")]
|
||||
@@ -368,7 +368,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 = match name {
|
||||
|
||||
@@ -35,7 +35,7 @@ mod _posixsubprocess {
|
||||
#[pyfunction]
|
||||
fn fork_exec(args: ForkExecArgs, vm: &VirtualMachine) -> PyResult<libc::pid_t> {
|
||||
if args.preexec_fn.is_some() {
|
||||
return Err(vm.new_not_implemented_error("preexec_fn not supported yet".to_owned()));
|
||||
return Err(vm.new_not_implemented_error("preexec_fn not supported yet"));
|
||||
}
|
||||
let extra_groups = args
|
||||
.groups_list
|
||||
|
||||
@@ -38,9 +38,7 @@ pub(crate) mod _struct {
|
||||
other.class().name()
|
||||
))),
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
vm.new_unicode_decode_error("Struct format must be a ascii string".to_owned())
|
||||
})?;
|
||||
.ok_or_else(|| vm.new_unicode_decode_error("Struct format must be a ascii string"))?;
|
||||
Ok(IntoStructFormatBytes(fmt))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ mod _random {
|
||||
#[pymethod]
|
||||
fn getrandbits(&self, k: isize, vm: &VirtualMachine) -> PyResult<BigInt> {
|
||||
match k {
|
||||
..0 => Err(vm.new_value_error("number of bits must be non-negative".to_owned())),
|
||||
..0 => Err(vm.new_value_error("number of bits must be non-negative")),
|
||||
0 => Ok(BigInt::zero()),
|
||||
mut k => {
|
||||
let mut rng = self.rng.lock();
|
||||
@@ -117,11 +117,11 @@ mod _random {
|
||||
let state: &[_; mt19937::N + 1] = state
|
||||
.as_slice()
|
||||
.try_into()
|
||||
.map_err(|_| vm.new_value_error("state vector is the wrong size".to_owned()))?;
|
||||
.map_err(|_| vm.new_value_error("state vector is the wrong size"))?;
|
||||
let (index, state) = state.split_last().unwrap();
|
||||
let index: usize = index.try_to_value(vm)?;
|
||||
if index > mt19937::N {
|
||||
return Err(vm.new_value_error("invalid state".to_owned()));
|
||||
return Err(vm.new_value_error("invalid state"));
|
||||
}
|
||||
let state: [u32; mt19937::N] = state
|
||||
.iter()
|
||||
|
||||
+1
-1
@@ -265,7 +265,7 @@ mod re {
|
||||
|
||||
fn make_regex(vm: &VirtualMachine, pattern: &str, flags: PyRegexFlags) -> PyResult<PyPattern> {
|
||||
let unicode = if flags.unicode && flags.ascii {
|
||||
return Err(vm.new_value_error("ASCII and UNICODE flags are incompatible".to_owned()));
|
||||
return Err(vm.new_value_error("ASCII and UNICODE flags are incompatible"));
|
||||
} else {
|
||||
!flags.ascii
|
||||
};
|
||||
|
||||
@@ -123,7 +123,7 @@ mod resource {
|
||||
};
|
||||
res.map(Rusage::from).map_err(|e| {
|
||||
if e.kind() == io::ErrorKind::InvalidInput {
|
||||
vm.new_value_error("invalid who parameter".to_owned())
|
||||
vm.new_value_error("invalid who parameter")
|
||||
} else {
|
||||
e.to_pyexception(vm)
|
||||
}
|
||||
@@ -139,7 +139,7 @@ mod resource {
|
||||
rlim_cur: cur & RLIM_INFINITY,
|
||||
rlim_max: max & RLIM_INFINITY,
|
||||
})),
|
||||
_ => Err(vm.new_value_error("expected a tuple of 2 integers".to_owned())),
|
||||
_ => Err(vm.new_value_error("expected a tuple of 2 integers")),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -153,7 +153,7 @@ mod resource {
|
||||
fn getrlimit(resource: i32, vm: &VirtualMachine) -> PyResult<Limits> {
|
||||
#[allow(clippy::unnecessary_cast)]
|
||||
if resource < 0 || resource >= RLIM_NLIMITS as i32 {
|
||||
return Err(vm.new_value_error("invalid resource specified".to_owned()));
|
||||
return Err(vm.new_value_error("invalid resource specified"));
|
||||
}
|
||||
let rlimit = unsafe {
|
||||
let mut rlimit = mem::MaybeUninit::<libc::rlimit>::uninit();
|
||||
@@ -169,7 +169,7 @@ mod resource {
|
||||
fn setrlimit(resource: i32, limits: Limits, vm: &VirtualMachine) -> PyResult<()> {
|
||||
#[allow(clippy::unnecessary_cast)]
|
||||
if resource < 0 || resource >= RLIM_NLIMITS as i32 {
|
||||
return Err(vm.new_value_error("invalid resource specified".to_owned()));
|
||||
return Err(vm.new_value_error("invalid resource specified"));
|
||||
}
|
||||
let res = unsafe {
|
||||
if libc::setrlimit(resource as _, &limits.0) == -1 {
|
||||
@@ -180,10 +180,10 @@ mod resource {
|
||||
};
|
||||
res.map_err(|e| match e.kind() {
|
||||
io::ErrorKind::InvalidInput => {
|
||||
vm.new_value_error("current limit exceeds maximum limit".to_owned())
|
||||
vm.new_value_error("current limit exceeds maximum limit")
|
||||
}
|
||||
io::ErrorKind::PermissionDenied => {
|
||||
vm.new_value_error("not allowed to raise maximum limit".to_owned())
|
||||
vm.new_value_error("not allowed to raise maximum limit")
|
||||
}
|
||||
_ => e.to_pyexception(vm),
|
||||
})
|
||||
|
||||
+15
-18
@@ -246,7 +246,7 @@ mod decl {
|
||||
});
|
||||
if let Some(timeout) = timeout {
|
||||
if timeout < 0.0 {
|
||||
return Err(vm.new_value_error("timeout must be positive".to_owned()));
|
||||
return Err(vm.new_value_error("timeout must be positive"));
|
||||
}
|
||||
}
|
||||
let deadline = timeout.map(|s| time::time(vm).unwrap() + s);
|
||||
@@ -353,9 +353,7 @@ mod decl {
|
||||
} else if let Some(float) = obj.payload::<PyFloat>() {
|
||||
let float = float.to_f64();
|
||||
if float.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 float.is_sign_negative() {
|
||||
None
|
||||
@@ -367,9 +365,10 @@ mod decl {
|
||||
if int.as_bigint().is_negative() {
|
||||
None
|
||||
} else {
|
||||
let n = int.as_bigint().to_u64().ok_or_else(|| {
|
||||
vm.new_overflow_error("value out of range".to_owned())
|
||||
})?;
|
||||
let n = int
|
||||
.as_bigint()
|
||||
.to_u64()
|
||||
.ok_or_else(|| vm.new_overflow_error("value out of range"))?;
|
||||
Some(if MILLIS {
|
||||
Duration::from_millis(n)
|
||||
} else {
|
||||
@@ -430,17 +429,16 @@ mod decl {
|
||||
use crate::builtins::PyInt;
|
||||
let int = obj
|
||||
.downcast::<PyInt>()
|
||||
.map_err(|_| vm.new_type_error("argument must be an integer".to_owned()))?;
|
||||
.map_err(|_| vm.new_type_error("argument must be an integer"))?;
|
||||
|
||||
let val = int.as_bigint();
|
||||
if val.is_negative() {
|
||||
return Err(vm.new_value_error("negative event mask".to_owned()));
|
||||
return Err(vm.new_value_error("negative event mask"));
|
||||
}
|
||||
|
||||
// Try converting to i16, should raise OverflowError if too large
|
||||
let mask = i16::try_from(val).map_err(|_| {
|
||||
vm.new_overflow_error("event mask value out of range".to_owned())
|
||||
})?;
|
||||
let mask = i16::try_from(val)
|
||||
.map_err(|_| vm.new_overflow_error("event mask value out of range"))?;
|
||||
|
||||
Ok(EventMask(mask))
|
||||
}
|
||||
@@ -497,7 +495,7 @@ mod decl {
|
||||
let TimeoutArg(timeout) = timeout.unwrap_or_default();
|
||||
let timeout_ms = match timeout {
|
||||
Some(d) => i32::try_from(d.as_millis())
|
||||
.map_err(|_| vm.new_overflow_error("value out of range".to_owned()))?,
|
||||
.map_err(|_| vm.new_overflow_error("value out of range"))?,
|
||||
None => -1i32,
|
||||
};
|
||||
let deadline = timeout.map(|d| Instant::now() + d);
|
||||
@@ -579,7 +577,7 @@ mod decl {
|
||||
type Args = EpollNewArgs;
|
||||
fn py_new(cls: PyTypeRef, args: EpollNewArgs, vm: &VirtualMachine) -> PyResult {
|
||||
if let ..=-2 | 0 = args.sizehint {
|
||||
return Err(vm.new_value_error("negative sizehint".to_owned()));
|
||||
return Err(vm.new_value_error("negative sizehint"));
|
||||
}
|
||||
if !matches!(args.flags, 0 | libc::EPOLL_CLOEXEC) {
|
||||
return Err(vm.new_os_error("invalid flags".to_owned()));
|
||||
@@ -625,9 +623,8 @@ mod decl {
|
||||
&self,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<impl Deref<Target = OwnedFd> + '_> {
|
||||
PyRwLockReadGuard::try_map(self.epoll_fd.read(), |x| x.as_ref()).map_err(|_| {
|
||||
vm.new_value_error("I/O operation on closed epoll object".to_owned())
|
||||
})
|
||||
PyRwLockReadGuard::try_map(self.epoll_fd.read(), |x| x.as_ref())
|
||||
.map_err(|_| vm.new_value_error("I/O operation on closed epoll object"))
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
@@ -680,7 +677,7 @@ mod decl {
|
||||
timeout
|
||||
.map(rustix::event::Timespec::try_from)
|
||||
.transpose()
|
||||
.map_err(|_| vm.new_overflow_error("timeout is too large".to_owned()))?;
|
||||
.map_err(|_| vm.new_overflow_error("timeout is too large"))?;
|
||||
|
||||
let deadline = timeout.map(|d| Instant::now() + d);
|
||||
let maxevents = match maxevents {
|
||||
|
||||
+29
-36
@@ -771,11 +771,11 @@ mod _socket {
|
||||
|
||||
// should really just be to_index() but test_socket tests the error messages explicitly
|
||||
if obj.fast_isinstance(vm.ctx.types.float_type) {
|
||||
return Err(vm.new_type_error("integer argument expected, got float".to_owned()));
|
||||
return Err(vm.new_type_error("integer argument expected, got float"));
|
||||
}
|
||||
let int = obj
|
||||
.try_index_opt(vm)
|
||||
.unwrap_or_else(|| Err(vm.new_type_error("an integer is required".to_owned())))?;
|
||||
.unwrap_or_else(|| Err(vm.new_type_error("an integer is required")))?;
|
||||
int.try_to_primitive::<CastFrom>(vm)
|
||||
.map(|sock| sock as RawSocket)
|
||||
}
|
||||
@@ -953,9 +953,7 @@ mod _socket {
|
||||
})?;
|
||||
if tuple.len() != 2 {
|
||||
return Err(vm
|
||||
.new_type_error(
|
||||
"AF_INET address must be a pair (host, post)".to_owned(),
|
||||
)
|
||||
.new_type_error("AF_INET address must be a pair (host, post)")
|
||||
.into());
|
||||
}
|
||||
let addr = Address::from_tuple(&tuple, vm)?;
|
||||
@@ -979,8 +977,7 @@ mod _socket {
|
||||
match tuple.len() {
|
||||
2..=4 => {}
|
||||
_ => return Err(vm.new_type_error(
|
||||
"AF_INET6 address must be a tuple (host, port[, flowinfo[, scopeid]])"
|
||||
.to_owned(),
|
||||
"AF_INET6 address must be a tuple (host, port[, flowinfo[, scopeid]])",
|
||||
).into()),
|
||||
}
|
||||
let (addr, flowinfo, scopeid) = Address::from_tuple_ipv6(&tuple, vm)?;
|
||||
@@ -1219,7 +1216,7 @@ mod _socket {
|
||||
let flags = flags.unwrap_or(0);
|
||||
let bufsize = bufsize
|
||||
.to_usize()
|
||||
.ok_or_else(|| vm.new_value_error("negative buffersize in recvfrom".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_value_error("negative buffersize in recvfrom"))?;
|
||||
let mut buffer = Vec::with_capacity(bufsize);
|
||||
let (n, addr) = self.sock_op(vm, SelectKind::Read, || {
|
||||
self.sock()?
|
||||
@@ -1242,12 +1239,10 @@ mod _socket {
|
||||
let buf = match nbytes {
|
||||
OptionalArg::Present(i) => {
|
||||
let i = i.to_usize().ok_or_else(|| {
|
||||
vm.new_value_error("negative buffersize in recvfrom_into".to_owned())
|
||||
vm.new_value_error("negative buffersize in recvfrom_into")
|
||||
})?;
|
||||
buf.get_mut(..i).ok_or_else(|| {
|
||||
vm.new_value_error(
|
||||
"nbytes is greater than the length of the buffer".to_owned(),
|
||||
)
|
||||
vm.new_value_error("nbytes is greater than the length of the buffer")
|
||||
})?
|
||||
}
|
||||
OptionalArg::Missing => buf,
|
||||
@@ -1316,9 +1311,9 @@ mod _socket {
|
||||
let (flags, address) = match arg3 {
|
||||
OptionalArg::Present(arg3) => {
|
||||
// should just be i32::try_from_obj but tests check for error message
|
||||
let int = arg2.try_index_opt(vm).unwrap_or_else(|| {
|
||||
Err(vm.new_type_error("an integer is required".to_owned()))
|
||||
})?;
|
||||
let int = arg2
|
||||
.try_index_opt(vm)
|
||||
.unwrap_or_else(|| Err(vm.new_type_error("an integer is required")))?;
|
||||
let flags = int.try_to_primitive::<i32>(vm)?;
|
||||
(flags, arg3)
|
||||
}
|
||||
@@ -1369,9 +1364,9 @@ mod _socket {
|
||||
&ancdata,
|
||||
|obj| -> PyResult<(i32, i32, ArgBytesLike)> {
|
||||
let seq: Vec<PyObjectRef> = obj.try_into_value(vm)?;
|
||||
let [lvl, typ, data]: [PyObjectRef; 3] = seq.try_into().map_err(|_| {
|
||||
vm.new_type_error("expected a sequence of length 3".to_owned())
|
||||
})?;
|
||||
let [lvl, typ, data]: [PyObjectRef; 3] = seq
|
||||
.try_into()
|
||||
.map_err(|_| vm.new_type_error("expected a sequence of length 3"))?;
|
||||
Ok((
|
||||
lvl.try_into_value(vm)?,
|
||||
typ.try_into_value(vm)?,
|
||||
@@ -1426,7 +1421,7 @@ mod _socket {
|
||||
for (lvl, typ, buf) in cmsgs {
|
||||
if pmhdr.is_null() {
|
||||
return Err(vm.new_runtime_error(
|
||||
"unexpected NULL result from CMSG_FIRSTHDR/CMSG_NXTHDR".to_owned(),
|
||||
"unexpected NULL result from CMSG_FIRSTHDR/CMSG_NXTHDR",
|
||||
));
|
||||
}
|
||||
let data = &*buf.borrow_buf();
|
||||
@@ -1590,7 +1585,7 @@ mod _socket {
|
||||
},
|
||||
_ => {
|
||||
return Err(vm
|
||||
.new_type_error("expected the value arg xor the optlen arg".to_owned())
|
||||
.new_type_error("expected the value arg xor the optlen arg")
|
||||
.into());
|
||||
}
|
||||
};
|
||||
@@ -1609,7 +1604,7 @@ mod _socket {
|
||||
c::SHUT_RDWR => Shutdown::Both,
|
||||
_ => {
|
||||
return Err(vm
|
||||
.new_value_error("`how` must be SHUT_RD, SHUT_WR, or SHUT_RDWR".to_owned())
|
||||
.new_value_error("`how` must be SHUT_RD, SHUT_WR, or SHUT_RDWR")
|
||||
.into());
|
||||
}
|
||||
};
|
||||
@@ -1646,7 +1641,7 @@ mod _socket {
|
||||
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
|
||||
let tuple = PyTupleRef::try_from_object(vm, obj)?;
|
||||
if tuple.len() != 2 {
|
||||
Err(vm.new_type_error("Address tuple should have only 2 values".to_owned()))
|
||||
Err(vm.new_type_error("Address tuple should have only 2 values"))
|
||||
} else {
|
||||
Self::from_tuple(&tuple, vm)
|
||||
}
|
||||
@@ -1659,7 +1654,7 @@ mod _socket {
|
||||
let port = i32::try_from_borrowed_object(vm, &tuple[1])?;
|
||||
let port = port
|
||||
.to_u16()
|
||||
.ok_or_else(|| vm.new_overflow_error("port must be 0-65535.".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_overflow_error("port must be 0-65535."))?;
|
||||
Ok(Address { host, port })
|
||||
}
|
||||
fn from_tuple_ipv6(
|
||||
@@ -1678,7 +1673,7 @@ mod _socket {
|
||||
.transpose()?
|
||||
.unwrap_or(0);
|
||||
if flowinfo > 0xfffff {
|
||||
return Err(vm.new_overflow_error("flowinfo must be 0-1048575.".to_owned()));
|
||||
return Err(vm.new_overflow_error("flowinfo must be 0-1048575."));
|
||||
}
|
||||
Ok((addr, flowinfo, scopeid))
|
||||
}
|
||||
@@ -1780,9 +1775,9 @@ mod _socket {
|
||||
protocolname: OptionalArg<PyStrRef>,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<String> {
|
||||
let port = port.to_u16().ok_or_else(|| {
|
||||
vm.new_overflow_error("getservbyport: port must be 0-65535.".to_owned())
|
||||
})?;
|
||||
let port = port
|
||||
.to_u16()
|
||||
.ok_or_else(|| vm.new_overflow_error("getservbyport: port must be 0-65535."))?;
|
||||
let cstr_proto = protocolname
|
||||
.as_ref()
|
||||
.map(|s| s.to_cstring(vm))
|
||||
@@ -2027,13 +2022,13 @@ mod _socket {
|
||||
match af_inet {
|
||||
c::AF_INET => {
|
||||
let packed_ip = <&[u8; 4]>::try_from(&*packed_ip).map_err(|_| {
|
||||
vm.new_value_error("invalid length of packed IP address string".to_owned())
|
||||
vm.new_value_error("invalid length of packed IP address string")
|
||||
})?;
|
||||
Ok(Ipv4Addr::from(*packed_ip).to_string())
|
||||
}
|
||||
c::AF_INET6 => {
|
||||
let packed_ip = <&[u8; 16]>::try_from(&*packed_ip).map_err(|_| {
|
||||
vm.new_value_error("invalid length of packed IP address string".to_owned())
|
||||
vm.new_value_error("invalid length of packed IP address string")
|
||||
})?;
|
||||
Ok(get_ipv6_addr_str(Ipv6Addr::from(*packed_ip)))
|
||||
}
|
||||
@@ -2061,9 +2056,7 @@ mod _socket {
|
||||
match address.len() {
|
||||
2..=4 => {}
|
||||
_ => {
|
||||
return Err(vm
|
||||
.new_type_error("illegal sockaddr argument".to_owned())
|
||||
.into());
|
||||
return Err(vm.new_type_error("illegal sockaddr argument").into());
|
||||
}
|
||||
}
|
||||
let (addr, flowinfo, scopeid) = Address::from_tuple_ipv6(&address, vm)?;
|
||||
@@ -2294,7 +2287,7 @@ mod _socket {
|
||||
.codec_registry
|
||||
.encode_text(pyname, "idna", None, vm)?;
|
||||
let name = std::str::from_utf8(name.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"))?;
|
||||
let mut res = dns_lookup::getaddrinfo(Some(name), None, Some(hints))
|
||||
.map_err(|e| convert_socket_error(vm, e, SocketError::GaiError))?;
|
||||
Ok(res.next().unwrap().map(|ainfo| ainfo.sockaddr)?)
|
||||
@@ -2311,7 +2304,7 @@ mod _socket {
|
||||
}
|
||||
};
|
||||
if invalid {
|
||||
return Err(vm.new_value_error("negative file descriptor".to_owned()));
|
||||
return Err(vm.new_value_error("negative file descriptor"));
|
||||
}
|
||||
Ok(unsafe { sock_from_raw_unchecked(fileno) })
|
||||
}
|
||||
@@ -2517,13 +2510,13 @@ mod _socket {
|
||||
#[pyfunction(name = "CMSG_LEN")]
|
||||
fn cmsg_len(length: usize, vm: &VirtualMachine) -> PyResult<usize> {
|
||||
checked_cmsg_len(length)
|
||||
.ok_or_else(|| vm.new_overflow_error("CMSG_LEN() argument out of range".to_owned()))
|
||||
.ok_or_else(|| vm.new_overflow_error("CMSG_LEN() argument out of range"))
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "redox")))]
|
||||
#[pyfunction(name = "CMSG_SPACE")]
|
||||
fn cmsg_space(length: usize, vm: &VirtualMachine) -> PyResult<usize> {
|
||||
checked_cmsg_space(length)
|
||||
.ok_or_else(|| vm.new_overflow_error("CMSG_SPACE() argument out of range".to_owned()))
|
||||
.ok_or_else(|| vm.new_overflow_error("CMSG_SPACE() argument out of range"))
|
||||
}
|
||||
}
|
||||
+28
-35
@@ -1015,9 +1015,7 @@ mod _sqlite {
|
||||
sleep,
|
||||
} = args;
|
||||
if zelf.is(&target) {
|
||||
return Err(
|
||||
vm.new_value_error("target cannot be the same connection instance".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("target cannot be the same connection instance"));
|
||||
}
|
||||
|
||||
let pages = if pages == 0 { -1 } else { pages };
|
||||
@@ -1165,7 +1163,7 @@ mod _sqlite {
|
||||
let data = Box::into_raw(Box::new(data));
|
||||
|
||||
if !callable.is_callable() {
|
||||
return Err(vm.new_type_error("parameter must be callable".to_owned()));
|
||||
return Err(vm.new_type_error("parameter must be callable"));
|
||||
}
|
||||
|
||||
let ret = unsafe {
|
||||
@@ -1889,12 +1887,12 @@ mod _sqlite {
|
||||
return self.data.getitem_by_index(vm, i);
|
||||
}
|
||||
}
|
||||
Err(vm.new_index_error("No item with that key".to_owned()))
|
||||
Err(vm.new_index_error("No item with that key"))
|
||||
} else if let Some(slice) = needle.payload::<PySlice>() {
|
||||
let list = self.data.getitem_by_slice(vm, slice.to_saturated(vm)?)?;
|
||||
Ok(vm.ctx.new_tuple(list).into())
|
||||
} else {
|
||||
Err(vm.new_index_error("Index must be int or string".to_owned()))
|
||||
Err(vm.new_index_error("Index must be int or string"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1908,7 +1906,7 @@ mod _sqlite {
|
||||
.inner(vm)?
|
||||
.description
|
||||
.clone()
|
||||
.ok_or_else(|| vm.new_value_error("no description in Cursor".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_value_error("no description in Cursor"))?;
|
||||
|
||||
Self {
|
||||
data: args.1,
|
||||
@@ -2069,8 +2067,7 @@ mod _sqlite {
|
||||
let mut inner = self.inner(vm)?;
|
||||
let blob_len = inner.blob.bytes();
|
||||
|
||||
let overflow_err =
|
||||
|| vm.new_overflow_error("seek offset results in overflow".to_owned());
|
||||
let overflow_err = || vm.new_overflow_error("seek offset results in overflow");
|
||||
|
||||
match origin {
|
||||
libc::SEEK_SET => {}
|
||||
@@ -2080,13 +2077,13 @@ mod _sqlite {
|
||||
libc::SEEK_END => offset = offset.checked_add(blob_len).ok_or_else(overflow_err)?,
|
||||
_ => {
|
||||
return Err(vm.new_value_error(
|
||||
"'origin' should be os.SEEK_SET, os.SEEK_CUR, or os.SEEK_END".to_owned(),
|
||||
"'origin' should be os.SEEK_SET, os.SEEK_CUR, or os.SEEK_END",
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if offset < 0 || offset > blob_len {
|
||||
Err(vm.new_value_error("offset out of blob range".to_owned()))
|
||||
Err(vm.new_value_error("offset out of blob range"))
|
||||
} else {
|
||||
inner.offset = offset;
|
||||
Ok(())
|
||||
@@ -2123,7 +2120,7 @@ mod _sqlite {
|
||||
index += length;
|
||||
}
|
||||
if index < 0 || index >= length {
|
||||
Err(vm.new_index_error("Blob index out of range".to_owned()))
|
||||
Err(vm.new_index_error("Blob index out of range"))
|
||||
} else {
|
||||
Ok(index)
|
||||
}
|
||||
@@ -2139,7 +2136,7 @@ mod _sqlite {
|
||||
if length <= max_write as usize {
|
||||
Ok(length as c_int)
|
||||
} else {
|
||||
Err(vm.new_value_error("data longer than blob length".to_owned()))
|
||||
Err(vm.new_value_error("data longer than blob length"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2176,7 +2173,7 @@ mod _sqlite {
|
||||
}
|
||||
Ok(vm.ctx.new_bytes(buf).into())
|
||||
} else {
|
||||
Err(vm.new_type_error("Blob indices must be integers".to_owned()))
|
||||
Err(vm.new_type_error("Blob indices must be integers"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2187,7 +2184,7 @@ mod _sqlite {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<()> {
|
||||
let Some(value) = value else {
|
||||
return Err(vm.new_type_error("Blob doesn't support deletion".to_owned()));
|
||||
return Err(vm.new_type_error("Blob doesn't support deletion"));
|
||||
};
|
||||
let inner = self.inner(vm)?;
|
||||
|
||||
@@ -2205,14 +2202,12 @@ mod _sqlite {
|
||||
let ret = inner.blob.write_single(value, index);
|
||||
self.check(ret, vm)
|
||||
} else if let Some(_slice) = needle.payload::<PySlice>() {
|
||||
Err(vm.new_not_implemented_error(
|
||||
"Blob slice assignment is not implemented".to_owned(),
|
||||
))
|
||||
Err(vm.new_not_implemented_error("Blob slice assignment is not implemented"))
|
||||
// let blob_len = inner.blob.bytes();
|
||||
// let slice = slice.to_saturated(vm)?;
|
||||
// let (range, step, length) = slice.adjust_indices(blob_len as usize);
|
||||
} else {
|
||||
Err(vm.new_type_error("Blob indices must be integers".to_owned()))
|
||||
Err(vm.new_type_error("Blob indices must be integers"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2871,9 +2866,8 @@ mod _sqlite {
|
||||
SQLITE_TEXT => {
|
||||
let text =
|
||||
ptr_to_vec(sqlite3_value_text(val), sqlite3_value_bytes(val), db, vm)?;
|
||||
let text = String::from_utf8(text).map_err(|_| {
|
||||
vm.new_value_error("invalid utf-8 with SQLITE_TEXT".to_owned())
|
||||
})?;
|
||||
let text = String::from_utf8(text)
|
||||
.map_err(|_| vm.new_value_error("invalid utf-8 with SQLITE_TEXT"))?;
|
||||
vm.ctx.new_str(text).into()
|
||||
}
|
||||
SQLITE_BLOB => {
|
||||
@@ -2893,10 +2887,10 @@ mod _sqlite {
|
||||
|
||||
fn ptr_to_str<'a>(p: *const libc::c_char, vm: &VirtualMachine) -> PyResult<&'a str> {
|
||||
if p.is_null() {
|
||||
return Err(vm.new_memory_error("string pointer is null".to_owned()));
|
||||
return Err(vm.new_memory_error("string pointer is null"));
|
||||
}
|
||||
unsafe { CStr::from_ptr(p).to_str() }
|
||||
.map_err(|_| vm.new_value_error("Invalid UIF-8 codepoint".to_owned()))
|
||||
.map_err(|_| vm.new_value_error("Invalid UIF-8 codepoint"))
|
||||
}
|
||||
|
||||
fn ptr_to_string(
|
||||
@@ -2906,7 +2900,7 @@ mod _sqlite {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<String> {
|
||||
let s = ptr_to_vec(p, nbytes, db, vm)?;
|
||||
String::from_utf8(s).map_err(|_| vm.new_value_error("invalid utf-8".to_owned()))
|
||||
String::from_utf8(s).map_err(|_| vm.new_value_error("invalid utf-8"))
|
||||
}
|
||||
|
||||
fn ptr_to_vec(
|
||||
@@ -2917,12 +2911,12 @@ mod _sqlite {
|
||||
) -> PyResult<Vec<u8>> {
|
||||
if p.is_null() {
|
||||
if !db.is_null() && unsafe { sqlite3_errcode(db) } == SQLITE_NOMEM {
|
||||
Err(vm.new_memory_error("sqlite out of memory".to_owned()))
|
||||
Err(vm.new_memory_error("sqlite out of memory"))
|
||||
} else {
|
||||
Ok(vec![])
|
||||
}
|
||||
} else if nbytes < 0 {
|
||||
Err(vm.new_system_error("negative size with ptr".to_owned()))
|
||||
Err(vm.new_system_error("negative size with ptr"))
|
||||
} else {
|
||||
Ok(unsafe { std::slice::from_raw_parts(p.cast(), nbytes as usize) }.to_vec())
|
||||
}
|
||||
@@ -2931,19 +2925,19 @@ mod _sqlite {
|
||||
fn str_to_ptr_len(s: &PyStr, vm: &VirtualMachine) -> PyResult<(*const libc::c_char, i32)> {
|
||||
let s = s
|
||||
.to_str()
|
||||
.ok_or_else(|| vm.new_unicode_encode_error("surrogates not allowed".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_unicode_encode_error("surrogates not allowed"))?;
|
||||
let len = c_int::try_from(s.len())
|
||||
.map_err(|_| vm.new_overflow_error("TEXT longer than INT_MAX bytes".to_owned()))?;
|
||||
.map_err(|_| vm.new_overflow_error("TEXT longer than INT_MAX bytes"))?;
|
||||
let ptr = s.as_ptr().cast();
|
||||
Ok((ptr, len))
|
||||
}
|
||||
|
||||
fn buffer_to_ptr_len(buffer: &PyBuffer, vm: &VirtualMachine) -> PyResult<(*const c_void, i32)> {
|
||||
let bytes = buffer.as_contiguous().ok_or_else(|| {
|
||||
vm.new_buffer_error("underlying buffer is not C-contiguous".to_owned())
|
||||
})?;
|
||||
let bytes = buffer
|
||||
.as_contiguous()
|
||||
.ok_or_else(|| vm.new_buffer_error("underlying buffer is not C-contiguous"))?;
|
||||
let len = c_int::try_from(bytes.len())
|
||||
.map_err(|_| vm.new_overflow_error("BLOB longer than INT_MAX bytes".to_owned()))?;
|
||||
.map_err(|_| vm.new_overflow_error("BLOB longer than INT_MAX bytes"))?;
|
||||
let ptr = bytes.as_ptr().cast();
|
||||
Ok((ptr, len))
|
||||
}
|
||||
@@ -3007,8 +3001,7 @@ mod _sqlite {
|
||||
.map(|&x| x.as_ptr().cast())
|
||||
.ok_or_else(|| {
|
||||
vm.new_value_error(
|
||||
"isolation_level string must be '', 'DEFERRED', 'IMMEDIATE', or 'EXCLUSIVE'"
|
||||
.to_owned(),
|
||||
"isolation_level string must be '', 'DEFERRED', 'IMMEDIATE', or 'EXCLUSIVE'",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
+13
-22
@@ -428,7 +428,7 @@ mod _ssl {
|
||||
#[pyfunction(name = "RAND_bytes")]
|
||||
fn rand_bytes(n: i32, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
|
||||
if n < 0 {
|
||||
return Err(vm.new_value_error("num must be positive".to_owned()));
|
||||
return Err(vm.new_value_error("num must be positive"));
|
||||
}
|
||||
let mut buf = vec![0; n as usize];
|
||||
openssl::rand::rand_bytes(&mut buf).map_err(|e| convert_openssl_error(vm, e))?;
|
||||
@@ -438,7 +438,7 @@ mod _ssl {
|
||||
#[pyfunction(name = "RAND_pseudo_bytes")]
|
||||
fn rand_pseudo_bytes(n: i32, vm: &VirtualMachine) -> PyResult<(Vec<u8>, bool)> {
|
||||
if n < 0 {
|
||||
return Err(vm.new_value_error("num must be positive".to_owned()));
|
||||
return Err(vm.new_value_error("num must be positive"));
|
||||
}
|
||||
let mut buf = vec![0; n as usize];
|
||||
let ret = unsafe { sys::RAND_bytes(buf.as_mut_ptr(), n) };
|
||||
@@ -473,14 +473,14 @@ mod _ssl {
|
||||
|
||||
fn py_new(cls: PyTypeRef, proto_version: Self::Args, vm: &VirtualMachine) -> PyResult {
|
||||
let proto = SslVersion::try_from(proto_version)
|
||||
.map_err(|_| vm.new_value_error("invalid protocol version".to_owned()))?;
|
||||
.map_err(|_| vm.new_value_error("invalid protocol version"))?;
|
||||
let method = match proto {
|
||||
// SslVersion::Ssl3 => unsafe { ssl::SslMethod::from_ptr(sys::SSLv3_method()) },
|
||||
SslVersion::Tls => ssl::SslMethod::tls(),
|
||||
// TODO: Tls1_1, Tls1_2 ?
|
||||
SslVersion::TlsClient => ssl::SslMethod::tls_client(),
|
||||
SslVersion::TlsServer => ssl::SslMethod::tls_server(),
|
||||
_ => return Err(vm.new_value_error("invalid protocol version".to_owned())),
|
||||
_ => return Err(vm.new_value_error("invalid protocol version")),
|
||||
};
|
||||
let mut builder =
|
||||
SslContextBuilder::new(method).map_err(|e| convert_openssl_error(vm, e))?;
|
||||
@@ -550,8 +550,7 @@ mod _ssl {
|
||||
value: Option<PyObjectRef>,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<()> {
|
||||
let value = value
|
||||
.ok_or_else(|| vm.new_attribute_error("cannot delete attribute".to_owned()))?;
|
||||
let value = value.ok_or_else(|| vm.new_attribute_error("cannot delete attribute"))?;
|
||||
*self.post_handshake_auth.lock() = value.is_true(vm)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -597,12 +596,11 @@ mod _ssl {
|
||||
fn set_verify_mode(&self, cert: i32, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let mut ctx = self.builder();
|
||||
let cert_req = CertRequirements::try_from(cert)
|
||||
.map_err(|_| vm.new_value_error("invalid value for verify_mode".to_owned()))?;
|
||||
.map_err(|_| vm.new_value_error("invalid value for verify_mode"))?;
|
||||
let mode = match cert_req {
|
||||
CertRequirements::None if self.check_hostname.load() => {
|
||||
return Err(vm.new_value_error(
|
||||
"Cannot set verify_mode to CERT_NONE when check_hostname is enabled."
|
||||
.to_owned(),
|
||||
"Cannot set verify_mode to CERT_NONE when check_hostname is enabled.",
|
||||
));
|
||||
}
|
||||
CertRequirements::None => SslVerifyMode::NONE,
|
||||
@@ -671,7 +669,7 @@ mod _ssl {
|
||||
#[cfg(not(ossl102))]
|
||||
{
|
||||
Err(vm.new_not_implemented_error(
|
||||
"The NPN extension requires OpenSSL 1.0.1 or later.".to_owned(),
|
||||
"The NPN extension requires OpenSSL 1.0.1 or later.",
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -683,9 +681,7 @@ mod _ssl {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<()> {
|
||||
if let (None, None, None) = (&args.cafile, &args.capath, &args.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"));
|
||||
}
|
||||
if let Some(cafile) = &args.cafile {
|
||||
cafile.ensure_no_nul(vm)?
|
||||
@@ -696,9 +692,7 @@ mod _ssl {
|
||||
|
||||
#[cold]
|
||||
fn invalid_cadata(vm: &VirtualMachine) -> PyBaseExceptionRef {
|
||||
vm.new_type_error(
|
||||
"cadata should be an ASCII string or a bytes-like object".to_owned(),
|
||||
)
|
||||
vm.new_type_error("cadata should be an ASCII string or a bytes-like object")
|
||||
}
|
||||
|
||||
let mut ctx = self.builder();
|
||||
@@ -762,9 +756,7 @@ mod _ssl {
|
||||
} = args;
|
||||
// TODO: requires passing a callback to C
|
||||
if password.is_some() {
|
||||
return Err(
|
||||
vm.new_not_implemented_error("password arg not yet supported".to_owned())
|
||||
);
|
||||
return Err(vm.new_not_implemented_error("password arg not yet supported"));
|
||||
}
|
||||
let mut ctx = self.builder();
|
||||
let key_path = keyfile.map(|path| path.to_path_buf(vm)).transpose()?;
|
||||
@@ -800,8 +792,7 @@ mod _ssl {
|
||||
let hostname = hostname.as_str();
|
||||
if hostname.is_empty() || hostname.starts_with('.') {
|
||||
return Err(vm.new_value_error(
|
||||
"server_hostname cannot be an empty string or start with a leading dot."
|
||||
.to_owned(),
|
||||
"server_hostname cannot be an empty string or start with a leading dot.",
|
||||
));
|
||||
}
|
||||
let ip = hostname.parse::<std::net::IpAddr>();
|
||||
@@ -996,7 +987,7 @@ mod _ssl {
|
||||
let binary = binary.unwrap_or(false);
|
||||
let stream = self.stream.read();
|
||||
if !stream.ssl().is_init_finished() {
|
||||
return Err(vm.new_value_error("handshake not done yet".to_owned()));
|
||||
return Err(vm.new_value_error("handshake not done yet"));
|
||||
}
|
||||
stream
|
||||
.ssl()
|
||||
|
||||
@@ -127,6 +127,6 @@ mod _statistics {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<f64> {
|
||||
normal_dist_inv_cdf(*p, *mu, *sigma)
|
||||
.ok_or_else(|| vm.new_value_error("inv_cdf undefined for these parameters".to_owned()))
|
||||
.ok_or_else(|| vm.new_value_error("inv_cdf undefined for these parameters"))
|
||||
}
|
||||
}
|
||||
@@ -198,9 +198,7 @@ mod termios {
|
||||
fn tcsetattr(fd: i32, when: i32, attributes: PyListRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let [iflag, oflag, cflag, lflag, ispeed, ospeed, cc] =
|
||||
<&[PyObjectRef; 7]>::try_from(&*attributes.borrow_vec())
|
||||
.map_err(|_| {
|
||||
vm.new_type_error("tcsetattr, arg 3: must be 7 element list".to_owned())
|
||||
})?
|
||||
.map_err(|_| vm.new_type_error("tcsetattr, arg 3: must be 7 element list"))?
|
||||
.clone();
|
||||
let mut termios = Termios::from_fd(fd).map_err(|e| termios_error(e, vm))?;
|
||||
termios.c_iflag = iflag.try_into_value(vm)?;
|
||||
@@ -225,7 +223,7 @@ mod termios {
|
||||
i.try_to_primitive(vm)?
|
||||
} else {
|
||||
return Err(vm.new_type_error(
|
||||
"tcsetattr: elements of attributes must be characters or integers".to_owned(),
|
||||
"tcsetattr: elements of attributes must be characters or integers",
|
||||
));
|
||||
};
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ impl<'a> TryFromBorrowedObject<'a> for NormalizeForm {
|
||||
"NFKC" => NormalizeForm::Nfkc,
|
||||
"NFD" => NormalizeForm::Nfd,
|
||||
"NFKD" => NormalizeForm::Nfkd,
|
||||
_ => return Err(vm.new_value_error("invalid normalization form".to_owned())),
|
||||
_ => return Err(vm.new_value_error("invalid normalization form")),
|
||||
})
|
||||
},
|
||||
vm,
|
||||
@@ -101,9 +101,7 @@ mod unicodedata {
|
||||
.as_wtf8()
|
||||
.code_points()
|
||||
.exactly_one()
|
||||
.map_err(|_| {
|
||||
vm.new_type_error("argument must be an unicode character, not str".to_owned())
|
||||
})?;
|
||||
.map_err(|_| vm.new_type_error("argument must be an unicode character, not str"))?;
|
||||
|
||||
Ok(self.check_age(c).then_some(c))
|
||||
}
|
||||
@@ -149,7 +147,7 @@ mod unicodedata {
|
||||
}
|
||||
}
|
||||
}
|
||||
default.ok_or_else(|| vm.new_value_error("character name not found!".to_owned()))
|
||||
default.ok_or_else(|| vm.new_value_error("character name not found!"))
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
|
||||
+8
-8
@@ -129,7 +129,7 @@ mod zlib {
|
||||
// 0 => ...
|
||||
9..=15 => Ok(InitOptions::Standard { header, wbits }),
|
||||
25..=31 => Ok(InitOptions::Gzip { wbits: wbits - 16 }),
|
||||
_ => Err(vm.new_value_error("Invalid initialization option".to_owned())),
|
||||
_ => Err(vm.new_value_error("Invalid initialization option")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -291,10 +291,11 @@ mod zlib {
|
||||
|
||||
#[pymethod]
|
||||
fn decompress(&self, args: DecompressArgs, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
|
||||
let max_length: usize =
|
||||
args.raw_max_length().unwrap_or(0).try_into().map_err(|_| {
|
||||
vm.new_value_error("max_length must be non-negative".to_owned())
|
||||
})?;
|
||||
let max_length: usize = args
|
||||
.raw_max_length()
|
||||
.unwrap_or(0)
|
||||
.try_into()
|
||||
.map_err(|_| vm.new_value_error("max_length must be non-negative"))?;
|
||||
let max_length = (max_length != 0).then_some(max_length);
|
||||
let data = &*args.data();
|
||||
|
||||
@@ -312,7 +313,7 @@ mod zlib {
|
||||
fn flush(&self, length: OptionalArg<ArgSize>, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
|
||||
let length = match length {
|
||||
OptionalArg::Present(ArgSize { value }) if value <= 0 => {
|
||||
return Err(vm.new_value_error("length must be greater than zero".to_owned()));
|
||||
return Err(vm.new_value_error("length must be greater than zero"));
|
||||
}
|
||||
OptionalArg::Present(ArgSize { value }) => value as usize,
|
||||
OptionalArg::Missing => DEF_BUF_SIZE,
|
||||
@@ -357,8 +358,7 @@ mod zlib {
|
||||
zdict,
|
||||
..
|
||||
} = args;
|
||||
let level =
|
||||
level.ok_or_else(|| vm.new_value_error("invalid initialization option".to_owned()))?;
|
||||
let level = level.ok_or_else(|| vm.new_value_error("invalid initialization option"))?;
|
||||
#[allow(unused_mut)]
|
||||
let mut compress = InitOptions::new(wbits.value, vm)?.compress(level);
|
||||
if let Some(zdict) = zdict {
|
||||
|
||||
+2
-2
@@ -176,7 +176,7 @@ pub trait AnyStr {
|
||||
SW: Fn(&Self, isize, &VirtualMachine) -> Vec<PyObjectRef>,
|
||||
{
|
||||
if args.sep.as_ref().is_some_and(|sep| sep.is_empty()) {
|
||||
return Err(vm.new_value_error("empty separator".to_owned()));
|
||||
return Err(vm.new_value_error("empty separator"));
|
||||
}
|
||||
let splits = if let Some(pattern) = args.sep {
|
||||
let Some(pattern) = pattern.as_ref() else {
|
||||
@@ -331,7 +331,7 @@ pub trait AnyStr {
|
||||
S: std::iter::Iterator<Item = &'a Self>,
|
||||
{
|
||||
if sub.is_empty() {
|
||||
return Err(vm.new_value_error("empty separator".to_owned()));
|
||||
return Err(vm.new_value_error("empty separator"));
|
||||
}
|
||||
|
||||
let mut sp = split();
|
||||
|
||||
@@ -206,16 +206,16 @@ impl PyAsyncGenASend {
|
||||
fn send(&self, val: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
let val = match self.state.load() {
|
||||
AwaitableState::Closed => {
|
||||
return Err(vm.new_runtime_error(
|
||||
"cannot reuse already awaited __anext__()/asend()".to_owned(),
|
||||
));
|
||||
return Err(
|
||||
vm.new_runtime_error("cannot reuse already awaited __anext__()/asend()")
|
||||
);
|
||||
}
|
||||
AwaitableState::Iter => val, // already running, all good
|
||||
AwaitableState::Init => {
|
||||
if self.ag.running_async.load() {
|
||||
return Err(vm.new_runtime_error(
|
||||
"anext(): asynchronous generator is already running".to_owned(),
|
||||
));
|
||||
return Err(
|
||||
vm.new_runtime_error("anext(): asynchronous generator is already running")
|
||||
);
|
||||
}
|
||||
self.ag.running_async.store(true);
|
||||
self.state.store(AwaitableState::Iter);
|
||||
@@ -243,9 +243,7 @@ impl PyAsyncGenASend {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult {
|
||||
if let AwaitableState::Closed = self.state.load() {
|
||||
return Err(
|
||||
vm.new_runtime_error("cannot reuse already awaited __anext__()/asend()".to_owned())
|
||||
);
|
||||
return Err(vm.new_runtime_error("cannot reuse already awaited __anext__()/asend()"));
|
||||
}
|
||||
|
||||
let res = self.ag.inner.throw(
|
||||
@@ -301,8 +299,7 @@ impl PyAsyncGenAThrow {
|
||||
fn send(&self, val: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
match self.state.load() {
|
||||
AwaitableState::Closed => {
|
||||
Err(vm
|
||||
.new_runtime_error("cannot reuse already awaited aclose()/athrow()".to_owned()))
|
||||
Err(vm.new_runtime_error("cannot reuse already awaited aclose()/athrow()"))
|
||||
}
|
||||
AwaitableState::Init => {
|
||||
if self.ag.running_async.load() {
|
||||
@@ -320,7 +317,7 @@ impl PyAsyncGenAThrow {
|
||||
}
|
||||
if !vm.is_none(&val) {
|
||||
return Err(vm.new_runtime_error(
|
||||
"can't send non-None value to a just-started async generator".to_owned(),
|
||||
"can't send non-None value to a just-started async generator",
|
||||
));
|
||||
}
|
||||
self.state.store(AwaitableState::Iter);
|
||||
@@ -398,7 +395,7 @@ impl PyAsyncGenAThrow {
|
||||
fn yield_close(&self, vm: &VirtualMachine) -> PyBaseExceptionRef {
|
||||
self.ag.running_async.store(false);
|
||||
self.state.store(AwaitableState::Closed);
|
||||
vm.new_runtime_error("async generator ignored GeneratorExit".to_owned())
|
||||
vm.new_runtime_error("async generator ignored GeneratorExit")
|
||||
}
|
||||
fn check_error(&self, exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyBaseExceptionRef {
|
||||
self.ag.running_async.store(false);
|
||||
|
||||
@@ -66,7 +66,7 @@ impl PyObjectRef {
|
||||
|
||||
let len_val = int_obj.as_bigint();
|
||||
if len_val.sign() == Sign::Minus {
|
||||
return Err(vm.new_value_error("__len__() should return >= 0".to_owned()));
|
||||
return Err(vm.new_value_error("__len__() should return >= 0"));
|
||||
}
|
||||
!len_val.is_zero()
|
||||
}
|
||||
|
||||
@@ -414,7 +414,7 @@ impl PyByteArray {
|
||||
#[pymethod]
|
||||
fn index(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult<usize> {
|
||||
let index = self.inner().find(options, |h, n| h.find(n), vm)?;
|
||||
index.ok_or_else(|| vm.new_value_error("substring not found".to_owned()))
|
||||
index.ok_or_else(|| vm.new_value_error("substring not found"))
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
@@ -426,7 +426,7 @@ impl PyByteArray {
|
||||
#[pymethod]
|
||||
fn rindex(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult<usize> {
|
||||
let index = self.inner().find(options, |h, n| h.rfind(n), vm)?;
|
||||
index.ok_or_else(|| vm.new_value_error("substring not found".to_owned()))
|
||||
index.ok_or_else(|| vm.new_value_error("substring not found"))
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
@@ -586,7 +586,7 @@ impl Py<PyByteArray> {
|
||||
let elements = &mut self.try_resizable(vm)?.elements;
|
||||
let index = elements
|
||||
.wrap_index(index.unwrap_or(-1))
|
||||
.ok_or_else(|| vm.new_index_error("index out of range".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_index_error("index out of range"))?;
|
||||
Ok(elements.remove(index))
|
||||
}
|
||||
|
||||
@@ -612,7 +612,7 @@ impl Py<PyByteArray> {
|
||||
let elements = &mut self.try_resizable(vm)?.elements;
|
||||
let index = elements
|
||||
.find_byte(value)
|
||||
.ok_or_else(|| vm.new_value_error("value not found in bytearray".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_value_error("value not found in bytearray"))?;
|
||||
elements.remove(index);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -337,7 +337,7 @@ impl PyBytes {
|
||||
#[pymethod]
|
||||
fn index(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult<usize> {
|
||||
let index = self.inner.find(options, |h, n| h.find(n), vm)?;
|
||||
index.ok_or_else(|| vm.new_value_error("substring not found".to_owned()))
|
||||
index.ok_or_else(|| vm.new_value_error("substring not found"))
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
@@ -349,7 +349,7 @@ impl PyBytes {
|
||||
#[pymethod]
|
||||
fn rindex(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult<usize> {
|
||||
let index = self.inner.find(options, |h, n| h.rfind(n), vm)?;
|
||||
index.ok_or_else(|| vm.new_value_error("substring not found".to_owned()))
|
||||
index.ok_or_else(|| vm.new_value_error("substring not found"))
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
|
||||
@@ -237,7 +237,7 @@ impl Representable for PyCode {
|
||||
impl PyCode {
|
||||
#[pyslot]
|
||||
fn slot_new(_cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_type_error("Cannot directly create code object".to_owned()))
|
||||
Err(vm.new_type_error("Cannot directly create code object"))
|
||||
}
|
||||
|
||||
#[pygetset]
|
||||
|
||||
@@ -112,7 +112,7 @@ fn to_op_complex(value: &PyObject, vm: &VirtualMachine) -> PyResult<Option<Compl
|
||||
|
||||
fn inner_div(v1: Complex64, v2: Complex64, vm: &VirtualMachine) -> PyResult<Complex64> {
|
||||
if v2.is_zero() {
|
||||
return Err(vm.new_zero_division_error("complex division by zero".to_owned()));
|
||||
return Err(vm.new_zero_division_error("complex division by zero"));
|
||||
}
|
||||
|
||||
Ok(v1.fdiv(v2))
|
||||
@@ -132,7 +132,7 @@ fn inner_pow(v1: Complex64, v2: Complex64, vm: &VirtualMachine) -> PyResult<Comp
|
||||
|
||||
let ans = powc(v1, v2);
|
||||
if ans.is_infinite() && !(v1.is_infinite() || v2.is_infinite()) {
|
||||
Err(vm.new_overflow_error("complex exponentiation overflow".to_owned()))
|
||||
Err(vm.new_overflow_error("complex exponentiation overflow"))
|
||||
} else {
|
||||
Ok(ans)
|
||||
}
|
||||
@@ -175,15 +175,13 @@ impl Constructor for PyComplex {
|
||||
} else if let Some(s) = val.payload_if_subclass::<PyStr>(vm) {
|
||||
if args.imag.is_present() {
|
||||
return Err(vm.new_type_error(
|
||||
"complex() can't take second arg if first is a string".to_owned(),
|
||||
"complex() can't take second arg if first is a string",
|
||||
));
|
||||
}
|
||||
let (re, im) = s
|
||||
.to_str()
|
||||
.and_then(rustpython_literal::complex::parse_str)
|
||||
.ok_or_else(|| {
|
||||
vm.new_value_error("complex() arg is a malformed string".to_owned())
|
||||
})?;
|
||||
.ok_or_else(|| vm.new_value_error("complex() arg is a malformed string"))?;
|
||||
return Self::from(Complex64 { re, im })
|
||||
.into_ref_with_type(vm, cls)
|
||||
.map(Into::into);
|
||||
@@ -204,9 +202,7 @@ impl Constructor for PyComplex {
|
||||
if let Some(c) = obj.try_complex(vm)? {
|
||||
c
|
||||
} else if obj.class().fast_issubclass(vm.ctx.types.str_type) {
|
||||
return Err(
|
||||
vm.new_type_error("complex() second arg can't be a string".to_owned())
|
||||
);
|
||||
return Err(vm.new_type_error("complex() second arg can't be a string"));
|
||||
} else {
|
||||
return Err(vm.new_type_error(format!(
|
||||
"complex() second argument must be a number, not '{}'",
|
||||
@@ -265,7 +261,7 @@ impl PyComplex {
|
||||
let is_finite = im.is_finite() && re.is_finite();
|
||||
let abs_result = re.hypot(im);
|
||||
if is_finite && abs_result.is_infinite() {
|
||||
Err(vm.new_overflow_error("absolute value too large".to_string()))
|
||||
Err(vm.new_overflow_error("absolute value too large"))
|
||||
} else {
|
||||
Ok(abs_result)
|
||||
}
|
||||
@@ -366,7 +362,7 @@ impl PyComplex {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<PyArithmeticValue<Complex64>> {
|
||||
if mod_val.flatten().is_some() {
|
||||
Err(vm.new_value_error("complex modulo not allowed".to_owned()))
|
||||
Err(vm.new_value_error("complex modulo not allowed"))
|
||||
} else {
|
||||
self.op(other, |a, b| inner_pow(a, b, vm), vm)
|
||||
}
|
||||
|
||||
@@ -199,7 +199,7 @@ impl PyMemberDef {
|
||||
match self.setter {
|
||||
MemberSetter::Setter(setter) => match setter {
|
||||
Some(setter) => (setter)(vm, obj, value),
|
||||
None => Err(vm.new_attribute_error("readonly attribute".to_string())),
|
||||
None => Err(vm.new_attribute_error("readonly attribute")),
|
||||
},
|
||||
MemberSetter::Offset(offset) => set_slot_at_object(obj, offset, self, value, vm),
|
||||
}
|
||||
@@ -233,9 +233,7 @@ impl PyPayload for PyMemberDescriptor {
|
||||
fn calculate_qualname(descr: &PyDescriptorOwned, vm: &VirtualMachine) -> PyResult<Option<String>> {
|
||||
if let Some(qualname) = vm.get_attribute_opt(descr.typ.clone().into(), "__qualname__")? {
|
||||
let str = qualname.downcast::<PyStr>().map_err(|_| {
|
||||
vm.new_type_error(
|
||||
"<descriptor>.__objclass__.__qualname__ is not a unicode object".to_owned(),
|
||||
)
|
||||
vm.new_type_error("<descriptor>.__objclass__.__qualname__ is not a unicode object")
|
||||
})?;
|
||||
Ok(Some(format!("{}.{}", str, descr.name)))
|
||||
} else {
|
||||
@@ -306,9 +304,7 @@ fn set_slot_at_object(
|
||||
match value {
|
||||
PySetterValue::Assign(v) => {
|
||||
if !v.class().is(vm.ctx.types.bool_type) {
|
||||
return Err(
|
||||
vm.new_type_error("attribute value type must be bool".to_owned())
|
||||
);
|
||||
return Err(vm.new_type_error("attribute value type must be bool"));
|
||||
}
|
||||
|
||||
obj.set_slot(offset, Some(v))
|
||||
|
||||
@@ -78,7 +78,7 @@ impl PyDict {
|
||||
let iter = other.get_iter(vm)?;
|
||||
loop {
|
||||
fn err(vm: &VirtualMachine) -> PyBaseExceptionRef {
|
||||
vm.new_value_error("Iterator must have exactly two elements".to_owned())
|
||||
vm.new_value_error("Iterator must have exactly two elements")
|
||||
}
|
||||
let element = match iter.next(vm)? {
|
||||
PyIterReturn::Return(obj) => obj,
|
||||
@@ -103,7 +103,7 @@ impl PyDict {
|
||||
dict.insert(vm, &*key, value)?;
|
||||
}
|
||||
if dict_other.entries.has_changed_size(dict_size) {
|
||||
return Err(vm.new_runtime_error("dict mutated during update".to_owned()));
|
||||
return Err(vm.new_runtime_error("dict mutated during update"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+17
-24
@@ -79,13 +79,11 @@ macro_rules! impl_try_from_object_float {
|
||||
impl_try_from_object_float!(f32, f64);
|
||||
|
||||
fn inner_div(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult<f64> {
|
||||
float_ops::div(v1, v2)
|
||||
.ok_or_else(|| vm.new_zero_division_error("float division by zero".to_owned()))
|
||||
float_ops::div(v1, v2).ok_or_else(|| vm.new_zero_division_error("float division by zero"))
|
||||
}
|
||||
|
||||
fn inner_mod(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult<f64> {
|
||||
float_ops::mod_(v1, v2)
|
||||
.ok_or_else(|| vm.new_zero_division_error("float mod by zero".to_owned()))
|
||||
float_ops::mod_(v1, v2).ok_or_else(|| vm.new_zero_division_error("float mod by zero"))
|
||||
}
|
||||
|
||||
pub fn try_to_bigint(value: f64, vm: &VirtualMachine) -> PyResult<BigInt> {
|
||||
@@ -93,12 +91,10 @@ pub fn try_to_bigint(value: f64, vm: &VirtualMachine) -> PyResult<BigInt> {
|
||||
Some(int) => Ok(int),
|
||||
None => {
|
||||
if value.is_infinite() {
|
||||
Err(vm.new_overflow_error(
|
||||
"OverflowError: cannot convert float infinity to integer".to_owned(),
|
||||
))
|
||||
} else if value.is_nan() {
|
||||
Err(vm
|
||||
.new_value_error("ValueError: cannot convert float NaN to integer".to_owned()))
|
||||
.new_overflow_error("OverflowError: cannot convert float infinity to integer"))
|
||||
} else if value.is_nan() {
|
||||
Err(vm.new_value_error("ValueError: cannot convert float NaN to integer"))
|
||||
} else {
|
||||
// unreachable unless BigInt has a bug
|
||||
unreachable!(
|
||||
@@ -111,12 +107,11 @@ pub fn try_to_bigint(value: f64, vm: &VirtualMachine) -> PyResult<BigInt> {
|
||||
}
|
||||
|
||||
fn inner_floordiv(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult<f64> {
|
||||
float_ops::floordiv(v1, v2)
|
||||
.ok_or_else(|| vm.new_zero_division_error("float floordiv by zero".to_owned()))
|
||||
float_ops::floordiv(v1, v2).ok_or_else(|| vm.new_zero_division_error("float floordiv by zero"))
|
||||
}
|
||||
|
||||
fn inner_divmod(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult<(f64, f64)> {
|
||||
float_ops::divmod(v1, v2).ok_or_else(|| vm.new_zero_division_error("float divmod()".to_owned()))
|
||||
float_ops::divmod(v1, v2).ok_or_else(|| vm.new_zero_division_error("float divmod()"))
|
||||
}
|
||||
|
||||
pub fn float_pow(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult {
|
||||
@@ -219,9 +214,9 @@ impl PyFloat {
|
||||
#[pystaticmethod(magic)]
|
||||
fn getformat(spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
|
||||
if !matches!(spec.as_str(), "double" | "float") {
|
||||
return Err(vm.new_value_error(
|
||||
"__getformat__() argument 1 must be 'double' or 'float'".to_owned(),
|
||||
));
|
||||
return Err(
|
||||
vm.new_value_error("__getformat__() argument 1 must be 'double' or 'float'")
|
||||
);
|
||||
}
|
||||
|
||||
const BIG_ENDIAN: bool = cfg!(target_endian = "big");
|
||||
@@ -357,7 +352,7 @@ impl PyFloat {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult {
|
||||
if mod_val.flatten().is_some() {
|
||||
Err(vm.new_type_error("floating point pow() does not accept a 3rd argument".to_owned()))
|
||||
Err(vm.new_type_error("floating point pow() does not accept a 3rd argument"))
|
||||
} else {
|
||||
self.complex_op(other, |a, b| float_pow(a, b, vm), vm)
|
||||
}
|
||||
@@ -423,9 +418,8 @@ impl PyFloat {
|
||||
None if ndigits.is_positive() => i32::MAX,
|
||||
None => i32::MIN,
|
||||
};
|
||||
let float = float_ops::round_float_digits(self.value, ndigits).ok_or_else(|| {
|
||||
vm.new_overflow_error("overflow occurred during round".to_owned())
|
||||
})?;
|
||||
let float = float_ops::round_float_digits(self.value, ndigits)
|
||||
.ok_or_else(|| vm.new_overflow_error("overflow occurred during round"))?;
|
||||
vm.ctx.new_float(float).into()
|
||||
} else {
|
||||
let fract = self.value.fract();
|
||||
@@ -482,9 +476,9 @@ impl PyFloat {
|
||||
.map(|(numer, denom)| (vm.ctx.new_bigint(&numer), vm.ctx.new_bigint(&denom)))
|
||||
.ok_or_else(|| {
|
||||
if value.is_infinite() {
|
||||
vm.new_overflow_error("cannot convert Infinity to integer ratio".to_owned())
|
||||
vm.new_overflow_error("cannot convert Infinity to integer ratio")
|
||||
} else if value.is_nan() {
|
||||
vm.new_value_error("cannot convert NaN to integer ratio".to_owned())
|
||||
vm.new_value_error("cannot convert NaN to integer ratio")
|
||||
} else {
|
||||
unreachable!("finite float must able to convert to integer ratio")
|
||||
}
|
||||
@@ -493,9 +487,8 @@ impl PyFloat {
|
||||
|
||||
#[pyclassmethod]
|
||||
fn fromhex(cls: PyTypeRef, string: PyStrRef, vm: &VirtualMachine) -> PyResult {
|
||||
let result = crate::literal::float::from_hex(string.as_str().trim()).ok_or_else(|| {
|
||||
vm.new_value_error("invalid hexadecimal floating-point string".to_owned())
|
||||
})?;
|
||||
let result = crate::literal::float::from_hex(string.as_str().trim())
|
||||
.ok_or_else(|| vm.new_value_error("invalid hexadecimal floating-point string"))?;
|
||||
PyType::call(&cls, vec![vm.ctx.new_float(result).into()].into(), vm)
|
||||
}
|
||||
|
||||
|
||||
@@ -93,18 +93,16 @@ impl Frame {
|
||||
PySetterValue::Assign(value) => {
|
||||
let zelf: FrameRef = zelf.downcast().unwrap_or_else(|_| unreachable!());
|
||||
|
||||
let value: PyIntRef = value.downcast().map_err(|_| {
|
||||
vm.new_type_error("attribute value type must be bool".to_owned())
|
||||
})?;
|
||||
let value: PyIntRef = value
|
||||
.downcast()
|
||||
.map_err(|_| vm.new_type_error("attribute value type must be bool"))?;
|
||||
|
||||
let mut trace_lines = zelf.trace_lines.lock();
|
||||
*trace_lines = !value.as_bigint().is_zero();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
PySetterValue::Delete => {
|
||||
Err(vm.new_type_error("can't delete numeric/char attribute".to_owned()))
|
||||
}
|
||||
PySetterValue::Delete => Err(vm.new_type_error("can't delete numeric/char attribute")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -492,16 +492,12 @@ impl PyFunction {
|
||||
match value {
|
||||
PySetterValue::Assign(value) => {
|
||||
let Ok(qualname) = value.downcast::<PyStr>() else {
|
||||
return Err(vm.new_type_error(
|
||||
"__qualname__ must be set to a string object".to_string(),
|
||||
));
|
||||
return Err(vm.new_type_error("__qualname__ must be set to a string object"));
|
||||
};
|
||||
*self.qualname.lock() = qualname;
|
||||
}
|
||||
PySetterValue::Delete => {
|
||||
return Err(
|
||||
vm.new_type_error("__qualname__ must be set to a string object".to_string())
|
||||
);
|
||||
return Err(vm.new_type_error("__qualname__ must be set to a string object"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -523,9 +519,7 @@ impl PyFunction {
|
||||
*self.type_params.lock() = value;
|
||||
}
|
||||
PySetterValue::Delete => {
|
||||
return Err(
|
||||
vm.new_type_error("__type_params__ must be set to a tuple object".to_string())
|
||||
);
|
||||
return Err(vm.new_type_error("__type_params__ must be set to a tuple object"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -618,7 +612,7 @@ impl Constructor for PyFunction {
|
||||
PyTupleTyped::<PyCellRef>::try_from_object(vm, closure_tuple.into())?;
|
||||
Some(typed_closure)
|
||||
} else if !args.code.freevars.is_empty() {
|
||||
return Err(vm.new_type_error("arg 5 (closure) must be tuple".to_owned()));
|
||||
return Err(vm.new_type_error("arg 5 (closure) must be tuple"));
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -862,7 +856,7 @@ impl PyCell {
|
||||
#[pygetset]
|
||||
fn cell_contents(&self, vm: &VirtualMachine) -> PyResult {
|
||||
self.get()
|
||||
.ok_or_else(|| vm.new_value_error("Cell is empty".to_owned()))
|
||||
.ok_or_else(|| vm.new_value_error("Cell is empty"))
|
||||
}
|
||||
#[pygetset(setter)]
|
||||
fn set_cell_contents(&self, x: PySetterValue) {
|
||||
|
||||
@@ -102,7 +102,7 @@ pub fn get_jit_arg_types(func: &Py<PyFunction>, vm: &VirtualMachine) -> PyResult
|
||||
|
||||
Ok(arg_types)
|
||||
} else {
|
||||
Err(vm.new_type_error("Function annotations aren't a dict".to_owned()))
|
||||
Err(vm.new_type_error("Function annotations aren't a dict"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@ pub fn jit_ret_type(func: &Py<PyFunction>, vm: &VirtualMachine) -> PyResult<Opti
|
||||
Ok(None)
|
||||
}
|
||||
} else {
|
||||
Err(vm.new_type_error("Function annotations aren't a dict".to_owned()))
|
||||
Err(vm.new_type_error("Function annotations aren't a dict"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ impl Constructor for PyGenericAlias {
|
||||
|
||||
fn py_new(cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult {
|
||||
if !args.kwargs.is_empty() {
|
||||
return Err(vm.new_type_error("GenericAlias() takes no keyword arguments".to_owned()));
|
||||
return Err(vm.new_type_error("GenericAlias() takes no keyword arguments"));
|
||||
}
|
||||
let (origin, arguments): (_, PyObjectRef) = args.bind(vm)?;
|
||||
PyGenericAlias::new(origin, arguments, vm)
|
||||
@@ -193,14 +193,12 @@ impl PyGenericAlias {
|
||||
|
||||
#[pymethod(magic)]
|
||||
fn instancecheck(_zelf: PyRef<Self>, _obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm
|
||||
.new_type_error("isinstance() argument 2 cannot be a parameterized generic".to_owned()))
|
||||
Err(vm.new_type_error("isinstance() argument 2 cannot be a parameterized generic"))
|
||||
}
|
||||
|
||||
#[pymethod(magic)]
|
||||
fn subclasscheck(_zelf: PyRef<Self>, _obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm
|
||||
.new_type_error("issubclass() argument 2 cannot be a parameterized generic".to_owned()))
|
||||
Err(vm.new_type_error("issubclass() argument 2 cannot be a parameterized generic"))
|
||||
}
|
||||
|
||||
#[pymethod(magic)]
|
||||
|
||||
+15
-24
@@ -121,7 +121,7 @@ fn inner_pow(int1: &BigInt, int2: &BigInt, vm: &VirtualMachine) -> PyResult {
|
||||
|
||||
fn inner_mod(int1: &BigInt, int2: &BigInt, vm: &VirtualMachine) -> PyResult {
|
||||
if int2.is_zero() {
|
||||
Err(vm.new_zero_division_error("integer modulo by zero".to_owned()))
|
||||
Err(vm.new_zero_division_error("integer modulo by zero"))
|
||||
} else {
|
||||
Ok(vm.ctx.new_int(int1.mod_floor(int2)).into())
|
||||
}
|
||||
@@ -129,7 +129,7 @@ fn inner_mod(int1: &BigInt, int2: &BigInt, vm: &VirtualMachine) -> PyResult {
|
||||
|
||||
fn inner_floordiv(int1: &BigInt, int2: &BigInt, vm: &VirtualMachine) -> PyResult {
|
||||
if int2.is_zero() {
|
||||
Err(vm.new_zero_division_error("integer division by zero".to_owned()))
|
||||
Err(vm.new_zero_division_error("integer division by zero"))
|
||||
} else {
|
||||
Ok(vm.ctx.new_int(int1.div_floor(int2)).into())
|
||||
}
|
||||
@@ -137,7 +137,7 @@ fn inner_floordiv(int1: &BigInt, int2: &BigInt, vm: &VirtualMachine) -> PyResult
|
||||
|
||||
fn inner_divmod(int1: &BigInt, int2: &BigInt, vm: &VirtualMachine) -> PyResult {
|
||||
if int2.is_zero() {
|
||||
return Err(vm.new_zero_division_error("integer division or modulo by zero".to_owned()));
|
||||
return Err(vm.new_zero_division_error("integer division or modulo by zero"));
|
||||
}
|
||||
let (div, modulo) = int1.div_mod_floor(int2);
|
||||
Ok(vm.new_tuple((div, modulo)).into())
|
||||
@@ -149,9 +149,8 @@ fn inner_lshift(base: &BigInt, bits: &BigInt, vm: &VirtualMachine) -> PyResult {
|
||||
bits,
|
||||
|base, bits| base << bits,
|
||||
|bits, vm| {
|
||||
bits.to_usize().ok_or_else(|| {
|
||||
vm.new_overflow_error("the number is too large to convert to int".to_owned())
|
||||
})
|
||||
bits.to_usize()
|
||||
.ok_or_else(|| vm.new_overflow_error("the number is too large to convert to int"))
|
||||
},
|
||||
vm,
|
||||
)
|
||||
@@ -179,7 +178,7 @@ where
|
||||
S: Fn(&BigInt, &VirtualMachine) -> PyResult<usize>,
|
||||
{
|
||||
if bits.is_negative() {
|
||||
Err(vm.new_value_error("negative shift count".to_owned()))
|
||||
Err(vm.new_value_error("negative shift count"))
|
||||
} else if base.is_zero() {
|
||||
Ok(vm.ctx.new_int(0).into())
|
||||
} else {
|
||||
@@ -189,7 +188,7 @@ where
|
||||
|
||||
fn inner_truediv(i1: &BigInt, i2: &BigInt, vm: &VirtualMachine) -> PyResult {
|
||||
if i2.is_zero() {
|
||||
return Err(vm.new_zero_division_error("division by zero".to_owned()));
|
||||
return Err(vm.new_zero_division_error("division by zero"));
|
||||
}
|
||||
|
||||
let float = true_div(i1, i2);
|
||||
@@ -209,9 +208,7 @@ impl Constructor for PyInt {
|
||||
|
||||
fn py_new(cls: PyTypeRef, options: Self::Args, vm: &VirtualMachine) -> PyResult {
|
||||
if cls.is(vm.ctx.types.bool_type) {
|
||||
return Err(
|
||||
vm.new_type_error("int.__new__(bool) is not safe, use bool.__new__()".to_owned())
|
||||
);
|
||||
return Err(vm.new_type_error("int.__new__(bool) is not safe, use bool.__new__()"));
|
||||
}
|
||||
|
||||
let value = if let OptionalArg::Present(val) = options.val_options {
|
||||
@@ -221,9 +218,7 @@ impl Constructor for PyInt {
|
||||
.as_bigint()
|
||||
.to_u32()
|
||||
.filter(|&v| v == 0 || (2..=36).contains(&v))
|
||||
.ok_or_else(|| {
|
||||
vm.new_value_error("int() base must be >= 2 and <= 36, or 0".to_owned())
|
||||
})?;
|
||||
.ok_or_else(|| vm.new_value_error("int() base must be >= 2 and <= 36, or 0"))?;
|
||||
try_int_radix(&val, base, vm)
|
||||
} else {
|
||||
let val = if cls.is(vm.ctx.types.int_type) {
|
||||
@@ -240,7 +235,7 @@ impl Constructor for PyInt {
|
||||
val.try_int(vm).map(|x| x.as_bigint().clone())
|
||||
}
|
||||
} else if let OptionalArg::Present(_) = options.base {
|
||||
Err(vm.new_type_error("int() missing string argument".to_owned()))
|
||||
Err(vm.new_type_error("int() missing string argument"))
|
||||
} else {
|
||||
Ok(Zero::zero())
|
||||
}?;
|
||||
@@ -411,7 +406,7 @@ impl PyInt {
|
||||
None => return Ok(vm.ctx.not_implemented()),
|
||||
};
|
||||
if modulus.is_zero() {
|
||||
return Err(vm.new_value_error("pow() 3rd argument cannot be 0".to_owned()));
|
||||
return Err(vm.new_value_error("pow() 3rd argument cannot be 0"));
|
||||
}
|
||||
|
||||
self.general_op(
|
||||
@@ -434,9 +429,7 @@ impl PyInt {
|
||||
}
|
||||
}
|
||||
let a = inverse(a % modulus, modulus).ok_or_else(|| {
|
||||
vm.new_value_error(
|
||||
"base is not invertible for the given modulus".to_owned(),
|
||||
)
|
||||
vm.new_value_error("base is not invertible for the given modulus")
|
||||
})?;
|
||||
let b = -b;
|
||||
a.modpow(&b, modulus)
|
||||
@@ -633,9 +626,7 @@ impl PyInt {
|
||||
let value = self.as_bigint();
|
||||
match value.sign() {
|
||||
Sign::Minus if !signed => {
|
||||
return Err(
|
||||
vm.new_overflow_error("can't convert negative int to unsigned".to_owned())
|
||||
);
|
||||
return Err(vm.new_overflow_error("can't convert negative int to unsigned"));
|
||||
}
|
||||
Sign::NoSign => return Ok(vec![0u8; byte_len].into()),
|
||||
_ => {}
|
||||
@@ -650,7 +641,7 @@ impl PyInt {
|
||||
|
||||
let origin_len = origin_bytes.len();
|
||||
if origin_len > byte_len {
|
||||
return Err(vm.new_overflow_error("int too big to convert".to_owned()));
|
||||
return Err(vm.new_overflow_error("int too big to convert"));
|
||||
}
|
||||
|
||||
let mut append_bytes = match value.sign() {
|
||||
@@ -882,7 +873,7 @@ pub(crate) fn get_value(obj: &PyObject) -> &BigInt {
|
||||
|
||||
pub fn try_to_float(int: &BigInt, vm: &VirtualMachine) -> PyResult<f64> {
|
||||
bigint_to_finite_float(int)
|
||||
.ok_or_else(|| vm.new_overflow_error("int too large to convert to float".to_owned()))
|
||||
.ok_or_else(|| vm.new_overflow_error("int too large to convert to float"))
|
||||
}
|
||||
|
||||
pub(crate) fn init(context: &Context) {
|
||||
|
||||
@@ -64,7 +64,7 @@ impl<T> PositionIterInternal<T> {
|
||||
self.position = f(obj, i);
|
||||
Ok(())
|
||||
} else {
|
||||
Err(vm.new_type_error("an integer is required.".to_owned()))
|
||||
Err(vm.new_type_error("an integer is required."))
|
||||
}
|
||||
} else {
|
||||
Ok(())
|
||||
|
||||
@@ -279,9 +279,9 @@ impl PyList {
|
||||
i += elements.len() as isize;
|
||||
}
|
||||
if elements.is_empty() {
|
||||
Err(vm.new_index_error("pop from empty list".to_owned()))
|
||||
Err(vm.new_index_error("pop from empty list"))
|
||||
} else if i < 0 || i as usize >= elements.len() {
|
||||
Err(vm.new_index_error("pop index out of range".to_owned()))
|
||||
Err(vm.new_index_error("pop index out of range"))
|
||||
} else {
|
||||
Ok(elements.remove(i as usize))
|
||||
}
|
||||
@@ -324,7 +324,7 @@ impl PyList {
|
||||
res?;
|
||||
|
||||
if !elements.is_empty() {
|
||||
return Err(vm.new_value_error("list modified during sort".to_owned()));
|
||||
return Err(vm.new_value_error("list modified during sort"));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
+30
-42
@@ -134,7 +134,7 @@ impl PyMemoryView {
|
||||
|
||||
fn try_not_released(&self, vm: &VirtualMachine) -> PyResult<()> {
|
||||
if self.released.load() {
|
||||
Err(vm.new_value_error("operation forbidden on released memoryview object".to_owned()))
|
||||
Err(vm.new_value_error("operation forbidden on released memoryview object"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
@@ -142,14 +142,14 @@ impl PyMemoryView {
|
||||
|
||||
fn getitem_by_idx(&self, i: isize, vm: &VirtualMachine) -> PyResult {
|
||||
if self.desc.ndim() != 1 {
|
||||
return Err(vm.new_not_implemented_error(
|
||||
"multi-dimensional sub-views are not implemented".to_owned(),
|
||||
));
|
||||
return Err(
|
||||
vm.new_not_implemented_error("multi-dimensional sub-views are not implemented")
|
||||
);
|
||||
}
|
||||
let (shape, stride, suboffset) = self.desc.dim_desc[0];
|
||||
let index = i
|
||||
.wrapped_at(shape)
|
||||
.ok_or_else(|| vm.new_index_error("index out of range".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_index_error("index out of range"))?;
|
||||
let index = index as isize * stride + suboffset;
|
||||
let pos = (index + self.start as isize) as usize;
|
||||
self.unpack_single(pos, vm)
|
||||
@@ -171,12 +171,12 @@ impl PyMemoryView {
|
||||
|
||||
fn setitem_by_idx(&self, i: isize, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
if self.desc.ndim() != 1 {
|
||||
return Err(vm.new_not_implemented_error("sub-views are not implemented".to_owned()));
|
||||
return Err(vm.new_not_implemented_error("sub-views are not implemented"));
|
||||
}
|
||||
let (shape, stride, suboffset) = self.desc.dim_desc[0];
|
||||
let index = i
|
||||
.wrapped_at(shape)
|
||||
.ok_or_else(|| vm.new_index_error("index out of range".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_index_error("index out of range"))?;
|
||||
let index = index as isize * stride + suboffset;
|
||||
let pos = (index + self.start as isize) as usize;
|
||||
self.pack_single(pos, value, vm)
|
||||
@@ -222,9 +222,7 @@ impl PyMemoryView {
|
||||
fn pos_from_multi_index(&self, indexes: &[isize], vm: &VirtualMachine) -> PyResult<usize> {
|
||||
match indexes.len().cmp(&self.desc.ndim()) {
|
||||
Ordering::Less => {
|
||||
return Err(
|
||||
vm.new_not_implemented_error("sub-views are not implemented".to_owned())
|
||||
);
|
||||
return Err(vm.new_not_implemented_error("sub-views are not implemented"));
|
||||
}
|
||||
Ordering::Greater => {
|
||||
return Err(vm.new_type_error(format!(
|
||||
@@ -492,7 +490,7 @@ impl Py<PyMemoryView> {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<()> {
|
||||
if self.desc.ndim() != 1 {
|
||||
return Err(vm.new_not_implemented_error("sub-view are not implemented".to_owned()));
|
||||
return Err(vm.new_not_implemented_error("sub-view are not implemented"));
|
||||
}
|
||||
|
||||
let mut dest = self.new_view();
|
||||
@@ -502,7 +500,7 @@ impl Py<PyMemoryView> {
|
||||
if self.is(&src) {
|
||||
return if !is_equiv_structure(&self.desc, &dest.desc) {
|
||||
Err(vm.new_value_error(
|
||||
"memoryview assignment: lvalue and rvalue have different structures".to_owned(),
|
||||
"memoryview assignment: lvalue and rvalue have different structures",
|
||||
))
|
||||
} else {
|
||||
// assign self[:] to self
|
||||
@@ -522,7 +520,7 @@ impl Py<PyMemoryView> {
|
||||
|
||||
if !is_equiv_structure(&src.desc, &dest.desc) {
|
||||
return Err(vm.new_value_error(
|
||||
"memoryview assignment: lvalue and rvalue have different structures".to_owned(),
|
||||
"memoryview assignment: lvalue and rvalue have different structures",
|
||||
));
|
||||
}
|
||||
|
||||
@@ -666,7 +664,7 @@ impl PyMemoryView {
|
||||
return zelf.unpack_single(0, vm);
|
||||
}
|
||||
}
|
||||
return Err(vm.new_type_error("invalid indexing of 0-dim memory".to_owned()));
|
||||
return Err(vm.new_type_error("invalid indexing of 0-dim memory"));
|
||||
}
|
||||
|
||||
match SubscriptNeedle::try_from_object(vm, needle)? {
|
||||
@@ -679,9 +677,9 @@ impl PyMemoryView {
|
||||
#[pymethod(magic)]
|
||||
fn delitem(&self, _needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
if self.desc.readonly {
|
||||
return Err(vm.new_type_error("cannot modify read-only memory".to_owned()));
|
||||
return Err(vm.new_type_error("cannot modify read-only memory"));
|
||||
}
|
||||
Err(vm.new_type_error("cannot delete memory".to_owned()))
|
||||
Err(vm.new_type_error("cannot delete memory"))
|
||||
}
|
||||
|
||||
#[pymethod(magic)]
|
||||
@@ -740,9 +738,7 @@ impl PyMemoryView {
|
||||
let format_spec = Self::parse_format(format.as_str(), vm)?;
|
||||
let itemsize = format_spec.size();
|
||||
if self.desc.len % itemsize != 0 {
|
||||
return Err(
|
||||
vm.new_type_error("memoryview: length is not a multiple of itemsize".to_owned())
|
||||
);
|
||||
return Err(vm.new_type_error("memoryview: length is not a multiple of itemsize"));
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
@@ -765,9 +761,7 @@ impl PyMemoryView {
|
||||
fn cast(&self, args: CastArgs, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
|
||||
self.try_not_released(vm)?;
|
||||
if !self.desc.is_contiguous() {
|
||||
return Err(vm.new_type_error(
|
||||
"memoryview: casts are restricted to C-contiguous views".to_owned(),
|
||||
));
|
||||
return Err(vm.new_type_error("memoryview: casts are restricted to C-contiguous views"));
|
||||
}
|
||||
|
||||
let CastArgs { format, shape } = args;
|
||||
@@ -775,7 +769,7 @@ impl PyMemoryView {
|
||||
if let OptionalArg::Present(shape) = shape {
|
||||
if self.desc.is_zero_in_shape() {
|
||||
return Err(vm.new_type_error(
|
||||
"memoryview: cannot cast view with zeros in shape or strides".to_owned(),
|
||||
"memoryview: cannot cast view with zeros in shape or strides",
|
||||
));
|
||||
}
|
||||
|
||||
@@ -797,9 +791,7 @@ impl PyMemoryView {
|
||||
let shape_ndim = shape.len();
|
||||
// TODO: MAX_NDIM
|
||||
if self.desc.ndim() != 1 && shape_ndim != 1 {
|
||||
return Err(
|
||||
vm.new_type_error("memoryview: cast must be 1D -> ND or ND -> 1D".to_owned())
|
||||
);
|
||||
return Err(vm.new_type_error("memoryview: cast must be 1D -> ND or ND -> 1D"));
|
||||
}
|
||||
|
||||
let mut other = self.cast_to_1d(format, vm)?;
|
||||
@@ -819,9 +811,7 @@ impl PyMemoryView {
|
||||
let x = usize::try_from_borrowed_object(vm, x)?;
|
||||
|
||||
if x > isize::MAX as usize / product_shape {
|
||||
return Err(vm.new_value_error(
|
||||
"memoryview.cast(): product(shape) > SSIZE_MAX".to_owned(),
|
||||
));
|
||||
return Err(vm.new_value_error("memoryview.cast(): product(shape) > SSIZE_MAX"));
|
||||
}
|
||||
product_shape *= x;
|
||||
dim_descriptor.push((x, 0, 0));
|
||||
@@ -833,9 +823,9 @@ impl PyMemoryView {
|
||||
}
|
||||
|
||||
if product_shape != other.desc.len {
|
||||
return Err(vm.new_type_error(
|
||||
"memoryview: product(shape) * itemsize != buffer size".to_owned(),
|
||||
));
|
||||
return Err(
|
||||
vm.new_type_error("memoryview: product(shape) * itemsize != buffer size")
|
||||
);
|
||||
}
|
||||
|
||||
other.desc.dim_desc = dim_descriptor;
|
||||
@@ -858,10 +848,10 @@ impl Py<PyMemoryView> {
|
||||
) -> PyResult<()> {
|
||||
self.try_not_released(vm)?;
|
||||
if self.desc.readonly {
|
||||
return Err(vm.new_type_error("cannot modify read-only memory".to_owned()));
|
||||
return Err(vm.new_type_error("cannot modify read-only memory"));
|
||||
}
|
||||
if value.is(&vm.ctx.none) {
|
||||
return Err(vm.new_type_error("cannot delete memory".to_owned()));
|
||||
return Err(vm.new_type_error("cannot delete memory"));
|
||||
}
|
||||
|
||||
if self.desc.ndim() == 0 {
|
||||
@@ -873,7 +863,7 @@ impl Py<PyMemoryView> {
|
||||
return self.pack_single(0, value, vm);
|
||||
}
|
||||
}
|
||||
return Err(vm.new_type_error("invalid indexing of 0-dim memory".to_owned()));
|
||||
return Err(vm.new_type_error("invalid indexing of 0-dim memory"));
|
||||
}
|
||||
match SubscriptNeedle::try_from_object(vm, needle)? {
|
||||
SubscriptNeedle::Index(i) => self.setitem_by_idx(i, value, vm),
|
||||
@@ -889,7 +879,7 @@ impl Py<PyMemoryView> {
|
||||
|
||||
#[pymethod(magic)]
|
||||
fn reduce(&self, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_type_error("cannot pickle 'memoryview' object".to_owned()))
|
||||
Err(vm.new_type_error("cannot pickle 'memoryview' object"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -930,11 +920,11 @@ impl TryFromObject for SubscriptNeedle {
|
||||
return Ok(Self::MultiIndex(v));
|
||||
} else if tuple.iter().all(|x| x.payload_is::<PySlice>()) {
|
||||
return Err(vm.new_not_implemented_error(
|
||||
"multi-dimensional slicing is not implemented".to_owned(),
|
||||
"multi-dimensional slicing is not implemented",
|
||||
));
|
||||
}
|
||||
}
|
||||
Err(vm.new_type_error("memoryview: invalid slice key".to_owned()))
|
||||
Err(vm.new_type_error("memoryview: invalid slice key"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -949,7 +939,7 @@ static BUFFER_METHODS: BufferMethods = BufferMethods {
|
||||
impl AsBuffer for PyMemoryView {
|
||||
fn as_buffer(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyBuffer> {
|
||||
if zelf.released.load() {
|
||||
Err(vm.new_value_error("operation forbidden on released memoryview object".to_owned()))
|
||||
Err(vm.new_value_error("operation forbidden on released memoryview object"))
|
||||
} else {
|
||||
Ok(PyBuffer::new(
|
||||
zelf.to_owned().into(),
|
||||
@@ -1038,9 +1028,7 @@ impl Hashable for PyMemoryView {
|
||||
.get_or_try_init(|| {
|
||||
zelf.try_not_released(vm)?;
|
||||
if !zelf.desc.readonly {
|
||||
return Err(
|
||||
vm.new_value_error("cannot hash writable memoryview object".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("cannot hash writable memoryview object"));
|
||||
}
|
||||
Ok(zelf.contiguous_or_collect(|bytes| vm.state.hash_secret.hash_bytes(bytes)))
|
||||
})
|
||||
|
||||
@@ -174,7 +174,7 @@ impl PyModule {
|
||||
let dict_attr = zelf.as_object().get_attr(identifier!(vm, __dict__), vm)?;
|
||||
let dict = dict_attr
|
||||
.downcast::<PyDict>()
|
||||
.map_err(|_| vm.new_type_error("<module>.__dict__ is not a dictionary".to_owned()))?;
|
||||
.map_err(|_| vm.new_type_error("<module>.__dict__ is not a dictionary"))?;
|
||||
let attrs = dict.into_iter().map(|(k, _v)| k).collect();
|
||||
Ok(attrs)
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ impl Initializer for PyNamespace {
|
||||
|
||||
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
|
||||
if !args.args.is_empty() {
|
||||
return Err(vm.new_type_error("no positional arguments expected".to_owned()));
|
||||
return Err(vm.new_type_error("no positional arguments expected"));
|
||||
}
|
||||
for (name, value) in args.kwargs.into_iter() {
|
||||
let name = vm.ctx.new_str(name);
|
||||
|
||||
@@ -121,8 +121,8 @@ fn object_getstate_default(obj: &PyObject, required: bool, vm: &VirtualMachine)
|
||||
state.into()
|
||||
};
|
||||
|
||||
let slot_names = type_slot_names(obj.class(), vm)
|
||||
.map_err(|_| vm.new_type_error("cannot pickle object".to_owned()))?;
|
||||
let slot_names =
|
||||
type_slot_names(obj.class(), vm).map_err(|_| vm.new_type_error("cannot pickle object"))?;
|
||||
|
||||
if required {
|
||||
let mut basicsize = obj.class().slots.basicsize;
|
||||
@@ -426,8 +426,7 @@ impl PyBaseObject {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(vm.new_type_error(
|
||||
"__class__ assignment only supported for mutable types or ModuleType subclasses"
|
||||
.to_owned(),
|
||||
"__class__ assignment only supported for mutable types or ModuleType subclasses",
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -491,11 +490,11 @@ impl PyBaseObject {
|
||||
|
||||
pub fn object_get_dict(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyDictRef> {
|
||||
obj.dict()
|
||||
.ok_or_else(|| vm.new_attribute_error("This object has no __dict__".to_owned()))
|
||||
.ok_or_else(|| vm.new_attribute_error("This object has no __dict__"))
|
||||
}
|
||||
pub fn object_set_dict(obj: PyObjectRef, dict: PyDictRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
obj.set_dict(dict)
|
||||
.map_err(|_| vm.new_attribute_error("This object has no __dict__".to_owned()))
|
||||
.map_err(|_| vm.new_attribute_error("This object has no __dict__"))
|
||||
}
|
||||
|
||||
pub fn init(ctx: &Context) {
|
||||
|
||||
@@ -200,7 +200,7 @@ impl PyRange {
|
||||
) -> PyResult<PyRef<Self>> {
|
||||
let step = step.map_or_else(|| vm.ctx.new_int(1), |step| step.into());
|
||||
if step.as_bigint().is_zero() {
|
||||
return Err(vm.new_value_error("range() arg 3 must not be zero".to_owned()));
|
||||
return Err(vm.new_value_error("range() arg 3 must not be zero"));
|
||||
}
|
||||
PyRange {
|
||||
start: start.try_index(vm)?,
|
||||
@@ -304,7 +304,7 @@ impl PyRange {
|
||||
}
|
||||
RangeIndex::Int(index) => match self.get(index.as_bigint()) {
|
||||
Some(value) => Ok(vm.ctx.new_int(value).into()),
|
||||
None => Err(vm.new_index_error("range object index out of range".to_owned())),
|
||||
None => Err(vm.new_index_error("range object index out of range")),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -675,7 +675,7 @@ fn range_state(length: &BigInt, state: PyObjectRef, vm: &VirtualMachine) -> PyRe
|
||||
}
|
||||
Ok(index.to_usize().unwrap_or(0))
|
||||
} else {
|
||||
Err(vm.new_type_error("an integer is required.".to_owned()))
|
||||
Err(vm.new_type_error("an integer is required."))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1308,7 +1308,7 @@ impl IterNext for PySetIterator {
|
||||
let next = if let IterStatus::Active(dict) = &internal.status {
|
||||
if dict.has_changed_size(&zelf.size) {
|
||||
internal.status = IterStatus::Exhausted;
|
||||
return Err(vm.new_runtime_error("set changed size during iteration".to_owned()));
|
||||
return Err(vm.new_runtime_error("set changed size during iteration"));
|
||||
}
|
||||
match dict.next_entry(internal.position) {
|
||||
Some((position, key, _)) => {
|
||||
|
||||
@@ -66,9 +66,7 @@ impl PySlice {
|
||||
fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
let slice: PySlice = match args.args.len() {
|
||||
0 => {
|
||||
return Err(
|
||||
vm.new_type_error("slice() must have at least one arguments.".to_owned())
|
||||
);
|
||||
return Err(vm.new_type_error("slice() must have at least one arguments."));
|
||||
}
|
||||
1 => {
|
||||
let stop = args.bind(vm)?;
|
||||
@@ -106,7 +104,7 @@ impl PySlice {
|
||||
step = this_step.as_bigint().clone();
|
||||
|
||||
if step.is_zero() {
|
||||
return Err(vm.new_value_error("slice step cannot be zero.".to_owned()));
|
||||
return Err(vm.new_value_error("slice step cannot be zero."));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,7 +175,7 @@ impl PySlice {
|
||||
fn indices(&self, length: ArgIndex, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
|
||||
let length = length.as_bigint();
|
||||
if length.is_negative() {
|
||||
return Err(vm.new_value_error("length should not be negative.".to_owned()));
|
||||
return Err(vm.new_value_error("length should not be negative."));
|
||||
}
|
||||
let (start, stop, step) = self.inner_indices(length, vm)?;
|
||||
Ok(vm.new_tuple((start, stop, step)))
|
||||
|
||||
+13
-18
@@ -619,7 +619,7 @@ impl PyStr {
|
||||
UnicodeEscape::new_repr(self.as_wtf8())
|
||||
.str_repr()
|
||||
.to_string()
|
||||
.ok_or_else(|| vm.new_overflow_error("string is too long to generate repr".to_owned()))
|
||||
.ok_or_else(|| vm.new_overflow_error("string is too long to generate repr"))
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
@@ -1165,13 +1165,13 @@ impl PyStr {
|
||||
#[pymethod]
|
||||
fn index(&self, args: FindArgs, vm: &VirtualMachine) -> PyResult<usize> {
|
||||
self._find(args, |r, s| Some(Self::_to_char_idx(r, r.find(s)?)))
|
||||
.ok_or_else(|| vm.new_value_error("substring not found".to_owned()))
|
||||
.ok_or_else(|| vm.new_value_error("substring not found"))
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn rindex(&self, args: FindArgs, vm: &VirtualMachine) -> PyResult<usize> {
|
||||
self._find(args, |r, s| Some(Self::_to_char_idx(r, r.rfind(s)?)))
|
||||
.ok_or_else(|| vm.new_value_error("substring not found".to_owned()))
|
||||
.ok_or_else(|| vm.new_value_error("substring not found"))
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
@@ -1267,9 +1267,7 @@ impl PyStr {
|
||||
) -> PyResult<Wtf8Buf> {
|
||||
let fillchar = fillchar.map_or(Ok(' '.into()), |ref s| {
|
||||
s.as_wtf8().code_points().exactly_one().map_err(|_| {
|
||||
vm.new_type_error(
|
||||
"The fill character must be exactly one character long".to_owned(),
|
||||
)
|
||||
vm.new_type_error("The fill character must be exactly one character long")
|
||||
})
|
||||
})?;
|
||||
Ok(if self.len() as isize >= width {
|
||||
@@ -1342,15 +1340,13 @@ impl PyStr {
|
||||
.to_u32()
|
||||
.and_then(std::char::from_u32)
|
||||
.ok_or_else(|| {
|
||||
vm.new_value_error(
|
||||
"character mapping must be in range(0x110000)".to_owned(),
|
||||
)
|
||||
vm.new_value_error("character mapping must be in range(0x110000)")
|
||||
})?;
|
||||
translated.push(ch);
|
||||
} else if !vm.is_none(&value) {
|
||||
return Err(vm.new_type_error(
|
||||
"character mapping must return integer, None or str".to_owned(),
|
||||
));
|
||||
return Err(
|
||||
vm.new_type_error("character mapping must return integer, None or str")
|
||||
);
|
||||
}
|
||||
}
|
||||
_ => translated.push(c),
|
||||
@@ -1386,13 +1382,12 @@ impl PyStr {
|
||||
Ok(new_dict.to_pyobject(vm))
|
||||
} else {
|
||||
Err(vm.new_value_error(
|
||||
"the first two maketrans arguments must have equal length".to_owned(),
|
||||
"the first two maketrans arguments must have equal length",
|
||||
))
|
||||
}
|
||||
}
|
||||
_ => Err(vm.new_type_error(
|
||||
"first maketrans argument must be a string if there is a second argument"
|
||||
.to_owned(),
|
||||
"first maketrans argument must be a string if there is a second argument",
|
||||
)),
|
||||
}
|
||||
} else {
|
||||
@@ -1413,19 +1408,19 @@ impl PyStr {
|
||||
new_dict.set_item(&*num_value.to_pyobject(vm), val, vm)?;
|
||||
} else {
|
||||
return Err(vm.new_value_error(
|
||||
"string keys in translate table must be of length 1".to_owned(),
|
||||
"string keys in translate table must be of length 1",
|
||||
));
|
||||
}
|
||||
} else {
|
||||
return Err(vm.new_type_error(
|
||||
"keys in translate table must be strings or integers".to_owned(),
|
||||
"keys in translate table must be strings or integers",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(new_dict.to_pyobject(vm))
|
||||
}
|
||||
_ => Err(vm.new_value_error(
|
||||
"if you give only one argument to maketrans it must be a dict".to_owned(),
|
||||
"if you give only one argument to maketrans it must be a dict",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,10 +81,10 @@ impl Initializer for PySuper {
|
||||
} else {
|
||||
let frame = vm
|
||||
.current_frame()
|
||||
.ok_or_else(|| vm.new_runtime_error("super(): no current frame".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_runtime_error("super(): no current frame"))?;
|
||||
|
||||
if frame.code.arg_count == 0 {
|
||||
return Err(vm.new_runtime_error("super(): no arguments".to_owned()));
|
||||
return Err(vm.new_runtime_error("super(): no arguments"));
|
||||
}
|
||||
let obj = frame.fastlocals.lock()[0]
|
||||
.clone()
|
||||
@@ -99,15 +99,15 @@ impl Initializer for PySuper {
|
||||
None
|
||||
}
|
||||
})
|
||||
.ok_or_else(|| vm.new_runtime_error("super(): arg[0] deleted".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_runtime_error("super(): arg[0] deleted"))?;
|
||||
|
||||
let mut typ = None;
|
||||
for (i, var) in frame.code.freevars.iter().enumerate() {
|
||||
if var.as_str() == "__class__" {
|
||||
let i = frame.code.cellvars.len() + i;
|
||||
let class = frame.cells_frees[i].get().ok_or_else(|| {
|
||||
vm.new_runtime_error("super(): empty __class__ cell".to_owned())
|
||||
})?;
|
||||
let class = frame.cells_frees[i]
|
||||
.get()
|
||||
.ok_or_else(|| vm.new_runtime_error("super(): empty __class__ cell"))?;
|
||||
typ = Some(class.downcast().map_err(|o| {
|
||||
vm.new_type_error(format!(
|
||||
"super(): __class__ is not a type ({})",
|
||||
@@ -119,7 +119,7 @@ impl Initializer for PySuper {
|
||||
}
|
||||
let typ = typ.ok_or_else(|| {
|
||||
vm.new_type_error(
|
||||
"super must be called with 1 argument or from inside class method".to_owned(),
|
||||
"super must be called with 1 argument or from inside class method",
|
||||
)
|
||||
})?;
|
||||
|
||||
@@ -252,8 +252,7 @@ fn super_check(ty: PyTypeRef, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult
|
||||
return Ok(cls);
|
||||
}
|
||||
}
|
||||
Err(vm
|
||||
.new_type_error("super(type, obj): obj must be an instance or subtype of type".to_owned()))
|
||||
Err(vm.new_type_error("super(type, obj): obj must be an instance or subtype of type"))
|
||||
}
|
||||
|
||||
pub fn init(context: &Context) {
|
||||
|
||||
@@ -312,7 +312,7 @@ impl PyTuple {
|
||||
return Ok(index);
|
||||
}
|
||||
}
|
||||
Err(vm.new_value_error("tuple.index(x): x not in tuple".to_owned()))
|
||||
Err(vm.new_value_error("tuple.index(x): x not in tuple"))
|
||||
}
|
||||
|
||||
fn _contains(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
|
||||
+7
-11
@@ -738,7 +738,7 @@ impl PyType {
|
||||
#[pygetset(magic, setter)]
|
||||
fn set_dict(&self, _value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
Err(vm.new_not_implemented_error(
|
||||
"Setting __dict__ attribute on a type isn't yet implemented".to_owned(),
|
||||
"Setting __dict__ attribute on a type isn't yet implemented",
|
||||
))
|
||||
}
|
||||
|
||||
@@ -769,7 +769,7 @@ impl PyType {
|
||||
))
|
||||
})?;
|
||||
if name.as_bytes().contains(&0) {
|
||||
return Err(vm.new_value_error("type name must not contain null characters".to_owned()));
|
||||
return Err(vm.new_value_error("type name must not contain null characters"));
|
||||
}
|
||||
|
||||
*self.heaptype_ext.as_ref().unwrap().name.write() = name;
|
||||
@@ -812,7 +812,7 @@ impl Constructor for PyType {
|
||||
args.clone().bind(vm)?;
|
||||
|
||||
if name.as_bytes().contains(&0) {
|
||||
return Err(vm.new_value_error("type name must not contain null characters".to_owned()));
|
||||
return Err(vm.new_value_error("type name must not contain null characters"));
|
||||
}
|
||||
|
||||
let (metatype, base, bases) = if bases.is_empty() {
|
||||
@@ -829,11 +829,10 @@ impl Constructor for PyType {
|
||||
{
|
||||
Err(vm.new_type_error(
|
||||
"type() doesn't support MRO entry resolution; \
|
||||
use types.new_class()"
|
||||
.to_owned(),
|
||||
use types.new_class()",
|
||||
))
|
||||
} else {
|
||||
Err(vm.new_type_error("bases must be types".to_owned()))
|
||||
Err(vm.new_type_error("bases must be types"))
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -1463,8 +1462,7 @@ fn calculate_meta_class(
|
||||
|
||||
return Err(vm.new_type_error(
|
||||
"metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass \
|
||||
of the metaclasses of all its bases"
|
||||
.to_owned(),
|
||||
of the metaclasses of all its bases",
|
||||
));
|
||||
}
|
||||
Ok(winner)
|
||||
@@ -1512,9 +1510,7 @@ fn best_base<'a>(bases: &'a [PyTypeRef], vm: &VirtualMachine) -> PyResult<&'a Py
|
||||
winner = Some(candidate);
|
||||
base = Some(base_i.deref());
|
||||
} else {
|
||||
return Err(
|
||||
vm.new_type_error("multiple bases have instance layout conflict".to_string())
|
||||
);
|
||||
return Err(vm.new_type_error("multiple bases have instance layout conflict"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -101,9 +101,7 @@ impl PyUnion {
|
||||
.iter()
|
||||
.any(|x| x.class().is(vm.ctx.types.generic_alias_type))
|
||||
{
|
||||
Err(vm.new_type_error(
|
||||
"isinstance() argument 2 cannot be a parameterized generic".to_owned(),
|
||||
))
|
||||
Err(vm.new_type_error("isinstance() argument 2 cannot be a parameterized generic"))
|
||||
} else {
|
||||
obj.is_instance(zelf.args().as_object(), vm)
|
||||
}
|
||||
@@ -116,9 +114,7 @@ impl PyUnion {
|
||||
.iter()
|
||||
.any(|x| x.class().is(vm.ctx.types.generic_alias_type))
|
||||
{
|
||||
Err(vm.new_type_error(
|
||||
"issubclass() argument 2 cannot be a parameterized generic".to_owned(),
|
||||
))
|
||||
Err(vm.new_type_error("issubclass() argument 2 cannot be a parameterized generic"))
|
||||
} else {
|
||||
obj.is_subclass(zelf.args().as_object(), vm)
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ impl Hashable for PyWeak {
|
||||
hash::SENTINEL => {
|
||||
let obj = zelf
|
||||
.upgrade()
|
||||
.ok_or_else(|| vm.new_type_error("weak object has gone away".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_type_error("weak object has gone away"))?;
|
||||
let hash = obj.hash(vm)?;
|
||||
match Radium::compare_exchange(
|
||||
&zelf.hash,
|
||||
|
||||
+2
-4
@@ -14,14 +14,12 @@ pub fn bytes_from_object(vm: &VirtualMachine, obj: &PyObject) -> PyResult<Vec<u8
|
||||
}
|
||||
}
|
||||
|
||||
Err(vm.new_type_error(
|
||||
"can assign only bytes, buffers, or iterables of ints in range(0, 256)".to_owned(),
|
||||
))
|
||||
Err(vm.new_type_error("can assign only bytes, buffers, or iterables of ints in range(0, 256)"))
|
||||
}
|
||||
|
||||
pub fn value_from_object(vm: &VirtualMachine, obj: &PyObject) -> PyResult<u8> {
|
||||
obj.try_index(vm)?
|
||||
.as_bigint()
|
||||
.to_u8()
|
||||
.ok_or_else(|| vm.new_value_error("byte must be in range(0, 256)".to_owned()))
|
||||
.ok_or_else(|| vm.new_value_error("byte must be in range(0, 256)"))
|
||||
}
|
||||
+13
-16
@@ -67,11 +67,12 @@ impl ByteInnerNewOptions {
|
||||
}
|
||||
|
||||
fn get_value_from_size(size: PyIntRef, vm: &VirtualMachine) -> PyResult<PyBytesInner> {
|
||||
let size = size.as_bigint().to_isize().ok_or_else(|| {
|
||||
vm.new_overflow_error("cannot fit 'int' into an index-sized integer".to_owned())
|
||||
})?;
|
||||
let size = size
|
||||
.as_bigint()
|
||||
.to_isize()
|
||||
.ok_or_else(|| vm.new_overflow_error("cannot fit 'int' into an index-sized integer"))?;
|
||||
let size = if size < 0 {
|
||||
return Err(vm.new_value_error("negative count".to_owned()));
|
||||
return Err(vm.new_value_error("negative count"));
|
||||
} else {
|
||||
size as usize
|
||||
};
|
||||
@@ -164,7 +165,7 @@ impl ByteInnerNewOptions {
|
||||
Err(vm.new_type_error(ENCODING_WITHOUT_STRING.to_owned()))
|
||||
}
|
||||
(OptionalArg::Missing, _, OptionalArg::Present(_)) => {
|
||||
Err(vm.new_type_error("errors without a string argument".to_owned()))
|
||||
Err(vm.new_type_error("errors without a string argument"))
|
||||
}
|
||||
(OptionalArg::Present(_), OptionalArg::Missing, OptionalArg::Present(_)) => {
|
||||
Err(vm.new_type_error(STRING_WITHOUT_ENCODING.to_owned()))
|
||||
@@ -244,9 +245,7 @@ impl ByteInnerTranslateOptions {
|
||||
.ok()
|
||||
.filter(|v| v.elements.len() == 256)
|
||||
.ok_or_else(|| {
|
||||
vm.new_value_error(
|
||||
"translation table must be 256 characters long".to_owned(),
|
||||
)
|
||||
vm.new_value_error("translation table must be 256 characters long")
|
||||
})?;
|
||||
Ok(bytes.elements.to_vec())
|
||||
},
|
||||
@@ -273,7 +272,7 @@ impl PyBytesInner {
|
||||
}
|
||||
|
||||
fn new_repr_overflow_error(vm: &VirtualMachine) -> PyBaseExceptionRef {
|
||||
vm.new_overflow_error("bytes object is too large to make repr".to_owned())
|
||||
vm.new_overflow_error("bytes object is too large to make repr")
|
||||
}
|
||||
|
||||
pub fn repr_with_name(&self, class_name: &str, vm: &VirtualMachine) -> PyResult<String> {
|
||||
@@ -582,9 +581,7 @@ impl PyBytesInner {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<Vec<u8>> {
|
||||
if from.len() != to.len() {
|
||||
return Err(
|
||||
vm.new_value_error("the two maketrans arguments must have equal length".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("the two maketrans arguments must have equal length"));
|
||||
}
|
||||
let mut res = vec![];
|
||||
|
||||
@@ -873,7 +870,7 @@ impl PyBytesInner {
|
||||
if to.len() as isize - from.len() as isize
|
||||
> (isize::MAX - self.elements.len() as isize) / count as isize
|
||||
{
|
||||
return Err(vm.new_overflow_error("replace bytes is too long".to_owned()));
|
||||
return Err(vm.new_overflow_error("replace bytes is too long"));
|
||||
}
|
||||
let result_len = (self.elements.len() as isize
|
||||
+ count as isize * (to.len() as isize - from.len() as isize))
|
||||
@@ -1024,7 +1021,7 @@ pub trait ByteOr: ToPrimitive {
|
||||
fn byte_or(&self, vm: &VirtualMachine) -> PyResult<u8> {
|
||||
match self.to_u8() {
|
||||
Some(value) => Ok(value),
|
||||
None => Err(vm.new_value_error("byte must be in range(0, 256)".to_owned())),
|
||||
None => Err(vm.new_value_error("byte must be in range(0, 256)")),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1254,11 +1251,11 @@ pub fn bytes_to_hex(
|
||||
};
|
||||
|
||||
if sep.len() != 1 {
|
||||
return Err(vm.new_value_error("sep must be length 1.".to_owned()));
|
||||
return Err(vm.new_value_error("sep must be length 1."));
|
||||
}
|
||||
let sep = sep[0];
|
||||
if sep > 127 {
|
||||
return Err(vm.new_value_error("sep must be ASCII.".to_owned()));
|
||||
return Err(vm.new_value_error("sep must be ASCII."));
|
||||
}
|
||||
|
||||
Ok(hex_impl(bytes, sep, bytes_per_sep))
|
||||
|
||||
+17
-25
@@ -104,7 +104,7 @@ fn spec_format_bytes(
|
||||
if let Some(i) = obj.payload::<PyInt>() {
|
||||
let ch = i
|
||||
.try_to_primitive::<u8>(vm)
|
||||
.map_err(|_| vm.new_overflow_error("%c arg not in range(256)".to_owned()))?;
|
||||
.map_err(|_| vm.new_overflow_error("%c arg not in range(256)"))?;
|
||||
return Ok(spec.format_char(ch));
|
||||
}
|
||||
if let Some(b) = obj.payload::<PyBytes>() {
|
||||
@@ -117,8 +117,7 @@ fn spec_format_bytes(
|
||||
return Ok(spec.format_char(buf[0]));
|
||||
}
|
||||
}
|
||||
Err(vm
|
||||
.new_type_error("%c requires an integer in range(256) or a single byte".to_owned()))
|
||||
Err(vm.new_type_error("%c requires an integer in range(256) or a single byte"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -193,9 +192,7 @@ fn spec_format_string(
|
||||
.as_bigint()
|
||||
.to_u32()
|
||||
.and_then(CodePoint::from_u32)
|
||||
.ok_or_else(|| {
|
||||
vm.new_overflow_error("%c arg not in range(0x110000)".to_owned())
|
||||
})?;
|
||||
.ok_or_else(|| vm.new_overflow_error("%c arg not in range(0x110000)"))?;
|
||||
return Ok(spec.format_char(ch));
|
||||
}
|
||||
if let Some(s) = obj.payload::<PyStr>() {
|
||||
@@ -203,7 +200,7 @@ fn spec_format_string(
|
||||
return Ok(spec.format_char(ch));
|
||||
}
|
||||
}
|
||||
Err(vm.new_type_error("%c requires int or char".to_owned()))
|
||||
Err(vm.new_type_error("%c requires int or char"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -218,10 +215,10 @@ fn try_update_quantity_from_element(
|
||||
let i = i.try_to_primitive::<i32>(vm)?.unsigned_abs();
|
||||
Ok(CFormatQuantity::Amount(i as usize))
|
||||
} else {
|
||||
Err(vm.new_type_error("* wants int".to_owned()))
|
||||
Err(vm.new_type_error("* wants int"))
|
||||
}
|
||||
}
|
||||
None => Err(vm.new_type_error("not enough arguments for format string".to_owned())),
|
||||
None => Err(vm.new_type_error("not enough arguments for format string")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -240,10 +237,10 @@ fn try_conversion_flag_from_tuple(
|
||||
};
|
||||
Ok(flags)
|
||||
} else {
|
||||
Err(vm.new_type_error("* wants int".to_owned()))
|
||||
Err(vm.new_type_error("* wants int"))
|
||||
}
|
||||
}
|
||||
None => Err(vm.new_type_error("not enough arguments for format string".to_owned())),
|
||||
None => Err(vm.new_type_error("not enough arguments for format string")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -277,7 +274,7 @@ fn try_update_precision_from_tuple<'a, I: Iterator<Item = &'a PyObjectRef>>(
|
||||
}
|
||||
|
||||
fn specifier_error(vm: &VirtualMachine) -> PyBaseExceptionRef {
|
||||
vm.new_type_error("format requires a mapping".to_owned())
|
||||
vm.new_type_error("format requires a mapping")
|
||||
}
|
||||
|
||||
pub(crate) fn cformat_bytes(
|
||||
@@ -313,7 +310,7 @@ pub(crate) fn cformat_bytes(
|
||||
}
|
||||
Ok(result)
|
||||
} else {
|
||||
Err(vm.new_type_error("not all arguments converted during bytes formatting".to_owned()))
|
||||
Err(vm.new_type_error("not all arguments converted during bytes formatting"))
|
||||
};
|
||||
}
|
||||
|
||||
@@ -333,7 +330,7 @@ pub(crate) fn cformat_bytes(
|
||||
}
|
||||
Ok(result)
|
||||
} else {
|
||||
Err(vm.new_type_error("format requires a mapping".to_owned()))
|
||||
Err(vm.new_type_error("format requires a mapping"))
|
||||
};
|
||||
}
|
||||
|
||||
@@ -359,9 +356,7 @@ pub(crate) fn cformat_bytes(
|
||||
|
||||
let value = match value_iter.next() {
|
||||
Some(obj) => Ok(obj.clone()),
|
||||
None => {
|
||||
Err(vm.new_type_error("not enough arguments for format string".to_owned()))
|
||||
}
|
||||
None => Err(vm.new_type_error("not enough arguments for format string")),
|
||||
}?;
|
||||
let part_result = spec_format_bytes(vm, &spec, value)?;
|
||||
result.extend(part_result);
|
||||
@@ -371,7 +366,7 @@ pub(crate) fn cformat_bytes(
|
||||
|
||||
// check that all arguments were converted
|
||||
if value_iter.next().is_some() && !is_mapping {
|
||||
Err(vm.new_type_error("not all arguments converted during bytes formatting".to_owned()))
|
||||
Err(vm.new_type_error("not all arguments converted during bytes formatting"))
|
||||
} else {
|
||||
Ok(result)
|
||||
}
|
||||
@@ -409,8 +404,7 @@ pub(crate) fn cformat_string(
|
||||
}
|
||||
Ok(result)
|
||||
} else {
|
||||
Err(vm
|
||||
.new_type_error("not all arguments converted during string formatting".to_owned()))
|
||||
Err(vm.new_type_error("not all arguments converted during string formatting"))
|
||||
};
|
||||
}
|
||||
|
||||
@@ -429,7 +423,7 @@ pub(crate) fn cformat_string(
|
||||
}
|
||||
Ok(result)
|
||||
} else {
|
||||
Err(vm.new_type_error("format requires a mapping".to_owned()))
|
||||
Err(vm.new_type_error("format requires a mapping"))
|
||||
};
|
||||
}
|
||||
|
||||
@@ -455,9 +449,7 @@ pub(crate) fn cformat_string(
|
||||
|
||||
let value = match value_iter.next() {
|
||||
Some(obj) => Ok(obj.clone()),
|
||||
None => {
|
||||
Err(vm.new_type_error("not enough arguments for format string".to_owned()))
|
||||
}
|
||||
None => Err(vm.new_type_error("not enough arguments for format string")),
|
||||
}?;
|
||||
let part_result = spec_format_string(vm, &spec, value, idx)?;
|
||||
result.push_wtf8(&part_result);
|
||||
@@ -467,7 +459,7 @@ pub(crate) fn cformat_string(
|
||||
|
||||
// check that all arguments were converted
|
||||
if value_iter.next().is_some() && !is_mapping {
|
||||
Err(vm.new_type_error("not all arguments converted during string formatting".to_owned()))
|
||||
Err(vm.new_type_error("not all arguments converted during string formatting"))
|
||||
} else {
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
+12
-22
@@ -85,9 +85,7 @@ impl PyCodec {
|
||||
.downcast::<PyTuple>()
|
||||
.ok()
|
||||
.filter(|tuple| tuple.len() == 2)
|
||||
.ok_or_else(|| {
|
||||
vm.new_type_error("encoder must return a tuple (object, integer)".to_owned())
|
||||
})?;
|
||||
.ok_or_else(|| vm.new_type_error("encoder must return a tuple (object, integer)"))?;
|
||||
// we don't actually care about the integer
|
||||
Ok(res[0].clone())
|
||||
}
|
||||
@@ -107,9 +105,7 @@ impl PyCodec {
|
||||
.downcast::<PyTuple>()
|
||||
.ok()
|
||||
.filter(|tuple| tuple.len() == 2)
|
||||
.ok_or_else(|| {
|
||||
vm.new_type_error("decoder must return a tuple (object,integer)".to_owned())
|
||||
})?;
|
||||
.ok_or_else(|| vm.new_type_error("decoder must return a tuple (object,integer)"))?;
|
||||
// we don't actually care about the integer
|
||||
Ok(res[0].clone())
|
||||
}
|
||||
@@ -144,9 +140,7 @@ impl TryFromObject for PyCodec {
|
||||
obj.downcast::<PyTuple>()
|
||||
.ok()
|
||||
.and_then(|tuple| PyCodec::from_tuple(tuple).ok())
|
||||
.ok_or_else(|| {
|
||||
vm.new_type_error("codec search functions must return 4-tuples".to_owned())
|
||||
})
|
||||
.ok_or_else(|| vm.new_type_error("codec search functions must return 4-tuples"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,7 +197,7 @@ impl CodecsRegistry {
|
||||
|
||||
pub fn register(&self, search_function: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
if !search_function.is_callable() {
|
||||
return Err(vm.new_type_error("argument must be callable".to_owned()));
|
||||
return Err(vm.new_type_error("argument must be callable"));
|
||||
}
|
||||
self.inner.write().search_path.push(search_function);
|
||||
Ok(())
|
||||
@@ -786,9 +780,9 @@ impl<'a> DecodeErrorHandler<PyDecodeContext<'a>> for StandardError {
|
||||
Strict => errors::Strict.handle_decode_error(ctx, byte_range, reason),
|
||||
Ignore => errors::Ignore.handle_decode_error(ctx, byte_range, reason),
|
||||
Replace => errors::Replace.handle_decode_error(ctx, byte_range, reason),
|
||||
XmlCharRefReplace => Err(ctx.vm.new_type_error(
|
||||
"don't know how to handle UnicodeDecodeError in error callback".to_owned(),
|
||||
)),
|
||||
XmlCharRefReplace => Err(ctx
|
||||
.vm
|
||||
.new_type_error("don't know how to handle UnicodeDecodeError in error callback")),
|
||||
BackslashReplace => {
|
||||
errors::BackslashReplace.handle_decode_error(ctx, byte_range, reason)
|
||||
}
|
||||
@@ -856,11 +850,8 @@ impl<'a> EncodeErrorHandler<PyEncodeContext<'a>> for ErrorsHandler<'_> {
|
||||
};
|
||||
let encode_exc = ctx.error_encoding(range.clone(), reason);
|
||||
let res = handler.call((encode_exc.clone(),), vm)?;
|
||||
let tuple_err = || {
|
||||
vm.new_type_error(
|
||||
"encoding error handler must return (str/bytes, int) tuple".to_owned(),
|
||||
)
|
||||
};
|
||||
let tuple_err =
|
||||
|| vm.new_type_error("encoding error handler must return (str/bytes, int) tuple");
|
||||
let (replace, restart) = match res.payload::<PyTuple>().map(|tup| tup.as_slice()) {
|
||||
Some([replace, restart]) => (replace.clone(), restart),
|
||||
_ => return Err(tuple_err()),
|
||||
@@ -914,12 +905,11 @@ impl<'a> DecodeErrorHandler<PyDecodeContext<'a>> for ErrorsHandler<'_> {
|
||||
if !new_data.is(&data_bytes) {
|
||||
let new_data: PyBytesRef = new_data
|
||||
.downcast()
|
||||
.map_err(|_| vm.new_type_error("object attribute must be bytes".to_owned()))?;
|
||||
.map_err(|_| vm.new_type_error("object attribute must be bytes"))?;
|
||||
ctx.data = PyDecodeData::Modified(new_data);
|
||||
}
|
||||
let data = &*ctx.data;
|
||||
let tuple_err =
|
||||
|| vm.new_type_error("decoding error handler must return (str, int) tuple".to_owned());
|
||||
let tuple_err = || vm.new_type_error("decoding error handler must return (str, int) tuple");
|
||||
match res.payload::<PyTuple>().map(|tup| tup.as_slice()) {
|
||||
Some([replace, restart]) => {
|
||||
let replace = replace
|
||||
@@ -1091,7 +1081,7 @@ fn bad_err_type(err: PyObjectRef, vm: &VirtualMachine) -> PyBaseExceptionRef {
|
||||
fn strict_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
let err = err
|
||||
.downcast()
|
||||
.unwrap_or_else(|_| vm.new_type_error("codec must pass exception instance".to_owned()));
|
||||
.unwrap_or_else(|_| vm.new_type_error("codec must pass exception instance"));
|
||||
Err(err)
|
||||
}
|
||||
|
||||
|
||||
@@ -130,7 +130,7 @@ impl TryFromObject for std::time::Duration {
|
||||
let sec = int?
|
||||
.as_bigint()
|
||||
.to_u64()
|
||||
.ok_or_else(|| vm.new_value_error("value out of range".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_value_error("value out of range"))?;
|
||||
Ok(Duration::from_secs(sec))
|
||||
} else {
|
||||
Err(vm.new_type_error(format!(
|
||||
|
||||
+1
-2
@@ -120,8 +120,7 @@ impl Coro {
|
||||
} else if jen.class().is(vm.ctx.types.async_generator)
|
||||
&& e.fast_isinstance(vm.ctx.exceptions.stop_async_iteration)
|
||||
{
|
||||
let err = vm
|
||||
.new_runtime_error("async generator raised StopAsyncIteration".to_owned());
|
||||
let err = vm.new_runtime_error("async generator raised StopAsyncIteration");
|
||||
err.set_cause(Some(e));
|
||||
Err(err)
|
||||
} else {
|
||||
|
||||
@@ -845,7 +845,7 @@ impl DictKey for str {
|
||||
}
|
||||
|
||||
fn key_as_isize(&self, vm: &VirtualMachine) -> PyResult<isize> {
|
||||
Err(vm.new_type_error("'str' object cannot be interpreted as an integer".to_owned()))
|
||||
Err(vm.new_type_error("'str' object cannot be interpreted as an integer"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -902,7 +902,7 @@ impl DictKey for Wtf8 {
|
||||
}
|
||||
|
||||
fn key_as_isize(&self, vm: &VirtualMachine) -> PyResult<isize> {
|
||||
Err(vm.new_type_error("'str' object cannot be interpreted as an integer".to_owned()))
|
||||
Err(vm.new_type_error("'str' object cannot be interpreted as an integer"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -959,7 +959,7 @@ impl DictKey for [u8] {
|
||||
}
|
||||
|
||||
fn key_as_isize(&self, vm: &VirtualMachine) -> PyResult<isize> {
|
||||
Err(vm.new_type_error("'str' object cannot be interpreted as an integer".to_owned()))
|
||||
Err(vm.new_type_error("'str' object cannot be interpreted as an integer"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -591,9 +591,7 @@ impl PyBaseException {
|
||||
match value.downcast::<PyTraceback>() {
|
||||
Ok(tb) => Some(tb),
|
||||
Err(_) => {
|
||||
return Err(
|
||||
vm.new_type_error("__traceback__ must be a traceback or None".to_owned())
|
||||
);
|
||||
return Err(vm.new_type_error("__traceback__ must be a traceback or None"));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
+3
-3
@@ -13,11 +13,11 @@ impl IntoPyException for FormatSpecError {
|
||||
fn into_pyexception(self, vm: &VirtualMachine) -> PyBaseExceptionRef {
|
||||
match self {
|
||||
FormatSpecError::DecimalDigitsTooMany => {
|
||||
vm.new_value_error("Too many decimal digits in format string".to_owned())
|
||||
vm.new_value_error("Too many decimal digits in format string")
|
||||
}
|
||||
FormatSpecError::PrecisionTooBig => vm.new_value_error("Precision too big".to_owned()),
|
||||
FormatSpecError::PrecisionTooBig => vm.new_value_error("Precision too big"),
|
||||
FormatSpecError::InvalidFormatSpecifier => {
|
||||
vm.new_value_error("Invalid format specifier".to_owned())
|
||||
vm.new_value_error("Invalid format specifier")
|
||||
}
|
||||
FormatSpecError::UnspecifiedFormat(c1, c2) => {
|
||||
let msg = format!("Cannot specify '{c1}' with '{c2}'.");
|
||||
|
||||
+9
-13
@@ -1265,7 +1265,7 @@ impl ExecutingFrame<'_> {
|
||||
let type_params: PyTupleRef = self
|
||||
.pop_value()
|
||||
.downcast()
|
||||
.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."))?;
|
||||
let value = self.pop_value();
|
||||
let type_alias = _typing::TypeAliasType::new(name, type_params, value);
|
||||
self.push_value(type_alias.into_ref(&vm.ctx).into());
|
||||
@@ -1544,7 +1544,7 @@ impl ExecutingFrame<'_> {
|
||||
Self::iterate_mapping_keys(vm, &obj, "keyword argument", |key| {
|
||||
// Check for keyword argument restrictions
|
||||
if key.downcast_ref::<PyStr>().is_none() {
|
||||
return Err(vm.new_type_error("keywords must be strings".to_owned()));
|
||||
return Err(vm.new_type_error("keywords must be strings"));
|
||||
}
|
||||
if map_obj.contains_key(&*key, vm) {
|
||||
let key_repr = &key.repr(vm)?;
|
||||
@@ -1610,7 +1610,7 @@ impl ExecutingFrame<'_> {
|
||||
Self::iterate_mapping_keys(vm, &kw_obj, "argument after **", |key| {
|
||||
let key_str = key
|
||||
.payload_if_subclass::<PyStr>(vm)
|
||||
.ok_or_else(|| vm.new_type_error("keywords must be strings".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_type_error("keywords must be strings"))?;
|
||||
let value = kw_obj.get_item(&*key, vm)?;
|
||||
kwargs.insert(key_str.as_str().to_owned(), value);
|
||||
Ok(())
|
||||
@@ -1689,9 +1689,7 @@ impl ExecutingFrame<'_> {
|
||||
} else {
|
||||
// if the cause arg is an exception, we overwrite it
|
||||
let ctor = ExceptionCtor::try_from_object(vm, val).map_err(|_| {
|
||||
vm.new_type_error(
|
||||
"exception causes must derive from BaseException".to_owned(),
|
||||
)
|
||||
vm.new_type_error("exception causes must derive from BaseException")
|
||||
})?;
|
||||
Some(ctor.instantiate(vm)?)
|
||||
})
|
||||
@@ -1705,7 +1703,7 @@ impl ExecutingFrame<'_> {
|
||||
}
|
||||
bytecode::RaiseKind::Reraise => vm
|
||||
.topmost_exception()
|
||||
.ok_or_else(|| vm.new_runtime_error("No active exception to reraise".to_owned()))?,
|
||||
.ok_or_else(|| vm.new_runtime_error("No active exception to reraise"))?,
|
||||
};
|
||||
#[cfg(debug_assertions)]
|
||||
debug!("Exception raised: {exception:?} with cause: {cause:?}");
|
||||
@@ -1880,7 +1878,7 @@ impl ExecutingFrame<'_> {
|
||||
let type_params: PyTupleRef = if flags.contains(bytecode::MakeFunctionFlags::TYPE_PARAMS) {
|
||||
self.pop_value()
|
||||
.downcast()
|
||||
.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."))?
|
||||
} else {
|
||||
vm.ctx.empty_tuple.clone()
|
||||
};
|
||||
@@ -2026,7 +2024,7 @@ impl ExecutingFrame<'_> {
|
||||
let displayhook = vm
|
||||
.sys_module
|
||||
.get_attr("displayhook", vm)
|
||||
.map_err(|_| vm.new_runtime_error("lost sys.displayhook".to_owned()))?;
|
||||
.map_err(|_| vm.new_runtime_error("lost sys.displayhook"))?;
|
||||
displayhook.call((expr,), vm)?;
|
||||
|
||||
Ok(None)
|
||||
@@ -2112,15 +2110,13 @@ impl ExecutingFrame<'_> {
|
||||
.is_subclass(vm.ctx.exceptions.base_exception_type.into(), 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",
|
||||
));
|
||||
}
|
||||
}
|
||||
} else if !b.is_subclass(vm.ctx.exceptions.base_exception_type.into(), 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",
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
@@ -19,9 +19,10 @@ impl PyObject {
|
||||
f: impl FnOnce(&[u8]) -> R,
|
||||
) -> PyResult<R> {
|
||||
let buffer = PyBuffer::try_from_borrowed_object(vm, self)?;
|
||||
buffer.as_contiguous().map(|x| f(&x)).ok_or_else(|| {
|
||||
vm.new_type_error("non-contiguous buffer is not a bytes-like object".to_owned())
|
||||
})
|
||||
buffer
|
||||
.as_contiguous()
|
||||
.map(|x| f(&x))
|
||||
.ok_or_else(|| vm.new_type_error("non-contiguous buffer is not a bytes-like object"))
|
||||
}
|
||||
|
||||
pub fn try_rw_bytes_like<R>(
|
||||
@@ -33,9 +34,7 @@ impl PyObject {
|
||||
buffer
|
||||
.as_contiguous_mut()
|
||||
.map(|mut x| f(&mut x))
|
||||
.ok_or_else(|| {
|
||||
vm.new_type_error("buffer is not a read-write bytes-like object".to_owned())
|
||||
})
|
||||
.ok_or_else(|| vm.new_type_error("buffer is not a read-write bytes-like object"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,7 +81,7 @@ impl<'a> TryFromBorrowedObject<'a> for ArgBytesLike {
|
||||
if buffer.desc.is_contiguous() {
|
||||
Ok(Self(buffer))
|
||||
} else {
|
||||
Err(vm.new_type_error("non-contiguous buffer is not a bytes-like object".to_owned()))
|
||||
Err(vm.new_type_error("non-contiguous buffer is not a bytes-like object"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -122,9 +121,9 @@ impl<'a> TryFromBorrowedObject<'a> for ArgMemoryBuffer {
|
||||
fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult<Self> {
|
||||
let buffer = PyBuffer::try_from_borrowed_object(vm, obj)?;
|
||||
if !buffer.desc.is_contiguous() {
|
||||
Err(vm.new_type_error("non-contiguous buffer is not a bytes-like object".to_owned()))
|
||||
Err(vm.new_type_error("non-contiguous buffer is not a bytes-like object"))
|
||||
} else if buffer.desc.readonly {
|
||||
Err(vm.new_type_error("buffer is not a read-write bytes-like object".to_owned()))
|
||||
Err(vm.new_type_error("buffer is not a read-write bytes-like object"))
|
||||
} else {
|
||||
Ok(Self(buffer))
|
||||
}
|
||||
@@ -176,9 +175,7 @@ impl TryFromObject for ArgAsciiBuffer {
|
||||
if string.as_str().is_ascii() {
|
||||
Ok(ArgAsciiBuffer::String(string))
|
||||
} else {
|
||||
Err(vm.new_value_error(
|
||||
"string argument should contain only ASCII characters".to_owned(),
|
||||
))
|
||||
Err(vm.new_value_error("string argument should contain only ASCII characters"))
|
||||
}
|
||||
}
|
||||
Err(obj) => ArgBytesLike::try_from_object(vm, obj).map(ArgAsciiBuffer::Buffer),
|
||||
|
||||
@@ -101,7 +101,7 @@ impl FsPath {
|
||||
|
||||
pub fn bytes_as_os_str<'a>(b: &'a [u8], vm: &VirtualMachine) -> PyResult<&'a std::ffi::OsStr> {
|
||||
rustpython_common::os::bytes_as_os_str(b)
|
||||
.map_err(|_| vm.new_unicode_decode_error("can't decode path for utf-8".to_owned()))
|
||||
.map_err(|_| vm.new_unicode_decode_error("can't decode path for utf-8"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ where
|
||||
{
|
||||
#[inline]
|
||||
fn from_setter_value(vm: &VirtualMachine, obj: PySetterValue) -> PyResult<Self> {
|
||||
let obj = obj.ok_or_else(|| vm.new_type_error("can't delete attribute".to_owned()))?;
|
||||
let obj = obj.ok_or_else(|| vm.new_type_error("can't delete attribute"))?;
|
||||
T::try_from_object(vm, obj)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,9 +39,7 @@ impl<'a> TryFromBorrowedObject<'a> for ArgByteOrder {
|
||||
|s: &PyStr| match s.as_str() {
|
||||
"big" => Ok(Self::Big),
|
||||
"little" => Ok(Self::Little),
|
||||
_ => {
|
||||
Err(vm.new_value_error("byteorder must be either 'little' or 'big'".to_owned()))
|
||||
}
|
||||
_ => Err(vm.new_value_error("byteorder must be either 'little' or 'big'")),
|
||||
},
|
||||
vm,
|
||||
)
|
||||
|
||||
@@ -391,7 +391,7 @@ pub trait BufferResizeGuard {
|
||||
fn try_resizable_opt(&self) -> Option<Self::Resizable<'_>>;
|
||||
fn try_resizable(&self, vm: &VirtualMachine) -> PyResult<Self::Resizable<'_>> {
|
||||
self.try_resizable_opt().ok_or_else(|| {
|
||||
vm.new_buffer_error("Existing exports of data: object cannot be re-sized".to_owned())
|
||||
vm.new_buffer_error("Existing exports of data: object cannot be re-sized")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,7 +96,7 @@ impl PyObject {
|
||||
if self.payload_is::<PyAsyncGen>() {
|
||||
vm.call_special_method(self, identifier!(vm, __aiter__), ())
|
||||
} else {
|
||||
Err(vm.new_type_error("wrong argument type".to_owned()))
|
||||
Err(vm.new_type_error("wrong argument type"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -303,7 +303,7 @@ impl PySequence<'_> {
|
||||
let elem = elem?;
|
||||
if vm.bool_eq(&elem, target)? {
|
||||
if n == isize::MAX as usize {
|
||||
return Err(vm.new_overflow_error("index exceeds C integer size".to_string()));
|
||||
return Err(vm.new_overflow_error("index exceeds C integer size"));
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
@@ -320,7 +320,7 @@ impl PySequence<'_> {
|
||||
|
||||
for elem in iter {
|
||||
if index == isize::MAX {
|
||||
return Err(vm.new_overflow_error("index exceeds C integer size".to_string()));
|
||||
return Err(vm.new_overflow_error("index exceeds C integer size"));
|
||||
}
|
||||
index += 1;
|
||||
|
||||
@@ -330,7 +330,7 @@ impl PySequence<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
Err(vm.new_value_error("sequence.index(x): x not in sequence".to_string()))
|
||||
Err(vm.new_value_error("sequence.index(x): x not in sequence"))
|
||||
}
|
||||
|
||||
pub fn extract<F, R>(&self, mut f: F, vm: &VirtualMachine) -> PyResult<Vec<R>>
|
||||
|
||||
+8
-15
@@ -34,7 +34,7 @@ where
|
||||
let pos = self
|
||||
.as_ref()
|
||||
.wrap_index(index)
|
||||
.ok_or_else(|| vm.new_index_error("assignment index out of range".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_index_error("assignment index out of range"))?;
|
||||
self.do_set(pos, value);
|
||||
Ok(())
|
||||
}
|
||||
@@ -47,8 +47,7 @@ where
|
||||
) -> PyResult<()> {
|
||||
let (range, step, slice_len) = slice.adjust_indices(self.as_ref().len());
|
||||
if slice_len != items.len() {
|
||||
Err(vm
|
||||
.new_buffer_error("Existing exports of data: object cannot be re-sized".to_owned()))
|
||||
Err(vm.new_buffer_error("Existing exports of data: object cannot be re-sized"))
|
||||
} else if step == 1 {
|
||||
self.do_set_range(range, items);
|
||||
Ok(())
|
||||
@@ -90,7 +89,7 @@ where
|
||||
let pos = self
|
||||
.as_ref()
|
||||
.wrap_index(index)
|
||||
.ok_or_else(|| vm.new_index_error("assignment index out of range".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_index_error("assignment index out of range"))?;
|
||||
self.do_delete(pos);
|
||||
Ok(())
|
||||
}
|
||||
@@ -206,7 +205,7 @@ pub trait SliceableSequenceOp {
|
||||
fn getitem_by_index(&self, vm: &VirtualMachine, index: isize) -> PyResult<Self::Item> {
|
||||
let pos = self
|
||||
.wrap_index(index)
|
||||
.ok_or_else(|| vm.new_index_error("index out of range".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_index_error("index out of range"))?;
|
||||
Ok(self.do_get(pos))
|
||||
}
|
||||
}
|
||||
@@ -267,18 +266,14 @@ impl SequenceIndex {
|
||||
if let Some(i) = obj.payload::<PyInt>() {
|
||||
// TODO: number protocol
|
||||
i.try_to_primitive(vm)
|
||||
.map_err(|_| {
|
||||
vm.new_index_error("cannot fit 'int' into an index-sized integer".to_owned())
|
||||
})
|
||||
.map_err(|_| vm.new_index_error("cannot fit 'int' into an index-sized integer"))
|
||||
.map(Self::Int)
|
||||
} else if let Some(slice) = obj.payload::<PySlice>() {
|
||||
slice.to_saturated(vm).map(Self::Slice)
|
||||
} else if let Some(i) = obj.try_index_opt(vm) {
|
||||
// TODO: __index__ for indices is no more supported?
|
||||
i?.try_to_primitive(vm)
|
||||
.map_err(|_| {
|
||||
vm.new_index_error("cannot fit 'int' into an index-sized integer".to_owned())
|
||||
})
|
||||
.map_err(|_| vm.new_index_error("cannot fit 'int' into an index-sized integer"))
|
||||
.map(Self::Int)
|
||||
} else {
|
||||
Err(vm.new_type_error(format!(
|
||||
@@ -356,7 +351,7 @@ impl SaturatedSlice {
|
||||
pub fn with_slice(slice: &PySlice, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
let step = to_isize_index(vm, slice.step_ref(vm))?.unwrap_or(1);
|
||||
if step == 0 {
|
||||
return Err(vm.new_value_error("slice step cannot be zero".to_owned()));
|
||||
return Err(vm.new_value_error("slice step cannot be zero"));
|
||||
}
|
||||
let start = to_isize_index(vm, slice.start_ref(vm))?
|
||||
.unwrap_or_else(|| if step.is_negative() { isize::MAX } else { 0 });
|
||||
@@ -461,9 +456,7 @@ fn to_isize_index(vm: &VirtualMachine, obj: &PyObject) -> PyResult<Option<isize>
|
||||
return Ok(None);
|
||||
}
|
||||
let result = obj.try_index_opt(vm).unwrap_or_else(|| {
|
||||
Err(vm.new_type_error(
|
||||
"slice indices must be integers or None or have an __index__ method".to_owned(),
|
||||
))
|
||||
Err(vm.new_type_error("slice indices must be integers or None or have an __index__ method"))
|
||||
})?;
|
||||
let value = result.as_bigint();
|
||||
let is_negative = value.is_negative();
|
||||
|
||||
@@ -21,7 +21,7 @@ impl Node for ruff::ConversionFlag {
|
||||
bytecode::ConversionFlag::Ascii => Self::Ascii,
|
||||
bytecode::ConversionFlag::Repr => Self::Repr,
|
||||
})
|
||||
.ok_or_else(|| vm.new_value_error("invalid conversion flag".to_owned()))
|
||||
.ok_or_else(|| vm.new_value_error("invalid conversion flag"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ impl Node for ruff::name::Name {
|
||||
) -> PyResult<Self> {
|
||||
match object.downcast::<PyStr>() {
|
||||
Ok(name) => Ok(Self::new(name)),
|
||||
Err(_) => Err(vm.new_value_error("expected str for name".to_owned())),
|
||||
Err(_) => Err(vm.new_value_error("expected str for name")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+11
-13
@@ -92,7 +92,7 @@ mod builtins {
|
||||
.try_to_primitive::<isize>(vm)?
|
||||
.to_u32()
|
||||
.and_then(CodePoint::from_u32)
|
||||
.ok_or_else(|| vm.new_value_error("chr() arg not in range(0x110000)".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_value_error("chr() arg not in range(0x110000)"))?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
@@ -118,7 +118,7 @@ mod builtins {
|
||||
#[cfg(not(feature = "ast"))]
|
||||
{
|
||||
_ = args; // to disable unused warning
|
||||
return Err(vm.new_type_error("AST Not Supported".to_owned()));
|
||||
return Err(vm.new_type_error("AST Not Supported"));
|
||||
}
|
||||
#[cfg(feature = "ast")]
|
||||
{
|
||||
@@ -134,9 +134,9 @@ mod builtins {
|
||||
let optimize: u8 = if optimize == -1 {
|
||||
vm.state.settings.optimize
|
||||
} else {
|
||||
optimize.try_into().map_err(|_| {
|
||||
vm.new_value_error("compile() optimize value invalid".to_owned())
|
||||
})?
|
||||
optimize
|
||||
.try_into()
|
||||
.map_err(|_| vm.new_value_error("compile() optimize value invalid"))?
|
||||
};
|
||||
|
||||
if args
|
||||
@@ -183,7 +183,7 @@ mod builtins {
|
||||
let flags = args.flags.map_or(Ok(0), |v| v.try_to_primitive(vm))?;
|
||||
|
||||
if !(flags & !ast::PY_COMPILE_FLAGS_MASK).is_zero() {
|
||||
return Err(vm.new_value_error("compile() unrecognized flags".to_owned()));
|
||||
return Err(vm.new_value_error("compile() unrecognized flags"));
|
||||
}
|
||||
|
||||
let allow_incomplete = !(flags & ast::PY_CF_ALLOW_INCOMPLETE_INPUT).is_zero();
|
||||
@@ -414,7 +414,7 @@ mod builtins {
|
||||
.get_attr(vm.ctx.intern_str("breakpointhook"), vm)
|
||||
{
|
||||
Ok(hook) => hook.as_ref().call(args, vm),
|
||||
Err(_) => Err(vm.new_runtime_error("lost sys.breakpointhook".to_owned())),
|
||||
Err(_) => Err(vm.new_runtime_error("lost sys.breakpointhook")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -831,9 +831,8 @@ mod builtins {
|
||||
#[pyfunction]
|
||||
fn vars(obj: OptionalArg, vm: &VirtualMachine) -> PyResult {
|
||||
if let OptionalArg::Present(obj) = obj {
|
||||
obj.get_attr(identifier!(vm, __dict__), vm).map_err(|_| {
|
||||
vm.new_type_error("vars() argument must have __dict__ attribute".to_owned())
|
||||
})
|
||||
obj.get_attr(identifier!(vm, __dict__), vm)
|
||||
.map_err(|_| vm.new_type_error("vars() argument must have __dict__ attribute"))
|
||||
} else {
|
||||
Ok(vm.current_locals()?.into())
|
||||
}
|
||||
@@ -873,7 +872,7 @@ mod builtins {
|
||||
};
|
||||
let entries: PyTupleRef = entries
|
||||
.downcast()
|
||||
.map_err(|_| vm.new_type_error("__mro_entries__ must return a tuple".to_owned()))?;
|
||||
.map_err(|_| vm.new_type_error("__mro_entries__ must return a tuple"))?;
|
||||
let new_bases = new_bases.get_or_insert_with(|| bases[..i].to_vec());
|
||||
new_bases.extend_from_slice(&entries);
|
||||
}
|
||||
@@ -903,8 +902,7 @@ mod builtins {
|
||||
} else if !metaclass.fast_issubclass(base_class) {
|
||||
return Err(vm.new_type_error(
|
||||
"metaclass conflict: the metaclass of a derived class must be a (non-strict) \
|
||||
subclass of the metaclasses of all its bases"
|
||||
.to_owned(),
|
||||
subclass of the metaclasses of all its bases",
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,7 +110,7 @@ mod _collections {
|
||||
let count = self.mut_count(vm, &obj)?;
|
||||
|
||||
if start_state != self.state.load() {
|
||||
return Err(vm.new_runtime_error("deque mutated during iteration".to_owned()));
|
||||
return Err(vm.new_runtime_error("deque mutated during iteration"));
|
||||
}
|
||||
Ok(count)
|
||||
}
|
||||
@@ -173,7 +173,7 @@ mod _collections {
|
||||
let (start, stop) = range.saturate(self.len(), vm)?;
|
||||
let index = self.mut_index_range(vm, &needle, start..stop)?;
|
||||
if start_state != self.state.load() {
|
||||
Err(vm.new_runtime_error("deque mutated during iteration".to_owned()))
|
||||
Err(vm.new_runtime_error("deque mutated during iteration"))
|
||||
} else if let Some(index) = index.into() {
|
||||
Ok(index)
|
||||
} else {
|
||||
@@ -192,7 +192,7 @@ mod _collections {
|
||||
let mut deque = self.borrow_deque_mut();
|
||||
|
||||
if self.maxlen == Some(deque.len()) {
|
||||
return Err(vm.new_index_error("deque already at its maximum size".to_owned()));
|
||||
return Err(vm.new_index_error("deque already at its maximum size"));
|
||||
}
|
||||
|
||||
let idx = if idx < 0 {
|
||||
@@ -217,7 +217,7 @@ mod _collections {
|
||||
self.state.fetch_add(1);
|
||||
self.borrow_deque_mut()
|
||||
.pop_back()
|
||||
.ok_or_else(|| vm.new_index_error("pop from an empty deque".to_owned()))
|
||||
.ok_or_else(|| vm.new_index_error("pop from an empty deque"))
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
@@ -225,7 +225,7 @@ mod _collections {
|
||||
self.state.fetch_add(1);
|
||||
self.borrow_deque_mut()
|
||||
.pop_front()
|
||||
.ok_or_else(|| vm.new_index_error("pop from an empty deque".to_owned()))
|
||||
.ok_or_else(|| vm.new_index_error("pop from an empty deque"))
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
@@ -234,13 +234,13 @@ mod _collections {
|
||||
let index = self.mut_index(vm, &obj)?;
|
||||
|
||||
if start_state != self.state.load() {
|
||||
Err(vm.new_index_error("deque mutated during remove().".to_owned()))
|
||||
Err(vm.new_index_error("deque mutated during remove()."))
|
||||
} else if let Some(index) = index.into() {
|
||||
let mut deque = self.borrow_deque_mut();
|
||||
self.state.fetch_add(1);
|
||||
Ok(deque.remove(index).unwrap())
|
||||
} else {
|
||||
Err(vm.new_value_error("deque.remove(x): x not in deque".to_owned()))
|
||||
Err(vm.new_value_error("deque.remove(x): x not in deque"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,7 +282,7 @@ mod _collections {
|
||||
let deque = self.borrow_deque();
|
||||
idx.wrapped_at(deque.len())
|
||||
.and_then(|i| deque.get(i).cloned())
|
||||
.ok_or_else(|| vm.new_index_error("deque index out of range".to_owned()))
|
||||
.ok_or_else(|| vm.new_index_error("deque index out of range"))
|
||||
}
|
||||
|
||||
#[pymethod(magic)]
|
||||
@@ -291,7 +291,7 @@ mod _collections {
|
||||
idx.wrapped_at(deque.len())
|
||||
.and_then(|i| deque.get_mut(i))
|
||||
.map(|x| *x = value)
|
||||
.ok_or_else(|| vm.new_index_error("deque index out of range".to_owned()))
|
||||
.ok_or_else(|| vm.new_index_error("deque index out of range"))
|
||||
}
|
||||
|
||||
#[pymethod(magic)]
|
||||
@@ -299,7 +299,7 @@ mod _collections {
|
||||
let mut deque = self.borrow_deque_mut();
|
||||
idx.wrapped_at(deque.len())
|
||||
.and_then(|i| deque.remove(i).map(drop))
|
||||
.ok_or_else(|| vm.new_index_error("deque index out of range".to_owned()))
|
||||
.ok_or_else(|| vm.new_index_error("deque index out of range"))
|
||||
}
|
||||
|
||||
#[pymethod(magic)]
|
||||
@@ -311,7 +311,7 @@ mod _collections {
|
||||
let start_state = self.state.load();
|
||||
let ret = self.mut_contains(vm, needle)?;
|
||||
if start_state != self.state.load() {
|
||||
Err(vm.new_runtime_error("deque mutated during iteration".to_owned()))
|
||||
Err(vm.new_runtime_error("deque mutated during iteration"))
|
||||
} else {
|
||||
Ok(ret)
|
||||
}
|
||||
@@ -443,11 +443,11 @@ mod _collections {
|
||||
if !vm.is_none(&obj) {
|
||||
let maxlen: isize = obj
|
||||
.payload::<PyInt>()
|
||||
.ok_or_else(|| vm.new_type_error("an integer is required.".to_owned()))?
|
||||
.ok_or_else(|| vm.new_type_error("an integer is required."))?
|
||||
.try_to_primitive(vm)?;
|
||||
|
||||
if maxlen.is_negative() {
|
||||
return Err(vm.new_value_error("maxlen must be non-negative.".to_owned()));
|
||||
return Err(vm.new_value_error("maxlen must be non-negative."));
|
||||
}
|
||||
Some(maxlen as usize)
|
||||
} else {
|
||||
@@ -651,7 +651,7 @@ mod _collections {
|
||||
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
|
||||
zelf.internal.lock().next(|deque, pos| {
|
||||
if zelf.state != deque.state.load() {
|
||||
return Err(vm.new_runtime_error("Deque mutated during iteration".to_owned()));
|
||||
return Err(vm.new_runtime_error("Deque mutated during iteration"));
|
||||
}
|
||||
let deque = deque.borrow_deque();
|
||||
Ok(PyIterReturn::from_result(
|
||||
@@ -717,7 +717,7 @@ mod _collections {
|
||||
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
|
||||
zelf.internal.lock().next(|deque, pos| {
|
||||
if deque.state.load() != zelf.state {
|
||||
return Err(vm.new_runtime_error("Deque mutated during iteration".to_owned()));
|
||||
return Err(vm.new_runtime_error("Deque mutated during iteration"));
|
||||
}
|
||||
let deque = deque.borrow_deque();
|
||||
let r = deque
|
||||
|
||||
@@ -160,10 +160,10 @@ pub(crate) mod _ctypes {
|
||||
})
|
||||
}
|
||||
} else {
|
||||
Err(vm.new_type_error("class must define a '_type_' string attribute".to_string()))
|
||||
Err(vm.new_type_error("class must define a '_type_' string attribute"))
|
||||
}
|
||||
} else {
|
||||
Err(vm.new_attribute_error("class must define a '_type_' attribute".to_string()))
|
||||
Err(vm.new_attribute_error("class must define a '_type_' attribute"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,7 +179,7 @@ pub(crate) mod _ctypes {
|
||||
let size_of_return = size_of_method.call(vec![], vm)?;
|
||||
Ok(usize::try_from_object(vm, size_of_return)?)
|
||||
}
|
||||
_ => Err(vm.new_type_error("this type has no size".to_string())),
|
||||
_ => Err(vm.new_type_error("this type has no size")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -248,26 +248,26 @@ pub(crate) mod _ctypes {
|
||||
let simple = obj.downcast_ref::<PyCSimple>().unwrap();
|
||||
Ok(simple.value.as_ptr() as usize)
|
||||
} else {
|
||||
Err(vm.new_type_error("expected a ctypes instance".to_string()))
|
||||
Err(vm.new_type_error("expected a ctypes instance"))
|
||||
}
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn byref(_args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
|
||||
// TODO: RUSTPYTHON
|
||||
Err(vm.new_value_error("not implemented".to_string()))
|
||||
Err(vm.new_value_error("not implemented"))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn alignment(_args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
|
||||
// TODO: RUSTPYTHON
|
||||
Err(vm.new_value_error("not implemented".to_string()))
|
||||
Err(vm.new_value_error("not implemented"))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn resize(_args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
|
||||
// TODO: RUSTPYTHON
|
||||
Err(vm.new_value_error("not implemented".to_string()))
|
||||
Err(vm.new_value_error("not implemented"))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
|
||||
@@ -62,9 +62,7 @@ fn set_primitive(_type_: &str, value: &PyObjectRef, vm: &VirtualMachine) -> PyRe
|
||||
{
|
||||
Ok(value.clone())
|
||||
} else {
|
||||
Err(vm.new_type_error(
|
||||
"one character bytes, bytearray or integer expected".to_string(),
|
||||
))
|
||||
Err(vm.new_type_error("one character bytes, bytearray or integer expected"))
|
||||
}
|
||||
}
|
||||
"u" => {
|
||||
@@ -72,7 +70,7 @@ fn set_primitive(_type_: &str, value: &PyObjectRef, vm: &VirtualMachine) -> PyRe
|
||||
if b {
|
||||
Ok(value.clone())
|
||||
} else {
|
||||
Err(vm.new_type_error("one character unicode string expected".to_string()))
|
||||
Err(vm.new_type_error("one character unicode string expected"))
|
||||
}
|
||||
} else {
|
||||
Err(vm.new_type_error(format!(
|
||||
@@ -137,7 +135,7 @@ fn set_primitive(_type_: &str, value: &PyObjectRef, vm: &VirtualMachine) -> PyRe
|
||||
{
|
||||
Ok(value.clone())
|
||||
} else {
|
||||
Err(vm.new_type_error("cannot be converted to pointer".to_string()))
|
||||
Err(vm.new_type_error("cannot be converted to pointer"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -234,7 +232,7 @@ impl PyCSimple {
|
||||
pub fn value(instance: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
|
||||
let zelf: &Py<Self> = instance
|
||||
.downcast_ref()
|
||||
.ok_or_else(|| vm.new_type_error("cannot get value of instance".to_string()))?;
|
||||
.ok_or_else(|| vm.new_type_error("cannot get value of instance"))?;
|
||||
Ok(unsafe { (*zelf.value.as_ptr()).clone() })
|
||||
}
|
||||
|
||||
@@ -242,7 +240,7 @@ impl PyCSimple {
|
||||
fn set_value(instance: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let zelf: PyRef<Self> = instance
|
||||
.downcast()
|
||||
.map_err(|_| vm.new_type_error("cannot set value of instance".to_string()))?;
|
||||
.map_err(|_| vm.new_type_error("cannot set value of instance"))?;
|
||||
let content = set_primitive(zelf._type_.as_str(), &value, vm)?;
|
||||
zelf.value.store(content);
|
||||
Ok(())
|
||||
|
||||
@@ -47,23 +47,18 @@ impl Function {
|
||||
let converted = ffi_type_from_str(&arg._type_);
|
||||
return match converted {
|
||||
Some(t) => Ok(t),
|
||||
None => Err(vm.new_type_error("Invalid type".to_string())), // TODO: add type name
|
||||
None => Err(vm.new_type_error("Invalid type")), // TODO: add type name
|
||||
};
|
||||
}
|
||||
if let Some(arg) = arg.payload_if_subclass::<PyCArray>(vm) {
|
||||
let t = arg.typ.read();
|
||||
let ty_attributes = t.attributes.read();
|
||||
let ty_pystr =
|
||||
ty_attributes
|
||||
.get(vm.ctx.intern_str("_type_"))
|
||||
.ok_or_else(|| {
|
||||
vm.new_type_error("Expected a ctypes simple type".to_string())
|
||||
})?;
|
||||
let ty_pystr = ty_attributes
|
||||
.get(vm.ctx.intern_str("_type_"))
|
||||
.ok_or_else(|| vm.new_type_error("Expected a ctypes simple type"))?;
|
||||
let ty_str = ty_pystr
|
||||
.downcast_ref::<PyStr>()
|
||||
.ok_or_else(|| {
|
||||
vm.new_type_error("Expected a ctypes simple type".to_string())
|
||||
})?
|
||||
.ok_or_else(|| vm.new_type_error("Expected a ctypes simple type"))?
|
||||
.to_string();
|
||||
let converted = ffi_type_from_str(&ty_str);
|
||||
match converted {
|
||||
@@ -71,15 +66,15 @@ impl Function {
|
||||
// TODO: Use
|
||||
Ok(Type::void())
|
||||
}
|
||||
None => Err(vm.new_type_error("Invalid type".to_string())), // TODO: add type name
|
||||
None => Err(vm.new_type_error("Invalid type")), // TODO: add type name
|
||||
}
|
||||
} else {
|
||||
Err(vm.new_type_error("Expected a ctypes simple type".to_string()))
|
||||
Err(vm.new_type_error("Expected a ctypes simple type"))
|
||||
}
|
||||
})
|
||||
.collect::<PyResult<Vec<Type>>>()?;
|
||||
let c_function_name = CString::new(function)
|
||||
.map_err(|_| vm.new_value_error("Function name contains null bytes".to_string()))?;
|
||||
.map_err(|_| vm.new_value_error("Function name contains null bytes"))?;
|
||||
let pointer: Symbol<'_, FP> = unsafe {
|
||||
library
|
||||
.get(c_function_name.as_bytes())
|
||||
@@ -90,7 +85,7 @@ impl Function {
|
||||
let return_type = match ret_type {
|
||||
// TODO: Fix this
|
||||
Some(_t) => {
|
||||
return Err(vm.new_not_implemented_error("Return type not implemented".to_string()));
|
||||
return Err(vm.new_not_implemented_error("Return type not implemented"));
|
||||
}
|
||||
None => Type::c_int(),
|
||||
};
|
||||
@@ -118,7 +113,7 @@ impl Function {
|
||||
if let Some(d) = arg.payload_if_subclass::<PyCArray>(vm) {
|
||||
return Ok(d.to_arg(vm).unwrap());
|
||||
}
|
||||
Err(vm.new_type_error("Expected a ctypes simple type".to_string()))
|
||||
Err(vm.new_type_error("Expected a ctypes simple type"))
|
||||
})
|
||||
.collect::<PyResult<Vec<Arg>>>()?;
|
||||
// TODO: FIX return
|
||||
@@ -152,14 +147,14 @@ impl Constructor for PyCFuncPtr {
|
||||
fn py_new(_cls: PyTypeRef, (tuple, _args): Self::Args, vm: &VirtualMachine) -> PyResult {
|
||||
let name = tuple
|
||||
.first()
|
||||
.ok_or(vm.new_type_error("Expected a tuple with at least 2 elements".to_string()))?
|
||||
.ok_or(vm.new_type_error("Expected a tuple with at least 2 elements"))?
|
||||
.downcast_ref::<PyStr>()
|
||||
.ok_or(vm.new_type_error("Expected a string".to_string()))?
|
||||
.ok_or(vm.new_type_error("Expected a string"))?
|
||||
.to_string();
|
||||
let handler = tuple
|
||||
.into_iter()
|
||||
.nth(1)
|
||||
.ok_or(vm.new_type_error("Expected a tuple with at least 2 elements".to_string()))?
|
||||
.ok_or(vm.new_type_error("Expected a tuple with at least 2 elements"))?
|
||||
.clone();
|
||||
Ok(Self {
|
||||
_flags_: AtomicCell::new(0),
|
||||
@@ -182,16 +177,16 @@ impl Callable for PyCFuncPtr {
|
||||
.get_lib(
|
||||
handle
|
||||
.to_usize()
|
||||
.ok_or(vm.new_value_error("Invalid handle".to_string()))?,
|
||||
.ok_or(vm.new_value_error("Invalid handle"))?,
|
||||
)
|
||||
.ok_or_else(|| vm.new_value_error("Library not found".to_string()))?;
|
||||
.ok_or_else(|| vm.new_value_error("Library not found"))?;
|
||||
let inner_lib = library.lib.lock();
|
||||
let name = zelf.name.read();
|
||||
let res_type = zelf._restype_.read();
|
||||
let func = Function::load(
|
||||
inner_lib
|
||||
.as_ref()
|
||||
.ok_or_else(|| vm.new_value_error("Library not found".to_string()))?,
|
||||
.ok_or_else(|| vm.new_value_error("Library not found"))?,
|
||||
&name,
|
||||
&args.args,
|
||||
&res_type,
|
||||
|
||||
@@ -22,24 +22,22 @@ impl Constructor for PyCStructure {
|
||||
fn py_new(cls: PyTypeRef, _args: Self::Args, vm: &VirtualMachine) -> PyResult {
|
||||
let fields_attr = cls
|
||||
.get_class_attr(vm.ctx.interned_str("_fields_").unwrap())
|
||||
.ok_or_else(|| {
|
||||
vm.new_attribute_error("Structure must have a _fields_ attribute".to_string())
|
||||
})?;
|
||||
.ok_or_else(|| vm.new_attribute_error("Structure must have a _fields_ attribute"))?;
|
||||
// downcast into list
|
||||
let fields = fields_attr.downcast_ref::<PyList>().ok_or_else(|| {
|
||||
vm.new_type_error("Structure _fields_ attribute must be a list".to_string())
|
||||
})?;
|
||||
let fields = fields_attr
|
||||
.downcast_ref::<PyList>()
|
||||
.ok_or_else(|| vm.new_type_error("Structure _fields_ attribute must be a list"))?;
|
||||
let fields = fields.borrow_vec();
|
||||
let mut field_data = HashMap::new();
|
||||
for field in fields.iter() {
|
||||
let field = field
|
||||
.downcast_ref::<PyTuple>()
|
||||
.ok_or_else(|| vm.new_type_error("Field must be a tuple".to_string()))?;
|
||||
.ok_or_else(|| vm.new_type_error("Field must be a tuple"))?;
|
||||
let name = field
|
||||
.first()
|
||||
.unwrap()
|
||||
.downcast_ref::<PyStr>()
|
||||
.ok_or_else(|| vm.new_type_error("Field name must be a string".to_string()))?;
|
||||
.ok_or_else(|| vm.new_type_error("Field name must be a string"))?;
|
||||
let typ = field.get(1).unwrap().clone();
|
||||
field_data.insert(name.as_str().to_string(), typ);
|
||||
}
|
||||
|
||||
+13
-12
@@ -102,9 +102,9 @@ mod _functools {
|
||||
|
||||
#[pymethod(magic)]
|
||||
fn setstate(zelf: &Py<Self>, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let state_tuple = state.downcast::<PyTuple>().map_err(|_| {
|
||||
vm.new_type_error("argument to __setstate__ must be a tuple".to_owned())
|
||||
})?;
|
||||
let state_tuple = state
|
||||
.downcast::<PyTuple>()
|
||||
.map_err(|_| vm.new_type_error("argument to __setstate__ must be a tuple"))?;
|
||||
|
||||
if state_tuple.len() != 4 {
|
||||
return Err(vm.new_type_error(format!(
|
||||
@@ -119,12 +119,12 @@ mod _functools {
|
||||
let dict = &state_tuple[3];
|
||||
|
||||
if !func.is_callable() {
|
||||
return Err(vm.new_type_error("invalid partial state".to_owned()));
|
||||
return Err(vm.new_type_error("invalid partial state"));
|
||||
}
|
||||
|
||||
// Validate that args is a tuple (or subclass)
|
||||
if !args.fast_isinstance(vm.ctx.types.tuple_type) {
|
||||
return Err(vm.new_type_error("invalid partial state".to_owned()));
|
||||
return Err(vm.new_type_error("invalid partial state"));
|
||||
}
|
||||
// Always convert to base tuple, even if it's a subclass
|
||||
let args_tuple = match args.clone().downcast::<PyTuple>() {
|
||||
@@ -143,7 +143,7 @@ mod _functools {
|
||||
let dict = kwds
|
||||
.clone()
|
||||
.downcast::<PyDict>()
|
||||
.map_err(|_| vm.new_type_error("invalid partial state".to_owned()))?;
|
||||
.map_err(|_| vm.new_type_error("invalid partial state"))?;
|
||||
if dict.class().is(vm.ctx.types.dict_type) {
|
||||
// It's already a base dict
|
||||
dict
|
||||
@@ -180,7 +180,7 @@ mod _functools {
|
||||
let dict_obj = dict
|
||||
.clone()
|
||||
.downcast::<PyDict>()
|
||||
.map_err(|_| vm.new_type_error("invalid partial state".to_owned()))?;
|
||||
.map_err(|_| vm.new_type_error("invalid partial state"))?;
|
||||
|
||||
// Clear existing dict and update with new values
|
||||
instance_dict.clear();
|
||||
@@ -196,12 +196,13 @@ mod _functools {
|
||||
type Args = FuncArgs;
|
||||
|
||||
fn py_new(cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult {
|
||||
let (func, args_slice) = args.args.split_first().ok_or_else(|| {
|
||||
vm.new_type_error("partial expected at least 1 argument, got 0".to_owned())
|
||||
})?;
|
||||
let (func, args_slice) = args
|
||||
.args
|
||||
.split_first()
|
||||
.ok_or_else(|| vm.new_type_error("partial expected at least 1 argument, got 0"))?;
|
||||
|
||||
if !func.is_callable() {
|
||||
return Err(vm.new_type_error("the first argument must be callable".to_owned()));
|
||||
return Err(vm.new_type_error("the first argument must be callable"));
|
||||
}
|
||||
|
||||
// Handle nested partial objects
|
||||
@@ -247,7 +248,7 @@ mod _functools {
|
||||
for (key, value) in &*inner.keywords {
|
||||
let key_str = key
|
||||
.downcast::<crate::builtins::PyStr>()
|
||||
.map_err(|_| vm.new_type_error("keywords must be strings".to_owned()))?;
|
||||
.map_err(|_| vm.new_type_error("keywords must be strings"))?;
|
||||
final_kwargs.insert(key_str.as_str().to_owned(), value);
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ mod lock {
|
||||
#[pyfunction]
|
||||
fn release_lock(vm: &VirtualMachine) -> PyResult<()> {
|
||||
if !IMP_LOCK.is_locked() {
|
||||
Err(vm.new_runtime_error("Global import lock not held".to_owned()))
|
||||
Err(vm.new_runtime_error("Global import lock not held"))
|
||||
} else {
|
||||
unsafe { IMP_LOCK.unlock() };
|
||||
Ok(())
|
||||
|
||||
+10
-10
@@ -253,7 +253,7 @@ mod decl {
|
||||
let start = start.into_option().unwrap_or_else(|| vm.new_pyobj(0));
|
||||
let step = step.into_option().unwrap_or_else(|| vm.new_pyobj(1));
|
||||
if !PyNumber::check(&start) || !PyNumber::check(&step) {
|
||||
return Err(vm.new_type_error("a number is required".to_owned()));
|
||||
return Err(vm.new_type_error("a number is required"));
|
||||
}
|
||||
|
||||
Self {
|
||||
@@ -397,7 +397,7 @@ mod decl {
|
||||
let times = self
|
||||
.times
|
||||
.as_ref()
|
||||
.ok_or_else(|| vm.new_type_error("length of unsized object.".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_type_error("length of unsized object."))?;
|
||||
Ok(*times.read())
|
||||
}
|
||||
|
||||
@@ -1489,7 +1489,7 @@ mod decl {
|
||||
|
||||
let r = r.as_bigint();
|
||||
if r.is_negative() {
|
||||
return Err(vm.new_value_error("r must be non-negative".to_owned()));
|
||||
return Err(vm.new_value_error("r must be non-negative"));
|
||||
}
|
||||
let r = r.to_usize().unwrap();
|
||||
|
||||
@@ -1620,7 +1620,7 @@ mod decl {
|
||||
let pool: Vec<_> = iterable.try_to_value(vm)?;
|
||||
let r = r.as_bigint();
|
||||
if r.is_negative() {
|
||||
return Err(vm.new_value_error("r must be non-negative".to_owned()));
|
||||
return Err(vm.new_value_error("r must be non-negative"));
|
||||
}
|
||||
let r = r.to_usize().unwrap();
|
||||
|
||||
@@ -1724,11 +1724,11 @@ mod decl {
|
||||
Some(r) => {
|
||||
let val = r
|
||||
.payload::<PyInt>()
|
||||
.ok_or_else(|| vm.new_type_error("Expected int as r".to_owned()))?
|
||||
.ok_or_else(|| vm.new_type_error("Expected int as r"))?
|
||||
.as_bigint();
|
||||
|
||||
if val.is_negative() {
|
||||
return Err(vm.new_value_error("r must be non-negative".to_owned()));
|
||||
return Err(vm.new_value_error("r must be non-negative"));
|
||||
}
|
||||
val.to_usize().unwrap()
|
||||
}
|
||||
@@ -1982,11 +1982,11 @@ mod decl {
|
||||
) -> PyResult {
|
||||
let n = n.as_bigint();
|
||||
if n.lt(&BigInt::one()) {
|
||||
return Err(vm.new_value_error("n must be at least one".to_owned()));
|
||||
return Err(vm.new_value_error("n must be at least one"));
|
||||
}
|
||||
let n = n.to_usize().ok_or(
|
||||
vm.new_overflow_error("Python int too large to convert to usize".to_owned()),
|
||||
)?;
|
||||
let n = n
|
||||
.to_usize()
|
||||
.ok_or(vm.new_overflow_error("Python int too large to convert to usize"))?;
|
||||
let iterable = iterable_ref.get_iter(vm)?;
|
||||
|
||||
Self {
|
||||
|
||||
@@ -103,7 +103,7 @@ mod decl {
|
||||
.unwrap_or_else(Err)
|
||||
.map_err(|DumpError| {
|
||||
vm.new_not_implemented_error(
|
||||
"TODO: not implemented yet or marshal unsupported type".to_owned(),
|
||||
"TODO: not implemented yet or marshal unsupported type",
|
||||
)
|
||||
})?;
|
||||
Ok(PyBytes::from(buf))
|
||||
@@ -204,7 +204,7 @@ mod decl {
|
||||
#[pyfunction]
|
||||
fn loads(pybuffer: PyBuffer, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
|
||||
let buf = pybuffer.as_contiguous().ok_or_else(|| {
|
||||
vm.new_buffer_error("Buffer provided to marshal.loads() is not contiguous".to_owned())
|
||||
vm.new_buffer_error("Buffer provided to marshal.loads() is not contiguous")
|
||||
})?;
|
||||
marshal::deserialize_value(&mut &buf[..], PyMarshalBag(vm)).map_err(|e| match e {
|
||||
marshal::MarshalError::Eof => vm.new_exception_msg(
|
||||
@@ -212,16 +212,16 @@ mod decl {
|
||||
"marshal data too short".to_owned(),
|
||||
),
|
||||
marshal::MarshalError::InvalidBytecode => {
|
||||
vm.new_value_error("Couldn't deserialize python bytecode".to_owned())
|
||||
vm.new_value_error("Couldn't deserialize python bytecode")
|
||||
}
|
||||
marshal::MarshalError::InvalidUtf8 => {
|
||||
vm.new_value_error("invalid utf8 in marshalled string".to_owned())
|
||||
vm.new_value_error("invalid utf8 in marshalled string")
|
||||
}
|
||||
marshal::MarshalError::InvalidLocation => {
|
||||
vm.new_value_error("invalid location in marshalled object".to_owned())
|
||||
vm.new_value_error("invalid location in marshalled object")
|
||||
}
|
||||
marshal::MarshalError::BadType => {
|
||||
vm.new_value_error("bad marshal data (unknown type code)".to_owned())
|
||||
vm.new_value_error("bad marshal data (unknown type code)")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -57,17 +57,20 @@ mod msvcrt {
|
||||
}
|
||||
#[pyfunction]
|
||||
fn putch(b: PyRef<PyBytes>, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let &c = b.as_bytes().iter().exactly_one().map_err(|_| {
|
||||
vm.new_type_error("putch() argument must be a byte string of length 1".to_owned())
|
||||
})?;
|
||||
let &c =
|
||||
b.as_bytes().iter().exactly_one().map_err(|_| {
|
||||
vm.new_type_error("putch() argument must be a byte string of length 1")
|
||||
})?;
|
||||
unsafe { suppress_iph!(_putch(c.into())) };
|
||||
Ok(())
|
||||
}
|
||||
#[pyfunction]
|
||||
fn putwch(s: PyStrRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let c = s.as_str().chars().exactly_one().map_err(|_| {
|
||||
vm.new_type_error("putch() argument must be a string of length 1".to_owned())
|
||||
})?;
|
||||
let c = s
|
||||
.as_str()
|
||||
.chars()
|
||||
.exactly_one()
|
||||
.map_err(|_| vm.new_type_error("putch() argument must be a string of length 1"))?;
|
||||
unsafe { suppress_iph!(_putwch(c as u16)) };
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+3
-5
@@ -180,7 +180,7 @@ pub(crate) mod module {
|
||||
OptionalArg::Present(0) => Console::STD_INPUT_HANDLE,
|
||||
OptionalArg::Present(1) | OptionalArg::Missing => Console::STD_OUTPUT_HANDLE,
|
||||
OptionalArg::Present(2) => Console::STD_ERROR_HANDLE,
|
||||
_ => return Err(vm.new_value_error("bad file descriptor".to_owned())),
|
||||
_ => return Err(vm.new_value_error("bad file descriptor")),
|
||||
};
|
||||
let h = unsafe { Console::GetStdHandle(stdhandle) };
|
||||
if h.is_null() {
|
||||
@@ -230,12 +230,10 @@ pub(crate) mod module {
|
||||
|
||||
let first = argv
|
||||
.first()
|
||||
.ok_or_else(|| vm.new_value_error("execv() arg 2 must not be empty".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_value_error("execv() arg 2 must not be empty"))?;
|
||||
|
||||
if first.is_empty() {
|
||||
return Err(
|
||||
vm.new_value_error("execv() arg 2 first element cannot be empty".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("execv() arg 2 first element cannot be empty"));
|
||||
}
|
||||
|
||||
let argv_execv: Vec<*const u16> = argv
|
||||
|
||||
+11
-11
@@ -206,7 +206,7 @@ mod _operator {
|
||||
return Ok(index);
|
||||
}
|
||||
}
|
||||
Err(vm.new_value_error("sequence.index(x): x not in sequence".to_owned()))
|
||||
Err(vm.new_value_error("sequence.index(x): x not in sequence"))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
@@ -325,16 +325,16 @@ mod _operator {
|
||||
(Either::A(a), Either::A(b)) => {
|
||||
if !a.as_str().is_ascii() || !b.as_str().is_ascii() {
|
||||
return Err(vm.new_type_error(
|
||||
"comparing strings with non-ASCII characters is not supported".to_owned(),
|
||||
"comparing strings with non-ASCII characters is not supported",
|
||||
));
|
||||
}
|
||||
constant_time_eq(a.as_bytes(), b.as_bytes())
|
||||
}
|
||||
(Either::B(a), Either::B(b)) => a.with_ref(|a| b.with_ref(|b| constant_time_eq(a, b))),
|
||||
_ => {
|
||||
return Err(vm.new_type_error(
|
||||
"unsupported operand types(s) or combination of types".to_owned(),
|
||||
));
|
||||
return Err(
|
||||
vm.new_type_error("unsupported operand types(s) or combination of types")
|
||||
);
|
||||
}
|
||||
};
|
||||
Ok(res)
|
||||
@@ -390,17 +390,17 @@ mod _operator {
|
||||
let n_attr = args.args.len();
|
||||
// Check we get no keyword and at least one positional.
|
||||
if !args.kwargs.is_empty() {
|
||||
return Err(vm.new_type_error("attrgetter() takes no keyword arguments".to_owned()));
|
||||
return Err(vm.new_type_error("attrgetter() takes no keyword arguments"));
|
||||
}
|
||||
if n_attr == 0 {
|
||||
return Err(vm.new_type_error("attrgetter expected 1 argument, got 0.".to_owned()));
|
||||
return Err(vm.new_type_error("attrgetter expected 1 argument, got 0."));
|
||||
}
|
||||
let mut attrs = Vec::with_capacity(n_attr);
|
||||
for o in args.args {
|
||||
if let Ok(r) = o.try_into_value(vm) {
|
||||
attrs.push(r);
|
||||
} else {
|
||||
return Err(vm.new_type_error("attribute name must be a string".to_owned()));
|
||||
return Err(vm.new_type_error("attribute name must be a string"));
|
||||
}
|
||||
}
|
||||
PyAttrGetter { attrs }
|
||||
@@ -467,10 +467,10 @@ mod _operator {
|
||||
fn py_new(cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult {
|
||||
// Check we get no keyword and at least one positional.
|
||||
if !args.kwargs.is_empty() {
|
||||
return Err(vm.new_type_error("itemgetter() takes no keyword arguments".to_owned()));
|
||||
return Err(vm.new_type_error("itemgetter() takes no keyword arguments"));
|
||||
}
|
||||
if args.args.is_empty() {
|
||||
return Err(vm.new_type_error("itemgetter expected 1 argument, got 0.".to_owned()));
|
||||
return Err(vm.new_type_error("itemgetter expected 1 argument, got 0."));
|
||||
}
|
||||
PyItemGetter { items: args.args }
|
||||
.into_ref_with_type(vm, cls)
|
||||
@@ -556,7 +556,7 @@ mod _operator {
|
||||
.into_ref_with_type(vm, cls)
|
||||
.map(Into::into)
|
||||
} else {
|
||||
Err(vm.new_type_error("method name must be a string".to_owned()))
|
||||
Err(vm.new_type_error("method name must be a string"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+14
-17
@@ -108,7 +108,7 @@ impl<const AVAILABLE: usize> FromArgs for DirFd<AVAILABLE> {
|
||||
};
|
||||
if AVAILABLE == 0 && fd != DEFAULT_DIR_FD {
|
||||
return Err(vm
|
||||
.new_not_implemented_error("dir_fd unavailable on this platform".to_owned())
|
||||
.new_not_implemented_error("dir_fd unavailable on this platform")
|
||||
.into());
|
||||
}
|
||||
Ok(Self([fd; AVAILABLE]))
|
||||
@@ -122,7 +122,7 @@ pub(super) struct FollowSymlinks(
|
||||
|
||||
fn bytes_as_os_str<'a>(b: &'a [u8], vm: &VirtualMachine) -> PyResult<&'a ffi::OsStr> {
|
||||
rustpython_common::os::bytes_as_os_str(b)
|
||||
.map_err(|_| vm.new_unicode_decode_error("can't decode path for utf-8".to_owned()))
|
||||
.map_err(|_| vm.new_unicode_decode_error("can't decode path for utf-8"))
|
||||
}
|
||||
|
||||
#[pymodule(sub)]
|
||||
@@ -343,9 +343,9 @@ pub(super) mod _os {
|
||||
#[cfg(not(all(unix, not(target_os = "redox"))))]
|
||||
{
|
||||
let _ = fno;
|
||||
return Err(vm.new_not_implemented_error(
|
||||
"can't pass fd to listdir on this platform".to_owned(),
|
||||
));
|
||||
return Err(
|
||||
vm.new_not_implemented_error("can't pass fd to listdir on this platform")
|
||||
);
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "redox")))]
|
||||
{
|
||||
@@ -388,10 +388,10 @@ pub(super) mod _os {
|
||||
let key = env_bytes_as_bytes(&key);
|
||||
let value = env_bytes_as_bytes(&value);
|
||||
if key.contains(&b'\0') || value.contains(&b'\0') {
|
||||
return Err(vm.new_value_error("embedded null byte".to_string()));
|
||||
return Err(vm.new_value_error("embedded null byte"));
|
||||
}
|
||||
if key.is_empty() || key.contains(&b'=') {
|
||||
return Err(vm.new_value_error("illegal environment variable name".to_string()));
|
||||
return Err(vm.new_value_error("illegal environment variable name"));
|
||||
}
|
||||
let key = super::bytes_as_os_str(key, vm)?;
|
||||
let value = super::bytes_as_os_str(value, vm)?;
|
||||
@@ -404,7 +404,7 @@ pub(super) mod _os {
|
||||
fn unsetenv(key: Either<PyStrRef, PyBytesRef>, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let key = env_bytes_as_bytes(&key);
|
||||
if key.contains(&b'\0') {
|
||||
return Err(vm.new_value_error("embedded null byte".to_string()));
|
||||
return Err(vm.new_value_error("embedded null byte"));
|
||||
}
|
||||
if key.is_empty() || key.contains(&b'=') {
|
||||
return Err(vm.new_errno_error(
|
||||
@@ -971,7 +971,7 @@ pub(super) mod _os {
|
||||
#[pyfunction]
|
||||
fn urandom(size: isize, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
|
||||
if size < 0 {
|
||||
return Err(vm.new_value_error("negative argument not allowed".to_owned()));
|
||||
return Err(vm.new_value_error("negative argument not allowed"));
|
||||
}
|
||||
let mut buf = vec![0u8; size as usize];
|
||||
getrandom::fill(&mut buf).map_err(|e| io::Error::from(e).into_pyexception(vm))?;
|
||||
@@ -1051,16 +1051,13 @@ pub(super) mod _os {
|
||||
let (acc, modif) = match (args.times, args.ns) {
|
||||
(Some(t), None) => {
|
||||
let (a, m) = parse_tup(&t).ok_or_else(|| {
|
||||
vm.new_type_error(
|
||||
"utime: 'times' must be either a tuple of two ints or None".to_owned(),
|
||||
)
|
||||
vm.new_type_error("utime: 'times' must be either a tuple of two ints or None")
|
||||
})?;
|
||||
(a.try_into_value(vm)?, m.try_into_value(vm)?)
|
||||
}
|
||||
(None, Some(ns)) => {
|
||||
let (a, m) = parse_tup(&ns).ok_or_else(|| {
|
||||
vm.new_type_error("utime: 'ns' must be a tuple of two ints".to_owned())
|
||||
})?;
|
||||
let (a, m) = parse_tup(&ns)
|
||||
.ok_or_else(|| vm.new_type_error("utime: 'ns' must be a tuple of two ints"))?;
|
||||
let ns_in_sec: PyObjectRef = vm.ctx.new_int(1_000_000_000).into();
|
||||
let ns_to_dur = |obj: PyObjectRef| {
|
||||
let divmod = vm._divmod(&obj, &ns_in_sec)?;
|
||||
@@ -1089,7 +1086,7 @@ pub(super) mod _os {
|
||||
}
|
||||
(Some(_), Some(_)) => {
|
||||
return Err(vm.new_value_error(
|
||||
"utime: you may specify either 'times' or 'ns' but not both".to_owned(),
|
||||
"utime: you may specify either 'times' or 'ns' but not both",
|
||||
));
|
||||
}
|
||||
};
|
||||
@@ -1286,7 +1283,7 @@ pub(super) mod _os {
|
||||
let count: usize = args
|
||||
.count
|
||||
.try_into()
|
||||
.map_err(|_| vm.new_value_error("count should >= 0".to_string()))?;
|
||||
.map_err(|_| vm.new_value_error("count should >= 0"))?;
|
||||
|
||||
// The flags argument is provided to allow
|
||||
// for future extensions and currently must be to 0.
|
||||
|
||||
+30
-46
@@ -288,8 +288,7 @@ pub mod module {
|
||||
|
||||
let flags = AccessFlags::from_bits(mode).ok_or_else(|| {
|
||||
vm.new_value_error(
|
||||
"One of the flags is wrong, there are only 4 possibilities F_OK, R_OK, W_OK and X_OK"
|
||||
.to_owned(),
|
||||
"One of the flags is wrong, there are only 4 possibilities F_OK, R_OK, W_OK and X_OK",
|
||||
)
|
||||
})?;
|
||||
|
||||
@@ -475,7 +474,7 @@ pub mod module {
|
||||
match arg {
|
||||
OptionalArg::Present(obj) => {
|
||||
if !obj.is_callable() {
|
||||
return Err(vm.new_type_error("Args must be callable".to_owned()));
|
||||
return Err(vm.new_type_error("Args must be callable"));
|
||||
}
|
||||
Ok(Some(obj))
|
||||
}
|
||||
@@ -486,7 +485,7 @@ pub mod module {
|
||||
let after_in_parent = into_option(self.after_in_parent, vm)?;
|
||||
let after_in_child = into_option(self.after_in_child, vm)?;
|
||||
if before.is_none() && after_in_parent.is_none() && after_in_child.is_none() {
|
||||
return Err(vm.new_type_error("At least one arg must be present".to_owned()));
|
||||
return Err(vm.new_type_error("At least one arg must be present"));
|
||||
}
|
||||
Ok((before, after_in_parent, after_in_child))
|
||||
}
|
||||
@@ -988,11 +987,9 @@ pub mod module {
|
||||
|
||||
let first = argv
|
||||
.first()
|
||||
.ok_or_else(|| vm.new_value_error("execv() arg 2 must not be empty".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_value_error("execv() arg 2 must not be empty"))?;
|
||||
if first.to_bytes().is_empty() {
|
||||
return Err(
|
||||
vm.new_value_error("execv() arg 2 first element cannot be empty".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("execv() arg 2 first element cannot be empty"));
|
||||
}
|
||||
|
||||
unistd::execv(&path, &argv)
|
||||
@@ -1016,12 +1013,10 @@ pub mod module {
|
||||
|
||||
let first = argv
|
||||
.first()
|
||||
.ok_or_else(|| vm.new_value_error("execve() arg 2 must not be empty".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_value_error("execve() arg 2 must not be empty"))?;
|
||||
|
||||
if first.to_bytes().is_empty() {
|
||||
return Err(
|
||||
vm.new_value_error("execve() arg 2 first element cannot be empty".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("execve() arg 2 first element cannot be empty"));
|
||||
}
|
||||
|
||||
let env = env
|
||||
@@ -1033,7 +1028,7 @@ pub mod module {
|
||||
);
|
||||
|
||||
if memchr::memchr(b'=', &key).is_some() {
|
||||
return Err(vm.new_value_error("illegal environment variable name".to_owned()));
|
||||
return Err(vm.new_value_error("illegal environment variable name"));
|
||||
}
|
||||
|
||||
let mut entry = key;
|
||||
@@ -1324,12 +1319,10 @@ pub mod module {
|
||||
.map(|item| {
|
||||
let tuple = item
|
||||
.downcast_ref::<crate::builtins::PyTuple>()
|
||||
.ok_or_else(|| vm.new_type_error("items() should return tuples".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_type_error("items() should return tuples"))?;
|
||||
let tuple_items = tuple.as_slice();
|
||||
if tuple_items.len() != 2 {
|
||||
return Err(vm.new_value_error(
|
||||
"items() tuples should have exactly 2 elements".to_owned(),
|
||||
));
|
||||
return Err(vm.new_value_error("items() tuples should have exactly 2 elements"));
|
||||
}
|
||||
Ok((tuple_items[0].clone(), tuple_items[1].clone()))
|
||||
})
|
||||
@@ -1339,19 +1332,13 @@ pub mod module {
|
||||
let k = OsPath::try_from_object(vm, k)?.into_bytes();
|
||||
let v = OsPath::try_from_object(vm, v)?.into_bytes();
|
||||
if k.contains(&0) {
|
||||
return Err(
|
||||
vm.new_value_error("envp dict key cannot contain a nul byte".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("envp dict key cannot contain a nul byte"));
|
||||
}
|
||||
if k.contains(&b'=') {
|
||||
return Err(vm.new_value_error(
|
||||
"envp dict key cannot contain a '=' character".to_owned(),
|
||||
));
|
||||
return Err(vm.new_value_error("envp dict key cannot contain a '=' character"));
|
||||
}
|
||||
if v.contains(&0) {
|
||||
return Err(
|
||||
vm.new_value_error("envp dict value cannot contain a nul byte".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("envp dict value cannot contain a nul byte"));
|
||||
}
|
||||
let mut env = k;
|
||||
env.push(b'=');
|
||||
@@ -1404,7 +1391,7 @@ pub mod module {
|
||||
.path
|
||||
.clone()
|
||||
.into_cstring(vm)
|
||||
.map_err(|_| vm.new_value_error("path should not have nul bytes".to_owned()))?;
|
||||
.map_err(|_| vm.new_value_error("path should not have nul bytes"))?;
|
||||
|
||||
let mut file_actions = unsafe {
|
||||
let mut fa = std::mem::MaybeUninit::uninit();
|
||||
@@ -1415,21 +1402,18 @@ pub mod module {
|
||||
for action in it.iter(vm)? {
|
||||
let action = action?;
|
||||
let (id, args) = action.split_first().ok_or_else(|| {
|
||||
vm.new_type_error(
|
||||
"Each file_actions element must be a non-empty tuple".to_owned(),
|
||||
)
|
||||
vm.new_type_error("Each file_actions element must be a non-empty tuple")
|
||||
})?;
|
||||
let id = i32::try_from_borrowed_object(vm, id)?;
|
||||
let id = PosixSpawnFileActionIdentifier::try_from(id).map_err(|_| {
|
||||
vm.new_type_error("Unknown file_actions identifier".to_owned())
|
||||
})?;
|
||||
let id = PosixSpawnFileActionIdentifier::try_from(id)
|
||||
.map_err(|_| vm.new_type_error("Unknown file_actions identifier"))?;
|
||||
let args: crate::function::FuncArgs = args.to_vec().into();
|
||||
let ret = match id {
|
||||
PosixSpawnFileActionIdentifier::Open => {
|
||||
let (fd, path, oflag, mode): (_, OsPath, _, _) = args.bind(vm)?;
|
||||
let path = CString::new(path.into_bytes()).map_err(|_| {
|
||||
vm.new_value_error(
|
||||
"POSIX_SPAWN_OPEN path should not have nul bytes".to_owned(),
|
||||
"POSIX_SPAWN_OPEN path should not have nul bytes",
|
||||
)
|
||||
})?;
|
||||
unsafe {
|
||||
@@ -1506,7 +1490,7 @@ pub mod module {
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
return Err(vm.new_not_implemented_error(
|
||||
"setsid parameter is not supported on this platform".to_owned(),
|
||||
"setsid parameter is not supported on this platform",
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1533,15 +1517,15 @@ pub mod module {
|
||||
if let Some(_scheduler) = self.scheduler {
|
||||
// TODO: Implement scheduler parameter handling
|
||||
// This requires platform-specific sched_param struct handling
|
||||
return Err(vm.new_not_implemented_error(
|
||||
"scheduler parameter is not yet implemented".to_owned(),
|
||||
));
|
||||
return Err(
|
||||
vm.new_not_implemented_error("scheduler parameter is not yet implemented")
|
||||
);
|
||||
}
|
||||
|
||||
if flags != 0 {
|
||||
// Check for potential overflow when casting to c_short
|
||||
if flags > libc::c_short::MAX as i32 {
|
||||
return Err(vm.new_value_error("Too many flags set for posix_spawn".to_owned()));
|
||||
return Err(vm.new_value_error("Too many flags set for posix_spawn"));
|
||||
}
|
||||
let ret =
|
||||
unsafe { libc::posix_spawnattr_setflags(&mut attrp, flags as libc::c_short) };
|
||||
@@ -1554,9 +1538,8 @@ pub mod module {
|
||||
.args
|
||||
.iter(vm)?
|
||||
.map(|res| {
|
||||
CString::new(res?.into_bytes()).map_err(|_| {
|
||||
vm.new_value_error("path should not have nul bytes".to_owned())
|
||||
})
|
||||
CString::new(res?.into_bytes())
|
||||
.map_err(|_| vm.new_value_error("path should not have nul bytes"))
|
||||
})
|
||||
.collect::<Result<_, _>>()?;
|
||||
let argv: Vec<*mut libc::c_char> = args
|
||||
@@ -1855,9 +1838,10 @@ pub mod module {
|
||||
Ok(int) => int.try_to_primitive(vm)?,
|
||||
Err(obj) => {
|
||||
let s = PyStrRef::try_from_object(vm, obj)?;
|
||||
s.as_str().parse::<PathconfVar>().map_err(|_| {
|
||||
vm.new_value_error("unrecognized configuration name".to_string())
|
||||
})? as i32
|
||||
s.as_str()
|
||||
.parse::<PathconfVar>()
|
||||
.map_err(|_| vm.new_value_error("unrecognized configuration name"))?
|
||||
as i32
|
||||
}
|
||||
};
|
||||
Ok(Self(i))
|
||||
@@ -2252,7 +2236,7 @@ pub mod module {
|
||||
if s.as_str() == "SC_PAGESIZE" {
|
||||
Ok(SysconfVar::SC_PAGESIZE)
|
||||
} else {
|
||||
Err(vm.new_value_error("unrecognized configuration name".to_string()))
|
||||
Err(vm.new_value_error("unrecognized configuration name"))
|
||||
}
|
||||
})? as i32
|
||||
}
|
||||
|
||||
@@ -147,7 +147,7 @@ pub(crate) mod _signal {
|
||||
_handler: PyObjectRef,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<Option<PyObjectRef>> {
|
||||
Err(vm.new_not_implemented_error("signal is not implemented on this platform".to_owned()))
|
||||
Err(vm.new_not_implemented_error("signal is not implemented on this platform"))
|
||||
}
|
||||
|
||||
#[cfg(any(unix, windows))]
|
||||
@@ -161,7 +161,7 @@ pub(crate) mod _signal {
|
||||
let signal_handlers = vm
|
||||
.signal_handlers
|
||||
.as_deref()
|
||||
.ok_or_else(|| vm.new_value_error("signal only works in main thread".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_value_error("signal only works in main thread"))?;
|
||||
|
||||
let sig_handler =
|
||||
match usize::try_from_borrowed_object(vm, &handler).ok() {
|
||||
@@ -169,8 +169,7 @@ pub(crate) mod _signal {
|
||||
Some(SIG_IGN) => SIG_IGN,
|
||||
None if handler.is_callable() => run_signal as sighandler_t,
|
||||
_ => return Err(vm.new_type_error(
|
||||
"signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object"
|
||||
.to_owned(),
|
||||
"signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object",
|
||||
)),
|
||||
};
|
||||
signal::check_signals(vm)?;
|
||||
@@ -194,7 +193,7 @@ pub(crate) mod _signal {
|
||||
let signal_handlers = vm
|
||||
.signal_handlers
|
||||
.as_deref()
|
||||
.ok_or_else(|| vm.new_value_error("getsignal only works in main thread".to_owned()))?;
|
||||
.ok_or_else(|| vm.new_value_error("getsignal only works in main thread"))?;
|
||||
let handler = signal_handlers.borrow()[signalnum as usize]
|
||||
.clone()
|
||||
.unwrap_or_else(|| vm.ctx.none());
|
||||
@@ -238,7 +237,7 @@ pub(crate) mod _signal {
|
||||
let fd = args.fd;
|
||||
|
||||
if vm.signal_handlers.is_none() {
|
||||
return Err(vm.new_value_error("signal only works in main thread".to_owned()));
|
||||
return Err(vm.new_value_error("signal only works in main thread"));
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
|
||||
@@ -128,7 +128,7 @@ mod _sre {
|
||||
let result = func.call((pattern, repl.clone()), vm)?;
|
||||
result
|
||||
.downcast::<Self>()
|
||||
.map_err(|_| vm.new_runtime_error("expected SRE_Template".to_owned()))
|
||||
.map_err(|_| vm.new_runtime_error("expected SRE_Template"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,7 +138,7 @@ mod _sre {
|
||||
template: PyListRef,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<Template> {
|
||||
let err = || vm.new_type_error("invalid template".to_owned());
|
||||
let err = || vm.new_type_error("invalid template");
|
||||
|
||||
let mut items = Vec::with_capacity(1);
|
||||
let v = template.borrow_vec();
|
||||
@@ -152,7 +152,7 @@ mod _sre {
|
||||
for trunk in trunks {
|
||||
let index: usize = trunk[0]
|
||||
.payload::<PyInt>()
|
||||
.ok_or_else(|| vm.new_type_error("expected usize".to_owned()))?
|
||||
.ok_or_else(|| vm.new_type_error("expected usize"))?
|
||||
.try_to_primitive(vm)?;
|
||||
items.push((index, trunk[1].clone()));
|
||||
}
|
||||
@@ -678,7 +678,7 @@ mod _sre {
|
||||
) -> PyResult<(isize, isize)> {
|
||||
let index = group.map_or(Ok(0), |group| {
|
||||
self.get_index(group, vm)
|
||||
.ok_or_else(|| vm.new_index_error("no such group".to_owned()))
|
||||
.ok_or_else(|| vm.new_index_error("no such group"))
|
||||
})?;
|
||||
Ok(self.regs[index])
|
||||
}
|
||||
|
||||
@@ -243,9 +243,7 @@ mod symtable {
|
||||
#[pymethod]
|
||||
fn get_namespace(&self, vm: &VirtualMachine) -> PyResult {
|
||||
if self.namespaces.len() != 1 {
|
||||
return Err(
|
||||
vm.new_value_error("namespace is bound to multiple namespaces".to_owned())
|
||||
);
|
||||
return Err(vm.new_value_error("namespace is bound to multiple namespaces"));
|
||||
}
|
||||
Ok(to_py_symbol_table(self.namespaces.first().unwrap().clone())
|
||||
.into_ref(&vm.ctx)
|
||||
|
||||
+9
-11
@@ -507,7 +507,7 @@ mod sys {
|
||||
fn _getframe(offset: OptionalArg<usize>, vm: &VirtualMachine) -> PyResult<FrameRef> {
|
||||
let offset = offset.into_option().unwrap_or(0);
|
||||
if offset > vm.frames.borrow().len() - 1 {
|
||||
return Err(vm.new_value_error("call stack is not deep enough".to_owned()));
|
||||
return Err(vm.new_value_error("call stack is not deep enough"));
|
||||
}
|
||||
let idx = vm.frames.borrow().len() - offset - 1;
|
||||
let frame = &vm.frames.borrow()[idx];
|
||||
@@ -760,9 +760,7 @@ mod sys {
|
||||
.to_usize()
|
||||
.filter(|&u| u >= 1)
|
||||
.ok_or_else(|| {
|
||||
vm.new_value_error(
|
||||
"recursion limit must be greater than or equal to one".to_owned(),
|
||||
)
|
||||
vm.new_value_error("recursion limit must be greater than or equal to one")
|
||||
})?;
|
||||
let recursion_depth = vm.current_recursion_depth();
|
||||
|
||||
@@ -803,7 +801,7 @@ mod sys {
|
||||
#[pyfunction]
|
||||
fn set_coroutine_origin_tracking_depth(depth: i32, vm: &VirtualMachine) -> PyResult<()> {
|
||||
if depth < 0 {
|
||||
return Err(vm.new_value_error("depth must be >= 0".to_owned()));
|
||||
return Err(vm.new_value_error("depth must be >= 0"));
|
||||
}
|
||||
crate::vm::thread::COROUTINE_ORIGIN_TRACKING_DEPTH.with(|cell| cell.set(depth as _));
|
||||
Ok(())
|
||||
@@ -825,7 +823,7 @@ mod sys {
|
||||
fn setswitchinterval(interval: f64, vm: &VirtualMachine) -> PyResult<()> {
|
||||
// Validate the interval parameter like CPython does
|
||||
if interval <= 0.0 {
|
||||
return Err(vm.new_value_error("switch interval must be strictly positive".to_owned()));
|
||||
return Err(vm.new_value_error("switch interval must be strictly positive"));
|
||||
}
|
||||
|
||||
// Store the switch interval value
|
||||
@@ -966,7 +964,7 @@ mod sys {
|
||||
|
||||
#[pyslot]
|
||||
fn slot_new(_cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_type_error("cannot create 'sys.flags' instances".to_owned()))
|
||||
Err(vm.new_type_error("cannot create 'sys.flags' instances"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1100,7 +1098,7 @@ mod sys {
|
||||
_args: crate::function::FuncArgs,
|
||||
vm: &crate::VirtualMachine,
|
||||
) -> crate::PyResult {
|
||||
Err(vm.new_type_error("cannot create 'sys.version_info' instances".to_owned()))
|
||||
Err(vm.new_type_error("cannot create 'sys.version_info' instances"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1185,17 +1183,17 @@ impl PyStderr<'_> {
|
||||
pub fn get_stdin(vm: &VirtualMachine) -> PyResult {
|
||||
vm.sys_module
|
||||
.get_attr("stdin", vm)
|
||||
.map_err(|_| vm.new_runtime_error("lost sys.stdin".to_owned()))
|
||||
.map_err(|_| vm.new_runtime_error("lost sys.stdin"))
|
||||
}
|
||||
pub fn get_stdout(vm: &VirtualMachine) -> PyResult {
|
||||
vm.sys_module
|
||||
.get_attr("stdout", vm)
|
||||
.map_err(|_| vm.new_runtime_error("lost sys.stdout".to_owned()))
|
||||
.map_err(|_| vm.new_runtime_error("lost sys.stdout"))
|
||||
}
|
||||
pub fn get_stderr(vm: &VirtualMachine) -> PyResult {
|
||||
vm.sys_module
|
||||
.get_attr("stderr", vm)
|
||||
.map_err(|_| vm.new_runtime_error("lost sys.stderr".to_owned()))
|
||||
.map_err(|_| vm.new_runtime_error("lost sys.stderr"))
|
||||
}
|
||||
|
||||
pub(crate) fn sysconfigdata_name() -> String {
|
||||
|
||||
@@ -132,7 +132,7 @@ pub(crate) mod _thread {
|
||||
#[pymethod(name = "release_lock")]
|
||||
fn release(&self, vm: &VirtualMachine) -> PyResult<()> {
|
||||
if !self.mu.is_locked() {
|
||||
return Err(vm.new_runtime_error("release unlocked lock".to_owned()));
|
||||
return Err(vm.new_runtime_error("release unlocked lock"));
|
||||
}
|
||||
unsafe { self.mu.unlock() };
|
||||
Ok(())
|
||||
@@ -172,7 +172,7 @@ pub(crate) mod _thread {
|
||||
impl Constructor for Lock {
|
||||
type Args = FuncArgs;
|
||||
fn py_new(_cls: PyTypeRef, _args: Self::Args, vm: &VirtualMachine) -> PyResult {
|
||||
Err(vm.new_type_error("cannot create '_thread.lock' instances".to_owned()))
|
||||
Err(vm.new_type_error("cannot create '_thread.lock' instances"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -218,7 +218,7 @@ pub(crate) mod _thread {
|
||||
#[pymethod(name = "release_lock")]
|
||||
fn release(&self, vm: &VirtualMachine) -> PyResult<()> {
|
||||
if !self.mu.is_locked() {
|
||||
return Err(vm.new_runtime_error("release unlocked lock".to_owned()));
|
||||
return Err(vm.new_runtime_error("release unlocked lock"));
|
||||
}
|
||||
unsafe { self.mu.unlock() };
|
||||
Ok(())
|
||||
|
||||
+16
-20
@@ -136,7 +136,7 @@ mod decl {
|
||||
not(any(target_os = "emscripten", target_os = "wasi"))
|
||||
))]
|
||||
fn _time(vm: &VirtualMachine) -> PyResult<f64> {
|
||||
Err(vm.new_not_implemented_error("time.time".to_owned()))
|
||||
Err(vm.new_not_implemented_error("time.time"))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
@@ -248,9 +248,7 @@ mod decl {
|
||||
}
|
||||
Either::B(int) => DateTime::<chrono::offset::Utc>::from_timestamp(int, 0),
|
||||
};
|
||||
timestamp.ok_or_else(|| {
|
||||
vm.new_overflow_error("timestamp out of range for platform time_t".to_owned())
|
||||
})
|
||||
timestamp.ok_or_else(|| vm.new_overflow_error("timestamp out of range for platform time_t"))
|
||||
}
|
||||
|
||||
impl OptionalArg<Either<f64, i64>> {
|
||||
@@ -363,7 +361,7 @@ mod decl {
|
||||
target_os = "emscripten",
|
||||
)))]
|
||||
fn get_thread_time(vm: &VirtualMachine) -> PyResult<Duration> {
|
||||
Err(vm.new_not_implemented_error("thread time unsupported in this system".to_owned()))
|
||||
Err(vm.new_not_implemented_error("thread time unsupported in this system"))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
@@ -428,7 +426,7 @@ mod decl {
|
||||
all(target_arch = "wasm32", not(target_os = "unknown"))
|
||||
)))]
|
||||
fn get_process_time(vm: &VirtualMachine) -> PyResult<Duration> {
|
||||
Err(vm.new_not_implemented_error("process time unsupported in this system".to_owned()))
|
||||
Err(vm.new_not_implemented_error("process time unsupported in this system"))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
@@ -491,9 +489,8 @@ mod decl {
|
||||
}
|
||||
|
||||
fn to_date_time(&self, vm: &VirtualMachine) -> PyResult<NaiveDateTime> {
|
||||
let invalid_overflow =
|
||||
|| vm.new_overflow_error("mktime argument out of range".to_owned());
|
||||
let invalid_value = || vm.new_value_error("invalid struct_time parameter".to_owned());
|
||||
let invalid_overflow = || vm.new_overflow_error("mktime argument out of range");
|
||||
let invalid_value = || vm.new_value_error("invalid struct_time parameter");
|
||||
|
||||
macro_rules! field {
|
||||
($field:ident) => {
|
||||
@@ -660,7 +657,7 @@ mod platform {
|
||||
false,
|
||||
clock_getres(ClockId::CLOCK_REALTIME, vm)?,
|
||||
),
|
||||
_ => return Err(vm.new_value_error("unknown clock".to_owned())),
|
||||
_ => return Err(vm.new_value_error("unknown clock")),
|
||||
};
|
||||
|
||||
Ok(py_namespace!(vm, {
|
||||
@@ -682,7 +679,7 @@ mod platform {
|
||||
)))]
|
||||
#[pyfunction]
|
||||
fn get_clock_info(_name: PyStrRef, vm: &VirtualMachine) -> PyResult<PyRef<PyNamespace>> {
|
||||
Err(vm.new_not_implemented_error("get_clock_info unsupported on this system".to_owned()))
|
||||
Err(vm.new_not_implemented_error("get_clock_info unsupported on this system"))
|
||||
}
|
||||
|
||||
pub(super) fn get_monotonic_time(vm: &VirtualMachine) -> PyResult<Duration> {
|
||||
@@ -747,9 +744,7 @@ mod platform {
|
||||
let u = (tv.tv_usec as i64).checked_mul(US_TO_NS)?;
|
||||
t.checked_add(u)
|
||||
})(tv)
|
||||
.ok_or_else(|| {
|
||||
vm.new_overflow_error("timestamp too large to convert to i64".to_owned())
|
||||
})
|
||||
.ok_or_else(|| vm.new_overflow_error("timestamp too large to convert to i64"))
|
||||
}
|
||||
let ru = getrusage(UsageWho::RUSAGE_SELF).map_err(|e| e.into_pyexception(vm))?;
|
||||
let utime = from_timeval(ru.user_time().into(), vm)?;
|
||||
@@ -791,9 +786,9 @@ mod platform {
|
||||
};
|
||||
|
||||
if frequency < 1 {
|
||||
Err(vm.new_runtime_error("invalid QueryPerformanceFrequency".to_owned()))
|
||||
Err(vm.new_runtime_error("invalid QueryPerformanceFrequency"))
|
||||
} else if frequency > i64::MAX / SEC_TO_NS {
|
||||
Err(vm.new_overflow_error("QueryPerformanceFrequency is too large".to_owned()))
|
||||
Err(vm.new_overflow_error("QueryPerformanceFrequency is too large"))
|
||||
} else {
|
||||
Ok(frequency)
|
||||
}
|
||||
@@ -844,9 +839,10 @@ mod platform {
|
||||
let ticks = unsafe { GetTickCount64() };
|
||||
|
||||
Ok(Duration::from_nanos(
|
||||
(ticks as i64).checked_mul(MS_TO_NS).ok_or_else(|| {
|
||||
vm.new_overflow_error("timestamp too large to convert to i64".to_owned())
|
||||
})? as u64,
|
||||
(ticks as i64)
|
||||
.checked_mul(MS_TO_NS)
|
||||
.ok_or_else(|| vm.new_overflow_error("timestamp too large to convert to i64"))?
|
||||
as u64,
|
||||
))
|
||||
}
|
||||
|
||||
@@ -873,7 +869,7 @@ mod platform {
|
||||
false,
|
||||
get_system_time_adjustment(vm)? as f64 * 1e-7,
|
||||
),
|
||||
_ => return Err(vm.new_value_error("unknown clock".to_owned())),
|
||||
_ => return Err(vm.new_value_error("unknown clock")),
|
||||
};
|
||||
|
||||
Ok(py_namespace!(vm, {
|
||||
|
||||
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user