mirror of
https://github.com/RustPython/RustPython.git
synced 2026-10-28 10:44:36 +08:00
Use Self where possible (#5892)
This commit is contained in:
1 parent
05013e3d0b
commit
69545c0798
128 files changed
+738
-825
No files matched your search
@@ -65,7 +65,7 @@ impl<T> Default for OncePtr<T> {
|
||||
impl<T> OncePtr<T> {
|
||||
#[inline]
|
||||
pub fn new() -> Self {
|
||||
OncePtr {
|
||||
Self {
|
||||
inner: Radium::new(ptr::null_mut()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,8 +38,8 @@ macro_rules! panic_oob {
|
||||
}
|
||||
|
||||
impl<T> BoxVec<T> {
|
||||
pub fn new(n: usize) -> BoxVec<T> {
|
||||
BoxVec {
|
||||
pub fn new(n: usize) -> Self {
|
||||
Self {
|
||||
xs: Box::new_uninit_slice(n),
|
||||
len: 0,
|
||||
}
|
||||
@@ -593,7 +593,7 @@ where
|
||||
T: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
let mut new = BoxVec::new(self.capacity());
|
||||
let mut new = Self::new(self.capacity());
|
||||
new.extend(self.iter().cloned());
|
||||
new
|
||||
}
|
||||
@@ -676,8 +676,8 @@ pub struct CapacityError<T = ()> {
|
||||
|
||||
impl<T> CapacityError<T> {
|
||||
/// Create a new `CapacityError` from `element`.
|
||||
pub const fn new(element: T) -> CapacityError<T> {
|
||||
CapacityError { element }
|
||||
pub const fn new(element: T) -> Self {
|
||||
Self { element }
|
||||
}
|
||||
|
||||
/// Extract the overflowing element
|
||||
|
||||
@@ -103,10 +103,10 @@ pub enum CFormatType {
|
||||
impl CFormatType {
|
||||
pub const fn to_char(self) -> char {
|
||||
match self {
|
||||
CFormatType::Number(x) => x as u8 as char,
|
||||
CFormatType::Float(x) => x as u8 as char,
|
||||
CFormatType::Character(x) => x as u8 as char,
|
||||
CFormatType::String(x) => x as u8 as char,
|
||||
Self::Number(x) => x as u8 as char,
|
||||
Self::Float(x) => x as u8 as char,
|
||||
Self::Character(x) => x as u8 as char,
|
||||
Self::String(x) => x as u8 as char,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -119,7 +119,7 @@ pub enum CFormatPrecision {
|
||||
|
||||
impl From<CFormatQuantity> for CFormatPrecision {
|
||||
fn from(quantity: CFormatQuantity) -> Self {
|
||||
CFormatPrecision::Quantity(quantity)
|
||||
Self::Quantity(quantity)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -338,7 +338,7 @@ impl CFormatSpec {
|
||||
_ => &num_chars,
|
||||
};
|
||||
let fill_chars_needed = width.saturating_sub(num_chars);
|
||||
let fill_string: T = CFormatSpec::compute_fill_string(fill_char, fill_chars_needed);
|
||||
let fill_string: T = Self::compute_fill_string(fill_char, fill_chars_needed);
|
||||
|
||||
if !fill_string.is_empty() {
|
||||
if self.flags.contains(CConversionFlags::LEFT_ADJUST) {
|
||||
@@ -361,7 +361,7 @@ impl CFormatSpec {
|
||||
_ => &num_chars,
|
||||
};
|
||||
let fill_chars_needed = width.saturating_sub(num_chars);
|
||||
let fill_string: T = CFormatSpec::compute_fill_string(fill_char, fill_chars_needed);
|
||||
let fill_string: T = Self::compute_fill_string(fill_char, fill_chars_needed);
|
||||
|
||||
if !fill_string.is_empty() {
|
||||
// Don't left-adjust if precision-filling: that will always be prepending 0s to %d
|
||||
@@ -721,13 +721,13 @@ pub enum CFormatPart<T> {
|
||||
impl<T> CFormatPart<T> {
|
||||
#[inline]
|
||||
pub const fn is_specifier(&self) -> bool {
|
||||
matches!(self, CFormatPart::Spec { .. })
|
||||
matches!(self, Self::Spec { .. })
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub const fn has_key(&self) -> bool {
|
||||
match self {
|
||||
CFormatPart::Spec(s) => s.mapping_key.is_some(),
|
||||
Self::Spec(s) => s.mapping_key.is_some(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
+35
-41
@@ -38,23 +38,23 @@ impl FormatParse for FormatConversion {
|
||||
}
|
||||
|
||||
impl FormatConversion {
|
||||
pub fn from_char(c: CodePoint) -> Option<FormatConversion> {
|
||||
pub fn from_char(c: CodePoint) -> Option<Self> {
|
||||
match c.to_char_lossy() {
|
||||
's' => Some(FormatConversion::Str),
|
||||
'r' => Some(FormatConversion::Repr),
|
||||
'a' => Some(FormatConversion::Ascii),
|
||||
'b' => Some(FormatConversion::Bytes),
|
||||
's' => Some(Self::Str),
|
||||
'r' => Some(Self::Repr),
|
||||
'a' => Some(Self::Ascii),
|
||||
'b' => Some(Self::Bytes),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn from_string(text: &Wtf8) -> Option<FormatConversion> {
|
||||
fn from_string(text: &Wtf8) -> Option<Self> {
|
||||
let mut chars = text.code_points();
|
||||
if chars.next()? != '!' {
|
||||
return None;
|
||||
}
|
||||
|
||||
FormatConversion::from_char(chars.next()?)
|
||||
Self::from_char(chars.next()?)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,12 +67,12 @@ pub enum FormatAlign {
|
||||
}
|
||||
|
||||
impl FormatAlign {
|
||||
fn from_char(c: CodePoint) -> Option<FormatAlign> {
|
||||
fn from_char(c: CodePoint) -> Option<Self> {
|
||||
match c.to_char_lossy() {
|
||||
'<' => Some(FormatAlign::Left),
|
||||
'>' => Some(FormatAlign::Right),
|
||||
'=' => Some(FormatAlign::AfterSign),
|
||||
'^' => Some(FormatAlign::Center),
|
||||
'<' => Some(Self::Left),
|
||||
'>' => Some(Self::Right),
|
||||
'=' => Some(Self::AfterSign),
|
||||
'^' => Some(Self::Center),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -141,7 +141,7 @@ pub enum FormatType {
|
||||
}
|
||||
|
||||
impl From<&FormatType> for char {
|
||||
fn from(from: &FormatType) -> char {
|
||||
fn from(from: &FormatType) -> Self {
|
||||
match from {
|
||||
FormatType::String => 's',
|
||||
FormatType::Binary => 'b',
|
||||
@@ -299,7 +299,7 @@ impl FormatSpec {
|
||||
align = align.or(Some(FormatAlign::AfterSign));
|
||||
}
|
||||
|
||||
Ok(FormatSpec {
|
||||
Ok(Self {
|
||||
conversion,
|
||||
fill,
|
||||
align,
|
||||
@@ -327,7 +327,7 @@ impl FormatSpec {
|
||||
let magnitude_int_str = parts.next().unwrap().to_string();
|
||||
let dec_digit_cnt = magnitude_str.len() as i32 - magnitude_int_str.len() as i32;
|
||||
let int_digit_cnt = disp_digit_cnt - dec_digit_cnt;
|
||||
let mut result = FormatSpec::separate_integer(magnitude_int_str, inter, sep, int_digit_cnt);
|
||||
let mut result = Self::separate_integer(magnitude_int_str, inter, sep, int_digit_cnt);
|
||||
if let Some(part) = parts.next() {
|
||||
result.push_str(&format!(".{part}"))
|
||||
}
|
||||
@@ -350,11 +350,11 @@ impl FormatSpec {
|
||||
// separate with 0 padding
|
||||
let padding = "0".repeat(diff as usize);
|
||||
let padded_num = format!("{padding}{magnitude_str}");
|
||||
FormatSpec::insert_separator(padded_num, inter, sep, sep_cnt)
|
||||
Self::insert_separator(padded_num, inter, sep, sep_cnt)
|
||||
} else {
|
||||
// separate without padding
|
||||
let sep_cnt = (magnitude_len - 1) / inter;
|
||||
FormatSpec::insert_separator(magnitude_str, inter, sep, sep_cnt)
|
||||
Self::insert_separator(magnitude_str, inter, sep, sep_cnt)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -412,12 +412,7 @@ impl FormatSpec {
|
||||
let magnitude_len = magnitude_str.len();
|
||||
let width = self.width.unwrap_or(magnitude_len) as i32 - prefix.len() as i32;
|
||||
let disp_digit_cnt = cmp::max(width, magnitude_len as i32);
|
||||
FormatSpec::add_magnitude_separators_for_char(
|
||||
magnitude_str,
|
||||
inter,
|
||||
sep,
|
||||
disp_digit_cnt,
|
||||
)
|
||||
Self::add_magnitude_separators_for_char(magnitude_str, inter, sep, disp_digit_cnt)
|
||||
}
|
||||
None => magnitude_str,
|
||||
}
|
||||
@@ -640,27 +635,26 @@ impl FormatSpec {
|
||||
"{}{}{}",
|
||||
sign_str,
|
||||
magnitude_str,
|
||||
FormatSpec::compute_fill_string(fill_char, fill_chars_needed)
|
||||
Self::compute_fill_string(fill_char, fill_chars_needed)
|
||||
),
|
||||
FormatAlign::Right => format!(
|
||||
"{}{}{}",
|
||||
FormatSpec::compute_fill_string(fill_char, fill_chars_needed),
|
||||
Self::compute_fill_string(fill_char, fill_chars_needed),
|
||||
sign_str,
|
||||
magnitude_str
|
||||
),
|
||||
FormatAlign::AfterSign => format!(
|
||||
"{}{}{}",
|
||||
sign_str,
|
||||
FormatSpec::compute_fill_string(fill_char, fill_chars_needed),
|
||||
Self::compute_fill_string(fill_char, fill_chars_needed),
|
||||
magnitude_str
|
||||
),
|
||||
FormatAlign::Center => {
|
||||
let left_fill_chars_needed = fill_chars_needed / 2;
|
||||
let right_fill_chars_needed = fill_chars_needed - left_fill_chars_needed;
|
||||
let left_fill_string =
|
||||
FormatSpec::compute_fill_string(fill_char, left_fill_chars_needed);
|
||||
let left_fill_string = Self::compute_fill_string(fill_char, left_fill_chars_needed);
|
||||
let right_fill_string =
|
||||
FormatSpec::compute_fill_string(fill_char, right_fill_chars_needed);
|
||||
Self::compute_fill_string(fill_char, right_fill_chars_needed);
|
||||
format!("{left_fill_string}{sign_str}{magnitude_str}{right_fill_string}")
|
||||
}
|
||||
})
|
||||
@@ -725,7 +719,7 @@ pub enum FormatParseError {
|
||||
impl FromStr for FormatSpec {
|
||||
type Err = FormatSpecError;
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
FormatSpec::parse(s)
|
||||
Self::parse(s)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -739,7 +733,7 @@ pub enum FieldNamePart {
|
||||
impl FieldNamePart {
|
||||
fn parse_part(
|
||||
chars: &mut impl PeekingNext<Item = CodePoint>,
|
||||
) -> Result<Option<FieldNamePart>, FormatParseError> {
|
||||
) -> Result<Option<Self>, FormatParseError> {
|
||||
chars
|
||||
.next()
|
||||
.map(|ch| match ch.to_char_lossy() {
|
||||
@@ -751,7 +745,7 @@ impl FieldNamePart {
|
||||
if attribute.is_empty() {
|
||||
Err(FormatParseError::EmptyAttribute)
|
||||
} else {
|
||||
Ok(FieldNamePart::Attribute(attribute))
|
||||
Ok(Self::Attribute(attribute))
|
||||
}
|
||||
}
|
||||
'[' => {
|
||||
@@ -761,9 +755,9 @@ impl FieldNamePart {
|
||||
return if index.is_empty() {
|
||||
Err(FormatParseError::EmptyAttribute)
|
||||
} else if let Some(index) = parse_usize(&index) {
|
||||
Ok(FieldNamePart::Index(index))
|
||||
Ok(Self::Index(index))
|
||||
} else {
|
||||
Ok(FieldNamePart::StringIndex(index))
|
||||
Ok(Self::StringIndex(index))
|
||||
};
|
||||
}
|
||||
index.push(ch);
|
||||
@@ -794,7 +788,7 @@ fn parse_usize(s: &Wtf8) -> Option<usize> {
|
||||
}
|
||||
|
||||
impl FieldName {
|
||||
pub fn parse(text: &Wtf8) -> Result<FieldName, FormatParseError> {
|
||||
pub fn parse(text: &Wtf8) -> Result<Self, FormatParseError> {
|
||||
let mut chars = text.code_points().peekable();
|
||||
let first: Wtf8Buf = chars
|
||||
.peeking_take_while(|ch| *ch != '.' && *ch != '[')
|
||||
@@ -813,7 +807,7 @@ impl FieldName {
|
||||
parts.push(part)
|
||||
}
|
||||
|
||||
Ok(FieldName { field_type, parts })
|
||||
Ok(Self { field_type, parts })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -854,7 +848,7 @@ impl FormatString {
|
||||
let mut cur_text = text;
|
||||
let mut result_string = Wtf8Buf::new();
|
||||
while !cur_text.is_empty() {
|
||||
match FormatString::parse_literal_single(cur_text) {
|
||||
match Self::parse_literal_single(cur_text) {
|
||||
Ok((next_char, remaining)) => {
|
||||
result_string.push(next_char);
|
||||
cur_text = remaining;
|
||||
@@ -968,7 +962,7 @@ impl FormatString {
|
||||
}
|
||||
if let Some(pos) = end_bracket_pos {
|
||||
let right = &text[pos..];
|
||||
let format_part = FormatString::parse_part_in_brackets(&left)?;
|
||||
let format_part = Self::parse_part_in_brackets(&left)?;
|
||||
Ok((format_part, &right[1..]))
|
||||
} else {
|
||||
Err(FormatParseError::UnmatchedBracket)
|
||||
@@ -990,14 +984,14 @@ impl<'a> FromTemplate<'a> for FormatString {
|
||||
while !cur_text.is_empty() {
|
||||
// Try to parse both literals and bracketed format parts until we
|
||||
// run out of text
|
||||
cur_text = FormatString::parse_literal(cur_text)
|
||||
.or_else(|_| FormatString::parse_spec(cur_text))
|
||||
cur_text = Self::parse_literal(cur_text)
|
||||
.or_else(|_| Self::parse_spec(cur_text))
|
||||
.map(|(part, new_text)| {
|
||||
parts.push(part);
|
||||
new_text
|
||||
})?;
|
||||
}
|
||||
Ok(FormatString {
|
||||
Ok(Self {
|
||||
format_parts: parts,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -140,8 +140,8 @@ unsafe impl<T: Sync> Sync for Pointers<T> {}
|
||||
|
||||
impl<L, T> LinkedList<L, T> {
|
||||
/// Creates an empty linked list.
|
||||
pub const fn new() -> LinkedList<L, T> {
|
||||
LinkedList {
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
head: None,
|
||||
// tail: None,
|
||||
_marker: PhantomData,
|
||||
@@ -323,8 +323,8 @@ where
|
||||
|
||||
impl<T> Pointers<T> {
|
||||
/// Create a new set of empty pointers
|
||||
pub fn new() -> Pointers<T> {
|
||||
Pointers {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
inner: UnsafeCell::new(PointersInner {
|
||||
prev: None,
|
||||
next: None,
|
||||
|
||||
@@ -11,7 +11,7 @@ pub struct RawCellMutex {
|
||||
|
||||
unsafe impl RawMutex for RawCellMutex {
|
||||
#[allow(clippy::declare_interior_mutable_const)]
|
||||
const INIT: Self = RawCellMutex {
|
||||
const INIT: Self = Self {
|
||||
locked: Cell::new(false),
|
||||
};
|
||||
|
||||
@@ -61,7 +61,7 @@ impl RawCellRwLock {
|
||||
|
||||
unsafe impl RawRwLock for RawCellRwLock {
|
||||
#[allow(clippy::declare_interior_mutable_const)]
|
||||
const INIT: Self = RawCellRwLock {
|
||||
const INIT: Self = Self {
|
||||
state: Cell::new(0),
|
||||
};
|
||||
|
||||
@@ -203,7 +203,7 @@ fn deadlock(lock_kind: &str, ty: &str) -> ! {
|
||||
|
||||
pub struct SingleThreadId(());
|
||||
unsafe impl GetThreadId for SingleThreadId {
|
||||
const INIT: Self = SingleThreadId(());
|
||||
const INIT: Self = Self(());
|
||||
fn nonzero_thread_id(&self) -> NonZero<usize> {
|
||||
NonZero::new(1).unwrap()
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ pub struct RawThreadMutex<R: RawMutex, G: GetThreadId> {
|
||||
|
||||
impl<R: RawMutex, G: GetThreadId> RawThreadMutex<R, G> {
|
||||
#[allow(clippy::declare_interior_mutable_const)]
|
||||
pub const INIT: Self = RawThreadMutex {
|
||||
pub const INIT: Self = Self {
|
||||
owner: AtomicUsize::new(0),
|
||||
mutex: R::INIT,
|
||||
get_thread_id: G::INIT,
|
||||
@@ -79,7 +79,7 @@ pub struct ThreadMutex<R: RawMutex, G: GetThreadId, T: ?Sized> {
|
||||
|
||||
impl<R: RawMutex, G: GetThreadId, T> ThreadMutex<R, G, T> {
|
||||
pub fn new(val: T) -> Self {
|
||||
ThreadMutex {
|
||||
Self {
|
||||
raw: RawThreadMutex::INIT,
|
||||
data: UnsafeCell::new(val),
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ impl RefCount {
|
||||
const MASK: usize = MAX_REFCOUNT;
|
||||
|
||||
pub fn new() -> Self {
|
||||
RefCount {
|
||||
Self {
|
||||
strong: Radium::new(1),
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -47,9 +47,9 @@ impl StrKind {
|
||||
#[inline(always)]
|
||||
pub fn can_encode(&self, code: CodePoint) -> bool {
|
||||
match self {
|
||||
StrKind::Ascii => code.is_ascii(),
|
||||
StrKind::Utf8 => code.to_char().is_some(),
|
||||
StrKind::Wtf8 => true,
|
||||
Self::Ascii => code.is_ascii(),
|
||||
Self::Utf8 => code.to_char().is_some(),
|
||||
Self::Wtf8 => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -283,7 +283,7 @@ impl Default for PatternContext {
|
||||
|
||||
impl PatternContext {
|
||||
pub fn new() -> Self {
|
||||
PatternContext {
|
||||
Self {
|
||||
stores: Vec::new(),
|
||||
allow_irrefutable: false,
|
||||
fail_pop: Vec::new(),
|
||||
|
||||
@@ -11,7 +11,7 @@ use rustpython_compiler_core::bytecode::{
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
pub struct BlockIdx(pub u32);
|
||||
impl BlockIdx {
|
||||
pub const NULL: BlockIdx = BlockIdx(u32::MAX);
|
||||
pub const NULL: Self = Self(u32::MAX);
|
||||
const fn idx(self) -> usize {
|
||||
self.0 as usize
|
||||
}
|
||||
@@ -58,7 +58,7 @@ pub struct Block {
|
||||
}
|
||||
impl Default for Block {
|
||||
fn default() -> Self {
|
||||
Block {
|
||||
Self {
|
||||
instructions: Vec::new(),
|
||||
next: BlockIdx::NULL,
|
||||
}
|
||||
@@ -91,7 +91,7 @@ impl CodeInfo {
|
||||
let max_stackdepth = self.max_stackdepth()?;
|
||||
let cell2arg = self.cell2arg();
|
||||
|
||||
let CodeInfo {
|
||||
let Self {
|
||||
flags,
|
||||
posonlyarg_count,
|
||||
arg_count,
|
||||
|
||||
+27
-27
@@ -28,39 +28,39 @@ pub trait ToPythonName {
|
||||
impl ToPythonName for Expr {
|
||||
fn python_name(&self) -> &'static str {
|
||||
match self {
|
||||
Expr::BoolOp { .. } | Expr::BinOp { .. } | Expr::UnaryOp { .. } => "operator",
|
||||
Expr::Subscript { .. } => "subscript",
|
||||
Expr::Await { .. } => "await expression",
|
||||
Expr::Yield { .. } | Expr::YieldFrom { .. } => "yield expression",
|
||||
Expr::Compare { .. } => "comparison",
|
||||
Expr::Attribute { .. } => "attribute",
|
||||
Expr::Call { .. } => "function call",
|
||||
Expr::BooleanLiteral(b) => {
|
||||
Self::BoolOp { .. } | Self::BinOp { .. } | Self::UnaryOp { .. } => "operator",
|
||||
Self::Subscript { .. } => "subscript",
|
||||
Self::Await { .. } => "await expression",
|
||||
Self::Yield { .. } | Self::YieldFrom { .. } => "yield expression",
|
||||
Self::Compare { .. } => "comparison",
|
||||
Self::Attribute { .. } => "attribute",
|
||||
Self::Call { .. } => "function call",
|
||||
Self::BooleanLiteral(b) => {
|
||||
if b.value {
|
||||
"True"
|
||||
} else {
|
||||
"False"
|
||||
}
|
||||
}
|
||||
Expr::EllipsisLiteral(_) => "ellipsis",
|
||||
Expr::NoneLiteral(_) => "None",
|
||||
Expr::NumberLiteral(_) | Expr::BytesLiteral(_) | Expr::StringLiteral(_) => "literal",
|
||||
Expr::Tuple(_) => "tuple",
|
||||
Expr::List { .. } => "list",
|
||||
Expr::Dict { .. } => "dict display",
|
||||
Expr::Set { .. } => "set display",
|
||||
Expr::ListComp { .. } => "list comprehension",
|
||||
Expr::DictComp { .. } => "dict comprehension",
|
||||
Expr::SetComp { .. } => "set comprehension",
|
||||
Expr::Generator { .. } => "generator expression",
|
||||
Expr::Starred { .. } => "starred",
|
||||
Expr::Slice { .. } => "slice",
|
||||
Expr::FString { .. } => "f-string expression",
|
||||
Expr::Name { .. } => "name",
|
||||
Expr::Lambda { .. } => "lambda",
|
||||
Expr::If { .. } => "conditional expression",
|
||||
Expr::Named { .. } => "named expression",
|
||||
Expr::IpyEscapeCommand(_) => todo!(),
|
||||
Self::EllipsisLiteral(_) => "ellipsis",
|
||||
Self::NoneLiteral(_) => "None",
|
||||
Self::NumberLiteral(_) | Self::BytesLiteral(_) | Self::StringLiteral(_) => "literal",
|
||||
Self::Tuple(_) => "tuple",
|
||||
Self::List { .. } => "list",
|
||||
Self::Dict { .. } => "dict display",
|
||||
Self::Set { .. } => "set display",
|
||||
Self::ListComp { .. } => "list comprehension",
|
||||
Self::DictComp { .. } => "dict comprehension",
|
||||
Self::SetComp { .. } => "set comprehension",
|
||||
Self::Generator { .. } => "generator expression",
|
||||
Self::Starred { .. } => "starred",
|
||||
Self::Slice { .. } => "slice",
|
||||
Self::FString { .. } => "f-string expression",
|
||||
Self::Name { .. } => "name",
|
||||
Self::Lambda { .. } => "lambda",
|
||||
Self::If { .. } => "conditional expression",
|
||||
Self::Named { .. } => "named expression",
|
||||
Self::IpyEscapeCommand(_) => todo!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,7 +49,7 @@ pub struct SymbolTable {
|
||||
|
||||
impl SymbolTable {
|
||||
fn new(name: String, typ: SymbolTableType, line_number: u32, is_nested: bool) -> Self {
|
||||
SymbolTable {
|
||||
Self {
|
||||
name,
|
||||
typ,
|
||||
line_number,
|
||||
@@ -87,11 +87,11 @@ pub enum SymbolTableType {
|
||||
impl fmt::Display for SymbolTableType {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
SymbolTableType::Module => write!(f, "module"),
|
||||
SymbolTableType::Class => write!(f, "class"),
|
||||
SymbolTableType::Function => write!(f, "function"),
|
||||
SymbolTableType::Comprehension => write!(f, "comprehension"),
|
||||
SymbolTableType::TypeParams => write!(f, "type parameter"),
|
||||
Self::Module => write!(f, "module"),
|
||||
Self::Class => write!(f, "class"),
|
||||
Self::Function => write!(f, "function"),
|
||||
Self::Comprehension => write!(f, "comprehension"),
|
||||
Self::TypeParams => write!(f, "type parameter"),
|
||||
// TODO missing types from the C implementation
|
||||
// if self._table.type == _symtable.TYPE_ANNOTATION:
|
||||
// return "annotation"
|
||||
@@ -154,7 +154,7 @@ pub struct Symbol {
|
||||
|
||||
impl Symbol {
|
||||
fn new(name: &str) -> Self {
|
||||
Symbol {
|
||||
Self {
|
||||
name: name.to_owned(),
|
||||
// table,
|
||||
scope: SymbolScope::Unknown,
|
||||
@@ -293,7 +293,7 @@ impl SymbolTableAnalyzer {
|
||||
|
||||
let mut info = (symbols, symbol_table.typ);
|
||||
self.tables.with_append(&mut info, |list| {
|
||||
let inner_scope = unsafe { &mut *(list as *mut _ as *mut SymbolTableAnalyzer) };
|
||||
let inner_scope = unsafe { &mut *(list as *mut _ as *mut Self) };
|
||||
// Analyze sub scopes:
|
||||
for sub_table in sub_tables.iter_mut() {
|
||||
inner_scope.analyze_symbol_table(sub_table)?;
|
||||
|
||||
@@ -36,16 +36,16 @@ impl Constant for ConstantData {
|
||||
fn borrow_constant(&self) -> BorrowedConstant<'_, Self> {
|
||||
use BorrowedConstant::*;
|
||||
match self {
|
||||
ConstantData::Integer { value } => Integer { value },
|
||||
ConstantData::Float { value } => Float { value: *value },
|
||||
ConstantData::Complex { value } => Complex { value: *value },
|
||||
ConstantData::Boolean { value } => Boolean { value: *value },
|
||||
ConstantData::Str { value } => Str { value },
|
||||
ConstantData::Bytes { value } => Bytes { value },
|
||||
ConstantData::Code { code } => Code { code },
|
||||
ConstantData::Tuple { elements } => Tuple { elements },
|
||||
ConstantData::None => None,
|
||||
ConstantData::Ellipsis => Ellipsis,
|
||||
Self::Integer { value } => Integer { value },
|
||||
Self::Float { value } => Float { value: *value },
|
||||
Self::Complex { value } => Complex { value: *value },
|
||||
Self::Boolean { value } => Boolean { value: *value },
|
||||
Self::Str { value } => Str { value },
|
||||
Self::Bytes { value } => Bytes { value },
|
||||
Self::Code { code } => Code { code },
|
||||
Self::Tuple { elements } => Tuple { elements },
|
||||
Self::None => None,
|
||||
Self::Ellipsis => Ellipsis,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -136,15 +136,15 @@ bitflags! {
|
||||
}
|
||||
|
||||
impl CodeFlags {
|
||||
pub const NAME_MAPPING: &'static [(&'static str, CodeFlags)] = &[
|
||||
("GENERATOR", CodeFlags::IS_GENERATOR),
|
||||
("COROUTINE", CodeFlags::IS_COROUTINE),
|
||||
pub const NAME_MAPPING: &'static [(&'static str, Self)] = &[
|
||||
("GENERATOR", Self::IS_GENERATOR),
|
||||
("COROUTINE", Self::IS_COROUTINE),
|
||||
(
|
||||
"ASYNC_GENERATOR",
|
||||
Self::from_bits_truncate(Self::IS_GENERATOR.bits() | Self::IS_COROUTINE.bits()),
|
||||
),
|
||||
("VARARGS", CodeFlags::HAS_VARARGS),
|
||||
("VARKEYWORDS", CodeFlags::HAS_VARKEYWORDS),
|
||||
("VARARGS", Self::HAS_VARARGS),
|
||||
("VARKEYWORDS", Self::HAS_VARKEYWORDS),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -154,7 +154,7 @@ impl CodeFlags {
|
||||
pub struct OpArgByte(pub u8);
|
||||
impl OpArgByte {
|
||||
pub const fn null() -> Self {
|
||||
OpArgByte(0)
|
||||
Self(0)
|
||||
}
|
||||
}
|
||||
impl fmt::Debug for OpArgByte {
|
||||
@@ -169,7 +169,7 @@ impl fmt::Debug for OpArgByte {
|
||||
pub struct OpArg(pub u32);
|
||||
impl OpArg {
|
||||
pub const fn null() -> Self {
|
||||
OpArg(0)
|
||||
Self(0)
|
||||
}
|
||||
|
||||
/// Returns how many CodeUnits a instruction with this op_arg will be encoded as
|
||||
@@ -281,7 +281,7 @@ pub struct Arg<T: OpArgType>(PhantomData<T>);
|
||||
impl<T: OpArgType> Arg<T> {
|
||||
#[inline]
|
||||
pub fn marker() -> Self {
|
||||
Arg(PhantomData)
|
||||
Self(PhantomData)
|
||||
}
|
||||
#[inline]
|
||||
pub fn new(arg: T) -> (Self, OpArg) {
|
||||
@@ -333,7 +333,7 @@ pub struct Label(pub u32);
|
||||
impl OpArgType for Label {
|
||||
#[inline(always)]
|
||||
fn from_op_arg(x: u32) -> Option<Self> {
|
||||
Some(Label(x))
|
||||
Some(Self(x))
|
||||
}
|
||||
#[inline(always)]
|
||||
fn to_op_arg(self) -> u32 {
|
||||
@@ -351,10 +351,10 @@ impl OpArgType for ConversionFlag {
|
||||
#[inline]
|
||||
fn from_op_arg(x: u32) -> Option<Self> {
|
||||
match x as u8 {
|
||||
b's' => Some(ConversionFlag::Str),
|
||||
b'a' => Some(ConversionFlag::Ascii),
|
||||
b'r' => Some(ConversionFlag::Repr),
|
||||
std::u8::MAX => Some(ConversionFlag::None),
|
||||
b's' => Some(Self::Str),
|
||||
b'a' => Some(Self::Ascii),
|
||||
b'r' => Some(Self::Repr),
|
||||
std::u8::MAX => Some(Self::None),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -631,9 +631,9 @@ const _: () = assert!(mem::size_of::<Instruction>() == 1);
|
||||
|
||||
impl From<Instruction> for u8 {
|
||||
#[inline]
|
||||
fn from(ins: Instruction) -> u8 {
|
||||
fn from(ins: Instruction) -> Self {
|
||||
// SAFETY: there's no padding bits
|
||||
unsafe { std::mem::transmute::<Instruction, u8>(ins) }
|
||||
unsafe { std::mem::transmute::<Instruction, Self>(ins) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -643,7 +643,7 @@ impl TryFrom<u8> for Instruction {
|
||||
#[inline]
|
||||
fn try_from(value: u8) -> Result<Self, crate::marshal::MarshalError> {
|
||||
if value <= u8::from(LAST_INSTRUCTION) {
|
||||
Ok(unsafe { std::mem::transmute::<u8, Instruction>(value) })
|
||||
Ok(unsafe { std::mem::transmute::<u8, Self>(value) })
|
||||
} else {
|
||||
Err(crate::marshal::MarshalError::InvalidBytecode)
|
||||
}
|
||||
@@ -680,7 +680,7 @@ bitflags! {
|
||||
impl OpArgType for MakeFunctionFlags {
|
||||
#[inline(always)]
|
||||
fn from_op_arg(x: u32) -> Option<Self> {
|
||||
MakeFunctionFlags::from_bits(x as u8)
|
||||
Self::from_bits(x as u8)
|
||||
}
|
||||
#[inline(always)]
|
||||
fn to_op_arg(self) -> u32 {
|
||||
|
||||
@@ -32,7 +32,7 @@ impl FrozenCodeObject<Vec<u8>> {
|
||||
let mut data = Vec::new();
|
||||
marshal::serialize_code(&mut data, code);
|
||||
let bytes = lz4_flex::compress_prepend_size(&data);
|
||||
FrozenCodeObject { bytes }
|
||||
Self { bytes }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,8 +42,8 @@ pub struct FrozenLib<B: ?Sized = [u8]> {
|
||||
}
|
||||
|
||||
impl<B: AsRef<[u8]> + ?Sized> FrozenLib<B> {
|
||||
pub const fn from_ref(b: &B) -> &FrozenLib<B> {
|
||||
unsafe { &*(b as *const B as *const FrozenLib<B>) }
|
||||
pub const fn from_ref(b: &B) -> &Self {
|
||||
unsafe { &*(b as *const B as *const Self) }
|
||||
}
|
||||
|
||||
/// Decode a library to a iterable of frozen modules
|
||||
@@ -100,7 +100,7 @@ fn read_entry<'a>(
|
||||
|
||||
impl FrozenLib<Vec<u8>> {
|
||||
/// Encode the given iterator of frozen modules into a compressed vector of bytes
|
||||
pub fn encode<'a, I, B: AsRef<[u8]>>(lib: I) -> FrozenLib<Vec<u8>>
|
||||
pub fn encode<'a, I, B: AsRef<[u8]>>(lib: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = (&'a str, FrozenModule<B>), IntoIter: ExactSizeIterator + Clone>,
|
||||
{
|
||||
|
||||
@@ -13,9 +13,9 @@ impl std::str::FromStr for Mode {
|
||||
// To support `builtins.compile()` `mode` argument
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"exec" => Ok(Mode::Exec),
|
||||
"eval" => Ok(Mode::Eval),
|
||||
"single" => Ok(Mode::Single),
|
||||
"exec" => Ok(Self::Exec),
|
||||
"eval" => Ok(Self::Eval),
|
||||
"single" => Ok(Self::Single),
|
||||
_ => Err(ModeParseError),
|
||||
}
|
||||
}
|
||||
|
||||
+6
-6
@@ -57,21 +57,21 @@ impl CompileError {
|
||||
|
||||
pub fn location(&self) -> Option<SourceLocation> {
|
||||
match self {
|
||||
CompileError::Codegen(codegen_error) => codegen_error.location.clone(),
|
||||
CompileError::Parse(parse_error) => Some(parse_error.location.clone()),
|
||||
Self::Codegen(codegen_error) => codegen_error.location.clone(),
|
||||
Self::Parse(parse_error) => Some(parse_error.location.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn python_location(&self) -> (usize, usize) {
|
||||
match self {
|
||||
CompileError::Codegen(codegen_error) => {
|
||||
Self::Codegen(codegen_error) => {
|
||||
if let Some(location) = &codegen_error.location {
|
||||
(location.row.get(), location.column.get())
|
||||
} else {
|
||||
(0, 0)
|
||||
}
|
||||
}
|
||||
CompileError::Parse(parse_error) => (
|
||||
Self::Parse(parse_error) => (
|
||||
parse_error.location.row.get(),
|
||||
parse_error.location.column.get(),
|
||||
),
|
||||
@@ -80,8 +80,8 @@ impl CompileError {
|
||||
|
||||
pub fn source_path(&self) -> &str {
|
||||
match self {
|
||||
CompileError::Codegen(codegen_error) => &codegen_error.source_path,
|
||||
CompileError::Parse(parse_error) => &parse_error.source_path,
|
||||
Self::Codegen(codegen_error) => &codegen_error.source_path,
|
||||
Self::Parse(parse_error) => &parse_error.source_path,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -234,7 +234,7 @@ impl CompilationSource {
|
||||
}
|
||||
|
||||
impl PyCompileArgs {
|
||||
fn parse(input: TokenStream, allow_dir: bool) -> Result<PyCompileArgs, Diagnostic> {
|
||||
fn parse(input: TokenStream, allow_dir: bool) -> Result<Self, Diagnostic> {
|
||||
let mut module_name = None;
|
||||
let mut mode = None;
|
||||
let mut source: Option<CompilationSource> = None;
|
||||
@@ -307,7 +307,7 @@ impl PyCompileArgs {
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(PyCompileArgs {
|
||||
Ok(Self {
|
||||
source,
|
||||
mode: mode.unwrap_or(Mode::Exec),
|
||||
module_name: module_name.unwrap_or_else(|| "frozen".to_owned()),
|
||||
|
||||
@@ -75,8 +75,8 @@ enum Repr {
|
||||
}
|
||||
|
||||
impl Diagnostic {
|
||||
pub fn error<T: Into<String>>(text: T) -> Diagnostic {
|
||||
Diagnostic {
|
||||
pub fn error<T: Into<String>>(text: T) -> Self {
|
||||
Self {
|
||||
inner: Repr::Single {
|
||||
text: text.into(),
|
||||
span: None,
|
||||
@@ -84,8 +84,8 @@ impl Diagnostic {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn spans_error<T: Into<String>>(spans: (Span, Span), text: T) -> Diagnostic {
|
||||
Diagnostic {
|
||||
pub(crate) fn spans_error<T: Into<String>>(spans: (Span, Span), text: T) -> Self {
|
||||
Self {
|
||||
inner: Repr::Single {
|
||||
text: text.into(),
|
||||
span: Some(spans),
|
||||
@@ -93,11 +93,11 @@ impl Diagnostic {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_vec(diagnostics: Vec<Diagnostic>) -> Result<(), Diagnostic> {
|
||||
pub fn from_vec(diagnostics: Vec<Self>) -> Result<(), Self> {
|
||||
if diagnostics.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Diagnostic {
|
||||
Err(Self {
|
||||
inner: Repr::Multi { diagnostics },
|
||||
})
|
||||
}
|
||||
@@ -113,8 +113,8 @@ impl Diagnostic {
|
||||
}
|
||||
|
||||
impl From<Error> for Diagnostic {
|
||||
fn from(err: Error) -> Diagnostic {
|
||||
Diagnostic {
|
||||
fn from(err: Error) -> Self {
|
||||
Self {
|
||||
inner: Repr::SynError(err),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,12 +14,12 @@ enum ParameterKind {
|
||||
}
|
||||
|
||||
impl ParameterKind {
|
||||
fn from_ident(ident: &Ident) -> Option<ParameterKind> {
|
||||
fn from_ident(ident: &Ident) -> Option<Self> {
|
||||
match ident.to_string().as_str() {
|
||||
"positional" => Some(ParameterKind::PositionalOnly),
|
||||
"any" => Some(ParameterKind::PositionalOrKeyword),
|
||||
"named" => Some(ParameterKind::KeywordOnly),
|
||||
"flatten" => Some(ParameterKind::Flatten),
|
||||
"positional" => Some(Self::PositionalOnly),
|
||||
"any" => Some(Self::PositionalOrKeyword),
|
||||
"named" => Some(Self::KeywordOnly),
|
||||
"flatten" => Some(Self::Flatten),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,7 @@ struct ArgAttribute {
|
||||
type DefaultValue = Option<Expr>;
|
||||
|
||||
impl ArgAttribute {
|
||||
fn from_attribute(attr: &Attribute) -> Option<Result<ArgAttribute>> {
|
||||
fn from_attribute(attr: &Attribute) -> Option<Result<Self>> {
|
||||
if !attr.path().is_ident("pyarg") {
|
||||
return None;
|
||||
}
|
||||
@@ -52,7 +52,7 @@ impl ArgAttribute {
|
||||
either 'positional', 'any', 'named', or 'flatten'.",
|
||||
)
|
||||
})?;
|
||||
arg_attr = Some(ArgAttribute {
|
||||
arg_attr = Some(Self {
|
||||
name: None,
|
||||
kind,
|
||||
default: None,
|
||||
|
||||
+19
-19
@@ -632,7 +632,7 @@ mod array {
|
||||
|
||||
impl From<ArrayContentType> for PyArray {
|
||||
fn from(array: ArrayContentType) -> Self {
|
||||
PyArray {
|
||||
Self {
|
||||
array: PyRwLock::new(array),
|
||||
exports: AtomicUsize::new(0),
|
||||
}
|
||||
@@ -659,7 +659,7 @@ mod array {
|
||||
vm.new_type_error("array() argument 1 must be a unicode character, not str")
|
||||
})?;
|
||||
|
||||
if cls.is(PyArray::class(&vm.ctx)) && !kwargs.is_empty() {
|
||||
if cls.is(Self::class(&vm.ctx)) && !kwargs.is_empty() {
|
||||
return Err(vm.new_type_error("array.array() takes no keyword arguments"));
|
||||
}
|
||||
|
||||
@@ -667,7 +667,7 @@ mod array {
|
||||
ArrayContentType::from_char(spec).map_err(|err| vm.new_value_error(err))?;
|
||||
|
||||
if let OptionalArg::Present(init) = init {
|
||||
if let Some(init) = init.payload::<PyArray>() {
|
||||
if let Some(init) = init.payload::<Self>() {
|
||||
match (spec, init.read().typecode()) {
|
||||
(spec, ch) if spec == ch => array.frombytes(&init.get_bytes()),
|
||||
(spec, 'u') => {
|
||||
@@ -765,7 +765,7 @@ mod array {
|
||||
let mut w = zelf.try_resizable(vm)?;
|
||||
if zelf.is(&obj) {
|
||||
w.imul(2, vm)
|
||||
} else if let Some(array) = obj.payload::<PyArray>() {
|
||||
} else if let Some(array) = obj.payload::<Self>() {
|
||||
w.iadd(&array.read(), vm)
|
||||
} else {
|
||||
let iter = ArgIterable::try_from_object(vm, obj)?;
|
||||
@@ -977,12 +977,12 @@ mod array {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn __copy__(&self) -> PyArray {
|
||||
fn __copy__(&self) -> Self {
|
||||
self.array.read().clone().into()
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn __deepcopy__(&self, _memo: PyObjectRef) -> PyArray {
|
||||
fn __deepcopy__(&self, _memo: PyObjectRef) -> Self {
|
||||
self.__copy__()
|
||||
}
|
||||
|
||||
@@ -1013,7 +1013,7 @@ mod array {
|
||||
cloned = zelf.read().clone();
|
||||
&cloned
|
||||
} else {
|
||||
match value.payload::<PyArray>() {
|
||||
match value.payload::<Self>() {
|
||||
Some(array) => {
|
||||
guard = array.read();
|
||||
&*guard
|
||||
@@ -1059,10 +1059,10 @@ mod array {
|
||||
|
||||
#[pymethod]
|
||||
fn __add__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
|
||||
if let Some(other) = other.payload::<PyArray>() {
|
||||
if let Some(other) = other.payload::<Self>() {
|
||||
self.read()
|
||||
.add(&other.read(), vm)
|
||||
.map(|array| PyArray::from(array).into_ref(&vm.ctx))
|
||||
.map(|array| Self::from(array).into_ref(&vm.ctx))
|
||||
} else {
|
||||
Err(vm.new_type_error(format!(
|
||||
"can only append array (not \"{}\") to array",
|
||||
@@ -1079,7 +1079,7 @@ mod array {
|
||||
) -> PyResult<PyRef<Self>> {
|
||||
if zelf.is(&other) {
|
||||
zelf.try_resizable(vm)?.imul(2, vm)?;
|
||||
} else if let Some(other) = other.payload::<PyArray>() {
|
||||
} else if let Some(other) = other.payload::<Self>() {
|
||||
zelf.try_resizable(vm)?.iadd(&other.read(), vm)?;
|
||||
} else {
|
||||
return Err(vm.new_type_error(format!(
|
||||
@@ -1454,17 +1454,17 @@ mod array {
|
||||
}
|
||||
|
||||
impl From<MachineFormatCode> for u8 {
|
||||
fn from(code: MachineFormatCode) -> u8 {
|
||||
fn from(code: MachineFormatCode) -> Self {
|
||||
use MachineFormatCode::*;
|
||||
match code {
|
||||
Int8 { signed } => signed as u8,
|
||||
Int16 { signed, big_endian } => 2 + signed as u8 * 2 + big_endian as u8,
|
||||
Int32 { signed, big_endian } => 6 + signed as u8 * 2 + big_endian as u8,
|
||||
Int64 { signed, big_endian } => 10 + signed as u8 * 2 + big_endian as u8,
|
||||
Ieee754Float { big_endian } => 14 + big_endian as u8,
|
||||
Ieee754Double { big_endian } => 16 + big_endian as u8,
|
||||
Utf16 { big_endian } => 18 + big_endian as u8,
|
||||
Utf32 { big_endian } => 20 + big_endian as u8,
|
||||
Int8 { signed } => signed as Self,
|
||||
Int16 { signed, big_endian } => 2 + signed as Self * 2 + big_endian as Self,
|
||||
Int32 { signed, big_endian } => 6 + signed as Self * 2 + big_endian as Self,
|
||||
Int64 { signed, big_endian } => 10 + signed as Self * 2 + big_endian as Self,
|
||||
Ieee754Float { big_endian } => 14 + big_endian as Self,
|
||||
Ieee754Double { big_endian } => 16 + big_endian as Self,
|
||||
Utf16 { big_endian } => 18 + big_endian as Self,
|
||||
Utf32 { big_endian } => 20 + big_endian as Self,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -48,7 +48,7 @@ mod _bz2 {
|
||||
|
||||
impl DecompressStatus for Status {
|
||||
fn is_stream_end(&self) -> bool {
|
||||
*self == Status::StreamEnd
|
||||
*self == Self::StreamEnd
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -150,7 +150,7 @@ mod _contextvars {
|
||||
if let Some(ctx) = ctxs.last() {
|
||||
ctx.clone()
|
||||
} else {
|
||||
let ctx = PyContext::empty(vm);
|
||||
let ctx = Self::empty(vm);
|
||||
ctx.inner.idx.set(0);
|
||||
ctx.inner.entered.set(true);
|
||||
let ctx = ctx.into_ref(&vm.ctx);
|
||||
@@ -253,7 +253,7 @@ mod _contextvars {
|
||||
impl Constructor for PyContext {
|
||||
type Args = ();
|
||||
fn py_new(_cls: PyTypeRef, _args: Self::Args, vm: &VirtualMachine) -> PyResult {
|
||||
Ok(PyContext::empty(vm).into_pyobject(vm))
|
||||
Ok(Self::empty(vm).into_pyobject(vm))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -499,7 +499,7 @@ mod _contextvars {
|
||||
impl Constructor for ContextVar {
|
||||
type Args = ContextVarOptions;
|
||||
fn py_new(_cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult {
|
||||
let var = ContextVar {
|
||||
let var = Self {
|
||||
name: args.name.to_string(),
|
||||
default: args.default.into_option(),
|
||||
cached_id: 0.into(),
|
||||
|
||||
+14
-14
@@ -68,7 +68,7 @@ mod _csv {
|
||||
type Args = PyObjectRef;
|
||||
|
||||
fn py_new(cls: PyTypeRef, ctx: Self::Args, vm: &VirtualMachine) -> PyResult {
|
||||
PyDialect::try_from_object(vm, ctx)?
|
||||
Self::try_from_object(vm, ctx)?
|
||||
.into_ref_with_type(vm, cls)
|
||||
.map(Into::into)
|
||||
}
|
||||
@@ -425,10 +425,10 @@ mod _csv {
|
||||
impl From<QuoteStyle> for csv_core::QuoteStyle {
|
||||
fn from(val: QuoteStyle) -> Self {
|
||||
match val {
|
||||
QuoteStyle::Minimal => csv_core::QuoteStyle::Always,
|
||||
QuoteStyle::All => csv_core::QuoteStyle::Always,
|
||||
QuoteStyle::Nonnumeric => csv_core::QuoteStyle::NonNumeric,
|
||||
QuoteStyle::None => csv_core::QuoteStyle::Never,
|
||||
QuoteStyle::Minimal => Self::Always,
|
||||
QuoteStyle::All => Self::Always,
|
||||
QuoteStyle::Nonnumeric => Self::NonNumeric,
|
||||
QuoteStyle::None => Self::Never,
|
||||
QuoteStyle::Strings => todo!(),
|
||||
QuoteStyle::Notnull => todo!(),
|
||||
}
|
||||
@@ -444,14 +444,14 @@ mod _csv {
|
||||
}
|
||||
impl TryFrom<isize> for QuoteStyle {
|
||||
type Error = PyTypeError;
|
||||
fn try_from(num: isize) -> Result<QuoteStyle, PyTypeError> {
|
||||
fn try_from(num: isize) -> Result<Self, PyTypeError> {
|
||||
match num {
|
||||
0 => Ok(QuoteStyle::Minimal),
|
||||
1 => Ok(QuoteStyle::All),
|
||||
2 => Ok(QuoteStyle::Nonnumeric),
|
||||
3 => Ok(QuoteStyle::None),
|
||||
4 => Ok(QuoteStyle::Strings),
|
||||
5 => Ok(QuoteStyle::Notnull),
|
||||
0 => Ok(Self::Minimal),
|
||||
1 => Ok(Self::All),
|
||||
2 => Ok(Self::Nonnumeric),
|
||||
3 => Ok(Self::None),
|
||||
4 => Ok(Self::Strings),
|
||||
5 => Ok(Self::Notnull),
|
||||
_ => Err(PyTypeError {}),
|
||||
}
|
||||
}
|
||||
@@ -488,7 +488,7 @@ mod _csv {
|
||||
}
|
||||
impl Default for FormatOptions {
|
||||
fn default() -> Self {
|
||||
FormatOptions {
|
||||
Self {
|
||||
dialect: DialectItem::None,
|
||||
delimiter: None,
|
||||
quotechar: None,
|
||||
@@ -557,7 +557,7 @@ mod _csv {
|
||||
|
||||
impl FromArgs for FormatOptions {
|
||||
fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result<Self, ArgumentError> {
|
||||
let mut res = FormatOptions::default();
|
||||
let mut res = Self::default();
|
||||
if let Some(dialect) = args.kwargs.swap_remove("dialect") {
|
||||
res.dialect = prase_dialect_item_from_arg(vm, dialect)?;
|
||||
} else if let Some(dialect) = args.args.first() {
|
||||
|
||||
+13
-13
@@ -100,7 +100,7 @@ pub mod _hashlib {
|
||||
#[pyclass(with(Representable))]
|
||||
impl PyHasher {
|
||||
fn new(name: &str, d: HashWrapper) -> Self {
|
||||
PyHasher {
|
||||
Self {
|
||||
name: name.to_owned(),
|
||||
ctx: PyRwLock::new(d),
|
||||
}
|
||||
@@ -143,7 +143,7 @@ pub mod _hashlib {
|
||||
|
||||
#[pymethod]
|
||||
fn copy(&self) -> Self {
|
||||
PyHasher::new(&self.name, self.ctx.read().clone())
|
||||
Self::new(&self.name, self.ctx.read().clone())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,7 +173,7 @@ pub mod _hashlib {
|
||||
#[pyclass]
|
||||
impl PyHasherXof {
|
||||
fn new(name: &str, d: HashXofWrapper) -> Self {
|
||||
PyHasherXof {
|
||||
Self {
|
||||
name: name.to_owned(),
|
||||
ctx: PyRwLock::new(d),
|
||||
}
|
||||
@@ -216,7 +216,7 @@ pub mod _hashlib {
|
||||
|
||||
#[pymethod]
|
||||
fn copy(&self) -> Self {
|
||||
PyHasherXof::new(&self.name, self.ctx.read().clone())
|
||||
Self::new(&self.name, self.ctx.read().clone())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -367,7 +367,7 @@ pub mod _hashlib {
|
||||
where
|
||||
D: ThreadSafeDynDigest + BlockSizeUser + Default + 'static,
|
||||
{
|
||||
let mut h = HashWrapper {
|
||||
let mut h = Self {
|
||||
block_size: D::block_size(),
|
||||
inner: Box::<D>::default(),
|
||||
};
|
||||
@@ -403,7 +403,7 @@ pub mod _hashlib {
|
||||
|
||||
impl HashXofWrapper {
|
||||
pub fn new_shake_128(data: OptionalArg<ArgBytesLike>) -> Self {
|
||||
let mut h = HashXofWrapper::Shake128(Shake128::default());
|
||||
let mut h = Self::Shake128(Shake128::default());
|
||||
if let OptionalArg::Present(d) = data {
|
||||
d.with_ref(|bytes| h.update(bytes));
|
||||
}
|
||||
@@ -411,7 +411,7 @@ pub mod _hashlib {
|
||||
}
|
||||
|
||||
pub fn new_shake_256(data: OptionalArg<ArgBytesLike>) -> Self {
|
||||
let mut h = HashXofWrapper::Shake256(Shake256::default());
|
||||
let mut h = Self::Shake256(Shake256::default());
|
||||
if let OptionalArg::Present(d) = data {
|
||||
d.with_ref(|bytes| h.update(bytes));
|
||||
}
|
||||
@@ -420,22 +420,22 @@ pub mod _hashlib {
|
||||
|
||||
fn update(&mut self, data: &[u8]) {
|
||||
match self {
|
||||
HashXofWrapper::Shake128(h) => h.update(data),
|
||||
HashXofWrapper::Shake256(h) => h.update(data),
|
||||
Self::Shake128(h) => h.update(data),
|
||||
Self::Shake256(h) => h.update(data),
|
||||
}
|
||||
}
|
||||
|
||||
fn block_size(&self) -> usize {
|
||||
match self {
|
||||
HashXofWrapper::Shake128(_) => Shake128::block_size(),
|
||||
HashXofWrapper::Shake256(_) => Shake256::block_size(),
|
||||
Self::Shake128(_) => Shake128::block_size(),
|
||||
Self::Shake256(_) => Shake256::block_size(),
|
||||
}
|
||||
}
|
||||
|
||||
fn finalize_xof(&self, length: usize) -> Vec<u8> {
|
||||
match self {
|
||||
HashXofWrapper::Shake128(h) => h.clone().finalize_boxed(length).into_vec(),
|
||||
HashXofWrapper::Shake256(h) => h.clone().finalize_boxed(length).into_vec(),
|
||||
Self::Shake128(h) => h.clone().finalize_boxed(length).into_vec(),
|
||||
Self::Shake256(h) => h.clone().finalize_boxed(length).into_vec(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ struct CStrPathLike {
|
||||
impl TryFromObject for CStrPathLike {
|
||||
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
|
||||
let s = OsPath::try_from_object(vm, obj)?.into_cstring(vm)?;
|
||||
Ok(CStrPathLike { s })
|
||||
Ok(Self { s })
|
||||
}
|
||||
}
|
||||
impl AsRef<CStr> for CStrPathLike {
|
||||
@@ -176,9 +176,9 @@ enum ExecErrorContext {
|
||||
impl ExecErrorContext {
|
||||
fn as_msg(&self) -> &'static str {
|
||||
match self {
|
||||
ExecErrorContext::NoExec => "noexec",
|
||||
ExecErrorContext::ChDir => "noexec:chdir",
|
||||
ExecErrorContext::Exec => "",
|
||||
Self::NoExec => "noexec",
|
||||
Self::ChDir => "noexec:chdir",
|
||||
Self::Exec => "",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ mod _pyexpat {
|
||||
#[pyclass]
|
||||
impl PyExpatLikeXmlParser {
|
||||
fn new(vm: &VirtualMachine) -> PyResult<PyExpatLikeXmlParserRef> {
|
||||
Ok(PyExpatLikeXmlParser {
|
||||
Ok(Self {
|
||||
start_element: MutableObject::new(vm.ctx.none()),
|
||||
end_element: MutableObject::new(vm.ctx.none()),
|
||||
character_data: MutableObject::new(vm.ctx.none()),
|
||||
|
||||
@@ -39,7 +39,7 @@ pub(crate) mod _struct {
|
||||
))),
|
||||
})
|
||||
.ok_or_else(|| vm.new_unicode_decode_error("Struct format must be a ascii string"))?;
|
||||
Ok(IntoStructFormatBytes(fmt))
|
||||
Ok(Self(fmt))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,7 +165,7 @@ pub(crate) mod _struct {
|
||||
vm: &VirtualMachine,
|
||||
format_spec: FormatSpec,
|
||||
buffer: ArgBytesLike,
|
||||
) -> PyResult<UnpackIterator> {
|
||||
) -> PyResult<Self> {
|
||||
if format_spec.size == 0 {
|
||||
Err(new_struct_error(
|
||||
vm,
|
||||
@@ -180,7 +180,7 @@ pub(crate) mod _struct {
|
||||
),
|
||||
))
|
||||
} else {
|
||||
Ok(UnpackIterator {
|
||||
Ok(Self {
|
||||
format_spec,
|
||||
buffer,
|
||||
offset: AtomicCell::new(0),
|
||||
@@ -244,7 +244,7 @@ pub(crate) mod _struct {
|
||||
fn py_new(cls: PyTypeRef, fmt: Self::Args, vm: &VirtualMachine) -> PyResult {
|
||||
let spec = fmt.format_spec(vm)?;
|
||||
let format = fmt.0;
|
||||
PyStruct { spec, format }
|
||||
Self { spec, format }
|
||||
.into_ref_with_type(vm, cls)
|
||||
.map(Into::into)
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ mod resource {
|
||||
impl From<libc::rusage> for Rusage {
|
||||
fn from(rusage: libc::rusage) -> Self {
|
||||
let tv = |tv: libc::timeval| tv.tv_sec as f64 + (tv.tv_usec as f64 / 1_000_000.0);
|
||||
Rusage {
|
||||
Self {
|
||||
ru_utime: tv(rusage.ru_utime),
|
||||
ru_stime: tv(rusage.ru_utime),
|
||||
ru_maxrss: rusage.ru_maxrss,
|
||||
|
||||
@@ -146,7 +146,7 @@ impl TryFromObject for Selectable {
|
||||
)?;
|
||||
meth.call((), vm)?.try_into_value(vm)
|
||||
})?;
|
||||
Ok(Selectable { obj, fno })
|
||||
Ok(Self { obj, fno })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,12 +155,12 @@ impl TryFromObject for Selectable {
|
||||
pub struct FdSet(mem::MaybeUninit<platform::fd_set>);
|
||||
|
||||
impl FdSet {
|
||||
pub fn new() -> FdSet {
|
||||
pub fn new() -> Self {
|
||||
// it's just ints, and all the code that's actually
|
||||
// interacting with it is in C, so it's safe to zero
|
||||
let mut fdset = std::mem::MaybeUninit::zeroed();
|
||||
unsafe { platform::FD_ZERO(fdset.as_mut_ptr()) };
|
||||
FdSet(fdset)
|
||||
Self(fdset)
|
||||
}
|
||||
|
||||
pub fn insert(&mut self, fd: RawFd) {
|
||||
@@ -440,7 +440,7 @@ mod decl {
|
||||
let mask = i16::try_from(val)
|
||||
.map_err(|_| vm.new_overflow_error("event mask value out of range"))?;
|
||||
|
||||
Ok(EventMask(mask))
|
||||
Ok(Self(mask))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -602,7 +602,7 @@ mod decl {
|
||||
fn new() -> std::io::Result<Self> {
|
||||
let epoll_fd = epoll::create(epoll::CreateFlags::CLOEXEC)?;
|
||||
let epoll_fd = Some(epoll_fd).into();
|
||||
Ok(PyEpoll { epoll_fd })
|
||||
Ok(Self { epoll_fd })
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
|
||||
@@ -799,7 +799,7 @@ mod _socket {
|
||||
|
||||
impl Default for PySocket {
|
||||
fn default() -> Self {
|
||||
PySocket {
|
||||
Self {
|
||||
kind: AtomicCell::default(),
|
||||
family: AtomicCell::default(),
|
||||
proto: AtomicCell::default(),
|
||||
@@ -1663,14 +1663,14 @@ mod _socket {
|
||||
let port = port
|
||||
.to_u16()
|
||||
.ok_or_else(|| vm.new_overflow_error("port must be 0-65535."))?;
|
||||
Ok(Address { host, port })
|
||||
Ok(Self { host, port })
|
||||
}
|
||||
|
||||
fn from_tuple_ipv6(
|
||||
tuple: &[PyObjectRef],
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<(Self, u32, u32)> {
|
||||
let addr = Address::from_tuple(tuple, vm)?;
|
||||
let addr = Self::from_tuple(tuple, vm)?;
|
||||
let flowinfo = tuple
|
||||
.get(2)
|
||||
.map(|obj| u32::try_from_borrowed_object(vm, obj))
|
||||
|
||||
@@ -49,8 +49,8 @@ mod syslog {
|
||||
impl GlobalIdent {
|
||||
fn as_ptr(&self) -> *const c_char {
|
||||
match self {
|
||||
GlobalIdent::Explicit(cstr) => cstr.as_ptr(),
|
||||
GlobalIdent::Implicit => std::ptr::null(),
|
||||
Self::Explicit(cstr) => cstr.as_ptr(),
|
||||
Self::Implicit => std::ptr::null(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+10
-10
@@ -47,10 +47,10 @@ impl<'a> TryFromBorrowedObject<'a> for NormalizeForm {
|
||||
obj.try_value_with(
|
||||
|form: &PyStr| {
|
||||
Ok(match form.as_str() {
|
||||
"NFC" => NormalizeForm::Nfc,
|
||||
"NFKC" => NormalizeForm::Nfkc,
|
||||
"NFD" => NormalizeForm::Nfd,
|
||||
"NFKD" => NormalizeForm::Nfkd,
|
||||
"NFC" => Self::Nfc,
|
||||
"NFKC" => Self::Nfkc,
|
||||
"NFD" => Self::Nfd,
|
||||
"NFKD" => Self::Nfkd,
|
||||
_ => return Err(vm.new_value_error("invalid normalization form")),
|
||||
})
|
||||
},
|
||||
@@ -221,12 +221,12 @@ mod unicodedata {
|
||||
impl EastAsianWidthAbbrName for EastAsianWidth {
|
||||
fn abbr_name(&self) -> &'static str {
|
||||
match self {
|
||||
EastAsianWidth::Narrow => "Na",
|
||||
EastAsianWidth::Wide => "W",
|
||||
EastAsianWidth::Neutral => "N",
|
||||
EastAsianWidth::Ambiguous => "A",
|
||||
EastAsianWidth::FullWidth => "F",
|
||||
EastAsianWidth::HalfWidth => "H",
|
||||
Self::Narrow => "Na",
|
||||
Self::Wide => "W",
|
||||
Self::Neutral => "N",
|
||||
Self::Ambiguous => "A",
|
||||
Self::FullWidth => "F",
|
||||
Self::HalfWidth => "H",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+9
-9
@@ -118,7 +118,7 @@ mod zlib {
|
||||
}
|
||||
|
||||
impl InitOptions {
|
||||
fn new(wbits: i8, vm: &VirtualMachine) -> PyResult<InitOptions> {
|
||||
fn new(wbits: i8, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
let header = wbits > 0;
|
||||
let wbits = wbits.unsigned_abs();
|
||||
match wbits {
|
||||
@@ -127,8 +127,8 @@ mod zlib {
|
||||
// > the zlib header of the compressed stream.
|
||||
// but flate2 doesn't expose it
|
||||
// 0 => ...
|
||||
9..=15 => Ok(InitOptions::Standard { header, wbits }),
|
||||
25..=31 => Ok(InitOptions::Gzip { wbits: wbits - 16 }),
|
||||
9..=15 => Ok(Self::Standard { header, wbits }),
|
||||
25..=31 => Ok(Self::Gzip { wbits: wbits - 16 }),
|
||||
_ => Err(vm.new_value_error("Invalid initialization option")),
|
||||
}
|
||||
}
|
||||
@@ -422,8 +422,8 @@ mod zlib {
|
||||
}
|
||||
|
||||
impl CompressStatusKind for Status {
|
||||
const OK: Self = Status::Ok;
|
||||
const EOF: Self = Status::StreamEnd;
|
||||
const OK: Self = Self::Ok;
|
||||
const EOF: Self = Self::StreamEnd;
|
||||
|
||||
fn to_usize(self) -> usize {
|
||||
self as usize
|
||||
@@ -431,8 +431,8 @@ mod zlib {
|
||||
}
|
||||
|
||||
impl CompressFlushKind for FlushCompress {
|
||||
const NONE: Self = FlushCompress::None;
|
||||
const FINISH: Self = FlushCompress::Finish;
|
||||
const NONE: Self = Self::None;
|
||||
const FINISH: Self = Self::Finish;
|
||||
|
||||
fn to_usize(self) -> usize {
|
||||
self as usize
|
||||
@@ -514,12 +514,12 @@ mod zlib {
|
||||
|
||||
impl DecompressStatus for Status {
|
||||
fn is_stream_end(&self) -> bool {
|
||||
*self == Status::StreamEnd
|
||||
*self == Self::StreamEnd
|
||||
}
|
||||
}
|
||||
|
||||
impl DecompressFlushKind for FlushDecompress {
|
||||
const SYNC: Self = FlushDecompress::Sync;
|
||||
const SYNC: Self = Self::Sync;
|
||||
}
|
||||
|
||||
impl Decompressor for Decompress {
|
||||
|
||||
+11
-11
@@ -27,16 +27,16 @@ pub(crate) enum Endianness {
|
||||
impl Endianness {
|
||||
/// Parse endianness
|
||||
/// See also: https://docs.python.org/3/library/struct.html?highlight=struct#byte-order-size-and-alignment
|
||||
fn parse<I>(chars: &mut Peekable<I>) -> Endianness
|
||||
fn parse<I>(chars: &mut Peekable<I>) -> Self
|
||||
where
|
||||
I: Sized + Iterator<Item = u8>,
|
||||
{
|
||||
let e = match chars.peek() {
|
||||
Some(b'@') => Endianness::Native,
|
||||
Some(b'=') => Endianness::Host,
|
||||
Some(b'<') => Endianness::Little,
|
||||
Some(b'>') | Some(b'!') => Endianness::Big,
|
||||
_ => return Endianness::Native,
|
||||
Some(b'@') => Self::Native,
|
||||
Some(b'=') => Self::Host,
|
||||
Some(b'<') => Self::Little,
|
||||
Some(b'>') | Some(b'!') => Self::Big,
|
||||
_ => return Self::Native,
|
||||
};
|
||||
chars.next().unwrap();
|
||||
e
|
||||
@@ -267,7 +267,7 @@ impl FormatCode {
|
||||
.and_then(|extra| offset.checked_add(extra))
|
||||
.ok_or_else(|| OVERFLOW_MSG.to_owned())?;
|
||||
|
||||
let code = FormatCode {
|
||||
let code = Self {
|
||||
repeat: repeat as usize,
|
||||
code,
|
||||
info,
|
||||
@@ -321,7 +321,7 @@ pub struct FormatSpec {
|
||||
}
|
||||
|
||||
impl FormatSpec {
|
||||
pub fn parse(fmt: &[u8], vm: &VirtualMachine) -> PyResult<FormatSpec> {
|
||||
pub fn parse(fmt: &[u8], vm: &VirtualMachine) -> PyResult<Self> {
|
||||
let mut chars = fmt.iter().copied().peekable();
|
||||
|
||||
// First determine "@", "<", ">","!" or "="
|
||||
@@ -331,7 +331,7 @@ impl FormatSpec {
|
||||
let (codes, size, arg_count) =
|
||||
FormatCode::parse(&mut chars, endianness).map_err(|err| new_struct_error(vm, err))?;
|
||||
|
||||
Ok(FormatSpec {
|
||||
Ok(Self {
|
||||
endianness,
|
||||
codes,
|
||||
size,
|
||||
@@ -544,7 +544,7 @@ impl Packable for f16 {
|
||||
fn pack<E: ByteOrder>(vm: &VirtualMachine, arg: PyObjectRef, data: &mut [u8]) -> PyResult<()> {
|
||||
let f_64 = *ArgIntoFloat::try_from_object(vm, arg)?;
|
||||
// "from_f64 should be preferred in any non-`const` context" except it gives the wrong result :/
|
||||
let f_16 = f16::from_f64_const(f_64);
|
||||
let f_16 = Self::from_f64_const(f_64);
|
||||
if f_16.is_infinite() != f_64.is_infinite() {
|
||||
return Err(vm.new_overflow_error("float too large to pack with e format"));
|
||||
}
|
||||
@@ -554,7 +554,7 @@ impl Packable for f16 {
|
||||
|
||||
fn unpack<E: ByteOrder>(vm: &VirtualMachine, rdr: &[u8]) -> PyObjectRef {
|
||||
let i = PackInt::unpack_int::<E>(rdr);
|
||||
f16::from_bits(i).to_f64().to_pyobject(vm)
|
||||
Self::from_bits(i).to_f64().to_pyobject(vm)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ impl PyAsyncGen {
|
||||
}
|
||||
|
||||
pub fn new(frame: FrameRef, name: PyStrRef) -> Self {
|
||||
PyAsyncGen {
|
||||
Self {
|
||||
inner: Coro::new(frame, name),
|
||||
running_async: AtomicCell::new(false),
|
||||
}
|
||||
@@ -76,7 +76,7 @@ impl PyAsyncGen {
|
||||
#[pyclass]
|
||||
impl PyRef<PyAsyncGen> {
|
||||
#[pymethod]
|
||||
fn __aiter__(self, _vm: &VirtualMachine) -> PyRef<PyAsyncGen> {
|
||||
fn __aiter__(self, _vm: &VirtualMachine) -> Self {
|
||||
self
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ impl ToPyObject for bool {
|
||||
}
|
||||
|
||||
impl<'a> TryFromBorrowedObject<'a> for bool {
|
||||
fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult<bool> {
|
||||
fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult<Self> {
|
||||
if obj.fast_isinstance(vm.ctx.types.int_type) {
|
||||
Ok(get_value(obj))
|
||||
} else {
|
||||
|
||||
@@ -264,7 +264,7 @@ impl TryFromObject for NativeFunctionOrMethod {
|
||||
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
|
||||
let class = vm.ctx.types.builtin_function_or_method_type;
|
||||
if obj.fast_isinstance(class) {
|
||||
Ok(NativeFunctionOrMethod(unsafe { obj.downcast_unchecked() }))
|
||||
Ok(Self(unsafe { obj.downcast_unchecked() }))
|
||||
} else {
|
||||
Err(vm.new_downcast_type_error(class, &obj))
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@ impl PyByteArray {
|
||||
}
|
||||
|
||||
fn from_inner(inner: PyBytesInner) -> Self {
|
||||
PyByteArray {
|
||||
Self {
|
||||
inner: PyRwLock::new(inner),
|
||||
exports: AtomicUsize::new(0),
|
||||
}
|
||||
@@ -335,29 +335,17 @@ impl PyByteArray {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn center(
|
||||
&self,
|
||||
options: ByteInnerPaddingOptions,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<PyByteArray> {
|
||||
fn center(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
Ok(self.inner().center(options, vm)?.into())
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn ljust(
|
||||
&self,
|
||||
options: ByteInnerPaddingOptions,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<PyByteArray> {
|
||||
fn ljust(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
Ok(self.inner().ljust(options, vm)?.into())
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn rjust(
|
||||
&self,
|
||||
options: ByteInnerPaddingOptions,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<PyByteArray> {
|
||||
fn rjust(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
Ok(self.inner().rjust(options, vm)?.into())
|
||||
}
|
||||
|
||||
@@ -367,7 +355,7 @@ impl PyByteArray {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn join(&self, iter: ArgIterable<PyBytesInner>, vm: &VirtualMachine) -> PyResult<PyByteArray> {
|
||||
fn join(&self, iter: ArgIterable<PyBytesInner>, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
Ok(self.inner().join(iter, vm)?.into())
|
||||
}
|
||||
|
||||
@@ -434,11 +422,7 @@ impl PyByteArray {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn translate(
|
||||
&self,
|
||||
options: ByteInnerTranslateOptions,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<PyByteArray> {
|
||||
fn translate(&self, options: ByteInnerTranslateOptions, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
Ok(self.inner().translate(options, vm)?.into())
|
||||
}
|
||||
|
||||
@@ -526,7 +510,7 @@ impl PyByteArray {
|
||||
new: PyBytesInner,
|
||||
count: OptionalArg<isize>,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<PyByteArray> {
|
||||
) -> PyResult<Self> {
|
||||
Ok(self.inner().replace(old, new, count, vm)?.into())
|
||||
}
|
||||
|
||||
@@ -553,7 +537,7 @@ impl PyByteArray {
|
||||
}
|
||||
|
||||
#[pymethod(name = "__mod__")]
|
||||
fn mod_(&self, values: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyByteArray> {
|
||||
fn mod_(&self, values: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
let formatted = self.inner().cformat(values, vm)?;
|
||||
Ok(formatted.into())
|
||||
}
|
||||
@@ -663,11 +647,7 @@ impl Py<PyByteArray> {
|
||||
#[pyclass]
|
||||
impl PyRef<PyByteArray> {
|
||||
#[pymethod]
|
||||
fn lstrip(
|
||||
self,
|
||||
chars: OptionalOption<PyBytesInner>,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyRef<PyByteArray> {
|
||||
fn lstrip(self, chars: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self {
|
||||
let inner = self.inner();
|
||||
let stripped = inner.lstrip(chars);
|
||||
let elements = &inner.elements;
|
||||
@@ -680,11 +660,7 @@ impl PyRef<PyByteArray> {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn rstrip(
|
||||
self,
|
||||
chars: OptionalOption<PyBytesInner>,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyRef<PyByteArray> {
|
||||
fn rstrip(self, chars: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self {
|
||||
let inner = self.inner();
|
||||
let stripped = inner.rstrip(chars);
|
||||
let elements = &inner.elements;
|
||||
|
||||
+11
-15
@@ -116,7 +116,7 @@ impl PyBytes {
|
||||
}
|
||||
|
||||
impl PyRef<PyBytes> {
|
||||
fn repeat(self, count: isize, vm: &VirtualMachine) -> PyResult<PyRef<PyBytes>> {
|
||||
fn repeat(self, count: isize, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
if count == 1 && self.class().is(vm.ctx.types.bytes_type) {
|
||||
// Special case: when some `bytes` is multiplied by `1`,
|
||||
// nothing really happens, we need to return an object itself
|
||||
@@ -270,17 +270,17 @@ impl PyBytes {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn center(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult<PyBytes> {
|
||||
fn center(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
Ok(self.inner.center(options, vm)?.into())
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn ljust(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult<PyBytes> {
|
||||
fn ljust(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
Ok(self.inner.ljust(options, vm)?.into())
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn rjust(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult<PyBytes> {
|
||||
fn rjust(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
Ok(self.inner.rjust(options, vm)?.into())
|
||||
}
|
||||
|
||||
@@ -290,7 +290,7 @@ impl PyBytes {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn join(&self, iter: ArgIterable<PyBytesInner>, vm: &VirtualMachine) -> PyResult<PyBytes> {
|
||||
fn join(&self, iter: ArgIterable<PyBytesInner>, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
Ok(self.inner.join(iter, vm)?.into())
|
||||
}
|
||||
|
||||
@@ -355,11 +355,7 @@ impl PyBytes {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn translate(
|
||||
&self,
|
||||
options: ByteInnerTranslateOptions,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<PyBytes> {
|
||||
fn translate(&self, options: ByteInnerTranslateOptions, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
Ok(self.inner.translate(options, vm)?.into())
|
||||
}
|
||||
|
||||
@@ -451,7 +447,7 @@ impl PyBytes {
|
||||
new: PyBytesInner,
|
||||
count: OptionalArg<isize>,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<PyBytes> {
|
||||
) -> PyResult<Self> {
|
||||
Ok(self.inner.replace(old, new, count, vm)?.into())
|
||||
}
|
||||
|
||||
@@ -467,7 +463,7 @@ impl PyBytes {
|
||||
}
|
||||
|
||||
#[pymethod(name = "__mod__")]
|
||||
fn mod_(&self, values: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyBytes> {
|
||||
fn mod_(&self, values: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
let formatted = self.inner.cformat(values, vm)?;
|
||||
Ok(formatted.into())
|
||||
}
|
||||
@@ -515,7 +511,7 @@ impl Py<PyBytes> {
|
||||
#[pyclass]
|
||||
impl PyRef<PyBytes> {
|
||||
#[pymethod]
|
||||
fn __bytes__(self, vm: &VirtualMachine) -> PyRef<PyBytes> {
|
||||
fn __bytes__(self, vm: &VirtualMachine) -> Self {
|
||||
if self.is(vm.ctx.types.bytes_type) {
|
||||
self
|
||||
} else {
|
||||
@@ -524,7 +520,7 @@ impl PyRef<PyBytes> {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn lstrip(self, chars: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> PyRef<PyBytes> {
|
||||
fn lstrip(self, chars: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self {
|
||||
let stripped = self.inner.lstrip(chars);
|
||||
if stripped == self.as_bytes() {
|
||||
self
|
||||
@@ -534,7 +530,7 @@ impl PyRef<PyBytes> {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn rstrip(self, chars: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> PyRef<PyBytes> {
|
||||
fn rstrip(self, chars: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self {
|
||||
let stripped = self.inner.rstrip(chars);
|
||||
if stripped == self.as_bytes() {
|
||||
self
|
||||
|
||||
@@ -92,7 +92,7 @@ impl Constructor for PyClassMethod {
|
||||
}
|
||||
|
||||
// Create PyClassMethod instance with the pre-populated dict
|
||||
let classmethod = PyClassMethod {
|
||||
let classmethod = Self {
|
||||
callable: PyMutex::new(callable),
|
||||
};
|
||||
|
||||
|
||||
@@ -202,8 +202,8 @@ impl Deref for PyCode {
|
||||
}
|
||||
|
||||
impl PyCode {
|
||||
pub fn new(code: CodeObject) -> PyCode {
|
||||
PyCode { code }
|
||||
pub fn new(code: CodeObject) -> Self {
|
||||
Self { code }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -335,7 +335,7 @@ impl PyCode {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
pub fn replace(&self, args: ReplaceArgs, vm: &VirtualMachine) -> PyResult<PyCode> {
|
||||
pub fn replace(&self, args: ReplaceArgs, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
let posonlyarg_count = match args.co_posonlyargcount {
|
||||
OptionalArg::Present(posonlyarg_count) => posonlyarg_count,
|
||||
OptionalArg::Missing => self.code.posonlyarg_count,
|
||||
@@ -392,7 +392,7 @@ impl PyCode {
|
||||
OptionalArg::Missing => self.code.varnames.iter().map(|s| s.to_object()).collect(),
|
||||
};
|
||||
|
||||
Ok(PyCode {
|
||||
Ok(Self {
|
||||
code: CodeObject {
|
||||
flags: CodeFlags::from_bits_truncate(flags),
|
||||
posonlyarg_count,
|
||||
|
||||
@@ -48,7 +48,7 @@ impl ToPyObject for Complex64 {
|
||||
|
||||
impl From<Complex64> for PyComplex {
|
||||
fn from(value: Complex64) -> Self {
|
||||
PyComplex { value }
|
||||
Self { value }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,7 +161,7 @@ impl Constructor for PyComplex {
|
||||
OptionalArg::Missing => (Complex64::new(0.0, 0.0), false),
|
||||
OptionalArg::Present(val) => {
|
||||
let val = if cls.is(vm.ctx.types.complex_type) && imag_missing {
|
||||
match val.downcast_exact::<PyComplex>(vm) {
|
||||
match val.downcast_exact::<Self>(vm) {
|
||||
Ok(c) => {
|
||||
return Ok(c.into_pyref().into());
|
||||
}
|
||||
@@ -393,7 +393,7 @@ impl PyComplex {
|
||||
#[pyclass]
|
||||
impl PyRef<PyComplex> {
|
||||
#[pymethod]
|
||||
fn __complex__(self, vm: &VirtualMachine) -> PyRef<PyComplex> {
|
||||
fn __complex__(self, vm: &VirtualMachine) -> Self {
|
||||
if self.is(vm.ctx.types.complex_type) {
|
||||
self
|
||||
} else {
|
||||
@@ -410,7 +410,7 @@ impl Comparable for PyComplex {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<PyComparisonValue> {
|
||||
op.eq_only(|| {
|
||||
let result = if let Some(other) = other.payload_if_subclass::<PyComplex>(vm) {
|
||||
let result = if let Some(other) = other.payload_if_subclass::<Self>(vm) {
|
||||
if zelf.value.re.is_nan()
|
||||
&& zelf.value.im.is_nan()
|
||||
&& other.value.re.is_nan()
|
||||
|
||||
@@ -30,7 +30,7 @@ impl PyCoroutine {
|
||||
}
|
||||
|
||||
pub fn new(frame: FrameRef, name: PyStrRef) -> Self {
|
||||
PyCoroutine {
|
||||
Self {
|
||||
inner: Coro::new(frame, name),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ impl PyDict {
|
||||
|
||||
// Used in update and ior.
|
||||
pub(crate) fn merge_object(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let casted: Result<PyRefExact<PyDict>, _> = other.downcast_exact(vm);
|
||||
let casted: Result<PyRefExact<Self>, _> = other.downcast_exact(vm);
|
||||
let other = match casted {
|
||||
Ok(dict_other) => return self.merge_dict(dict_other.into_pyref(), vm),
|
||||
Err(other) => other,
|
||||
@@ -187,7 +187,7 @@ impl PyDict {
|
||||
) -> PyResult {
|
||||
let value = value.unwrap_or_none(vm);
|
||||
let d = PyType::call(&class, ().into(), vm)?;
|
||||
match d.downcast_exact::<PyDict>(vm) {
|
||||
match d.downcast_exact::<Self>(vm) {
|
||||
Ok(pydict) => {
|
||||
for key in iterable.iter(vm)? {
|
||||
pydict.__setitem__(key?, value.clone(), vm)?;
|
||||
@@ -263,8 +263,8 @@ impl PyDict {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
pub fn copy(&self) -> PyDict {
|
||||
PyDict {
|
||||
pub fn copy(&self) -> Self {
|
||||
Self {
|
||||
entries: self.entries.clone(),
|
||||
}
|
||||
}
|
||||
@@ -331,7 +331,7 @@ impl PyDict {
|
||||
impl Py<PyDict> {
|
||||
fn inner_cmp(
|
||||
&self,
|
||||
other: &Py<PyDict>,
|
||||
other: &Self,
|
||||
op: PyComparisonOp,
|
||||
item: bool,
|
||||
vm: &VirtualMachine,
|
||||
@@ -403,7 +403,7 @@ impl PyRef<PyDict> {
|
||||
|
||||
#[pymethod]
|
||||
fn __ror__(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
let other_dict: Result<PyDictRef, _> = other.downcast();
|
||||
let other_dict: Result<Self, _> = other.downcast();
|
||||
if let Ok(other) = other_dict {
|
||||
let other_cp = other.copy();
|
||||
other_cp.merge_dict(self, vm)?;
|
||||
@@ -692,8 +692,8 @@ pub struct DictIntoIter {
|
||||
}
|
||||
|
||||
impl DictIntoIter {
|
||||
pub const fn new(dict: PyDictRef) -> DictIntoIter {
|
||||
DictIntoIter { dict, position: 0 }
|
||||
pub const fn new(dict: PyDictRef) -> Self {
|
||||
Self { dict, position: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ impl Constructor for PyEnumerate {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult {
|
||||
let counter = start.map_or_else(BigInt::zero, |start| start.as_bigint().clone());
|
||||
PyEnumerate {
|
||||
Self {
|
||||
counter: PyRwLock::new(counter),
|
||||
iterator,
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ impl ToPyObject for f32 {
|
||||
|
||||
impl From<f64> for PyFloat {
|
||||
fn from(value: f64) -> Self {
|
||||
PyFloat { value }
|
||||
Self { value }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,7 +146,7 @@ impl Constructor for PyFloat {
|
||||
}
|
||||
}
|
||||
};
|
||||
PyFloat::from(float_val)
|
||||
Self::from(float_val)
|
||||
.into_ref_with_type(vm, cls)
|
||||
.map(Into::into)
|
||||
}
|
||||
@@ -523,7 +523,7 @@ impl Comparable for PyFloat {
|
||||
op: PyComparisonOp,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<PyComparisonValue> {
|
||||
let ret = if let Some(other) = other.payload_if_subclass::<PyFloat>(vm) {
|
||||
let ret = if let Some(other) = other.payload_if_subclass::<Self>(vm) {
|
||||
zelf.value
|
||||
.partial_cmp(&other.value)
|
||||
.map_or_else(|| op == PyComparisonOp::Ne, |ord| op.eval_ord(ord))
|
||||
|
||||
@@ -78,7 +78,7 @@ impl PyFunction {
|
||||
}
|
||||
});
|
||||
|
||||
let func = PyFunction {
|
||||
let func = Self {
|
||||
code,
|
||||
globals,
|
||||
builtins,
|
||||
@@ -449,7 +449,7 @@ impl PyFunction {
|
||||
#[pymember]
|
||||
fn __doc__(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult {
|
||||
// When accessed from instance, obj is the PyFunction instance
|
||||
if let Ok(func) = obj.downcast::<PyFunction>() {
|
||||
if let Ok(func) = obj.downcast::<Self>() {
|
||||
let doc = func.doc.lock();
|
||||
Ok(doc.clone())
|
||||
} else {
|
||||
@@ -460,7 +460,7 @@ impl PyFunction {
|
||||
|
||||
#[pymember(setter)]
|
||||
fn set___doc__(vm: &VirtualMachine, zelf: PyObjectRef, value: PySetterValue) -> PyResult<()> {
|
||||
let zelf: PyRef<PyFunction> = zelf.downcast().unwrap_or_else(|_| unreachable!());
|
||||
let zelf: PyRef<Self> = zelf.downcast().unwrap_or_else(|_| unreachable!());
|
||||
let value = value.unwrap_or_none(vm);
|
||||
*zelf.doc.lock() = value;
|
||||
Ok(())
|
||||
@@ -637,7 +637,7 @@ impl Constructor for PyFunction {
|
||||
// Get doc from code object - for now just use None
|
||||
let doc = vm.ctx.none();
|
||||
|
||||
let func = PyFunction::new(
|
||||
let func = Self::new(
|
||||
args.code,
|
||||
args.globals,
|
||||
closure,
|
||||
@@ -715,7 +715,7 @@ impl Constructor for PyBoundMethod {
|
||||
Self::Args { function, object }: Self::Args,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult {
|
||||
PyBoundMethod::new(object, function)
|
||||
Self::new(object, function)
|
||||
.into_ref_with_type(vm, cls)
|
||||
.map(Into::into)
|
||||
}
|
||||
@@ -723,7 +723,7 @@ impl Constructor for PyBoundMethod {
|
||||
|
||||
impl PyBoundMethod {
|
||||
pub fn new(object: PyObjectRef, function: PyObjectRef) -> Self {
|
||||
PyBoundMethod { object, function }
|
||||
Self { object, function }
|
||||
}
|
||||
|
||||
pub fn new_ref(object: PyObjectRef, function: PyObjectRef, ctx: &Context) -> PyRef<Self> {
|
||||
|
||||
@@ -33,7 +33,7 @@ impl PyGenerator {
|
||||
}
|
||||
|
||||
pub fn new(frame: FrameRef, name: PyStrRef) -> Self {
|
||||
PyGenerator {
|
||||
Self {
|
||||
inner: Coro::new(frame, name),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ impl Constructor for PyGenericAlias {
|
||||
} else {
|
||||
PyTuple::new_ref(vec![arguments], &vm.ctx)
|
||||
};
|
||||
PyGenericAlias::new(origin, args, false, vm)
|
||||
Self::new(origin, args, false, vm)
|
||||
.into_ref_with_type(vm, cls)
|
||||
.map(Into::into)
|
||||
}
|
||||
@@ -201,7 +201,7 @@ impl PyGenericAlias {
|
||||
vm,
|
||||
)?;
|
||||
|
||||
Ok(PyGenericAlias::new(zelf.origin.clone(), new_args, false, vm).into_pyobject(vm))
|
||||
Ok(Self::new(zelf.origin.clone(), new_args, false, vm).into_pyobject(vm))
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
@@ -596,7 +596,7 @@ impl Iterable for PyGenericAlias {
|
||||
// CPython's ga_iter creates an iterator that yields one starred GenericAlias
|
||||
// we don't have gaiterobject yet
|
||||
|
||||
let starred_alias = PyGenericAlias::new(
|
||||
let starred_alias = Self::new(
|
||||
zelf.origin.clone(),
|
||||
zelf.args.clone(),
|
||||
true, // starred
|
||||
|
||||
+26
-26
@@ -223,7 +223,7 @@ impl Constructor for PyInt {
|
||||
try_int_radix(&val, base, vm)
|
||||
} else {
|
||||
let val = if cls.is(vm.ctx.types.int_type) {
|
||||
match val.downcast_exact::<PyInt>(vm) {
|
||||
match val.downcast_exact::<Self>(vm) {
|
||||
Ok(i) => {
|
||||
return Ok(i.into_pyref().into());
|
||||
}
|
||||
@@ -255,7 +255,7 @@ impl PyInt {
|
||||
} else if cls.is(vm.ctx.types.bool_type) {
|
||||
Ok(vm.ctx.new_bool(!value.into().eq(&BigInt::zero())))
|
||||
} else {
|
||||
PyInt::from(value).into_ref_with_type(vm, cls)
|
||||
Self::from(value).into_ref_with_type(vm, cls)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -298,7 +298,7 @@ impl PyInt {
|
||||
F: Fn(&BigInt, &BigInt) -> BigInt,
|
||||
{
|
||||
let r = other
|
||||
.payload_if_subclass::<PyInt>(vm)
|
||||
.payload_if_subclass::<Self>(vm)
|
||||
.map(|other| op(&self.value, &other.value));
|
||||
PyArithmeticValue::from_option(r)
|
||||
}
|
||||
@@ -308,7 +308,7 @@ impl PyInt {
|
||||
where
|
||||
F: Fn(&BigInt, &BigInt) -> PyResult,
|
||||
{
|
||||
if let Some(other) = other.payload_if_subclass::<PyInt>(vm) {
|
||||
if let Some(other) = other.payload_if_subclass::<Self>(vm) {
|
||||
op(&self.value, &other.value)
|
||||
} else {
|
||||
Ok(vm.ctx.not_implemented())
|
||||
@@ -402,7 +402,7 @@ impl PyInt {
|
||||
}
|
||||
|
||||
fn modpow(&self, other: PyObjectRef, modulus: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
let modulus = match modulus.payload_if_subclass::<PyInt>(vm) {
|
||||
let modulus = match modulus.payload_if_subclass::<Self>(vm) {
|
||||
Some(val) => val.as_bigint(),
|
||||
None => return Ok(vm.ctx.not_implemented()),
|
||||
};
|
||||
@@ -717,7 +717,7 @@ impl Comparable for PyInt {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<PyComparisonValue> {
|
||||
let r = other
|
||||
.payload_if_subclass::<PyInt>(vm)
|
||||
.payload_if_subclass::<Self>(vm)
|
||||
.map(|other| op.eval_ord(zelf.value.cmp(&other.value)));
|
||||
Ok(PyComparisonValue::from_option(r))
|
||||
}
|
||||
@@ -751,11 +751,11 @@ impl AsNumber for PyInt {
|
||||
|
||||
impl PyInt {
|
||||
pub(super) const AS_NUMBER: PyNumberMethods = PyNumberMethods {
|
||||
add: Some(|a, b, vm| PyInt::number_op(a, b, |a, b, _vm| a + b, vm)),
|
||||
subtract: Some(|a, b, vm| PyInt::number_op(a, b, |a, b, _vm| a - b, vm)),
|
||||
multiply: Some(|a, b, vm| PyInt::number_op(a, b, |a, b, _vm| a * b, vm)),
|
||||
remainder: Some(|a, b, vm| PyInt::number_op(a, b, inner_mod, vm)),
|
||||
divmod: Some(|a, b, vm| PyInt::number_op(a, b, inner_divmod, vm)),
|
||||
add: Some(|a, b, vm| Self::number_op(a, b, |a, b, _vm| a + b, vm)),
|
||||
subtract: Some(|a, b, vm| Self::number_op(a, b, |a, b, _vm| a - b, vm)),
|
||||
multiply: Some(|a, b, vm| Self::number_op(a, b, |a, b, _vm| a * b, vm)),
|
||||
remainder: Some(|a, b, vm| Self::number_op(a, b, inner_mod, vm)),
|
||||
divmod: Some(|a, b, vm| Self::number_op(a, b, inner_divmod, vm)),
|
||||
power: Some(|a, b, c, vm| {
|
||||
if let (Some(a), Some(b)) = (
|
||||
a.payload::<Self>(),
|
||||
@@ -774,24 +774,24 @@ impl PyInt {
|
||||
Ok(vm.ctx.not_implemented())
|
||||
}
|
||||
}),
|
||||
negative: Some(|num, vm| (&PyInt::number_downcast(num).value).neg().to_pyresult(vm)),
|
||||
positive: Some(|num, vm| Ok(PyInt::number_downcast_exact(num, vm).into())),
|
||||
absolute: Some(|num, vm| PyInt::number_downcast(num).value.abs().to_pyresult(vm)),
|
||||
boolean: Some(|num, _vm| Ok(PyInt::number_downcast(num).value.is_zero())),
|
||||
invert: Some(|num, vm| (&PyInt::number_downcast(num).value).not().to_pyresult(vm)),
|
||||
lshift: Some(|a, b, vm| PyInt::number_op(a, b, inner_lshift, vm)),
|
||||
rshift: Some(|a, b, vm| PyInt::number_op(a, b, inner_rshift, vm)),
|
||||
and: Some(|a, b, vm| PyInt::number_op(a, b, |a, b, _vm| a & b, vm)),
|
||||
xor: Some(|a, b, vm| PyInt::number_op(a, b, |a, b, _vm| a ^ b, vm)),
|
||||
or: Some(|a, b, vm| PyInt::number_op(a, b, |a, b, _vm| a | b, vm)),
|
||||
int: Some(|num, vm| Ok(PyInt::number_downcast_exact(num, vm).into())),
|
||||
negative: Some(|num, vm| (&Self::number_downcast(num).value).neg().to_pyresult(vm)),
|
||||
positive: Some(|num, vm| Ok(Self::number_downcast_exact(num, vm).into())),
|
||||
absolute: Some(|num, vm| Self::number_downcast(num).value.abs().to_pyresult(vm)),
|
||||
boolean: Some(|num, _vm| Ok(Self::number_downcast(num).value.is_zero())),
|
||||
invert: Some(|num, vm| (&Self::number_downcast(num).value).not().to_pyresult(vm)),
|
||||
lshift: Some(|a, b, vm| Self::number_op(a, b, inner_lshift, vm)),
|
||||
rshift: Some(|a, b, vm| Self::number_op(a, b, inner_rshift, vm)),
|
||||
and: Some(|a, b, vm| Self::number_op(a, b, |a, b, _vm| a & b, vm)),
|
||||
xor: Some(|a, b, vm| Self::number_op(a, b, |a, b, _vm| a ^ b, vm)),
|
||||
or: Some(|a, b, vm| Self::number_op(a, b, |a, b, _vm| a | b, vm)),
|
||||
int: Some(|num, vm| Ok(Self::number_downcast_exact(num, vm).into())),
|
||||
float: Some(|num, vm| {
|
||||
let zelf = PyInt::number_downcast(num);
|
||||
let zelf = Self::number_downcast(num);
|
||||
try_to_float(&zelf.value, vm).map(|x| vm.ctx.new_float(x).into())
|
||||
}),
|
||||
floor_divide: Some(|a, b, vm| PyInt::number_op(a, b, inner_floordiv, vm)),
|
||||
true_divide: Some(|a, b, vm| PyInt::number_op(a, b, inner_truediv, vm)),
|
||||
index: Some(|num, vm| Ok(PyInt::number_downcast_exact(num, vm).into())),
|
||||
floor_divide: Some(|a, b, vm| Self::number_op(a, b, inner_floordiv, vm)),
|
||||
true_divide: Some(|a, b, vm| Self::number_op(a, b, inner_truediv, vm)),
|
||||
index: Some(|num, vm| Ok(Self::number_downcast_exact(num, vm).into())),
|
||||
..PyNumberMethods::NOT_IMPLEMENTED
|
||||
};
|
||||
|
||||
|
||||
@@ -28,8 +28,8 @@ pub enum IterStatus<T> {
|
||||
unsafe impl<T: Traverse> Traverse for IterStatus<T> {
|
||||
fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) {
|
||||
match self {
|
||||
IterStatus::Active(r) => r.traverse(tracer_fn),
|
||||
IterStatus::Exhausted => (),
|
||||
Self::Active(r) => r.traverse(tracer_fn),
|
||||
Self::Exhausted => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ impl fmt::Debug for PyList {
|
||||
|
||||
impl From<Vec<PyObjectRef>> for PyList {
|
||||
fn from(elements: Vec<PyObjectRef>) -> Self {
|
||||
PyList {
|
||||
Self {
|
||||
elements: PyRwLock::new(elements),
|
||||
}
|
||||
}
|
||||
@@ -131,7 +131,7 @@ impl PyList {
|
||||
}
|
||||
|
||||
fn concat(&self, other: &PyObject, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
|
||||
let other = other.payload_if_subclass::<PyList>(vm).ok_or_else(|| {
|
||||
let other = other.payload_if_subclass::<Self>(vm).ok_or_else(|| {
|
||||
vm.new_type_error(format!(
|
||||
"Cannot add {} and {}",
|
||||
Self::class(&vm.ctx).name(),
|
||||
@@ -379,9 +379,7 @@ impl Constructor for PyList {
|
||||
type Args = FuncArgs;
|
||||
|
||||
fn py_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
PyList::default()
|
||||
.into_ref_with_type(vm, cls)
|
||||
.map(Into::into)
|
||||
Self::default().into_ref_with_type(vm, cls).map(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ impl Constructor for PyMap {
|
||||
|
||||
fn py_new(cls: PyTypeRef, (mapper, iterators): Self::Args, vm: &VirtualMachine) -> PyResult {
|
||||
let iterators = iterators.into_vec();
|
||||
PyMap { mapper, iterators }
|
||||
Self { mapper, iterators }
|
||||
.into_ref_with_type(vm, cls)
|
||||
.map(Into::into)
|
||||
}
|
||||
|
||||
@@ -29,8 +29,8 @@ enum MappingProxyInner {
|
||||
unsafe impl Traverse for MappingProxyInner {
|
||||
fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) {
|
||||
match self {
|
||||
MappingProxyInner::Class(r) => r.traverse(tracer_fn),
|
||||
MappingProxyInner::Mapping(arg) => arg.traverse(tracer_fn),
|
||||
Self::Class(r) => r.traverse(tracer_fn),
|
||||
Self::Mapping(arg) => arg.traverse(tracer_fn),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,7 +79,7 @@ impl PyMemoryView {
|
||||
Ok(other.new_view())
|
||||
} else {
|
||||
let buffer = PyBuffer::try_from_borrowed_object(vm, obj)?;
|
||||
PyMemoryView::from_buffer(buffer, vm)
|
||||
Self::from_buffer(buffer, vm)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,7 +93,7 @@ impl PyMemoryView {
|
||||
let format_spec = Self::parse_format(&buffer.desc.format, vm)?;
|
||||
let desc = buffer.desc.clone();
|
||||
|
||||
Ok(PyMemoryView {
|
||||
Ok(Self {
|
||||
buffer: ManuallyDrop::new(buffer),
|
||||
released: AtomicCell::new(false),
|
||||
start: 0,
|
||||
@@ -120,7 +120,7 @@ impl PyMemoryView {
|
||||
|
||||
/// this should be the only way to create a memoryview from another memoryview
|
||||
pub fn new_view(&self) -> Self {
|
||||
let zelf = PyMemoryView {
|
||||
let zelf = Self {
|
||||
buffer: self.buffer.clone(),
|
||||
released: AtomicCell::new(false),
|
||||
start: self.start,
|
||||
|
||||
@@ -83,7 +83,7 @@ impl PyModule {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn __init_dict_from_def(vm: &VirtualMachine, module: &Py<PyModule>) {
|
||||
pub fn __init_dict_from_def(vm: &VirtualMachine, module: &Py<Self>) {
|
||||
let doc = module.def.unwrap().doc.map(|doc| doc.to_owned());
|
||||
module.init_dict(module.name.unwrap(), doc, vm);
|
||||
}
|
||||
@@ -169,7 +169,7 @@ impl Py<PyModule> {
|
||||
impl PyModule {
|
||||
#[pyslot]
|
||||
fn slot_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
PyModule::new().into_ref_with_type(vm, cls).map(Into::into)
|
||||
Self::new().into_ref_with_type(vm, cls).map(Into::into)
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
|
||||
@@ -69,7 +69,7 @@ impl Constructor for PyBaseObject {
|
||||
}
|
||||
}
|
||||
|
||||
Ok(crate::PyRef::new_ref(PyBaseObject, cls, dict).into())
|
||||
Ok(crate::PyRef::new_ref(Self, cls, dict).into())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -199,9 +199,9 @@ impl PyProperty {
|
||||
};
|
||||
|
||||
// Create new property using py_new and init
|
||||
let new_prop = PyProperty::py_new(zelf.class().to_owned(), FuncArgs::default(), vm)?;
|
||||
let new_prop_ref = new_prop.downcast::<PyProperty>().unwrap();
|
||||
PyProperty::init(new_prop_ref.clone(), args, vm)?;
|
||||
let new_prop = Self::py_new(zelf.class().to_owned(), FuncArgs::default(), vm)?;
|
||||
let new_prop_ref = new_prop.downcast::<Self>().unwrap();
|
||||
Self::init(new_prop_ref.clone(), args, vm)?;
|
||||
|
||||
// Copy the name if it exists
|
||||
if let Some(name) = zelf.name.read().clone() {
|
||||
@@ -312,7 +312,7 @@ impl Constructor for PyProperty {
|
||||
type Args = FuncArgs;
|
||||
|
||||
fn py_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
PyProperty {
|
||||
Self {
|
||||
getter: PyRwLock::new(None),
|
||||
setter: PyRwLock::new(None),
|
||||
deleter: PyRwLock::new(None),
|
||||
|
||||
@@ -185,7 +185,7 @@ pub fn init(context: &Context) {
|
||||
))]
|
||||
impl PyRange {
|
||||
fn new(cls: PyTypeRef, stop: ArgIndex, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
|
||||
PyRange {
|
||||
Self {
|
||||
start: vm.ctx.new_pyref(0),
|
||||
stop: stop.into(),
|
||||
step: vm.ctx.new_pyref(1),
|
||||
@@ -204,7 +204,7 @@ impl PyRange {
|
||||
if step.as_bigint().is_zero() {
|
||||
return Err(vm.new_value_error("range() arg 3 must not be zero"));
|
||||
}
|
||||
PyRange {
|
||||
Self {
|
||||
start: start.try_index(vm)?,
|
||||
stop: stop.try_index(vm)?,
|
||||
step,
|
||||
@@ -296,7 +296,7 @@ impl PyRange {
|
||||
sub_start = (sub_start * range_step.as_bigint()) + range_start.as_bigint();
|
||||
sub_stop = (sub_stop * range_step.as_bigint()) + range_start.as_bigint();
|
||||
|
||||
Ok(PyRange {
|
||||
Ok(Self {
|
||||
start: vm.ctx.new_pyref(sub_start),
|
||||
stop: vm.ctx.new_pyref(sub_stop),
|
||||
step: vm.ctx.new_pyref(sub_step),
|
||||
@@ -315,10 +315,10 @@ impl PyRange {
|
||||
fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
let range = if args.args.len() <= 1 {
|
||||
let stop = args.bind(vm)?;
|
||||
PyRange::new(cls, stop, vm)
|
||||
Self::new(cls, stop, vm)
|
||||
} else {
|
||||
let (start, stop, step) = args.bind(vm)?;
|
||||
PyRange::new_from(cls, start, stop, step, vm)
|
||||
Self::new_from(cls, start, stop, step, vm)
|
||||
}?;
|
||||
|
||||
Ok(range.into())
|
||||
@@ -697,14 +697,14 @@ pub enum RangeIndex {
|
||||
impl TryFromObject for RangeIndex {
|
||||
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
|
||||
match_class!(match obj {
|
||||
i @ PyInt => Ok(RangeIndex::Int(i)),
|
||||
s @ PySlice => Ok(RangeIndex::Slice(s)),
|
||||
i @ PyInt => Ok(Self::Int(i)),
|
||||
s @ PySlice => Ok(Self::Slice(s)),
|
||||
obj => {
|
||||
let val = obj.try_index(vm).map_err(|_| vm.new_type_error(format!(
|
||||
"sequence indices be integers or slices or classes that override __index__ operator, not '{}'",
|
||||
obj.class().name()
|
||||
)))?;
|
||||
Ok(RangeIndex::Int(val))
|
||||
Ok(Self::Int(val))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+13
-26
@@ -82,7 +82,7 @@ pub struct PyFrozenSet {
|
||||
|
||||
impl Default for PyFrozenSet {
|
||||
fn default() -> Self {
|
||||
PyFrozenSet {
|
||||
Self {
|
||||
inner: PySetInner::default(),
|
||||
hash: hash::SENTINEL.into(),
|
||||
}
|
||||
@@ -183,7 +183,7 @@ impl PySetInner {
|
||||
where
|
||||
T: IntoIterator<Item = PyResult<PyObjectRef>>,
|
||||
{
|
||||
let set = PySetInner::default();
|
||||
let set = Self::default();
|
||||
for item in iter {
|
||||
set.add(item?, vm)?;
|
||||
}
|
||||
@@ -211,8 +211,8 @@ impl PySetInner {
|
||||
self.content.sizeof()
|
||||
}
|
||||
|
||||
fn copy(&self) -> PySetInner {
|
||||
PySetInner {
|
||||
fn copy(&self) -> Self {
|
||||
Self {
|
||||
content: PyRc::new((*self.content).clone()),
|
||||
}
|
||||
}
|
||||
@@ -221,12 +221,7 @@ impl PySetInner {
|
||||
self.retry_op_with_frozenset(needle, vm, |needle, vm| self.content.contains(vm, needle))
|
||||
}
|
||||
|
||||
fn compare(
|
||||
&self,
|
||||
other: &PySetInner,
|
||||
op: PyComparisonOp,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<bool> {
|
||||
fn compare(&self, other: &Self, op: PyComparisonOp, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
if op == PyComparisonOp::Ne {
|
||||
return self.compare(other, PyComparisonOp::Eq, vm).map(|eq| !eq);
|
||||
}
|
||||
@@ -247,7 +242,7 @@ impl PySetInner {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(super) fn union(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult<PySetInner> {
|
||||
pub(super) fn union(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
let set = self.clone();
|
||||
for item in other.iter(vm)? {
|
||||
set.add(item?, vm)?;
|
||||
@@ -256,12 +251,8 @@ impl PySetInner {
|
||||
Ok(set)
|
||||
}
|
||||
|
||||
pub(super) fn intersection(
|
||||
&self,
|
||||
other: ArgIterable,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<PySetInner> {
|
||||
let set = PySetInner::default();
|
||||
pub(super) fn intersection(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
let set = Self::default();
|
||||
for item in other.iter(vm)? {
|
||||
let obj = item?;
|
||||
if self.contains(&obj, vm)? {
|
||||
@@ -271,11 +262,7 @@ impl PySetInner {
|
||||
Ok(set)
|
||||
}
|
||||
|
||||
pub(super) fn difference(
|
||||
&self,
|
||||
other: ArgIterable,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<PySetInner> {
|
||||
pub(super) fn difference(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
let set = self.copy();
|
||||
for item in other.iter(vm)? {
|
||||
set.content.delete_if_exists(vm, &*item?)?;
|
||||
@@ -287,7 +274,7 @@ impl PySetInner {
|
||||
&self,
|
||||
other: ArgIterable,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<PySetInner> {
|
||||
) -> PyResult<Self> {
|
||||
let new_inner = self.clone();
|
||||
|
||||
// We want to remove duplicates in other
|
||||
@@ -310,7 +297,7 @@ impl PySetInner {
|
||||
}
|
||||
|
||||
fn issubset(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
let other_set = PySetInner::from_iter(other.iter(vm)?, vm)?;
|
||||
let other_set = Self::from_iter(other.iter(vm)?, vm)?;
|
||||
self.compare(&other_set, PyComparisonOp::Le, vm)
|
||||
}
|
||||
|
||||
@@ -412,7 +399,7 @@ impl PySetInner {
|
||||
others: impl std::iter::Iterator<Item = ArgIterable>,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<()> {
|
||||
let temp_inner = self.fold_op(others, PySetInner::intersection, vm)?;
|
||||
let temp_inner = self.fold_op(others, Self::intersection, vm)?;
|
||||
self.clear();
|
||||
for obj in temp_inner.elements() {
|
||||
self.add(obj, vm)?;
|
||||
@@ -1278,7 +1265,7 @@ impl TryFromObject for AnySet {
|
||||
if class.fast_issubclass(vm.ctx.types.set_type)
|
||||
|| class.fast_issubclass(vm.ctx.types.frozenset_type)
|
||||
{
|
||||
Ok(AnySet { object: obj })
|
||||
Ok(Self { object: obj })
|
||||
} else {
|
||||
Err(vm.new_type_error(format!("{class} is not a subtype of set or frozenset")))
|
||||
}
|
||||
|
||||
@@ -65,13 +65,13 @@ impl PySlice {
|
||||
|
||||
#[pyslot]
|
||||
fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
let slice: PySlice = match args.args.len() {
|
||||
let slice: Self = match args.args.len() {
|
||||
0 => {
|
||||
return Err(vm.new_type_error("slice() must have at least one arguments."));
|
||||
}
|
||||
1 => {
|
||||
let stop = args.bind(vm)?;
|
||||
PySlice {
|
||||
Self {
|
||||
start: None,
|
||||
stop,
|
||||
step: None,
|
||||
@@ -80,7 +80,7 @@ impl PySlice {
|
||||
_ => {
|
||||
let (start, stop, step): (PyObjectRef, PyObjectRef, OptionalArg<PyObjectRef>) =
|
||||
args.bind(vm)?;
|
||||
PySlice {
|
||||
Self {
|
||||
start: Some(start),
|
||||
stop,
|
||||
step: step.into_option(),
|
||||
|
||||
@@ -46,7 +46,7 @@ impl Constructor for PyStaticMethod {
|
||||
fn py_new(cls: PyTypeRef, callable: Self::Args, vm: &VirtualMachine) -> PyResult {
|
||||
let doc = callable.get_attr("__doc__", vm);
|
||||
|
||||
let result = PyStaticMethod {
|
||||
let result = Self {
|
||||
callable: PyMutex::new(callable),
|
||||
}
|
||||
.into_ref_with_type(vm, cls)?;
|
||||
|
||||
+31
-31
@@ -181,7 +181,7 @@ impl From<CodePoint> for PyStr {
|
||||
|
||||
impl From<StrData> for PyStr {
|
||||
fn from(data: StrData) -> Self {
|
||||
PyStr {
|
||||
Self {
|
||||
data,
|
||||
hash: Radium::new(hash::SENTINEL),
|
||||
}
|
||||
@@ -364,13 +364,13 @@ impl Constructor for PyStr {
|
||||
}
|
||||
}
|
||||
OptionalArg::Missing => {
|
||||
PyStr::from(String::new()).into_ref_with_type(vm, cls.clone())?
|
||||
Self::from(String::new()).into_ref_with_type(vm, cls.clone())?
|
||||
}
|
||||
};
|
||||
if string.class().is(&cls) {
|
||||
Ok(string.into())
|
||||
} else {
|
||||
PyStr::from(string.as_wtf8())
|
||||
Self::from(string.as_wtf8())
|
||||
.into_ref_with_type(vm, cls)
|
||||
.map(Into::into)
|
||||
}
|
||||
@@ -517,7 +517,7 @@ impl PyStr {
|
||||
impl PyStr {
|
||||
#[pymethod]
|
||||
fn __add__(zelf: PyRef<Self>, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
if let Some(other) = other.payload::<PyStr>() {
|
||||
if let Some(other) = other.payload::<Self>() {
|
||||
let bytes = zelf.as_wtf8().py_add(other.as_wtf8());
|
||||
Ok(unsafe {
|
||||
// SAFETY: `kind` is safely decided
|
||||
@@ -626,7 +626,7 @@ impl PyStr {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn lower(&self) -> PyStr {
|
||||
fn lower(&self) -> Self {
|
||||
match self.as_str_kind() {
|
||||
PyKindStr::Ascii(s) => s.to_ascii_lowercase().into(),
|
||||
PyKindStr::Utf8(s) => s.to_lowercase().into(),
|
||||
@@ -648,7 +648,7 @@ impl PyStr {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn upper(&self) -> PyStr {
|
||||
fn upper(&self) -> Self {
|
||||
match self.as_str_kind() {
|
||||
PyKindStr::Ascii(s) => s.to_ascii_uppercase().into(),
|
||||
PyKindStr::Utf8(s) => s.to_uppercase().into(),
|
||||
@@ -765,7 +765,7 @@ impl PyStr {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn strip(&self, chars: OptionalOption<PyStrRef>) -> PyStr {
|
||||
fn strip(&self, chars: OptionalOption<PyStrRef>) -> Self {
|
||||
match self.as_str_kind() {
|
||||
PyKindStr::Ascii(s) => s
|
||||
.py_strip(
|
||||
@@ -845,7 +845,7 @@ impl PyStr {
|
||||
&affix,
|
||||
"endswith",
|
||||
"str",
|
||||
|s, x: &Py<PyStr>| s.ends_with(x.as_wtf8()),
|
||||
|s, x: &Py<Self>| s.ends_with(x.as_wtf8()),
|
||||
vm,
|
||||
)
|
||||
}
|
||||
@@ -865,7 +865,7 @@ impl PyStr {
|
||||
&affix,
|
||||
"startswith",
|
||||
"str",
|
||||
|s, x: &Py<PyStr>| s.starts_with(x.as_wtf8()),
|
||||
|s, x: &Py<Self>| s.starts_with(x.as_wtf8()),
|
||||
vm,
|
||||
)
|
||||
}
|
||||
@@ -1335,7 +1335,7 @@ impl PyStr {
|
||||
for c in self.as_str().chars() {
|
||||
match table.get_item(&*(c as u32).to_pyobject(vm), vm) {
|
||||
Ok(value) => {
|
||||
if let Some(text) = value.payload::<PyStr>() {
|
||||
if let Some(text) = value.payload::<Self>() {
|
||||
translated.push_str(text.as_str());
|
||||
} else if let Some(bigint) = value.payload::<PyInt>() {
|
||||
let ch = bigint
|
||||
@@ -1367,7 +1367,7 @@ impl PyStr {
|
||||
) -> PyResult {
|
||||
let new_dict = vm.ctx.new_dict();
|
||||
if let OptionalArg::Present(to_str) = to_str {
|
||||
match dict_or_str.downcast::<PyStr>() {
|
||||
match dict_or_str.downcast::<Self>() {
|
||||
Ok(from_str) => {
|
||||
if to_str.len() == from_str.len() {
|
||||
for (c1, c2) in from_str.as_str().chars().zip(to_str.as_str().chars()) {
|
||||
@@ -1405,7 +1405,7 @@ impl PyStr {
|
||||
val,
|
||||
vm,
|
||||
)?;
|
||||
} else if let Some(string) = key.payload::<PyStr>() {
|
||||
} else if let Some(string) = key.payload::<Self>() {
|
||||
if string.len() == 1 {
|
||||
let num_value = string.as_str().chars().next().unwrap() as u32;
|
||||
new_dict.set_item(&*num_value.to_pyobject(vm), val, vm)?;
|
||||
@@ -1693,7 +1693,7 @@ pub fn init(ctx: &Context) {
|
||||
|
||||
impl SliceableSequenceOp for PyStr {
|
||||
type Item = CodePoint;
|
||||
type Sliced = PyStr;
|
||||
type Sliced = Self;
|
||||
|
||||
fn do_get(&self, index: usize) -> Self::Item {
|
||||
self.data.nth_char(index)
|
||||
@@ -1706,13 +1706,13 @@ impl SliceableSequenceOp for PyStr {
|
||||
let char_len = range.len();
|
||||
let out = rustpython_common::str::get_chars(s, range);
|
||||
// SAFETY: char_len is accurate
|
||||
unsafe { PyStr::new_with_char_len(out, char_len) }
|
||||
unsafe { Self::new_with_char_len(out, char_len) }
|
||||
}
|
||||
PyKindStr::Wtf8(w) => {
|
||||
let char_len = range.len();
|
||||
let out = rustpython_common::str::get_codepoints(w, range);
|
||||
// SAFETY: char_len is accurate
|
||||
unsafe { PyStr::new_with_char_len(out, char_len) }
|
||||
unsafe { Self::new_with_char_len(out, char_len) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1734,7 +1734,7 @@ impl SliceableSequenceOp for PyStr {
|
||||
.take(range.len()),
|
||||
);
|
||||
// SAFETY: char_len is accurate
|
||||
unsafe { PyStr::new_with_char_len(out, range.len()) }
|
||||
unsafe { Self::new_with_char_len(out, range.len()) }
|
||||
}
|
||||
PyKindStr::Wtf8(w) => {
|
||||
let char_len = range.len();
|
||||
@@ -1746,7 +1746,7 @@ impl SliceableSequenceOp for PyStr {
|
||||
.take(range.len()),
|
||||
);
|
||||
// SAFETY: char_len is accurate
|
||||
unsafe { PyStr::new_with_char_len(out, char_len) }
|
||||
unsafe { Self::new_with_char_len(out, char_len) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1765,7 +1765,7 @@ impl SliceableSequenceOp for PyStr {
|
||||
let mut out = String::with_capacity(2 * char_len);
|
||||
out.extend(s.chars().skip(range.start).take(range.len()).step_by(step));
|
||||
// SAFETY: char_len is accurate
|
||||
unsafe { PyStr::new_with_char_len(out, char_len) }
|
||||
unsafe { Self::new_with_char_len(out, char_len) }
|
||||
}
|
||||
PyKindStr::Wtf8(w) => {
|
||||
let char_len = (range.len() / step) + 1;
|
||||
@@ -1777,7 +1777,7 @@ impl SliceableSequenceOp for PyStr {
|
||||
.step_by(step),
|
||||
);
|
||||
// SAFETY: char_len is accurate
|
||||
unsafe { PyStr::new_with_char_len(out, char_len) }
|
||||
unsafe { Self::new_with_char_len(out, char_len) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1802,7 +1802,7 @@ impl SliceableSequenceOp for PyStr {
|
||||
.step_by(step),
|
||||
);
|
||||
// SAFETY: char_len is accurate
|
||||
unsafe { PyStr::new_with_char_len(out, char_len) }
|
||||
unsafe { Self::new_with_char_len(out, char_len) }
|
||||
}
|
||||
PyKindStr::Wtf8(w) => {
|
||||
let char_len = (range.len() / step) + 1;
|
||||
@@ -1816,13 +1816,13 @@ impl SliceableSequenceOp for PyStr {
|
||||
.step_by(step),
|
||||
);
|
||||
// SAFETY: char_len is accurate
|
||||
unsafe { PyStr::new_with_char_len(out, char_len) }
|
||||
unsafe { Self::new_with_char_len(out, char_len) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn empty() -> Self::Sliced {
|
||||
PyStr::default()
|
||||
Self::default()
|
||||
}
|
||||
|
||||
fn len(&self) -> usize {
|
||||
@@ -1886,15 +1886,15 @@ impl AnyStrWrapper<AsciiStr> for PyStrRef {
|
||||
|
||||
impl AnyStrContainer<str> for String {
|
||||
fn new() -> Self {
|
||||
String::new()
|
||||
Self::new()
|
||||
}
|
||||
|
||||
fn with_capacity(capacity: usize) -> Self {
|
||||
String::with_capacity(capacity)
|
||||
Self::with_capacity(capacity)
|
||||
}
|
||||
|
||||
fn push_str(&mut self, other: &str) {
|
||||
String::push_str(self, other)
|
||||
Self::push_str(self, other)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1925,7 +1925,7 @@ impl AnyStr for str {
|
||||
}
|
||||
|
||||
fn elements(&self) -> impl Iterator<Item = char> {
|
||||
str::chars(self)
|
||||
Self::chars(self)
|
||||
}
|
||||
|
||||
fn get_bytes(&self, range: std::ops::Range<usize>) -> &Self {
|
||||
@@ -1999,11 +1999,11 @@ impl AnyStr for str {
|
||||
|
||||
impl AnyStrContainer<Wtf8> for Wtf8Buf {
|
||||
fn new() -> Self {
|
||||
Wtf8Buf::new()
|
||||
Self::new()
|
||||
}
|
||||
|
||||
fn with_capacity(capacity: usize) -> Self {
|
||||
Wtf8Buf::with_capacity(capacity)
|
||||
Self::with_capacity(capacity)
|
||||
}
|
||||
|
||||
fn push_str(&mut self, other: &Wtf8) {
|
||||
@@ -2117,15 +2117,15 @@ impl AnyStr for Wtf8 {
|
||||
|
||||
impl AnyStrContainer<AsciiStr> for AsciiString {
|
||||
fn new() -> Self {
|
||||
AsciiString::new()
|
||||
Self::new()
|
||||
}
|
||||
|
||||
fn with_capacity(capacity: usize) -> Self {
|
||||
AsciiString::with_capacity(capacity)
|
||||
Self::with_capacity(capacity)
|
||||
}
|
||||
|
||||
fn push_str(&mut self, other: &AsciiStr) {
|
||||
AsciiString::push_str(self, other)
|
||||
Self::push_str(self, other)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@ impl Constructor for PySuper {
|
||||
type Args = FuncArgs;
|
||||
|
||||
fn py_new(cls: PyTypeRef, _args: Self::Args, vm: &VirtualMachine) -> PyResult {
|
||||
let obj = PySuper {
|
||||
let obj = Self {
|
||||
inner: PyRwLock::new(PySuperInner::new(
|
||||
vm.ctx.types.object_type.to_owned(), // is this correct?
|
||||
vm.ctx.none(),
|
||||
@@ -205,7 +205,7 @@ impl GetDescriptor for PySuper {
|
||||
let zelf_class = zelf.as_object().class();
|
||||
if zelf_class.is(vm.ctx.types.super_type) {
|
||||
let typ = zelf.inner.read().typ.clone();
|
||||
Ok(PySuper {
|
||||
Ok(Self {
|
||||
inner: PyRwLock::new(PySuperInner::new(typ, obj, vm)?),
|
||||
}
|
||||
.into_ref(&vm.ctx)
|
||||
|
||||
@@ -28,7 +28,7 @@ impl PyPayload for PyTraceback {
|
||||
#[pyclass]
|
||||
impl PyTraceback {
|
||||
pub fn new(next: Option<PyRef<Self>>, frame: FrameRef, lasti: u32, lineno: LineNumber) -> Self {
|
||||
PyTraceback {
|
||||
Self {
|
||||
next: PyMutex::new(next),
|
||||
frame,
|
||||
lasti,
|
||||
@@ -63,7 +63,7 @@ impl PyTraceback {
|
||||
}
|
||||
|
||||
impl PyTracebackRef {
|
||||
pub fn iter(&self) -> impl Iterator<Item = PyTracebackRef> {
|
||||
pub fn iter(&self) -> impl Iterator<Item = Self> {
|
||||
std::iter::successors(Some(self.clone()), |tb| tb.next.lock().clone())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -336,7 +336,7 @@ impl PyTuple {
|
||||
let tup_arg = if zelf.class().is(vm.ctx.types.tuple_type) {
|
||||
zelf
|
||||
} else {
|
||||
PyTuple::new_ref(zelf.elements.clone().into_vec(), &vm.ctx)
|
||||
Self::new_ref(zelf.elements.clone().into_vec(), &vm.ctx)
|
||||
};
|
||||
(tup_arg,)
|
||||
}
|
||||
|
||||
@@ -260,7 +260,7 @@ impl PyType {
|
||||
}
|
||||
|
||||
let new_type = PyRef::new_ref(
|
||||
PyType {
|
||||
Self {
|
||||
base: Some(base),
|
||||
bases: PyRwLock::new(bases),
|
||||
mro: PyRwLock::new(mro),
|
||||
@@ -305,7 +305,7 @@ impl PyType {
|
||||
let mro = base.mro_map_collect(|x| x.to_owned());
|
||||
|
||||
let new_type = PyRef::new_ref(
|
||||
PyType {
|
||||
Self {
|
||||
base: Some(base),
|
||||
bases,
|
||||
mro: PyRwLock::new(mro),
|
||||
@@ -434,7 +434,7 @@ impl PyType {
|
||||
let mut attributes = PyAttributes::default();
|
||||
|
||||
for bc in std::iter::once(self)
|
||||
.chain(self.mro.read().iter().map(|cls| -> &PyType { cls }))
|
||||
.chain(self.mro.read().iter().map(|cls| -> &Self { cls }))
|
||||
.rev()
|
||||
{
|
||||
for (name, value) in bc.attributes.read().iter() {
|
||||
@@ -446,7 +446,7 @@ impl PyType {
|
||||
}
|
||||
|
||||
// bound method for every type
|
||||
pub(crate) fn __new__(zelf: PyRef<PyType>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
pub(crate) fn __new__(zelf: PyRef<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
let (subtype, args): (PyRef<Self>, FuncArgs) = args.bind(vm)?;
|
||||
if !subtype.fast_issubclass(&zelf) {
|
||||
return Err(vm.new_type_error(format!(
|
||||
@@ -486,13 +486,13 @@ impl PyType {
|
||||
}
|
||||
|
||||
impl Py<PyType> {
|
||||
pub(crate) fn is_subtype(&self, other: &Py<PyType>) -> bool {
|
||||
pub(crate) fn is_subtype(&self, other: &Self) -> bool {
|
||||
is_subtype_with_mro(&self.mro.read(), self, other)
|
||||
}
|
||||
|
||||
/// Equivalent to CPython's PyType_CheckExact macro
|
||||
/// Checks if obj is exactly a type (not a subclass)
|
||||
pub fn check_exact<'a>(obj: &'a PyObject, vm: &VirtualMachine) -> Option<&'a Py<PyType>> {
|
||||
pub fn check_exact<'a>(obj: &'a PyObject, vm: &VirtualMachine) -> Option<&'a Self> {
|
||||
obj.downcast_ref_if_exact::<PyType>(vm)
|
||||
}
|
||||
|
||||
@@ -533,7 +533,7 @@ impl Py<PyType> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn iter_base_chain(&self) -> impl Iterator<Item = &Py<PyType>> {
|
||||
pub fn iter_base_chain(&self) -> impl Iterator<Item = &Self> {
|
||||
std::iter::successors(Some(self), |cls| cls.base.as_deref())
|
||||
}
|
||||
|
||||
@@ -929,7 +929,7 @@ impl Constructor for PyType {
|
||||
let bases = bases
|
||||
.iter()
|
||||
.map(|obj| {
|
||||
obj.clone().downcast::<PyType>().or_else(|obj| {
|
||||
obj.clone().downcast::<Self>().or_else(|obj| {
|
||||
if vm
|
||||
.get_attribute_opt(obj, identifier!(vm, __mro_entries__))?
|
||||
.is_some()
|
||||
|
||||
@@ -53,7 +53,7 @@ impl Constructor for PyWeakProxy {
|
||||
)
|
||||
});
|
||||
// TODO: PyWeakProxy should use the same payload as PyWeak
|
||||
PyWeakProxy {
|
||||
Self {
|
||||
weak: referent.downgrade_with_typ(callback.into_option(), weak_cls.clone(), vm)?,
|
||||
}
|
||||
.into_ref_with_type(vm, cls)
|
||||
|
||||
@@ -36,7 +36,7 @@ impl Constructor for PyZip {
|
||||
fn py_new(cls: PyTypeRef, (iterators, args): Self::Args, vm: &VirtualMachine) -> PyResult {
|
||||
let iterators = iterators.into_vec();
|
||||
let strict = Radium::new(args.strict.unwrap_or(false));
|
||||
PyZip { iterators, strict }
|
||||
Self { iterators, strict }
|
||||
.into_ref_with_type(vm, cls)
|
||||
.map(Into::into)
|
||||
}
|
||||
|
||||
+20
-41
@@ -30,7 +30,7 @@ pub struct PyBytesInner {
|
||||
}
|
||||
|
||||
impl From<Vec<u8>> for PyBytesInner {
|
||||
fn from(elements: Vec<u8>) -> PyBytesInner {
|
||||
fn from(elements: Vec<u8>) -> Self {
|
||||
Self { elements }
|
||||
}
|
||||
}
|
||||
@@ -342,11 +342,7 @@ impl PyBytesInner {
|
||||
self.elements.py_add(other)
|
||||
}
|
||||
|
||||
pub fn contains(
|
||||
&self,
|
||||
needle: Either<PyBytesInner, PyIntRef>,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<bool> {
|
||||
pub fn contains(&self, needle: Either<Self, PyIntRef>, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
Ok(match needle {
|
||||
Either::A(byte) => self.elements.contains_str(byte.elements.as_slice()),
|
||||
Either::B(int) => self.elements.contains(&int.as_bigint().byte_or(vm)?),
|
||||
@@ -552,11 +548,7 @@ impl PyBytesInner {
|
||||
.py_count(needle.as_slice(), range, |h, n| h.find_iter(n).count()))
|
||||
}
|
||||
|
||||
pub fn join(
|
||||
&self,
|
||||
iterable: ArgIterable<PyBytesInner>,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<Vec<u8>> {
|
||||
pub fn join(&self, iterable: ArgIterable<Self>, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
|
||||
let iter = iterable.iter(vm)?;
|
||||
self.elements.py_join(iter)
|
||||
}
|
||||
@@ -575,11 +567,7 @@ impl PyBytesInner {
|
||||
Ok(self.elements.py_find(&needle, range, find))
|
||||
}
|
||||
|
||||
pub fn maketrans(
|
||||
from: PyBytesInner,
|
||||
to: PyBytesInner,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<Vec<u8>> {
|
||||
pub fn maketrans(from: Self, to: Self, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
|
||||
if from.len() != to.len() {
|
||||
return Err(vm.new_value_error("the two maketrans arguments must have equal length"));
|
||||
}
|
||||
@@ -618,7 +606,7 @@ impl PyBytesInner {
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
pub fn strip(&self, chars: OptionalOption<PyBytesInner>) -> Vec<u8> {
|
||||
pub fn strip(&self, chars: OptionalOption<Self>) -> Vec<u8> {
|
||||
self.elements
|
||||
.py_strip(
|
||||
chars,
|
||||
@@ -628,7 +616,7 @@ impl PyBytesInner {
|
||||
.to_vec()
|
||||
}
|
||||
|
||||
pub fn lstrip(&self, chars: OptionalOption<PyBytesInner>) -> &[u8] {
|
||||
pub fn lstrip(&self, chars: OptionalOption<Self>) -> &[u8] {
|
||||
self.elements.py_strip(
|
||||
chars,
|
||||
|s, chars| s.trim_start_with(|c| chars.contains(&(c as u8))),
|
||||
@@ -636,7 +624,7 @@ impl PyBytesInner {
|
||||
)
|
||||
}
|
||||
|
||||
pub fn rstrip(&self, chars: OptionalOption<PyBytesInner>) -> &[u8] {
|
||||
pub fn rstrip(&self, chars: OptionalOption<Self>) -> &[u8] {
|
||||
self.elements.py_strip(
|
||||
chars,
|
||||
|s, chars| s.trim_end_with(|c| chars.contains(&(c as u8))),
|
||||
@@ -645,7 +633,7 @@ impl PyBytesInner {
|
||||
}
|
||||
|
||||
// new in Python 3.9
|
||||
pub fn removeprefix(&self, prefix: PyBytesInner) -> Vec<u8> {
|
||||
pub fn removeprefix(&self, prefix: Self) -> Vec<u8> {
|
||||
self.elements
|
||||
.py_removeprefix(&prefix.elements, prefix.elements.len(), |s, p| {
|
||||
s.starts_with(p)
|
||||
@@ -654,7 +642,7 @@ impl PyBytesInner {
|
||||
}
|
||||
|
||||
// new in Python 3.9
|
||||
pub fn removesuffix(&self, suffix: PyBytesInner) -> Vec<u8> {
|
||||
pub fn removesuffix(&self, suffix: Self) -> Vec<u8> {
|
||||
self.elements
|
||||
.py_removesuffix(&suffix.elements, suffix.elements.len(), |s, p| {
|
||||
s.ends_with(p)
|
||||
@@ -703,11 +691,7 @@ impl PyBytesInner {
|
||||
Ok(elements)
|
||||
}
|
||||
|
||||
pub fn partition(
|
||||
&self,
|
||||
sub: &PyBytesInner,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<(Vec<u8>, bool, Vec<u8>)> {
|
||||
pub fn partition(&self, sub: &Self, vm: &VirtualMachine) -> PyResult<(Vec<u8>, bool, Vec<u8>)> {
|
||||
self.elements.py_partition(
|
||||
&sub.elements,
|
||||
|| self.elements.splitn_str(2, &sub.elements),
|
||||
@@ -717,7 +701,7 @@ impl PyBytesInner {
|
||||
|
||||
pub fn rpartition(
|
||||
&self,
|
||||
sub: &PyBytesInner,
|
||||
sub: &Self,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<(Vec<u8>, bool, Vec<u8>)> {
|
||||
self.elements.py_partition(
|
||||
@@ -771,7 +755,7 @@ impl PyBytesInner {
|
||||
}
|
||||
|
||||
// len(self)>=1, from="", len(to)>=1, max_count>=1
|
||||
fn replace_interleave(&self, to: PyBytesInner, max_count: Option<usize>) -> Vec<u8> {
|
||||
fn replace_interleave(&self, to: Self, max_count: Option<usize>) -> Vec<u8> {
|
||||
let place_count = self.elements.len() + 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();
|
||||
@@ -786,7 +770,7 @@ impl PyBytesInner {
|
||||
result
|
||||
}
|
||||
|
||||
fn replace_delete(&self, from: PyBytesInner, max_count: Option<usize>) -> Vec<u8> {
|
||||
fn replace_delete(&self, from: Self, max_count: Option<usize>) -> Vec<u8> {
|
||||
let count = count_substring(
|
||||
self.elements.as_slice(),
|
||||
from.elements.as_slice(),
|
||||
@@ -815,12 +799,7 @@ impl PyBytesInner {
|
||||
result
|
||||
}
|
||||
|
||||
pub fn replace_in_place(
|
||||
&self,
|
||||
from: PyBytesInner,
|
||||
to: PyBytesInner,
|
||||
max_count: Option<usize>,
|
||||
) -> Vec<u8> {
|
||||
pub fn replace_in_place(&self, from: Self, to: Self, max_count: Option<usize>) -> Vec<u8> {
|
||||
let len = from.len();
|
||||
let mut iter = self.elements.find_iter(&from.elements);
|
||||
|
||||
@@ -849,8 +828,8 @@ impl PyBytesInner {
|
||||
|
||||
fn replace_general(
|
||||
&self,
|
||||
from: PyBytesInner,
|
||||
to: PyBytesInner,
|
||||
from: Self,
|
||||
to: Self,
|
||||
max_count: Option<usize>,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<Vec<u8>> {
|
||||
@@ -894,8 +873,8 @@ impl PyBytesInner {
|
||||
|
||||
pub fn replace(
|
||||
&self,
|
||||
from: PyBytesInner,
|
||||
to: PyBytesInner,
|
||||
from: Self,
|
||||
to: Self,
|
||||
max_count: OptionalArg<isize>,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<Vec<u8>> {
|
||||
@@ -1040,11 +1019,11 @@ impl AnyStrWrapper<[u8]> for PyBytesInner {
|
||||
|
||||
impl AnyStrContainer<[u8]> for Vec<u8> {
|
||||
fn new() -> Self {
|
||||
Vec::new()
|
||||
Self::new()
|
||||
}
|
||||
|
||||
fn with_capacity(capacity: usize) -> Self {
|
||||
Vec::with_capacity(capacity)
|
||||
Self::with_capacity(capacity)
|
||||
}
|
||||
|
||||
fn push_str(&mut self, other: &[u8]) {
|
||||
|
||||
+3
-3
@@ -42,7 +42,7 @@ impl PyCodec {
|
||||
#[inline]
|
||||
pub fn from_tuple(tuple: PyTupleRef) -> Result<Self, PyTupleRef> {
|
||||
if tuple.len() == 4 {
|
||||
Ok(PyCodec(tuple))
|
||||
Ok(Self(tuple))
|
||||
} else {
|
||||
Err(tuple)
|
||||
}
|
||||
@@ -139,7 +139,7 @@ impl TryFromObject for PyCodec {
|
||||
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
|
||||
obj.downcast::<PyTuple>()
|
||||
.ok()
|
||||
.and_then(|tuple| PyCodec::from_tuple(tuple).ok())
|
||||
.and_then(|tuple| Self::from_tuple(tuple).ok())
|
||||
.ok_or_else(|| vm.new_type_error("codec search functions must return 4-tuples"))
|
||||
}
|
||||
}
|
||||
@@ -190,7 +190,7 @@ impl CodecsRegistry {
|
||||
search_cache: HashMap::new(),
|
||||
errors,
|
||||
};
|
||||
CodecsRegistry {
|
||||
Self {
|
||||
inner: PyRwLock::new(inner),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,15 +123,14 @@ impl<'a, T: PyPayload> TryFromBorrowedObject<'a> for &'a Py<T> {
|
||||
|
||||
impl TryFromObject for std::time::Duration {
|
||||
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
|
||||
use std::time::Duration;
|
||||
if let Some(float) = obj.payload::<PyFloat>() {
|
||||
Ok(Duration::from_secs_f64(float.to_f64()))
|
||||
Ok(Self::from_secs_f64(float.to_f64()))
|
||||
} else if let Some(int) = obj.try_index_opt(vm) {
|
||||
let sec = int?
|
||||
.as_bigint()
|
||||
.to_u64()
|
||||
.ok_or_else(|| vm.new_value_error("value out of range"))?;
|
||||
Ok(Duration::from_secs(sec))
|
||||
Ok(Self::from_secs(sec))
|
||||
} else {
|
||||
Err(vm.new_type_error(format!(
|
||||
"expected an int or float for duration, got {}",
|
||||
|
||||
+3
-3
@@ -11,8 +11,8 @@ impl ExecutionResult {
|
||||
/// Turn an ExecutionResult into a PyResult that would be returned from a generator or coroutine
|
||||
fn into_iter_return(self, vm: &VirtualMachine) -> PyIterReturn {
|
||||
match self {
|
||||
ExecutionResult::Yield(value) => PyIterReturn::Return(value),
|
||||
ExecutionResult::Return(value) => {
|
||||
Self::Yield(value) => PyIterReturn::Return(value),
|
||||
Self::Return(value) => {
|
||||
let arg = if vm.is_none(&value) {
|
||||
None
|
||||
} else {
|
||||
@@ -49,7 +49,7 @@ fn gen_name(jen: &PyObject, vm: &VirtualMachine) -> &'static str {
|
||||
|
||||
impl Coro {
|
||||
pub fn new(frame: FrameRef, name: PyStrRef) -> Self {
|
||||
Coro {
|
||||
Self {
|
||||
frame,
|
||||
closed: AtomicCell::new(false),
|
||||
running: AtomicCell::new(false),
|
||||
|
||||
@@ -795,7 +795,7 @@ impl DictKey for PyStrInterned {
|
||||
|
||||
#[inline]
|
||||
fn _to_owned(&self, _vm: &VirtualMachine) -> Self::Owned {
|
||||
let zelf: &'static PyStrInterned = unsafe { &*(self as *const _) };
|
||||
let zelf: &'static Self = unsafe { &*(self as *const _) };
|
||||
zelf.to_exact()
|
||||
}
|
||||
|
||||
@@ -890,7 +890,7 @@ impl DictKey for str {
|
||||
}
|
||||
|
||||
impl DictKey for String {
|
||||
type Owned = String;
|
||||
type Owned = Self;
|
||||
|
||||
#[inline]
|
||||
fn _to_owned(&self, _vm: &VirtualMachine) -> Self::Owned {
|
||||
@@ -951,7 +951,7 @@ impl DictKey for Wtf8 {
|
||||
}
|
||||
|
||||
impl DictKey for Wtf8Buf {
|
||||
type Owned = Wtf8Buf;
|
||||
type Owned = Self;
|
||||
|
||||
#[inline]
|
||||
fn _to_owned(&self, _vm: &VirtualMachine) -> Self::Owned {
|
||||
@@ -1012,7 +1012,7 @@ impl DictKey for [u8] {
|
||||
}
|
||||
|
||||
impl DictKey for Vec<u8> {
|
||||
type Owned = Vec<u8>;
|
||||
type Owned = Self;
|
||||
|
||||
#[inline]
|
||||
fn _to_owned(&self, _vm: &VirtualMachine) -> Self::Owned {
|
||||
@@ -1037,7 +1037,7 @@ impl DictKey for Vec<u8> {
|
||||
}
|
||||
|
||||
impl DictKey for usize {
|
||||
type Owned = usize;
|
||||
type Owned = Self;
|
||||
|
||||
#[inline]
|
||||
fn _to_owned(&self, _vm: &VirtualMachine) -> Self::Owned {
|
||||
|
||||
@@ -547,8 +547,8 @@ macro_rules! extend_exception {
|
||||
}
|
||||
|
||||
impl PyBaseException {
|
||||
pub(crate) fn new(args: Vec<PyObjectRef>, vm: &VirtualMachine) -> PyBaseException {
|
||||
PyBaseException {
|
||||
pub(crate) fn new(args: Vec<PyObjectRef>, vm: &VirtualMachine) -> Self {
|
||||
Self {
|
||||
traceback: PyRwLock::new(None),
|
||||
cause: PyRwLock::new(None),
|
||||
context: PyRwLock::new(None),
|
||||
@@ -688,10 +688,10 @@ impl Constructor for PyBaseException {
|
||||
type Args = FuncArgs;
|
||||
|
||||
fn py_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
|
||||
if cls.is(PyBaseException::class(&vm.ctx)) && !args.kwargs.is_empty() {
|
||||
if cls.is(Self::class(&vm.ctx)) && !args.kwargs.is_empty() {
|
||||
return Err(vm.new_type_error("BaseException() takes no keyword arguments"));
|
||||
}
|
||||
PyBaseException::new(args.args, vm)
|
||||
Self::new(args.args, vm)
|
||||
.into_ref_with_type(vm, cls)
|
||||
.map(Into::into)
|
||||
}
|
||||
|
||||
+11
-19
@@ -12,35 +12,29 @@ use crate::common::wtf8::{Wtf8, Wtf8Buf};
|
||||
impl IntoPyException for FormatSpecError {
|
||||
fn into_pyexception(self, vm: &VirtualMachine) -> PyBaseExceptionRef {
|
||||
match self {
|
||||
FormatSpecError::DecimalDigitsTooMany => {
|
||||
Self::DecimalDigitsTooMany => {
|
||||
vm.new_value_error("Too many decimal digits in format string")
|
||||
}
|
||||
FormatSpecError::PrecisionTooBig => vm.new_value_error("Precision too big"),
|
||||
FormatSpecError::InvalidFormatSpecifier => {
|
||||
vm.new_value_error("Invalid format specifier")
|
||||
}
|
||||
FormatSpecError::UnspecifiedFormat(c1, c2) => {
|
||||
Self::PrecisionTooBig => vm.new_value_error("Precision too big"),
|
||||
Self::InvalidFormatSpecifier => vm.new_value_error("Invalid format specifier"),
|
||||
Self::UnspecifiedFormat(c1, c2) => {
|
||||
let msg = format!("Cannot specify '{c1}' with '{c2}'.");
|
||||
vm.new_value_error(msg)
|
||||
}
|
||||
FormatSpecError::UnknownFormatCode(c, s) => {
|
||||
Self::UnknownFormatCode(c, s) => {
|
||||
let msg = format!("Unknown format code '{c}' for object of type '{s}'");
|
||||
vm.new_value_error(msg)
|
||||
}
|
||||
FormatSpecError::PrecisionNotAllowed => {
|
||||
Self::PrecisionNotAllowed => {
|
||||
vm.new_value_error("Precision not allowed in integer format specifier")
|
||||
}
|
||||
FormatSpecError::NotAllowed(s) => {
|
||||
Self::NotAllowed(s) => {
|
||||
let msg = format!("{s} not allowed with integer format specifier 'c'");
|
||||
vm.new_value_error(msg)
|
||||
}
|
||||
FormatSpecError::UnableToConvert => {
|
||||
vm.new_value_error("Unable to convert int to float")
|
||||
}
|
||||
FormatSpecError::CodeNotInRange => {
|
||||
vm.new_overflow_error("%c arg not in range(0x110000)")
|
||||
}
|
||||
FormatSpecError::NotImplemented(c, s) => {
|
||||
Self::UnableToConvert => vm.new_value_error("Unable to convert int to float"),
|
||||
Self::CodeNotInRange => vm.new_overflow_error("%c arg not in range(0x110000)"),
|
||||
Self::NotImplemented(c, s) => {
|
||||
let msg = format!("Format code '{c}' for object of type '{s}' not implemented yet");
|
||||
vm.new_value_error(msg)
|
||||
}
|
||||
@@ -51,9 +45,7 @@ impl IntoPyException for FormatSpecError {
|
||||
impl ToPyException for FormatParseError {
|
||||
fn to_pyexception(&self, vm: &VirtualMachine) -> PyBaseExceptionRef {
|
||||
match self {
|
||||
FormatParseError::UnmatchedBracket => {
|
||||
vm.new_value_error("expected '}' before end of string")
|
||||
}
|
||||
Self::UnmatchedBracket => vm.new_value_error("expected '}' before end of string"),
|
||||
_ => vm.new_value_error("Unexpected error parsing format string"),
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -142,7 +142,7 @@ impl Frame {
|
||||
closure: &[PyCellRef],
|
||||
func_obj: Option<PyObjectRef>,
|
||||
vm: &VirtualMachine,
|
||||
) -> Frame {
|
||||
) -> Self {
|
||||
let cells_frees = std::iter::repeat_with(|| PyCell::default().into_ref(&vm.ctx))
|
||||
.take(code.cellvars.len())
|
||||
.chain(closure.iter().cloned())
|
||||
@@ -155,7 +155,7 @@ impl Frame {
|
||||
lasti: 0,
|
||||
};
|
||||
|
||||
Frame {
|
||||
Self {
|
||||
fastlocals: PyMutex::new(vec![None; code.varnames.len()].into_boxed_slice()),
|
||||
cells_frees,
|
||||
locals: scope.locals,
|
||||
@@ -2285,7 +2285,7 @@ impl fmt::Debug for Frame {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let state = self.state.lock();
|
||||
let stack_str = state.stack.iter().fold(String::new(), |mut s, elem| {
|
||||
if elem.payload_is::<Frame>() {
|
||||
if elem.payload_is::<Self>() {
|
||||
s.push_str("\n > {frame}");
|
||||
} else {
|
||||
std::fmt::write(&mut s, format_args!("\n > {elem:?}")).unwrap();
|
||||
|
||||
+18
-18
@@ -78,7 +78,7 @@ where
|
||||
A: Into<PosArgs>,
|
||||
{
|
||||
fn from(args: A) -> Self {
|
||||
FuncArgs {
|
||||
Self {
|
||||
args: args.into().into_vec(),
|
||||
kwargs: IndexMap::new(),
|
||||
}
|
||||
@@ -87,7 +87,7 @@ where
|
||||
|
||||
impl From<KwArgs> for FuncArgs {
|
||||
fn from(kwargs: KwArgs) -> Self {
|
||||
FuncArgs {
|
||||
Self {
|
||||
args: Vec::new(),
|
||||
kwargs: kwargs.0,
|
||||
}
|
||||
@@ -125,7 +125,7 @@ impl FuncArgs {
|
||||
|
||||
let kwargs = kwarg_names.zip_eq(args).collect::<IndexMap<_, _>>();
|
||||
|
||||
FuncArgs {
|
||||
Self {
|
||||
args: pos_args,
|
||||
kwargs,
|
||||
}
|
||||
@@ -250,7 +250,7 @@ pub enum ArgumentError {
|
||||
|
||||
impl From<PyBaseExceptionRef> for ArgumentError {
|
||||
fn from(ex: PyBaseExceptionRef) -> Self {
|
||||
ArgumentError::Exception(ex)
|
||||
Self::Exception(ex)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -262,23 +262,23 @@ impl ArgumentError {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyBaseExceptionRef {
|
||||
match self {
|
||||
ArgumentError::TooFewArgs => vm.new_type_error(format!(
|
||||
Self::TooFewArgs => vm.new_type_error(format!(
|
||||
"Expected at least {} arguments ({} given)",
|
||||
arity.start(),
|
||||
num_given
|
||||
)),
|
||||
ArgumentError::TooManyArgs => vm.new_type_error(format!(
|
||||
Self::TooManyArgs => vm.new_type_error(format!(
|
||||
"Expected at most {} arguments ({} given)",
|
||||
arity.end(),
|
||||
num_given
|
||||
)),
|
||||
ArgumentError::InvalidKeywordArgument(name) => {
|
||||
Self::InvalidKeywordArgument(name) => {
|
||||
vm.new_type_error(format!("{name} is an invalid keyword argument"))
|
||||
}
|
||||
ArgumentError::RequiredKeywordArgument(name) => {
|
||||
Self::RequiredKeywordArgument(name) => {
|
||||
vm.new_type_error(format!("Required keyword only argument {name}"))
|
||||
}
|
||||
ArgumentError::Exception(ex) => ex,
|
||||
Self::Exception(ex) => ex,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -345,7 +345,7 @@ where
|
||||
|
||||
impl<T> KwArgs<T> {
|
||||
pub const fn new(map: IndexMap<String, T>) -> Self {
|
||||
KwArgs(map)
|
||||
Self(map)
|
||||
}
|
||||
|
||||
pub fn pop_kwarg(&mut self, name: &str) -> Option<T> {
|
||||
@@ -359,13 +359,13 @@ impl<T> KwArgs<T> {
|
||||
|
||||
impl<T> FromIterator<(String, T)> for KwArgs<T> {
|
||||
fn from_iter<I: IntoIterator<Item = (String, T)>>(iter: I) -> Self {
|
||||
KwArgs(iter.into_iter().collect())
|
||||
Self(iter.into_iter().collect())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Default for KwArgs<T> {
|
||||
fn default() -> Self {
|
||||
KwArgs(IndexMap::new())
|
||||
Self(IndexMap::new())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -378,7 +378,7 @@ where
|
||||
for (name, value) in args.remaining_keywords() {
|
||||
kwargs.insert(name, value.try_into_value(vm)?);
|
||||
}
|
||||
Ok(KwArgs(kwargs))
|
||||
Ok(Self(kwargs))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -459,7 +459,7 @@ where
|
||||
while let Some(value) = args.take_positional() {
|
||||
varargs.push(value.try_into_value(vm)?);
|
||||
}
|
||||
Ok(PosArgs(varargs))
|
||||
Ok(Self(varargs))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -501,8 +501,8 @@ where
|
||||
{
|
||||
fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) {
|
||||
match self {
|
||||
OptionalArg::Present(o) => o.traverse(tracer_fn),
|
||||
OptionalArg::Missing => (),
|
||||
Self::Present(o) => o.traverse(tracer_fn),
|
||||
Self::Missing => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -532,9 +532,9 @@ where
|
||||
|
||||
fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result<Self, ArgumentError> {
|
||||
let r = if let Some(value) = args.take_positional() {
|
||||
OptionalArg::Present(value.try_into_value(vm)?)
|
||||
Self::Present(value.try_into_value(vm)?)
|
||||
} else {
|
||||
OptionalArg::Missing
|
||||
Self::Missing
|
||||
};
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
@@ -34,8 +34,8 @@ where
|
||||
{
|
||||
fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef {
|
||||
match self {
|
||||
PyArithmeticValue::Implemented(v) => v.to_pyobject(vm),
|
||||
PyArithmeticValue::NotImplemented => vm.ctx.not_implemented(),
|
||||
Self::Implemented(v) => v.to_pyobject(vm),
|
||||
Self::NotImplemented => vm.ctx.not_implemented(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,7 +173,7 @@ impl TryFromObject for ArgAsciiBuffer {
|
||||
match obj.downcast::<PyStr>() {
|
||||
Ok(string) => {
|
||||
if string.as_str().is_ascii() {
|
||||
Ok(ArgAsciiBuffer::String(string))
|
||||
Ok(Self::String(string))
|
||||
} else {
|
||||
Err(vm.new_value_error("string argument should contain only ASCII characters"))
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ impl<A: AsRef<PyObject>, B: AsRef<PyObject>> AsRef<PyObject> for Either<A, B> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Into<PyObjectRef>, B: Into<PyObjectRef>> From<Either<A, B>> for PyObjectRef {
|
||||
impl<A: Into<Self>, B: Into<Self>> From<Either<A, B>> for PyObjectRef {
|
||||
#[inline(always)]
|
||||
fn from(value: Either<A, B>) -> Self {
|
||||
match value {
|
||||
|
||||
+10
-10
@@ -27,11 +27,11 @@ impl FsPath {
|
||||
let pathlike = match_class!(match obj {
|
||||
s @ PyStr => {
|
||||
check_nul(s.as_bytes())?;
|
||||
FsPath::Str(s)
|
||||
Self::Str(s)
|
||||
}
|
||||
b @ PyBytes => {
|
||||
check_nul(&b)?;
|
||||
FsPath::Bytes(b)
|
||||
Self::Bytes(b)
|
||||
}
|
||||
obj => return Ok(Err(obj)),
|
||||
});
|
||||
@@ -61,30 +61,30 @@ impl FsPath {
|
||||
pub fn as_os_str(&self, vm: &VirtualMachine) -> PyResult<Cow<'_, OsStr>> {
|
||||
// TODO: FS encodings
|
||||
match self {
|
||||
FsPath::Str(s) => vm.fsencode(s),
|
||||
FsPath::Bytes(b) => Self::bytes_as_os_str(b.as_bytes(), vm).map(Cow::Borrowed),
|
||||
Self::Str(s) => vm.fsencode(s),
|
||||
Self::Bytes(b) => Self::bytes_as_os_str(b.as_bytes(), vm).map(Cow::Borrowed),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_bytes(&self) -> &[u8] {
|
||||
// TODO: FS encodings
|
||||
match self {
|
||||
FsPath::Str(s) => s.as_bytes(),
|
||||
FsPath::Bytes(b) => b.as_bytes(),
|
||||
Self::Str(s) => s.as_bytes(),
|
||||
Self::Bytes(b) => b.as_bytes(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_string_lossy(&self) -> Cow<'_, str> {
|
||||
match self {
|
||||
FsPath::Str(s) => s.to_string_lossy(),
|
||||
FsPath::Bytes(s) => String::from_utf8_lossy(s),
|
||||
Self::Str(s) => s.to_string_lossy(),
|
||||
Self::Bytes(s) => String::from_utf8_lossy(s),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_path_buf(&self, vm: &VirtualMachine) -> PyResult<PathBuf> {
|
||||
let path = match self {
|
||||
FsPath::Str(s) => PathBuf::from(s.as_str()),
|
||||
FsPath::Bytes(b) => PathBuf::from(Self::bytes_as_os_str(b, vm)?),
|
||||
Self::Str(s) => PathBuf::from(s.as_str()),
|
||||
Self::Bytes(b) => PathBuf::from(Self::bytes_as_os_str(b, vm)?),
|
||||
};
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ impl TryFromObject for ArgIntoComplex {
|
||||
let (value, _) = obj.try_complex(vm)?.ok_or_else(|| {
|
||||
vm.new_type_error(format!("must be real number, not {}", obj.class().name()))
|
||||
})?;
|
||||
Ok(ArgIntoComplex { value })
|
||||
Ok(Self { value })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,7 +86,7 @@ impl TryFromObject for ArgIntoFloat {
|
||||
// Equivalent to PyFloat_AsDouble.
|
||||
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
|
||||
let value = obj.try_float(vm)?.to_f64();
|
||||
Ok(ArgIntoFloat { value })
|
||||
Ok(Self { value })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ impl AsRef<PyObject> for ArgCallable {
|
||||
|
||||
impl From<ArgCallable> for PyObjectRef {
|
||||
#[inline(always)]
|
||||
fn from(value: ArgCallable) -> PyObjectRef {
|
||||
fn from(value: ArgCallable) -> Self {
|
||||
value.obj
|
||||
}
|
||||
}
|
||||
@@ -63,7 +63,7 @@ impl TryFromObject for ArgCallable {
|
||||
);
|
||||
};
|
||||
let call = callable.call;
|
||||
Ok(ArgCallable { obj, call })
|
||||
Ok(Self { obj, call })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,7 +175,7 @@ impl Deref for ArgMapping {
|
||||
|
||||
impl From<ArgMapping> for PyObjectRef {
|
||||
#[inline(always)]
|
||||
fn from(value: ArgMapping) -> PyObjectRef {
|
||||
fn from(value: ArgMapping) -> Self {
|
||||
value.obj
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -311,7 +311,7 @@ impl MaybeInternedString for Py<PyStr> {
|
||||
#[inline(always)]
|
||||
fn as_interned(&self) -> Option<&'static PyStrInterned> {
|
||||
if self.as_object().is_interned() {
|
||||
Some(unsafe { std::mem::transmute::<&Py<PyStr>, &PyInterned<PyStr>>(self) })
|
||||
Some(unsafe { std::mem::transmute::<&Self, &PyInterned<PyStr>>(self) })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
|
||||
+12
-12
@@ -164,7 +164,7 @@ cfg_if::cfg_if! {
|
||||
|
||||
impl WeakRefList {
|
||||
pub fn new() -> Self {
|
||||
WeakRefList {
|
||||
Self {
|
||||
inner: OncePtr::new(),
|
||||
}
|
||||
}
|
||||
@@ -268,7 +268,7 @@ impl WeakRefList {
|
||||
(inner.ref_count == 0).then_some(ptr)
|
||||
};
|
||||
if let Some(ptr) = to_dealloc {
|
||||
unsafe { WeakRefList::dealloc(ptr) }
|
||||
unsafe { Self::dealloc(ptr) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -369,7 +369,7 @@ impl PyWeak {
|
||||
fn drop_inner(&self) {
|
||||
let dealloc = {
|
||||
let mut guard = unsafe { self.parent.as_ref().lock() };
|
||||
let offset = std::mem::offset_of!(PyInner<PyWeak>, payload);
|
||||
let offset = std::mem::offset_of!(PyInner<Self>, payload);
|
||||
let py_inner = (self as *const Self)
|
||||
.cast::<u8>()
|
||||
.wrapping_sub(offset)
|
||||
@@ -446,7 +446,7 @@ impl InstanceDict {
|
||||
impl<T: PyObjectPayload> PyInner<T> {
|
||||
fn new(payload: T, typ: PyTypeRef, dict: Option<PyDictRef>) -> Box<Self> {
|
||||
let member_count = typ.slots.member_count;
|
||||
Box::new(PyInner {
|
||||
Box::new(Self {
|
||||
ref_count: RefCount::new(),
|
||||
typeid: TypeId::of::<T>(),
|
||||
vtable: PyObjVTable::of::<T>(),
|
||||
@@ -546,7 +546,7 @@ impl PyObjectRef {
|
||||
if self.payload_is::<T>() {
|
||||
// SAFETY: just checked that the payload is T, and PyRef is repr(transparent) over
|
||||
// PyObjectRef
|
||||
Some(unsafe { &*(self as *const PyObjectRef as *const PyRef<T>) })
|
||||
Some(unsafe { &*(self as *const Self as *const PyRef<T>) })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
@@ -572,7 +572,7 @@ impl PyObjectRef {
|
||||
pub unsafe fn downcast_unchecked_ref<T: PyObjectPayload>(&self) -> &Py<T> {
|
||||
debug_assert!(self.payload_is::<T>());
|
||||
// SAFETY: requirements forwarded from caller
|
||||
unsafe { &*(self as *const PyObjectRef as *const PyRef<T>) }
|
||||
unsafe { &*(self as *const Self as *const PyRef<T>) }
|
||||
}
|
||||
|
||||
// ideally we'd be able to define these in pyobject.rs, but method visibility rules are weird
|
||||
@@ -758,7 +758,7 @@ impl PyObject {
|
||||
pub unsafe fn downcast_unchecked_ref<T: PyObjectPayload>(&self) -> &Py<T> {
|
||||
debug_assert!(self.payload_is::<T>());
|
||||
// SAFETY: requirements forwarded from caller
|
||||
unsafe { &*(self as *const PyObject as *const Py<T>) }
|
||||
unsafe { &*(self as *const Self as *const Py<T>) }
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
@@ -772,7 +772,7 @@ impl PyObject {
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub const fn as_raw(&self) -> *const PyObject {
|
||||
pub const fn as_raw(&self) -> *const Self {
|
||||
self
|
||||
}
|
||||
|
||||
@@ -819,7 +819,7 @@ impl PyObject {
|
||||
|
||||
/// Can only be called when ref_count has dropped to zero. `ptr` must be valid
|
||||
#[inline(never)]
|
||||
unsafe fn drop_slow(ptr: NonNull<PyObject>) {
|
||||
unsafe fn drop_slow(ptr: NonNull<Self>) {
|
||||
if let Err(()) = unsafe { ptr.as_ref().drop_slow_inner() } {
|
||||
// abort drop for whatever reason
|
||||
return;
|
||||
@@ -862,9 +862,9 @@ impl AsRef<PyObject> for PyObjectRef {
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<PyObject> for PyObject {
|
||||
impl AsRef<Self> for PyObject {
|
||||
#[inline(always)]
|
||||
fn as_ref(&self) -> &PyObject {
|
||||
fn as_ref(&self) -> &Self {
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -1084,7 +1084,7 @@ where
|
||||
#[inline]
|
||||
fn from(value: PyRef<T>) -> Self {
|
||||
let me = ManuallyDrop::new(value);
|
||||
PyObjectRef { ptr: me.ptr.cast() }
|
||||
Self { ptr: me.ptr.cast() }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -493,7 +493,7 @@ impl<T> AsObject for T where T: Borrow<PyObject> {}
|
||||
impl PyObject {
|
||||
#[inline(always)]
|
||||
fn unique_id(&self) -> usize {
|
||||
self as *const PyObject as usize
|
||||
self as *const Self as usize
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -144,8 +144,8 @@ unsafe impl<A: Traverse, B: Traverse> Traverse for Either<A, B> {
|
||||
#[inline]
|
||||
fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) {
|
||||
match self {
|
||||
Either::A(a) => a.traverse(tracer_fn),
|
||||
Either::B(b) => b.traverse(tracer_fn),
|
||||
Self::A(a) => a.traverse(tracer_fn),
|
||||
Self::B(b) => b.traverse(tracer_fn),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ pub(in crate::object) struct PyObjVTable {
|
||||
|
||||
impl PyObjVTable {
|
||||
pub const fn of<T: PyObjectPayload>() -> &'static Self {
|
||||
&PyObjVTable {
|
||||
&Self {
|
||||
drop_dealloc: drop_dealloc_obj::<T>,
|
||||
debug: debug_obj::<T>,
|
||||
trace: const {
|
||||
@@ -49,7 +49,7 @@ unsafe impl Traverse for PyInner<Erased> {
|
||||
|
||||
if let Some(f) = self.vtable.trace {
|
||||
unsafe {
|
||||
let zelf = &*(self as *const PyInner<Erased> as *const PyObject);
|
||||
let zelf = &*(self as *const Self as *const PyObject);
|
||||
f(zelf, tracer_fn)
|
||||
}
|
||||
};
|
||||
|
||||
+4
-4
@@ -44,13 +44,13 @@ impl OsPath {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn from_fspath(fspath: FsPath, vm: &VirtualMachine) -> PyResult<OsPath> {
|
||||
pub(crate) fn from_fspath(fspath: FsPath, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
let path = fspath.as_os_str(vm)?.into_owned();
|
||||
let mode = match fspath {
|
||||
FsPath::Str(_) => OutputMode::String,
|
||||
FsPath::Bytes(_) => OutputMode::Bytes,
|
||||
};
|
||||
Ok(OsPath { path, mode })
|
||||
Ok(Self { path, mode })
|
||||
}
|
||||
|
||||
pub fn as_path(&self) -> &Path {
|
||||
@@ -119,8 +119,8 @@ impl From<OsPath> for OsPathOrFd {
|
||||
impl OsPathOrFd {
|
||||
pub fn filename(&self, vm: &VirtualMachine) -> PyObjectRef {
|
||||
match self {
|
||||
OsPathOrFd::Path(path) => path.filename(vm),
|
||||
OsPathOrFd::Fd(fd) => vm.ctx.new_int(*fd).into(),
|
||||
Self::Path(path) => path.filename(vm),
|
||||
Self::Fd(fd) => vm.ctx.new_int(*fd).into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ impl PyBuffer {
|
||||
|
||||
pub fn from_byte_vector(bytes: Vec<u8>, vm: &VirtualMachine) -> Self {
|
||||
let bytes_len = bytes.len();
|
||||
PyBuffer::new(
|
||||
Self::new(
|
||||
PyPayload::into_pyobject(VecBuffer::from(bytes), vm),
|
||||
BufferDescriptor::simple(bytes_len, true),
|
||||
&VEC_BUFFER_METHODS,
|
||||
|
||||
@@ -76,8 +76,8 @@ impl PyIter<PyObjectRef> {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PyIter<PyObjectRef>> for PyObjectRef {
|
||||
fn from(value: PyIter<PyObjectRef>) -> PyObjectRef {
|
||||
impl From<PyIter<Self>> for PyObjectRef {
|
||||
fn from(value: PyIter<Self>) -> Self {
|
||||
value.0
|
||||
}
|
||||
}
|
||||
@@ -132,7 +132,7 @@ impl TryFromObject for PyIter<PyObjectRef> {
|
||||
};
|
||||
if let Some(get_iter) = get_iter {
|
||||
let iter = get_iter(iter_target, vm)?;
|
||||
if PyIter::check(&iter) {
|
||||
if Self::check(&iter) {
|
||||
Ok(Self(iter))
|
||||
} else {
|
||||
Err(vm.new_type_error(format!(
|
||||
@@ -160,8 +160,8 @@ pub enum PyIterReturn<T = PyObjectRef> {
|
||||
unsafe impl<T: Traverse> Traverse for PyIterReturn<T> {
|
||||
fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) {
|
||||
match self {
|
||||
PyIterReturn::Return(r) => r.traverse(tracer_fn),
|
||||
PyIterReturn::StopIteration(Some(obj)) => obj.traverse(tracer_fn),
|
||||
Self::Return(r) => r.traverse(tracer_fn),
|
||||
Self::StopIteration(Some(obj)) => obj.traverse(tracer_fn),
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ impl PyMappingMethods {
|
||||
}
|
||||
|
||||
#[allow(clippy::declare_interior_mutable_const)]
|
||||
pub const NOT_IMPLEMENTED: PyMappingMethods = PyMappingMethods {
|
||||
pub const NOT_IMPLEMENTED: Self = Self {
|
||||
length: AtomicCell::new(None),
|
||||
subscript: AtomicCell::new(None),
|
||||
ass_subscript: AtomicCell::new(None),
|
||||
|
||||
@@ -159,7 +159,7 @@ pub struct PyNumberMethods {
|
||||
|
||||
impl PyNumberMethods {
|
||||
/// this is NOT a global variable
|
||||
pub const NOT_IMPLEMENTED: PyNumberMethods = PyNumberMethods {
|
||||
pub const NOT_IMPLEMENTED: Self = Self {
|
||||
add: None,
|
||||
subtract: None,
|
||||
multiply: None,
|
||||
@@ -197,7 +197,7 @@ impl PyNumberMethods {
|
||||
inplace_matrix_multiply: None,
|
||||
};
|
||||
|
||||
pub fn not_implemented() -> &'static PyNumberMethods {
|
||||
pub fn not_implemented() -> &'static Self {
|
||||
static GLOBAL_NOT_IMPLEMENTED: PyNumberMethods = PyNumberMethods::NOT_IMPLEMENTED;
|
||||
&GLOBAL_NOT_IMPLEMENTED
|
||||
}
|
||||
|
||||
@@ -273,7 +273,7 @@ impl PyObject {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<Either<PyObjectRef, bool>> {
|
||||
let swapped = op.swapped();
|
||||
let call_cmp = |obj: &PyObject, other: &PyObject, op| {
|
||||
let call_cmp = |obj: &Self, other: &Self, op| {
|
||||
let cmp = obj
|
||||
.class()
|
||||
.mro_find_map(|cls| cls.slots.richcompare.load())
|
||||
@@ -409,7 +409,7 @@ impl PyObject {
|
||||
}
|
||||
}
|
||||
|
||||
fn abstract_issubclass(&self, cls: &PyObject, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
fn abstract_issubclass(&self, cls: &Self, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
// Store the current derived class to check
|
||||
let mut bases: PyTupleRef;
|
||||
let mut derived = self;
|
||||
@@ -457,7 +457,7 @@ impl PyObject {
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
fn recursive_issubclass(&self, cls: &PyObject, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
fn recursive_issubclass(&self, cls: &Self, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
// Fast path for both being types (matches CPython's PyType_Check)
|
||||
if let Some(cls) = PyType::check(cls)
|
||||
&& let Some(derived) = PyType::check(self)
|
||||
@@ -485,14 +485,14 @@ impl PyObject {
|
||||
|
||||
/// Real issubclass check without going through __subclasscheck__
|
||||
/// This is equivalent to CPython's _PyObject_RealIsSubclass which just calls recursive_issubclass
|
||||
pub fn real_is_subclass(&self, cls: &PyObject, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
pub fn real_is_subclass(&self, cls: &Self, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
self.recursive_issubclass(cls, vm)
|
||||
}
|
||||
|
||||
/// Determines if `self` is a subclass of `cls`, either directly, indirectly or virtually
|
||||
/// via the __subclasscheck__ magic method.
|
||||
/// PyObject_IsSubclass/object_issubclass
|
||||
pub fn is_subclass(&self, cls: &PyObject, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
pub fn is_subclass(&self, cls: &Self, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
let derived = self;
|
||||
// PyType_CheckExact(cls)
|
||||
if cls.class().is(vm.ctx.types.type_type) {
|
||||
@@ -536,13 +536,13 @@ impl PyObject {
|
||||
}
|
||||
|
||||
// _PyObject_RealIsInstance
|
||||
pub(crate) fn real_is_instance(&self, cls: &PyObject, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
pub(crate) fn real_is_instance(&self, cls: &Self, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
self.object_isinstance(cls, vm)
|
||||
}
|
||||
|
||||
/// Real isinstance check without going through __instancecheck__
|
||||
/// This is equivalent to CPython's _PyObject_RealIsInstance/object_isinstance
|
||||
fn object_isinstance(&self, cls: &PyObject, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
fn object_isinstance(&self, cls: &Self, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
if let Ok(cls) = cls.try_to_ref::<PyType>(vm) {
|
||||
// PyType_Check(cls) - cls is a type object
|
||||
let mut retval = self.class().is_subtype(cls);
|
||||
@@ -581,12 +581,12 @@ impl PyObject {
|
||||
|
||||
/// Determines if `self` is an instance of `cls`, either directly, indirectly or virtually via
|
||||
/// the __instancecheck__ magic method.
|
||||
pub fn is_instance(&self, cls: &PyObject, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
pub fn is_instance(&self, cls: &Self, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
self.object_recursive_isinstance(cls, vm)
|
||||
}
|
||||
|
||||
// This is object_recursive_isinstance from CPython's Objects/abstract.c
|
||||
fn object_recursive_isinstance(&self, cls: &PyObject, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
fn object_recursive_isinstance(&self, cls: &Self, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
// PyObject_TypeCheck(inst, (PyTypeObject *)cls)
|
||||
// This is an exact check of the type
|
||||
if self.class().is(cls) {
|
||||
|
||||
@@ -50,7 +50,7 @@ impl Debug for PySequenceMethods {
|
||||
|
||||
impl PySequenceMethods {
|
||||
#[allow(clippy::declare_interior_mutable_const)]
|
||||
pub const NOT_IMPLEMENTED: PySequenceMethods = PySequenceMethods {
|
||||
pub const NOT_IMPLEMENTED: Self = Self {
|
||||
length: AtomicCell::new(None),
|
||||
concat: AtomicCell::new(None),
|
||||
repeat: AtomicCell::new(None),
|
||||
|
||||
+1
-1
@@ -45,7 +45,7 @@ where
|
||||
impl Write for String {
|
||||
type Error = fmt::Error;
|
||||
fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
|
||||
<String as fmt::Write>::write_fmt(self, args)
|
||||
<Self as fmt::Write>::write_fmt(self, args)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+4
-4
@@ -16,22 +16,22 @@ impl fmt::Debug for Scope {
|
||||
|
||||
impl Scope {
|
||||
#[inline]
|
||||
pub fn new(locals: Option<ArgMapping>, globals: PyDictRef) -> Scope {
|
||||
pub fn new(locals: Option<ArgMapping>, globals: PyDictRef) -> Self {
|
||||
let locals = locals.unwrap_or_else(|| ArgMapping::from_dict_exact(globals.clone()));
|
||||
Scope { locals, globals }
|
||||
Self { locals, globals }
|
||||
}
|
||||
|
||||
pub fn with_builtins(
|
||||
locals: Option<ArgMapping>,
|
||||
globals: PyDictRef,
|
||||
vm: &VirtualMachine,
|
||||
) -> Scope {
|
||||
) -> Self {
|
||||
if !globals.contains_key("__builtins__", vm) {
|
||||
globals
|
||||
.set_item("__builtins__", vm.builtins.clone().into(), vm)
|
||||
.unwrap();
|
||||
}
|
||||
Scope::new(locals, globals)
|
||||
Self::new(locals, globals)
|
||||
}
|
||||
|
||||
// pub fn get_locals(&self) -> &PyDictRef {
|
||||
|
||||
+1
-1
@@ -139,7 +139,7 @@ where
|
||||
}
|
||||
|
||||
impl<T: Clone> SequenceMutExt<T> for Vec<T> {
|
||||
fn as_vec_mut(&mut self) -> &mut Vec<T> {
|
||||
fn as_vec_mut(&mut self) -> &mut Self {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user