mirror of
https://github.com/RustPython/RustPython.git
synced 2026-06-02 19:39:49 +09:00
fix cspell warnings
This commit is contained in:
@@ -10,14 +10,19 @@ cellarg
|
||||
cellvar
|
||||
cellvars
|
||||
cmpop
|
||||
weakreflist
|
||||
XXPRIME
|
||||
dictoffset
|
||||
elts
|
||||
xstat
|
||||
excepthandler
|
||||
fileutils
|
||||
finalbody
|
||||
freevar
|
||||
freevars
|
||||
fromlist
|
||||
heaptype
|
||||
HIGHRES
|
||||
IMMUTABLETYPE
|
||||
kwonlyarg
|
||||
kwonlyargs
|
||||
|
||||
@@ -1,17 +1,34 @@
|
||||
abiflags
|
||||
abstractmethods
|
||||
aenter
|
||||
aexit
|
||||
aiter
|
||||
anext
|
||||
appendleft
|
||||
argcount
|
||||
arrayiterator
|
||||
arraytype
|
||||
asend
|
||||
asyncgen
|
||||
athrow
|
||||
backslashreplace
|
||||
basicsize
|
||||
bdfl
|
||||
bigcharset
|
||||
breakpointhook
|
||||
cformat
|
||||
chunksize
|
||||
classcell
|
||||
closefd
|
||||
closesocket
|
||||
codepoint
|
||||
codepoints
|
||||
codesize
|
||||
contextvar
|
||||
cpython
|
||||
cratio
|
||||
dealloc
|
||||
debugbuild
|
||||
decompressor
|
||||
defaultaction
|
||||
descr
|
||||
@@ -19,15 +36,29 @@ dictcomp
|
||||
dictitems
|
||||
dictkeys
|
||||
dictview
|
||||
digestmod
|
||||
dllhandle
|
||||
docstring
|
||||
docstrings
|
||||
dunder
|
||||
endianness
|
||||
endpos
|
||||
eventmask
|
||||
excepthook
|
||||
exceptiongroup
|
||||
exitfuncs
|
||||
extendleft
|
||||
fastlocals
|
||||
fdel
|
||||
fedcba
|
||||
fget
|
||||
fileencoding
|
||||
fillchar
|
||||
fillvalue
|
||||
finallyhandler
|
||||
firstiter
|
||||
firstlineno
|
||||
fnctl
|
||||
frombytes
|
||||
fromhex
|
||||
fromunicode
|
||||
@@ -35,45 +66,87 @@ fset
|
||||
fspath
|
||||
fstring
|
||||
fstrings
|
||||
ftruncate
|
||||
genexpr
|
||||
getattro
|
||||
getcodesize
|
||||
getdefaultencoding
|
||||
getfilesystemencodeerrors
|
||||
getfilesystemencoding
|
||||
getformat
|
||||
getframe
|
||||
getnewargs
|
||||
getpip
|
||||
getrandom
|
||||
getrecursionlimit
|
||||
getrefcount
|
||||
getweakrefcount
|
||||
getweakrefs
|
||||
getwindowsversion
|
||||
gmtoff
|
||||
groupdict
|
||||
groupindex
|
||||
hamt
|
||||
hostnames
|
||||
idfunc
|
||||
idiv
|
||||
impls
|
||||
indexgroup
|
||||
infj
|
||||
instancecheck
|
||||
instanceof
|
||||
irepeat
|
||||
isabstractmethod
|
||||
isbytes
|
||||
iscased
|
||||
istext
|
||||
itemiterator
|
||||
itemsize
|
||||
iternext
|
||||
keepends
|
||||
keyfunc
|
||||
keyiterator
|
||||
kwarg
|
||||
kwargs
|
||||
kwdefaults
|
||||
kwonlyargcount
|
||||
lastgroup
|
||||
linearization
|
||||
linearize
|
||||
listcomp
|
||||
lvalue
|
||||
mappingproxy
|
||||
maskpri
|
||||
maxdigits
|
||||
MAXGROUPS
|
||||
MAXREPEAT
|
||||
maxsplit
|
||||
maxunicode
|
||||
memoryview
|
||||
memoryviewiterator
|
||||
metaclass
|
||||
metaclasses
|
||||
metatype
|
||||
mformat
|
||||
mro
|
||||
mros
|
||||
multiarch
|
||||
namereplace
|
||||
nanj
|
||||
nbytes
|
||||
ncallbacks
|
||||
ndigits
|
||||
ndim
|
||||
nlocals
|
||||
nonbytes
|
||||
origname
|
||||
posixsubprocess
|
||||
posonly
|
||||
posonlyargcount
|
||||
profilefunc
|
||||
pycodecs
|
||||
pycs
|
||||
pyexpat
|
||||
pytraverse
|
||||
PYTHONDEBUG
|
||||
PYTHONHOME
|
||||
PYTHONINSPECT
|
||||
@@ -82,11 +155,19 @@ PYTHONPATH
|
||||
PYTHONPATH
|
||||
PYTHONVERBOSE
|
||||
PYTHONWARNINGS
|
||||
pytraverse
|
||||
qualname
|
||||
quotetabs
|
||||
radd
|
||||
rdiv
|
||||
rdivmod
|
||||
readall
|
||||
readbuffer
|
||||
reconstructor
|
||||
releaselevel
|
||||
reverseitemiterator
|
||||
reverseiterator
|
||||
reversekeyiterator
|
||||
reversevalueiterator
|
||||
rfloordiv
|
||||
rlshift
|
||||
@@ -95,22 +176,42 @@ rpow
|
||||
rrshift
|
||||
rsub
|
||||
rtruediv
|
||||
rvalue
|
||||
scproxy
|
||||
setattro
|
||||
setcomp
|
||||
showwarnmsg
|
||||
warnmsg
|
||||
signum
|
||||
slotnames
|
||||
stacklevel
|
||||
stacksize
|
||||
startpos
|
||||
subclasscheck
|
||||
subclasshook
|
||||
suboffset
|
||||
sumprod
|
||||
surrogateescape
|
||||
surrogatepass
|
||||
sysconfigdata
|
||||
sysvars
|
||||
titlecased
|
||||
unimportable
|
||||
unionable
|
||||
unraisablehook
|
||||
unsliceable
|
||||
urandom
|
||||
valueiterator
|
||||
vararg
|
||||
varargs
|
||||
varnames
|
||||
warningregistry
|
||||
warnmsg
|
||||
warnoptions
|
||||
warnopts
|
||||
weakproxy
|
||||
winver
|
||||
xopts
|
||||
withdata
|
||||
xmlcharrefreplace
|
||||
xoptions
|
||||
xopts
|
||||
yieldfrom
|
||||
|
||||
@@ -3,27 +3,42 @@ bidi
|
||||
biguint
|
||||
bindgen
|
||||
bitflags
|
||||
bitor
|
||||
bstr
|
||||
byteorder
|
||||
byteset
|
||||
caseless
|
||||
chrono
|
||||
consts
|
||||
cranelift
|
||||
cstring
|
||||
datelike
|
||||
deserializer
|
||||
flate2
|
||||
fract
|
||||
getres
|
||||
hasher
|
||||
hexf
|
||||
hexversion
|
||||
idents
|
||||
illumos
|
||||
indexmap
|
||||
insta
|
||||
keccak
|
||||
lalrpop
|
||||
lexopt
|
||||
libc
|
||||
libloading
|
||||
libz
|
||||
longlong
|
||||
Manually
|
||||
maplit
|
||||
memmap
|
||||
memmem
|
||||
metas
|
||||
modpow
|
||||
msvc
|
||||
muldiv
|
||||
nanos
|
||||
objclass
|
||||
peekable
|
||||
@@ -31,17 +46,25 @@ powc
|
||||
powf
|
||||
prepended
|
||||
punct
|
||||
puruspe
|
||||
replacen
|
||||
rsplitn
|
||||
rustc
|
||||
rustfmt
|
||||
rustyline
|
||||
seekfrom
|
||||
siphash
|
||||
splitn
|
||||
subsec
|
||||
thiserror
|
||||
timelike
|
||||
timsort
|
||||
trai
|
||||
ulonglong
|
||||
unic
|
||||
unistd
|
||||
unsync
|
||||
wasmbind
|
||||
widestring
|
||||
winapi
|
||||
winsock
|
||||
winsock
|
||||
|
||||
17
.cspell.json
17
.cspell.json
@@ -47,16 +47,24 @@
|
||||
// words - list of words to be always considered correct
|
||||
"words": [
|
||||
// RustPython
|
||||
"aiterable",
|
||||
"alnum",
|
||||
"baseclass",
|
||||
"boxvec",
|
||||
"Bytecode",
|
||||
"cfgs",
|
||||
"codegen",
|
||||
"coro",
|
||||
"dedentations",
|
||||
"dedents",
|
||||
"deduped",
|
||||
"downcasted",
|
||||
"dumpable",
|
||||
"emscripten",
|
||||
"excs",
|
||||
"finalizer",
|
||||
"GetSet",
|
||||
"groupref",
|
||||
"internable",
|
||||
"makeunicodedata",
|
||||
"miri",
|
||||
@@ -100,6 +108,15 @@
|
||||
"unraisable",
|
||||
"wasi",
|
||||
"zelf",
|
||||
// unix
|
||||
"CLOEXEC",
|
||||
"codeset",
|
||||
"endgrent",
|
||||
"getrusage",
|
||||
"nanosleep",
|
||||
"WRLCK",
|
||||
// win32
|
||||
"birthtime",
|
||||
],
|
||||
// flagWords - list of words to be always considered incorrect
|
||||
"flagWords": [
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// cspell:ignore
|
||||
//! An unresizable vector backed by a `Box<[T]>`
|
||||
|
||||
#![allow(clippy::needless_lifetimes)]
|
||||
|
||||
@@ -53,14 +53,14 @@ impl HashSecret {
|
||||
fix_sentinel(mod_int(self.hash_one(data) as _))
|
||||
}
|
||||
|
||||
pub fn hash_iter<'a, T: 'a, I, F, E>(&self, iter: I, hashf: F) -> Result<PyHash, E>
|
||||
pub fn hash_iter<'a, T: 'a, I, F, E>(&self, iter: I, hash_func: F) -> Result<PyHash, E>
|
||||
where
|
||||
I: IntoIterator<Item = &'a T>,
|
||||
F: Fn(&'a T) -> Result<PyHash, E>,
|
||||
{
|
||||
let mut hasher = self.build_hasher();
|
||||
for element in iter {
|
||||
let item_hash = hashf(element)?;
|
||||
let item_hash = hash_func(element)?;
|
||||
item_hash.hash(&mut hasher);
|
||||
}
|
||||
Ok(fix_sentinel(mod_int(hasher.finish() as PyHash)))
|
||||
|
||||
@@ -3,7 +3,7 @@ use std::rc::Rc;
|
||||
#[cfg(feature = "threading")]
|
||||
use std::sync::Arc;
|
||||
|
||||
// type aliases instead of newtypes because you can't do `fn method(self: PyRc<Self>)` with a
|
||||
// type aliases instead of new-types because you can't do `fn method(self: PyRc<Self>)` with a
|
||||
// newtype; requires the arbitrary_self_types unstable feature
|
||||
|
||||
#[cfg(feature = "threading")]
|
||||
|
||||
@@ -13,7 +13,7 @@ mod non_threading {
|
||||
|
||||
impl<T> StaticCell<T> {
|
||||
#[doc(hidden)]
|
||||
pub const fn _from_localkey(inner: &'static LocalKey<OnceCell<&'static T>>) -> Self {
|
||||
pub const fn _from_local_key(inner: &'static LocalKey<OnceCell<&'static T>>) -> Self {
|
||||
Self { inner }
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ mod non_threading {
|
||||
::std::thread_local! {
|
||||
$vis static $name: $crate::lock::OnceCell<&'static $t> = $crate::lock::OnceCell::new();
|
||||
}
|
||||
$crate::static_cell::StaticCell::_from_localkey(&$name)
|
||||
$crate::static_cell::StaticCell::_from_local_key(&$name)
|
||||
};)+
|
||||
};
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ pub fn derive_from_args(input: TokenStream) -> TokenStream {
|
||||
/// - `IMMUTABLETYPE`: class attributes are immutable.
|
||||
/// - `with`: which trait implementations are to be included in the python class.
|
||||
/// ```rust, ignore
|
||||
/// #[pyclass(module = "mymodule", name = "MyClass", base = "BaseClass")]
|
||||
/// #[pyclass(module = "my_module", name = "MyClass", base = "BaseClass")]
|
||||
/// struct MyStruct {
|
||||
/// x: i32,
|
||||
/// }
|
||||
@@ -161,8 +161,8 @@ pub fn pyexception(attr: TokenStream, item: TokenStream) -> TokenStream {
|
||||
/// - `name`: the name of the python module,
|
||||
/// by default, it is the name of the module, but this can be configured.
|
||||
/// ```rust, ignore
|
||||
/// // This will create a module named `mymodule`
|
||||
/// #[pymodule(name = "mymodule")]
|
||||
/// // This will create a module named `my_module`
|
||||
/// #[pymodule(name = "my_module")]
|
||||
/// mod module {
|
||||
/// }
|
||||
/// ```
|
||||
@@ -173,7 +173,7 @@ pub fn pyexception(attr: TokenStream, item: TokenStream) -> TokenStream {
|
||||
/// }
|
||||
///
|
||||
/// #[pymodule(with(submodule))]
|
||||
/// mod mymodule {
|
||||
/// mod my_module {
|
||||
/// }
|
||||
/// ```
|
||||
/// - `with`: declare the list of submodules that this module contains (see `sub` for example).
|
||||
@@ -190,7 +190,7 @@ pub fn pyexception(attr: TokenStream, item: TokenStream) -> TokenStream {
|
||||
/// #### Examples
|
||||
/// ```rust, ignore
|
||||
/// #[pymodule]
|
||||
/// mod mymodule {
|
||||
/// mod my_module {
|
||||
/// #[pyattr]
|
||||
/// const MY_CONSTANT: i32 = 42;
|
||||
/// #[pyattr]
|
||||
|
||||
@@ -9,13 +9,13 @@
|
||||
//! use rustpython_vm::{pymodule, py_freeze};
|
||||
//! fn main() {
|
||||
//! rustpython::run(|vm| {
|
||||
//! vm.add_native_module("mymod".to_owned(), Box::new(mymod::make_module));
|
||||
//! vm.add_frozen(py_freeze!(source = "def foo(): pass", module_name = "otherthing"));
|
||||
//! vm.add_native_module("my_mod".to_owned(), Box::new(my_mod::make_module));
|
||||
//! vm.add_frozen(py_freeze!(source = "def foo(): pass", module_name = "other_thing"));
|
||||
//! });
|
||||
//! }
|
||||
//!
|
||||
//! #[pymodule]
|
||||
//! mod mymod {
|
||||
//! mod my_mod {
|
||||
//! use rustpython_vm::builtins::PyStrRef;
|
||||
//TODO: use rustpython_vm::prelude::*;
|
||||
//!
|
||||
|
||||
@@ -880,14 +880,14 @@ mod array {
|
||||
return Err(vm.new_value_error("negative count".to_owned()));
|
||||
}
|
||||
let n = vm.check_repeat_or_overflow_error(itemsize, n)?;
|
||||
let nbytes = n * itemsize;
|
||||
let n_bytes = n * itemsize;
|
||||
|
||||
let b = vm.call_method(&f, "read", (nbytes,))?;
|
||||
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()))?;
|
||||
|
||||
let not_enough_bytes = b.len() != nbytes;
|
||||
let not_enough_bytes = b.len() != n_bytes;
|
||||
|
||||
self._from_bytes(b.as_bytes(), itemsize, vm)?;
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// spell-checker:ignore hexlify unhexlify uuencodes
|
||||
// spell-checker:ignore hexlify unhexlify uuencodes CRCTAB
|
||||
|
||||
pub(super) use decl::crc32;
|
||||
pub(crate) use decl::make_module;
|
||||
@@ -339,7 +339,7 @@ mod decl {
|
||||
|| (buffer[idx + 1] >= b'a' && buffer[idx + 1] <= b'f')
|
||||
|| (buffer[idx + 1] >= b'0' && buffer[idx + 1] <= b'9'))
|
||||
{
|
||||
// hexval
|
||||
// hex val
|
||||
if let (Some(ch1), Some(ch2)) =
|
||||
(unhex_nibble(buffer[idx]), unhex_nibble(buffer[idx + 1]))
|
||||
{
|
||||
|
||||
@@ -981,14 +981,14 @@ mod _csv {
|
||||
String::from_utf8(input.to_vec()).unwrap()
|
||||
};
|
||||
loop {
|
||||
let (res, nread, nwritten, nends) = reader.read_record(
|
||||
let (res, n_read, n_written, n_ends) = reader.read_record(
|
||||
&input.as_bytes()[input_offset..],
|
||||
&mut buffer[output_offset..],
|
||||
&mut output_ends[output_ends_offset..],
|
||||
);
|
||||
input_offset += nread;
|
||||
output_offset += nwritten;
|
||||
output_ends_offset += nends;
|
||||
input_offset += n_read;
|
||||
output_offset += n_written;
|
||||
output_ends_offset += n_ends;
|
||||
match res {
|
||||
csv_core::ReadRecordResult::InputEmpty => {}
|
||||
csv_core::ReadRecordResult::OutputFull => resize_buf(buffer),
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// cspell:disable
|
||||
|
||||
pub(crate) use fcntl::make_module;
|
||||
|
||||
#[pymodule]
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// cspell:disable
|
||||
pub(crate) use grp::make_module;
|
||||
|
||||
#[pymodule]
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// cspell:ignore abday abmon yesexpr
|
||||
|
||||
pub(crate) use _locale::make_module;
|
||||
|
||||
#[cfg(windows)]
|
||||
|
||||
@@ -136,7 +136,7 @@ mod math {
|
||||
if base.is_sign_negative() {
|
||||
return Err(vm.new_value_error("math domain error".to_owned()));
|
||||
}
|
||||
log2(x, vm).map(|logx| logx / base.log2())
|
||||
log2(x, vm).map(|log_x| log_x / base.log2())
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
@@ -188,7 +188,7 @@ mod math {
|
||||
|
||||
#[pyfunction]
|
||||
fn log10(x: PyObjectRef, vm: &VirtualMachine) -> PyResult<f64> {
|
||||
log2(x, vm).map(|logx| logx / 10f64.log2())
|
||||
log2(x, vm).map(|log_x| log_x / 10f64.log2())
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
@@ -588,16 +588,16 @@ mod math {
|
||||
where
|
||||
F: Fn(&BigInt, &PyInt) -> BigInt,
|
||||
{
|
||||
let argvec = args.into_vec();
|
||||
let arg_vec = args.into_vec();
|
||||
|
||||
if argvec.is_empty() {
|
||||
if arg_vec.is_empty() {
|
||||
return default;
|
||||
} else if argvec.len() == 1 {
|
||||
return op(argvec[0].as_bigint(), &argvec[0]);
|
||||
} else if arg_vec.len() == 1 {
|
||||
return op(arg_vec[0].as_bigint(), &arg_vec[0]);
|
||||
}
|
||||
|
||||
let mut res = argvec[0].as_bigint().clone();
|
||||
for num in &argvec[1..] {
|
||||
let mut res = arg_vec[0].as_bigint().clone();
|
||||
for num in &arg_vec[1..] {
|
||||
res = op(&res, num)
|
||||
}
|
||||
res
|
||||
@@ -895,15 +895,15 @@ mod math {
|
||||
return Err(vm.new_value_error("math domain error".to_owned()));
|
||||
}
|
||||
|
||||
let absx = x.abs();
|
||||
let absy = y.abs();
|
||||
let modulus = absx % absy;
|
||||
let abs_x = x.abs();
|
||||
let abs_y = y.abs();
|
||||
let modulus = abs_x % abs_y;
|
||||
|
||||
let c = absy - modulus;
|
||||
let c = abs_y - modulus;
|
||||
let r = match modulus.partial_cmp(&c) {
|
||||
Some(Ordering::Less) => modulus,
|
||||
Some(Ordering::Greater) => -c,
|
||||
_ => modulus - 2.0 * fmod(0.5 * (absx - modulus), absy),
|
||||
_ => modulus - 2.0 * fmod(0.5 * (abs_x - modulus), abs_y),
|
||||
};
|
||||
|
||||
return Ok(1.0_f64.copysign(x) * r);
|
||||
|
||||
@@ -79,7 +79,7 @@ mod _random {
|
||||
};
|
||||
|
||||
let words = (k - 1) / 32 + 1;
|
||||
let wordarray = (0..words)
|
||||
let word_array = (0..words)
|
||||
.map(|_| {
|
||||
let word = gen_u32(k);
|
||||
k = k.wrapping_sub(32);
|
||||
@@ -87,7 +87,7 @@ mod _random {
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let uint = BigUint::new(wordarray);
|
||||
let uint = BigUint::new(word_array);
|
||||
// very unlikely but might as well check
|
||||
let sign = if uint.is_zero() {
|
||||
Sign::NoSign
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// spell-checker:ignore logoption openlog setlogmask upto
|
||||
// spell-checker:ignore logoption openlog setlogmask upto NDELAY
|
||||
|
||||
pub(crate) use syslog::make_module;
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// cspell:ignore createcommand
|
||||
|
||||
pub(crate) use self::_tkinter::make_module;
|
||||
|
||||
#[pymodule]
|
||||
@@ -45,7 +47,7 @@ mod _tkinter {
|
||||
|
||||
#[pyfunction]
|
||||
fn create(args: FuncArgs, _vm: &VirtualMachine) -> PyResult<TkApp> {
|
||||
// TODO: handle arguements
|
||||
// TODO: handle arguments
|
||||
// TODO: this means creating 2 tk instances is not possible.
|
||||
let tk = Tk::new(()).unwrap();
|
||||
Ok(TkApp {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// spell-checker:ignore compressobj decompressobj zdict chunksize zlibmodule miniz
|
||||
// spell-checker:ignore compressobj decompressobj zdict chunksize zlibmodule miniz chunker
|
||||
|
||||
pub(crate) use zlib::make_module;
|
||||
|
||||
|
||||
@@ -200,7 +200,7 @@ pub trait AnyStr {
|
||||
F: Fn(&Self) -> PyObjectRef;
|
||||
|
||||
#[inline]
|
||||
fn py_startsendswith<'a, T, F>(
|
||||
fn py_starts_ends_with<'a, T, F>(
|
||||
&self,
|
||||
affix: &'a PyObject,
|
||||
func_name: &str,
|
||||
|
||||
@@ -375,7 +375,7 @@ impl PyByteArray {
|
||||
Some(x) => x,
|
||||
None => return Ok(false),
|
||||
};
|
||||
substr.py_startsendswith(
|
||||
substr.py_starts_ends_with(
|
||||
&affix,
|
||||
"endswith",
|
||||
"bytes",
|
||||
@@ -396,7 +396,7 @@ impl PyByteArray {
|
||||
Some(x) => x,
|
||||
None => return Ok(false),
|
||||
};
|
||||
substr.py_startsendswith(
|
||||
substr.py_starts_ends_with(
|
||||
&affix,
|
||||
"startswith",
|
||||
"bytes",
|
||||
|
||||
@@ -299,7 +299,7 @@ impl PyBytes {
|
||||
Some(x) => x,
|
||||
None => return Ok(false),
|
||||
};
|
||||
substr.py_startsendswith(
|
||||
substr.py_starts_ends_with(
|
||||
&affix,
|
||||
"endswith",
|
||||
"bytes",
|
||||
@@ -319,7 +319,7 @@ impl PyBytes {
|
||||
Some(x) => x,
|
||||
None => return Ok(false),
|
||||
};
|
||||
substr.py_startsendswith(
|
||||
substr.py_starts_ends_with(
|
||||
&affix,
|
||||
"startswith",
|
||||
"bytes",
|
||||
@@ -541,7 +541,7 @@ impl PyRef<PyBytes> {
|
||||
/// Other possible values are 'ignore', 'replace'
|
||||
/// For a list of possible encodings,
|
||||
/// see https://docs.python.org/3/library/codecs.html#standard-encodings
|
||||
/// currently, only 'utf-8' and 'ascii' emplemented
|
||||
/// currently, only 'utf-8' and 'ascii' implemented
|
||||
#[pymethod]
|
||||
fn decode(self, args: DecodeArgs, vm: &VirtualMachine) -> PyResult<PyStrRef> {
|
||||
bytes_decode(self.into(), args, vm)
|
||||
|
||||
@@ -53,7 +53,7 @@ impl From<Complex64> for PyComplex {
|
||||
|
||||
impl PyObjectRef {
|
||||
/// Tries converting a python object into a complex, returns an option of whether the complex
|
||||
/// and whether the object was a complex originally or coereced into one
|
||||
/// and whether the object was a complex originally or coerced into one
|
||||
pub fn try_complex(&self, vm: &VirtualMachine) -> PyResult<Option<(Complex64, bool)>> {
|
||||
if let Some(complex) = self.payload_if_exact::<PyComplex>(vm) {
|
||||
return Ok(Some((complex.value, true)));
|
||||
|
||||
@@ -281,8 +281,8 @@ impl PyDict {
|
||||
|
||||
#[pymethod(magic)]
|
||||
fn or(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
let dicted: Result<PyDictRef, _> = other.downcast();
|
||||
if let Ok(other) = dicted {
|
||||
let other_dict: Result<PyDictRef, _> = other.downcast();
|
||||
if let Ok(other) = other_dict {
|
||||
let self_cp = self.copy();
|
||||
self_cp.merge_dict(other, vm)?;
|
||||
return Ok(self_cp.into_pyobject(vm));
|
||||
@@ -397,8 +397,8 @@ impl PyRef<PyDict> {
|
||||
|
||||
#[pymethod(magic)]
|
||||
fn ror(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
let dicted: Result<PyDictRef, _> = other.downcast();
|
||||
if let Ok(other) = dicted {
|
||||
let other_dict: Result<PyDictRef, _> = other.downcast();
|
||||
if let Ok(other) = other_dict {
|
||||
let other_cp = other.copy();
|
||||
other_cp.merge_dict(self, vm)?;
|
||||
return Ok(other_cp.into_pyobject(vm));
|
||||
|
||||
@@ -198,9 +198,9 @@ impl PyFunction {
|
||||
// function definition calls for
|
||||
if nargs < nexpected_args {
|
||||
let defaults = get_defaults!().0.as_ref().map(|tup| tup.as_slice());
|
||||
let ndefs = defaults.map_or(0, |d| d.len());
|
||||
let n_defs = defaults.map_or(0, |d| d.len());
|
||||
|
||||
let nrequired = code.arg_count as usize - ndefs;
|
||||
let nrequired = code.arg_count as usize - n_defs;
|
||||
|
||||
// Given the number of defaults available, check all the arguments for which we
|
||||
// _don't_ have defaults; if any are missing, raise an exception
|
||||
@@ -642,9 +642,9 @@ impl PyBoundMethod {
|
||||
vm: &VirtualMachine,
|
||||
) -> (Option<PyObjectRef>, (PyObjectRef, Option<PyObjectRef>)) {
|
||||
let builtins_getattr = vm.builtins.get_attr("getattr", vm).ok();
|
||||
let funcself = self.object.clone();
|
||||
let funcname = self.function.get_attr("__name__", vm).ok();
|
||||
(builtins_getattr, (funcself, funcname))
|
||||
let func_self = self.object.clone();
|
||||
let func_name = self.function.get_attr("__name__", vm).ok();
|
||||
(builtins_getattr, (func_self, func_name))
|
||||
}
|
||||
|
||||
#[pygetset(magic)]
|
||||
@@ -700,16 +700,16 @@ impl Representable for PyBoundMethod {
|
||||
#[inline]
|
||||
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
|
||||
#[allow(clippy::needless_match)] // False positive on nightly
|
||||
let funcname =
|
||||
let func_name =
|
||||
if let Some(qname) = vm.get_attribute_opt(zelf.function.clone(), "__qualname__")? {
|
||||
Some(qname)
|
||||
} else {
|
||||
vm.get_attribute_opt(zelf.function.clone(), "__name__")?
|
||||
};
|
||||
let funcname: Option<PyStrRef> = funcname.and_then(|o| o.downcast().ok());
|
||||
let func_name: Option<PyStrRef> = func_name.and_then(|o| o.downcast().ok());
|
||||
Ok(format!(
|
||||
"<bound method {} of {}>",
|
||||
funcname.as_ref().map_or("?", |s| s.as_str()),
|
||||
func_name.as_ref().map_or("?", |s| s.as_str()),
|
||||
&zelf.object.repr(vm)?.as_str(),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -524,13 +524,14 @@ impl PyInt {
|
||||
|
||||
// Malachite division uses floor rounding, Python uses half-even
|
||||
let remainder = &value - &rounded;
|
||||
let halfpow10 = &pow10 / BigInt::from(2);
|
||||
let correction =
|
||||
if remainder > halfpow10 || (remainder == halfpow10 && quotient.is_odd()) {
|
||||
pow10
|
||||
} else {
|
||||
BigInt::from(0)
|
||||
};
|
||||
let half_pow10 = &pow10 / BigInt::from(2);
|
||||
let correction = if remainder > half_pow10
|
||||
|| (remainder == half_pow10 && quotient.is_odd())
|
||||
{
|
||||
pow10
|
||||
} else {
|
||||
BigInt::from(0)
|
||||
};
|
||||
let rounded = (rounded + correction) * sign;
|
||||
return Ok(vm.ctx.new_int(rounded));
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ pub struct PyMemoryView {
|
||||
// avoid double release when memoryview had released the buffer before drop
|
||||
buffer: ManuallyDrop<PyBuffer>,
|
||||
// the released memoryview does not mean the buffer is destroyed
|
||||
// because the possible another memeoryview is viewing from it
|
||||
// because the possible another memoryview is viewing from it
|
||||
released: AtomicCell<bool>,
|
||||
// start does NOT mean the bytes before start will not be visited,
|
||||
// it means the point we starting to get the absolute position via
|
||||
@@ -103,7 +103,7 @@ impl PyMemoryView {
|
||||
})
|
||||
}
|
||||
|
||||
/// don't use this function to create the memeoryview if the buffer is exporting
|
||||
/// don't use this function to create the memoryview if the buffer is exporting
|
||||
/// via another memoryview, use PyMemoryView::new_view() or PyMemoryView::from_object
|
||||
/// to reduce the chain
|
||||
pub fn from_buffer_range(
|
||||
@@ -262,8 +262,8 @@ impl PyMemoryView {
|
||||
// no suboffset set, stride must be positive
|
||||
self.start += stride as usize * range.start;
|
||||
}
|
||||
let newlen = range.len();
|
||||
self.desc.dim_desc[dim].0 = newlen;
|
||||
let new_len = range.len();
|
||||
self.desc.dim_desc[dim].0 = new_len;
|
||||
}
|
||||
|
||||
fn init_slice(&mut self, slice: &PySlice, dim: usize, vm: &VirtualMachine) -> PyResult<()> {
|
||||
|
||||
@@ -836,7 +836,7 @@ impl PyStr {
|
||||
Some(x) => x,
|
||||
None => return Ok(false),
|
||||
};
|
||||
substr.py_startsendswith(
|
||||
substr.py_starts_ends_with(
|
||||
&affix,
|
||||
"endswith",
|
||||
"str",
|
||||
@@ -856,7 +856,7 @@ impl PyStr {
|
||||
Some(x) => x,
|
||||
None => return Ok(false),
|
||||
};
|
||||
substr.py_startsendswith(
|
||||
substr.py_starts_ends_with(
|
||||
&affix,
|
||||
"startswith",
|
||||
"str",
|
||||
|
||||
@@ -29,7 +29,7 @@ impl PySuperInner {
|
||||
let obj = if vm.is_none(&obj) {
|
||||
None
|
||||
} else {
|
||||
let obj_type = supercheck(typ.clone(), obj.clone(), vm)?;
|
||||
let obj_type = super_check(typ.clone(), obj.clone(), vm)?;
|
||||
Some((obj, obj_type))
|
||||
};
|
||||
Ok(Self { typ, obj })
|
||||
@@ -236,7 +236,7 @@ impl Representable for PySuper {
|
||||
}
|
||||
}
|
||||
|
||||
fn supercheck(ty: PyTypeRef, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyTypeRef> {
|
||||
fn super_check(ty: PyTypeRef, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyTypeRef> {
|
||||
if let Ok(cls) = obj.clone().downcast::<PyType>() {
|
||||
if cls.fast_issubclass(&ty) {
|
||||
return Ok(cls);
|
||||
|
||||
@@ -748,10 +748,10 @@ impl PyBytesInner {
|
||||
self.elements.py_zfill(width)
|
||||
}
|
||||
|
||||
// len(self)>=1, from="", len(to)>=1, maxcount>=1
|
||||
fn replace_interleave(&self, to: PyBytesInner, maxcount: Option<usize>) -> Vec<u8> {
|
||||
// len(self)>=1, from="", len(to)>=1, max_count>=1
|
||||
fn replace_interleave(&self, to: PyBytesInner, max_count: Option<usize>) -> Vec<u8> {
|
||||
let place_count = self.elements.len() + 1;
|
||||
let count = maxcount.map_or(place_count, |v| std::cmp::min(v, place_count)) - 1;
|
||||
let count = max_count.map_or(place_count, |v| std::cmp::min(v, place_count)) - 1;
|
||||
let capacity = self.elements.len() + count * to.len();
|
||||
let mut result = Vec::with_capacity(capacity);
|
||||
let to_slice = to.elements.as_slice();
|
||||
@@ -764,8 +764,12 @@ impl PyBytesInner {
|
||||
result
|
||||
}
|
||||
|
||||
fn replace_delete(&self, from: PyBytesInner, maxcount: Option<usize>) -> Vec<u8> {
|
||||
let count = count_substring(self.elements.as_slice(), from.elements.as_slice(), maxcount);
|
||||
fn replace_delete(&self, from: PyBytesInner, max_count: Option<usize>) -> Vec<u8> {
|
||||
let count = count_substring(
|
||||
self.elements.as_slice(),
|
||||
from.elements.as_slice(),
|
||||
max_count,
|
||||
);
|
||||
if count == 0 {
|
||||
// no matches
|
||||
return self.elements.clone();
|
||||
@@ -793,7 +797,7 @@ impl PyBytesInner {
|
||||
&self,
|
||||
from: PyBytesInner,
|
||||
to: PyBytesInner,
|
||||
maxcount: Option<usize>,
|
||||
max_count: Option<usize>,
|
||||
) -> Vec<u8> {
|
||||
let len = from.len();
|
||||
let mut iter = self.elements.find_iter(&from.elements);
|
||||
@@ -801,7 +805,7 @@ impl PyBytesInner {
|
||||
let mut new = if let Some(offset) = iter.next() {
|
||||
let mut new = self.elements.clone();
|
||||
new[offset..offset + len].clone_from_slice(to.elements.as_slice());
|
||||
if maxcount == Some(1) {
|
||||
if max_count == Some(1) {
|
||||
return new;
|
||||
} else {
|
||||
new
|
||||
@@ -810,7 +814,7 @@ impl PyBytesInner {
|
||||
return self.elements.clone();
|
||||
};
|
||||
|
||||
let mut count = maxcount.unwrap_or(usize::MAX) - 1;
|
||||
let mut count = max_count.unwrap_or(usize::MAX) - 1;
|
||||
for offset in iter {
|
||||
new[offset..offset + len].clone_from_slice(to.elements.as_slice());
|
||||
count -= 1;
|
||||
@@ -825,10 +829,14 @@ impl PyBytesInner {
|
||||
&self,
|
||||
from: PyBytesInner,
|
||||
to: PyBytesInner,
|
||||
maxcount: Option<usize>,
|
||||
max_count: Option<usize>,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<Vec<u8>> {
|
||||
let count = count_substring(self.elements.as_slice(), from.elements.as_slice(), maxcount);
|
||||
let count = count_substring(
|
||||
self.elements.as_slice(),
|
||||
from.elements.as_slice(),
|
||||
max_count,
|
||||
);
|
||||
if count == 0 {
|
||||
// no matches, return unchanged
|
||||
return Ok(self.elements.clone());
|
||||
@@ -866,19 +874,19 @@ impl PyBytesInner {
|
||||
&self,
|
||||
from: PyBytesInner,
|
||||
to: PyBytesInner,
|
||||
maxcount: OptionalArg<isize>,
|
||||
max_count: OptionalArg<isize>,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<Vec<u8>> {
|
||||
// stringlib_replace in CPython
|
||||
let maxcount = match maxcount {
|
||||
OptionalArg::Present(maxcount) if maxcount >= 0 => {
|
||||
if maxcount == 0 || (self.elements.is_empty() && !from.is_empty()) {
|
||||
let max_count = match max_count {
|
||||
OptionalArg::Present(max_count) if max_count >= 0 => {
|
||||
if max_count == 0 || (self.elements.is_empty() && !from.is_empty()) {
|
||||
// nothing to do; return the original bytes
|
||||
return Ok(self.elements.clone());
|
||||
} else if self.elements.is_empty() && from.is_empty() {
|
||||
return Ok(to.elements);
|
||||
}
|
||||
Some(maxcount as usize)
|
||||
Some(max_count as usize)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
@@ -892,7 +900,7 @@ impl PyBytesInner {
|
||||
// insert the 'to' bytes everywhere.
|
||||
// >>> b"Python".replace(b"", b".")
|
||||
// b'.P.y.t.h.o.n.'
|
||||
return Ok(self.replace_interleave(to, maxcount));
|
||||
return Ok(self.replace_interleave(to, max_count));
|
||||
}
|
||||
|
||||
// Except for b"".replace(b"", b"A") == b"A" there is no way beyond this
|
||||
@@ -904,13 +912,13 @@ impl PyBytesInner {
|
||||
|
||||
if to.elements.is_empty() {
|
||||
// delete all occurrences of 'from' bytes
|
||||
Ok(self.replace_delete(from, maxcount))
|
||||
Ok(self.replace_delete(from, max_count))
|
||||
} else if from.len() == to.len() {
|
||||
// Handle special case where both bytes have the same length
|
||||
Ok(self.replace_in_place(from, to, maxcount))
|
||||
Ok(self.replace_in_place(from, to, max_count))
|
||||
} else {
|
||||
// Otherwise use the more generic algorithms
|
||||
self.replace_general(from, to, maxcount, vm)
|
||||
self.replace_general(from, to, max_count, vm)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -978,10 +986,10 @@ where
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn count_substring(haystack: &[u8], needle: &[u8], maxcount: Option<usize>) -> usize {
|
||||
fn count_substring(haystack: &[u8], needle: &[u8], max_count: Option<usize>) -> usize {
|
||||
let substrings = haystack.find_iter(needle);
|
||||
if let Some(maxcount) = maxcount {
|
||||
std::cmp::min(substrings.take(maxcount).count(), maxcount)
|
||||
if let Some(max_count) = max_count {
|
||||
std::cmp::min(substrings.take(max_count).count(), max_count)
|
||||
} else {
|
||||
substrings.count()
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
//cspell:ignore bytesobject
|
||||
|
||||
//! Implementation of Printf-Style string formatting
|
||||
//! as per the [Python Docs](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting).
|
||||
|
||||
|
||||
@@ -212,10 +212,10 @@ impl VirtualMachine {
|
||||
if let Some(text) = maybe_text {
|
||||
// if text ends with \n, remove it
|
||||
let rtext = text.as_str().trim_end_matches('\n');
|
||||
let ltext = rtext.trim_start_matches([' ', '\n', '\x0c']); // \x0c is \f
|
||||
let spaces = (rtext.len() - ltext.len()) as isize;
|
||||
let l_text = rtext.trim_start_matches([' ', '\n', '\x0c']); // \x0c is \f
|
||||
let spaces = (rtext.len() - l_text.len()) as isize;
|
||||
|
||||
writeln!(output, " {}", ltext)?;
|
||||
writeln!(output, " {}", l_text)?;
|
||||
|
||||
let maybe_offset: Option<isize> =
|
||||
getattr("offset").and_then(|obj| obj.try_to_value::<isize>(vm).ok());
|
||||
@@ -237,7 +237,7 @@ impl VirtualMachine {
|
||||
let colno = offset - 1 - spaces;
|
||||
let end_colno = end_offset - 1 - spaces;
|
||||
if colno >= 0 {
|
||||
let caretspace = ltext.chars().collect::<Vec<_>>()[..colno as usize]
|
||||
let caret_space = l_text.chars().collect::<Vec<_>>()[..colno as usize]
|
||||
.iter()
|
||||
.map(|c| if c.is_whitespace() { *c } else { ' ' })
|
||||
.collect::<String>();
|
||||
@@ -250,7 +250,7 @@ impl VirtualMachine {
|
||||
writeln!(
|
||||
output,
|
||||
" {}{}",
|
||||
caretspace,
|
||||
caret_space,
|
||||
"^".repeat(error_width as usize)
|
||||
)?;
|
||||
}
|
||||
|
||||
@@ -350,7 +350,7 @@ impl ExecutingFrame<'_> {
|
||||
fn run(&mut self, vm: &VirtualMachine) -> PyResult<ExecutionResult> {
|
||||
flame_guard!(format!("Frame::run({})", self.code.obj_name));
|
||||
// Execute until return or exception:
|
||||
let instrs = &self.code.instructions;
|
||||
let instructions = &self.code.instructions;
|
||||
let mut arg_state = bytecode::OpArgState::default();
|
||||
loop {
|
||||
let idx = self.lasti() as usize;
|
||||
@@ -359,7 +359,7 @@ impl ExecutingFrame<'_> {
|
||||
// self.code.locations[idx], self.code.source_path
|
||||
// );
|
||||
self.update_lasti(|i| *i += 1);
|
||||
let bytecode::CodeUnit { op, arg } = instrs[idx];
|
||||
let bytecode::CodeUnit { op, arg } = instructions[idx];
|
||||
let arg = arg_state.extend(arg);
|
||||
let mut do_extend_arg = false;
|
||||
let result = self.execute_instruction(op, arg, &mut do_extend_arg, vm);
|
||||
@@ -805,14 +805,14 @@ impl ExecutingFrame<'_> {
|
||||
dict.set_item(&*key, value, vm)?;
|
||||
Ok(None)
|
||||
}
|
||||
bytecode::Instruction::BinaryOperation { op } => self.execute_binop(vm, op.get(arg)),
|
||||
bytecode::Instruction::BinaryOperation { op } => self.execute_bin_op(vm, op.get(arg)),
|
||||
bytecode::Instruction::BinaryOperationInplace { op } => {
|
||||
self.execute_binop_inplace(vm, op.get(arg))
|
||||
self.execute_bin_op_inplace(vm, op.get(arg))
|
||||
}
|
||||
bytecode::Instruction::LoadAttr { idx } => self.load_attr(vm, idx.get(arg)),
|
||||
bytecode::Instruction::StoreAttr { idx } => self.store_attr(vm, idx.get(arg)),
|
||||
bytecode::Instruction::DeleteAttr { idx } => self.delete_attr(vm, idx.get(arg)),
|
||||
bytecode::Instruction::UnaryOperation { op } => self.execute_unop(vm, op.get(arg)),
|
||||
bytecode::Instruction::UnaryOperation { op } => self.execute_unary_op(vm, op.get(arg)),
|
||||
bytecode::Instruction::TestOperation { op } => self.execute_test(vm, op.get(arg)),
|
||||
bytecode::Instruction::CompareOperation { op } => self.execute_compare(vm, op.get(arg)),
|
||||
bytecode::Instruction::ReturnValue => {
|
||||
@@ -1792,7 +1792,7 @@ impl ExecutingFrame<'_> {
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "flame-it", flame("Frame"))]
|
||||
fn execute_binop(&mut self, vm: &VirtualMachine, op: bytecode::BinaryOperator) -> FrameResult {
|
||||
fn execute_bin_op(&mut self, vm: &VirtualMachine, op: bytecode::BinaryOperator) -> FrameResult {
|
||||
let b_ref = &self.pop_value();
|
||||
let a_ref = &self.pop_value();
|
||||
let value = match op {
|
||||
@@ -1814,7 +1814,7 @@ impl ExecutingFrame<'_> {
|
||||
self.push_value(value);
|
||||
Ok(None)
|
||||
}
|
||||
fn execute_binop_inplace(
|
||||
fn execute_bin_op_inplace(
|
||||
&mut self,
|
||||
vm: &VirtualMachine,
|
||||
op: bytecode::BinaryOperator,
|
||||
@@ -1842,7 +1842,11 @@ impl ExecutingFrame<'_> {
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "flame-it", flame("Frame"))]
|
||||
fn execute_unop(&mut self, vm: &VirtualMachine, op: bytecode::UnaryOperator) -> FrameResult {
|
||||
fn execute_unary_op(
|
||||
&mut self,
|
||||
vm: &VirtualMachine,
|
||||
op: bytecode::UnaryOperator,
|
||||
) -> FrameResult {
|
||||
let a = self.pop_value();
|
||||
let value = match op {
|
||||
bytecode::UnaryOperator::Minus => vm._neg(&a)?,
|
||||
|
||||
@@ -276,7 +276,7 @@ impl ArgumentError {
|
||||
vm.new_type_error(format!("{name} is an invalid keyword argument"))
|
||||
}
|
||||
ArgumentError::RequiredKeywordArgument(name) => {
|
||||
vm.new_type_error(format!("Required keyqord only argument {name}"))
|
||||
vm.new_type_error(format!("Required keyword only argument {name}"))
|
||||
}
|
||||
ArgumentError::Exception(ex) => ex,
|
||||
}
|
||||
|
||||
@@ -94,7 +94,7 @@ impl FsPath {
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn to_widecstring(&self, vm: &VirtualMachine) -> PyResult<widestring::WideCString> {
|
||||
pub fn to_wide_cstring(&self, vm: &VirtualMachine) -> PyResult<widestring::WideCString> {
|
||||
widestring::WideCString::from_os_str(self.as_os_str(vm)?)
|
||||
.map_err(|err| err.into_pyexception(vm))
|
||||
}
|
||||
|
||||
@@ -76,7 +76,7 @@ impl TryFromObject for ArgCallable {
|
||||
/// objects using a generic type parameter that implements `TryFromObject`.
|
||||
pub struct ArgIterable<T = PyObjectRef> {
|
||||
iterable: PyObjectRef,
|
||||
iterfn: Option<crate::types::IterFunc>,
|
||||
iter_fn: Option<crate::types::IterFunc>,
|
||||
_item: PhantomData<T>,
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ impl<T> ArgIterable<T> {
|
||||
/// This operation may fail if an exception is raised while invoking the
|
||||
/// `__iter__` method of the iterable object.
|
||||
pub fn iter<'a>(&self, vm: &'a VirtualMachine) -> PyResult<PyIterIter<'a, T>> {
|
||||
let iter = PyIter::new(match self.iterfn {
|
||||
let iter = PyIter::new(match self.iter_fn {
|
||||
Some(f) => f(self.iterable.clone(), vm)?,
|
||||
None => PySequenceIterator::new(self.iterable.clone(), vm)?.into_pyobject(vm),
|
||||
});
|
||||
@@ -105,17 +105,17 @@ where
|
||||
T: TryFromObject,
|
||||
{
|
||||
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
|
||||
let iterfn = {
|
||||
let iter_fn = {
|
||||
let cls = obj.class();
|
||||
let iterfn = cls.mro_find_map(|x| x.slots.iter.load());
|
||||
if iterfn.is_none() && !cls.has_attr(identifier!(vm, __getitem__)) {
|
||||
let iter_fn = cls.mro_find_map(|x| x.slots.iter.load());
|
||||
if iter_fn.is_none() && !cls.has_attr(identifier!(vm, __getitem__)) {
|
||||
return Err(vm.new_type_error(format!("'{}' object is not iterable", cls.name())));
|
||||
}
|
||||
iterfn
|
||||
iter_fn
|
||||
};
|
||||
Ok(Self {
|
||||
iterable: obj,
|
||||
iterfn,
|
||||
iter_fn,
|
||||
_item: PhantomData,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -81,7 +81,7 @@ pub fn make_frozen(vm: &VirtualMachine, name: &str) -> PyResult<PyRef<PyCode>> {
|
||||
|
||||
pub fn import_frozen(vm: &VirtualMachine, module_name: &str) -> PyResult {
|
||||
let frozen = make_frozen(vm, module_name)?;
|
||||
let module = import_codeobj(vm, module_name, frozen, false)?;
|
||||
let module = import_code_obj(vm, module_name, frozen, false)?;
|
||||
debug_assert!(module.get_attr(identifier!(vm, __name__), vm).is_ok());
|
||||
// TODO: give a correct origname here
|
||||
module.set_attr("__origname__", vm.ctx.new_str(module_name.to_owned()), vm)?;
|
||||
@@ -116,7 +116,7 @@ pub fn import_file(
|
||||
vm.compile_opts(),
|
||||
)
|
||||
.map_err(|err| vm.new_syntax_error(&err, Some(content)))?;
|
||||
import_codeobj(vm, module_name, code, true)
|
||||
import_code_obj(vm, module_name, code, true)
|
||||
}
|
||||
|
||||
#[cfg(feature = "rustpython-compiler")]
|
||||
@@ -129,10 +129,10 @@ pub fn import_source(vm: &VirtualMachine, module_name: &str, content: &str) -> P
|
||||
vm.compile_opts(),
|
||||
)
|
||||
.map_err(|err| vm.new_syntax_error(&err, Some(content)))?;
|
||||
import_codeobj(vm, module_name, code, false)
|
||||
import_code_obj(vm, module_name, code, false)
|
||||
}
|
||||
|
||||
pub fn import_codeobj(
|
||||
pub fn import_code_obj(
|
||||
vm: &VirtualMachine,
|
||||
module_name: &str,
|
||||
code_obj: PyRef<PyCode>,
|
||||
|
||||
@@ -207,7 +207,7 @@ impl WeakRefList {
|
||||
hash: Radium::new(crate::common::hash::SENTINEL),
|
||||
};
|
||||
let weak = PyRef::new_ref(obj, cls, dict);
|
||||
// SAFETY: we don't actually own the PyObjectWeaks inside `list`, and every time we take
|
||||
// SAFETY: we don't actually own the PyObjectWeak's inside `list`, and every time we take
|
||||
// one out of the list we immediately wrap it in ManuallyDrop or forget it
|
||||
inner.list.push_front(unsafe { ptr::read(&weak) });
|
||||
inner.ref_count += 1;
|
||||
@@ -1301,6 +1301,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn miri_test_drop() {
|
||||
//cspell:ignore dfghjkl
|
||||
let ctx = crate::Context::genesis();
|
||||
let obj = ctx.new_bytes(b"dfghjkl".to_vec());
|
||||
drop(obj);
|
||||
|
||||
@@ -70,7 +70,7 @@ impl OsPath {
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn to_widecstring(&self, vm: &VirtualMachine) -> PyResult<widestring::WideCString> {
|
||||
pub fn to_wide_cstring(&self, vm: &VirtualMachine) -> PyResult<widestring::WideCString> {
|
||||
widestring::WideCString::from_os_str(&self.path).map_err(|err| err.to_pyexception(vm))
|
||||
}
|
||||
|
||||
@@ -167,18 +167,18 @@ impl<'a> IOErrorBuilder<'a> {
|
||||
|
||||
impl ToPyException for IOErrorBuilder<'_> {
|
||||
fn to_pyexception(&self, vm: &VirtualMachine) -> PyBaseExceptionRef {
|
||||
let excp = self.error.to_pyexception(vm);
|
||||
let exc = self.error.to_pyexception(vm);
|
||||
|
||||
if let Some(filename) = &self.filename {
|
||||
excp.as_object()
|
||||
exc.as_object()
|
||||
.set_attr("filename", filename.filename(vm), vm)
|
||||
.unwrap();
|
||||
}
|
||||
if let Some(filename2) = &self.filename2 {
|
||||
excp.as_object()
|
||||
exc.as_object()
|
||||
.set_attr("filename2", filename2.filename(vm), vm)
|
||||
.unwrap();
|
||||
}
|
||||
excp
|
||||
exc
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,7 +131,7 @@ impl PyBuffer {
|
||||
|
||||
// drop PyBuffer without calling release
|
||||
// after this function, the owner should use forget()
|
||||
// or wrap PyBuffer in the ManaullyDrop to prevent drop()
|
||||
// or wrap PyBuffer in the ManuallyDrop to prevent drop()
|
||||
pub(crate) unsafe fn drop_without_release(&mut self) {
|
||||
// SAFETY: requirements forwarded from caller
|
||||
unsafe {
|
||||
@@ -267,7 +267,7 @@ impl BufferDescriptor {
|
||||
Ok(pos)
|
||||
}
|
||||
|
||||
pub fn for_each_segment<F>(&self, try_conti: bool, mut f: F)
|
||||
pub fn for_each_segment<F>(&self, try_contiguous: bool, mut f: F)
|
||||
where
|
||||
F: FnMut(Range<isize>),
|
||||
{
|
||||
@@ -275,20 +275,20 @@ impl BufferDescriptor {
|
||||
f(0..self.itemsize as isize);
|
||||
return;
|
||||
}
|
||||
if try_conti && self.is_last_dim_contiguous() {
|
||||
if try_contiguous && self.is_last_dim_contiguous() {
|
||||
self._for_each_segment::<_, true>(0, 0, &mut f);
|
||||
} else {
|
||||
self._for_each_segment::<_, false>(0, 0, &mut f);
|
||||
}
|
||||
}
|
||||
|
||||
fn _for_each_segment<F, const CONTI: bool>(&self, mut index: isize, dim: usize, f: &mut F)
|
||||
fn _for_each_segment<F, const CONTIGUOUS: bool>(&self, mut index: isize, dim: usize, f: &mut F)
|
||||
where
|
||||
F: FnMut(Range<isize>),
|
||||
{
|
||||
let (shape, stride, suboffset) = self.dim_desc[dim];
|
||||
if dim + 1 == self.ndim() {
|
||||
if CONTI {
|
||||
if CONTIGUOUS {
|
||||
f(index..index + (shape * self.itemsize) as isize);
|
||||
} else {
|
||||
for _ in 0..shape {
|
||||
@@ -300,13 +300,13 @@ impl BufferDescriptor {
|
||||
return;
|
||||
}
|
||||
for _ in 0..shape {
|
||||
self._for_each_segment::<F, CONTI>(index + suboffset, dim + 1, f);
|
||||
self._for_each_segment::<F, CONTIGUOUS>(index + suboffset, dim + 1, f);
|
||||
index += stride;
|
||||
}
|
||||
}
|
||||
|
||||
/// zip two BufferDescriptor with the same shape
|
||||
pub fn zip_eq<F>(&self, other: &Self, try_conti: bool, mut f: F)
|
||||
pub fn zip_eq<F>(&self, other: &Self, try_contiguous: bool, mut f: F)
|
||||
where
|
||||
F: FnMut(Range<isize>, Range<isize>) -> bool,
|
||||
{
|
||||
@@ -314,14 +314,14 @@ impl BufferDescriptor {
|
||||
f(0..self.itemsize as isize, 0..other.itemsize as isize);
|
||||
return;
|
||||
}
|
||||
if try_conti && self.is_last_dim_contiguous() {
|
||||
if try_contiguous && self.is_last_dim_contiguous() {
|
||||
self._zip_eq::<_, true>(other, 0, 0, 0, &mut f);
|
||||
} else {
|
||||
self._zip_eq::<_, false>(other, 0, 0, 0, &mut f);
|
||||
}
|
||||
}
|
||||
|
||||
fn _zip_eq<F, const CONTI: bool>(
|
||||
fn _zip_eq<F, const CONTIGUOUS: bool>(
|
||||
&self,
|
||||
other: &Self,
|
||||
mut a_index: isize,
|
||||
@@ -335,7 +335,7 @@ impl BufferDescriptor {
|
||||
let (_b_shape, b_stride, b_suboffset) = other.dim_desc[dim];
|
||||
debug_assert_eq!(shape, _b_shape);
|
||||
if dim + 1 == self.ndim() {
|
||||
if CONTI {
|
||||
if CONTIGUOUS {
|
||||
if f(
|
||||
a_index..a_index + (shape * self.itemsize) as isize,
|
||||
b_index..b_index + (shape * other.itemsize) as isize,
|
||||
@@ -360,7 +360,7 @@ impl BufferDescriptor {
|
||||
}
|
||||
|
||||
for _ in 0..shape {
|
||||
self._zip_eq::<F, CONTI>(
|
||||
self._zip_eq::<F, CONTIGUOUS>(
|
||||
other,
|
||||
a_index + a_suboffset,
|
||||
b_index + b_suboffset,
|
||||
|
||||
@@ -125,12 +125,12 @@ impl TryFromObject for PyIter<PyObjectRef> {
|
||||
// in the vm when a for loop is entered. Next, it is used when the builtin
|
||||
// function 'iter' is called.
|
||||
fn try_from_object(vm: &VirtualMachine, iter_target: PyObjectRef) -> PyResult<Self> {
|
||||
let getiter = {
|
||||
let get_iter = {
|
||||
let cls = iter_target.class();
|
||||
cls.mro_find_map(|x| x.slots.iter.load())
|
||||
};
|
||||
if let Some(getiter) = getiter {
|
||||
let iter = getiter(iter_target, vm)?;
|
||||
if let Some(get_iter) = get_iter {
|
||||
let iter = get_iter(iter_target, vm)?;
|
||||
if PyIter::check(&iter) {
|
||||
Ok(Self(iter))
|
||||
} else {
|
||||
|
||||
@@ -28,8 +28,8 @@ impl PyObjectRef {
|
||||
// int PyObject_GenericSetDict(PyObject *o, PyObject *value, void *context)
|
||||
|
||||
#[inline(always)]
|
||||
pub fn rich_compare(self, other: Self, opid: PyComparisonOp, vm: &VirtualMachine) -> PyResult {
|
||||
self._cmp(&other, opid, vm).map(|res| res.to_pyobject(vm))
|
||||
pub fn rich_compare(self, other: Self, op_id: PyComparisonOp, vm: &VirtualMachine) -> PyResult {
|
||||
self._cmp(&other, op_id, vm).map(|res| res.to_pyobject(vm))
|
||||
}
|
||||
|
||||
pub fn bytes(self, vm: &VirtualMachine) -> PyResult {
|
||||
@@ -323,17 +323,17 @@ impl PyObject {
|
||||
match op {
|
||||
PyComparisonOp::Eq => Ok(Either::B(self.is(&other))),
|
||||
PyComparisonOp::Ne => Ok(Either::B(!self.is(&other))),
|
||||
_ => Err(vm.new_unsupported_binop_error(self, other, op.operator_token())),
|
||||
_ => Err(vm.new_unsupported_bin_op_error(self, other, op.operator_token())),
|
||||
}
|
||||
}
|
||||
#[inline(always)]
|
||||
pub fn rich_compare_bool(
|
||||
&self,
|
||||
other: &Self,
|
||||
opid: PyComparisonOp,
|
||||
op_id: PyComparisonOp,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<bool> {
|
||||
match self._cmp(other, opid, vm)? {
|
||||
match self._cmp(other, op_id, vm)? {
|
||||
Either::A(obj) => obj.try_to_bool(vm),
|
||||
Either::B(other) => Ok(other),
|
||||
}
|
||||
@@ -479,13 +479,13 @@ impl PyObject {
|
||||
let r = if let Ok(typ) = cls.try_to_ref::<PyType>(vm) {
|
||||
if self.class().fast_issubclass(typ) {
|
||||
true
|
||||
} else if let Ok(icls) =
|
||||
} else if let Ok(i_cls) =
|
||||
PyTypeRef::try_from_object(vm, self.get_attr(identifier!(vm, __class__), vm)?)
|
||||
{
|
||||
if icls.is(self.class()) {
|
||||
if i_cls.is(self.class()) {
|
||||
false
|
||||
} else {
|
||||
icls.fast_issubclass(typ)
|
||||
i_cls.fast_issubclass(typ)
|
||||
}
|
||||
} else {
|
||||
false
|
||||
@@ -497,11 +497,11 @@ impl PyObject {
|
||||
cls.class()
|
||||
)
|
||||
})?;
|
||||
let icls: PyObjectRef = self.get_attr(identifier!(vm, __class__), vm)?;
|
||||
if vm.is_none(&icls) {
|
||||
let i_cls: PyObjectRef = self.get_attr(identifier!(vm, __class__), vm)?;
|
||||
if vm.is_none(&i_cls) {
|
||||
false
|
||||
} else {
|
||||
icls.abstract_issubclass(cls, vm)?
|
||||
i_cls.abstract_issubclass(cls, vm)?
|
||||
}
|
||||
};
|
||||
Ok(r)
|
||||
|
||||
@@ -588,12 +588,14 @@ mod builtins {
|
||||
iterator.class().name()
|
||||
)));
|
||||
}
|
||||
PyIter::new(iterator).next(vm).map(|iret| match iret {
|
||||
PyIterReturn::Return(obj) => PyIterReturn::Return(obj),
|
||||
PyIterReturn::StopIteration(v) => {
|
||||
default_value.map_or(PyIterReturn::StopIteration(v), PyIterReturn::Return)
|
||||
}
|
||||
})
|
||||
PyIter::new(iterator)
|
||||
.next(vm)
|
||||
.map(|iter_ret| match iter_ret {
|
||||
PyIterReturn::Return(obj) => PyIterReturn::Return(obj),
|
||||
PyIterReturn::StopIteration(v) => {
|
||||
default_value.map_or(PyIterReturn::StopIteration(v), PyIterReturn::Return)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
|
||||
@@ -673,14 +673,14 @@ mod _io {
|
||||
}
|
||||
fn _readinto(
|
||||
zelf: PyObjectRef,
|
||||
bufobj: PyObjectRef,
|
||||
buf_obj: PyObjectRef,
|
||||
method: &str,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<usize> {
|
||||
let b = ArgMemoryBuffer::try_from_borrowed_object(vm, &bufobj)?;
|
||||
let b = ArgMemoryBuffer::try_from_borrowed_object(vm, &buf_obj)?;
|
||||
let l = b.len();
|
||||
let data = vm.call_method(&zelf, method, (l,))?;
|
||||
if data.is(&bufobj) {
|
||||
if data.is(&buf_obj) {
|
||||
return Ok(l);
|
||||
}
|
||||
let mut buf = b.borrow_buf_mut();
|
||||
@@ -929,25 +929,25 @@ mod _io {
|
||||
) -> PyResult<Option<usize>> {
|
||||
let len = buf_range.len();
|
||||
let res = if let Some(buf) = buf {
|
||||
let memobj = PyMemoryView::from_buffer_range(buf, buf_range, vm)?.to_pyobject(vm);
|
||||
let mem_obj = PyMemoryView::from_buffer_range(buf, buf_range, vm)?.to_pyobject(vm);
|
||||
|
||||
// TODO: loop if write() raises an interrupt
|
||||
vm.call_method(self.raw.as_ref().unwrap(), "write", (memobj,))?
|
||||
vm.call_method(self.raw.as_ref().unwrap(), "write", (mem_obj,))?
|
||||
} else {
|
||||
let v = std::mem::take(&mut self.buffer);
|
||||
let writebuf = VecBuffer::from(v).into_ref(&vm.ctx);
|
||||
let memobj = PyMemoryView::from_buffer_range(
|
||||
writebuf.clone().into_pybuffer(true),
|
||||
let write_buf = VecBuffer::from(v).into_ref(&vm.ctx);
|
||||
let mem_obj = PyMemoryView::from_buffer_range(
|
||||
write_buf.clone().into_pybuffer(true),
|
||||
buf_range,
|
||||
vm,
|
||||
)?
|
||||
.into_ref(&vm.ctx);
|
||||
|
||||
// TODO: loop if write() raises an interrupt
|
||||
let res = vm.call_method(self.raw.as_ref().unwrap(), "write", (memobj.clone(),));
|
||||
let res = vm.call_method(self.raw.as_ref().unwrap(), "write", (mem_obj.clone(),));
|
||||
|
||||
memobj.release();
|
||||
self.buffer = writebuf.take();
|
||||
mem_obj.release();
|
||||
self.buffer = write_buf.take();
|
||||
|
||||
res?
|
||||
};
|
||||
@@ -1159,9 +1159,9 @@ mod _io {
|
||||
let res = match v {
|
||||
Either::A(v) => {
|
||||
let v = v.unwrap_or(&mut self.buffer);
|
||||
let readbuf = VecBuffer::from(std::mem::take(v)).into_ref(&vm.ctx);
|
||||
let memobj = PyMemoryView::from_buffer_range(
|
||||
readbuf.clone().into_pybuffer(false),
|
||||
let read_buf = VecBuffer::from(std::mem::take(v)).into_ref(&vm.ctx);
|
||||
let mem_obj = PyMemoryView::from_buffer_range(
|
||||
read_buf.clone().into_pybuffer(false),
|
||||
buf_range,
|
||||
vm,
|
||||
)?
|
||||
@@ -1169,17 +1169,17 @@ mod _io {
|
||||
|
||||
// TODO: loop if readinto() raises an interrupt
|
||||
let res =
|
||||
vm.call_method(self.raw.as_ref().unwrap(), "readinto", (memobj.clone(),));
|
||||
vm.call_method(self.raw.as_ref().unwrap(), "readinto", (mem_obj.clone(),));
|
||||
|
||||
memobj.release();
|
||||
std::mem::swap(v, &mut readbuf.take());
|
||||
mem_obj.release();
|
||||
std::mem::swap(v, &mut read_buf.take());
|
||||
|
||||
res?
|
||||
}
|
||||
Either::B(buf) => {
|
||||
let memobj = PyMemoryView::from_buffer_range(buf, buf_range, vm)?;
|
||||
let mem_obj = PyMemoryView::from_buffer_range(buf, buf_range, vm)?;
|
||||
// TODO: loop if readinto() raises an interrupt
|
||||
vm.call_method(self.raw.as_ref().unwrap(), "readinto", (memobj,))?
|
||||
vm.call_method(self.raw.as_ref().unwrap(), "readinto", (mem_obj,))?
|
||||
}
|
||||
};
|
||||
|
||||
@@ -2305,14 +2305,14 @@ mod _io {
|
||||
let incremental_encoder =
|
||||
codec.get_incremental_encoder(Some(errors.to_owned()), vm)?;
|
||||
let encoding_name = vm.get_attribute_opt(incremental_encoder.clone(), "name")?;
|
||||
let encodefunc = encoding_name.and_then(|name| {
|
||||
let encode_func = encoding_name.and_then(|name| {
|
||||
let name = name.payload::<PyStr>()?;
|
||||
match name.as_str() {
|
||||
"utf-8" => Some(textio_encode_utf8 as EncodeFunc),
|
||||
_ => None,
|
||||
}
|
||||
});
|
||||
Some((incremental_encoder, encodefunc))
|
||||
Some((incremental_encoder, encode_func))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -2600,12 +2600,12 @@ mod _io {
|
||||
while skip_bytes > 0 {
|
||||
cookie.set_decoder_state(decoder, vm)?;
|
||||
let input = &next_input.as_bytes()[..skip_bytes as usize];
|
||||
let ndecoded = decoder_decode(input)?;
|
||||
if ndecoded.chars <= num_to_skip.chars {
|
||||
let n_decoded = decoder_decode(input)?;
|
||||
if n_decoded.chars <= num_to_skip.chars {
|
||||
let (dec_buffer, dec_flags) = decoder_getstate()?;
|
||||
if dec_buffer.is_empty() {
|
||||
cookie.dec_flags = dec_flags;
|
||||
num_to_skip -= ndecoded;
|
||||
num_to_skip -= n_decoded;
|
||||
break;
|
||||
}
|
||||
skip_bytes -= dec_buffer.len() as isize;
|
||||
@@ -2625,23 +2625,23 @@ mod _io {
|
||||
cookie.set_num_to_skip(num_to_skip);
|
||||
|
||||
if num_to_skip.chars != 0 {
|
||||
let mut ndecoded = Utf8size::default();
|
||||
let mut n_decoded = Utf8size::default();
|
||||
let mut input = next_input.as_bytes();
|
||||
input = &input[skip_bytes..];
|
||||
while !input.is_empty() {
|
||||
let (byte1, rest) = input.split_at(1);
|
||||
let n = decoder_decode(byte1)?;
|
||||
ndecoded += n;
|
||||
n_decoded += n;
|
||||
cookie.bytes_to_feed += 1;
|
||||
let (dec_buffer, dec_flags) = decoder_getstate()?;
|
||||
if dec_buffer.is_empty() && ndecoded.chars < num_to_skip.chars {
|
||||
if dec_buffer.is_empty() && n_decoded.chars < num_to_skip.chars {
|
||||
cookie.start_pos += cookie.bytes_to_feed as Offset;
|
||||
num_to_skip -= ndecoded;
|
||||
num_to_skip -= n_decoded;
|
||||
cookie.dec_flags = dec_flags;
|
||||
cookie.bytes_to_feed = 0;
|
||||
ndecoded = Utf8size::default();
|
||||
n_decoded = Utf8size::default();
|
||||
}
|
||||
if ndecoded.chars >= num_to_skip.chars {
|
||||
if n_decoded.chars >= num_to_skip.chars {
|
||||
break;
|
||||
}
|
||||
input = rest;
|
||||
@@ -2650,7 +2650,7 @@ mod _io {
|
||||
let decoded =
|
||||
vm.call_method(decoder, "decode", (vm.ctx.new_bytes(vec![]), true))?;
|
||||
let decoded = check_decoded(decoded, vm)?;
|
||||
let final_decoded_chars = ndecoded.chars + decoded.char_len();
|
||||
let final_decoded_chars = n_decoded.chars + decoded.char_len();
|
||||
cookie.need_eof = true;
|
||||
if final_decoded_chars < num_to_skip.chars {
|
||||
return Err(
|
||||
@@ -2739,7 +2739,7 @@ mod _io {
|
||||
let mut textio = self.lock(vm)?;
|
||||
textio.check_closed(vm)?;
|
||||
|
||||
let (encoder, encodefunc) = textio
|
||||
let (encoder, encode_func) = textio
|
||||
.encoder
|
||||
.as_ref()
|
||||
.ok_or_else(|| new_unsupported_operation(vm, "not writable".to_owned()))?;
|
||||
@@ -2767,8 +2767,8 @@ mod _io {
|
||||
} else {
|
||||
obj
|
||||
};
|
||||
let chunk = if let Some(encodefunc) = *encodefunc {
|
||||
encodefunc(chunk)
|
||||
let chunk = if let Some(encode_func) = *encode_func {
|
||||
encode_func(chunk)
|
||||
} else {
|
||||
let b = vm.call_method(encoder, "encode", (chunk.clone(),))?;
|
||||
b.downcast::<PyBytes>()
|
||||
@@ -2866,7 +2866,7 @@ mod _io {
|
||||
}
|
||||
|
||||
let mut start;
|
||||
let mut endpos;
|
||||
let mut end_pos;
|
||||
let mut offset_to_buffer;
|
||||
let mut chunked = Utf8size::default();
|
||||
let mut remaining: Option<SlicedStr> = None;
|
||||
@@ -2883,7 +2883,7 @@ mod _io {
|
||||
textio.set_decoded_chars(None);
|
||||
textio.snapshot = None;
|
||||
start = Utf8size::default();
|
||||
endpos = Utf8size::default();
|
||||
end_pos = Utf8size::default();
|
||||
offset_to_buffer = Utf8size::default();
|
||||
break 'outer None;
|
||||
}
|
||||
@@ -2918,11 +2918,11 @@ mod _io {
|
||||
let nl_res = textio.newline.find_newline(line_from_start);
|
||||
match nl_res {
|
||||
Ok(p) | Err(p) => {
|
||||
endpos = start + Utf8size::len_str(&line_from_start[..p]);
|
||||
end_pos = start + Utf8size::len_str(&line_from_start[..p]);
|
||||
if let Some(limit) = limit {
|
||||
// original CPython logic: endpos = start + limit - chunked
|
||||
if chunked.chars + endpos.chars >= limit {
|
||||
endpos = start
|
||||
// original CPython logic: end_pos = start + limit - chunked
|
||||
if chunked.chars + end_pos.chars >= limit {
|
||||
end_pos = start
|
||||
+ Utf8size {
|
||||
chars: limit - chunked.chars,
|
||||
bytes: crate::common::str::codepoint_range_end(
|
||||
@@ -2939,21 +2939,21 @@ mod _io {
|
||||
if nl_res.is_ok() {
|
||||
break Some(line);
|
||||
}
|
||||
if endpos.bytes > start.bytes {
|
||||
let chunk = SlicedStr(line.clone(), start.bytes..endpos.bytes);
|
||||
if end_pos.bytes > start.bytes {
|
||||
let chunk = SlicedStr(line.clone(), start.bytes..end_pos.bytes);
|
||||
chunked += chunk.utf8_len();
|
||||
chunks.push(chunk);
|
||||
}
|
||||
let line_len = line.byte_len();
|
||||
if endpos.bytes < line_len {
|
||||
remaining = Some(SlicedStr(line, endpos.bytes..line_len));
|
||||
if end_pos.bytes < line_len {
|
||||
remaining = Some(SlicedStr(line, end_pos.bytes..line_len));
|
||||
}
|
||||
textio.set_decoded_chars(None);
|
||||
};
|
||||
|
||||
let cur_line = cur_line.map(|line| {
|
||||
textio.decoded_chars_used = endpos - offset_to_buffer;
|
||||
SlicedStr(line, start.bytes..endpos.bytes)
|
||||
textio.decoded_chars_used = end_pos - offset_to_buffer;
|
||||
SlicedStr(line, start.bytes..end_pos.bytes)
|
||||
});
|
||||
// don't need to care about chunked.chars anymore
|
||||
let mut chunked = chunked.bytes;
|
||||
@@ -3166,7 +3166,7 @@ mod _io {
|
||||
#[derive(Debug)]
|
||||
struct IncrementalNewlineDecoderData {
|
||||
decoder: PyObjectRef,
|
||||
// afaict, this is used for nothing
|
||||
// currently this is used for nothing
|
||||
// errors: PyObjectRef,
|
||||
pendingcr: bool,
|
||||
translate: bool,
|
||||
@@ -4237,7 +4237,7 @@ mod fileio {
|
||||
#[cfg(any(unix, target_os = "wasi"))]
|
||||
let fd = Fd::open(&path.clone().into_cstring(vm)?, flags, 0o666);
|
||||
#[cfg(windows)]
|
||||
let fd = Fd::wopen(&path.to_widecstring(vm)?, flags, 0o666);
|
||||
let fd = Fd::wopen(&path.to_wide_cstring(vm)?, flags, 0o666);
|
||||
let filename = OsPathOrFd::Path(path);
|
||||
match fd {
|
||||
Ok(fd) => (fd.0, filename),
|
||||
|
||||
@@ -1087,7 +1087,7 @@ mod decl {
|
||||
#[derive(Debug, PyPayload)]
|
||||
struct PyItertoolsAccumulate {
|
||||
iterable: PyIter,
|
||||
binop: Option<PyObjectRef>,
|
||||
bin_op: Option<PyObjectRef>,
|
||||
initial: Option<PyObjectRef>,
|
||||
acc_value: PyRwLock<Option<PyObjectRef>>,
|
||||
}
|
||||
@@ -1107,7 +1107,7 @@ mod decl {
|
||||
fn py_new(cls: PyTypeRef, args: AccumulateArgs, vm: &VirtualMachine) -> PyResult {
|
||||
PyItertoolsAccumulate {
|
||||
iterable: args.iterable,
|
||||
binop: args.func.flatten(),
|
||||
bin_op: args.func.flatten(),
|
||||
initial: args.initial.flatten(),
|
||||
acc_value: PyRwLock::new(None),
|
||||
}
|
||||
@@ -1127,7 +1127,7 @@ mod decl {
|
||||
#[pymethod(magic)]
|
||||
fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyTupleRef {
|
||||
let class = zelf.class().to_owned();
|
||||
let binop = zelf.binop.clone();
|
||||
let bin_op = zelf.bin_op.clone();
|
||||
let it = zelf.iterable.clone();
|
||||
let acc_value = zelf.acc_value.read().clone();
|
||||
if let Some(initial) = &zelf.initial {
|
||||
@@ -1136,7 +1136,7 @@ mod decl {
|
||||
source: PyRwLock::new(Some(chain_args.to_pyobject(vm).get_iter(vm).unwrap())),
|
||||
active: PyRwLock::new(None),
|
||||
};
|
||||
let tup = vm.new_tuple((chain, binop));
|
||||
let tup = vm.new_tuple((chain, bin_op));
|
||||
return vm.new_tuple((class, tup, acc_value));
|
||||
}
|
||||
match acc_value {
|
||||
@@ -1151,7 +1151,7 @@ mod decl {
|
||||
.into_pyobject(vm);
|
||||
let acc = Self {
|
||||
iterable: PyIter::new(chain),
|
||||
binop,
|
||||
bin_op,
|
||||
initial: None,
|
||||
acc_value: PyRwLock::new(None),
|
||||
};
|
||||
@@ -1161,7 +1161,7 @@ mod decl {
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let tup = vm.new_tuple((it, binop));
|
||||
let tup = vm.new_tuple((it, bin_op));
|
||||
vm.new_tuple((class, tup, acc_value))
|
||||
}
|
||||
}
|
||||
@@ -1191,7 +1191,7 @@ mod decl {
|
||||
return Ok(PyIterReturn::StopIteration(v));
|
||||
}
|
||||
};
|
||||
match &zelf.binop {
|
||||
match &zelf.bin_op {
|
||||
None => vm._add(&value, &obj)?,
|
||||
Some(op) => op.call((value, obj), vm)?,
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ pub(crate) mod module {
|
||||
|
||||
#[pyfunction]
|
||||
pub(super) fn access(path: OsPath, mode: u8, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
let attr = unsafe { FileSystem::GetFileAttributesW(path.to_widecstring(vm)?.as_ptr()) };
|
||||
let attr = unsafe { FileSystem::GetFileAttributesW(path.to_wide_cstring(vm)?.as_ptr()) };
|
||||
Ok(attr != FileSystem::INVALID_FILE_ATTRIBUTES
|
||||
&& (mode & 2 == 0
|
||||
|| attr & FileSystem::FILE_ATTRIBUTE_READONLY == 0
|
||||
@@ -256,7 +256,7 @@ pub(crate) mod module {
|
||||
|
||||
#[pyfunction]
|
||||
fn _getfullpathname(path: OsPath, vm: &VirtualMachine) -> PyResult {
|
||||
let wpath = path.to_widecstring(vm)?;
|
||||
let wpath = path.to_wide_cstring(vm)?;
|
||||
let mut buffer = vec![0u16; Foundation::MAX_PATH as usize];
|
||||
let ret = unsafe {
|
||||
FileSystem::GetFullPathNameW(
|
||||
@@ -289,7 +289,7 @@ pub(crate) mod module {
|
||||
|
||||
#[pyfunction]
|
||||
fn _getvolumepathname(path: OsPath, vm: &VirtualMachine) -> PyResult {
|
||||
let wide = path.to_widecstring(vm)?;
|
||||
let wide = path.to_wide_cstring(vm)?;
|
||||
let buflen = std::cmp::max(wide.len(), Foundation::MAX_PATH as usize);
|
||||
let mut buffer = vec![0u16; buflen];
|
||||
let ret = unsafe {
|
||||
@@ -344,7 +344,7 @@ pub(crate) mod module {
|
||||
fn _getdiskusage(path: OsPath, vm: &VirtualMachine) -> PyResult<(u64, u64)> {
|
||||
use FileSystem::GetDiskFreeSpaceExW;
|
||||
|
||||
let wpath = path.to_widecstring(vm)?;
|
||||
let wpath = path.to_wide_cstring(vm)?;
|
||||
let mut _free_to_me: u64 = 0;
|
||||
let mut total: u64 = 0;
|
||||
let mut free: u64 = 0;
|
||||
@@ -437,7 +437,7 @@ pub(crate) mod module {
|
||||
let mode = mode.unwrap_or(0o777);
|
||||
let [] = dir_fd.0;
|
||||
let _ = mode;
|
||||
let wide = path.to_widecstring(vm)?;
|
||||
let wide = path.to_wide_cstring(vm)?;
|
||||
let res = unsafe { FileSystem::CreateDirectoryW(wide.as_ptr(), std::ptr::null_mut()) };
|
||||
if res == 0 {
|
||||
return Err(errno_err(vm));
|
||||
|
||||
@@ -389,15 +389,15 @@ mod _operator {
|
||||
type Args = FuncArgs;
|
||||
|
||||
fn py_new(cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult {
|
||||
let nattr = args.args.len();
|
||||
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()));
|
||||
}
|
||||
if nattr == 0 {
|
||||
if n_attr == 0 {
|
||||
return Err(vm.new_type_error("attrgetter expected 1 argument, got 0.".to_owned()));
|
||||
}
|
||||
let mut attrs = Vec::with_capacity(nattr);
|
||||
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);
|
||||
|
||||
@@ -219,7 +219,7 @@ pub(super) mod _os {
|
||||
#[cfg(windows)]
|
||||
let fd = {
|
||||
let [] = dir_fd.0;
|
||||
let name = name.to_widecstring(vm)?;
|
||||
let name = name.to_wide_cstring(vm)?;
|
||||
let flags = flags | libc::O_NOINHERIT;
|
||||
Fd::wopen(&name, flags, mode)
|
||||
};
|
||||
|
||||
@@ -287,7 +287,7 @@ mod _sre {
|
||||
with_sre_str!(zelf, &string_args.string, vm, |s| {
|
||||
let req = s.create_request(&zelf, string_args.pos, string_args.endpos);
|
||||
let state = State::default();
|
||||
let mut matchlist: Vec<PyObjectRef> = Vec::new();
|
||||
let mut match_list: Vec<PyObjectRef> = Vec::new();
|
||||
let mut iter = SearchIter { req, state };
|
||||
|
||||
while iter.next().is_some() {
|
||||
@@ -301,10 +301,10 @@ mod _sre {
|
||||
.into()
|
||||
};
|
||||
|
||||
matchlist.push(item);
|
||||
match_list.push(item);
|
||||
}
|
||||
|
||||
Ok(matchlist)
|
||||
Ok(match_list)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -362,7 +362,7 @@ mod _sre {
|
||||
with_sre_str!(zelf, &split_args.string, vm, |s| {
|
||||
let req = s.create_request(&zelf, 0, usize::MAX);
|
||||
let state = State::default();
|
||||
let mut splitlist: Vec<PyObjectRef> = Vec::new();
|
||||
let mut split_list: Vec<PyObjectRef> = Vec::new();
|
||||
let mut iter = SearchIter { req, state };
|
||||
let mut n = 0;
|
||||
let mut last = 0;
|
||||
@@ -370,13 +370,13 @@ mod _sre {
|
||||
while (split_args.maxsplit == 0 || n < split_args.maxsplit) && iter.next().is_some()
|
||||
{
|
||||
/* get segment before this match */
|
||||
splitlist.push(s.slice(last, iter.state.start, vm));
|
||||
split_list.push(s.slice(last, iter.state.start, vm));
|
||||
|
||||
let m = Match::new(&mut iter.state, zelf.clone(), split_args.string.clone());
|
||||
|
||||
// add groups (if any)
|
||||
for i in 1..=zelf.groups {
|
||||
splitlist.push(m.get_slice(i, s, vm).unwrap_or_else(|| vm.ctx.none()));
|
||||
split_list.push(m.get_slice(i, s, vm).unwrap_or_else(|| vm.ctx.none()));
|
||||
}
|
||||
|
||||
n += 1;
|
||||
@@ -384,9 +384,9 @@ mod _sre {
|
||||
}
|
||||
|
||||
// get segment following last match (even if empty)
|
||||
splitlist.push(req.string.slice(last, s.count(), vm));
|
||||
split_list.push(req.string.slice(last, s.count(), vm));
|
||||
|
||||
Ok(splitlist)
|
||||
Ok(split_list)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -444,7 +444,7 @@ mod _sre {
|
||||
with_sre_str!(zelf, &string, vm, |s| {
|
||||
let req = s.create_request(&zelf, 0, usize::MAX);
|
||||
let state = State::default();
|
||||
let mut sublist: Vec<PyObjectRef> = Vec::new();
|
||||
let mut sub_list: Vec<PyObjectRef> = Vec::new();
|
||||
let mut iter = SearchIter { req, state };
|
||||
let mut n = 0;
|
||||
let mut last_pos = 0;
|
||||
@@ -452,26 +452,26 @@ mod _sre {
|
||||
while (count == 0 || n < count) && iter.next().is_some() {
|
||||
if last_pos < iter.state.start {
|
||||
/* get segment before this match */
|
||||
sublist.push(s.slice(last_pos, iter.state.start, vm));
|
||||
sub_list.push(s.slice(last_pos, iter.state.start, vm));
|
||||
}
|
||||
|
||||
match &filter {
|
||||
FilterType::Literal(literal) => sublist.push(literal.clone()),
|
||||
FilterType::Literal(literal) => sub_list.push(literal.clone()),
|
||||
FilterType::Callable(callable) => {
|
||||
let m = Match::new(&mut iter.state, zelf.clone(), string.clone())
|
||||
.into_ref(&vm.ctx);
|
||||
sublist.push(callable.invoke((m,), vm)?);
|
||||
sub_list.push(callable.invoke((m,), vm)?);
|
||||
}
|
||||
FilterType::Template(template) => {
|
||||
let m = Match::new(&mut iter.state, zelf.clone(), string.clone());
|
||||
// template.expand(m)?
|
||||
// let mut list = vec![template.literal.clone()];
|
||||
sublist.push(template.literal.clone());
|
||||
sub_list.push(template.literal.clone());
|
||||
for (index, literal) in template.items.iter().cloned() {
|
||||
if let Some(item) = m.get_slice(index, s, vm) {
|
||||
sublist.push(item);
|
||||
sub_list.push(item);
|
||||
}
|
||||
sublist.push(literal);
|
||||
sub_list.push(literal);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -481,9 +481,9 @@ mod _sre {
|
||||
}
|
||||
|
||||
/* get segment following last match */
|
||||
sublist.push(s.slice(last_pos, iter.req.end, vm));
|
||||
sub_list.push(s.slice(last_pos, iter.req.end, vm));
|
||||
|
||||
let list = PyList::from(sublist).into_pyobject(vm);
|
||||
let list = PyList::from(sub_list).into_pyobject(vm);
|
||||
|
||||
let join_type: PyObjectRef = if zelf.isbytes {
|
||||
vm.ctx.new_bytes(vec![]).into()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
//cspell:ignore cfmt
|
||||
//! The python `time` module.
|
||||
|
||||
// See also:
|
||||
@@ -377,10 +378,10 @@ mod decl {
|
||||
|
||||
#[cfg(any(windows, all(target_arch = "wasm32", target_os = "emscripten")))]
|
||||
pub(super) fn time_muldiv(ticks: i64, mul: i64, div: i64) -> u64 {
|
||||
let intpart = ticks / div;
|
||||
let int_part = ticks / div;
|
||||
let ticks = ticks % div;
|
||||
let remaining = (ticks * mul) / div;
|
||||
(intpart * mul + remaining) as u64
|
||||
(int_part * mul + remaining) as u64
|
||||
}
|
||||
|
||||
#[cfg(all(target_arch = "wasm32", target_os = "emscripten"))]
|
||||
|
||||
@@ -39,13 +39,13 @@ pub fn with_vm<F, R>(obj: &PyObject, f: F) -> Option<R>
|
||||
where
|
||||
F: Fn(&VirtualMachine) -> R,
|
||||
{
|
||||
let vm_owns_obj = |intp: NonNull<VirtualMachine>| {
|
||||
let vm_owns_obj = |interp: NonNull<VirtualMachine>| {
|
||||
// SAFETY: all references in VM_STACK should be valid
|
||||
let vm = unsafe { intp.as_ref() };
|
||||
let vm = unsafe { interp.as_ref() };
|
||||
obj.fast_isinstance(vm.ctx.types.object_type)
|
||||
};
|
||||
VM_STACK.with(|vms| {
|
||||
let intp = match vms.borrow().iter().copied().exactly_one() {
|
||||
let interp = match vms.borrow().iter().copied().exactly_one() {
|
||||
Ok(x) => {
|
||||
debug_assert!(vm_owns_obj(x));
|
||||
x
|
||||
@@ -54,7 +54,7 @@ where
|
||||
};
|
||||
// SAFETY: all references in VM_STACK should be valid, and should not be changed or moved
|
||||
// at least until this function returns and the stack unwinds to an enter_vm() call
|
||||
let vm = unsafe { intp.as_ref() };
|
||||
let vm = unsafe { interp.as_ref() };
|
||||
let prev = VM_CURRENT.with(|current| current.replace(vm));
|
||||
let ret = f(vm);
|
||||
VM_CURRENT.with(|current| current.replace(prev));
|
||||
|
||||
@@ -155,7 +155,7 @@ impl VirtualMachine {
|
||||
))
|
||||
}
|
||||
|
||||
pub fn new_unsupported_binop_error(
|
||||
pub fn new_unsupported_bin_op_error(
|
||||
&self,
|
||||
a: &PyObject,
|
||||
b: &PyObject,
|
||||
@@ -169,7 +169,7 @@ impl VirtualMachine {
|
||||
))
|
||||
}
|
||||
|
||||
pub fn new_unsupported_ternop_error(
|
||||
pub fn new_unsupported_ternary_op_error(
|
||||
&self,
|
||||
a: &PyObject,
|
||||
b: &PyObject,
|
||||
|
||||
@@ -206,7 +206,7 @@ impl VirtualMachine {
|
||||
if !result.is(&self.ctx.not_implemented) {
|
||||
return Ok(result);
|
||||
}
|
||||
Err(self.new_unsupported_binop_error(a, b, op))
|
||||
Err(self.new_unsupported_bin_op_error(a, b, op))
|
||||
}
|
||||
|
||||
/// Binary in-place operators
|
||||
@@ -250,7 +250,7 @@ impl VirtualMachine {
|
||||
if !result.is(&self.ctx.not_implemented) {
|
||||
return Ok(result);
|
||||
}
|
||||
Err(self.new_unsupported_binop_error(a, b, op))
|
||||
Err(self.new_unsupported_bin_op_error(a, b, op))
|
||||
}
|
||||
|
||||
fn ternary_op(
|
||||
@@ -384,7 +384,7 @@ impl VirtualMachine {
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
Err(self.new_unsupported_binop_error(a, b, "+"))
|
||||
Err(self.new_unsupported_bin_op_error(a, b, "+"))
|
||||
}
|
||||
|
||||
pub fn _iadd(&self, a: &PyObject, b: &PyObject) -> PyResult {
|
||||
@@ -398,7 +398,7 @@ impl VirtualMachine {
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
Err(self.new_unsupported_binop_error(a, b, "+="))
|
||||
Err(self.new_unsupported_bin_op_error(a, b, "+="))
|
||||
}
|
||||
|
||||
pub fn _mul(&self, a: &PyObject, b: &PyObject) -> PyResult {
|
||||
@@ -419,7 +419,7 @@ impl VirtualMachine {
|
||||
})?;
|
||||
return seq_b.repeat(n, self);
|
||||
}
|
||||
Err(self.new_unsupported_binop_error(a, b, "*"))
|
||||
Err(self.new_unsupported_bin_op_error(a, b, "*"))
|
||||
}
|
||||
|
||||
pub fn _imul(&self, a: &PyObject, b: &PyObject) -> PyResult {
|
||||
@@ -448,7 +448,7 @@ impl VirtualMachine {
|
||||
* used. */
|
||||
return seq_b.repeat(n, self);
|
||||
}
|
||||
Err(self.new_unsupported_binop_error(a, b, "*="))
|
||||
Err(self.new_unsupported_bin_op_error(a, b, "*="))
|
||||
}
|
||||
|
||||
pub fn _abs(&self, a: &PyObject) -> PyResult<PyObjectRef> {
|
||||
|
||||
@@ -549,7 +549,7 @@ fn _match<S: StrDrive>(req: &Request<'_, S>, state: &mut State, mut ctx: MatchCo
|
||||
break 'result false;
|
||||
};
|
||||
|
||||
let mut gctx = MatchContext {
|
||||
let mut g_ctx = MatchContext {
|
||||
cursor: req.string.create_cursor(group_start),
|
||||
..ctx
|
||||
};
|
||||
@@ -557,12 +557,12 @@ fn _match<S: StrDrive>(req: &Request<'_, S>, state: &mut State, mut ctx: MatchCo
|
||||
for _ in group_start..group_end {
|
||||
#[allow(clippy::redundant_closure_call)]
|
||||
if ctx.at_end(req)
|
||||
|| $f(ctx.peek_char::<S>()) != $f(gctx.peek_char::<S>())
|
||||
|| $f(ctx.peek_char::<S>()) != $f(g_ctx.peek_char::<S>())
|
||||
{
|
||||
break 'result false;
|
||||
}
|
||||
ctx.advance_char::<S>();
|
||||
gctx.advance_char::<S>();
|
||||
g_ctx.advance_char::<S>();
|
||||
}
|
||||
|
||||
ctx.skip_code(2);
|
||||
@@ -627,8 +627,8 @@ fn _match<S: StrDrive>(req: &Request<'_, S>, state: &mut State, mut ctx: MatchCo
|
||||
break 'context next_ctx;
|
||||
}
|
||||
SreOpcode::AT => {
|
||||
let atcode = SreAtCode::try_from(ctx.peek_code(req, 1)).unwrap();
|
||||
if at(req, &ctx, atcode) {
|
||||
let at_code = SreAtCode::try_from(ctx.peek_code(req, 1)).unwrap();
|
||||
if at(req, &ctx, at_code) {
|
||||
ctx.skip_code(2);
|
||||
} else {
|
||||
break 'result false;
|
||||
@@ -642,8 +642,8 @@ fn _match<S: StrDrive>(req: &Request<'_, S>, state: &mut State, mut ctx: MatchCo
|
||||
continue 'context;
|
||||
}
|
||||
SreOpcode::CATEGORY => {
|
||||
let catcode = SreCatCode::try_from(ctx.peek_code(req, 1)).unwrap();
|
||||
if ctx.at_end(req) || !category(catcode, ctx.peek_char::<S>()) {
|
||||
let cat_code = SreCatCode::try_from(ctx.peek_code(req, 1)).unwrap();
|
||||
if ctx.at_end(req) || !category(cat_code, ctx.peek_char::<S>()) {
|
||||
break 'result false;
|
||||
}
|
||||
ctx.skip_code(2);
|
||||
@@ -1179,8 +1179,8 @@ impl MatchContext {
|
||||
}
|
||||
}
|
||||
|
||||
fn at<S: StrDrive>(req: &Request<'_, S>, ctx: &MatchContext, atcode: SreAtCode) -> bool {
|
||||
match atcode {
|
||||
fn at<S: StrDrive>(req: &Request<'_, S>, ctx: &MatchContext, at_code: SreAtCode) -> bool {
|
||||
match at_code {
|
||||
SreAtCode::BEGINNING | SreAtCode::BEGINNING_STRING => ctx.at_beginning(),
|
||||
SreAtCode::BEGINNING_LINE => ctx.at_beginning() || is_linebreak(ctx.back_peek_char::<S>()),
|
||||
SreAtCode::BOUNDARY => ctx.at_boundary(req, is_word),
|
||||
@@ -1210,8 +1210,8 @@ fn charset_loc_ignore(set: &[u32], c: u32) -> bool {
|
||||
up != lo && charset(set, up)
|
||||
}
|
||||
|
||||
fn category(catcode: SreCatCode, c: u32) -> bool {
|
||||
match catcode {
|
||||
fn category(cat_code: SreCatCode, c: u32) -> bool {
|
||||
match cat_code {
|
||||
SreCatCode::DIGIT => is_digit(c),
|
||||
SreCatCode::NOT_DIGIT => !is_digit(c),
|
||||
SreCatCode::SPACE => is_space(c),
|
||||
@@ -1250,13 +1250,13 @@ fn charset(set: &[u32], ch: u32) -> bool {
|
||||
}
|
||||
SreOpcode::CATEGORY => {
|
||||
/* <CATEGORY> <code> */
|
||||
let catcode = match SreCatCode::try_from(set[i + 1]) {
|
||||
let cat_code = match SreCatCode::try_from(set[i + 1]) {
|
||||
Ok(code) => code,
|
||||
Err(_) => {
|
||||
break;
|
||||
}
|
||||
};
|
||||
if category(catcode, ch) {
|
||||
if category(cat_code, ch) {
|
||||
return ok;
|
||||
}
|
||||
i += 2;
|
||||
@@ -1270,14 +1270,14 @@ fn charset(set: &[u32], ch: u32) -> bool {
|
||||
i += 1 + 8;
|
||||
}
|
||||
SreOpcode::BIGCHARSET => {
|
||||
/* <BIGCHARSET> <blockcount> <256 blockindices> <blocks> */
|
||||
/* <BIGCHARSET> <block_count> <256 block_indices> <blocks> */
|
||||
let count = set[i + 1] as usize;
|
||||
if ch < 0x10000 {
|
||||
let set = &set[i + 2..];
|
||||
let block_index = ch >> 8;
|
||||
let (_, blockindices, _) = unsafe { set.align_to::<u8>() };
|
||||
let (_, block_indices, _) = unsafe { set.align_to::<u8>() };
|
||||
let blocks = &set[64..];
|
||||
let block = blockindices[block_index as usize];
|
||||
let block = block_indices[block_index as usize];
|
||||
if blocks[((block as u32 * 256 + (ch & 255)) / 32) as usize]
|
||||
& (1u32 << (ch & 31))
|
||||
!= 0
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
//! string has no surrogates, it can be viewed as a UTF-8 Rust [`str`] without
|
||||
//! needing any copies or re-encoding.
|
||||
//!
|
||||
//! This implementation is mostly copied from the WTF-8 implentation in the
|
||||
//! This implementation is mostly copied from the WTF-8 implementation in the
|
||||
//! Rust 1.85 standard library, which is used as the backing for [`OsStr`] on
|
||||
//! Windows targets. As previously mentioned, however, it is modified to not
|
||||
//! join two surrogates into one codepoint when concatenating strings, in order
|
||||
@@ -463,8 +463,8 @@ impl Wtf8Buf {
|
||||
|
||||
pub fn pop(&mut self) -> Option<CodePoint> {
|
||||
let ch = self.code_points().next_back()?;
|
||||
let newlen = self.len() - ch.len_wtf8();
|
||||
self.bytes.truncate(newlen);
|
||||
let new_len = self.len() - ch.len_wtf8();
|
||||
self.bytes.truncate(new_len);
|
||||
Some(ch)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user