clippy enum_glob_use (#8121)

This commit is contained in:
Shahar Naveh authored and GitHub committed 2026-06-17 13:24:36 +09:00
1 parent 697a441e70
commit 11da0b42c3
20 files changed
+319 -303

No files matched your search

+1
View File
@@ -387,6 +387,7 @@ cloned_instead_of_copied = "warn"
collapsible_else_if = "warn"
comparison_chain = "warn"
duration_suboptimal_units = "warn"
enum_glob_use = "warn"
explicit_deref_methods = "warn"
explicit_into_iter_loop = "warn"
explicit_iter_loop = "warn"
+26 -7
View File
@@ -7005,23 +7005,42 @@ impl Compiler {
/// [CPython `compiler_addcompare`](https://github.com/python/cpython/blob/627894459a84be3488a1789919679c997056a03c/Python/compile.c#L2880-L2924)
fn compile_addcompare(&mut self, op: &ast::CmpOp) {
use bytecode::ComparisonOperator::*;
match op {
ast::CmpOp::Eq => emit!(self, Instruction::CompareOp { opname: Equal }),
ast::CmpOp::NotEq => emit!(self, Instruction::CompareOp { opname: NotEqual }),
ast::CmpOp::Lt => emit!(self, Instruction::CompareOp { opname: Less }),
ast::CmpOp::Eq => emit!(
self,
Instruction::CompareOp {
opname: ComparisonOperator::Equal
}
),
ast::CmpOp::NotEq => emit!(
self,
Instruction::CompareOp {
opname: ComparisonOperator::NotEqual
}
),
ast::CmpOp::Lt => emit!(
self,
Instruction::CompareOp {
opname: ComparisonOperator::Less
}
),
ast::CmpOp::LtE => emit!(
self,
Instruction::CompareOp {
opname: LessOrEqual
opname: ComparisonOperator::LessOrEqual
}
),
ast::CmpOp::Gt => emit!(
self,
Instruction::CompareOp {
opname: ComparisonOperator::Greater
}
),
ast::CmpOp::Gt => emit!(self, Instruction::CompareOp { opname: Greater }),
ast::CmpOp::GtE => {
emit!(
self,
Instruction::CompareOp {
opname: GreaterOrEqual
opname: ComparisonOperator::GreaterOrEqual
}
)
}
+10 -9
View File
@@ -2568,16 +2568,15 @@ impl SymbolTableBuilder {
}
fn scan_pattern(&mut self, pattern: &ast::Pattern) -> SymbolTableResult {
use ast::Pattern::*;
match pattern {
MatchValue(ast::PatternMatchValue { value, .. }) => {
ast::Pattern::MatchValue(ast::PatternMatchValue { value, .. }) => {
self.scan_expression(value, ExpressionContext::Load)?
}
MatchSingleton(_) => {}
MatchSequence(ast::PatternMatchSequence { patterns, .. }) => {
ast::Pattern::MatchSingleton(_) => {}
ast::Pattern::MatchSequence(ast::PatternMatchSequence { patterns, .. }) => {
self.scan_patterns(patterns)?
}
MatchMapping(ast::PatternMatchMapping {
ast::Pattern::MatchMapping(ast::PatternMatchMapping {
keys,
patterns,
rest,
@@ -2589,19 +2588,19 @@ impl SymbolTableBuilder {
self.register_ident(rest, SymbolUsage::Assigned)?;
}
}
MatchClass(ast::PatternMatchClass { cls, arguments, .. }) => {
ast::Pattern::MatchClass(ast::PatternMatchClass { cls, arguments, .. }) => {
self.scan_expression(cls, ExpressionContext::Load)?;
self.scan_patterns(&arguments.patterns)?;
for kw in &arguments.keywords {
self.scan_pattern(&kw.pattern)?;
}
}
MatchStar(ast::PatternMatchStar { name, .. }) => {
ast::Pattern::MatchStar(ast::PatternMatchStar { name, .. }) => {
if let Some(name) = name {
self.register_ident(name, SymbolUsage::Assigned)?;
}
}
MatchAs(ast::PatternMatchAs { pattern, name, .. }) => {
ast::Pattern::MatchAs(ast::PatternMatchAs { pattern, name, .. }) => {
if let Some(pattern) = pattern {
self.scan_pattern(pattern)?;
}
@@ -2609,7 +2608,9 @@ impl SymbolTableBuilder {
self.register_ident(name, SymbolUsage::Assigned)?;
}
}
MatchOr(ast::PatternMatchOr { patterns, .. }) => self.scan_patterns(patterns)?,
ast::Pattern::MatchOr(ast::PatternMatchOr { patterns, .. }) => {
self.scan_patterns(patterns)?
}
}
Ok(())
}
+31 -34
View File
@@ -35,18 +35,17 @@ pub struct CFormatError {
impl fmt::Display for CFormatError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use CFormatErrorType::*;
match self.typ {
UnmatchedKeyParentheses => write!(f, "incomplete format key"),
IncompleteFormat => write!(f, "incomplete format"),
UnsupportedFormatChar(c) => write!(
CFormatErrorType::UnmatchedKeyParentheses => write!(f, "incomplete format key"),
CFormatErrorType::IncompleteFormat => write!(f, "incomplete format"),
CFormatErrorType::UnsupportedFormatChar(c) => write!(
f,
"unsupported format character '{}' ({:#x}) at index {}",
c,
c.to_u32(),
self.index
),
IntTooBig => write!(f, "width/precision too big"),
CFormatErrorType::IntTooBig => write!(f, "width/precision too big"),
_ => write!(f, "unexpected error parsing format string"),
}
}
@@ -78,11 +77,9 @@ pub enum CFloatType {
impl CFloatType {
const fn case(self) -> Case {
use CFloatType::*;
match self {
ExponentLower | PointDecimalLower | GeneralLower => Case::Lower,
ExponentUpper | PointDecimalUpper | GeneralUpper => Case::Upper,
Self::ExponentLower | Self::PointDecimalLower | Self::GeneralLower => Case::Lower,
Self::ExponentUpper | Self::PointDecimalUpper | Self::GeneralUpper => Case::Upper,
}
}
}
@@ -443,16 +440,16 @@ impl CFormatSpec {
#[must_use]
pub fn format_number(&self, num: &BigInt) -> String {
use CNumberType::*;
let CFormatType::Number(format_type) = self.format_type else {
unreachable!()
};
let magnitude = num.abs();
let prefix = if self.flags.contains(CConversionFlags::ALTERNATE_FORM) {
match format_type {
Octal => "0o",
HexLower => "0x",
HexUpper => "0X",
CNumberType::Octal => "0o",
CNumberType::HexLower => "0x",
CNumberType::HexUpper => "0X",
_ => "",
}
} else {
@@ -460,10 +457,12 @@ impl CFormatSpec {
};
let magnitude_string: String = match format_type {
DecimalD | DecimalI | DecimalU => magnitude.to_str_radix(10),
Octal => magnitude.to_str_radix(8),
HexLower => magnitude.to_str_radix(16),
HexUpper => {
CNumberType::DecimalD | CNumberType::DecimalI | CNumberType::DecimalU => {
magnitude.to_str_radix(10)
}
CNumberType::Octal => magnitude.to_str_radix(8),
CNumberType::HexLower => magnitude.to_str_radix(16),
CNumberType::HexUpper => {
let mut result = magnitude.to_str_radix(16);
result.make_ascii_uppercase();
result
@@ -621,35 +620,33 @@ where
C: FormatChar,
I: Iterator<Item = C>,
{
use CFloatType::*;
use CNumberType::*;
let (index, c) = iter.next().ok_or_else(|| {
(
CFormatErrorType::IncompleteFormat,
iter.peek().map_or(0, |x| x.0),
)
})?;
let format_type = match c.to_char_lossy() {
'd' => CFormatType::Number(DecimalD),
'i' => CFormatType::Number(DecimalI),
'u' => CFormatType::Number(DecimalU),
'o' => CFormatType::Number(Octal),
'x' => CFormatType::Number(HexLower),
'X' => CFormatType::Number(HexUpper),
'e' => CFormatType::Float(ExponentLower),
'E' => CFormatType::Float(ExponentUpper),
'f' => CFormatType::Float(PointDecimalLower),
'F' => CFormatType::Float(PointDecimalUpper),
'g' => CFormatType::Float(GeneralLower),
'G' => CFormatType::Float(GeneralUpper),
Ok(match c.to_char_lossy() {
'd' => CFormatType::Number(CNumberType::DecimalD),
'i' => CFormatType::Number(CNumberType::DecimalI),
'u' => CFormatType::Number(CNumberType::DecimalU),
'o' => CFormatType::Number(CNumberType::Octal),
'x' => CFormatType::Number(CNumberType::HexLower),
'X' => CFormatType::Number(CNumberType::HexUpper),
'e' => CFormatType::Float(CFloatType::ExponentLower),
'E' => CFormatType::Float(CFloatType::ExponentUpper),
'f' => CFormatType::Float(CFloatType::PointDecimalLower),
'F' => CFormatType::Float(CFloatType::PointDecimalUpper),
'g' => CFormatType::Float(CFloatType::GeneralLower),
'G' => CFormatType::Float(CFloatType::GeneralUpper),
'c' => CFormatType::Character(CCharacterType::Character),
'r' => CFormatType::String(CFormatConversion::Repr),
's' => CFormatType::String(CFormatConversion::Str),
'b' => CFormatType::String(CFormatConversion::Bytes),
'a' => CFormatType::String(CFormatConversion::Ascii),
_ => return Err((CFormatErrorType::UnsupportedFormatChar(c.into()), index)),
};
Ok(format_type)
})
}
fn parse_quantity<C, I>(iter: &mut ParseIter<I>) -> Result<Option<CFormatQuantity>, ParsingError>
+3 -4
View File
@@ -25,11 +25,10 @@ impl core::ops::BitOr for StrKind {
type Output = Self;
fn bitor(self, other: Self) -> Self {
use StrKind::*;
match (self, other) {
(Wtf8, _) | (_, Wtf8) => Wtf8,
(Utf8, _) | (_, Utf8) => Utf8,
(Ascii, Ascii) => Ascii,
(Self::Wtf8, _) | (_, Self::Wtf8) => Self::Wtf8,
(Self::Utf8, _) | (_, Self::Utf8) => Self::Utf8,
(Self::Ascii, Self::Ascii) => Self::Ascii,
}
}
}
+51 -56
View File
@@ -293,21 +293,19 @@ impl Constant for ConstantData {
type Name = String;
fn borrow_constant(&self) -> BorrowedConstant<'_, Self> {
use BorrowedConstant::*;
match self {
Self::Integer { value } => Integer { value },
Self::Float { value } => Float { value: *value },
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::Slice { elements } => Slice { elements },
Self::Frozenset { elements } => Frozenset { elements },
Self::None => None,
Self::Ellipsis => Ellipsis,
Self::Integer { value } => BorrowedConstant::Integer { value },
Self::Float { value } => BorrowedConstant::Float { value: *value },
Self::Complex { value } => BorrowedConstant::Complex { value: *value },
Self::Boolean { value } => BorrowedConstant::Boolean { value: *value },
Self::Str { value } => BorrowedConstant::Str { value },
Self::Bytes { value } => BorrowedConstant::Bytes { value },
Self::Code { code } => BorrowedConstant::Code { code },
Self::Tuple { elements } => BorrowedConstant::Tuple { elements },
Self::Slice { elements } => BorrowedConstant::Slice { elements },
Self::Frozenset { elements } => BorrowedConstant::Frozenset { elements },
Self::None => BorrowedConstant::None,
Self::Ellipsis => BorrowedConstant::Ellipsis,
}
}
}
@@ -913,23 +911,23 @@ pub enum ConstantData {
impl PartialEq for ConstantData {
fn eq(&self, other: &Self) -> bool {
use ConstantData::*;
match (self, other) {
(Integer { value: a }, Integer { value: b }) => a == b,
(Float { value: a }, Float { value: b }) => a.to_bits() == b.to_bits(),
(Complex { value: a }, Complex { value: b }) => {
(Self::Integer { value: a }, Self::Integer { value: b }) => a == b,
(Self::Float { value: a }, Self::Float { value: b }) => a.to_bits() == b.to_bits(),
(Self::Complex { value: a }, Self::Complex { value: b }) => {
a.re.to_bits() == b.re.to_bits() && a.im.to_bits() == b.im.to_bits()
}
(Boolean { value: a }, Boolean { value: b }) => a == b,
(Str { value: a }, Str { value: b }) => a == b,
(Bytes { value: a }, Bytes { value: b }) => a == b,
(Code { code: a }, Code { code: b }) => core::ptr::eq(a.as_ref(), b.as_ref()),
(Tuple { elements: a }, Tuple { elements: b }) => a == b,
(Slice { elements: a }, Slice { elements: b }) => a == b,
(Frozenset { elements: a }, Frozenset { elements: b }) => a == b,
(None, None) => true,
(Ellipsis, Ellipsis) => true,
(Self::Boolean { value: a }, Self::Boolean { value: b }) => a == b,
(Self::Str { value: a }, Self::Str { value: b }) => a == b,
(Self::Bytes { value: a }, Self::Bytes { value: b }) => a == b,
(Self::Code { code: a }, Self::Code { code: b }) => {
core::ptr::eq(a.as_ref(), b.as_ref())
}
(Self::Tuple { elements: a }, Self::Tuple { elements: b }) => a == b,
(Self::Slice { elements: a }, Self::Slice { elements: b }) => a == b,
(Self::Frozenset { elements: a }, Self::Frozenset { elements: b }) => a == b,
(Self::None, Self::None) => true,
(Self::Ellipsis, Self::Ellipsis) => true,
_ => false,
}
}
@@ -939,25 +937,24 @@ impl Eq for ConstantData {}
impl hash::Hash for ConstantData {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
use ConstantData::*;
mem::discriminant(self).hash(state);
match self {
Integer { value } => value.hash(state),
Float { value } => value.to_bits().hash(state),
Complex { value } => {
Self::Integer { value } => value.hash(state),
Self::Float { value } => value.to_bits().hash(state),
Self::Complex { value } => {
value.re.to_bits().hash(state);
value.im.to_bits().hash(state);
}
Boolean { value } => value.hash(state),
Str { value } => value.hash(state),
Bytes { value } => value.hash(state),
Code { code } => core::ptr::hash(code.as_ref(), state),
Tuple { elements } => elements.hash(state),
Slice { elements } => elements.hash(state),
Frozenset { elements } => elements.hash(state),
None => {}
Ellipsis => {}
Self::Boolean { value } => value.hash(state),
Self::Str { value } => value.hash(state),
Self::Bytes { value } => value.hash(state),
Self::Code { code } => core::ptr::hash(code.as_ref(), state),
Self::Tuple { elements } => elements.hash(state),
Self::Slice { elements } => elements.hash(state),
Self::Frozenset { elements } => elements.hash(state),
Self::None => {}
Self::Ellipsis => {}
}
}
}
@@ -1040,41 +1037,39 @@ impl<C: Constant> BorrowedConstant<'_, C> {
#[must_use]
pub fn to_owned(self) -> ConstantData {
use ConstantData::*;
match self {
BorrowedConstant::Integer { value } => Integer {
BorrowedConstant::Integer { value } => ConstantData::Integer {
value: value.clone(),
},
BorrowedConstant::Float { value } => Float { value },
BorrowedConstant::Complex { value } => Complex { value },
BorrowedConstant::Boolean { value } => Boolean { value },
BorrowedConstant::Str { value } => Str {
BorrowedConstant::Float { value } => ConstantData::Float { value },
BorrowedConstant::Complex { value } => ConstantData::Complex { value },
BorrowedConstant::Boolean { value } => ConstantData::Boolean { value },
BorrowedConstant::Str { value } => ConstantData::Str {
value: value.to_owned(),
},
BorrowedConstant::Bytes { value } => Bytes {
BorrowedConstant::Bytes { value } => ConstantData::Bytes {
value: value.to_owned(),
},
BorrowedConstant::Code { code } => Code {
BorrowedConstant::Code { code } => ConstantData::Code {
code: Box::new(code.map_clone_bag(&BasicBag)),
},
BorrowedConstant::Tuple { elements } => Tuple {
BorrowedConstant::Tuple { elements } => ConstantData::Tuple {
elements: elements
.iter()
.map(|c| c.borrow_constant().to_owned())
.collect(),
},
BorrowedConstant::Slice { elements } => Slice {
BorrowedConstant::Slice { elements } => ConstantData::Slice {
elements: Box::new(elements.each_ref().map(|c| c.borrow_constant().to_owned())),
},
BorrowedConstant::Frozenset { elements } => Frozenset {
BorrowedConstant::Frozenset { elements } => ConstantData::Frozenset {
elements: elements
.iter()
.map(|c| c.borrow_constant().to_owned())
.collect(),
},
BorrowedConstant::None => None,
BorrowedConstant::Ellipsis => Ellipsis,
BorrowedConstant::None => ConstantData::None,
BorrowedConstant::Ellipsis => ConstantData::Ellipsis,
}
}
}
+29 -30
View File
@@ -81,37 +81,36 @@ impl TryFrom<u8> for Type {
type Error = MarshalError;
fn try_from(value: u8) -> Result<Self> {
use Type::*;
Ok(match value {
b'0' => Null,
b'N' => None,
b'F' => False,
b'T' => True,
b'S' => StopIter,
b'.' => Ellipsis,
b'i' => Int,
b'I' => Int64,
b'l' => Long,
b'f' => FloatStr,
b'g' => Float,
b'x' => ComplexStr,
b'y' => Complex,
b's' => Bytes,
b't' => Interned,
b'r' => Ref,
b'(' => Tuple,
b')' => SmallTuple,
b'[' => List,
b'{' => Dict,
b'c' => Code,
b'u' => Unicode,
b'<' => Set,
b'>' => FrozenSet,
b':' => Slice,
b'a' => Ascii,
b'A' => AsciiInterned,
b'z' => ShortAscii,
b'Z' => ShortAsciiInterned,
b'0' => Self::Null,
b'N' => Self::None,
b'F' => Self::False,
b'T' => Self::True,
b'S' => Self::StopIter,
b'.' => Self::Ellipsis,
b'i' => Self::Int,
b'I' => Self::Int64,
b'l' => Self::Long,
b'f' => Self::FloatStr,
b'g' => Self::Float,
b'x' => Self::ComplexStr,
b'y' => Self::Complex,
b's' => Self::Bytes,
b't' => Self::Interned,
b'r' => Self::Ref,
b'(' => Self::Tuple,
b')' => Self::SmallTuple,
b'[' => Self::List,
b'{' => Self::Dict,
b'c' => Self::Code,
b'u' => Self::Unicode,
b'<' => Self::Set,
b'>' => Self::FrozenSet,
b':' => Self::Slice,
b'a' => Self::Ascii,
b'A' => Self::AsciiInterned,
b'z' => Self::ShortAscii,
b'Z' => Self::ShortAsciiInterned,
_ => return Err(MarshalError::BadType),
})
}
+10 -9
View File
@@ -1949,24 +1949,25 @@ fn impl_item_new<Item>(
where
Item: ItemLike + ToTokens + GetIdent,
{
use AttrName::*;
match attr_name {
attr_name @ (Method | ClassMethod | StaticMethod) => Box::new(MethodItem {
attr_name @ (AttrName::Method | AttrName::ClassMethod | AttrName::StaticMethod) => {
Box::new(MethodItem {
inner: ContentItemInner { index, attr_name },
})
}
AttrName::GetSet => Box::new(GetSetItem {
inner: ContentItemInner { index, attr_name },
}),
GetSet => Box::new(GetSetItem {
AttrName::Slot => Box::new(SlotItem {
inner: ContentItemInner { index, attr_name },
}),
Slot => Box::new(SlotItem {
AttrName::Attr => Box::new(AttributeItem {
inner: ContentItemInner { index, attr_name },
}),
Attr => Box::new(AttributeItem {
AttrName::ExtendClass => Box::new(ExtendClassItem {
inner: ContentItemInner { index, attr_name },
}),
ExtendClass => Box::new(ExtendClassItem {
inner: ContentItemInner { index, attr_name },
}),
Member => Box::new(MemberItem {
AttrName::Member => Box::new(MemberItem {
inner: ContentItemInner { index, attr_name },
}),
}
+9 -12
View File
@@ -2,7 +2,7 @@ use itertools::Itertools;
use proc_macro2::{Span, TokenStream};
use quote::{ToTokens, quote};
use std::collections::{HashMap, HashSet};
use syn::{Attribute, Ident, Result, Signature, UseTree, spanned::Spanned};
use syn::{Attribute, FnArg, Ident, Result, Signature, UseTree, spanned::Spanned};
use syn_ext::{
ext::{AttributeExt as SynAttributeExt, *},
types::*,
@@ -609,11 +609,10 @@ impl AttributeExt for Attribute {
}
pub(crate) fn pyclass_ident_and_attrs(item: &syn::Item) -> Result<(&Ident, &[Attribute])> {
use syn::Item::*;
Ok(match item {
Struct(syn::ItemStruct { ident, attrs, .. }) => (ident, attrs),
Enum(syn::ItemEnum { ident, attrs, .. }) => (ident, attrs),
Use(item_use) => (
syn::Item::Struct(syn::ItemStruct { ident, attrs, .. }) => (ident, attrs),
syn::Item::Enum(syn::ItemEnum { ident, attrs, .. }) => (ident, attrs),
syn::Item::Use(item_use) => (
iter_use_idents(item_use, |ident, _is_unique| Ok(ident))?
.into_iter()
.exactly_one()
@@ -635,10 +634,9 @@ pub(crate) fn pyclass_ident_and_attrs(item: &syn::Item) -> Result<(&Ident, &[Att
}
pub(crate) fn pyexception_ident_and_attrs(item: &syn::Item) -> Result<(&Ident, &[Attribute])> {
use syn::Item::*;
Ok(match item {
Struct(syn::ItemStruct { ident, attrs, .. }) => (ident, attrs),
Enum(syn::ItemEnum { ident, attrs, .. }) => (ident, attrs),
syn::Item::Struct(syn::ItemStruct { ident, attrs, .. }) => (ident, attrs),
syn::Item::Enum(syn::ItemEnum { ident, attrs, .. }) => (ident, attrs),
other => {
bail_span!(other, "#[pyexception] can only be on a struct or enum",)
}
@@ -741,7 +739,7 @@ pub(crate) fn infer_native_call_flags(sig: &Signature, drop_first_typed: usize)
// METH_* calling convention flags used by CALL specialization.
let mut typed_args = Vec::new();
for arg in &sig.inputs {
let syn::FnArg::Typed(typed) = arg else {
let FnArg::Typed(typed) = arg else {
continue;
};
let ty_tokens = &typed.ty;
@@ -811,10 +809,9 @@ fn func_sig(sig: &Signature) -> String {
sig.inputs
.iter()
.filter_map(|arg| {
use syn::FnArg::*;
let arg = match arg {
Typed(typed) => typed,
Receiver(_) => return Some("$self".to_owned()),
FnArg::Typed(typed) => typed,
FnArg::Receiver(_) => return Some("$self".to_owned()),
};
let ty = arg.ty.as_ref();
let ty = quote!(#ty).to_string();
+14 -9
View File
@@ -1448,16 +1448,21 @@ pub mod array {
impl From<MachineFormatCode> for u8 {
fn from(code: MachineFormatCode) -> Self {
use MachineFormatCode::*;
match code {
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,
MachineFormatCode::Int8 { signed } => signed as Self,
MachineFormatCode::Int16 { signed, big_endian } => {
2 + signed as Self * 2 + big_endian as Self
}
MachineFormatCode::Int32 { signed, big_endian } => {
6 + signed as Self * 2 + big_endian as Self
}
MachineFormatCode::Int64 { signed, big_endian } => {
10 + signed as Self * 2 + big_endian as Self
}
MachineFormatCode::Ieee754Float { big_endian } => 14 + big_endian as Self,
MachineFormatCode::Ieee754Double { big_endian } => 16 + big_endian as Self,
MachineFormatCode::Utf16 { big_endian } => 18 + big_endian as Self,
MachineFormatCode::Utf32 { big_endian } => 20 + big_endian as Self,
}
}
}
+9 -8
View File
@@ -849,20 +849,21 @@ fn new_binascii_error<T: Into<Wtf8Buf>>(msg: T, vm: &VirtualMachine) -> PyBaseEx
impl ToPyException for Base64DecodeError {
fn to_pyexception(&self, vm: &VirtualMachine) -> PyBaseExceptionRef {
use base64::DecodeError::*;
use base64::DecodeError;
let message = match &self.0 {
InvalidByte(0, PAD) => "Leading padding not allowed".to_owned(),
InvalidByte(_, PAD) => "Discontinuous padding not allowed".to_owned(),
InvalidByte(_, _) => "Only base64 data is allowed".to_owned(),
InvalidLastSymbol(_, PAD) => "Excess data after padding".to_owned(),
InvalidLastSymbol(length, _) => {
DecodeError::InvalidByte(0, PAD) => "Leading padding not allowed".to_owned(),
DecodeError::InvalidByte(_, PAD) => "Discontinuous padding not allowed".to_owned(),
DecodeError::InvalidByte(_, _) => "Only base64 data is allowed".to_owned(),
DecodeError::InvalidLastSymbol(_, PAD) => "Excess data after padding".to_owned(),
DecodeError::InvalidLastSymbol(length, _) => {
format!(
"Invalid base64-encoded string: number of data characters {length} cannot be 1 more than a multiple of 4"
)
}
// TODO: clean up errors
InvalidLength(_) => "Incorrect padding".to_owned(),
InvalidPadding => "Incorrect padding".to_owned(),
DecodeError::InvalidLength(_) => "Incorrect padding".to_owned(),
DecodeError::InvalidPadding => "Incorrect padding".to_owned(),
};
new_binascii_error(format!("error decoding base64: {message}"), vm)
}
+9 -9
View File
@@ -162,7 +162,7 @@ mod unicodedata {
use super::{
BIDI_CLASS, BIDI_MIRRORED, COMBINING_CLASS, DECOMP_COMPAT, DECOMP_RANGE, DECOMP_UPDATES,
EAST_ASIAN_WIDTH, GENERAL_CATEGORY, NUMERIC_TYPE_DIFF, NormalizeForm::*, UNICODE_VERSION,
EAST_ASIAN_WIDTH, GENERAL_CATEGORY, NUMERIC_TYPE_DIFF, NormalizeForm, UNICODE_VERSION,
UnicodeVersion, lookup_numeric_val, lookup_property,
};
use crate::vm::{
@@ -337,22 +337,22 @@ mod unicodedata {
fn normalize(&self, form: super::NormalizeForm, unistr: PyStrRef) -> Wtf8Buf {
let text = unistr.as_wtf8();
match form {
Nfc => {
NormalizeForm::Nfc => {
let normalizer = ComposingNormalizerBorrowed::new_nfc();
text.map_utf8(|s| normalizer.normalize_iter(s.chars()))
.collect()
}
Nfkc => {
NormalizeForm::Nfkc => {
let normalizer = ComposingNormalizerBorrowed::new_nfkc();
text.map_utf8(|s| normalizer.normalize_iter(s.chars()))
.collect()
}
Nfd => {
NormalizeForm::Nfd => {
let normalizer = DecomposingNormalizerBorrowed::new_nfd();
text.map_utf8(|s| normalizer.normalize_iter(s.chars()))
.collect()
}
Nfkd => {
NormalizeForm::Nfkd => {
let normalizer = DecomposingNormalizerBorrowed::new_nfkd();
text.map_utf8(|s| normalizer.normalize_iter(s.chars()))
.collect()
@@ -364,22 +364,22 @@ mod unicodedata {
fn is_normalized(&self, form: super::NormalizeForm, unistr: PyStrRef) -> bool {
let text = unistr.as_wtf8();
let normalized: Wtf8Buf = match form {
Nfc => {
NormalizeForm::Nfc => {
let normalizer = ComposingNormalizerBorrowed::new_nfc();
text.map_utf8(|s| normalizer.normalize_iter(s.chars()))
.collect()
}
Nfkc => {
NormalizeForm::Nfkc => {
let normalizer = ComposingNormalizerBorrowed::new_nfkc();
text.map_utf8(|s| normalizer.normalize_iter(s.chars()))
.collect()
}
Nfd => {
NormalizeForm::Nfd => {
let normalizer = DecomposingNormalizerBorrowed::new_nfd();
text.map_utf8(|s| normalizer.normalize_iter(s.chars()))
.collect()
}
Nfkd => {
NormalizeForm::Nfkd => {
let normalizer = DecomposingNormalizerBorrowed::new_nfkd();
text.map_utf8(|s| normalizer.normalize_iter(s.chars()))
.collect()
+39 -40
View File
@@ -112,7 +112,6 @@ impl fmt::Debug for FormatType {
impl FormatType {
fn info(self, e: Endianness) -> &'static FormatInfo {
use FormatType::*;
use mem::{align_of, size_of};
macro_rules! native_info {
@@ -140,71 +139,71 @@ impl FormatType {
macro_rules! match_nonnative {
($zelf:expr, $end:ty) => {{
match $zelf {
Pad | Str | Pascal => &FormatInfo {
Self::Pad | Self::Str | Self::Pascal => &FormatInfo {
size: size_of::<u8>(),
align: 0,
pack: None,
unpack: None,
},
SByte => nonnative_info!(i8, $end),
UByte => nonnative_info!(u8, $end),
Char => &FormatInfo {
Self::SByte => nonnative_info!(i8, $end),
Self::UByte => nonnative_info!(u8, $end),
Self::Char => &FormatInfo {
size: size_of::<u8>(),
align: 0,
pack: Some(pack_char),
unpack: Some(unpack_char),
},
Short => nonnative_info!(i16, $end),
UShort => nonnative_info!(u16, $end),
Int | Long => nonnative_info!(i32, $end),
UInt | ULong => nonnative_info!(u32, $end),
LongLong => nonnative_info!(i64, $end),
ULongLong => nonnative_info!(u64, $end),
Bool => nonnative_info!(bool, $end),
Half => nonnative_info!(f16, $end),
Float => nonnative_info!(f32, $end),
Double => nonnative_info!(f64, $end),
LongDouble => nonnative_info!(f64, $end), // long double same as double
PyObject => nonnative_info!(usize, $end), // pointer size
_ => unreachable!(), // size_t or void*
Self::Short => nonnative_info!(i16, $end),
Self::UShort => nonnative_info!(u16, $end),
Self::Int | Self::Long => nonnative_info!(i32, $end),
Self::UInt | Self::ULong => nonnative_info!(u32, $end),
Self::LongLong => nonnative_info!(i64, $end),
Self::ULongLong => nonnative_info!(u64, $end),
Self::Bool => nonnative_info!(bool, $end),
Self::Half => nonnative_info!(f16, $end),
Self::Float => nonnative_info!(f32, $end),
Self::Double => nonnative_info!(f64, $end),
Self::LongDouble => nonnative_info!(f64, $end), // long double same as double
Self::PyObject => nonnative_info!(usize, $end), // pointer size
_ => unreachable!(), // size_t or void*
}
}};
}
match e {
Endianness::Native => match self {
Pad | Str | Pascal => &FormatInfo {
Self::Pad | Self::Str | Self::Pascal => &FormatInfo {
size: size_of::<raw::c_char>(),
align: 0,
pack: None,
unpack: None,
},
SByte => native_info!(raw::c_schar),
UByte => native_info!(raw::c_uchar),
Char => &FormatInfo {
Self::SByte => native_info!(raw::c_schar),
Self::UByte => native_info!(raw::c_uchar),
Self::Char => &FormatInfo {
size: size_of::<raw::c_char>(),
align: 0,
pack: Some(pack_char),
unpack: Some(unpack_char),
},
WideChar => native_info!(wchar_t),
Short => native_info!(raw::c_short),
UShort => native_info!(raw::c_ushort),
Int => native_info!(raw::c_int),
UInt => native_info!(raw::c_uint),
Long => native_info!(raw::c_long),
ULong => native_info!(raw::c_ulong),
SSizeT => native_info!(isize), // ssize_t == isize
SizeT => native_info!(usize), // size_t == usize
LongLong => native_info!(raw::c_longlong),
ULongLong => native_info!(raw::c_ulonglong),
Bool => native_info!(bool),
Half => native_info!(f16),
Float => native_info!(raw::c_float),
Double => native_info!(raw::c_double),
LongDouble => native_info!(raw::c_double), // long double same as double for now
VoidP => native_info!(*mut raw::c_void),
PyObject => native_info!(*mut raw::c_void), // pointer to PyObject
Self::WideChar => native_info!(wchar_t),
Self::Short => native_info!(raw::c_short),
Self::UShort => native_info!(raw::c_ushort),
Self::Int => native_info!(raw::c_int),
Self::UInt => native_info!(raw::c_uint),
Self::Long => native_info!(raw::c_long),
Self::ULong => native_info!(raw::c_ulong),
Self::SSizeT => native_info!(isize), // ssize_t == isize
Self::SizeT => native_info!(usize), // size_t == usize
Self::LongLong => native_info!(raw::c_longlong),
Self::ULongLong => native_info!(raw::c_ulonglong),
Self::Bool => native_info!(bool),
Self::Half => native_info!(f16),
Self::Float => native_info!(raw::c_float),
Self::Double => native_info!(raw::c_double),
Self::LongDouble => native_info!(raw::c_double), // long double same as double for now
Self::VoidP => native_info!(*mut raw::c_void),
Self::PyObject => native_info!(*mut raw::c_void), // pointer to PyObject
},
Endianness::Big => match_nonnative!(self, BigEndian),
Endianness::Little => match_nonnative!(self, LittleEndian),
+6 -8
View File
@@ -15,9 +15,7 @@ use crate::{
class::{PyClassDef, PyClassImpl},
common::ascii,
dict_inner::{self, DictKey},
function::{
ArgIterable, FuncArgs, KwArgs, OptionalArg, PyArithmeticValue::*, PyComparisonValue,
},
function::{ArgIterable, FuncArgs, KwArgs, OptionalArg, PyArithmeticValue, PyComparisonValue},
iter::PyExactSizeIterator,
protocol::{PyIterIter, PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods},
recursion::ReprGuard,
@@ -478,7 +476,7 @@ impl Py<PyDict> {
.map(|x| x.map(|eq| !eq));
}
if !op.eval_ord(self.__len__().cmp(&other.__len__())) {
return Ok(Implemented(false));
return Ok(PyArithmeticValue::Implemented(false));
}
let (superset, subset) = if self.__len__() < other.__len__() {
(other, self)
@@ -492,15 +490,15 @@ impl Py<PyDict> {
continue;
}
if item && !vm.bool_eq(&v1, &v2)? {
return Ok(Implemented(false));
return Ok(PyArithmeticValue::Implemented(false));
}
}
None => {
return Ok(Implemented(false));
return Ok(PyArithmeticValue::Implemented(false));
}
}
}
Ok(Implemented(true))
Ok(PyArithmeticValue::Implemented(true))
}
#[cfg_attr(feature = "flame-it", flame("PyDictRef"))]
@@ -1289,7 +1287,7 @@ trait ViewSetOps: DictView {
ref _dictitems @ PyDictItems => {}
ref _dictkeys @ PyDictKeys => {}
_ => {
return Ok(NotImplemented);
return Ok(PyArithmeticValue::NotImplemented);
}
});
let lhs: Vec<PyObjectRef> = zelf.as_object().to_owned().try_into_value(vm)?;
+4 -4
View File
@@ -9,12 +9,12 @@ use crate::{
common::{float_ops, format::FormatSpec, hash, wtf8::Wtf8Buf},
convert::{IntoPyException, ToPyObject, ToPyResult},
function::{
ArgBytesLike, FuncArgs, OptionalArg, OptionalOption, PyArithmeticValue::*,
PyComparisonValue,
ArgBytesLike, FuncArgs, OptionalArg, OptionalOption, PyArithmeticValue, PyComparisonValue,
},
protocol::PyNumberMethods,
types::{AsNumber, Callable, Comparable, Constructor, Hashable, PyComparisonOp, Representable},
};
use core::cell::Cell;
use core::ptr::NonNull;
use malachite_bigint::{BigInt, ToBigInt};
@@ -446,9 +446,9 @@ impl Comparable for PyFloat {
PyComparisonOp::Gt => float_ops::gt_int(a, b),
}
} else {
return Ok(NotImplemented);
return Ok(PyArithmeticValue::NotImplemented);
};
Ok(Implemented(ret))
Ok(PyArithmeticValue::Implemented(ret))
}
}
+23 -17
View File
@@ -816,16 +816,20 @@ impl<'a> EncodeErrorHandler<PyEncodeContext<'a>> for StandardError {
range: Range<StrSize>,
reason: Option<&str>,
) -> PyResult<(EncodeReplace<PyEncodeContext<'a>>, StrSize)> {
use StandardError::*;
// use errors::*;
match self {
Strict => errors::Strict.handle_encode_error(ctx, range, reason),
Ignore => errors::Ignore.handle_encode_error(ctx, range, reason),
Replace => errors::Replace.handle_encode_error(ctx, range, reason),
XmlCharRefReplace => errors::XmlCharRefReplace.handle_encode_error(ctx, range, reason),
BackslashReplace => errors::BackslashReplace.handle_encode_error(ctx, range, reason),
SurrogatePass => SurrogatePass.handle_encode_error(ctx, range, reason),
SurrogateEscape => errors::SurrogateEscape.handle_encode_error(ctx, range, reason),
Self::Strict => errors::Strict.handle_encode_error(ctx, range, reason),
Self::Ignore => errors::Ignore.handle_encode_error(ctx, range, reason),
Self::Replace => errors::Replace.handle_encode_error(ctx, range, reason),
Self::XmlCharRefReplace => {
errors::XmlCharRefReplace.handle_encode_error(ctx, range, reason)
}
Self::BackslashReplace => {
errors::BackslashReplace.handle_encode_error(ctx, range, reason)
}
Self::SurrogatePass => SurrogatePass.handle_encode_error(ctx, range, reason),
Self::SurrogateEscape => {
errors::SurrogateEscape.handle_encode_error(ctx, range, reason)
}
}
}
}
@@ -837,19 +841,20 @@ impl<'a> DecodeErrorHandler<PyDecodeContext<'a>> for StandardError {
byte_range: Range<usize>,
reason: Option<&str>,
) -> PyResult<(PyStrRef, usize)> {
use StandardError::*;
match self {
Strict => errors::Strict.handle_decode_error(ctx, byte_range, reason),
Ignore => errors::Ignore.handle_decode_error(ctx, byte_range, reason),
Replace => errors::Replace.handle_decode_error(ctx, byte_range, reason),
XmlCharRefReplace => Err(ctx
Self::Strict => errors::Strict.handle_decode_error(ctx, byte_range, reason),
Self::Ignore => errors::Ignore.handle_decode_error(ctx, byte_range, reason),
Self::Replace => errors::Replace.handle_decode_error(ctx, byte_range, reason),
Self::XmlCharRefReplace => Err(ctx
.vm
.new_type_error("don't know how to handle UnicodeDecodeError in error callback")),
BackslashReplace => {
Self::BackslashReplace => {
errors::BackslashReplace.handle_decode_error(ctx, byte_range, reason)
}
SurrogatePass => self::SurrogatePass.handle_decode_error(ctx, byte_range, reason),
SurrogateEscape => errors::SurrogateEscape.handle_decode_error(ctx, byte_range, reason),
Self::SurrogatePass => self::SurrogatePass.handle_decode_error(ctx, byte_range, reason),
Self::SurrogateEscape => {
errors::SurrogateEscape.handle_decode_error(ctx, byte_range, reason)
}
}
}
}
@@ -858,6 +863,7 @@ pub(crate) struct ErrorsHandler<'a> {
errors: &'a Py<PyUtf8Str>,
resolved: OnceCell<ResolvedError>,
}
enum ResolvedError {
Standard(StandardError),
Handler(PyObjectRef),
+8 -9
View File
@@ -178,16 +178,15 @@ impl TraceEvent {
impl core::fmt::Display for TraceEvent {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
use TraceEvent::*;
match self {
Call => write!(f, "call"),
Return => write!(f, "return"),
Exception => write!(f, "exception"),
Line => write!(f, "line"),
Opcode => write!(f, "opcode"),
CCall => write!(f, "c_call"),
CReturn => write!(f, "c_return"),
CException => write!(f, "c_exception"),
Self::Call => write!(f, "call"),
Self::Return => write!(f, "return"),
Self::Exception => write!(f, "exception"),
Self::Line => write!(f, "line"),
Self::Opcode => write!(f, "opcode"),
Self::CCall => write!(f, "c_call"),
Self::CReturn => write!(f, "c_return"),
Self::CException => write!(f, "c_exception"),
}
}
}
+9 -8
View File
@@ -123,14 +123,13 @@ enum FrozenError {
impl FrozenError {
fn to_pyexception(&self, mod_name: &str, vm: &VirtualMachine) -> PyBaseExceptionRef {
use FrozenError::*;
let msg = match self {
BadName | NotFound => format!("No such frozen object named {mod_name}"),
Disabled => format!(
Self::BadName | Self::NotFound => format!("No such frozen object named {mod_name}"),
Self::Disabled => format!(
"Frozen modules are disabled and the frozen object named {mod_name} is not essential"
),
Excluded => format!("Excluded frozen object named {mod_name}"),
Invalid => format!("Frozen object named {mod_name} is invalid"),
Self::Excluded => format!("Excluded frozen object named {mod_name}"),
Self::Invalid => format!("Frozen object named {mod_name} is invalid"),
};
vm.new_import_error(msg, vm.ctx.new_utf8_str(mod_name))
}
@@ -173,6 +172,8 @@ mod _imp {
import, version,
};
use super::FrozenError;
#[pyattr]
fn check_hash_based_pycs(vm: &VirtualMachine) -> PyStrRef {
vm.ctx
@@ -312,8 +313,6 @@ mod _imp {
withdata: OptionalArg<bool>,
vm: &VirtualMachine,
) -> PyResult<Option<(Option<PyRef<PyMemoryView>>, bool, Option<PyStrRef>)>> {
use super::FrozenError::*;
if withdata.into_option().is_some() {
// this is keyword-only argument in CPython
unimplemented!();
@@ -322,7 +321,9 @@ mod _imp {
let name_str = name.as_str();
let info = match super::find_frozen(name_str, vm) {
Ok(info) => info,
Err(NotFound | Disabled | BadName) => return Ok(None),
Err(FrozenError::NotFound | FrozenError::Disabled | FrozenError::BadName) => {
return Ok(None);
}
Err(e) => return Err(e.to_pyexception(name_str, vm)),
};
+19 -19
View File
@@ -19,7 +19,7 @@ mod decl {
};
use malachite_bigint::BigInt;
use num_traits::Zero;
use rustpython_compiler_core::marshal;
use rustpython_compiler_core::marshal::{self, DumpableValue};
#[pyattr(name = "version")]
use marshal::FORMAT_VERSION;
@@ -32,57 +32,57 @@ mod decl {
fn with_dump<R>(
&self,
f: impl FnOnce(marshal::DumpableValue<'_, Self>) -> R,
f: impl FnOnce(DumpableValue<'_, Self>) -> R,
) -> Result<R, Self::Error> {
use marshal::DumpableValue::*;
if self.is(PyStopIteration::static_type()) {
return Ok(f(StopIter));
return Ok(f(DumpableValue::StopIter));
}
let ret = match_class!(match self {
PyNone => f(None),
PyEllipsis => f(Ellipsis),
PyNone => f(DumpableValue::None),
PyEllipsis => f(DumpableValue::Ellipsis),
ref pyint @ PyInt => {
if self.class().is(PyBool::static_type()) {
f(Boolean(!pyint.as_bigint().is_zero()))
f(DumpableValue::Boolean(!pyint.as_bigint().is_zero()))
} else {
f(Integer(pyint.as_bigint()))
f(DumpableValue::Integer(pyint.as_bigint()))
}
}
ref pyfloat @ PyFloat => {
f(Float(pyfloat.to_f64()))
f(DumpableValue::Float(pyfloat.to_f64()))
}
ref pycomplex @ PyComplex => {
f(Complex(pycomplex.to_complex64()))
f(DumpableValue::Complex(pycomplex.to_complex64()))
}
ref pystr @ PyStr => {
f(Str(pystr.as_wtf8()))
f(DumpableValue::Str(pystr.as_wtf8()))
}
ref pylist @ PyList => {
f(List(&pylist.borrow_vec()))
f(DumpableValue::List(&pylist.borrow_vec()))
}
ref pyset @ PySet => {
let elements = pyset.elements();
f(Set(&elements))
f(DumpableValue::Set(&elements))
}
ref pyfrozen @ PyFrozenSet => {
let elements = pyfrozen.elements();
f(Frozenset(&elements))
f(DumpableValue::Frozenset(&elements))
}
ref pytuple @ PyTuple => {
f(Tuple(pytuple.as_slice()))
f(DumpableValue::Tuple(pytuple.as_slice()))
}
ref pydict @ PyDict => {
let entries = pydict.into_iter().collect::<Vec<_>>();
f(Dict(&entries))
f(DumpableValue::Dict(&entries))
}
ref bytes @ PyBytes => {
f(Bytes(bytes.as_bytes()))
f(DumpableValue::Bytes(bytes.as_bytes()))
}
ref bytes @ PyByteArray => {
f(Bytes(&bytes.borrow_buf()))
f(DumpableValue::Bytes(&bytes.borrow_buf()))
}
ref co @ PyCode => {
f(Code(co))
f(DumpableValue::Code(co))
}
_ => return Err(DumpError),
});
+9 -11
View File
@@ -5,12 +5,12 @@ pub(crate) use winsound::module_def;
#[pymodule]
mod winsound {
use crate::builtins::{PyBytes, PyStr};
use crate::builtins::{PyBaseExceptionRef, PyBytes, PyStr};
use crate::convert::{IntoPyException, TryFromBorrowedObject};
use crate::host_env::windows::ToWideString;
use crate::protocol::PyBuffer;
use crate::{AsObject, PyObjectRef, PyResult, VirtualMachine};
use rustpython_host_env::winsound::{PlaySoundSource, play_sound};
use rustpython_host_env::winsound::{PlaySoundError, PlaySoundSource, play_sound};
// PlaySound flags
#[pyattr]
@@ -68,16 +68,14 @@ mod winsound {
flags: i32,
}
fn map_play_err(
vm: &VirtualMachine,
) -> impl FnOnce(
rustpython_host_env::winsound::PlaySoundError,
) -> crate::builtins::PyBaseExceptionRef
+ '_ {
use rustpython_host_env::winsound::PlaySoundError::*;
fn map_play_err(vm: &VirtualMachine) -> impl FnOnce(PlaySoundError) -> PyBaseExceptionRef + '_ {
|err| match err {
MemoryAsyncRejected => vm.new_runtime_error("Cannot play asynchronously from memory"),
MemoryFlagWithoutBuffer | CallFailed => vm.new_runtime_error("Failed to play sound"),
PlaySoundError::MemoryAsyncRejected => {
vm.new_runtime_error("Cannot play asynchronously from memory")
}
PlaySoundError::MemoryFlagWithoutBuffer | PlaySoundError::CallFailed => {
vm.new_runtime_error("Failed to play sound")
}
}
}