mirror of
https://github.com/RustPython/RustPython.git
synced 2026-10-28 10:44:36 +08:00
Clippy warn uninlined_format_args & redundant_else (#7873)
This commit is contained in:
1 parent
399ba4f29d
commit
54be99bbc9
67 files changed
+326
-358
No files matched your search
@@ -358,4 +358,6 @@ inconsistent_struct_constructor = "warn"
|
||||
manual_is_variant_and = "warn"
|
||||
map_unwrap_or = "warn"
|
||||
must_use_candidate = "warn"
|
||||
redundant_else = "warn"
|
||||
uninlined_format_args = "warn"
|
||||
unnecessary_wraps = "warn"
|
||||
@@ -289,7 +289,7 @@ pub fn compile_program(
|
||||
) -> CompileResult<CodeObject> {
|
||||
let symbol_table = SymbolTable::scan_program(ast, source_file.clone())
|
||||
.map_err(|e| e.into_codegen_error(source_file.name().to_owned()))?;
|
||||
let mut compiler = Compiler::new(opts, source_file, "<module>".to_owned());
|
||||
let mut compiler = Compiler::new(opts, source_file, "<module>");
|
||||
compiler.compile_program(ast, symbol_table)?;
|
||||
let code = compiler.exit_scope();
|
||||
trace!("Compilation completed: {code:?}");
|
||||
@@ -304,7 +304,7 @@ pub fn compile_program_single(
|
||||
) -> CompileResult<CodeObject> {
|
||||
let symbol_table = SymbolTable::scan_program(ast, source_file.clone())
|
||||
.map_err(|e| e.into_codegen_error(source_file.name().to_owned()))?;
|
||||
let mut compiler = Compiler::new(opts, source_file, "<module>".to_owned());
|
||||
let mut compiler = Compiler::new(opts, source_file, "<module>");
|
||||
compiler.compile_program_single(&ast.body, symbol_table)?;
|
||||
let code = compiler.exit_scope();
|
||||
trace!("Compilation completed: {code:?}");
|
||||
@@ -318,7 +318,7 @@ pub fn compile_block_expression(
|
||||
) -> CompileResult<CodeObject> {
|
||||
let symbol_table = SymbolTable::scan_program(ast, source_file.clone())
|
||||
.map_err(|e| e.into_codegen_error(source_file.name().to_owned()))?;
|
||||
let mut compiler = Compiler::new(opts, source_file, "<module>".to_owned());
|
||||
let mut compiler = Compiler::new(opts, source_file, "<module>");
|
||||
compiler.compile_block_expr(&ast.body, symbol_table)?;
|
||||
let code = compiler.exit_scope();
|
||||
trace!("Compilation completed: {code:?}");
|
||||
@@ -332,7 +332,7 @@ pub fn compile_expression(
|
||||
) -> CompileResult<CodeObject> {
|
||||
let symbol_table = SymbolTable::scan_expr(ast, source_file.clone())
|
||||
.map_err(|e| e.into_codegen_error(source_file.name().to_owned()))?;
|
||||
let mut compiler = Compiler::new(opts, source_file, "<module>".to_owned());
|
||||
let mut compiler = Compiler::new(opts, source_file, "<module>");
|
||||
compiler.compile_eval(ast, symbol_table)?;
|
||||
let code = compiler.exit_scope();
|
||||
Ok(code)
|
||||
@@ -447,13 +447,14 @@ impl PatternContext {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Eq, PartialEq)]
|
||||
enum JumpOp {
|
||||
Jump,
|
||||
PopJumpIfFalse,
|
||||
}
|
||||
|
||||
/// Type of collection to build in starunpack_helper
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
enum CollectionType {
|
||||
Tuple,
|
||||
List,
|
||||
@@ -541,7 +542,7 @@ impl Compiler {
|
||||
}
|
||||
}
|
||||
|
||||
fn new(opts: CompileOpts, source_file: SourceFile, code_name: String) -> Self {
|
||||
fn new(opts: CompileOpts, source_file: SourceFile, code_name: &str) -> Self {
|
||||
let module_code = ir::CodeInfo {
|
||||
// CPython convention: top-level module / interactive /
|
||||
// expression code does not carry CO_NEWLOCALS or CO_OPTIMIZED.
|
||||
@@ -558,8 +559,8 @@ impl Compiler {
|
||||
current_block: BlockIdx::new(0),
|
||||
annotations_blocks: None,
|
||||
metadata: ir::CodeUnitMetadata {
|
||||
name: code_name.clone(),
|
||||
qualname: Some(code_name),
|
||||
name: code_name.to_string(),
|
||||
qualname: Some(code_name.to_string()),
|
||||
consts: IndexSet::default(),
|
||||
names: IndexSet::default(),
|
||||
varnames: IndexSet::default(),
|
||||
@@ -1287,8 +1288,7 @@ impl Compiler {
|
||||
let name = current_table.name.clone();
|
||||
let typ = current_table.typ;
|
||||
return Err(self.error(CodegenErrorType::SyntaxError(format!(
|
||||
"no symbol table available in {} (type: {:?})",
|
||||
name, typ
|
||||
"no symbol table available in {name} (type: {typ:?})"
|
||||
))));
|
||||
}
|
||||
|
||||
@@ -1829,7 +1829,7 @@ impl Compiler {
|
||||
posonlyarg_count: u32,
|
||||
arg_count: u32,
|
||||
kwonlyarg_count: u32,
|
||||
obj_name: String,
|
||||
obj_name: &str,
|
||||
) -> CompileResult<()> {
|
||||
// First push the symbol table
|
||||
let table = self.push_symbol_table()?;
|
||||
@@ -1842,7 +1842,7 @@ impl Compiler {
|
||||
let lineno = self.get_source_line_number().get();
|
||||
|
||||
// Call enter_scope which does most of the work
|
||||
self.enter_scope(&obj_name, scope_type, key, lineno.to_u32())?;
|
||||
self.enter_scope(obj_name, scope_type, key, lineno.to_u32())?;
|
||||
|
||||
// Override the values that push_output sets explicitly
|
||||
// enter_scope sets default values based on scope_type, but push_output
|
||||
@@ -3400,7 +3400,7 @@ impl Compiler {
|
||||
parameters.posonlyargs.len().to_u32(),
|
||||
(parameters.posonlyargs.len() + parameters.args.len()).to_u32(),
|
||||
parameters.kwonlyargs.len().to_u32(),
|
||||
name.to_owned(),
|
||||
name,
|
||||
)?;
|
||||
|
||||
let args_iter = core::iter::empty()
|
||||
@@ -5258,7 +5258,7 @@ impl Compiler {
|
||||
0,
|
||||
num_typeparam_args as u32,
|
||||
0,
|
||||
type_params_name,
|
||||
&type_params_name,
|
||||
)?;
|
||||
|
||||
// TypeParams scope is function-like
|
||||
@@ -5820,7 +5820,7 @@ impl Compiler {
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
type_params_name,
|
||||
&type_params_name,
|
||||
)?;
|
||||
|
||||
// Set private name for name mangling
|
||||
@@ -7956,21 +7956,20 @@ impl Compiler {
|
||||
if let ast::Expr::Starred(_) = &element {
|
||||
if seen_star {
|
||||
return Err(self.error(CodegenErrorType::MultipleStarArgs));
|
||||
} else {
|
||||
seen_star = true;
|
||||
let before = i;
|
||||
let after = elts.len() - i - 1;
|
||||
let (before, after) = (|| Some((before.to_u8()?, after.to_u8()?)))(
|
||||
)
|
||||
}
|
||||
|
||||
seen_star = true;
|
||||
let before = i;
|
||||
let after = elts.len() - i - 1;
|
||||
let (before, after) = (|| Some((before.to_u8()?, after.to_u8()?)))()
|
||||
.ok_or_else(|| {
|
||||
self.error_ranged(
|
||||
CodegenErrorType::TooManyStarUnpack,
|
||||
target.range(),
|
||||
)
|
||||
})?;
|
||||
let counts = bytecode::UnpackExArgs { before, after };
|
||||
emit!(self, Instruction::UnpackEx { counts });
|
||||
}
|
||||
let counts = bytecode::UnpackExArgs { before, after };
|
||||
emit!(self, Instruction::UnpackEx { counts });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9696,8 +9695,7 @@ impl Compiler {
|
||||
let name = current_table.name.clone();
|
||||
let typ = current_table.typ;
|
||||
Err(self.error(CodegenErrorType::SyntaxError(format!(
|
||||
"no symbol table available in {} (type: {:?})",
|
||||
name, typ
|
||||
"no symbol table available in {name} (type: {typ:?})"
|
||||
))))
|
||||
}
|
||||
})();
|
||||
@@ -9715,14 +9713,14 @@ impl Compiler {
|
||||
posonlyarg_count: u32,
|
||||
arg_count: u32,
|
||||
kwonlyarg_count: u32,
|
||||
obj_name: String,
|
||||
obj_name: &str,
|
||||
) -> CompileResult<()> {
|
||||
let scope_type = table.typ;
|
||||
self.symbol_table_stack.push(table);
|
||||
|
||||
let key = self.symbol_table_stack.len() - 1;
|
||||
let lineno = self.get_source_line_number().get();
|
||||
self.enter_scope(&obj_name, scope_type, key, lineno.to_u32())?;
|
||||
self.enter_scope(obj_name, scope_type, key, lineno.to_u32())?;
|
||||
|
||||
if let Some(info) = self.code_stack.last_mut() {
|
||||
info.flags = flags | (info.flags & bytecode::CodeFlags::NESTED);
|
||||
@@ -9786,7 +9784,7 @@ impl Compiler {
|
||||
// and relies on the inlined path itself to handle GET_AITER /
|
||||
// async-comprehension cleanup.
|
||||
return self.compile_inlined_comprehension(
|
||||
comp_table,
|
||||
&comp_table,
|
||||
init_collection,
|
||||
generators,
|
||||
compile_element,
|
||||
@@ -9821,7 +9819,7 @@ impl Compiler {
|
||||
// scope itself. Peek past those nested scopes so we can enter the
|
||||
// correct comprehension table here, then let the real outermost
|
||||
// iterator compile consume its nested scopes later in parent scope.
|
||||
self.push_output_with_symbol_table(comp_table, flags, 1, 1, 0, name.to_owned())?;
|
||||
self.push_output_with_symbol_table(comp_table, flags, 1, 1, 0, name)?;
|
||||
|
||||
// Set qualname for comprehension
|
||||
self.set_qualname();
|
||||
@@ -10028,7 +10026,7 @@ impl Compiler {
|
||||
/// This generates bytecode inline without creating a new code object
|
||||
fn compile_inlined_comprehension(
|
||||
&mut self,
|
||||
comp_table: SymbolTable,
|
||||
comp_table: &SymbolTable,
|
||||
init_collection: Option<AnyInstruction>,
|
||||
generators: &[ast::Comprehension],
|
||||
compile_element: &dyn Fn(&mut Self, usize) -> CompileResult<()>,
|
||||
@@ -12380,7 +12378,7 @@ mod tests {
|
||||
let symbol_table = SymbolTable::scan_program(&ast, source_file.clone())
|
||||
.map_err(|e| e.into_codegen_error(source_file.name().to_owned()))
|
||||
.unwrap();
|
||||
let mut compiler = Compiler::new(opts, source_file, "<module>".to_owned());
|
||||
let mut compiler = Compiler::new(opts, source_file, "<module>");
|
||||
compiler.compile_program(&ast, symbol_table).unwrap();
|
||||
compiler.exit_scope()
|
||||
}
|
||||
@@ -12418,7 +12416,7 @@ mod tests {
|
||||
let symbol_table = SymbolTable::scan_program(&ast, source_file.clone())
|
||||
.map_err(|e| e.into_codegen_error(source_file.name().to_owned()))
|
||||
.unwrap();
|
||||
let mut compiler = Compiler::new(opts, source_file, "<module>".to_owned());
|
||||
let mut compiler = Compiler::new(opts, source_file, "<module>");
|
||||
compiler.compile_program(&ast, symbol_table).unwrap();
|
||||
let _table = compiler.pop_symbol_table();
|
||||
let stack_top = compiler.code_stack.pop().unwrap();
|
||||
@@ -12459,7 +12457,7 @@ mod tests {
|
||||
let is_async = function.is_async;
|
||||
let range = function.range();
|
||||
|
||||
let mut compiler = Compiler::new(opts, source_file, "<module>".to_owned());
|
||||
let mut compiler = Compiler::new(opts, source_file, "<module>");
|
||||
compiler.future_annotations = symbol_table.future_annotations;
|
||||
compiler.symbol_table_stack.push(symbol_table);
|
||||
compiler.set_source_range(range);
|
||||
|
||||
@@ -2418,7 +2418,7 @@ impl SymbolTableBuilder {
|
||||
};
|
||||
if !seen_names.insert(name) {
|
||||
return Err(SymbolTableError {
|
||||
error: format!("duplicate type parameter '{}'", name),
|
||||
error: format!("duplicate type parameter '{name}'"),
|
||||
location: Some(
|
||||
self.source_file
|
||||
.to_source_code()
|
||||
@@ -2431,8 +2431,7 @@ impl SymbolTableBuilder {
|
||||
} else if default_seen {
|
||||
return Err(SymbolTableError {
|
||||
error: format!(
|
||||
"non-default type parameter '{}' follows default type parameter",
|
||||
name
|
||||
"non-default type parameter '{name}' follows default type parameter"
|
||||
),
|
||||
location: Some(
|
||||
self.source_file
|
||||
@@ -2743,8 +2742,7 @@ impl SymbolTableBuilder {
|
||||
{
|
||||
return Err(SymbolTableError {
|
||||
error: format!(
|
||||
"assignment expression cannot rebind comprehension iteration variable '{}'",
|
||||
mangled
|
||||
"assignment expression cannot rebind comprehension iteration variable '{mangled}'"
|
||||
),
|
||||
location,
|
||||
});
|
||||
@@ -2868,8 +2866,7 @@ impl SymbolTableBuilder {
|
||||
{
|
||||
return Err(SymbolTableError {
|
||||
error: format!(
|
||||
"comprehension inner loop cannot rebind assignment expression target '{}'",
|
||||
name
|
||||
"comprehension inner loop cannot rebind assignment expression target '{name}'"
|
||||
),
|
||||
location,
|
||||
});
|
||||
|
||||
@@ -788,21 +788,23 @@ impl<S> CFormatStrOrBytes<S> {
|
||||
iter.next().unwrap();
|
||||
literal.extend([second]);
|
||||
continue;
|
||||
} else {
|
||||
if !literal.is_empty() {
|
||||
parts.push((
|
||||
part_index,
|
||||
CFormatPart::Literal(core::mem::take(&mut literal)),
|
||||
));
|
||||
}
|
||||
let spec = CFormatSpecKeyed::parse(iter).map_err(|err| CFormatError {
|
||||
typ: err.0,
|
||||
index: err.1,
|
||||
})?;
|
||||
parts.push((index, CFormatPart::Spec(spec)));
|
||||
if let Some(&(index, _)) = iter.peek() {
|
||||
part_index = index;
|
||||
}
|
||||
}
|
||||
|
||||
if !literal.is_empty() {
|
||||
parts.push((
|
||||
part_index,
|
||||
CFormatPart::Literal(core::mem::take(&mut literal)),
|
||||
));
|
||||
}
|
||||
|
||||
let spec = CFormatSpecKeyed::parse(iter).map_err(|err| CFormatError {
|
||||
typ: err.0,
|
||||
index: err.1,
|
||||
})?;
|
||||
|
||||
parts.push((index, CFormatPart::Spec(spec)));
|
||||
if let Some(&(index, _)) = iter.peek() {
|
||||
part_index = index;
|
||||
}
|
||||
} else {
|
||||
return Err(CFormatError {
|
||||
|
||||
@@ -763,7 +763,7 @@ impl FormatSpec {
|
||||
Ok("inf%".to_owned())
|
||||
} else {
|
||||
let capped = float::clamp_fmt_precision(precision);
|
||||
let mut result = format!("{:.*}", capped, scaled);
|
||||
let mut result = format!("{scaled:.capped$}");
|
||||
// Pad with '0's up to the requested precision to match
|
||||
// CPython byte-identically past the internal cap.
|
||||
let missing = precision.saturating_sub(capped);
|
||||
|
||||
@@ -65,7 +65,7 @@ impl CompileError {
|
||||
line: loc.line,
|
||||
character_offset: loc.character_offset.saturating_add(1),
|
||||
};
|
||||
let msg = format!("'{}' was never closed", bracket_char);
|
||||
let msg = format!("'{bracket_char}' was never closed");
|
||||
is_unclosed_bracket = true;
|
||||
(parser::ParseErrorType::OtherError(msg), loc, end_loc)
|
||||
} else {
|
||||
|
||||
@@ -52,7 +52,7 @@ pub trait Compiler {
|
||||
&self,
|
||||
source: &str,
|
||||
mode: Mode,
|
||||
module_name: String,
|
||||
module_name: &str,
|
||||
) -> Result<CodeObject, Box<dyn core::error::Error>>;
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ impl CompilationSource {
|
||||
&self,
|
||||
source: &str,
|
||||
mode: Mode,
|
||||
module_name: String,
|
||||
module_name: &str,
|
||||
compiler: &dyn Compiler,
|
||||
origin: F,
|
||||
) -> Result<CodeObject, Diagnostic> {
|
||||
@@ -76,15 +76,15 @@ impl CompilationSource {
|
||||
fn compile(
|
||||
&self,
|
||||
mode: Mode,
|
||||
module_name: String,
|
||||
module_name: &str,
|
||||
compiler: &dyn Compiler,
|
||||
) -> Result<HashMap<String, CompiledModule>, Diagnostic> {
|
||||
match &self.kind {
|
||||
CompilationSourceKind::Dir { base, rel_path } => {
|
||||
self.compile_dir(base, &base.join(rel_path), String::new(), mode, compiler)
|
||||
self.compile_dir(base, &base.join(rel_path), "", mode, compiler)
|
||||
}
|
||||
_ => Ok(hashmap! {
|
||||
module_name.clone() => CompiledModule {
|
||||
module_name.to_string() => CompiledModule {
|
||||
code: self.compile_single(mode, module_name, compiler)?,
|
||||
package: false,
|
||||
},
|
||||
@@ -95,7 +95,7 @@ impl CompilationSource {
|
||||
fn compile_single(
|
||||
&self,
|
||||
mode: Mode,
|
||||
module_name: String,
|
||||
module_name: &str,
|
||||
compiler: &dyn Compiler,
|
||||
) -> Result<CodeObject, Diagnostic> {
|
||||
match &self.kind {
|
||||
@@ -126,7 +126,7 @@ impl CompilationSource {
|
||||
&self,
|
||||
base: &Path,
|
||||
path: &Path,
|
||||
parent: String,
|
||||
parent: &str,
|
||||
mode: Mode,
|
||||
compiler: &dyn Compiler,
|
||||
) -> Result<HashMap<String, CompiledModule>, Diagnostic> {
|
||||
@@ -152,26 +152,21 @@ impl CompilationSource {
|
||||
Diagnostic::spans_error(self.span, format!("Invalid UTF-8 in file name {path:?}"))
|
||||
})?;
|
||||
if path.is_dir() {
|
||||
code_map.extend(self.compile_dir(
|
||||
base,
|
||||
&path,
|
||||
if parent.is_empty() {
|
||||
file_name.to_string()
|
||||
} else {
|
||||
format!("{parent}.{file_name}")
|
||||
},
|
||||
mode,
|
||||
compiler,
|
||||
)?);
|
||||
let nparent = if parent.is_empty() {
|
||||
file_name.to_string()
|
||||
} else {
|
||||
format!("{parent}.{file_name}")
|
||||
};
|
||||
code_map.extend(self.compile_dir(base, &path, &nparent, mode, compiler)?);
|
||||
} else if file_name.ends_with(".py") {
|
||||
let stem = path.file_stem().unwrap().to_str().unwrap();
|
||||
let is_init = stem == "__init__";
|
||||
let module_name = if is_init {
|
||||
parent.clone()
|
||||
parent
|
||||
} else if parent.is_empty() {
|
||||
stem.to_owned()
|
||||
stem
|
||||
} else {
|
||||
format!("{parent}.{stem}")
|
||||
&format!("{parent}.{stem}")
|
||||
};
|
||||
|
||||
let compile_path = |src_path: &Path| {
|
||||
@@ -181,7 +176,7 @@ impl CompilationSource {
|
||||
format!("Error reading file {path:?}: {err}"),
|
||||
)
|
||||
})?;
|
||||
self.compile_string(&source, mode, module_name.clone(), compiler, || {
|
||||
self.compile_string(&source, mode, module_name, compiler, || {
|
||||
path.strip_prefix(base).ok().unwrap_or(&path).display()
|
||||
})
|
||||
};
|
||||
@@ -211,7 +206,7 @@ impl CompilationSource {
|
||||
};
|
||||
|
||||
code_map.insert(
|
||||
module_name,
|
||||
module_name.to_string(),
|
||||
CompiledModule {
|
||||
code,
|
||||
package: is_init,
|
||||
@@ -343,7 +338,7 @@ pub(crate) fn impl_py_compile(
|
||||
let crate_name = args.crate_name;
|
||||
let code = args
|
||||
.source
|
||||
.compile_single(args.mode, args.module_name, compiler)?;
|
||||
.compile_single(args.mode, &args.module_name, compiler)?;
|
||||
|
||||
let frozen = frozen::FrozenCodeObject::encode(&code);
|
||||
let bytes = LitByteStr::new(&frozen.bytes, Span::call_site());
|
||||
@@ -362,7 +357,9 @@ pub(crate) fn impl_py_freeze(
|
||||
let args = PyCompileArgs::parse(input, true)?;
|
||||
|
||||
let crate_name = args.crate_name;
|
||||
let code_map = args.source.compile(args.mode, args.module_name, compiler)?;
|
||||
let code_map = args
|
||||
.source
|
||||
.compile(args.mode, &args.module_name, compiler)?;
|
||||
|
||||
let data = frozen::FrozenLib::encode(code_map.iter().map(|(k, v)| {
|
||||
let v = frozen::FrozenModule {
|
||||
|
||||
@@ -55,7 +55,7 @@ pub fn pyexception(attr: PunctuatedNestedMeta, item: Item) -> TokenStream {
|
||||
if matches!(item, syn::Item::Impl(_)) {
|
||||
pyclass::impl_pyexception_impl(attr, item)
|
||||
} else {
|
||||
result_to_tokens(pyclass::impl_pyexception(attr, item))
|
||||
result_to_tokens(pyclass::impl_pyexception(attr, &item))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ use syn::{Attribute, Ident, Item, Result, parse_quote, spanned::Spanned};
|
||||
use syn_ext::ext::*;
|
||||
use syn_ext::types::*;
|
||||
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
|
||||
enum AttrName {
|
||||
Method,
|
||||
ClassMethod,
|
||||
@@ -780,8 +780,8 @@ pub(crate) fn impl_pyclass(attr: PunctuatedNestedMeta, item: Item) -> Result<Tok
|
||||
/// But, inside `macro_rules` we don't have an opportunity
|
||||
/// to add non-literal attributes to `pyclass`.
|
||||
/// That's why we have to use this proxy.
|
||||
pub(crate) fn impl_pyexception(attr: PunctuatedNestedMeta, item: Item) -> Result<TokenStream> {
|
||||
let (ident, _attrs) = pyexception_ident_and_attrs(&item)?;
|
||||
pub(crate) fn impl_pyexception(attr: PunctuatedNestedMeta, item: &Item) -> Result<TokenStream> {
|
||||
let (ident, _attrs) = pyexception_ident_and_attrs(item)?;
|
||||
let fake_ident = Ident::new("pyclass", item.span());
|
||||
let class_meta = ExceptionItemMeta::from_nested(ident.clone(), fake_ident, attr.into_iter())?;
|
||||
let class_name = class_meta.class_name()?;
|
||||
@@ -1131,7 +1131,7 @@ where
|
||||
|
||||
args.context
|
||||
.getset_items
|
||||
.add_item(py_name, args.cfgs.to_vec(), kind, ident.clone())?;
|
||||
.add_item(&py_name, args.cfgs.to_vec(), kind, ident.clone())?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1298,7 +1298,7 @@ where
|
||||
}
|
||||
|
||||
args.context.member_items.add_item(
|
||||
py_name,
|
||||
&py_name,
|
||||
member_item_kind,
|
||||
member_kind,
|
||||
ident.clone(),
|
||||
@@ -1402,6 +1402,7 @@ struct GetSetNursery {
|
||||
validated: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Eq, PartialEq)]
|
||||
enum GetSetItemKind {
|
||||
Get,
|
||||
Set,
|
||||
@@ -1410,7 +1411,7 @@ enum GetSetItemKind {
|
||||
impl GetSetNursery {
|
||||
fn add_item(
|
||||
&mut self,
|
||||
name: String,
|
||||
name: &str,
|
||||
cfgs: Vec<Attribute>,
|
||||
kind: GetSetItemKind,
|
||||
item_ident: Ident,
|
||||
@@ -1418,7 +1419,7 @@ impl GetSetNursery {
|
||||
assert!(!self.validated, "new item is not allowed after validation");
|
||||
// Note: Both getter and setter can have #[cfg], but they must have matching cfgs
|
||||
// since the map key is (name, cfgs). This ensures getter and setter are paired correctly.
|
||||
let entry = self.map.entry((name.clone(), cfgs)).or_default();
|
||||
let entry = self.map.entry((name.to_string(), cfgs)).or_default();
|
||||
let func = match kind {
|
||||
GetSetItemKind::Get => &mut entry.0,
|
||||
GetSetItemKind::Set => &mut entry.1,
|
||||
@@ -1492,6 +1493,7 @@ struct MemberNurseryEntry {
|
||||
setter: Option<Ident>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Eq, PartialEq)]
|
||||
enum MemberItemKind {
|
||||
Get,
|
||||
Set,
|
||||
@@ -1500,7 +1502,7 @@ enum MemberItemKind {
|
||||
impl MemberNursery {
|
||||
fn add_item(
|
||||
&mut self,
|
||||
name: String,
|
||||
name: &str,
|
||||
kind: MemberItemKind,
|
||||
member_kind: MemberKindStr,
|
||||
item_ident: Ident,
|
||||
@@ -1508,7 +1510,7 @@ impl MemberNursery {
|
||||
assert!(!self.validated, "new item is not allowed after validation");
|
||||
let entry = self
|
||||
.map
|
||||
.entry(name.clone())
|
||||
.entry(name.to_string())
|
||||
.or_insert_with(|| MemberNurseryEntry {
|
||||
kind: member_kind,
|
||||
getter: None,
|
||||
|
||||
@@ -550,7 +550,7 @@ pub(crate) fn impl_pystruct_sequence(
|
||||
};
|
||||
|
||||
let module_class_name = if let Some(ref m) = module_name {
|
||||
format!("{}.{}", m, class_name)
|
||||
format!("{m}.{class_name}")
|
||||
} else {
|
||||
class_name.clone()
|
||||
};
|
||||
|
||||
@@ -273,10 +273,10 @@ impl derive_impl::Compiler for Compiler {
|
||||
&self,
|
||||
source: &str,
|
||||
mode: rustpython_compiler::Mode,
|
||||
module_name: String,
|
||||
module_name: &str,
|
||||
) -> Result<rustpython_compiler::CodeObject, Box<dyn core::error::Error>> {
|
||||
use rustpython_compiler::{CompileOpts, compile};
|
||||
Ok(compile(source, mode, &module_name, CompileOpts::default())?)
|
||||
Ok(compile(source, mode, module_name, CompileOpts::default())?)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -454,7 +454,7 @@ pub fn fopen(path: &std::path::Path, mode: &str) -> std::io::Result<*mut libc::F
|
||||
if mode != "rb" {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
format!("unsupported mode: {}", mode),
|
||||
format!("unsupported mode: {mode}"),
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
@@ -123,8 +123,7 @@ fn extract_annotations_from_annotate_code(code: &CodeObject) -> HashMap<Wtf8Buf,
|
||||
)
|
||||
}
|
||||
Some(other) => panic!(
|
||||
"Unsupported annotation const for '{:?}' at idx {}: {:?}",
|
||||
param_name, val_idx, other
|
||||
"Unsupported annotation const for '{param_name:?}' at idx {val_idx}: {other:?}"
|
||||
),
|
||||
None => panic!(
|
||||
"Annotation const idx out of bounds for '{:?}': {} (len={})",
|
||||
|
||||
@@ -807,7 +807,7 @@ pub(crate) mod _asyncio {
|
||||
// Create context dict for call_exception_handler
|
||||
let context = PyDict::default().into_ref(&vm.ctx);
|
||||
let class_name = zelf.class().name().to_string();
|
||||
let message = format!("{} exception was never retrieved", class_name);
|
||||
let message = format!("{class_name} exception was never retrieved");
|
||||
context.set_item(
|
||||
vm.ctx.intern_str("message"),
|
||||
vm.ctx.new_str(message).into(),
|
||||
@@ -831,9 +831,9 @@ pub(crate) mod _asyncio {
|
||||
let class_name = zelf.class().name().to_string();
|
||||
if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) {
|
||||
let info = get_future_repr_info(zelf.as_object(), vm)?;
|
||||
Ok(format!("<{} {}>", class_name, info))
|
||||
Ok(format!("<{class_name} {info}>"))
|
||||
} else {
|
||||
Ok(format!("<{} ...>", class_name))
|
||||
Ok(format!("<{class_name} ...>"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1851,7 +1851,7 @@ pub(crate) mod _asyncio {
|
||||
.repr(vm)
|
||||
.unwrap_or_else(|_| vm.ctx.new_str("<Task>"));
|
||||
let message =
|
||||
format!("Task was destroyed but it is pending!\ntask: {}", task_repr);
|
||||
format!("Task was destroyed but it is pending!\ntask: {task_repr}");
|
||||
context.set_item(
|
||||
vm.ctx.intern_str("message"),
|
||||
vm.ctx.new_str(message).into(),
|
||||
@@ -1887,7 +1887,7 @@ pub(crate) mod _asyncio {
|
||||
// Create context dict for call_exception_handler
|
||||
let context = PyDict::default().into_ref(&vm.ctx);
|
||||
let class_name = zelf.class().name().to_string();
|
||||
let message = format!("{} exception was never retrieved", class_name);
|
||||
let message = format!("{class_name} exception was never retrieved");
|
||||
context.set_item(
|
||||
vm.ctx.intern_str("message"),
|
||||
vm.ctx.new_str(message).into(),
|
||||
@@ -2177,8 +2177,7 @@ pub(crate) mod _asyncio {
|
||||
.repr(vm)
|
||||
.unwrap_or_else(|_| vm.ctx.new_str("<Future>"));
|
||||
let msg = format!(
|
||||
"Task {} got Future {} attached to a different loop",
|
||||
task_repr, result_repr
|
||||
"Task {task_repr} got Future {result_repr} attached to a different loop"
|
||||
);
|
||||
task.base.fut_state.store(FutureState::Finished);
|
||||
*task.base.fut_exception.write() = Some(vm.new_runtime_error(msg).into());
|
||||
|
||||
@@ -1736,8 +1736,7 @@ mod _sqlite3 {
|
||||
st.bind_parameters(¶meters, vm)?;
|
||||
} else if params_needed > 0 {
|
||||
let msg = format!(
|
||||
"Incorrect number of bindings supplied. The current statement uses {}, and 0 were supplied.",
|
||||
params_needed
|
||||
"Incorrect number of bindings supplied. The current statement uses {params_needed}, and 0 were supplied."
|
||||
);
|
||||
return Err(new_programming_error(vm, msg));
|
||||
}
|
||||
@@ -3175,8 +3174,7 @@ mod _sqlite3 {
|
||||
return Err(new_programming_error(
|
||||
vm,
|
||||
format!(
|
||||
"Incorrect number of bindings supplied. The current statement uses {}, and {} were supplied.",
|
||||
num_needed, num_supplied
|
||||
"Incorrect number of bindings supplied. The current statement uses {num_needed}, and {num_supplied} were supplied."
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
@@ -691,20 +691,22 @@ mod decl {
|
||||
out_data.push(RUN_CHAR);
|
||||
out_data.push(0);
|
||||
return Ok(out_data);
|
||||
} else {
|
||||
let mut in_end = idx + 1;
|
||||
while in_end < len && buffer[in_end] == ch && in_end < idx + 255 {
|
||||
in_end += 1;
|
||||
}
|
||||
if in_end - idx > 3 {
|
||||
out_data.push(ch);
|
||||
out_data.push(RUN_CHAR);
|
||||
out_data.push(((in_end - idx) % 256) as u8);
|
||||
idx = in_end - 1;
|
||||
} else {
|
||||
out_data.push(ch);
|
||||
}
|
||||
}
|
||||
|
||||
let mut in_end = idx + 1;
|
||||
while in_end < len && buffer[in_end] == ch && in_end < idx + 255 {
|
||||
in_end += 1;
|
||||
}
|
||||
|
||||
if in_end - idx > 3 {
|
||||
out_data.push(ch);
|
||||
out_data.push(RUN_CHAR);
|
||||
out_data.push(((in_end - idx) % 256) as u8);
|
||||
idx = in_end - 1;
|
||||
} else {
|
||||
out_data.push(ch);
|
||||
}
|
||||
|
||||
idx += 1;
|
||||
}
|
||||
Ok(out_data)
|
||||
|
||||
@@ -753,9 +753,9 @@ mod decl {
|
||||
|
||||
// Match Python's timedelta str format: H:MM:SS.ffffff (no leading zero for hours)
|
||||
if us != 0 {
|
||||
format!("Timeout ({}:{:02}:{:02}.{:06})!\n", hour, min, sec, us)
|
||||
format!("Timeout ({hour}:{min:02}:{sec:02}.{us:06})!\n")
|
||||
} else {
|
||||
format!("Timeout ({}:{:02}:{:02})!\n", hour, min, sec)
|
||||
format!("Timeout ({hour}:{min:02}:{sec:02})!\n")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1051,8 +1051,7 @@ mod decl {
|
||||
let is_fatal = unsafe { FAULTHANDLER_HANDLERS.iter().any(|h| h.signum == signum) };
|
||||
if is_fatal {
|
||||
return Err(vm.new_runtime_error(format!(
|
||||
"signal {} cannot be registered, use enable() instead",
|
||||
signum
|
||||
"signal {signum} cannot be registered, use enable() instead"
|
||||
)));
|
||||
}
|
||||
|
||||
|
||||
@@ -308,7 +308,7 @@ mod _locale {
|
||||
{
|
||||
// On Windows, use GetACP() to get the ANSI code page
|
||||
let acp = unsafe { GetACP() };
|
||||
format!("cp{}", acp)
|
||||
format!("cp{acp}")
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
|
||||
@@ -948,10 +948,10 @@ fn float_repr(value: f64) -> String {
|
||||
"-inf".to_owned()
|
||||
}
|
||||
} else {
|
||||
let s = format!("{}", value);
|
||||
let s = format!("{value}");
|
||||
// If no decimal point and not in scientific notation, add .0
|
||||
if !s.contains('.') && !s.contains('e') && !s.contains('E') {
|
||||
format!("{}.0", s)
|
||||
format!("{s}.0")
|
||||
} else {
|
||||
s
|
||||
}
|
||||
|
||||
@@ -579,7 +579,7 @@ mod mmap {
|
||||
let handle = unsafe { suppress_iph!(libc::get_osfhandle(fileno)) };
|
||||
// Check for invalid handle value (-1 on Windows)
|
||||
if handle == -1 || handle == INVALID_HANDLE_VALUE as isize {
|
||||
return Err(vm.new_os_error(format!("Invalid file descriptor: {}", fileno)));
|
||||
return Err(vm.new_os_error(format!("Invalid file descriptor: {fileno}")));
|
||||
}
|
||||
Some(handle as HANDLE)
|
||||
} else {
|
||||
|
||||
@@ -1555,13 +1555,11 @@ mod _overlapped {
|
||||
ERROR_SUCCESS | ERROR_NOT_FOUND | ERROR_OPERATION_ABORTED => {}
|
||||
_ => {
|
||||
let msg = format!(
|
||||
"{:?} still has pending operation at deallocation, the process may crash",
|
||||
zelf
|
||||
"{zelf:?} still has pending operation at deallocation, the process may crash"
|
||||
);
|
||||
let exc = vm.new_runtime_error(msg);
|
||||
let err_msg = Some(format!(
|
||||
"Exception ignored while deallocating overlapped operation {:?}",
|
||||
zelf
|
||||
"Exception ignored while deallocating overlapped operation {zelf:?}"
|
||||
));
|
||||
let obj: PyObjectRef = zelf.to_owned().into();
|
||||
vm.run_unraisable(exc, err_msg, obj);
|
||||
@@ -1656,9 +1654,8 @@ mod _overlapped {
|
||||
if overlapped.is_null() {
|
||||
if err == Foundation::WAIT_TIMEOUT {
|
||||
return Ok(vm.ctx.none());
|
||||
} else {
|
||||
return Err(set_from_windows_err(err, vm));
|
||||
}
|
||||
return Err(set_from_windows_err(err, vm));
|
||||
}
|
||||
|
||||
let value = vm.ctx.new_tuple(vec![
|
||||
|
||||
@@ -1492,8 +1492,7 @@ mod _socket {
|
||||
if bytes_data.len() != expected_size {
|
||||
return Err(vm
|
||||
.new_value_error(format!(
|
||||
"socket descriptor string has wrong size, should be {} bytes",
|
||||
expected_size
|
||||
"socket descriptor string has wrong size, should be {expected_size} bytes"
|
||||
))
|
||||
.into());
|
||||
}
|
||||
@@ -2393,7 +2392,7 @@ mod _socket {
|
||||
let cmd_val = cmd_int.as_bigint();
|
||||
let cmd: u32 = cmd_val
|
||||
.to_u32()
|
||||
.ok_or_else(|| vm.new_value_error(format!("invalid ioctl command {}", cmd_val)))?;
|
||||
.ok_or_else(|| vm.new_value_error(format!("invalid ioctl command {cmd_val}")))?;
|
||||
|
||||
match cmd {
|
||||
c::SIO_RCVALL | c::SIO_LOOPBACK_FAST_PATH => {
|
||||
@@ -2466,7 +2465,7 @@ mod _socket {
|
||||
Ok(recv)
|
||||
}
|
||||
_ => Err(vm
|
||||
.new_value_error(format!("invalid ioctl command {}", cmd))
|
||||
.new_value_error(format!("invalid ioctl command {cmd}"))
|
||||
.into()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4877,10 +4877,7 @@ mod _ssl {
|
||||
// Read certificate file
|
||||
let path_str = path.as_str();
|
||||
let cert_data = rustpython_host_env::fs::read(path_str).map_err(|e| {
|
||||
vm.new_os_error(format!(
|
||||
"Failed to read certificate file {}: {}",
|
||||
path_str, e
|
||||
))
|
||||
vm.new_os_error(format!("Failed to read certificate file {path_str}: {e}"))
|
||||
})?;
|
||||
|
||||
// Auto-detect PEM vs DER format
|
||||
@@ -4950,8 +4947,7 @@ mod _ssl {
|
||||
// If no stores could be opened, raise OSError
|
||||
if stores.is_empty() {
|
||||
return Err(vm.new_os_error(format!(
|
||||
"failed to open certificate store {:?}",
|
||||
store_name_str
|
||||
"failed to open certificate store {store_name_str:?}"
|
||||
)));
|
||||
}
|
||||
|
||||
@@ -5003,8 +4999,7 @@ mod _ssl {
|
||||
|
||||
if store.is_null() {
|
||||
return Err(vm.new_os_error(format!(
|
||||
"failed to open certificate store {:?}",
|
||||
store_name_str
|
||||
"failed to open certificate store {store_name_str:?}"
|
||||
)));
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ use crate::vm::{
|
||||
PyObject, PyResult, VirtualMachine, builtins::PyStr, convert::TryFromBorrowedObject,
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, Eq, PartialEq)]
|
||||
enum NormalizeForm {
|
||||
Nfc,
|
||||
Nfkc,
|
||||
|
||||
@@ -73,7 +73,7 @@ pub struct PyBool(pub PyInt);
|
||||
impl Debug for PyBool {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
|
||||
let value = !self.0.as_bigint().is_zero();
|
||||
write!(f, "PyBool({})", value)
|
||||
write!(f, "PyBool({value})")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -748,7 +748,7 @@ impl Constructor for PyCode {
|
||||
// Parse and validate bytecode from bytes
|
||||
let bytecode_bytes = args.co_code.as_bytes();
|
||||
let instructions = CodeUnits::try_from(bytecode_bytes)
|
||||
.map_err(|e| vm.new_value_error(format!("invalid bytecode: {}", e)))?;
|
||||
.map_err(|e| vm.new_value_error(format!("invalid bytecode: {e}")))?;
|
||||
|
||||
// Convert constants
|
||||
let constants = args
|
||||
@@ -1342,7 +1342,7 @@ impl PyCode {
|
||||
OptionalArg::Present(code_bytes) => {
|
||||
// Parse and validate bytecode from bytes
|
||||
CodeUnits::try_from(code_bytes.as_bytes())
|
||||
.map_err(|e| vm.new_value_error(format!("invalid bytecode: {}", e)))?
|
||||
.map_err(|e| vm.new_value_error(format!("invalid bytecode: {e}")))?
|
||||
}
|
||||
OptionalArg::Missing => self.code.instructions.clone(),
|
||||
};
|
||||
|
||||
@@ -107,24 +107,26 @@ impl PyObjectRef {
|
||||
)?;
|
||||
|
||||
return Ok(Some((ret.value, true)));
|
||||
} else {
|
||||
return match result.downcast_ref::<PyComplex>() {
|
||||
Some(complex_obj) => Ok(Some((complex_obj.value, true))),
|
||||
None => Err(vm.new_type_error(format!(
|
||||
"__complex__ returned non-complex (type '{}')",
|
||||
result.class().name()
|
||||
))),
|
||||
};
|
||||
}
|
||||
|
||||
return match result.downcast_ref::<PyComplex>() {
|
||||
Some(complex_obj) => Ok(Some((complex_obj.value, true))),
|
||||
None => Err(vm.new_type_error(format!(
|
||||
"__complex__ returned non-complex (type '{}')",
|
||||
result.class().name()
|
||||
))),
|
||||
};
|
||||
}
|
||||
// `complex` does not have a `__complex__` by default, so subclasses might not either,
|
||||
// use the actual stored value in this case
|
||||
if let Some(complex) = self.downcast_ref::<PyComplex>() {
|
||||
return Ok(Some((complex.value, true)));
|
||||
}
|
||||
|
||||
if let Some(float) = self.try_float_opt(vm) {
|
||||
return Ok(Some((Complex64::new(float?.to_f64(), 0.0), false)));
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -555,7 +555,7 @@ impl core::fmt::Debug for SlotFunc {
|
||||
SlotFunc::GetAttro(_) => write!(f, "SlotFunc::GetAttro(...)"),
|
||||
SlotFunc::SetAttro(_) => write!(f, "SlotFunc::SetAttro(...)"),
|
||||
SlotFunc::DelAttro(_) => write!(f, "SlotFunc::DelAttro(...)"),
|
||||
SlotFunc::RichCompare(_, op) => write!(f, "SlotFunc::RichCompare(..., {:?})", op),
|
||||
SlotFunc::RichCompare(_, op) => write!(f, "SlotFunc::RichCompare(..., {op:?})"),
|
||||
SlotFunc::DescrGet(_) => write!(f, "SlotFunc::DescrGet(...)"),
|
||||
SlotFunc::DescrSet(_) => write!(f, "SlotFunc::DescrSet(...)"),
|
||||
SlotFunc::DescrDel(_) => write!(f, "SlotFunc::DescrDel(...)"),
|
||||
|
||||
@@ -268,7 +268,7 @@ impl PyFunction {
|
||||
.map_or(0, |d| d.len());
|
||||
let n_required = n_expected_args - n_defaults;
|
||||
let takes_msg = if n_defaults > 0 {
|
||||
format!("from {} to {}", n_required, n_expected_args)
|
||||
format!("from {n_required} to {n_expected_args}")
|
||||
} else {
|
||||
n_expected_args.to_string()
|
||||
};
|
||||
|
||||
@@ -1247,9 +1247,8 @@ impl PyStr {
|
||||
let first = first?;
|
||||
if first.as_object().class().is(vm.ctx.types.str_type) {
|
||||
return Ok(first);
|
||||
} else {
|
||||
first.as_wtf8().to_owned()
|
||||
}
|
||||
first.as_wtf8().to_owned()
|
||||
}
|
||||
Err(iter) => zelf.as_wtf8().py_join(iter)?,
|
||||
};
|
||||
|
||||
@@ -314,17 +314,15 @@ impl IterNext for PyTemplateIter {
|
||||
continue;
|
||||
}
|
||||
return Ok(PyIterReturn::Return(item.clone()));
|
||||
} else {
|
||||
return Ok(PyIterReturn::StopIteration(None));
|
||||
}
|
||||
return Ok(PyIterReturn::StopIteration(None));
|
||||
} else if index < zelf.template.interpolations.len() {
|
||||
let item = zelf.template.interpolations.get(index).unwrap();
|
||||
zelf.index.fetch_add(1, Ordering::SeqCst);
|
||||
zelf.from_strings.store(true, Ordering::SeqCst);
|
||||
return Ok(PyIterReturn::Return(item.clone()));
|
||||
} else {
|
||||
return Ok(PyIterReturn::StopIteration(None));
|
||||
}
|
||||
return Ok(PyIterReturn::StopIteration(None));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2949,7 +2949,7 @@ fn mangle_name(class_name: &str, name: &str) -> String {
|
||||
}
|
||||
// Strip leading underscores from class name
|
||||
let class_name = class_name.trim_start_matches('_');
|
||||
format!("_{}{}", class_name, name)
|
||||
format!("_{class_name}{name}")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -797,9 +797,8 @@ impl PyBytesInner {
|
||||
new[offset..offset + len].clone_from_slice(to.elements.as_slice());
|
||||
if max_count == Some(1) {
|
||||
return new;
|
||||
} else {
|
||||
new
|
||||
}
|
||||
new
|
||||
} else {
|
||||
return self.elements.clone();
|
||||
};
|
||||
|
||||
+25
-11
@@ -299,6 +299,10 @@ impl<T: Clone> Dict<T> {
|
||||
// but still possible
|
||||
continue;
|
||||
};
|
||||
#[expect(
|
||||
clippy::redundant_else,
|
||||
reason = "Keeping the empty `else` block here for documentation"
|
||||
)]
|
||||
if entry.index == index_index {
|
||||
let removed = core::mem::replace(&mut entry.value, value);
|
||||
self.bump_version();
|
||||
@@ -400,11 +404,11 @@ impl<T: Clone> Dict<T> {
|
||||
if let Some(index) = entry.index() {
|
||||
let inner = self.read();
|
||||
if let Some(entry) = inner.get_entry_checked(index, index_index) {
|
||||
// The dict was not changed since we did lookup
|
||||
break Some(entry.value.clone());
|
||||
} else {
|
||||
// The dict was changed since we did lookup. Let's try again.
|
||||
continue;
|
||||
}
|
||||
|
||||
// The dict was changed since we did lookup. Let's try again.
|
||||
} else {
|
||||
break None;
|
||||
}
|
||||
@@ -511,15 +515,15 @@ impl<T: Clone> Dict<T> {
|
||||
ControlFlow::Break(Some(entry)) => break Some(entry),
|
||||
_ => continue,
|
||||
}
|
||||
} else {
|
||||
let mut inner = self.write();
|
||||
if inner.indices.get(index_index) != Some(&entry) {
|
||||
continue;
|
||||
}
|
||||
inner.unchecked_push(index_index, hash, key.to_owned(), value, entry);
|
||||
self.bump_version();
|
||||
break None;
|
||||
}
|
||||
|
||||
let mut inner = self.write();
|
||||
if inner.indices.get(index_index) != Some(&entry) {
|
||||
continue;
|
||||
}
|
||||
inner.unchecked_push(index_index, hash, key.to_owned(), value, entry);
|
||||
self.bump_version();
|
||||
break None;
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
@@ -718,6 +722,11 @@ impl<T: Clone> Dict<T> {
|
||||
inner.entries.get_unchecked(i).as_ref().unwrap_unchecked()
|
||||
};
|
||||
let ret = (idx, index_index);
|
||||
|
||||
#[expect(
|
||||
clippy::redundant_else,
|
||||
reason = "Keeping the empty `else` block here for documentation"
|
||||
)]
|
||||
if key.key_is(&entry.key) {
|
||||
break 'outer ret;
|
||||
} else if entry.hash == hash_value {
|
||||
@@ -730,6 +739,11 @@ impl<T: Clone> Dict<T> {
|
||||
// warn!("Perturb value: {}", i);
|
||||
}
|
||||
};
|
||||
|
||||
#[expect(
|
||||
clippy::redundant_else,
|
||||
reason = "Keeping the empty `else` block here for documentation"
|
||||
)]
|
||||
// This comparison needs to be done outside the lock.
|
||||
if key.key_eq(vm, &entry_key)? {
|
||||
break 'outer ret;
|
||||
|
||||
@@ -289,8 +289,7 @@ pub(super) mod types {
|
||||
for (i, exc) in exceptions.iter().enumerate() {
|
||||
if !exc.fast_isinstance(vm.ctx.exceptions.base_exception_type) {
|
||||
return Err(vm.new_value_error(format!(
|
||||
"Item {} of second argument (exceptions) is not an exception",
|
||||
i
|
||||
"Item {i} of second argument (exceptions) is not an exception"
|
||||
)));
|
||||
}
|
||||
// Check if any exception is not an Exception subclass
|
||||
|
||||
@@ -2404,8 +2404,7 @@ pub(super) mod types {
|
||||
}
|
||||
_ => {
|
||||
return Err(vm.new_type_error(format!(
|
||||
"function takes exactly 4 or 6 arguments ({} given)",
|
||||
location_tup_len
|
||||
"function takes exactly 4 or 6 arguments ({location_tup_len} given)"
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3104,8 +3104,7 @@ impl ExecutingFrame<'_> {
|
||||
.unwrap_or_else(|| String::from("?"));
|
||||
let match_args_type_name = match_args.class().__name__(vm);
|
||||
return Err(vm.new_type_error(format!(
|
||||
"{}.__match_args__ must be a tuple (got {})",
|
||||
type_name, match_args_type_name
|
||||
"{type_name}.__match_args__ must be a tuple (got {match_args_type_name})"
|
||||
)));
|
||||
}
|
||||
};
|
||||
@@ -3569,9 +3568,7 @@ impl ExecutingFrame<'_> {
|
||||
// This means swap TOS with the element at index (len - n)
|
||||
debug_assert!(
|
||||
index_val <= len,
|
||||
"SWAP index {} exceeds stack size {}",
|
||||
index_val,
|
||||
len
|
||||
"SWAP index {index_val} exceeds stack size {len}"
|
||||
);
|
||||
let j = len - index_val;
|
||||
self.localsplus.stack_swap(i, j);
|
||||
|
||||
@@ -26,7 +26,7 @@ mod platform {
|
||||
|
||||
pub(super) fn stdlib_landmarks() -> [String; 2] {
|
||||
let subdir = stdlib_subdir();
|
||||
[format!("{}/os.py", subdir), format!("{}/os.pyc", subdir)]
|
||||
[format!("{subdir}/os.py"), format!("{subdir}/os.pyc")]
|
||||
}
|
||||
|
||||
pub(super) fn platstdlib_landmark() -> String {
|
||||
|
||||
@@ -390,10 +390,10 @@ pub(crate) fn import_module_level(
|
||||
if level == 0 {
|
||||
let sys_modules = vm.sys_module.get_attr("modules", vm)?;
|
||||
return sys_modules.get_item(name, vm).map_err(|_| {
|
||||
vm.new_import_error(format!("No module named '{}'", name), name.to_owned())
|
||||
vm.new_import_error(format!("No module named '{name}'"), name.to_owned())
|
||||
});
|
||||
}
|
||||
return Err(vm.new_import_error(format!("No module named '{}'", name), name.to_owned()));
|
||||
return Err(vm.new_import_error(format!("No module named '{name}'"), name.to_owned()));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ impl PathConverter {
|
||||
/// Generate error message prefix like "rename: "
|
||||
fn error_prefix(&self) -> String {
|
||||
match self.function_name {
|
||||
Some(func) => format!("{}: ", func),
|
||||
Some(func) => format!("{func}: "),
|
||||
None => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,22 +239,19 @@ fn range_from_object(
|
||||
|
||||
if start_row_val > end_row_val {
|
||||
return Err(vm.new_value_error(format!(
|
||||
"AST node line range ({}, {}) is not valid",
|
||||
start_row_val, end_row_val
|
||||
"AST node line range ({start_row_val}, {end_row_val}) is not valid"
|
||||
)));
|
||||
}
|
||||
if (start_row_val < 0 && end_row_val != start_row_val)
|
||||
|| (start_col_val < 0 && end_col_val != start_col_val)
|
||||
{
|
||||
return Err(vm.new_value_error(format!(
|
||||
"AST node column range ({}, {}) for line range ({}, {}) is not valid",
|
||||
start_col_val, end_col_val, start_row_val, end_row_val
|
||||
"AST node column range ({start_col_val}, {end_col_val}) for line range ({start_row_val}, {end_row_val}) is not valid"
|
||||
)));
|
||||
}
|
||||
if start_row_val == end_row_val && start_col_val > end_col_val {
|
||||
return Err(vm.new_value_error(format!(
|
||||
"line {}, column {}-{} is not a valid range",
|
||||
start_row_val, start_col_val, end_col_val
|
||||
"line {start_row_val}, column {start_col_val}-{end_col_val} is not a valid range"
|
||||
)));
|
||||
}
|
||||
|
||||
|
||||
@@ -426,7 +426,7 @@ mod _codecs_windows {
|
||||
|
||||
if size == 0 {
|
||||
let err = std::io::Error::last_os_error();
|
||||
return Err(vm.new_os_error(format!("mbcs_encode failed: {}", err)));
|
||||
return Err(vm.new_os_error(format!("mbcs_encode failed: {err}")));
|
||||
}
|
||||
|
||||
let mut buffer = vec![0u8; size as usize];
|
||||
@@ -515,7 +515,7 @@ mod _codecs_windows {
|
||||
};
|
||||
if size == 0 {
|
||||
let err = std::io::Error::last_os_error();
|
||||
return Err(vm.new_os_error(format!("mbcs_decode failed: {}", err)));
|
||||
return Err(vm.new_os_error(format!("mbcs_decode failed: {err}")));
|
||||
}
|
||||
|
||||
let mut buffer = vec![0u16; size as usize];
|
||||
@@ -531,11 +531,11 @@ mod _codecs_windows {
|
||||
};
|
||||
if result == 0 {
|
||||
let err = std::io::Error::last_os_error();
|
||||
return Err(vm.new_os_error(format!("mbcs_decode failed: {}", err)));
|
||||
return Err(vm.new_os_error(format!("mbcs_decode failed: {err}")));
|
||||
}
|
||||
buffer.truncate(result as usize);
|
||||
let s = String::from_utf16(&buffer)
|
||||
.map_err(|e| vm.new_unicode_decode_error(format!("mbcs_decode failed: {}", e)))?;
|
||||
.map_err(|e| vm.new_unicode_decode_error(format!("mbcs_decode failed: {e}")))?;
|
||||
return Ok((s, len));
|
||||
}
|
||||
|
||||
@@ -553,11 +553,11 @@ mod _codecs_windows {
|
||||
};
|
||||
if result == 0 {
|
||||
let err = std::io::Error::last_os_error();
|
||||
return Err(vm.new_os_error(format!("mbcs_decode failed: {}", err)));
|
||||
return Err(vm.new_os_error(format!("mbcs_decode failed: {err}")));
|
||||
}
|
||||
buffer.truncate(result as usize);
|
||||
let s = String::from_utf16(&buffer)
|
||||
.map_err(|e| vm.new_unicode_decode_error(format!("mbcs_decode failed: {}", e)))?;
|
||||
.map_err(|e| vm.new_unicode_decode_error(format!("mbcs_decode failed: {e}")))?;
|
||||
|
||||
Ok((s, len))
|
||||
}
|
||||
@@ -612,7 +612,7 @@ mod _codecs_windows {
|
||||
|
||||
if size == 0 {
|
||||
let err = std::io::Error::last_os_error();
|
||||
return Err(vm.new_os_error(format!("oem_encode failed: {}", err)));
|
||||
return Err(vm.new_os_error(format!("oem_encode failed: {err}")));
|
||||
}
|
||||
|
||||
let mut buffer = vec![0u8; size as usize];
|
||||
@@ -701,7 +701,7 @@ mod _codecs_windows {
|
||||
};
|
||||
if size == 0 {
|
||||
let err = std::io::Error::last_os_error();
|
||||
return Err(vm.new_os_error(format!("oem_decode failed: {}", err)));
|
||||
return Err(vm.new_os_error(format!("oem_decode failed: {err}")));
|
||||
}
|
||||
|
||||
let mut buffer = vec![0u16; size as usize];
|
||||
@@ -717,11 +717,11 @@ mod _codecs_windows {
|
||||
};
|
||||
if result == 0 {
|
||||
let err = std::io::Error::last_os_error();
|
||||
return Err(vm.new_os_error(format!("oem_decode failed: {}", err)));
|
||||
return Err(vm.new_os_error(format!("oem_decode failed: {err}")));
|
||||
}
|
||||
buffer.truncate(result as usize);
|
||||
let s = String::from_utf16(&buffer)
|
||||
.map_err(|e| vm.new_unicode_decode_error(format!("oem_decode failed: {}", e)))?;
|
||||
.map_err(|e| vm.new_unicode_decode_error(format!("oem_decode failed: {e}")))?;
|
||||
return Ok((s, len));
|
||||
}
|
||||
|
||||
@@ -739,11 +739,11 @@ mod _codecs_windows {
|
||||
};
|
||||
if result == 0 {
|
||||
let err = std::io::Error::last_os_error();
|
||||
return Err(vm.new_os_error(format!("oem_decode failed: {}", err)));
|
||||
return Err(vm.new_os_error(format!("oem_decode failed: {err}")));
|
||||
}
|
||||
buffer.truncate(result as usize);
|
||||
let s = String::from_utf16(&buffer)
|
||||
.map_err(|e| vm.new_unicode_decode_error(format!("oem_decode failed: {}", e)))?;
|
||||
.map_err(|e| vm.new_unicode_decode_error(format!("oem_decode failed: {e}")))?;
|
||||
|
||||
Ok((s, len))
|
||||
}
|
||||
|
||||
@@ -286,7 +286,7 @@ pub(crate) mod _ctypes {
|
||||
FfiArgValue::I64(v) => v,
|
||||
_ => 0,
|
||||
};
|
||||
Ok(format!("<cparam '{}' ({})>", tag_char, n))
|
||||
Ok(format!("<cparam '{tag_char}' ({n})>"))
|
||||
}
|
||||
b'B' | b'H' | b'I' | b'L' | b'Q' => {
|
||||
// Unsigned integers
|
||||
@@ -297,14 +297,14 @@ pub(crate) mod _ctypes {
|
||||
FfiArgValue::U64(v) => v,
|
||||
_ => 0,
|
||||
};
|
||||
Ok(format!("<cparam '{}' ({})>", tag_char, n))
|
||||
Ok(format!("<cparam '{tag_char}' ({n})>"))
|
||||
}
|
||||
b'f' => {
|
||||
let v = match zelf.value {
|
||||
FfiArgValue::F32(v) => v as f64,
|
||||
_ => 0.0,
|
||||
};
|
||||
Ok(format!("<cparam '{}' ({})>", tag_char, v))
|
||||
Ok(format!("<cparam '{tag_char}' ({v})>"))
|
||||
}
|
||||
b'd' | b'g' => {
|
||||
let v = match zelf.value {
|
||||
@@ -312,7 +312,7 @@ pub(crate) mod _ctypes {
|
||||
FfiArgValue::F32(v) => v as f64,
|
||||
_ => 0.0,
|
||||
};
|
||||
Ok(format!("<cparam '{}' ({})>", tag_char, v))
|
||||
Ok(format!("<cparam '{tag_char}' ({v})>"))
|
||||
}
|
||||
b'c' => {
|
||||
// c_char - single byte
|
||||
@@ -324,7 +324,7 @@ pub(crate) mod _ctypes {
|
||||
if is_literal_char(byte) {
|
||||
Ok(format!("<cparam '{}' ('{}')>", tag_char, byte as char))
|
||||
} else {
|
||||
Ok(format!("<cparam '{}' ('\\x{:02x}')>", tag_char, byte))
|
||||
Ok(format!("<cparam '{tag_char}' ('\\x{byte:02x}')>"))
|
||||
}
|
||||
}
|
||||
b'z' | b'Z' | b'P' | b'V' => {
|
||||
@@ -334,16 +334,16 @@ pub(crate) mod _ctypes {
|
||||
_ => 0,
|
||||
};
|
||||
if ptr == 0 {
|
||||
Ok(format!("<cparam '{}' (nil)>", tag_char))
|
||||
Ok(format!("<cparam '{tag_char}' (nil)>"))
|
||||
} else {
|
||||
Ok(format!("<cparam '{}' ({:#x})>", tag_char, ptr))
|
||||
Ok(format!("<cparam '{tag_char}' ({ptr:#x})>"))
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
// Default fallback
|
||||
let addr = zelf.get_id();
|
||||
if is_literal_char(zelf.tag) {
|
||||
Ok(format!("<cparam '{}' at {:#x}>", tag_char, addr))
|
||||
Ok(format!("<cparam '{tag_char}' at {addr:#x}>"))
|
||||
} else {
|
||||
Ok(format!("<cparam {:#04x} at {:#x}>", zelf.tag, addr))
|
||||
}
|
||||
@@ -575,7 +575,7 @@ pub(crate) mod _ctypes {
|
||||
.get_or_insert_lib_with_mode(&*os_str, mode, vm)
|
||||
.map_err(|e| {
|
||||
let name_str = os_str.to_string_lossy();
|
||||
vm.new_os_error(format!("{}: {}", name_str, e))
|
||||
vm.new_os_error(format!("{name_str}: {e}"))
|
||||
})?;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
@@ -358,7 +358,7 @@ pub(super) fn get_field_format(
|
||||
// For simple types, replace existing endian prefix with the correct one
|
||||
let base_fmt = fmt.trim_start_matches(['<', '>', '@', '=', '!']);
|
||||
if !base_fmt.is_empty() {
|
||||
return format!("{}{}", endian_prefix, base_fmt);
|
||||
return format!("{endian_prefix}{base_fmt}");
|
||||
}
|
||||
return fmt.clone();
|
||||
}
|
||||
@@ -370,7 +370,7 @@ pub(super) fn get_field_format(
|
||||
let s = type_str
|
||||
.to_str()
|
||||
.expect("_type_ is validated as ASCII at type creation");
|
||||
return format!("{}{}", endian_prefix, s);
|
||||
return format!("{endian_prefix}{s}");
|
||||
}
|
||||
|
||||
// Default: single byte
|
||||
@@ -962,9 +962,8 @@ impl PyCData {
|
||||
self.write_bytes_at_offset(offset, &to_copy[..copy_len]);
|
||||
self.keep_ref(index, value, vm)?;
|
||||
return Ok(());
|
||||
} else {
|
||||
return Err(vm.new_type_error("bytes expected instead of str instance"));
|
||||
}
|
||||
return Err(vm.new_type_error("bytes expected instead of str instance"));
|
||||
}
|
||||
|
||||
// For c_wchar arrays with str input, convert to wchar_t
|
||||
@@ -1509,8 +1508,7 @@ impl Constructor for PyCField {
|
||||
let type_bits = byte_size * 8;
|
||||
if bo + bs > type_bits {
|
||||
return Err(vm.new_value_error(format!(
|
||||
"bit field '{}' overflows its type ({} + {} > {})",
|
||||
name, bo, bs, type_bits
|
||||
"bit field '{name}' overflows its type ({bo} + {bs} > {type_bits})"
|
||||
)));
|
||||
}
|
||||
Ok(Self::new_bitfield(
|
||||
|
||||
@@ -1038,7 +1038,7 @@ impl Constructor for PyCFuncPtr {
|
||||
// dlsym can return NULL for symbols that resolve to NULL (e.g., GNU IFUNC)
|
||||
// Treat NULL addresses as errors
|
||||
if addr == 0 {
|
||||
return Err(vm.new_attribute_error(format!("function '{}' not found", name)));
|
||||
return Err(vm.new_attribute_error(format!("function '{name}' not found")));
|
||||
}
|
||||
addr
|
||||
} else {
|
||||
@@ -1479,7 +1479,7 @@ fn build_callargs_with_paramflags(
|
||||
} else if let Some(def) = default {
|
||||
def.clone()
|
||||
} else {
|
||||
return Err(vm.new_type_error(format!("required argument {} missing", param_idx)));
|
||||
return Err(vm.new_type_error(format!("required argument {param_idx} missing")));
|
||||
};
|
||||
|
||||
if is_out {
|
||||
@@ -1837,7 +1837,7 @@ impl Representable for PyCFuncPtr {
|
||||
let type_name = zelf.class().name();
|
||||
// Use object id, not function pointer address
|
||||
let addr = zelf.get_id();
|
||||
Ok(format!("<{} object at {:#x}>", type_name, addr))
|
||||
Ok(format!("<{type_name} object at {addr:#x}>"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2182,10 +2182,7 @@ unsafe extern "C" fn thunk_callback(
|
||||
.callable
|
||||
.repr(vm)
|
||||
.map_or_else(|_| "<unknown>".to_string(), |s| s.to_string());
|
||||
let msg = format!(
|
||||
"Exception ignored while calling ctypes callback function {}",
|
||||
repr
|
||||
);
|
||||
let msg = format!("Exception ignored while calling ctypes callback function {repr}");
|
||||
vm.run_unraisable(exc.clone(), Some(msg), vm.ctx.none());
|
||||
}
|
||||
|
||||
|
||||
@@ -65,7 +65,7 @@ impl Initializer for PyCPointerType {
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
stg_info.format = Some(format!("&{}{}", shape_str, current_format));
|
||||
stg_info.format = Some(format!("&{shape_str}{current_format}"));
|
||||
}
|
||||
|
||||
let _ = new_type.init_type_data(stg_info);
|
||||
@@ -204,7 +204,7 @@ impl PyCPointerType {
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
stg_info.format = Some(format!("&{}{}", shape_str, current_format));
|
||||
stg_info.format = Some(format!("&{shape_str}{current_format}"));
|
||||
}
|
||||
|
||||
// 4. Set _type_ attribute on the pointer type
|
||||
@@ -648,9 +648,8 @@ impl PyCPointer {
|
||||
*(addr as *mut usize) = ptr_val;
|
||||
}
|
||||
return zelf.0.keep_ref(index as usize, holder, vm);
|
||||
} else {
|
||||
Self::write_value_at_address(addr, element_size, &value, type_code.as_deref(), vm)?;
|
||||
}
|
||||
Self::write_value_at_address(addr, element_size, &value, type_code.as_deref(), vm)?;
|
||||
}
|
||||
|
||||
// KeepRef: store reference to keep value alive using actual index
|
||||
|
||||
@@ -56,7 +56,7 @@ fn ctypes_code_to_pep3118(code: char) -> char {
|
||||
fn alloc_format_string_for_type(code: char, big_endian: bool) -> String {
|
||||
let prefix = if big_endian { ">" } else { "<" };
|
||||
let pep_code = ctypes_code_to_pep3118(code);
|
||||
format!("{}{}", prefix, pep_code)
|
||||
format!("{prefix}{pep_code}")
|
||||
}
|
||||
|
||||
/// Create a new simple type instance from a class
|
||||
@@ -574,8 +574,7 @@ impl Initializer for PyCSimpleType {
|
||||
// Validate _type_ is a valid type character
|
||||
if !SIMPLE_TYPE_CHARS.contains(type_str.as_str()) {
|
||||
return Err(vm.new_attribute_error(format!(
|
||||
"class must define a '_type_' attribute which must be a single character string containing one of '{}', currently it is '{}'.",
|
||||
SIMPLE_TYPE_CHARS, type_str
|
||||
"class must define a '_type_' attribute which must be a single character string containing one of '{SIMPLE_TYPE_CHARS}', currently it is '{type_str}'."
|
||||
)));
|
||||
}
|
||||
|
||||
@@ -1131,11 +1130,11 @@ impl Representable for PyCSimple {
|
||||
// Direct SimpleCData: "typename(repr(value))"
|
||||
let value = PyCSimple::value(zelf.to_owned().into(), vm)?;
|
||||
let value_repr = value.repr(vm)?.to_string();
|
||||
Ok(format!("{}({})", type_name, value_repr))
|
||||
Ok(format!("{type_name}({value_repr})"))
|
||||
} else {
|
||||
// Subclass: "<typename object at addr>"
|
||||
let addr = zelf.get_id();
|
||||
Ok(format!("<{} object at {:#x}>", type_name, addr))
|
||||
Ok(format!("<{type_name} object at {addr:#x}>"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -405,7 +405,7 @@ impl PyCStructType {
|
||||
.map(|d| d.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
format.push_str(&std::format!("({}){}", shape_str, field_format));
|
||||
format.push_str(&std::format!("({shape_str}){field_format}"));
|
||||
} else {
|
||||
format.push_str(&field_format);
|
||||
}
|
||||
@@ -749,10 +749,9 @@ impl PyCStructure {
|
||||
let field_name = name_str.as_str().to_owned();
|
||||
// Check for duplicate in kwargs
|
||||
if kwargs.contains_key(&field_name) {
|
||||
return Err(vm.new_type_error(format!(
|
||||
"duplicate values for field {:?}",
|
||||
field_name
|
||||
)));
|
||||
return Err(
|
||||
vm.new_type_error(format!("duplicate values for field {field_name:?}"))
|
||||
);
|
||||
}
|
||||
self_obj.as_object().set_attr(
|
||||
vm.ctx.intern_str(field_name),
|
||||
|
||||
@@ -620,10 +620,9 @@ impl PyCUnion {
|
||||
let field_name = name_str.as_str().to_owned();
|
||||
// Check for duplicate in kwargs
|
||||
if kwargs.contains_key(&field_name) {
|
||||
return Err(vm.new_type_error(format!(
|
||||
"duplicate values for field {:?}",
|
||||
field_name
|
||||
)));
|
||||
return Err(
|
||||
vm.new_type_error(format!("duplicate values for field {field_name:?}"))
|
||||
);
|
||||
}
|
||||
self_obj.as_object().set_attr(
|
||||
vm.ctx.intern_str(field_name),
|
||||
|
||||
@@ -333,8 +333,7 @@ mod _functools {
|
||||
if is_placeholder(value) {
|
||||
return Err(vm.new_type_error(format!(
|
||||
"Placeholder cannot be passed as a keyword argument to partial(). \
|
||||
Did you mean partial(..., {}=Placeholder, ...)(value)?",
|
||||
key
|
||||
Did you mean partial(..., {key}=Placeholder, ...)(value)?"
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
+30
-32
@@ -1153,41 +1153,41 @@ mod _io {
|
||||
}
|
||||
vm.check_signals()?;
|
||||
}
|
||||
None => {
|
||||
None if remaining > self.buffer.len() => {
|
||||
// raw file is non-blocking
|
||||
if remaining > self.buffer.len() {
|
||||
// can't buffer everything, buffer what we can and error
|
||||
let buf = buffer.as_contiguous().unwrap();
|
||||
let buffer_len = self.buffer.len();
|
||||
self.buffer.copy_from_slice(&buf[written..][..buffer_len]);
|
||||
self.raw_pos = 0;
|
||||
let buffer_size = self.buffer.len() as _;
|
||||
self.adjust_position(buffer_size);
|
||||
self.write_end = buffer_size;
|
||||
// BlockingIOError(errno, msg, characters_written)
|
||||
let chars_written = written + buffer_len;
|
||||
return Err(vm.invoke_exception(
|
||||
vm.ctx.exceptions.blocking_io_error.to_owned(),
|
||||
vec![
|
||||
vm.new_pyobj(EAGAIN),
|
||||
vm.new_pyobj("write could not complete without blocking"),
|
||||
vm.new_pyobj(chars_written),
|
||||
],
|
||||
)?);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
// can't buffer everything, buffer what we can and error
|
||||
let buf = buffer.as_contiguous().unwrap();
|
||||
let buffer_len = self.buffer.len();
|
||||
self.buffer.copy_from_slice(&buf[written..][..buffer_len]);
|
||||
self.raw_pos = 0;
|
||||
let buffer_size = self.buffer.len() as _;
|
||||
self.adjust_position(buffer_size);
|
||||
self.write_end = buffer_size;
|
||||
// BlockingIOError(errno, msg, characters_written)
|
||||
let chars_written = written + buffer_len;
|
||||
return Err(vm.invoke_exception(
|
||||
vm.ctx.exceptions.blocking_io_error.to_owned(),
|
||||
vec![
|
||||
vm.new_pyobj(EAGAIN),
|
||||
vm.new_pyobj("write could not complete without blocking"),
|
||||
vm.new_pyobj(chars_written),
|
||||
],
|
||||
)?);
|
||||
}
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
|
||||
if self.readable() {
|
||||
self.reset_read();
|
||||
}
|
||||
|
||||
if remaining > 0 {
|
||||
let buf = buffer.as_contiguous().unwrap();
|
||||
self.buffer[..remaining].copy_from_slice(&buf[written..][..remaining]);
|
||||
written += remaining;
|
||||
}
|
||||
|
||||
self.write_pos = 0;
|
||||
self.write_end = remaining as _;
|
||||
self.adjust_position(remaining as _);
|
||||
@@ -2340,11 +2340,10 @@ mod _io {
|
||||
let pos_after = p + 2;
|
||||
if ch_after_cr == b'\n' {
|
||||
break Ok(searched + pos_after);
|
||||
} else {
|
||||
searched += pos_after;
|
||||
remaining = &remaining[pos_after..];
|
||||
continue;
|
||||
}
|
||||
searched += pos_after;
|
||||
remaining = &remaining[pos_after..];
|
||||
continue;
|
||||
}
|
||||
None => break Err(searched + p),
|
||||
},
|
||||
@@ -3247,12 +3246,11 @@ mod _io {
|
||||
reset_encoder(encoder, start_of_stream)?;
|
||||
}
|
||||
return Ok(res);
|
||||
} else {
|
||||
return Err(new_unsupported_operation(
|
||||
vm,
|
||||
"can't do nonzero end-relative seeks".to_owned(),
|
||||
));
|
||||
}
|
||||
return Err(new_unsupported_operation(
|
||||
vm,
|
||||
"can't do nonzero end-relative seeks".to_owned(),
|
||||
));
|
||||
}
|
||||
_ => {
|
||||
return Err(
|
||||
|
||||
@@ -228,7 +228,7 @@ pub(crate) mod _signal {
|
||||
libc::SIGABRT,
|
||||
];
|
||||
if !VALID_SIGNALS.contains(&signalnum) {
|
||||
return Err(vm.new_value_error(format!("signal number {} out of range", signalnum)));
|
||||
return Err(vm.new_value_error(format!("signal number {signalnum} out of range")));
|
||||
}
|
||||
}
|
||||
if !vm.is_main_thread() {
|
||||
@@ -507,7 +507,7 @@ pub(crate) mod _signal {
|
||||
|
||||
let res = unsafe { libc::raise(signalnum) };
|
||||
if res != 0 {
|
||||
return Err(vm.new_os_error(format!("raise_signal failed for signal {}", signalnum)));
|
||||
return Err(vm.new_os_error(format!("raise_signal failed for signal {signalnum}")));
|
||||
}
|
||||
|
||||
// Check if a signal was triggered and handle it
|
||||
@@ -521,7 +521,7 @@ pub(crate) mod _signal {
|
||||
#[pyfunction]
|
||||
fn strsignal(signalnum: i32, vm: &VirtualMachine) -> PyResult<Option<String>> {
|
||||
if signalnum < 1 || signalnum >= signal::NSIG as i32 {
|
||||
return Err(vm.new_value_error(format!("signal number {} out of range", signalnum)));
|
||||
return Err(vm.new_value_error(format!("signal number {signalnum} out of range")));
|
||||
}
|
||||
let s = unsafe { libc::strsignal(signalnum) };
|
||||
if s.is_null() {
|
||||
@@ -536,7 +536,7 @@ pub(crate) mod _signal {
|
||||
#[pyfunction]
|
||||
fn strsignal(signalnum: i32, vm: &VirtualMachine) -> PyResult<Option<String>> {
|
||||
if signalnum < 1 || signalnum >= signal::NSIG as i32 {
|
||||
return Err(vm.new_value_error(format!("signal number {} out of range", signalnum)));
|
||||
return Err(vm.new_value_error(format!("signal number {signalnum} out of range")));
|
||||
}
|
||||
// Windows doesn't have strsignal(), provide our own mapping
|
||||
let name = match signalnum {
|
||||
|
||||
@@ -863,11 +863,7 @@ pub(crate) mod _thread {
|
||||
};
|
||||
let name = thread_name.unwrap_or_else(|| Wtf8Buf::from(format!("{}", get_ident())));
|
||||
|
||||
let _ = vm.call_method(
|
||||
&file,
|
||||
"write",
|
||||
(format!("Exception in thread {}:\n", name),),
|
||||
);
|
||||
let _ = vm.call_method(&file, "write", (format!("Exception in thread {name}:\n"),));
|
||||
|
||||
// Display the traceback
|
||||
if let Ok(traceback_mod) = vm.import("traceback", 0)
|
||||
|
||||
@@ -172,7 +172,7 @@ pub(crate) mod decl {
|
||||
} else {
|
||||
parts.join(", ")
|
||||
};
|
||||
Ok(vm.ctx.new_str(format!("({})", inner)).into())
|
||||
Ok(vm.ctx.new_str(format!("({inner})")).into())
|
||||
} else {
|
||||
Ok(vm.ctx.new_str(typing_type_repr(value, vm)?).into())
|
||||
}
|
||||
@@ -181,7 +181,7 @@ pub(crate) mod decl {
|
||||
impl Representable for ConstEvaluator {
|
||||
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
|
||||
let value_repr = zelf.value.repr(vm)?;
|
||||
Ok(format!("<constevaluator {}>", value_repr))
|
||||
Ok(format!("<constevaluator {value_repr}>"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -104,11 +104,11 @@ mod _warnings {
|
||||
let cat_obj = match category {
|
||||
Some(c) if !vm.is_none(&c) => c,
|
||||
_ => {
|
||||
if message.fast_isinstance(vm.ctx.exceptions.warning) {
|
||||
return Ok(Some(message.class().to_owned()));
|
||||
return Ok(if message.fast_isinstance(vm.ctx.exceptions.warning) {
|
||||
Some(message.class().to_owned())
|
||||
} else {
|
||||
return Ok(None); // will default to UserWarning in warn_explicit
|
||||
}
|
||||
None // will default to UserWarning in warn_explicit
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1599,8 +1599,7 @@ mod _winapi {
|
||||
let max_total_objects = (MAXIMUM_WAIT_OBJECTS - 1) * (MAXIMUM_WAIT_OBJECTS - 1);
|
||||
if nhandles > max_total_objects {
|
||||
return Err(vm.new_value_error(format!(
|
||||
"need at most {} handles, got a sequence of length {}",
|
||||
max_total_objects, nhandles
|
||||
"need at most {max_total_objects} handles, got a sequence of length {nhandles}"
|
||||
)));
|
||||
}
|
||||
|
||||
|
||||
@@ -688,10 +688,9 @@ mod _wmi {
|
||||
}
|
||||
|
||||
if err == ERROR_MORE_DATA {
|
||||
return Err(vm.new_os_error(format!(
|
||||
"Query returns more than {} characters",
|
||||
BUFFER_SIZE,
|
||||
)));
|
||||
return Err(
|
||||
vm.new_os_error(format!("Query returns more than {BUFFER_SIZE} characters"))
|
||||
);
|
||||
} else if err != 0 {
|
||||
return Err(std::io::Error::from_raw_os_error(err as i32).to_pyexception(vm));
|
||||
}
|
||||
|
||||
@@ -1121,6 +1121,10 @@ mod builtins {
|
||||
start: OptionalArg<PyObjectRef>,
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::redundant_else,
|
||||
reason = "match_class! macro expansion arms has a `return` inside"
|
||||
)]
|
||||
#[pyfunction]
|
||||
fn sum(SumArgs { iterable, start }: SumArgs, vm: &VirtualMachine) -> PyResult {
|
||||
// Start with zero and add at will:
|
||||
@@ -1130,17 +1134,13 @@ mod builtins {
|
||||
|
||||
match_class!(match sum {
|
||||
PyStr =>
|
||||
return Err(vm.new_type_error(
|
||||
"sum() can't sum strings [use ''.join(seq) instead]".to_owned()
|
||||
)),
|
||||
return Err(vm.new_type_error("sum() can't sum strings [use ''.join(seq) instead]")),
|
||||
PyBytes =>
|
||||
return Err(vm.new_type_error(
|
||||
"sum() can't sum bytes [use b''.join(seq) instead]".to_owned()
|
||||
)),
|
||||
return Err(vm.new_type_error("sum() can't sum bytes [use b''.join(seq) instead]")),
|
||||
PyByteArray =>
|
||||
return Err(vm.new_type_error(
|
||||
"sum() can't sum bytearray [use b''.join(seq) instead]".to_owned()
|
||||
)),
|
||||
return Err(
|
||||
vm.new_type_error("sum() can't sum bytearray [use b''.join(seq) instead]")
|
||||
),
|
||||
_ => (),
|
||||
});
|
||||
|
||||
@@ -1336,15 +1336,13 @@ mod builtins {
|
||||
{
|
||||
let cell_value = classcell.get().ok_or_else(|| {
|
||||
vm.new_runtime_error(format!(
|
||||
"__class__ not set defining {:?} as {:?}. Was __classcell__ propagated to type.__new__?",
|
||||
name, class
|
||||
"__class__ not set defining {name:?} as {class:?}. Was __classcell__ propagated to type.__new__?"
|
||||
))
|
||||
})?;
|
||||
|
||||
if !cell_value.is(&class) {
|
||||
return Err(vm.new_type_error(format!(
|
||||
"__class__ set to {:?} defining {:?} as {:?}",
|
||||
cell_value, name, class
|
||||
"__class__ set to {cell_value:?} defining {name:?} as {class:?}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,7 +163,7 @@ mod gc {
|
||||
if let Some(g) = generation_opt
|
||||
&& !(0..=2).contains(&g)
|
||||
{
|
||||
return Err(vm.new_value_error(format!("generation must be in range(0, 3), not {}", g)));
|
||||
return Err(vm.new_value_error(format!("generation must be in range(0, 3), not {g}")));
|
||||
}
|
||||
let objects = gc_state::gc_state().get_objects(generation_opt);
|
||||
Ok(vm.ctx.new_list(objects))
|
||||
|
||||
@@ -1249,26 +1249,26 @@ mod decl {
|
||||
if idx < 0 {
|
||||
zelf.exhausted.store(true);
|
||||
return Ok(PyIterReturn::StopIteration(None));
|
||||
} else {
|
||||
// Increment the current index which we know is not at its
|
||||
// maximum. Then move back to the right setting each index
|
||||
// to its lowest possible value (one higher than the index
|
||||
// to its left -- this maintains the sort order invariant).
|
||||
indices[idx as usize] += 1;
|
||||
for j in idx as usize + 1..r {
|
||||
indices[j] = indices[j - 1] + 1;
|
||||
}
|
||||
|
||||
// Update the result tuple for the new indices
|
||||
// starting with i, the leftmost index that changed
|
||||
for i in idx as usize..r {
|
||||
let index = indices[i];
|
||||
let elem = &zelf.pool[index];
|
||||
elem.clone_into(&mut result[i]);
|
||||
}
|
||||
|
||||
result.to_vec()
|
||||
}
|
||||
|
||||
// Increment the current index which we know is not at its
|
||||
// maximum. Then move back to the right setting each index
|
||||
// to its lowest possible value (one higher than the index
|
||||
// to its left -- this maintains the sort order invariant).
|
||||
indices[idx as usize] += 1;
|
||||
for j in idx as usize + 1..r {
|
||||
indices[j] = indices[j - 1] + 1;
|
||||
}
|
||||
|
||||
// Update the result tuple for the new indices
|
||||
// starting with i, the leftmost index that changed
|
||||
for i in idx as usize..r {
|
||||
let index = indices[i];
|
||||
let elem = &zelf.pool[index];
|
||||
elem.clone_into(&mut result[i]);
|
||||
}
|
||||
|
||||
result.to_vec()
|
||||
} else {
|
||||
let res = zelf.pool[0..r].to_vec();
|
||||
*result_lock = Some(res.clone());
|
||||
|
||||
@@ -1087,7 +1087,7 @@ pub(crate) mod module {
|
||||
return Err(vm.new_value_error("illegal environment variable name"));
|
||||
}
|
||||
|
||||
let env_str = format!("{}={}", key_str, value_str);
|
||||
let env_str = format!("{key_str}={value_str}");
|
||||
env_strings.push(
|
||||
widestring::WideCString::from_os_str(&*std::ffi::OsString::from(env_str))
|
||||
.map_err(|err| err.to_pyexception(vm))?,
|
||||
@@ -1209,7 +1209,7 @@ pub(crate) mod module {
|
||||
return Err(vm.new_value_error("illegal environment variable name"));
|
||||
}
|
||||
|
||||
let env_str = format!("{}={}", key_str, value_str);
|
||||
let env_str = format!("{key_str}={value_str}");
|
||||
env_strings.push(make_widestring(&env_str)?);
|
||||
}
|
||||
|
||||
|
||||
@@ -515,7 +515,7 @@ pub(super) mod _os {
|
||||
{
|
||||
return Err(vm.new_value_error("illegal environment variable name"));
|
||||
}
|
||||
let env_str = format!("{}={}", key_str, value_str);
|
||||
let env_str = format!("{key_str}={value_str}");
|
||||
let wide = env_str.to_wide_with_nul();
|
||||
check_env_var_len(wide.len(), vm)?;
|
||||
|
||||
@@ -562,7 +562,7 @@ pub(super) mod _os {
|
||||
return Err(vm.new_value_error("illegal environment variable name"));
|
||||
}
|
||||
// "key=" to unset (empty value removes the variable)
|
||||
let env_str = format!("{}=", key_str);
|
||||
let env_str = format!("{key_str}=");
|
||||
let wide = env_str.to_wide_with_nul();
|
||||
check_env_var_len(wide.len(), vm)?;
|
||||
|
||||
|
||||
@@ -906,8 +906,7 @@ pub mod module {
|
||||
if num_threads > 1 {
|
||||
let pid = unsafe { libc::getpid() };
|
||||
let msg = format!(
|
||||
"This process (pid={}) is multi-threaded, use of {}() may lead to deadlocks in the child.",
|
||||
pid, name
|
||||
"This process (pid={pid}) is multi-threaded, use of {name}() may lead to deadlocks in the child."
|
||||
);
|
||||
|
||||
// Match PyErr_WarnFormat(..., stacklevel=1) in CPython.
|
||||
|
||||
@@ -1250,7 +1250,7 @@ pub mod sys {
|
||||
if let Ok(module_str) = module_name.downcast::<PyStr>() {
|
||||
let module = module_str.as_wtf8();
|
||||
if module != "builtins" && module != "__main__" {
|
||||
write!(stderr, "{}.", module);
|
||||
write!(stderr, "{module}.");
|
||||
}
|
||||
} else {
|
||||
write!(stderr, "<unknown>.");
|
||||
|
||||
@@ -1664,8 +1664,7 @@ pub trait Initializer: PyPayload {
|
||||
== 2;
|
||||
if double_appearance {
|
||||
panic!(
|
||||
"This type `{}` doesn't seem to support `init`. Override `slot_init` instead: {}",
|
||||
class_name_for_debug, msg
|
||||
"This type `{class_name_for_debug}` doesn't seem to support `init`. Override `slot_init` instead: {msg}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,7 +239,7 @@ pub trait PyStructSequence: StaticType + PyClassImpl + Sized + 'static {
|
||||
_ => alloc::borrow::Cow::Borrowed(Self::TP_NAME),
|
||||
}
|
||||
};
|
||||
let repr_str = format!("{}({}{})", type_name, body, suffix);
|
||||
let repr_str = format!("{type_name}({body}{suffix})");
|
||||
Ok(vm.ctx.new_str(repr_str))
|
||||
}
|
||||
|
||||
@@ -277,7 +277,7 @@ pub trait PyStructSequence: StaticType + PyClassImpl + Sized + 'static {
|
||||
// Check for unexpected keyword arguments
|
||||
if !kwargs.is_empty() {
|
||||
let names: Vec<&str> = kwargs.keys().map(|k| k.as_str()).collect();
|
||||
return Err(vm.new_type_error(format!("Got unexpected field name(s): {:?}", names)));
|
||||
return Err(vm.new_type_error(format!("Got unexpected field name(s): {names:?}")));
|
||||
}
|
||||
|
||||
PyTuple::new_unchecked(items.into_boxed_slice())
|
||||
|
||||
@@ -1168,7 +1168,7 @@ impl VirtualMachine {
|
||||
if let Some(stderr) = stderr {
|
||||
let _ = vm.call_method(stderr, "write", (s.to_owned(),));
|
||||
} else {
|
||||
eprint!("{}", s);
|
||||
eprint!("{s}");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1191,7 +1191,7 @@ impl VirtualMachine {
|
||||
Ok(exc_str) if !exc_str.as_wtf8().is_empty() => {
|
||||
format!("{}: {}\n", exc_type_name, exc_str.as_wtf8())
|
||||
}
|
||||
_ => format!("{}\n", exc_type_name),
|
||||
_ => format!("{exc_type_name}\n"),
|
||||
};
|
||||
write_to_stderr(&msg, &stderr, self);
|
||||
|
||||
@@ -1886,9 +1886,9 @@ impl VirtualMachine {
|
||||
if i >= elements.len() {
|
||||
results.shrink_to_fit();
|
||||
return Ok(Ok(results));
|
||||
} else {
|
||||
elements[i].clone()
|
||||
}
|
||||
elements[i].clone()
|
||||
|
||||
// free the lock
|
||||
};
|
||||
match f(elem) {
|
||||
@@ -2149,9 +2149,8 @@ impl VirtualMachine {
|
||||
arg => {
|
||||
if self.is_none(arg) {
|
||||
return 0;
|
||||
} else {
|
||||
arg.str(self).ok()
|
||||
}
|
||||
arg.str(self).ok()
|
||||
}
|
||||
}),
|
||||
_ => args.as_object().repr(self).ok(),
|
||||
|
||||
Reference in new issue
Block a user