mirror of
https://github.com/RustPython/RustPython.git
synced 2026-06-02 19:39:49 +09:00
Merge pull request #4310 from youknowone/fix-clippy
Fix nightly clippy warnings
This commit is contained in:
@@ -457,7 +457,7 @@ impl Compiler {
|
||||
NameUsage::Delete if is_forbidden_name(name) => "cannot delete",
|
||||
_ => return Ok(()),
|
||||
};
|
||||
Err(self.error(CodegenErrorType::SyntaxError(format!("{} {}", msg, name))))
|
||||
Err(self.error(CodegenErrorType::SyntaxError(format!("{msg} {name}"))))
|
||||
}
|
||||
|
||||
fn compile_name(&mut self, name: &str, usage: NameUsage) -> CompileResult<()> {
|
||||
|
||||
@@ -37,8 +37,8 @@ impl fmt::Display for CodegenErrorType {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
use CodegenErrorType::*;
|
||||
match self {
|
||||
Assign(target) => write!(f, "cannot assign to {}", target),
|
||||
Delete(target) => write!(f, "cannot delete {}", target),
|
||||
Assign(target) => write!(f, "cannot assign to {target}"),
|
||||
Delete(target) => write!(f, "cannot delete {target}"),
|
||||
SyntaxError(err) => write!(f, "{}", err.as_str()),
|
||||
MultipleStarArgs => {
|
||||
write!(f, "two starred expressions in assignment")
|
||||
@@ -59,7 +59,7 @@ impl fmt::Display for CodegenErrorType {
|
||||
"from __future__ imports must occur at the beginning of the file"
|
||||
),
|
||||
InvalidFutureFeature(feat) => {
|
||||
write!(f, "future feature {} is not defined", feat)
|
||||
write!(f, "future feature {feat} is not defined")
|
||||
}
|
||||
FunctionImportStar => {
|
||||
write!(f, "import * only allowed at module level")
|
||||
|
||||
@@ -1154,27 +1154,26 @@ impl SymbolTableBuilder {
|
||||
SymbolUsage::Global if !symbol.is_global() => {
|
||||
if flags.contains(SymbolFlags::PARAMETER) {
|
||||
return Err(SymbolTableError {
|
||||
error: format!("name '{}' is parameter and global", name),
|
||||
error: format!("name '{name}' is parameter and global"),
|
||||
location,
|
||||
});
|
||||
}
|
||||
if flags.contains(SymbolFlags::REFERENCED) {
|
||||
return Err(SymbolTableError {
|
||||
error: format!("name '{}' is used prior to global declaration", name),
|
||||
error: format!("name '{name}' is used prior to global declaration"),
|
||||
location,
|
||||
});
|
||||
}
|
||||
if flags.contains(SymbolFlags::ANNOTATED) {
|
||||
return Err(SymbolTableError {
|
||||
error: format!("annotated name '{}' can't be global", name),
|
||||
error: format!("annotated name '{name}' can't be global"),
|
||||
location,
|
||||
});
|
||||
}
|
||||
if flags.contains(SymbolFlags::ASSIGNED) {
|
||||
return Err(SymbolTableError {
|
||||
error: format!(
|
||||
"name '{}' is assigned to before global declaration",
|
||||
name
|
||||
"name '{name}' is assigned to before global declaration"
|
||||
),
|
||||
location,
|
||||
});
|
||||
@@ -1183,27 +1182,26 @@ impl SymbolTableBuilder {
|
||||
SymbolUsage::Nonlocal => {
|
||||
if flags.contains(SymbolFlags::PARAMETER) {
|
||||
return Err(SymbolTableError {
|
||||
error: format!("name '{}' is parameter and nonlocal", name),
|
||||
error: format!("name '{name}' is parameter and nonlocal"),
|
||||
location,
|
||||
});
|
||||
}
|
||||
if flags.contains(SymbolFlags::REFERENCED) {
|
||||
return Err(SymbolTableError {
|
||||
error: format!("name '{}' is used prior to nonlocal declaration", name),
|
||||
error: format!("name '{name}' is used prior to nonlocal declaration"),
|
||||
location,
|
||||
});
|
||||
}
|
||||
if flags.contains(SymbolFlags::ANNOTATED) {
|
||||
return Err(SymbolTableError {
|
||||
error: format!("annotated name '{}' can't be nonlocal", name),
|
||||
error: format!("annotated name '{name}' can't be nonlocal"),
|
||||
location,
|
||||
});
|
||||
}
|
||||
if flags.contains(SymbolFlags::ASSIGNED) {
|
||||
return Err(SymbolTableError {
|
||||
error: format!(
|
||||
"name '{}' is assigned to before nonlocal declaration",
|
||||
name
|
||||
"name '{name}' is assigned to before nonlocal declaration"
|
||||
),
|
||||
location,
|
||||
});
|
||||
@@ -1220,7 +1218,7 @@ impl SymbolTableBuilder {
|
||||
match role {
|
||||
SymbolUsage::Nonlocal if scope_depth < 2 => {
|
||||
return Err(SymbolTableError {
|
||||
error: format!("cannot define nonlocal '{}' at top level.", name),
|
||||
error: format!("cannot define nonlocal '{name}' at top level."),
|
||||
location,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -482,15 +482,15 @@ impl<C: Constant> BorrowedConstant<'_, C> {
|
||||
// takes `self` because we need to consume the iterator
|
||||
pub fn fmt_display(self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
BorrowedConstant::Integer { value } => write!(f, "{}", value),
|
||||
BorrowedConstant::Float { value } => write!(f, "{}", value),
|
||||
BorrowedConstant::Complex { value } => write!(f, "{}", value),
|
||||
BorrowedConstant::Integer { value } => write!(f, "{value}"),
|
||||
BorrowedConstant::Float { value } => write!(f, "{value}"),
|
||||
BorrowedConstant::Complex { value } => write!(f, "{value}"),
|
||||
BorrowedConstant::Boolean { value } => {
|
||||
write!(f, "{}", if value { "True" } else { "False" })
|
||||
}
|
||||
BorrowedConstant::Str { value } => write!(f, "{:?}", value),
|
||||
BorrowedConstant::Str { value } => write!(f, "{value:?}"),
|
||||
BorrowedConstant::Bytes { value } => write!(f, "b{:?}", value.as_bstr()),
|
||||
BorrowedConstant::Code { code } => write!(f, "{:?}", code),
|
||||
BorrowedConstant::Code { code } => write!(f, "{code:?}"),
|
||||
BorrowedConstant::Tuple { elements } => {
|
||||
write!(f, "(")?;
|
||||
let mut first = true;
|
||||
@@ -852,7 +852,7 @@ impl<C: Constant> fmt::Display for CodeObject<C> {
|
||||
self.display_inner(f, false, 1)?;
|
||||
for constant in &*self.constants {
|
||||
if let BorrowedConstant::Code { code } = constant.borrow_constant() {
|
||||
writeln!(f, "\nDisassembly of {:?}", code)?;
|
||||
writeln!(f, "\nDisassembly of {code:?}")?;
|
||||
code.fmt(f)?;
|
||||
}
|
||||
}
|
||||
@@ -1118,14 +1118,14 @@ impl Instruction {
|
||||
}
|
||||
}
|
||||
}
|
||||
UnaryOperation { op } => w!(UnaryOperation, format_args!("{:?}", op)),
|
||||
BinaryOperation { op } => w!(BinaryOperation, format_args!("{:?}", op)),
|
||||
UnaryOperation { op } => w!(UnaryOperation, format_args!("{op:?}")),
|
||||
BinaryOperation { op } => w!(BinaryOperation, format_args!("{op:?}")),
|
||||
BinaryOperationInplace { op } => {
|
||||
w!(BinaryOperationInplace, format_args!("{:?}", op))
|
||||
w!(BinaryOperationInplace, format_args!("{op:?}"))
|
||||
}
|
||||
LoadAttr { idx } => w!(LoadAttr, name(*idx)),
|
||||
TestOperation { op } => w!(TestOperation, format_args!("{:?}", op)),
|
||||
CompareOperation { op } => w!(CompareOperation, format_args!("{:?}", op)),
|
||||
TestOperation { op } => w!(TestOperation, format_args!("{op:?}")),
|
||||
CompareOperation { op } => w!(CompareOperation, format_args!("{op:?}")),
|
||||
Pop => w!(Pop),
|
||||
Rotate2 => w!(Rotate2),
|
||||
Rotate3 => w!(Rotate3),
|
||||
@@ -1139,7 +1139,7 @@ impl Instruction {
|
||||
JumpIfFalse { target } => w!(JumpIfFalse, target),
|
||||
JumpIfTrueOrPop { target } => w!(JumpIfTrueOrPop, target),
|
||||
JumpIfFalseOrPop { target } => w!(JumpIfFalseOrPop, target),
|
||||
MakeFunction(flags) => w!(MakeFunction, format_args!("{:?}", flags)),
|
||||
MakeFunction(flags) => w!(MakeFunction, format_args!("{flags:?}")),
|
||||
CallFunctionPositional { nargs } => w!(CallFunctionPositional, nargs),
|
||||
CallFunctionKeyword { nargs } => w!(CallFunctionKeyword, nargs),
|
||||
CallFunctionEx { has_kwargs } => w!(CallFunctionEx, has_kwargs),
|
||||
@@ -1163,7 +1163,7 @@ impl Instruction {
|
||||
BeforeAsyncWith => w!(BeforeAsyncWith),
|
||||
SetupAsyncWith { end } => w!(SetupAsyncWith, end),
|
||||
PopBlock => w!(PopBlock),
|
||||
Raise { kind } => w!(Raise, format_args!("{:?}", kind)),
|
||||
Raise { kind } => w!(Raise, format_args!("{kind:?}")),
|
||||
BuildString { size } => w!(BuildString, size),
|
||||
BuildTuple { size, unpack } => w!(BuildTuple, size, unpack),
|
||||
BuildList { size, unpack } => w!(BuildList, size, unpack),
|
||||
@@ -1182,7 +1182,7 @@ impl Instruction {
|
||||
LoadBuildClass => w!(LoadBuildClass),
|
||||
UnpackSequence { size } => w!(UnpackSequence, size),
|
||||
UnpackEx { before, after } => w!(UnpackEx, before, after),
|
||||
FormatValue { conversion } => w!(FormatValue, format_args!("{:?}", conversion)),
|
||||
FormatValue { conversion } => w!(FormatValue, format_args!("{conversion:?}")),
|
||||
PopException => w!(PopException),
|
||||
Reverse { amount } => w!(Reverse, amount),
|
||||
GetAwaitable => w!(GetAwaitable),
|
||||
|
||||
@@ -34,7 +34,7 @@ impl fmt::Display for LexicalErrorType {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
LexicalErrorType::StringError => write!(f, "Got unexpected string"),
|
||||
LexicalErrorType::FStringError(error) => write!(f, "Got error in f-string: {}", error),
|
||||
LexicalErrorType::FStringError(error) => write!(f, "Got error in f-string: {error}"),
|
||||
LexicalErrorType::UnicodeError => write!(f, "Got unexpected unicode"),
|
||||
LexicalErrorType::NestingError => write!(f, "Got unexpected nesting"),
|
||||
LexicalErrorType::IndentationError => {
|
||||
@@ -56,13 +56,13 @@ impl fmt::Display for LexicalErrorType {
|
||||
write!(f, "positional argument follows keyword argument")
|
||||
}
|
||||
LexicalErrorType::UnrecognizedToken { tok } => {
|
||||
write!(f, "Got unexpected token {}", tok)
|
||||
write!(f, "Got unexpected token {tok}")
|
||||
}
|
||||
LexicalErrorType::LineContinuationError => {
|
||||
write!(f, "unexpected character after line continuation character")
|
||||
}
|
||||
LexicalErrorType::Eof => write!(f, "unexpected EOF while parsing"),
|
||||
LexicalErrorType::OtherError(msg) => write!(f, "{}", msg),
|
||||
LexicalErrorType::OtherError(msg) => write!(f, "{msg}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -97,17 +97,16 @@ impl fmt::Display for FStringErrorType {
|
||||
FStringErrorType::UnopenedRbrace => write!(f, "Unopened '}}'"),
|
||||
FStringErrorType::ExpectedRbrace => write!(f, "Expected '}}' after conversion flag."),
|
||||
FStringErrorType::InvalidExpression(error) => {
|
||||
write!(f, "{}", error)
|
||||
write!(f, "{error}")
|
||||
}
|
||||
FStringErrorType::InvalidConversionFlag => write!(f, "invalid conversion character"),
|
||||
FStringErrorType::EmptyExpression => write!(f, "empty expression not allowed"),
|
||||
FStringErrorType::MismatchedDelimiter(first, second) => write!(
|
||||
f,
|
||||
"closing parenthesis '{}' does not match opening parenthesis '{}'",
|
||||
second, first
|
||||
"closing parenthesis '{second}' does not match opening parenthesis '{first}'"
|
||||
),
|
||||
FStringErrorType::SingleRbrace => write!(f, "single '}}' is not allowed"),
|
||||
FStringErrorType::Unmatched(delim) => write!(f, "unmatched '{}'", delim),
|
||||
FStringErrorType::Unmatched(delim) => write!(f, "unmatched '{delim}'"),
|
||||
FStringErrorType::ExpressionNestedTooDeeply => {
|
||||
write!(f, "expressions nested too deeply")
|
||||
}
|
||||
@@ -118,7 +117,7 @@ impl fmt::Display for FStringErrorType {
|
||||
if *c == '\\' {
|
||||
write!(f, "f-string expression part cannot include a backslash")
|
||||
} else {
|
||||
write!(f, "f-string expression part cannot include '{}'s", c)
|
||||
write!(f, "f-string expression part cannot include '{c}'s")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -198,7 +197,7 @@ impl fmt::Display for ParseErrorType {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match *self {
|
||||
ParseErrorType::Eof => write!(f, "Got unexpected EOF"),
|
||||
ParseErrorType::ExtraToken(ref tok) => write!(f, "Got extraneous token: {:?}", tok),
|
||||
ParseErrorType::ExtraToken(ref tok) => write!(f, "Got extraneous token: {tok:?}"),
|
||||
ParseErrorType::InvalidToken => write!(f, "Got invalid token"),
|
||||
ParseErrorType::UnrecognizedToken(ref tok, ref expected) => {
|
||||
if *tok == Tok::Indent {
|
||||
@@ -206,10 +205,10 @@ impl fmt::Display for ParseErrorType {
|
||||
} else if expected.as_deref() == Some("Indent") {
|
||||
write!(f, "expected an indented block")
|
||||
} else {
|
||||
write!(f, "invalid syntax. Got unexpected token {}", tok)
|
||||
write!(f, "invalid syntax. Got unexpected token {tok}")
|
||||
}
|
||||
}
|
||||
ParseErrorType::Lexical(ref error) => write!(f, "{}", error),
|
||||
ParseErrorType::Lexical(ref error) => write!(f, "{error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -344,7 +344,7 @@ impl FStringParser {
|
||||
}
|
||||
|
||||
fn parse_fstring_expr(source: &str) -> Result<Expr, ParseError> {
|
||||
let fstring_body = format!("({})", source);
|
||||
let fstring_body = format!("({source})");
|
||||
parse_expression(&fstring_body, "<fstring>")
|
||||
}
|
||||
|
||||
|
||||
@@ -321,7 +321,7 @@ where
|
||||
let value_text = self.radix_run(radix);
|
||||
let end_pos = self.get_pos();
|
||||
let value = BigInt::from_str_radix(&value_text, radix).map_err(|e| LexicalError {
|
||||
error: LexicalErrorType::OtherError(format!("{:?}", e)),
|
||||
error: LexicalErrorType::OtherError(format!("{e:?}")),
|
||||
location: start_pos,
|
||||
})?;
|
||||
Ok((start_pos, Tok::Int { value }, end_pos))
|
||||
|
||||
@@ -118,17 +118,17 @@ impl fmt::Display for Tok {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
use Tok::*;
|
||||
match self {
|
||||
Name { name } => write!(f, "'{}'", name),
|
||||
Int { value } => write!(f, "'{}'", value),
|
||||
Float { value } => write!(f, "'{}'", value),
|
||||
Complex { real, imag } => write!(f, "{}j{}", real, imag),
|
||||
Name { name } => write!(f, "'{name}'"),
|
||||
Int { value } => write!(f, "'{value}'"),
|
||||
Float { value } => write!(f, "'{value}'"),
|
||||
Complex { real, imag } => write!(f, "{real}j{imag}"),
|
||||
String { value, kind } => {
|
||||
match kind {
|
||||
StringKind::F => f.write_str("f")?,
|
||||
StringKind::U => f.write_str("u")?,
|
||||
StringKind::Normal => {}
|
||||
}
|
||||
write!(f, "{:?}", value)
|
||||
write!(f, "{value:?}")
|
||||
}
|
||||
Bytes { value } => {
|
||||
write!(f, "b\"")?;
|
||||
@@ -138,7 +138,7 @@ impl fmt::Display for Tok {
|
||||
10 => f.write_str("\\n")?,
|
||||
13 => f.write_str("\\r")?,
|
||||
32..=126 => f.write_char(*i as char)?,
|
||||
_ => write!(f, "\\x{:02x}", i)?,
|
||||
_ => write!(f, "\\x{i:02x}")?,
|
||||
}
|
||||
}
|
||||
f.write_str("\"")
|
||||
|
||||
@@ -73,7 +73,7 @@ fn main() {
|
||||
error!("Error while compiling {:?}: {}", script, e);
|
||||
}
|
||||
} else {
|
||||
eprintln!("{:?} is not a file.", script);
|
||||
eprintln!("{script:?} is not a file.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -90,7 +90,7 @@ fn display_script(
|
||||
if expand_codeobjects {
|
||||
println!("{}", code.display_expand_codeobjects());
|
||||
} else {
|
||||
println!("{}", code);
|
||||
println!("{code}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ gen()
|
||||
PyResult::Ok(v)
|
||||
})?;
|
||||
match r {
|
||||
PyIterReturn::Return(value) => println!("{}", value),
|
||||
PyIterReturn::Return(value) => println!("{value}"),
|
||||
PyIterReturn::StopIteration(_) => break,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ fn main() -> ExitCode {
|
||||
});
|
||||
let result = py_main(&interp);
|
||||
let result = result.map(|result| {
|
||||
println!("name: {}", result);
|
||||
println!("name: {result}");
|
||||
});
|
||||
ExitCode::from(interp.run(|_vm| result))
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ fn main() {
|
||||
|
||||
let folder = Path::new(matches.value_of("folder").unwrap());
|
||||
if folder.exists() && folder.is_dir() {
|
||||
println!("Parsing folder of python code: {:?}", folder);
|
||||
println!("Parsing folder of python code: {folder:?}");
|
||||
let t1 = Instant::now();
|
||||
let parsed_files = parse_folder(folder).unwrap();
|
||||
let t2 = Instant::now();
|
||||
@@ -43,7 +43,7 @@ fn main() {
|
||||
};
|
||||
statistics(results);
|
||||
} else {
|
||||
println!("{:?} is not a folder.", folder);
|
||||
println!("{folder:?} is not a folder.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,13 +111,13 @@ fn statistics(results: ScanResult) {
|
||||
.iter()
|
||||
.filter(|p| p.result.is_ok())
|
||||
.count();
|
||||
println!("Passed: {} Failed: {} Total: {}", passed, failed, total);
|
||||
println!("Passed: {passed} Failed: {failed} Total: {total}");
|
||||
println!(
|
||||
"That is {} % success rate.",
|
||||
(passed as f64 * 100.0) / total as f64
|
||||
);
|
||||
let duration = results.t2 - results.t1;
|
||||
println!("Total time spend: {:?}", duration);
|
||||
println!("Total time spend: {duration:?}");
|
||||
println!(
|
||||
"Processed {} files. That's {} files/second",
|
||||
total,
|
||||
|
||||
@@ -344,7 +344,7 @@ fn get_paths(env_variable_name: &str) -> impl Iterator<Item = String> + '_ {
|
||||
.map(|path| {
|
||||
path.into_os_string()
|
||||
.into_string()
|
||||
.unwrap_or_else(|_| panic!("{} isn't valid unicode", env_variable_name))
|
||||
.unwrap_or_else(|_| panic!("{env_variable_name} isn't valid unicode"))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
|
||||
@@ -121,11 +121,11 @@ pub fn run_shell(vm: &VirtualMachine, scope: Scope) -> PyResult<()> {
|
||||
break;
|
||||
}
|
||||
ReadlineResult::Other(err) => {
|
||||
eprintln!("Readline error: {:?}", err);
|
||||
eprintln!("Readline error: {err:?}");
|
||||
break;
|
||||
}
|
||||
ReadlineResult::Io(err) => {
|
||||
eprintln!("IO error: {:?}", err);
|
||||
eprintln!("IO error: {err:?}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
fn main() {
|
||||
#[allow(clippy::unusual_byte_groupings)]
|
||||
if let Ok(v) = std::env::var("DEP_OPENSSL_VERSION_NUMBER") {
|
||||
println!("cargo:rustc-env=OPENSSL_API_VERSION={}", v);
|
||||
println!("cargo:rustc-env=OPENSSL_API_VERSION={v}");
|
||||
// cfg setup from openssl crate's build script
|
||||
let version = u64::from_str_radix(&v, 16).unwrap();
|
||||
if version >= 0x1_00_01_00_0 {
|
||||
@@ -22,7 +22,7 @@ fn main() {
|
||||
}
|
||||
if let Ok(v) = std::env::var("DEP_OPENSSL_CONF") {
|
||||
for conf in v.split(',') {
|
||||
println!("cargo:rustc-cfg=osslconf=\"{}\"", conf);
|
||||
println!("cargo:rustc-cfg=osslconf=\"{conf}\"");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -551,15 +551,13 @@ mod array {
|
||||
fn u32_to_char(ch: u32) -> Result<char, String> {
|
||||
if ch > 0x10ffff {
|
||||
return Err(format!(
|
||||
"character U+{:4x} is not in range [U+0000; U+10ffff]",
|
||||
ch
|
||||
"character U+{ch:4x} is not in range [U+0000; U+10ffff]"
|
||||
));
|
||||
};
|
||||
char::from_u32(ch).ok_or_else(|| {
|
||||
format!(
|
||||
"'utf-8' codec can't encode character '\\u{:x}' \
|
||||
in position 0: surrogates not allowed",
|
||||
ch
|
||||
"'utf-8' codec can't encode character '\\u{ch:x}' \
|
||||
in position 0: surrogates not allowed"
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -638,8 +636,7 @@ mod array {
|
||||
(spec, ch) if spec == ch => array.frombytes(&init.get_bytes()),
|
||||
(spec, 'u') => {
|
||||
return Err(vm.new_type_error(format!(
|
||||
"cannot use a unicode array to initialize an array with typecode '{}'",
|
||||
spec
|
||||
"cannot use a unicode array to initialize an array with typecode '{spec}'"
|
||||
)))
|
||||
}
|
||||
_ => {
|
||||
@@ -654,8 +651,7 @@ mod array {
|
||||
array.frombytes_move(bytes);
|
||||
} else {
|
||||
return Err(vm.new_type_error(format!(
|
||||
"cannot use a str to initialize an array with typecode '{}'",
|
||||
spec
|
||||
"cannot use a str to initialize an array with typecode '{spec}'"
|
||||
)));
|
||||
}
|
||||
} else if init.payload_is::<PyBytes>() || init.payload_is::<PyByteArray>() {
|
||||
@@ -1079,7 +1075,7 @@ mod array {
|
||||
let class_name = class.name();
|
||||
if zelf.read().typecode() == 'u' {
|
||||
if zelf.len() == 0 {
|
||||
return Ok(format!("{}('u')", class_name));
|
||||
return Ok(format!("{class_name}('u')"));
|
||||
}
|
||||
return Ok(format!(
|
||||
"{}('u', {})",
|
||||
|
||||
@@ -184,7 +184,7 @@ mod decl {
|
||||
base64::decode(&buf)
|
||||
})
|
||||
})
|
||||
.map_err(|err| new_binascii_error(format!("error decoding base64: {}", err), vm))
|
||||
.map_err(|err| new_binascii_error(format!("error decoding base64: {err}"), vm))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
|
||||
@@ -53,7 +53,7 @@ mod grp {
|
||||
let group = group.ok_or_else(|| {
|
||||
vm.new_key_error(
|
||||
vm.ctx
|
||||
.new_str(format!("getgrgid: group id {} not found", gr_gid))
|
||||
.new_str(format!("getgrgid: group id {gr_gid} not found"))
|
||||
.into(),
|
||||
)
|
||||
})?;
|
||||
@@ -70,7 +70,7 @@ mod grp {
|
||||
let group = group.ok_or_else(|| {
|
||||
vm.new_key_error(
|
||||
vm.ctx
|
||||
.new_str(format!("getgrnam: group name {} not found", gr_name))
|
||||
.new_str(format!("getgrnam: group name {gr_name} not found"))
|
||||
.into(),
|
||||
)
|
||||
})?;
|
||||
|
||||
@@ -164,7 +164,7 @@ mod hashlib {
|
||||
data: args.data,
|
||||
usedforsecurity: args.usedforsecurity,
|
||||
}),
|
||||
other => Err(vm.new_value_error(format!("Unknown hashing algorithm: {}", other))),
|
||||
other => Err(vm.new_value_error(format!("Unknown hashing algorithm: {other}"))),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ pub fn write_json_string<W: io::Write>(s: &str, ascii_only: bool, w: &mut W) ->
|
||||
write_start_idx = idx + c.len_utf8();
|
||||
// codepoints outside the BMP get 2 '\uxxxx' sequences to represent them
|
||||
for point in c.encode_utf16(&mut [0; 2]) {
|
||||
write!(w, "\\u{:04x}", point)?;
|
||||
write!(w, "\\u{point:04x}")?;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -195,19 +195,14 @@ pub fn scanstring<'a>(
|
||||
));
|
||||
continue;
|
||||
}
|
||||
_ => {
|
||||
return Err(DecodeError::new(
|
||||
format!("Invalid \\escape: {:?}", c),
|
||||
char_i,
|
||||
))
|
||||
}
|
||||
_ => return Err(DecodeError::new(format!("Invalid \\escape: {c:?}"), char_i)),
|
||||
};
|
||||
chunk_start = byte_i + 2;
|
||||
push_chunk(StrOrChar::Str(esc));
|
||||
}
|
||||
'\x00'..='\x1f' if strict => {
|
||||
return Err(DecodeError::new(
|
||||
format!("Invalid control character {:?} at", c),
|
||||
format!("Invalid control character {c:?} at"),
|
||||
char_i,
|
||||
));
|
||||
}
|
||||
|
||||
@@ -740,10 +740,7 @@ mod mmap {
|
||||
.map(|obj| {
|
||||
let name = obj.class().name().to_string();
|
||||
obj.try_into_value::<Option<isize>>(vm).map_err(|_| {
|
||||
vm.new_type_error(format!(
|
||||
"read argument must be int or None, not {}",
|
||||
name,
|
||||
))
|
||||
vm.new_type_error(format!("read argument must be int or None, not {name}",))
|
||||
})
|
||||
})
|
||||
.transpose()?
|
||||
|
||||
@@ -64,10 +64,7 @@ pub(crate) mod _struct {
|
||||
if (-offset) as usize > buffer_len {
|
||||
return Err(new_struct_error(
|
||||
vm,
|
||||
format!(
|
||||
"offset {} out of range for {}-byte buffer",
|
||||
offset, buffer_len
|
||||
),
|
||||
format!("offset {offset} out of range for {buffer_len}-byte buffer"),
|
||||
));
|
||||
}
|
||||
buffer_len - (-offset as usize)
|
||||
@@ -98,12 +95,9 @@ pub(crate) mod _struct {
|
||||
Err(new_struct_error(
|
||||
vm,
|
||||
if is_pack {
|
||||
format!("no space to pack {} bytes at offset {}", needed, offset)
|
||||
format!("no space to pack {needed} bytes at offset {offset}")
|
||||
} else {
|
||||
format!(
|
||||
"not enough data to unpack {} bytes at offset {}",
|
||||
needed, offset
|
||||
)
|
||||
format!("not enough data to unpack {needed} bytes at offset {offset}")
|
||||
},
|
||||
))
|
||||
} else {
|
||||
|
||||
@@ -100,9 +100,9 @@ mod _scproxy {
|
||||
.and_then(|v| v.downcast::<CFNumber>())
|
||||
.and_then(|v| v.to_i32())
|
||||
{
|
||||
format!("http://{}:{}", h, port)
|
||||
format!("http://{h}:{port}")
|
||||
} else {
|
||||
format!("http://{}", h)
|
||||
format!("http://{h}")
|
||||
};
|
||||
result.set_item(proto, vm.new_pyobj(v), vm)?;
|
||||
}
|
||||
|
||||
@@ -991,7 +991,7 @@ mod _socket {
|
||||
}
|
||||
Ok(addr6.into())
|
||||
}
|
||||
_ => Err(vm.new_os_error(format!("{}(): bad family", caller)).into()),
|
||||
_ => Err(vm.new_os_error(format!("{caller}(): bad family")).into()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1954,7 +1954,7 @@ mod _socket {
|
||||
})?;
|
||||
Ok(get_ipv6_addr_str(Ipv6Addr::from(*packed_ip)))
|
||||
}
|
||||
_ => Err(vm.new_value_error(format!("unknown address family {}", af_inet))),
|
||||
_ => Err(vm.new_value_error(format!("unknown address family {af_inet}"))),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -358,7 +358,7 @@ mod _ssl {
|
||||
_nid2obj(Nid::from_raw(nid))
|
||||
.as_deref()
|
||||
.map(obj2py)
|
||||
.ok_or_else(|| vm.new_value_error(format!("unknown NID {}", nid)))
|
||||
.ok_or_else(|| vm.new_value_error(format!("unknown NID {nid}")))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
@@ -1153,9 +1153,9 @@ mod _ssl {
|
||||
// add `library` attribute
|
||||
let attr_name = vm.ctx.as_ref().intern_str("library");
|
||||
cls.set_attr(attr_name, vm.ctx.new_str(lib).into());
|
||||
format!("[{}] {} ({}:{})", lib, errstr, file, line)
|
||||
format!("[{lib}] {errstr} ({file}:{line})")
|
||||
} else {
|
||||
format!("{} ({}:{})", errstr, file, line)
|
||||
format!("{errstr} ({file}:{line})")
|
||||
};
|
||||
// add `reason` attribute
|
||||
let attr_name = vm.ctx.as_ref().intern_str("reason");
|
||||
@@ -1314,7 +1314,7 @@ mod _ssl {
|
||||
|
||||
#[pyfunction]
|
||||
fn _test_decode_cert(path: PyPathLike, vm: &VirtualMachine) -> PyResult {
|
||||
let pem = std::fs::read(&path).map_err(|e| e.to_pyexception(vm))?;
|
||||
let pem = std::fs::read(path).map_err(|e| e.to_pyexception(vm))?;
|
||||
let x509 = X509::from_pem(&pem).map_err(|e| convert_openssl_error(vm, e))?;
|
||||
cert_to_py(vm, &x509, false)
|
||||
}
|
||||
|
||||
@@ -211,8 +211,7 @@ mod termios {
|
||||
let cc = cc.borrow_vec();
|
||||
let cc = <&[PyObjectRef; NCCS]>::try_from(&*cc).map_err(|_| {
|
||||
vm.new_type_error(format!(
|
||||
"tcsetattr: attributes[6] must be {} element list",
|
||||
NCCS
|
||||
"tcsetattr: attributes[6] must be {NCCS} element list"
|
||||
))
|
||||
})?;
|
||||
for (cc, x) in termios.c_cc.iter_mut().zip(cc.iter()) {
|
||||
|
||||
@@ -82,7 +82,7 @@ mod unicodedata {
|
||||
return Ok(character.to_string());
|
||||
}
|
||||
}
|
||||
Err(vm.new_lookup_error(format!("undefined character name '{}'", name)))
|
||||
Err(vm.new_lookup_error(format!("undefined character name '{name}'")))
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
|
||||
@@ -31,7 +31,7 @@ fn main() {
|
||||
write!(
|
||||
f,
|
||||
"sysvars! {{ {} }}",
|
||||
std::env::vars_os().format_with(", ", |(k, v), f| f(&format_args!("{:?} => {:?}", k, v)))
|
||||
std::env::vars_os().format_with(", ", |(k, v), f| f(&format_args!("{k:?} => {v:?}")))
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
@@ -60,8 +60,8 @@ fn command(cmd: &str, args: &[&str]) -> String {
|
||||
match Command::new(cmd).args(args).output() {
|
||||
Ok(output) => match String::from_utf8(output.stdout) {
|
||||
Ok(s) => s,
|
||||
Err(err) => format!("(output error: {})", err),
|
||||
Err(err) => format!("(output error: {err})"),
|
||||
},
|
||||
Err(err) => format!("(command error: {})", err),
|
||||
Err(err) => format!("(command error: {err})"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,8 +94,7 @@ impl Constructor for PyBool {
|
||||
let actual_class = zelf.class();
|
||||
let actual_type = &actual_class.name();
|
||||
return Err(vm.new_type_error(format!(
|
||||
"requires a 'type' object but received a '{}'",
|
||||
actual_type
|
||||
"requires a 'type' object but received a '{actual_type}'"
|
||||
)));
|
||||
}
|
||||
let val = x.map_or(Ok(false), |val| val.try_to_bool(vm))?;
|
||||
|
||||
@@ -150,7 +150,7 @@ impl PyClassMethod {
|
||||
) {
|
||||
(None, _) => None,
|
||||
(Some(qualname), Some(module)) if module != "builtins" => {
|
||||
Some(format!("<{}.{}({})>", module, qualname, callable))
|
||||
Some(format!("<{module}.{qualname}({callable})>"))
|
||||
}
|
||||
_ => Some(format!("<{}({})>", class.slot_name(), callable)),
|
||||
}
|
||||
|
||||
@@ -100,7 +100,7 @@ fn inner_div(v1: Complex64, v2: Complex64, vm: &VirtualMachine) -> PyResult<Comp
|
||||
fn inner_pow(v1: Complex64, v2: Complex64, vm: &VirtualMachine) -> PyResult<Complex64> {
|
||||
if v1.is_zero() {
|
||||
return if v2.im != 0.0 {
|
||||
let msg = format!("{} cannot be raised to a negative or complex power", v1);
|
||||
let msg = format!("{v1} cannot be raised to a negative or complex power");
|
||||
Err(vm.new_zero_division_error(msg))
|
||||
} else if v2.is_zero() {
|
||||
Ok(Complex64::new(1.0, 0.0))
|
||||
|
||||
@@ -260,7 +260,7 @@ impl PyDict {
|
||||
for (key, value) in zelf {
|
||||
let key_repr = &key.repr(vm)?;
|
||||
let value_repr = value.repr(vm)?;
|
||||
str_parts.push(format!("{}: {}", key_repr, value_repr));
|
||||
str_parts.push(format!("{key_repr}: {value_repr}"));
|
||||
}
|
||||
|
||||
format!("{{{}}}", str_parts.join(", "))
|
||||
|
||||
@@ -124,7 +124,7 @@ fn inner_divmod(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult<(f64, f64)> {
|
||||
|
||||
pub fn float_pow(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult {
|
||||
if v1.is_zero() && v2.is_sign_negative() {
|
||||
let msg = format!("{} cannot be raised to a negative power", v1);
|
||||
let msg = format!("{v1} cannot be raised to a negative power");
|
||||
Err(vm.new_zero_division_error(msg))
|
||||
} else if v1.is_sign_negative() && (v2.floor() - v2).abs() > f64::EPSILON {
|
||||
let v1 = Complex64::new(v1, 0.);
|
||||
@@ -180,9 +180,7 @@ fn float_from_string(val: PyObjectRef, vm: &VirtualMachine) -> PyResult<f64> {
|
||||
};
|
||||
float_ops::parse_bytes(b).ok_or_else(|| {
|
||||
val.repr(vm)
|
||||
.map(|repr| {
|
||||
vm.new_value_error(format!("could not convert string to float: '{}'", repr))
|
||||
})
|
||||
.map(|repr| vm.new_value_error(format!("could not convert string to float: '{repr}'")))
|
||||
.unwrap_or_else(|e| e)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -133,7 +133,7 @@ impl PyFunction {
|
||||
let slot = &mut fastlocals[pos];
|
||||
if slot.is_some() {
|
||||
return Err(
|
||||
vm.new_type_error(format!("Got multiple values for argument '{}'", name))
|
||||
vm.new_type_error(format!("Got multiple values for argument '{name}'"))
|
||||
);
|
||||
}
|
||||
*slot = Some(value);
|
||||
@@ -143,7 +143,7 @@ impl PyFunction {
|
||||
posonly_passed_as_kwarg.push(name);
|
||||
} else {
|
||||
return Err(
|
||||
vm.new_type_error(format!("got an unexpected keyword argument '{}'", name))
|
||||
vm.new_type_error(format!("got an unexpected keyword argument '{name}'"))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -251,7 +251,7 @@ impl PyFunction {
|
||||
|
||||
// No default value and not specified.
|
||||
return Err(
|
||||
vm.new_type_error(format!("Missing required kw only argument: '{}'", kwarg))
|
||||
vm.new_type_error(format!("Missing required kw only argument: '{kwarg}'"))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,7 +106,7 @@ impl PyGenericAlias {
|
||||
(Some(qualname), Some(module)) => Ok(if module == "builtins" {
|
||||
qualname
|
||||
} else {
|
||||
format!("{}.{}", module, qualname)
|
||||
format!("{module}.{qualname}")
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,11 +53,11 @@ impl PyModule {
|
||||
return vm.invoke(&getattr, (name,));
|
||||
}
|
||||
let module_name = if let Some(name) = Self::name(zelf.to_owned(), vm) {
|
||||
format!(" '{}'", name)
|
||||
format!(" '{name}'")
|
||||
} else {
|
||||
"".to_owned()
|
||||
};
|
||||
Err(vm.new_attribute_error(format!("module{} has no attribute '{}'", module_name, name)))
|
||||
Err(vm.new_attribute_error(format!("module{module_name} has no attribute '{name}'")))
|
||||
}
|
||||
|
||||
fn name(zelf: PyRef<Self>, vm: &VirtualMachine) -> Option<PyStrRef> {
|
||||
|
||||
@@ -61,7 +61,7 @@ impl PyNamespace {
|
||||
}
|
||||
format!("{}({})", name, parts.join(", "))
|
||||
} else {
|
||||
format!("{}(...)", name)
|
||||
format!("{name}(...)")
|
||||
};
|
||||
Ok(repr)
|
||||
}
|
||||
|
||||
@@ -277,8 +277,7 @@ impl PyBaseObject {
|
||||
let value_class = value.class();
|
||||
let type_repr = &value_class.name();
|
||||
Err(vm.new_type_error(format!(
|
||||
"__class__ must be set to a class, not '{}' object",
|
||||
type_repr
|
||||
"__class__ must be set to a class, not '{type_repr}' object"
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -308,7 +308,7 @@ impl PyRange {
|
||||
if let Ok(int) = needle.clone().downcast::<PyInt>() {
|
||||
match self.index_of(int.as_bigint()) {
|
||||
Some(idx) => Ok(idx),
|
||||
None => Err(vm.new_value_error(format!("{} is not in range", int))),
|
||||
None => Err(vm.new_value_error(format!("{int} is not in range"))),
|
||||
}
|
||||
} else {
|
||||
// Fallback to iteration.
|
||||
|
||||
@@ -619,7 +619,7 @@ impl PySet {
|
||||
let borrowed_name = class.name();
|
||||
let class_name = borrowed_name.deref();
|
||||
let s = if zelf.inner.len() == 0 {
|
||||
format!("{}()", class_name)
|
||||
format!("{class_name}()")
|
||||
} else if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) {
|
||||
let name = if class_name != "set" {
|
||||
Some(class_name)
|
||||
@@ -628,7 +628,7 @@ impl PySet {
|
||||
};
|
||||
zelf.inner.repr(name, vm)?
|
||||
} else {
|
||||
format!("{}(...)", class_name)
|
||||
format!("{class_name}(...)")
|
||||
};
|
||||
Ok(s)
|
||||
}
|
||||
@@ -957,11 +957,11 @@ impl PyFrozenSet {
|
||||
let class = zelf.class();
|
||||
let class_name = class.name();
|
||||
let s = if inner.len() == 0 {
|
||||
format!("{}()", class_name)
|
||||
format!("{class_name}()")
|
||||
} else if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) {
|
||||
inner.repr(Some(&class_name), vm)?
|
||||
} else {
|
||||
format!("{}(...)", class_name)
|
||||
format!("{class_name}(...)")
|
||||
};
|
||||
Ok(s)
|
||||
}
|
||||
@@ -1052,7 +1052,7 @@ impl TryFromObject for AnySet {
|
||||
{
|
||||
Ok(AnySet { object: obj })
|
||||
} else {
|
||||
Err(vm.new_type_error(format!("{} is not a subtype of set or frozenset", class)))
|
||||
Err(vm.new_type_error(format!("{class} is not a subtype of set or frozenset")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,7 +152,7 @@ impl PyStaticMethod {
|
||||
) {
|
||||
(None, _) => None,
|
||||
(Some(qualname), Some(module)) if module != "builtins" => {
|
||||
Some(format!("<{}.{}({})>", module, qualname, callable))
|
||||
Some(format!("<{module}.{qualname}({callable})>"))
|
||||
}
|
||||
_ => Some(format!("<{}({})>", class.slot_name(), callable)),
|
||||
}
|
||||
|
||||
@@ -129,7 +129,7 @@ impl PySuper {
|
||||
let typname = &self.typ.name();
|
||||
match self.obj {
|
||||
Some((_, ref ty)) => format!("<super: <class '{}'>, <{} object>>", typname, ty.name()),
|
||||
None => format!("<super: <class '{}'>, NULL>", typname),
|
||||
None => format!("<super: <class '{typname}'>, NULL>"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ impl PyUnion {
|
||||
(Some(qualname), Some(module)) => Ok(if module == "builtins" {
|
||||
qualname
|
||||
} else {
|
||||
format!("{}.{}", module, qualname)
|
||||
format!("{module}.{qualname}")
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ impl PyWeak {
|
||||
o.get_id(),
|
||||
)
|
||||
} else {
|
||||
format!("<weakref at {:#x}; dead>", id)
|
||||
format!("<weakref at {id:#x}; dead>")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -450,8 +450,7 @@ impl PyBytesInner {
|
||||
};
|
||||
|
||||
Err(vm.new_value_error(format!(
|
||||
"non-hexadecimal number found in fromhex() arg at position {}",
|
||||
i
|
||||
"non-hexadecimal number found in fromhex() arg at position {i}"
|
||||
)))
|
||||
}
|
||||
|
||||
|
||||
@@ -192,9 +192,9 @@ impl CFormatSpec {
|
||||
// arguments, the LEFT_ADJUST flag will be used by a later call to fill_string with
|
||||
// the 0-filled string as the string param.
|
||||
if !fill_with_precision && self.flags.contains(CConversionFlags::LEFT_ADJUST) {
|
||||
format!("{}{}", string, fill_string)
|
||||
format!("{string}{fill_string}")
|
||||
} else {
|
||||
format!("{}{}", fill_string, string)
|
||||
format!("{fill_string}{string}")
|
||||
}
|
||||
} else {
|
||||
string
|
||||
@@ -286,7 +286,7 @@ impl CFormatSpec {
|
||||
} else {
|
||||
' ' // '-' overrides the '0' conversion if both are given
|
||||
};
|
||||
let signed_prefix = format!("{}{}", sign_string, prefix);
|
||||
let signed_prefix = format!("{sign_string}{prefix}");
|
||||
format!(
|
||||
"{}{}",
|
||||
signed_prefix,
|
||||
@@ -299,7 +299,7 @@ impl CFormatSpec {
|
||||
)
|
||||
} else {
|
||||
self.fill_string(
|
||||
format!("{}{}{}", sign_string, prefix, padded_magnitude_string),
|
||||
format!("{sign_string}{prefix}{padded_magnitude_string}"),
|
||||
' ',
|
||||
None,
|
||||
false,
|
||||
@@ -371,12 +371,7 @@ impl CFormatSpec {
|
||||
)
|
||||
)
|
||||
} else {
|
||||
self.fill_string(
|
||||
format!("{}{}", sign_string, magnitude_string),
|
||||
' ',
|
||||
None,
|
||||
false,
|
||||
)
|
||||
self.fill_string(format!("{sign_string}{magnitude_string}"), ' ', None, false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -450,7 +445,7 @@ impl CFormatSpec {
|
||||
if e.fast_isinstance(vm.ctx.exceptions.type_error) {
|
||||
// formatfloat in bytesobject.c generates its own specific exception
|
||||
// text in this case, mirror it here.
|
||||
vm.new_type_error(format!("float argument required, not {}", type_name))
|
||||
vm.new_type_error(format!("float argument required, not {type_name}"))
|
||||
} else {
|
||||
e
|
||||
}
|
||||
@@ -1366,8 +1361,7 @@ mod tests {
|
||||
let result = fmt.parse::<CFormatString>();
|
||||
assert_eq!(
|
||||
result, expected,
|
||||
"left = {:#?} \n\n\n right = {:#?}",
|
||||
result, expected
|
||||
"left = {result:#?} \n\n\n right = {expected:#?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -242,7 +242,7 @@ impl CodecsRegistry {
|
||||
return Ok(codec.clone());
|
||||
}
|
||||
}
|
||||
Err(vm.new_lookup_error(format!("unknown encoding: {}", encoding)))
|
||||
Err(vm.new_lookup_error(format!("unknown encoding: {encoding}")))
|
||||
}
|
||||
|
||||
fn _lookup_text_encoding(
|
||||
@@ -256,8 +256,7 @@ impl CodecsRegistry {
|
||||
Ok(codec)
|
||||
} else {
|
||||
Err(vm.new_lookup_error(format!(
|
||||
"'{}' is not a text encoding; use {} to handle arbitrary codecs",
|
||||
encoding, generic_func
|
||||
"'{encoding}' is not a text encoding; use {generic_func} to handle arbitrary codecs"
|
||||
)))
|
||||
}
|
||||
}
|
||||
@@ -338,7 +337,7 @@ impl CodecsRegistry {
|
||||
|
||||
pub fn lookup_error(&self, name: &str, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
|
||||
self.lookup_error_opt(name)
|
||||
.ok_or_else(|| vm.new_lookup_error(format!("unknown error handler name '{}'", name)))
|
||||
.ok_or_else(|| vm.new_lookup_error(format!("unknown error handler name '{name}'")))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -440,7 +439,7 @@ fn backslashreplace_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(S
|
||||
let b = PyBytesRef::try_from_object(vm, err.get_attr("object", vm)?)?;
|
||||
let mut replace = String::with_capacity(4 * range.len());
|
||||
for &c in &b[range.clone()] {
|
||||
write!(replace, "\\x{:02x}", c).unwrap();
|
||||
write!(replace, "\\x{c:02x}").unwrap();
|
||||
}
|
||||
return Ok((replace, range.end));
|
||||
} else if !is_encode_ish_err(&err, vm) {
|
||||
@@ -455,11 +454,11 @@ fn backslashreplace_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(S
|
||||
for c in s_after_start.chars().take(num_chars) {
|
||||
let c = c as u32;
|
||||
if c >= 0x10000 {
|
||||
write!(out, "\\U{:08x}", c).unwrap();
|
||||
write!(out, "\\U{c:08x}").unwrap();
|
||||
} else if c >= 0x100 {
|
||||
write!(out, "\\u{:04x}", c).unwrap();
|
||||
write!(out, "\\u{c:04x}").unwrap();
|
||||
} else {
|
||||
write!(out, "\\x{:02x}", c).unwrap();
|
||||
write!(out, "\\x{c:02x}").unwrap();
|
||||
}
|
||||
}
|
||||
Ok((out, range.end))
|
||||
|
||||
@@ -912,8 +912,8 @@ mod tests {
|
||||
dict.insert(vm, &*key1, value2.clone()).unwrap();
|
||||
assert_eq!(2, dict.len());
|
||||
|
||||
assert_eq!(true, dict.contains(vm, &*key1).unwrap());
|
||||
assert_eq!(true, dict.contains(vm, "x").unwrap());
|
||||
assert!(dict.contains(vm, &*key1).unwrap());
|
||||
assert!(dict.contains(vm, "x").unwrap());
|
||||
|
||||
let val = dict.get(vm, "x").unwrap().unwrap();
|
||||
vm.bool_eq(&val, &value2)
|
||||
|
||||
@@ -45,10 +45,10 @@ impl VirtualMachine {
|
||||
if let Ok(stderr) = sys::get_stderr(vm) {
|
||||
let mut stderr = py_io::PyWriter(stderr, vm);
|
||||
// if this fails stderr might be closed -- ignore it
|
||||
let _ = writeln!(stderr, "{}", errstr);
|
||||
let _ = writeln!(stderr, "{errstr}");
|
||||
let _ = self.write_exception(&mut stderr, exc);
|
||||
} else {
|
||||
eprintln!("{}\nlost sys.stderr", errstr);
|
||||
eprintln!("{errstr}\nlost sys.stderr");
|
||||
let _ = self.write_exception(&mut py_io::IoWriter(io::stderr()), exc);
|
||||
}
|
||||
};
|
||||
@@ -106,7 +106,7 @@ impl VirtualMachine {
|
||||
} {
|
||||
if !seen.contains(&cause_or_context.get_id()) {
|
||||
self.write_exception_recursive(output, &cause_or_context, seen)?;
|
||||
writeln!(output, "{}", msg)?;
|
||||
writeln!(output, "{msg}")?;
|
||||
} else {
|
||||
seen.insert(cause_or_context.get_id());
|
||||
}
|
||||
@@ -135,7 +135,7 @@ impl VirtualMachine {
|
||||
let exc_class = exc.class();
|
||||
let exc_name = exc_class.name();
|
||||
match args_repr.len() {
|
||||
0 => write!(output, "{}", exc_name),
|
||||
0 => write!(output, "{exc_name}"),
|
||||
1 => write!(output, "{}: {}", exc_name, args_repr[0]),
|
||||
_ => write!(
|
||||
output,
|
||||
@@ -900,7 +900,7 @@ fn os_error_str(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyResult<PyStrR
|
||||
Err(_) => format!("[Errno {}] {}: '{}'", errno, msg, filename.str(vm)?),
|
||||
},
|
||||
Err(_) => {
|
||||
format!("[Errno {}] {}", errno, msg)
|
||||
format!("[Errno {errno}] {msg}")
|
||||
}
|
||||
};
|
||||
Ok(vm.ctx.new_str(s))
|
||||
|
||||
@@ -567,10 +567,7 @@ impl FormatSpec {
|
||||
FormatSpec::compute_fill_string(fill_char, left_fill_chars_needed);
|
||||
let right_fill_string =
|
||||
FormatSpec::compute_fill_string(fill_char, right_fill_chars_needed);
|
||||
format!(
|
||||
"{}{}{}{}",
|
||||
left_fill_string, sign_str, magnitude_string, right_fill_string
|
||||
)
|
||||
format!("{left_fill_string}{sign_str}{magnitude_string}{right_fill_string}")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -463,15 +463,12 @@ impl ExecutingFrame<'_> {
|
||||
if let Some(&name) = self.code.cellvars.get(i) {
|
||||
vm.new_exception_msg(
|
||||
vm.ctx.exceptions.unbound_local_error.to_owned(),
|
||||
format!("local variable '{}' referenced before assignment", name),
|
||||
format!("local variable '{name}' referenced before assignment"),
|
||||
)
|
||||
} else {
|
||||
let name = self.code.freevars[i - self.code.cellvars.len()];
|
||||
vm.new_name_error(
|
||||
format!(
|
||||
"free variable '{}' referenced before assignment in enclosing scope",
|
||||
name
|
||||
),
|
||||
format!("free variable '{name}' referenced before assignment in enclosing scope"),
|
||||
name.to_owned(),
|
||||
)
|
||||
}
|
||||
@@ -1063,7 +1060,7 @@ impl ExecutingFrame<'_> {
|
||||
self.globals
|
||||
.get_chain(self.builtins, name, vm)?
|
||||
.ok_or_else(|| {
|
||||
vm.new_name_error(format!("name '{}' is not defined", name), name.to_owned())
|
||||
vm.new_name_error(format!("name '{name}' is not defined"), name.to_owned())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1103,7 +1100,7 @@ impl ExecutingFrame<'_> {
|
||||
fn import_from(&mut self, vm: &VirtualMachine, idx: bytecode::NameIdx) -> PyResult {
|
||||
let module = self.last_value();
|
||||
let name = self.code.names[idx as usize];
|
||||
let err = || vm.new_import_error(format!("cannot import name '{}'", name), name);
|
||||
let err = || vm.new_import_error(format!("cannot import name '{name}'"), name);
|
||||
// Load attribute, and transform any error into import error.
|
||||
if let Some(obj) = vm.get_attribute_opt(module.clone(), name)? {
|
||||
return Ok(obj);
|
||||
@@ -1113,7 +1110,7 @@ impl ExecutingFrame<'_> {
|
||||
.get_attr(identifier!(vm, __name__), vm)
|
||||
.map_err(|_| err())?;
|
||||
let mod_name = mod_name.downcast::<PyStr>().map_err(|_| err())?;
|
||||
let full_mod_name = format!("{}.{}", mod_name, name);
|
||||
let full_mod_name = format!("{mod_name}.{name}");
|
||||
let sys_modules = vm
|
||||
.sys_module
|
||||
.clone()
|
||||
@@ -1706,7 +1703,7 @@ impl ExecutingFrame<'_> {
|
||||
return Ok(None);
|
||||
}
|
||||
std::cmp::Ordering::Greater => {
|
||||
format!("too many values to unpack (expected {})", size)
|
||||
format!("too many values to unpack (expected {size})")
|
||||
}
|
||||
std::cmp::Ordering::Less => format!(
|
||||
"not enough values to unpack (expected {}, got {})",
|
||||
@@ -1890,14 +1887,14 @@ impl fmt::Debug for Frame {
|
||||
if elem.payload_is::<Frame>() {
|
||||
"\n > {frame}".to_owned()
|
||||
} else {
|
||||
format!("\n > {:?}", elem)
|
||||
format!("\n > {elem:?}")
|
||||
}
|
||||
})
|
||||
.collect::<String>();
|
||||
let block_str = state
|
||||
.blocks
|
||||
.iter()
|
||||
.map(|elem| format!("\n > {:?}", elem))
|
||||
.map(|elem| format!("\n > {elem:?}"))
|
||||
.collect::<String>();
|
||||
// TODO: fix this up
|
||||
let locals = self.locals.clone();
|
||||
|
||||
@@ -158,8 +158,7 @@ impl FuncArgs {
|
||||
let kwarg_class = kwarg.class();
|
||||
let actual_ty_name = &kwarg_class.name();
|
||||
Err(vm.new_type_error(format!(
|
||||
"argument of type {} is required for named parameter `{}` (got: {})",
|
||||
expected_ty_name, key, actual_ty_name
|
||||
"argument of type {expected_ty_name} is required for named parameter `{key}` (got: {actual_ty_name})"
|
||||
)))
|
||||
}
|
||||
}
|
||||
@@ -217,7 +216,7 @@ impl FuncArgs {
|
||||
self.kwargs
|
||||
.keys()
|
||||
.next()
|
||||
.map(|k| vm.new_type_error(format!("Unexpected keyword argument {}", k)))
|
||||
.map(|k| vm.new_type_error(format!("Unexpected keyword argument {k}")))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -262,10 +261,10 @@ impl ArgumentError {
|
||||
num_given
|
||||
)),
|
||||
ArgumentError::InvalidKeywordArgument(name) => {
|
||||
vm.new_type_error(format!("{} is an invalid keyword argument", name))
|
||||
vm.new_type_error(format!("{name} is an invalid keyword argument"))
|
||||
}
|
||||
ArgumentError::RequiredKeywordArgument(name) => {
|
||||
vm.new_type_error(format!("Required keyqord only argument {}", name))
|
||||
vm.new_type_error(format!("Required keyqord only argument {name}"))
|
||||
}
|
||||
ArgumentError::Exception(ex) => ex,
|
||||
}
|
||||
|
||||
@@ -73,9 +73,10 @@ pub(crate) fn init_importlib_package(
|
||||
}
|
||||
|
||||
pub fn make_frozen(vm: &VirtualMachine, name: &str) -> PyResult<PyRef<PyCode>> {
|
||||
let frozen = vm.state.frozen.get(name).ok_or_else(|| {
|
||||
vm.new_import_error(format!("No such frozen object named {}", name), name)
|
||||
})?;
|
||||
let frozen =
|
||||
vm.state.frozen.get(name).ok_or_else(|| {
|
||||
vm.new_import_error(format!("No such frozen object named {name}"), name)
|
||||
})?;
|
||||
Ok(vm.ctx.new_code(frozen.code.clone()))
|
||||
}
|
||||
|
||||
@@ -89,7 +90,7 @@ pub fn import_builtin(vm: &VirtualMachine, module_name: &str) -> PyResult {
|
||||
.get(module_name)
|
||||
.ok_or_else(|| {
|
||||
vm.new_import_error(
|
||||
format!("Cannot import builtin module {}", module_name),
|
||||
format!("Cannot import builtin module {module_name}"),
|
||||
module_name,
|
||||
)
|
||||
})
|
||||
|
||||
@@ -255,7 +255,7 @@ impl BufferDescriptor {
|
||||
.zip_eq(self.dim_desc.iter().cloned())
|
||||
{
|
||||
let i = i.wrapped_at(shape).ok_or_else(|| {
|
||||
vm.new_index_error(format!("index out of bounds on dimension {}", i))
|
||||
vm.new_index_error(format!("index out of bounds on dimension {i}"))
|
||||
})?;
|
||||
pos += i as isize * stride + suboffset;
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ mod basic_readline {
|
||||
|
||||
pub fn readline(&mut self, prompt: &str) -> ReadlineResult {
|
||||
use std::io::prelude::*;
|
||||
print!("{}", prompt);
|
||||
print!("{prompt}");
|
||||
if let Err(e) = io::stdout().flush() {
|
||||
return ReadlineResult::Io(e);
|
||||
}
|
||||
|
||||
@@ -78,9 +78,8 @@ mod _ast {
|
||||
}
|
||||
|
||||
fn get_node_field(vm: &VirtualMachine, obj: &PyObject, field: &str, typ: &str) -> PyResult {
|
||||
vm.get_attribute_opt(obj.to_owned(), field)?.ok_or_else(|| {
|
||||
vm.new_type_error(format!("required field \"{}\" missing from {}", field, typ))
|
||||
})
|
||||
vm.get_attribute_opt(obj.to_owned(), field)?
|
||||
.ok_or_else(|| vm.new_type_error(format!("required field \"{field}\" missing from {typ}")))
|
||||
}
|
||||
|
||||
fn get_node_field_opt(
|
||||
|
||||
@@ -73,7 +73,7 @@ mod builtins {
|
||||
if x.is_negative() {
|
||||
format!("-0b{:b}", x.abs())
|
||||
} else {
|
||||
format!("0b{:b}", x)
|
||||
format!("0b{x:b}")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -303,8 +303,7 @@ mod builtins {
|
||||
|
||||
if !code_obj.freevars.is_empty() {
|
||||
return Err(vm.new_type_error(format!(
|
||||
"code object passed to {}() may not contain free variables",
|
||||
func
|
||||
"code object passed to {func}() may not contain free variables"
|
||||
)));
|
||||
}
|
||||
|
||||
@@ -368,7 +367,7 @@ mod builtins {
|
||||
#[pyfunction]
|
||||
fn hex(number: PyIntRef) -> String {
|
||||
let n = number.as_bigint();
|
||||
format!("{:#x}", n)
|
||||
format!("{n:#x}")
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
@@ -478,8 +477,7 @@ mod builtins {
|
||||
std::cmp::Ordering::Greater => {
|
||||
if default.is_some() {
|
||||
return Err(vm.new_type_error(format!(
|
||||
"Cannot specify a default for {}() with multiple positional arguments",
|
||||
func_name
|
||||
"Cannot specify a default for {func_name}() with multiple positional arguments"
|
||||
)));
|
||||
}
|
||||
args.args
|
||||
@@ -488,7 +486,7 @@ mod builtins {
|
||||
std::cmp::Ordering::Less => {
|
||||
// zero arguments means type error:
|
||||
return Err(
|
||||
vm.new_type_error(format!("{} expected at least 1 argument, got 0", func_name))
|
||||
vm.new_type_error(format!("{func_name} expected at least 1 argument, got 0"))
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -498,7 +496,7 @@ mod builtins {
|
||||
Some(x) => x,
|
||||
None => {
|
||||
return default.ok_or_else(|| {
|
||||
vm.new_value_error(format!("{}() arg is an empty sequence", func_name))
|
||||
vm.new_value_error(format!("{func_name}() arg is an empty sequence"))
|
||||
})
|
||||
}
|
||||
};
|
||||
@@ -560,7 +558,7 @@ mod builtins {
|
||||
let s = if n.is_negative() {
|
||||
format!("-0o{:o}", n.abs())
|
||||
} else {
|
||||
format!("0o{:o}", n)
|
||||
format!("0o{n:o}")
|
||||
};
|
||||
|
||||
Ok(vm.ctx.new_str(s).into())
|
||||
@@ -573,8 +571,7 @@ mod builtins {
|
||||
let bytes_len = bytes.len();
|
||||
if bytes_len != 1 {
|
||||
return Err(vm.new_type_error(format!(
|
||||
"ord() expected a character, but string of length {} found",
|
||||
bytes_len
|
||||
"ord() expected a character, but string of length {bytes_len} found"
|
||||
)));
|
||||
}
|
||||
Ok(u32::from(bytes[0]))
|
||||
@@ -584,8 +581,7 @@ mod builtins {
|
||||
let string_len = string.chars().count();
|
||||
if string_len != 1 {
|
||||
return Err(vm.new_type_error(format!(
|
||||
"ord() expected a character, but string of length {} found",
|
||||
string_len
|
||||
"ord() expected a character, but string of length {string_len} found"
|
||||
)));
|
||||
}
|
||||
match string.chars().next() {
|
||||
@@ -939,15 +935,13 @@ mod builtins {
|
||||
if let Some(ref classcell) = classcell {
|
||||
let classcell = classcell.get().ok_or_else(|| {
|
||||
vm.new_type_error(format!(
|
||||
"__class__ not set defining {:?} as {:?}. Was __classcell__ propagated to type.__new__?",
|
||||
meta_name, class
|
||||
"__class__ not set defining {meta_name:?} as {class:?}. Was __classcell__ propagated to type.__new__?"
|
||||
))
|
||||
})?;
|
||||
|
||||
if !classcell.is(&class) {
|
||||
return Err(vm.new_type_error(format!(
|
||||
"__class__ set to {:?} defining {:?} as {:?}",
|
||||
classcell, meta_name, class
|
||||
"__class__ set to {classcell:?} defining {meta_name:?} as {class:?}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,7 +212,7 @@ mod _codecs {
|
||||
|
||||
fn error_oob_restart(&self, i: usize) -> PyBaseExceptionRef {
|
||||
self.vm
|
||||
.new_index_error(format!("position {} from error handler out of bounds", i))
|
||||
.new_index_error(format!("position {i} from error handler out of bounds"))
|
||||
}
|
||||
|
||||
fn error_encoding(
|
||||
|
||||
@@ -173,7 +173,7 @@ mod _collections {
|
||||
Err(vm.new_value_error(
|
||||
needle
|
||||
.repr(vm)
|
||||
.map(|repr| format!("{} is not in deque", repr))
|
||||
.map(|repr| format!("{repr} is not in deque"))
|
||||
.unwrap_or_else(|_| String::new()),
|
||||
))
|
||||
}
|
||||
@@ -302,11 +302,11 @@ mod _collections {
|
||||
let class_name = class.name();
|
||||
let closing_part = zelf
|
||||
.maxlen
|
||||
.map(|maxlen| format!("], maxlen={}", maxlen))
|
||||
.map(|maxlen| format!("], maxlen={maxlen}"))
|
||||
.unwrap_or_else(|| "]".to_owned());
|
||||
|
||||
let s = if zelf.len() == 0 {
|
||||
format!("{}([{})", class_name, closing_part)
|
||||
format!("{class_name}([{closing_part})")
|
||||
} else if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) {
|
||||
collection_repr(Some(&class_name), "[", &closing_part, deque.iter(), vm)?
|
||||
} else {
|
||||
|
||||
@@ -113,9 +113,7 @@ mod _imp {
|
||||
.frozen
|
||||
.get(name.as_str())
|
||||
.map(|frozen| frozen.package)
|
||||
.ok_or_else(|| {
|
||||
vm.new_import_error(format!("No such frozen object named {}", name), name)
|
||||
})
|
||||
.ok_or_else(|| vm.new_import_error(format!("No such frozen object named {name}"), name))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
|
||||
@@ -88,8 +88,7 @@ impl TryFromObject for Fildes {
|
||||
let fd = int.try_to_primitive(vm)?;
|
||||
if fd < 0 {
|
||||
return Err(vm.new_value_error(format!(
|
||||
"file descriptor cannot be a negative integer ({})",
|
||||
fd
|
||||
"file descriptor cannot be a negative integer ({fd})"
|
||||
)));
|
||||
}
|
||||
Ok(Fildes(fd))
|
||||
@@ -183,7 +182,7 @@ mod _io {
|
||||
if v >= 0 {
|
||||
Ok(v as usize)
|
||||
} else {
|
||||
Err(vm.new_value_error(format!("Negative size value {}", v)))
|
||||
Err(vm.new_value_error(format!("Negative size value {v}")))
|
||||
}
|
||||
})
|
||||
.transpose()
|
||||
@@ -843,7 +842,7 @@ mod _io {
|
||||
let offset = get_offset(ret, vm)?;
|
||||
if offset < 0 {
|
||||
return Err(
|
||||
vm.new_os_error(format!("Raw stream returned invalid position {}", offset))
|
||||
vm.new_os_error(format!("Raw stream returned invalid position {offset}"))
|
||||
);
|
||||
}
|
||||
self.abs_pos = offset;
|
||||
@@ -888,7 +887,7 @@ mod _io {
|
||||
let offset = get_offset(ret, vm)?;
|
||||
if offset < 0 {
|
||||
return Err(
|
||||
vm.new_os_error(format!("Raw stream returned invalid position {}", offset))
|
||||
vm.new_os_error(format!("Raw stream returned invalid position {offset}"))
|
||||
);
|
||||
}
|
||||
self.abs_pos = offset;
|
||||
@@ -941,8 +940,7 @@ mod _io {
|
||||
let n = isize::try_from_object(vm, res)?;
|
||||
if n < 0 || n as usize > len {
|
||||
return Err(vm.new_os_error(format!(
|
||||
"raw write() returned invalid length {} (should have been between 0 and {})",
|
||||
n, len
|
||||
"raw write() returned invalid length {n} (should have been between 0 and {len})"
|
||||
)));
|
||||
}
|
||||
if self.abs_pos != -1 {
|
||||
@@ -1173,8 +1171,7 @@ mod _io {
|
||||
let n = isize::try_from_object(vm, res)?;
|
||||
if n < 0 || n as usize > len {
|
||||
return Err(vm.new_os_error(format!(
|
||||
"raw readinto() returned invalid length {} (should have been between 0 and {})",
|
||||
n, len
|
||||
"raw readinto() returned invalid length {n} (should have been between 0 and {len})"
|
||||
)));
|
||||
}
|
||||
if n > 0 && self.abs_pos != -1 {
|
||||
@@ -1457,7 +1454,7 @@ mod _io {
|
||||
) -> PyResult<Offset> {
|
||||
let whence = whence.unwrap_or(0);
|
||||
if !validate_whence(whence) {
|
||||
return Err(vm.new_value_error(format!("whence value {} unsupported", whence)));
|
||||
return Err(vm.new_value_error(format!("whence value {whence} unsupported")));
|
||||
}
|
||||
let mut data = self.lock(vm)?;
|
||||
let raw = data.check_init(vm)?;
|
||||
@@ -1540,9 +1537,9 @@ mod _io {
|
||||
let cls = zelf.class();
|
||||
let slot_name = cls.slot_name();
|
||||
let repr = if let Some(name_repr) = name_repr {
|
||||
format!("<{} name={}>", slot_name, name_repr)
|
||||
format!("<{slot_name} name={name_repr}>")
|
||||
} else {
|
||||
format!("<{}>", slot_name)
|
||||
format!("<{slot_name}>")
|
||||
};
|
||||
Ok(repr)
|
||||
}
|
||||
@@ -1961,7 +1958,7 @@ mod _io {
|
||||
"\n" => Self::Lf,
|
||||
"\r" => Self::Cr,
|
||||
"\r\n" => Self::Crlf,
|
||||
_ => return Err(vm.new_value_error(format!("illegal newline value: {}", s))),
|
||||
_ => return Err(vm.new_value_error(format!("illegal newline value: {s}"))),
|
||||
}
|
||||
};
|
||||
Ok(nl)
|
||||
@@ -2405,8 +2402,9 @@ mod _io {
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
return Err(vm
|
||||
.new_value_error(format!("invalid whence ({}, should be 0, 1 or 2)", how)))
|
||||
return Err(
|
||||
vm.new_value_error(format!("invalid whence ({how}, should be 0, 1 or 2)"))
|
||||
)
|
||||
}
|
||||
};
|
||||
use crate::types::PyComparisonOp;
|
||||
@@ -3480,7 +3478,7 @@ mod _io {
|
||||
impl ParseModeError {
|
||||
fn error_msg(&self, mode_string: &str) -> String {
|
||||
match self {
|
||||
ParseModeError::InvalidMode => format!("invalid mode: '{}'", mode_string),
|
||||
ParseModeError::InvalidMode => format!("invalid mode: '{mode_string}'"),
|
||||
ParseModeError::MultipleFile => {
|
||||
"must have exactly one of create/read/write/append mode".to_owned()
|
||||
}
|
||||
@@ -3759,7 +3757,7 @@ mod fileio {
|
||||
impl ModeError {
|
||||
fn error_msg(&self, mode_str: &str) -> String {
|
||||
match self {
|
||||
ModeError::Invalid => format!("invalid mode: {}", mode_str),
|
||||
ModeError::Invalid => format!("invalid mode: {mode_str}"),
|
||||
ModeError::BadRwa => {
|
||||
"Must have exactly one of create/read/write/append mode and at most one plus"
|
||||
.to_owned()
|
||||
@@ -3894,7 +3892,7 @@ mod fileio {
|
||||
}
|
||||
let fd = i32::try_from_object(vm, fd)?;
|
||||
if fd < 0 {
|
||||
return Err(vm.new_value_error(format!("opener returned {}", fd)));
|
||||
return Err(vm.new_value_error(format!("opener returned {fd}")));
|
||||
}
|
||||
fd
|
||||
} else if let Some(i) = name.payload::<crate::builtins::PyInt>() {
|
||||
@@ -3992,12 +3990,9 @@ mod fileio {
|
||||
let mode = zelf.mode();
|
||||
let closefd = if zelf.closefd.load() { "True" } else { "False" };
|
||||
let repr = if let Some(name_repr) = name_repr {
|
||||
format!(
|
||||
"<_io.FileIO name={} mode='{}' closefd={}>",
|
||||
name_repr, mode, closefd
|
||||
)
|
||||
format!("<_io.FileIO name={name_repr} mode='{mode}' closefd={closefd}>")
|
||||
} else {
|
||||
format!("<_io.FileIO fd={} mode='{}' closefd={}>", fd, mode, closefd)
|
||||
format!("<_io.FileIO fd={fd} mode='{mode}' closefd={closefd}>")
|
||||
};
|
||||
Ok(repr)
|
||||
}
|
||||
|
||||
@@ -273,7 +273,7 @@ mod decl {
|
||||
let cur = format!("{}", self.cur.read().clone().repr(vm)?);
|
||||
let step = &self.step;
|
||||
if vm.bool_eq(step, vm.ctx.new_int(1).as_object())? {
|
||||
return Ok(format!("count({})", cur));
|
||||
return Ok(format!("count({cur})"));
|
||||
}
|
||||
Ok(format!("count({}, {})", cur, step.repr(vm)?))
|
||||
}
|
||||
@@ -404,7 +404,7 @@ mod decl {
|
||||
fmt.push_str(", ");
|
||||
fmt.push_str(×.read().to_string());
|
||||
}
|
||||
Ok(format!("repeat({})", fmt))
|
||||
Ok(format!("repeat({fmt})"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -857,8 +857,7 @@ mod decl {
|
||||
}
|
||||
// We don't have an int or value was < 0 or > sys.maxsize
|
||||
Err(vm.new_value_error(format!(
|
||||
"{} argument for islice() must be None or an integer: 0 <= x <= sys.maxsize.",
|
||||
name
|
||||
"{name} argument for islice() must be None or an integer: 0 <= x <= sys.maxsize."
|
||||
)))
|
||||
}
|
||||
|
||||
|
||||
@@ -369,7 +369,7 @@ mod _operator {
|
||||
} else {
|
||||
"...".to_owned()
|
||||
};
|
||||
Ok(format!("operator.attrgetter({})", fmt))
|
||||
Ok(format!("operator.attrgetter({fmt})"))
|
||||
}
|
||||
|
||||
#[pymethod(magic)]
|
||||
@@ -465,7 +465,7 @@ mod _operator {
|
||||
} else {
|
||||
"...".to_owned()
|
||||
};
|
||||
Ok(format!("operator.itemgetter({})", fmt))
|
||||
Ok(format!("operator.itemgetter({fmt})"))
|
||||
}
|
||||
|
||||
#[pymethod(magic)]
|
||||
@@ -541,7 +541,7 @@ mod _operator {
|
||||
let mut parts = Vec::with_capacity(kwargs.len());
|
||||
for (key, value) in kwargs {
|
||||
let value_repr = value.repr(vm)?;
|
||||
parts.push(format!("{}={}", key, value_repr));
|
||||
parts.push(format!("{key}={value_repr}"));
|
||||
}
|
||||
fmt.push(parts.join(", "));
|
||||
}
|
||||
@@ -549,7 +549,7 @@ mod _operator {
|
||||
} else {
|
||||
"...".to_owned()
|
||||
};
|
||||
Ok(format!("operator.methodcaller({})", fmt))
|
||||
Ok(format!("operator.methodcaller({fmt})"))
|
||||
}
|
||||
|
||||
#[pymethod(magic)]
|
||||
|
||||
@@ -1609,7 +1609,7 @@ pub(super) mod _os {
|
||||
// TODO: just call libc::truncate() on POSIX
|
||||
let f = OpenOptions::new()
|
||||
.write(true)
|
||||
.open(&path)
|
||||
.open(path)
|
||||
.map_err(|e| e.into_pyexception(vm))?;
|
||||
f.set_len(length as u64)
|
||||
.map_err(|e| e.into_pyexception(vm))?;
|
||||
@@ -1637,7 +1637,7 @@ pub(super) mod _os {
|
||||
#[pyfunction]
|
||||
fn waitstatus_to_exitcode(status: i32, vm: &VirtualMachine) -> PyResult<i32> {
|
||||
let status = u32::try_from(status)
|
||||
.map_err(|_| vm.new_value_error(format!("invalid WEXITSTATUS: {}", status)))?;
|
||||
.map_err(|_| vm.new_value_error(format!("invalid WEXITSTATUS: {status}")))?;
|
||||
|
||||
cfg_if::cfg_if! {
|
||||
if #[cfg(not(windows))] {
|
||||
@@ -1650,7 +1650,7 @@ pub(super) mod _os {
|
||||
return Ok(-libc::WTERMSIG(status));
|
||||
}
|
||||
|
||||
Err(vm.new_value_error(format!("Invalid wait status: {}", status)))
|
||||
Err(vm.new_value_error(format!("Invalid wait status: {status}")))
|
||||
} else {
|
||||
i32::try_from(status.rotate_right(8))
|
||||
.map_err(|_| vm.new_value_error(format!("invalid wait status: {}", status)))
|
||||
|
||||
@@ -268,7 +268,7 @@ pub mod module {
|
||||
)
|
||||
})?;
|
||||
|
||||
let metadata = fs::metadata(&path.path);
|
||||
let metadata = fs::metadata(path.path);
|
||||
|
||||
// if it's only checking for F_OK
|
||||
if flags == AccessFlags::F_OK {
|
||||
@@ -1012,10 +1012,10 @@ pub mod module {
|
||||
|
||||
match i.cmp(&-1) {
|
||||
Ordering::Greater => Ok(Some(i.try_into().map_err(|_| {
|
||||
vm.new_overflow_error(format!("{} is larger than maximum", typ_name))
|
||||
vm.new_overflow_error(format!("{typ_name} is larger than maximum"))
|
||||
})?)),
|
||||
Ordering::Less => {
|
||||
Err(vm.new_overflow_error(format!("{} is less than minimum", typ_name)))
|
||||
Err(vm.new_overflow_error(format!("{typ_name} is less than minimum")))
|
||||
}
|
||||
Ordering::Equal => Ok(None), // -1 means does not change the value
|
||||
}
|
||||
@@ -1371,7 +1371,7 @@ pub mod module {
|
||||
for sig in sigs.iter(vm)? {
|
||||
let sig = sig?;
|
||||
let sig = signal::Signal::try_from(sig).map_err(|_| {
|
||||
vm.new_value_error(format!("signal number {} out of range", sig))
|
||||
vm.new_value_error(format!("signal number {sig} out of range"))
|
||||
})?;
|
||||
set.add(sig);
|
||||
}
|
||||
@@ -1604,7 +1604,7 @@ pub mod module {
|
||||
slice
|
||||
.to_str()
|
||||
.map(|s| s.to_owned())
|
||||
.map_err(|e| vm.new_unicode_decode_error(format!("unable to decode login name: {}", e)))
|
||||
.map_err(|e| vm.new_unicode_decode_error(format!("unable to decode login name: {e}")))
|
||||
}
|
||||
|
||||
// cfg from nix
|
||||
|
||||
@@ -61,7 +61,7 @@ mod pwd {
|
||||
let user = user.ok_or_else(|| {
|
||||
vm.new_key_error(
|
||||
vm.ctx
|
||||
.new_str(format!("getpwnam(): name not found: {}", pw_name))
|
||||
.new_str(format!("getpwnam(): name not found: {pw_name}"))
|
||||
.into(),
|
||||
)
|
||||
})?;
|
||||
|
||||
@@ -230,9 +230,7 @@ pub(crate) mod _signal {
|
||||
let nonblock =
|
||||
fcntl::OFlag::from_bits_truncate(oflags).contains(fcntl::OFlag::O_NONBLOCK);
|
||||
if !nonblock {
|
||||
return Err(
|
||||
vm.new_value_error(format!("the fd {} must be in non-blocking mode", fd))
|
||||
);
|
||||
return Err(vm.new_value_error(format!("the fd {fd} must be in non-blocking mode")));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -375,9 +375,9 @@ mod _sre {
|
||||
};
|
||||
|
||||
if flags.is_empty() {
|
||||
Ok(format!("re.compile({})", s))
|
||||
Ok(format!("re.compile({s})"))
|
||||
} else {
|
||||
Ok(format!("re.compile({}, {})", s, flags))
|
||||
Ok(format!("re.compile({s}, {flags})"))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -92,7 +92,7 @@ mod symtable {
|
||||
}
|
||||
.into_ref(vm))
|
||||
} else {
|
||||
Err(vm.new_key_error(vm.ctx.new_str(format!("lookup {} failed", name)).into()))
|
||||
Err(vm.new_key_error(vm.ctx.new_str(format!("lookup {name} failed")).into()))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -619,8 +619,7 @@ mod sys {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(vm.new_recursion_error(format!(
|
||||
"cannot set the recursion limit to {} at the recursion depth {}: the limit is too low",
|
||||
recursion_limit, recursion_depth
|
||||
"cannot set the recursion limit to {recursion_limit} at the recursion depth {recursion_depth}: the limit is too low"
|
||||
)))
|
||||
}
|
||||
}
|
||||
@@ -920,7 +919,7 @@ impl PyStderr<'_> {
|
||||
return;
|
||||
}
|
||||
}
|
||||
eprint!("{}", args)
|
||||
eprint!("{args}")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ pub(crate) mod _sysconfigdata {
|
||||
}
|
||||
sysvars! {
|
||||
// fake shared module extension
|
||||
"EXT_SUFFIX" => format!(".rustpython-{}", MULTIARCH),
|
||||
"EXT_SUFFIX" => format!(".rustpython-{MULTIARCH}"),
|
||||
"MULTIARCH" => MULTIARCH,
|
||||
// enough for tests to stop expecting urandom() to fail after restricting file resources
|
||||
"HAVE_GETRANDOM" => 1,
|
||||
|
||||
@@ -52,7 +52,7 @@ mod time {
|
||||
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(|e| vm.new_value_error(format!("Time error: {:?}", e)))
|
||||
.map_err(|e| vm.new_value_error(format!("Time error: {e:?}")))
|
||||
}
|
||||
|
||||
// TODO: implement proper monotonic time for wasm/wasi.
|
||||
@@ -220,7 +220,7 @@ mod time {
|
||||
) -> PyResult<PyStructTime> {
|
||||
let format = format.as_ref().map_or("%a %b %H:%M:%S %Y", |s| s.as_str());
|
||||
let instant = NaiveDateTime::parse_from_str(string.as_str(), format)
|
||||
.map_err(|e| vm.new_value_error(format!("Parse error: {:?}", e)))?;
|
||||
.map_err(|e| vm.new_value_error(format!("Parse error: {e:?}")))?;
|
||||
Ok(PyStructTime::new(vm, instant, -1))
|
||||
}
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ pub trait PyStructSequence: StaticType + PyClassImpl + Sized + 'static {
|
||||
fn repr(zelf: PyRef<PyTuple>, vm: &VirtualMachine) -> PyResult<String> {
|
||||
let format_field = |(value, name): (&PyObjectRef, _)| {
|
||||
let s = value.repr(vm)?;
|
||||
Ok(format!("{}={}", name, s))
|
||||
Ok(format!("{name}={s}"))
|
||||
};
|
||||
let (body, suffix) = if let Some(_guard) =
|
||||
rustpython_vm::recursion::ReprGuard::enter(vm, zelf.as_object())
|
||||
|
||||
@@ -25,7 +25,7 @@ pub fn get_version() -> String {
|
||||
}
|
||||
|
||||
pub fn get_version_number() -> String {
|
||||
format!("{}.{}.{}{}", MAJOR, MINOR, MICRO, RELEASELEVEL)
|
||||
format!("{MAJOR}.{MINOR}.{MICRO}{RELEASELEVEL}")
|
||||
}
|
||||
|
||||
pub fn get_compiler() -> String {
|
||||
@@ -105,5 +105,5 @@ pub fn get_git_datetime() -> String {
|
||||
let date = get_git_date();
|
||||
let time = get_git_time();
|
||||
|
||||
format!("{} {}", date, time)
|
||||
format!("{date} {time}")
|
||||
}
|
||||
|
||||
@@ -261,7 +261,7 @@ impl VirtualMachine {
|
||||
self,
|
||||
)?;
|
||||
self.sys_module.set_attr(
|
||||
format!("__{}__", name), // e.g. __stdin__
|
||||
format!("__{name}__"), // e.g. __stdin__
|
||||
stdio.clone(),
|
||||
self,
|
||||
)?;
|
||||
@@ -405,7 +405,7 @@ impl VirtualMachine {
|
||||
// To be called right before raising the recursion depth.
|
||||
fn check_recursive_call(&self, _where: &str) -> PyResult<()> {
|
||||
if self.recursion_depth.get() >= self.recursion_limit.get() {
|
||||
Err(self.new_recursion_error(format!("maximum recursion depth exceeded {}", _where)))
|
||||
Err(self.new_recursion_error(format!("maximum recursion depth exceeded {_where}")))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
@@ -447,10 +447,10 @@ impl VirtualMachine {
|
||||
pub fn class(&self, module: &str, class: &str) -> PyTypeRef {
|
||||
let module = self
|
||||
.import(module, None, 0)
|
||||
.unwrap_or_else(|_| panic!("unable to import {}", module));
|
||||
.unwrap_or_else(|_| panic!("unable to import {module}"));
|
||||
let class = module
|
||||
.get_attr(class, self)
|
||||
.unwrap_or_else(|_| panic!("module {:?} has no class {}", module, class));
|
||||
.unwrap_or_else(|_| panic!("module {module:?} has no class {class}"));
|
||||
class.downcast().expect("not a class")
|
||||
}
|
||||
|
||||
@@ -487,7 +487,7 @@ impl VirtualMachine {
|
||||
Some(cached_module) => {
|
||||
if self.is_none(&cached_module) {
|
||||
Err(self.new_import_error(
|
||||
format!("import of {} halted; None in sys.modules", module),
|
||||
format!("import of {module} halted; None in sys.modules"),
|
||||
module,
|
||||
))
|
||||
} else {
|
||||
@@ -754,7 +754,7 @@ impl VirtualMachine {
|
||||
};
|
||||
if let Some(msg) = msg {
|
||||
let stderr = stdlib::sys::PyStderr(self);
|
||||
writeln!(stderr, "{}", msg);
|
||||
writeln!(stderr, "{msg}");
|
||||
}
|
||||
1
|
||||
} else {
|
||||
|
||||
@@ -38,7 +38,7 @@ impl VirtualMachine {
|
||||
} else {
|
||||
"run with RUST_BACKTRACE=1 to see Python backtrace"
|
||||
};
|
||||
panic!("{}; {}", msg, after)
|
||||
panic!("{msg}; {after}")
|
||||
}
|
||||
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
|
||||
{
|
||||
|
||||
@@ -117,7 +117,7 @@ fn get_filter(
|
||||
None
|
||||
};
|
||||
let tmp_item = tmp_item.ok_or_else(|| {
|
||||
vm.new_value_error(format!("_warnings.filters item {} isn't a 5-tuple", i))
|
||||
vm.new_value_error(format!("_warnings.filters item {i} isn't a 5-tuple"))
|
||||
})?;
|
||||
|
||||
/* Python code: action, msg, cat, mod, ln = item */
|
||||
|
||||
Reference in New Issue
Block a user