Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Migrate to the 2024 edition #5560

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion 2 Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ members = [
[workspace.package]
version = "0.4.0"
authors = ["RustPython Team"]
edition = "2021"
edition = "2024"
rust-version = "1.85.0"
repository = "https://github.com/RustPython/RustPython"
license = "MIT"
Expand Down
6 changes: 3 additions & 3 deletions 6 benches/execution.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use criterion::measurement::WallTime;
use criterion::{
black_box, criterion_group, criterion_main, Bencher, BenchmarkGroup, BenchmarkId, Criterion,
Throughput,
Bencher, BenchmarkGroup, BenchmarkId, Criterion, Throughput, black_box, criterion_group,
criterion_main,
};
use rustpython_compiler::Mode;
use rustpython_parser::ast;
use rustpython_parser::Parse;
use rustpython_parser::ast;
use rustpython_vm::{Interpreter, PyResult, Settings};
use std::collections::HashMap;
use std::path::Path;
Expand Down
4 changes: 2 additions & 2 deletions 4 benches/microbenchmarks.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use criterion::{
criterion_group, criterion_main, measurement::WallTime, BatchSize, BenchmarkGroup, BenchmarkId,
Criterion, Throughput,
BatchSize, BenchmarkGroup, BenchmarkId, Criterion, Throughput, criterion_group, criterion_main,
measurement::WallTime,
};
use pyo3::types::PyAnyMethods;
use rustpython_compiler::Mode;
Expand Down
14 changes: 7 additions & 7 deletions 14 common/src/fileutils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
pub use libc::stat as StatStruct;

#[cfg(windows)]
pub use windows::{fstat, StatStruct};
pub use windows::{StatStruct, fstat};

#[cfg(not(windows))]
pub fn fstat(fd: libc::c_int) -> std::io::Result<StatStruct> {
Expand All @@ -28,19 +28,19 @@ pub mod windows {
use std::ffi::{CString, OsStr, OsString};
use std::os::windows::ffi::OsStrExt;
use std::sync::OnceLock;
use windows_sys::core::PCWSTR;
use windows_sys::Win32::Foundation::{
FreeLibrary, SetLastError, BOOL, ERROR_INVALID_HANDLE, ERROR_NOT_SUPPORTED, FILETIME,
HANDLE, INVALID_HANDLE_VALUE,
BOOL, ERROR_INVALID_HANDLE, ERROR_NOT_SUPPORTED, FILETIME, FreeLibrary, HANDLE,
INVALID_HANDLE_VALUE, SetLastError,
};
use windows_sys::Win32::Storage::FileSystem::{
FileBasicInfo, FileIdInfo, GetFileInformationByHandle, GetFileInformationByHandleEx,
GetFileType, BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_READONLY,
BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_READONLY,
FILE_ATTRIBUTE_REPARSE_POINT, FILE_BASIC_INFO, FILE_ID_INFO, FILE_TYPE_CHAR,
FILE_TYPE_DISK, FILE_TYPE_PIPE, FILE_TYPE_UNKNOWN,
FILE_TYPE_DISK, FILE_TYPE_PIPE, FILE_TYPE_UNKNOWN, FileBasicInfo, FileIdInfo,
GetFileInformationByHandle, GetFileInformationByHandleEx, GetFileType,
};
use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW};
use windows_sys::Win32::System::SystemServices::IO_REPARSE_TAG_SYMLINK;
use windows_sys::core::PCWSTR;

pub const S_IFIFO: libc::c_int = 0o010000;
pub const S_IFLNK: libc::c_int = 0o120000;
Expand Down
12 changes: 2 additions & 10 deletions 12 common/src/float_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,7 @@ pub fn gt_int(value: f64, other_int: &BigInt) -> bool {
}

pub fn div(v1: f64, v2: f64) -> Option<f64> {
if v2 != 0.0 {
Some(v1 / v2)
} else {
None
}
if v2 != 0.0 { Some(v1 / v2) } else { None }
}

pub fn mod_(v1: f64, v2: f64) -> Option<f64> {
Expand Down Expand Up @@ -125,11 +121,7 @@ pub fn nextafter(x: f64, y: f64) -> f64 {
let b = x.to_bits();
let bits = if (y > x) == (x > 0.0) { b + 1 } else { b - 1 };
let ret = f64::from_bits(bits);
if ret == 0.0 {
ret.copysign(x)
} else {
ret
}
if ret == 0.0 { ret.copysign(x) } else { ret }
}
}

Expand Down
6 changes: 1 addition & 5 deletions 6 common/src/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,11 +150,7 @@ pub fn hash_bigint(value: &BigInt) -> PyHash {

#[inline(always)]
pub fn fix_sentinel(x: PyHash) -> PyHash {
if x == SENTINEL {
-2
} else {
x
}
if x == SENTINEL { -2 } else { x }
}

#[inline]
Expand Down
6 changes: 1 addition & 5 deletions 6 common/src/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,11 +241,7 @@ pub mod levenshtein {
if b.is_ascii_uppercase() {
b += b'a' - b'A';
}
if a == b {
CASE_COST
} else {
MOVE_COST
}
if a == b { CASE_COST } else { MOVE_COST }
}

pub fn levenshtein_distance(a: &str, b: &str, max_cost: usize) -> usize {
Expand Down
14 changes: 8 additions & 6 deletions 14 compiler/codegen/src/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,21 @@
#![deny(clippy::cast_possible_truncation)]

use crate::{
IndexSet,
error::{CodegenError, CodegenErrorType},
ir,
symboltable::{self, SymbolFlags, SymbolScope, SymbolTable},
IndexSet,
};
use itertools::Itertools;
use num_complex::Complex64;
use num_traits::ToPrimitive;
use rustpython_ast::located::{self as located_ast, Located};
use rustpython_compiler_core::{
Mode,
bytecode::{
self, Arg as OpArgMarker, CodeObject, ComparisonOperator, ConstantData, Instruction, OpArg,
OpArgType,
},
Mode,
};
use rustpython_parser_core::source_code::{LineNumber, SourceLocation};
use std::borrow::Cow;
Expand Down Expand Up @@ -975,7 +975,7 @@ impl Compiler {
}
}
located_ast::Expr::BinOp(_) | located_ast::Expr::UnaryOp(_) => {
return Err(self.error(CodegenErrorType::Delete("expression")))
return Err(self.error(CodegenErrorType::Delete("expression")));
}
_ => return Err(self.error(CodegenErrorType::Delete(expression.python_name()))),
}
Expand Down Expand Up @@ -1213,7 +1213,7 @@ impl Compiler {

if !finalbody.is_empty() {
emit!(self, Instruction::PopBlock); // pop excepthandler block
// We enter the finally block, without exception.
// We enter the finally block, without exception.
emit!(self, Instruction::EnterFinally);
}

Expand Down Expand Up @@ -3124,7 +3124,9 @@ impl Compiler {
| "with_statement" | "print_function" | "unicode_literals" | "generator_stop" => {}
"annotations" => self.future_annotations = true,
other => {
return Err(self.error(CodegenErrorType::InvalidFutureFeature(other.to_owned())))
return Err(
self.error(CodegenErrorType::InvalidFutureFeature(other.to_owned()))
);
}
}
}
Expand Down Expand Up @@ -3477,8 +3479,8 @@ impl ToU32 for usize {
#[cfg(test)]
mod tests {
use super::*;
use rustpython_parser::ast::Suite;
use rustpython_parser::Parse;
use rustpython_parser::ast::Suite;
use rustpython_parser_core::source_code::LinearLocator;

fn compile_exec(source: &str) -> CodeObject {
Expand Down
6 changes: 1 addition & 5 deletions 6 compiler/codegen/src/ir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,11 +199,7 @@ impl CodeInfo {
})
.collect::<Box<[_]>>();

if found_cellarg {
Some(cell2arg)
} else {
None
}
if found_cellarg { Some(cell2arg) } else { None }
}

fn dce(&mut self) {
Expand Down
9 changes: 6 additions & 3 deletions 9 compiler/codegen/src/symboltable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ Inspirational file: https://github.com/python/cpython/blob/main/Python/symtable.
*/

use crate::{
error::{CodegenError, CodegenErrorType},
IndexMap,
error::{CodegenError, CodegenErrorType},
};
use bitflags::bitflags;
use rustpython_ast::{self as ast, located::Located};
Expand Down Expand Up @@ -505,7 +505,10 @@ impl SymbolTableAnalyzer {
// check if assignee is an iterator in top scope
if parent_symbol.flags.contains(SymbolFlags::ITER) {
return Err(SymbolTableError {
error: format!("assignment expression cannot rebind comprehension iteration variable {}", symbol.name),
error: format!(
"assignment expression cannot rebind comprehension iteration variable {}",
symbol.name
),
location: None,
});
}
Expand Down Expand Up @@ -1408,7 +1411,7 @@ impl SymbolTableBuilder {
return Err(SymbolTableError {
error: format!("cannot define nonlocal '{name}' at top level."),
location,
})
});
}
_ => {
// Ok!
Expand Down
6 changes: 3 additions & 3 deletions 6 compiler/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use rustpython_codegen::{compile, symboltable};
use rustpython_parser::ast::{self as ast, fold::Fold, ConstantOptimizer};
use rustpython_parser::ast::{self as ast, ConstantOptimizer, fold::Fold};

pub use rustpython_codegen::compile::CompileOpts;
pub use rustpython_compiler_core::{bytecode::CodeObject, Mode};
pub use rustpython_parser::{source_code::LinearLocator, Parse};
pub use rustpython_compiler_core::{Mode, bytecode::CodeObject};
pub use rustpython_parser::{Parse, source_code::LinearLocator};

// these modules are out of repository. re-exporting them here for convenience.
pub use rustpython_codegen as codegen;
Expand Down
17 changes: 9 additions & 8 deletions 17 derive-impl/src/compile_bytecode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,16 @@ use crate::Diagnostic;
use once_cell::sync::Lazy;
use proc_macro2::{Span, TokenStream};
use quote::quote;
use rustpython_compiler_core::{bytecode::CodeObject, frozen, Mode};
use rustpython_compiler_core::{Mode, bytecode::CodeObject, frozen};
use std::{
collections::HashMap,
env, fs,
path::{Path, PathBuf},
};
use syn::{
self,
self, LitByteStr, LitStr, Macro,
parse::{ParseStream, Parser, Result as ParseResult},
spanned::Spanned,
LitByteStr, LitStr, Macro,
};

static CARGO_MANIFEST_DIR: Lazy<PathBuf> = Lazy::new(|| {
Expand Down Expand Up @@ -118,11 +117,13 @@ impl CompilationSource {
})?;
self.compile_string(&source, mode, module_name, compiler, || rel_path.display())
}
CompilationSourceKind::SourceCode(code) => {
self.compile_string(&textwrap::dedent(code), mode, module_name, compiler, || {
"string literal"
})
}
CompilationSourceKind::SourceCode(code) => self.compile_string(
&textwrap::dedent(code),
mode,
module_name,
compiler,
|| "string literal",
),
CompilationSourceKind::Dir(_) => {
unreachable!("Can't use compile_single with directory source")
}
Expand Down
4 changes: 2 additions & 2 deletions 4 derive-impl/src/from_args.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use quote::{ToTokens, quote};
use syn::ext::IdentExt;
use syn::meta::ParseNestedMeta;
use syn::{parse_quote, Attribute, Data, DeriveInput, Expr, Field, Ident, Result, Token};
use syn::{Attribute, Data, DeriveInput, Expr, Field, Ident, Result, Token, parse_quote};

/// The kind of the python parameter, this corresponds to the value of Parameter.kind
/// (https://docs.python.org/3/library/inspect.html#inspect.Parameter.kind)
Expand Down
33 changes: 14 additions & 19 deletions 33 derive-impl/src/pyclass.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use super::Diagnostic;
use crate::util::{
format_doc, pyclass_ident_and_attrs, pyexception_ident_and_attrs, text_signature,
ClassItemMeta, ContentItem, ContentItemInner, ErrorVec, ExceptionItemMeta, ItemMeta,
ItemMetaInner, ItemNursery, SimpleItemMeta, ALL_ALLOWED_NAMES,
ALL_ALLOWED_NAMES, ClassItemMeta, ContentItem, ContentItemInner, ErrorVec, ExceptionItemMeta,
ItemMeta, ItemMetaInner, ItemNursery, SimpleItemMeta, format_doc, pyclass_ident_and_attrs,
pyexception_ident_and_attrs, text_signature,
};
use proc_macro2::{Delimiter, Group, Span, TokenStream, TokenTree};
use quote::{quote, quote_spanned, ToTokens};
use quote::{ToTokens, quote, quote_spanned};
use std::collections::{HashMap, HashSet};
use std::str::FromStr;
use syn::{parse_quote, spanned::Spanned, Attribute, Ident, Item, Result};
use syn::{Attribute, Ident, Item, Result, parse_quote, spanned::Spanned};
use syn_ext::ext::*;
use syn_ext::types::*;

Expand Down Expand Up @@ -126,15 +126,15 @@ pub(crate) fn impl_pyclass_impl(attr: PunctuatedNestedMeta, item: Item) -> Resul
return Err(syn::Error::new_spanned(
segment,
"Py{Ref}<T> is expected but Py{Ref}<?> is found",
))
));
}
}
}
_ => {
return Err(syn::Error::new_spanned(
segment,
"Py{Ref}<T> is expected but Py{Ref}? is found",
))
));
}
}
} else {
Expand All @@ -152,7 +152,7 @@ pub(crate) fn impl_pyclass_impl(attr: PunctuatedNestedMeta, item: Item) -> Resul
return Err(syn::Error::new_spanned(
imp.self_ty,
"PyImpl can only be implemented for Py{Ref}<T> or T",
))
));
}
};

