Apply some clipy lints (#6045)

This commit is contained in:
Shahar Naveh authored and GitHub committed 2025-07-30 12:16:02 +09:00
1 parent f402deef6d
commit 4bf32a04f4
32 files changed
+198 -100

No files matched your search

+1 -1
View File
@@ -165,7 +165,7 @@ impl<T> BoxVec<T> {
if index >= self.len() {
None
} else {
self.drain(index..index + 1).next()
self.drain(index..=index).next()
}
}
+2 -2
View File
@@ -389,7 +389,7 @@ impl FormatSpec {
fn insert_separator(mut magnitude_str: String, inter: i32, sep: char, sep_cnt: i32) -> String {
let magnitude_len = magnitude_str.len() as i32;
for i in 1..sep_cnt + 1 {
for i in 1..=sep_cnt {
magnitude_str.insert((magnitude_len - inter * i) as usize, sep);
}
magnitude_str
@@ -754,7 +754,7 @@ impl FormatSpec {
let inter = self.get_separator_interval().try_into().unwrap();
let len = magnitude_str.len() as i32;
let separated_magnitude =
FormatSpec::add_magnitude_separators_for_char(magnitude_str, inter, sep, len);
Self::add_magnitude_separators_for_char(magnitude_str, inter, sep, len);
Ok(separated_magnitude)
}
None => Ok(magnitude_str),
+7 -7
View File
@@ -360,7 +360,7 @@ impl Compiler {
fblock: Vec::with_capacity(MAXBLOCKS),
symbol_table_index: 0, // Module is always the first symbol table
};
Compiler {
Self {
code_stack: vec![module_code],
symbol_table_stack: Vec::new(),
source_file,
@@ -380,7 +380,7 @@ impl Compiler {
/// Check if the slice is a two-element slice (no step)
// = is_two_element_slice
fn is_two_element_slice(slice: &Expr) -> bool {
const fn is_two_element_slice(slice: &Expr) -> bool {
matches!(slice, Expr::Slice(s) if s.step.is_none())
}
@@ -882,7 +882,7 @@ impl Compiler {
self._name_inner(name, |i| &mut i.metadata.names)
}
fn varname(&mut self, name: &str) -> CompileResult<bytecode::NameIdx> {
if Compiler::is_forbidden_arg_name(name) {
if Self::is_forbidden_arg_name(name) {
return Err(self.error(CodegenErrorType::SyntaxError(format!(
"cannot assign to {name}",
))));
@@ -3435,7 +3435,7 @@ impl Compiler {
// Create a new tuple of attribute names.
let mut attr_names = vec![];
for name in kwd_attrs.iter() {
for name in &kwd_attrs {
// Py_NewRef(name) is emulated by cloning the name into a PyObject.
attr_names.push(ConstantData::Str {
value: name.as_str().to_string().into(),
@@ -3667,7 +3667,7 @@ impl Compiler {
pc.stores.insert(insert_pos + j, elem);
}
// Also perform the same rotation on the evaluation stack.
for _ in 0..(i_stores + 1) {
for _ in 0..=i_stores {
self.pattern_helper_rotate(i_control + 1)?;
}
}
@@ -4547,7 +4547,7 @@ impl Compiler {
}) => {
let prev_ctx = self.ctx;
let name = "<lambda>".to_owned();
let default_params = Default::default();
let default_params = Parameters::default();
let params = parameters.as_deref().unwrap_or(&default_params);
// Prepare defaults before entering function
@@ -4577,7 +4577,7 @@ impl Compiler {
let have_kwdefaults = !kw_with_defaults.is_empty();
if have_kwdefaults {
let default_kw_count = kw_with_defaults.len();
for (arg, default) in kw_with_defaults.iter() {
for (arg, default) in &kw_with_defaults {
self.emit_load_const(ConstantData::Str {
value: arg.name.as_str().into(),
});
+1 -1
View File
@@ -464,7 +464,7 @@ impl<'a, 'b, 'c> Unparser<'a, 'b, 'c> {
if let Some(vararg) = &args.vararg {
self.unparse_arg(vararg)?;
}
for kwarg in args.kwonlyargs.iter() {
for kwarg in &args.kwonlyargs {
self.p_delim(&mut first, ", ")?;
self.unparse_function_arg(kwarg)?;
}
+58 -8
View File
@@ -42,8 +42,10 @@ pub trait Constant: Sized {
impl Constant for ConstantData {
type Name = String;
fn borrow_constant(&self) -> BorrowedConstant<'_, Self> {
use BorrowedConstant::*;
match self {
Self::Integer { value } => Integer { value },
Self::Float { value } => Float { value: *value },
@@ -62,21 +64,28 @@ impl Constant for ConstantData {
/// A Constant Bag
pub trait ConstantBag: Sized + Copy {
type Constant: Constant;
fn make_constant<C: Constant>(&self, constant: BorrowedConstant<'_, C>) -> Self::Constant;
fn make_int(&self, value: BigInt) -> Self::Constant;
fn make_tuple(&self, elements: impl Iterator<Item = Self::Constant>) -> Self::Constant;
fn make_code(&self, code: CodeObject<Self::Constant>) -> Self::Constant;
fn make_name(&self, name: &str) -> <Self::Constant as Constant>::Name;
}
pub trait AsBag {
type Bag: ConstantBag;
#[allow(clippy::wrong_self_convention)]
fn as_bag(self) -> Self::Bag;
}
impl<Bag: ConstantBag> AsBag for Bag {
type Bag = Self;
fn as_bag(self) -> Self {
self
}
@@ -87,22 +96,27 @@ pub struct BasicBag;
impl ConstantBag for BasicBag {
type Constant = ConstantData;
fn make_constant<C: Constant>(&self, constant: BorrowedConstant<'_, C>) -> Self::Constant {
constant.to_owned()
}
fn make_int(&self, value: BigInt) -> Self::Constant {
ConstantData::Integer { value }
}
fn make_tuple(&self, elements: impl Iterator<Item = Self::Constant>) -> Self::Constant {
ConstantData::Tuple {
elements: elements.collect(),
}
}
fn make_code(&self, code: CodeObject<Self::Constant>) -> Self::Constant {
ConstantData::Code {
code: Box::new(code),
}
}
fn make_name(&self, name: &str) -> <Self::Constant as Constant>::Name {
name.to_owned()
}
@@ -163,11 +177,13 @@ impl CodeFlags {
#[derive(Copy, Clone, PartialEq, Eq)]
#[repr(transparent)]
pub struct OpArgByte(pub u8);
impl OpArgByte {
pub const fn null() -> Self {
Self(0)
}
}
impl fmt::Debug for OpArgByte {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
@@ -178,6 +194,7 @@ impl fmt::Debug for OpArgByte {
#[derive(Copy, Clone, Debug)]
#[repr(transparent)]
pub struct OpArg(pub u32);
impl OpArg {
pub const fn null() -> Self {
Self(0)
@@ -185,7 +202,7 @@ impl OpArg {
/// Returns how many CodeUnits a instruction with this op_arg will be encoded as
#[inline]
pub fn instr_size(self) -> usize {
pub const fn instr_size(self) -> usize {
(self.0 > 0xff) as usize + (self.0 > 0xff_ff) as usize + (self.0 > 0xff_ff_ff) as usize + 1
}
@@ -219,19 +236,22 @@ impl OpArgState {
}
(ins.op, arg)
}
#[inline(always)]
pub fn extend(&mut self, arg: OpArgByte) -> OpArg {
self.state = (self.state << 8) | u32::from(arg.0);
OpArg(self.state)
}
#[inline(always)]
pub fn reset(&mut self) {
pub const fn reset(&mut self) {
self.state = 0
}
}
pub trait OpArgType: Copy {
fn from_op_arg(x: u32) -> Option<Self>;
fn to_op_arg(self) -> u32;
}
@@ -240,6 +260,7 @@ impl OpArgType for u32 {
fn from_op_arg(x: u32) -> Option<Self> {
Some(x)
}
#[inline(always)]
fn to_op_arg(self) -> u32 {
self
@@ -251,6 +272,7 @@ impl OpArgType for bool {
fn from_op_arg(x: u32) -> Option<Self> {
Some(x != 0)
}
#[inline(always)]
fn to_op_arg(self) -> u32 {
self as u32
@@ -263,6 +285,7 @@ macro_rules! op_arg_enum_impl {
fn to_op_arg(self) -> u32 {
self as u32
}
fn from_op_arg(x: u32) -> Option<Self> {
Some(match u8::try_from(x).ok()? {
$($value => Self::$var,)*
@@ -291,13 +314,15 @@ pub struct Arg<T: OpArgType>(PhantomData<T>);
impl<T: OpArgType> Arg<T> {
#[inline]
pub fn marker() -> Self {
pub const fn marker() -> Self {
Self(PhantomData)
}
#[inline]
pub fn new(arg: T) -> (Self, OpArg) {
(Self(PhantomData), OpArg(arg.to_op_arg()))
}
#[inline]
pub fn new_single(arg: T) -> (Self, OpArgByte)
where
@@ -305,17 +330,20 @@ impl<T: OpArgType> Arg<T> {
{
(Self(PhantomData), OpArgByte(arg.into()))
}
#[inline(always)]
pub fn get(self, arg: OpArg) -> T {
self.try_get(arg).unwrap()
}
#[inline(always)]
pub fn try_get(self, arg: OpArg) -> Option<T> {
T::from_op_arg(arg.0)
}
#[inline(always)]
/// # Safety
/// T::from_op_arg(self) must succeed
#[inline(always)]
pub unsafe fn get_unchecked(self, arg: OpArg) -> T {
// SAFETY: requirements forwarded from caller
unsafe { T::from_op_arg(arg.0).unwrap_unchecked() }
@@ -327,6 +355,7 @@ impl<T: OpArgType> PartialEq for Arg<T> {
true
}
}
impl<T: OpArgType> Eq for Arg<T> {}
impl<T: OpArgType> fmt::Debug for Arg<T> {
@@ -346,6 +375,7 @@ impl OpArgType for Label {
fn from_op_arg(x: u32) -> Option<Self> {
Some(Self(x))
}
#[inline(always)]
fn to_op_arg(self) -> u32 {
self.0
@@ -369,6 +399,7 @@ impl OpArgType for ConversionFlag {
_ => None,
}
}
#[inline]
fn to_op_arg(self) -> u32 {
self as i8 as u8 as u32
@@ -681,8 +712,10 @@ pub enum Instruction {
ExtendedArg,
// If you add a new instruction here, be sure to keep LAST_INSTRUCTION updated
}
// This must be kept up to date to avoid marshaling errors
const LAST_INSTRUCTION: Instruction = Instruction::ExtendedArg;
const _: () = assert!(mem::size_of::<Instruction>() == 1);
impl From<Instruction> for u8 {
@@ -716,7 +749,7 @@ pub struct CodeUnit {
const _: () = assert!(mem::size_of::<CodeUnit>() == 2);
impl CodeUnit {
pub fn new(op: Instruction, arg: OpArgByte) -> Self {
pub const fn new(op: Instruction, arg: OpArgByte) -> Self {
Self { op, arg }
}
}
@@ -733,11 +766,13 @@ bitflags! {
const TYPE_PARAMS = 0x10;
}
}
impl OpArgType for MakeFunctionFlags {
#[inline(always)]
fn from_op_arg(x: u32) -> Option<Self> {
Self::from_bits(x as u8)
}
#[inline(always)]
fn to_op_arg(self) -> u32 {
self.bits().into()
@@ -770,6 +805,7 @@ pub enum ConstantData {
impl PartialEq for ConstantData {
fn eq(&self, other: &Self) -> bool {
use ConstantData::*;
match (self, other) {
(Integer { value: a }, Integer { value: b }) => a == b,
// we want to compare floats *by actual value* - if we have the *exact same* float
@@ -795,6 +831,7 @@ impl Eq for ConstantData {}
impl hash::Hash for ConstantData {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
use ConstantData::*;
mem::discriminant(self).hash(state);
match self {
Integer { value } => value.hash(state),
@@ -829,6 +866,7 @@ pub enum BorrowedConstant<'a, C: Constant> {
}
impl<C: Constant> Copy for BorrowedConstant<'_, C> {}
impl<C: Constant> Clone for BorrowedConstant<'_, C> {
fn clone(&self) -> Self {
*self
@@ -845,7 +883,7 @@ impl<C: Constant> BorrowedConstant<'_, C> {
write!(f, "{}", if *value { "True" } else { "False" })
}
BorrowedConstant::Str { value } => write!(f, "{value:?}"),
BorrowedConstant::Bytes { value } => write!(f, "b\"{}\"", value.escape_ascii()),
BorrowedConstant::Bytes { value } => write!(f, r#"b"{}""#, value.escape_ascii()),
BorrowedConstant::Code { code } => write!(f, "{code:?}"),
BorrowedConstant::Tuple { elements } => {
write!(f, "(")?;
@@ -864,8 +902,10 @@ impl<C: Constant> BorrowedConstant<'_, C> {
BorrowedConstant::Ellipsis => write!(f, "..."),
}
}
pub fn to_owned(self) -> ConstantData {
use ConstantData::*;
match self {
BorrowedConstant::Integer { value } => Integer {
value: value.clone(),
@@ -975,11 +1015,13 @@ impl OpArgType for UnpackExArgs {
let [before, after, ..] = x.to_le_bytes();
Some(Self { before, after })
}
#[inline(always)]
fn to_op_arg(self) -> u32 {
u32::from_le_bytes([self.before, self.after, 0, 0])
}
}
impl fmt::Display for UnpackExArgs {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "before: {}, after: {}", self.before, self.after)
@@ -1208,7 +1250,7 @@ impl<C: Constant> fmt::Display for CodeObject<C> {
impl Instruction {
/// Gets the label stored inside this instruction, if it exists
#[inline]
pub fn label_arg(&self) -> Option<Arg<Label>> {
pub const fn label_arg(&self) -> Option<Arg<Label>> {
match self {
Jump { target: l }
| JumpIfTrue { target: l }
@@ -1235,7 +1277,7 @@ impl Instruction {
/// let jump_inst = Instruction::Jump { target: Arg::marker() };
/// assert!(jump_inst.unconditional_branch())
/// ```
pub fn unconditional_branch(&self) -> bool {
pub const fn unconditional_branch(&self) -> bool {
matches!(
self,
Jump { .. }
@@ -1571,23 +1613,31 @@ impl Instruction {
pub trait InstrDisplayContext {
type Constant: Constant;
fn get_constant(&self, i: usize) -> &Self::Constant;
fn get_name(&self, i: usize) -> &str;
fn get_varname(&self, i: usize) -> &str;
fn get_cell_name(&self, i: usize) -> &str;
}
impl<C: Constant> InstrDisplayContext for CodeObject<C> {
type Constant = C;
fn get_constant(&self, i: usize) -> &C {
&self.constants[i]
}
fn get_name(&self, i: usize) -> &str {
self.names[i].as_ref()
}
fn get_varname(&self, i: usize) -> &str {
self.varnames[i].as_ref()
}
fn get_cell_name(&self, i: usize) -> &str {
self.cellvars
.get(i)
+2
View File
@@ -57,6 +57,7 @@ impl<B: AsRef<[u8]> + ?Sized> FrozenLib<B> {
impl<'a, B: AsRef<[u8]> + ?Sized> IntoIterator for &'a FrozenLib<B> {
type Item = (&'a str, FrozenModule<&'a [u8]>);
type IntoIter = FrozenModulesIter<'a>;
fn into_iter(self) -> Self::IntoIter {
self.decode()
}
@@ -84,6 +85,7 @@ impl<'a> Iterator for FrozenModulesIter<'a> {
(self.remaining as usize, Some(self.remaining as usize))
}
}
impl ExactSizeIterator for FrozenModulesIter<'_> {}
fn read_entry<'a>(
+50 -2
View File
@@ -75,8 +75,10 @@ enum Type {
impl TryFrom<u8> for Type {
type Error = MarshalError;
fn try_from(value: u8) -> Result<Self> {
use Type::*;
Ok(match value {
// b'0' => Null,
b'N' => None,
@@ -111,24 +113,31 @@ impl TryFrom<u8> for Type {
pub trait Read {
fn read_slice(&mut self, n: u32) -> Result<&[u8]>;
fn read_array<const N: usize>(&mut self) -> Result<&[u8; N]> {
self.read_slice(N as u32).map(|s| s.try_into().unwrap())
}
fn read_str(&mut self, len: u32) -> Result<&str> {
Ok(std::str::from_utf8(self.read_slice(len)?)?)
}
fn read_wtf8(&mut self, len: u32) -> Result<&Wtf8> {
Wtf8::from_bytes(self.read_slice(len)?).ok_or(MarshalError::InvalidUtf8)
}
fn read_u8(&mut self) -> Result<u8> {
Ok(u8::from_le_bytes(*self.read_array()?))
}
fn read_u16(&mut self) -> Result<u16> {
Ok(u16::from_le_bytes(*self.read_array()?))
}
fn read_u32(&mut self) -> Result<u32> {
Ok(u32::from_le_bytes(*self.read_array()?))
}
fn read_u64(&mut self) -> Result<u64> {
Ok(u64::from_le_bytes(*self.read_array()?))
}
@@ -136,6 +145,7 @@ pub trait Read {
pub(crate) trait ReadBorrowed<'a>: Read {
fn read_slice_borrow(&mut self, n: u32) -> Result<&'a [u8]>;
fn read_str_borrow(&mut self, len: u32) -> Result<&'a str> {
Ok(std::str::from_utf8(self.read_slice_borrow(len)?)?)
}
@@ -264,85 +274,117 @@ pub fn deserialize_code<R: Read, Bag: ConstantBag>(
pub trait MarshalBag: Copy {
type Value;
type ConstantBag: ConstantBag;
fn make_bool(&self, value: bool) -> Self::Value;
fn make_none(&self) -> Self::Value;
fn make_ellipsis(&self) -> Self::Value;
fn make_float(&self, value: f64) -> Self::Value;
fn make_complex(&self, value: Complex64) -> Self::Value;
fn make_str(&self, value: &Wtf8) -> Self::Value;
fn make_bytes(&self, value: &[u8]) -> Self::Value;
fn make_int(&self, value: BigInt) -> Self::Value;
fn make_tuple(&self, elements: impl Iterator<Item = Self::Value>) -> Self::Value;
fn make_code(
&self,
code: CodeObject<<Self::ConstantBag as ConstantBag>::Constant>,
) -> Self::Value;
fn make_stop_iter(&self) -> Result<Self::Value>;
fn make_list(&self, it: impl Iterator<Item = Self::Value>) -> Result<Self::Value>;
fn make_set(&self, it: impl Iterator<Item = Self::Value>) -> Result<Self::Value>;
fn make_frozenset(&self, it: impl Iterator<Item = Self::Value>) -> Result<Self::Value>;
fn make_dict(
&self,
it: impl Iterator<Item = (Self::Value, Self::Value)>,
) -> Result<Self::Value>;
type ConstantBag: ConstantBag;
fn constant_bag(self) -> Self::ConstantBag;
}
impl<Bag: ConstantBag> MarshalBag for Bag {
type Value = Bag::Constant;
type ConstantBag = Self;
fn make_bool(&self, value: bool) -> Self::Value {
self.make_constant::<Bag::Constant>(BorrowedConstant::Boolean { value })
}
fn make_none(&self) -> Self::Value {
self.make_constant::<Bag::Constant>(BorrowedConstant::None)
}
fn make_ellipsis(&self) -> Self::Value {
self.make_constant::<Bag::Constant>(BorrowedConstant::Ellipsis)
}
fn make_float(&self, value: f64) -> Self::Value {
self.make_constant::<Bag::Constant>(BorrowedConstant::Float { value })
}
fn make_complex(&self, value: Complex64) -> Self::Value {
self.make_constant::<Bag::Constant>(BorrowedConstant::Complex { value })
}
fn make_str(&self, value: &Wtf8) -> Self::Value {
self.make_constant::<Bag::Constant>(BorrowedConstant::Str { value })
}
fn make_bytes(&self, value: &[u8]) -> Self::Value {
self.make_constant::<Bag::Constant>(BorrowedConstant::Bytes { value })
}
fn make_int(&self, value: BigInt) -> Self::Value {
self.make_int(value)
}
fn make_tuple(&self, elements: impl Iterator<Item = Self::Value>) -> Self::Value {
self.make_tuple(elements)
}
fn make_code(
&self,
code: CodeObject<<Self::ConstantBag as ConstantBag>::Constant>,
) -> Self::Value {
self.make_code(code)
}
fn make_stop_iter(&self) -> Result<Self::Value> {
Err(MarshalError::BadType)
}
fn make_list(&self, _: impl Iterator<Item = Self::Value>) -> Result<Self::Value> {
Err(MarshalError::BadType)
}
fn make_set(&self, _: impl Iterator<Item = Self::Value>) -> Result<Self::Value> {
Err(MarshalError::BadType)
}
fn make_frozenset(&self, _: impl Iterator<Item = Self::Value>) -> Result<Self::Value> {
Err(MarshalError::BadType)
}
fn make_dict(
&self,
_: impl Iterator<Item = (Self::Value, Self::Value)>,
) -> Result<Self::Value> {
Err(MarshalError::BadType)
}
type ConstantBag = Self;
fn constant_bag(self) -> Self::ConstantBag {
self
}
@@ -421,6 +463,7 @@ pub fn deserialize_value<R: Read, Bag: MarshalBag>(rdr: &mut R, bag: Bag) -> Res
pub trait Dumpable: Sized {
type Error;
type Constant: Constant;
fn with_dump<R>(&self, f: impl FnOnce(DumpableValue<'_, Self>) -> R) -> Result<R, Self::Error>;
}
@@ -462,6 +505,7 @@ impl<'a, C: Constant> From<BorrowedConstant<'a, C>> for DumpableValue<'a, C> {
impl<C: Constant> Dumpable for C {
type Error = Infallible;
type Constant = Self;
#[inline(always)]
fn with_dump<R>(&self, f: impl FnOnce(DumpableValue<'_, Self>) -> R) -> Result<R, Self::Error> {
Ok(f(self.borrow_constant().into()))
@@ -470,15 +514,19 @@ impl<C: Constant> Dumpable for C {
pub trait Write {
fn write_slice(&mut self, slice: &[u8]);
fn write_u8(&mut self, v: u8) {
self.write_slice(&v.to_le_bytes())
}
fn write_u16(&mut self, v: u16) {
self.write_slice(&v.to_le_bytes())
}
fn write_u32(&mut self, v: u32) {
self.write_slice(&v.to_le_bytes())
}
fn write_u64(&mut self, v: u64) {
self.write_slice(&v.to_le_bytes())
}
+17 -17
View File
@@ -8,26 +8,26 @@ pub enum Quote {
impl Quote {
#[inline]
pub const fn swap(self) -> Quote {
pub const fn swap(self) -> Self {
match self {
Quote::Single => Quote::Double,
Quote::Double => Quote::Single,
Self::Single => Self::Double,
Self::Double => Self::Single,
}
}
#[inline]
pub const fn to_byte(&self) -> u8 {
match self {
Quote::Single => b'\'',
Quote::Double => b'"',
Self::Single => b'\'',
Self::Double => b'"',
}
}
#[inline]
pub const fn to_char(&self) -> char {
match self {
Quote::Single => '\'',
Quote::Double => '"',
Self::Single => '\'',
Self::Double => '"',
}
}
}
@@ -95,7 +95,7 @@ pub struct UnicodeEscape<'a> {
impl<'a> UnicodeEscape<'a> {
#[inline]
pub fn with_forced_quote(source: &'a Wtf8, quote: Quote) -> Self {
pub const fn with_forced_quote(source: &'a Wtf8, quote: Quote) -> Self {
let layout = EscapeLayout { quote, len: None };
Self { source, layout }
}
@@ -109,7 +109,7 @@ impl<'a> UnicodeEscape<'a> {
Self::with_preferred_quote(source, Quote::Single)
}
#[inline]
pub fn str_repr<'r>(&'a self) -> StrRepr<'r, 'a> {
pub const fn str_repr<'r>(&'a self) -> StrRepr<'r, 'a> {
StrRepr(self)
}
}
@@ -169,7 +169,7 @@ impl UnicodeEscape<'_> {
};
let Some(new_len) = length_add(out_len, incr) else {
#[cold]
fn stop(
const fn stop(
single_count: usize,
double_count: usize,
preferred_quote: Quote,
@@ -283,11 +283,11 @@ pub struct AsciiEscape<'a> {
impl<'a> AsciiEscape<'a> {
#[inline]
pub fn new(source: &'a [u8], layout: EscapeLayout) -> Self {
pub const fn new(source: &'a [u8], layout: EscapeLayout) -> Self {
Self { source, layout }
}
#[inline]
pub fn with_forced_quote(source: &'a [u8], quote: Quote) -> Self {
pub const fn with_forced_quote(source: &'a [u8], quote: Quote) -> Self {
let layout = EscapeLayout { quote, len: None };
Self { source, layout }
}
@@ -301,7 +301,7 @@ impl<'a> AsciiEscape<'a> {
Self::with_preferred_quote(source, Quote::Single)
}
#[inline]
pub fn bytes_repr<'r>(&'a self) -> BytesRepr<'r, 'a> {
pub const fn bytes_repr<'r>(&'a self) -> BytesRepr<'r, 'a> {
BytesRepr(self)
}
}
@@ -329,7 +329,7 @@ impl AsciiEscape<'_> {
let mut single_count = 0;
let mut double_count = 0;
for ch in source.iter() {
for ch in source {
let incr = match ch {
b'\'' => {
single_count += 1;
@@ -343,7 +343,7 @@ impl AsciiEscape<'_> {
};
let Some(new_len) = length_add(out_len, incr) else {
#[cold]
fn stop(
const fn stop(
single_count: usize,
double_count: usize,
preferred_quote: Quote,
@@ -370,7 +370,7 @@ impl AsciiEscape<'_> {
}
}
fn escaped_char_len(ch: u8) -> usize {
const fn escaped_char_len(ch: u8) -> usize {
match ch {
b'\\' | b'\t' | b'\r' | b'\n' => 2,
0x20..=0x7e => 1,
@@ -413,7 +413,7 @@ unsafe impl Escape for AsciiEscape<'_> {
#[cold]
fn write_body_slow(&self, formatter: &mut impl std::fmt::Write) -> std::fmt::Result {
for ch in self.source.iter() {
for ch in self.source {
Self::write_char(*ch, self.layout().quote, formatter)?;
}
Ok(())
+1 -1
View File
@@ -44,7 +44,7 @@ fn format_inf(case: Case) -> String {
inf.to_string()
}
pub fn decimal_point_or_empty(precision: usize, alternate_form: bool) -> &'static str {
pub const fn decimal_point_or_empty(precision: usize, alternate_form: bool) -> &'static str {
match (precision, alternate_form) {
(0, true) => ".",
_ => "",
+1 -1
View File
@@ -89,7 +89,7 @@ python_person.name: {}",
impl<'a> TryFromBorrowedObject<'a> for PythonPerson {
fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult<Self> {
let name = obj.get_attr("name", vm)?.try_into_value::<String>(vm)?;
Ok(PythonPerson { name })
Ok(Self { name })
}
}
}
+2 -2
View File
@@ -26,8 +26,8 @@ impl FromStr for InstallPipMode {
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"ensurepip" => Ok(InstallPipMode::Ensurepip),
"get-pip" => Ok(InstallPipMode::GetPip),
"ensurepip" => Ok(Self::Ensurepip),
"get-pip" => Ok(Self::GetPip),
_ => Err("--install-pip takes ensurepip or get-pip as first argument"),
}
}
+1 -1
View File
@@ -54,7 +54,7 @@ fn split_idents_on_dot(line: &str) -> Option<(usize, Vec<String>)> {
}
impl<'vm> ShellHelper<'vm> {
pub fn new(vm: &'vm VirtualMachine, globals: PyDictRef) -> Self {
pub const fn new(vm: &'vm VirtualMachine, globals: PyDictRef) -> Self {
ShellHelper { vm, globals }
}
+1 -3
View File
@@ -24,9 +24,7 @@ pub fn make_module(vm: &VirtualMachine) -> PyRef<PyModule> {
"east_asian_width",
"normalize",
"mirrored",
]
.into_iter()
{
] {
crate::vm::extend_module!(vm, &module, {
attr => ucd.get_attr(attr, vm).unwrap(),
});
+14 -14
View File
@@ -107,6 +107,7 @@ impl<'a> AsBag for &'a Context {
PyObjBag(self)
}
}
impl<'a> AsBag for &'a VirtualMachine {
type Bag = PyObjBag<'a>;
fn as_bag(self) -> PyObjBag<'a> {
@@ -123,28 +124,27 @@ impl ConstantBag for PyObjBag<'_> {
fn make_constant<C: Constant>(&self, constant: BorrowedConstant<'_, C>) -> Self::Constant {
let ctx = self.0;
let obj = match constant {
bytecode::BorrowedConstant::Integer { value } => ctx.new_bigint(value).into(),
bytecode::BorrowedConstant::Float { value } => ctx.new_float(value).into(),
bytecode::BorrowedConstant::Complex { value } => ctx.new_complex(value).into(),
bytecode::BorrowedConstant::Str { value } if value.len() <= 20 => {
BorrowedConstant::Integer { value } => ctx.new_bigint(value).into(),
BorrowedConstant::Float { value } => ctx.new_float(value).into(),
BorrowedConstant::Complex { value } => ctx.new_complex(value).into(),
BorrowedConstant::Str { value } if value.len() <= 20 => {
ctx.intern_str(value).to_object()
}
bytecode::BorrowedConstant::Str { value } => ctx.new_str(value).into(),
bytecode::BorrowedConstant::Bytes { value } => ctx.new_bytes(value.to_vec()).into(),
bytecode::BorrowedConstant::Boolean { value } => ctx.new_bool(value).into(),
bytecode::BorrowedConstant::Code { code } => {
ctx.new_code(code.map_clone_bag(self)).into()
}
bytecode::BorrowedConstant::Tuple { elements } => {
BorrowedConstant::Str { value } => ctx.new_str(value).into(),
BorrowedConstant::Bytes { value } => ctx.new_bytes(value.to_vec()).into(),
BorrowedConstant::Boolean { value } => ctx.new_bool(value).into(),
BorrowedConstant::Code { code } => ctx.new_code(code.map_clone_bag(self)).into(),
BorrowedConstant::Tuple { elements } => {
let elements = elements
.iter()
.map(|constant| self.make_constant(constant.borrow_constant()).0)
.collect();
ctx.new_tuple(elements).into()
}
bytecode::BorrowedConstant::None => ctx.none(),
bytecode::BorrowedConstant::Ellipsis => ctx.ellipsis.clone().into(),
BorrowedConstant::None => ctx.none(),
BorrowedConstant::Ellipsis => ctx.ellipsis.clone().into(),
};
Literal(obj)
}
@@ -172,7 +172,7 @@ pub trait IntoCodeObject {
}
impl IntoCodeObject for CodeObject {
fn into_code_object(self, _ctx: &Context) -> CodeObject {
fn into_code_object(self, _ctx: &Context) -> Self {
self
}
}
+1 -1
View File
@@ -280,7 +280,7 @@ impl PyDict {
if let OptionalArg::Present(dict_obj) = dict_obj {
self.merge_object(dict_obj, vm)?;
}
for (key, value) in kwargs.into_iter() {
for (key, value) in kwargs {
self.entries.insert(vm, &key, value)?;
}
Ok(())
+4 -4
View File
@@ -338,7 +338,7 @@ fn subs_tvars(
{
// TypeVarTuple case - extend with tuple elements
if let Ok(tuple) = substituted_arg.try_to_ref::<PyTuple>(vm) {
for elem in tuple.iter() {
for elem in tuple {
sub_args.push(elem.clone());
}
continue;
@@ -387,7 +387,7 @@ fn unpack_args(item: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
if !has_ellipsis_at_end {
// Safe to unpack - add all elements's PyList_SetSlice
for arg in tuple.iter() {
for arg in tuple {
new_args.push(arg.clone());
}
continue;
@@ -484,7 +484,7 @@ pub fn subs_parameters(
if unpack {
// Handle unpacked TypeVarTuple's tuple_extend
if let Ok(tuple) = substituted_arg.try_to_ref::<PyTuple>(vm) {
for elem in tuple.iter() {
for elem in tuple {
new_args.push(elem.clone());
}
} else {
@@ -572,7 +572,7 @@ impl Hashable for PyGenericAlias {
impl GetAttr for PyGenericAlias {
fn getattro(zelf: &Py<Self>, attr: &Py<PyStr>, vm: &VirtualMachine) -> PyResult {
for exc in ATTR_EXCEPTIONS.iter() {
for exc in &ATTR_EXCEPTIONS {
if *(*exc) == attr.to_string() {
return zelf.as_object().generic_getattr(attr, vm);
}
+1 -1
View File
@@ -51,7 +51,7 @@ impl Initializer for PyNamespace {
if !args.args.is_empty() {
return Err(vm.new_type_error("no positional arguments expected"));
}
for (name, value) in args.kwargs.into_iter() {
for (name, value) in args.kwargs {
let name = vm.ctx.new_str(name);
zelf.as_object().set_attr(&name, value, vm)?;
}
+1 -1
View File
@@ -228,7 +228,7 @@ impl Hashable for PySlice {
};
let mut acc = XXPRIME_5;
for part in [zelf.start_ref(vm), &zelf.stop, zelf.step_ref(vm)].iter() {
for part in &[zelf.start_ref(vm), &zelf.stop, zelf.step_ref(vm)] {
let lane = part.hash(vm)? as PyUHash;
if lane == u64::MAX as PyUHash {
return Ok(-1 as PyHash);
+1 -1
View File
@@ -1522,7 +1522,7 @@ impl PyStrRef {
pub fn try_into_utf8(self, vm: &VirtualMachine) -> PyResult<PyRef<PyUtf8Str>> {
self.ensure_valid_utf8(vm)?;
Ok(unsafe { mem::transmute::<PyRef<PyStr>, PyRef<PyUtf8Str>>(self) })
Ok(unsafe { mem::transmute::<Self, PyRef<PyUtf8Str>>(self) })
}
}
+1 -1
View File
@@ -174,7 +174,7 @@ impl GetAttr for PySuper {
.skip_while(|cls| !cls.is(&zelf.inner.read().typ))
.skip(1) // skip su->type (if any)
.collect();
for cls in mro.iter() {
for cls in &mro {
if let Some(descr) = cls.get_direct_attr(name) {
return vm
.call_get_descriptor_specific(
+2 -2
View File
@@ -69,13 +69,13 @@ impl PyTraceback {
}
impl Constructor for PyTraceback {
type Args = (Option<PyRef<PyTraceback>>, FrameRef, u32, usize);
type Args = (Option<PyRef<Self>>, FrameRef, u32, usize);
fn py_new(cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult {
let (next, frame, lasti, lineno) = args;
let lineno = OneIndexed::new(lineno)
.ok_or_else(|| vm.new_value_error("lineno must be positive".to_owned()))?;
let tb = PyTraceback::new(next, frame, lasti, lineno);
let tb = Self::new(next, frame, lasti, lineno);
tb.into_ref_with_type(vm, cls).map(Into::into)
}
}
+6 -6
View File
@@ -232,13 +232,13 @@ impl PyTuple<PyObjectRef> {
}
impl<T> PyTuple<PyRef<T>> {
pub fn new_ref_typed(elements: Vec<PyRef<T>>, ctx: &Context) -> PyRef<PyTuple<PyRef<T>>> {
pub fn new_ref_typed(elements: Vec<PyRef<T>>, ctx: &Context) -> PyRef<Self> {
// SAFETY: PyRef<T> has the same layout as PyObjectRef
unsafe {
let elements: Vec<PyObjectRef> =
std::mem::transmute::<Vec<PyRef<T>>, Vec<PyObjectRef>>(elements);
let tuple = PyTuple::<PyObjectRef>::new_ref(elements, ctx);
std::mem::transmute::<PyRef<PyTuple>, PyRef<PyTuple<PyRef<T>>>>(tuple)
std::mem::transmute::<PyRef<PyTuple>, PyRef<Self>>(tuple)
}
}
}
@@ -339,7 +339,7 @@ impl PyTuple {
}
fn _contains(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult<bool> {
for element in self.elements.iter() {
for element in &self.elements {
if vm.identical_or_equal(element, needle)? {
return Ok(true);
}
@@ -483,21 +483,21 @@ impl PyRef<PyTuple<PyObjectRef>> {
<PyRef<T> as TransmuteFromObject>::check(vm, elem)?;
}
// SAFETY: We just verified all elements are of type T
Ok(unsafe { std::mem::transmute::<PyRef<PyTuple>, PyRef<PyTuple<PyRef<T>>>>(self) })
Ok(unsafe { std::mem::transmute::<Self, PyRef<PyTuple<PyRef<T>>>>(self) })
}
}
impl<T: PyPayload> PyRef<PyTuple<PyRef<T>>> {
pub fn into_untyped(self) -> PyRef<PyTuple> {
// SAFETY: PyTuple<PyRef<T>> has the same layout as PyTuple
unsafe { std::mem::transmute::<PyRef<PyTuple<PyRef<T>>>, PyRef<PyTuple>>(self) }
unsafe { std::mem::transmute::<Self, PyRef<PyTuple>>(self) }
}
}
impl<T: PyPayload> Py<PyTuple<PyRef<T>>> {
pub fn as_untyped(&self) -> &Py<PyTuple> {
// SAFETY: PyTuple<PyRef<T>> has the same layout as PyTuple
unsafe { std::mem::transmute::<&Py<PyTuple<PyRef<T>>>, &Py<PyTuple>>(self) }
unsafe { std::mem::transmute::<&Self, &Py<PyTuple>>(self) }
}
}
+3 -3
View File
@@ -341,7 +341,7 @@ impl ExecutingFrame<'_> {
}
#[inline(always)]
fn lasti(&self) -> u32 {
const fn lasti(&self) -> u32 {
#[cfg(feature = "threading")]
{
self.state.lasti
@@ -1313,7 +1313,7 @@ impl ExecutingFrame<'_> {
// push a tuple of extracted attributes.
if subject.is_instance(cls.as_ref(), vm)? {
let mut extracted = vec![];
for name in names.iter() {
for name in names {
let name_str = name.downcast_ref::<PyStr>().unwrap();
let value = subject.get_attr(name_str, vm)?;
extracted.push(value);
@@ -2074,7 +2074,7 @@ impl ExecutingFrame<'_> {
bytecode::TestOperator::NotIn => self._not_in(vm, &a, &b)?,
bytecode::TestOperator::ExceptionMatch => {
if let Some(tuple_of_exceptions) = b.downcast_ref::<PyTuple>() {
for exception in tuple_of_exceptions.iter() {
for exception in tuple_of_exceptions {
if !exception
.is_subclass(vm.ctx.exceptions.base_exception_type.into(), vm)?
{
+1 -1
View File
@@ -71,7 +71,7 @@ pub(crate) mod _ast {
let zelf = vm.ctx.new_base_object(cls, dict);
// Initialize the instance with the provided arguments
NodeAst::__init__(zelf.clone(), args, vm)?;
Self::__init__(zelf.clone(), args, vm)?;
Ok(zelf)
}
+1 -1
View File
@@ -3601,7 +3601,7 @@ mod _io {
}
#[pygetset]
fn line_buffering(&self) -> bool {
const fn line_buffering(&self) -> bool {
false
}
}
+1 -1
View File
@@ -1381,7 +1381,7 @@ mod decl {
}
let mut pools: Vec<PyObjectRef> = Vec::new();
for element in zelf.pools.iter() {
for element in &zelf.pools {
pools.push(element.clone().into_pytuple(vm).into());
}
+1 -1
View File
@@ -516,7 +516,7 @@ pub mod module {
if reversed {
funcs.reverse();
}
for func in funcs.into_iter() {
for func in funcs {
if let Err(e) = func.call((), vm) {
let exit = e.fast_isinstance(vm.ctx.exceptions.system_exit);
vm.run_unraisable(e, Some("Exception ignored in".to_owned()), func);
+1 -1
View File
@@ -69,7 +69,7 @@ mod symtable {
}
#[pymethod]
fn is_optimized(&self) -> bool {
const fn is_optimized(&self) -> bool {
matches!(
self.symtable.typ,
CompilerScope::Function | CompilerScope::AsyncFunction
+1 -1
View File
@@ -286,7 +286,7 @@ pub(crate) mod _thread {
}
#[pyfunction]
fn allocate_lock() -> Lock {
const fn allocate_lock() -> Lock {
Lock { mu: RawMutex::INIT }
}
+1 -1
View File
@@ -165,7 +165,7 @@ pub(crate) mod decl {
vm.ctx.empty_tuple.clone()
};
let ta = TypeAliasType::new(name, type_params, value);
let ta = Self::new(name, type_params, value);
ta.into_ref_with_type(vm, cls).map(Into::into)
}
}
+9 -9
View File
@@ -68,7 +68,7 @@ impl Marks {
}
}
pub fn last_index(&self) -> isize {
pub const fn last_index(&self) -> isize {
self.last_index
}
@@ -1054,11 +1054,11 @@ impl MatchContext {
&req.pattern_codes[self.code_position..]
}
fn remaining_codes<S>(&self, req: &Request<'_, S>) -> usize {
const fn remaining_codes<S>(&self, req: &Request<'_, S>) -> usize {
req.pattern_codes.len() - self.code_position
}
fn remaining_chars<S>(&self, req: &Request<'_, S>) -> usize {
const fn remaining_chars<S>(&self, req: &Request<'_, S>) -> usize {
req.end - self.cursor.position
}
@@ -1097,7 +1097,7 @@ impl MatchContext {
self.peek_code(req, peek).try_into()
}
fn skip_code(&mut self, skip: usize) {
const fn skip_code(&mut self, skip: usize) {
self.code_position += skip;
}
@@ -1105,12 +1105,12 @@ impl MatchContext {
self.skip_code(self.peek_code(req, peek) as usize + 1);
}
fn at_beginning(&self) -> bool {
const fn at_beginning(&self) -> bool {
// self.ctx().string_position == self.state().start
self.cursor.position == 0
}
fn at_end<S>(&self, req: &Request<'_, S>) -> bool {
const fn at_end<S>(&self, req: &Request<'_, S>) -> bool {
self.cursor.position == req.end
}
@@ -1144,7 +1144,7 @@ impl MatchContext {
this == that
}
fn can_success<S>(&self, req: &Request<'_, S>) -> bool {
const fn can_success<S>(&self, req: &Request<'_, S>) -> bool {
if !self.toplevel {
return true;
}
@@ -1163,12 +1163,12 @@ impl MatchContext {
}
#[must_use]
fn next_offset(&mut self, offset: usize, jump: Jump) -> Self {
const fn next_offset(&mut self, offset: usize, jump: Jump) -> Self {
self.next_at(self.code_position + offset, jump)
}
#[must_use]
fn next_at(&mut self, code_position: usize, jump: Jump) -> Self {
const fn next_at(&mut self, code_position: usize, jump: Jump) -> Self {
self.jump = jump;
Self {
code_position,
+4 -4
View File
@@ -223,7 +223,7 @@ impl StrDrive for &Wtf8 {
///
/// `bytes` must produce a valid UTF-8-like (UTF-8 or WTF-8) string
#[inline]
unsafe fn next_code_point(ptr: &mut *const u8) -> u32 {
const unsafe fn next_code_point(ptr: &mut *const u8) -> u32 {
// Decode UTF-8
let x = unsafe { **ptr };
*ptr = unsafe { ptr.offset(1) };
@@ -271,7 +271,7 @@ unsafe fn next_code_point(ptr: &mut *const u8) -> u32 {
///
/// `bytes` must produce a valid UTF-8-like (UTF-8 or WTF-8) string
#[inline]
unsafe fn next_code_point_reverse(ptr: &mut *const u8) -> u32 {
const unsafe fn next_code_point_reverse(ptr: &mut *const u8) -> u32 {
// Decode UTF-8
*ptr = unsafe { ptr.offset(-1) };
let w = match unsafe { **ptr } {
@@ -367,7 +367,7 @@ pub(crate) fn is_loc_word(ch: u32) -> bool {
ch == '_' as u32 || is_loc_alnum(ch)
}
#[inline]
pub(crate) fn is_linebreak(ch: u32) -> bool {
pub(crate) const fn is_linebreak(ch: u32) -> bool {
ch == '\n' as u32
}
#[inline]
@@ -433,7 +433,7 @@ pub(crate) fn is_uni_space(ch: u32) -> bool {
)
}
#[inline]
pub(crate) fn is_uni_linebreak(ch: u32) -> bool {
pub(crate) const fn is_uni_linebreak(ch: u32) -> bool {
matches!(
ch,
0x000A | 0x000B | 0x000C | 0x000D | 0x001C | 0x001D | 0x001E | 0x0085 | 0x2028 | 0x2029