Expand Down Expand Up @@ -1237,11 +1237,7 @@ impl MethodItemMeta {
name
} else {
let name = inner.item_name();
if magic {
format!("__{name}__")
} else {
name
}
if magic { format!("__{name}__") } else { name }
})
}
}
Expand Down Expand Up @@ -1308,11 +1304,7 @@ impl GetSetItemMeta {
GetSetItemKind::Set => extract_prefix_name("set_", "setter")?,
GetSetItemKind::Delete => extract_prefix_name("del_", "deleter")?,
};
if magic {
format!("__{name}__")
} else {
name
}
if magic { format!("__{name}__") } else { name }
};
Ok((py_name, kind))
}
Expand Down Expand Up @@ -1488,7 +1480,10 @@ fn extract_impl_attrs(attr: PunctuatedNestedMeta, item: &Ident) -> Result<Extrac
)
} else {
if path.is_ident("DefaultConstructor") {
bail_span!(meta, "Try `#[pyclass(with(Constructor, ...))]` instead of `#[pyclass(with(DefaultConstructor, ...))]`. DefaultConstructor implicitly implements Constructor.")
bail_span!(
meta,
"Try `#[pyclass(with(Constructor, ...))]` instead of `#[pyclass(with(DefaultConstructor, ...))]`. DefaultConstructor implicitly implements Constructor."
)
}
if path.is_ident("Constructor") || path.is_ident("Unconstructible") {
has_constructor = true;
Expand Down
Loading
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.