Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
* Added alloc_instead_of_core, std_instead_of_alloc, and std_instead_…
…of_core clippy rules

* Manually changed part of the code to use core/alloc
  • Loading branch information
terryluan12 committed Dec 29, 2025
commit 61f9c0842c69fcdccf69df6c1ab608e922ac044a
5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -232,8 +232,11 @@ unsafe_op_in_unsafe_fn = "deny"
elided_lifetimes_in_paths = "warn"

[workspace.lints.clippy]
alloc_instead_of_core = "warn"
std_instead_of_alloc = "warn"
std_instead_of_core = "warn"
perf = "warn"
style = "warn"
complexity = "warn"
suspicious = "warn"
correctness = "warn"
correctness = "warn"
10 changes: 5 additions & 5 deletions crates/codegen/src/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ fn compiler_unwrap_option<T>(zelf: &Compiler, o: Option<T>) -> T {
o.unwrap()
}

// fn compiler_result_unwrap<T, E: std::fmt::Debug>(zelf: &Compiler, result: Result<T, E>) -> T {
// fn compiler_result_unwrap<T, E: core::fmt::Debug>(zelf: &Compiler, result: Result<T, E>) -> T {
// if result.is_err() {
// eprintln!("=== CODEGEN PANIC INFO ===");
// eprintln!("This IS an internal error, an result was unwrapped during codegen");
Expand Down Expand Up @@ -1831,7 +1831,7 @@ impl Compiler {
name.to_owned(),
);

let args_iter = std::iter::empty()
let args_iter = core::iter::empty()
.chain(&parameters.posonlyargs)
.chain(&parameters.args)
.map(|arg| &arg.parameter)
Expand Down Expand Up @@ -2438,7 +2438,7 @@ impl Compiler {
let mut funcflags = bytecode::MakeFunctionFlags::empty();

// Handle positional defaults
let defaults: Vec<_> = std::iter::empty()
let defaults: Vec<_> = core::iter::empty()
.chain(&parameters.posonlyargs)
.chain(&parameters.args)
.filter_map(|x| x.default.as_deref())
Expand Down Expand Up @@ -2566,7 +2566,7 @@ impl Compiler {
let mut num_annotations = 0;

// Handle parameter annotations
let parameters_iter = std::iter::empty()
let parameters_iter = core::iter::empty()
.chain(&parameters.posonlyargs)
.chain(&parameters.args)
.chain(&parameters.kwonlyargs)
Expand Down Expand Up @@ -4965,7 +4965,7 @@ impl Compiler {
let name = "<lambda>".to_owned();

// Prepare defaults before entering function
let defaults: Vec<_> = std::iter::empty()
let defaults: Vec<_> = core::iter::empty()
.chain(&params.posonlyargs)
.chain(&params.args)
.filter_map(|x| x.default.as_deref())
Expand Down
2 changes: 1 addition & 1 deletion crates/codegen/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ pub enum CodegenErrorType {
NotImplementedYet, // RustPython marker for unimplemented features
}

impl std::error::Error for CodegenErrorType {}
impl core::error::Error for CodegenErrorType {}

impl fmt::Display for CodegenErrorType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Expand Down
2 changes: 2 additions & 0 deletions crates/codegen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
#[macro_use]
extern crate log;

extern crate alloc;

type IndexMap<K, V> = indexmap::IndexMap<K, V, ahash::RandomState>;
type IndexSet<T> = indexmap::IndexSet<T, ahash::RandomState>;

Expand Down
4 changes: 2 additions & 2 deletions crates/codegen/src/symboltable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,8 +215,8 @@ impl SymbolTableError {

type SymbolTableResult<T = ()> = Result<T, SymbolTableError>;

impl std::fmt::Debug for SymbolTable {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Debug for SymbolTable {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
f,
"SymbolTable({:?} symbols, {:?} sub scopes)",
Expand Down
8 changes: 4 additions & 4 deletions crates/codegen/src/unparse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use ruff_python_ast::{
use ruff_text_size::Ranged;
use rustpython_compiler_core::SourceFile;
use rustpython_literal::escape::{AsciiEscape, UnicodeEscape};
use std::fmt::{self, Display as _};
use alloc::fmt::{self, Display as _};

mod precedence {
macro_rules! precedence {
Expand Down Expand Up @@ -51,7 +51,7 @@ impl<'a, 'b, 'c> Unparser<'a, 'b, 'c> {
}

fn p_delim(&mut self, first: &mut bool, s: &str) -> fmt::Result {
self.p_if(!std::mem::take(first), s)
self.p_if(!core::mem::take(first), s)
}

fn write_fmt(&mut self, f: fmt::Arguments<'_>) -> fmt::Result {
Expand Down Expand Up @@ -575,7 +575,7 @@ impl<'a, 'b, 'c> Unparser<'a, 'b, 'c> {
if conversion != ConversionFlag::None {
self.p("!")?;
let buf = &[conversion as u8];
let c = std::str::from_utf8(buf).unwrap();
let c = core::str::from_utf8(buf).unwrap();
self.p(c)?;
}

Expand Down Expand Up @@ -650,7 +650,7 @@ impl fmt::Display for UnparseExpr<'_> {
}

fn to_string_fmt(f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result) -> String {
use std::cell::Cell;
use core::cell::Cell;
struct Fmt<F>(Cell<Option<F>>);
impl<F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result> fmt::Display for Fmt<F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Expand Down
2 changes: 1 addition & 1 deletion crates/common/src/boxvec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -693,7 +693,7 @@ impl<T> CapacityError<T> {

const CAPERROR: &str = "insufficient capacity";

impl<T> std::error::Error for CapacityError<T> {}
impl<T> core::error::Error for CapacityError<T> {}

impl<T> fmt::Display for CapacityError<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Expand Down
17 changes: 9 additions & 8 deletions crates/common/src/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ impl From<usize> for StrLen {
}

impl fmt::Debug for StrLen {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let len = self.0.load(Relaxed);
if len == usize::MAX {
f.write_str("<uncomputed>")
Expand Down Expand Up @@ -327,8 +327,8 @@ impl StrData {
}
}

impl std::fmt::Display for StrData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Display for StrData {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
self.data.fmt(f)
}
}
Expand Down Expand Up @@ -421,7 +421,7 @@ pub fn zfill(bytes: &[u8], width: usize) -> Vec<u8> {
};
let mut filled = Vec::new();
filled.extend_from_slice(sign);
filled.extend(std::iter::repeat_n(b'0', width - bytes.len()));
filled.extend(core::iter::repeat_n(b'0', width - bytes.len()));
filled.extend_from_slice(s);
filled
}
Expand Down Expand Up @@ -465,7 +465,8 @@ impl fmt::Display for UnicodeEscapeCodepoint {
}

pub mod levenshtein {
use std::{cell::RefCell, thread_local};
use core::cell::RefCell;
use std::thread_local;

pub const MOVE_COST: usize = 2;
const CASE_COST: usize = 1;
Expand Down Expand Up @@ -524,9 +525,9 @@ pub mod levenshtein {
}

if b_end < a_end {
std::mem::swap(&mut a_bytes, &mut b_bytes);
std::mem::swap(&mut a_begin, &mut b_begin);
std::mem::swap(&mut a_end, &mut b_end);
core::mem::swap(&mut a_bytes, &mut b_bytes);
core::mem::swap(&mut a_begin, &mut b_begin);
core::mem::swap(&mut a_end, &mut b_end);
}

if (b_end - a_end) * MOVE_COST > max_cost {
Expand Down
8 changes: 4 additions & 4 deletions crates/compiler-core/src/marshal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ pub enum MarshalError {
BadType,
}

impl std::fmt::Display for MarshalError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Display for MarshalError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Eof => f.write_str("unexpected end of data"),
Self::InvalidBytecode => f.write_str("invalid bytecode"),
Expand All @@ -38,9 +38,9 @@ impl From<std::str::Utf8Error> for MarshalError {
}
}

impl std::error::Error for MarshalError {}
impl core::error::Error for MarshalError {}

type Result<T, E = MarshalError> = std::result::Result<T, E>;
type Result<T, E = MarshalError> = core::result::Result<T, E>;

#[repr(u8)]
enum Type {
Expand Down
4 changes: 2 additions & 2 deletions crates/compiler-core/src/mode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ impl std::str::FromStr for Mode {
#[derive(Debug)]
pub struct ModeParseError;

impl std::fmt::Display for ModeParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Display for ModeParseError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, r#"mode must be "exec", "eval", or "single""#)
}
}
2 changes: 1 addition & 1 deletion crates/compiler/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ pub struct ParseError {
pub source_path: String,
}

impl std::fmt::Display for ParseError {
impl ::core::fmt::Display for ParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.error.fmt(f)
}
Expand Down
4 changes: 2 additions & 2 deletions crates/derive-impl/src/compile_bytecode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,11 @@ pub trait Compiler {
source: &str,
mode: Mode,
module_name: String,
) -> Result<CodeObject, Box<dyn std::error::Error>>;
) -> Result<CodeObject, Box<dyn core::error::Error>>;
}

impl CompilationSource {
fn compile_string<D: std::fmt::Display, F: FnOnce() -> D>(
fn compile_string<D: core::fmt::Display, F: FnOnce() -> D>(
&self,
source: &str,
mode: Mode,
Expand Down
8 changes: 4 additions & 4 deletions crates/derive-impl/src/from_args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ enum ParameterKind {
impl TryFrom<&Ident> for ParameterKind {
type Error = ();

fn try_from(ident: &Ident) -> std::result::Result<Self, Self::Error> {
fn try_from(ident: &Ident) -> core::result::Result<Self, Self::Error> {
Ok(match ident.to_string().as_str() {
"positional" => Self::PositionalOnly,
"any" => Self::PositionalOrKeyword,
Expand Down Expand Up @@ -105,12 +105,12 @@ impl ArgAttribute {
impl TryFrom<&Field> for ArgAttribute {
type Error = syn::Error;

fn try_from(field: &Field) -> std::result::Result<Self, Self::Error> {
fn try_from(field: &Field) -> core::result::Result<Self, Self::Error> {
let mut pyarg_attrs = field
.attrs
.iter()
.filter_map(Self::from_attribute)
.collect::<std::result::Result<Vec<_>, _>>()?;
.collect::<core::result::Result<Vec<_>, _>>()?;

if pyarg_attrs.len() >= 2 {
bail_span!(field, "Multiple pyarg attributes on field")
Expand Down Expand Up @@ -234,7 +234,7 @@ pub fn impl_from_args(input: DeriveInput) -> Result<TokenStream> {
fn from_args(
vm: &::rustpython_vm::VirtualMachine,
args: &mut ::rustpython_vm::function::FuncArgs
) -> ::std::result::Result<Self, ::rustpython_vm::function::ArgumentError> {
) -> ::core::result::Result<Self, ::rustpython_vm::function::ArgumentError> {
Ok(Self { #fields })
}
}
Expand Down
10 changes: 5 additions & 5 deletions crates/derive-impl/src/pyclass.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use proc_macro2::{Delimiter, Group, Span, TokenStream, TokenTree};
use quote::{ToTokens, quote, quote_spanned};
use rustpython_doc::DB;
use std::collections::{HashMap, HashSet};
use std::str::FromStr;
use core::str::FromStr;
use syn::{Attribute, Ident, Item, Result, parse_quote, spanned::Spanned};
use syn_ext::ext::*;
use syn_ext::types::*;
Expand All @@ -25,8 +25,8 @@ enum AttrName {
Member,
}

impl std::fmt::Display for AttrName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Display for AttrName {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let s = match self {
Self::Method => "pymethod",
Self::ClassMethod => "pyclassmethod",
Expand All @@ -44,7 +44,7 @@ impl std::fmt::Display for AttrName {
impl FromStr for AttrName {
type Err = String;

fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
fn from_str(s: &str) -> core::result::Result<Self, Self::Err> {
Ok(match s {
"pymethod" => Self::Method,
"pyclassmethod" => Self::ClassMethod,
Expand Down Expand Up @@ -1488,7 +1488,7 @@ impl ItemMeta for SlotItemMeta {

fn from_nested<I>(item_ident: Ident, meta_ident: Ident, mut nested: I) -> Result<Self>
where
I: std::iter::Iterator<Item = NestedMeta>,
I: core::iter::Iterator<Item = NestedMeta>,
{
let meta_map = if let Some(nested_meta) = nested.next() {
match nested_meta {
Expand Down
9 changes: 5 additions & 4 deletions crates/derive-impl/src/pymodule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ use crate::util::{
use proc_macro2::{Delimiter, Group, TokenStream, TokenTree};
use quote::{ToTokens, quote, quote_spanned};
use rustpython_doc::DB;
use std::{collections::HashSet, str::FromStr};
use std::{collections::HashSet};
use core::str::FromStr;
use syn::{Attribute, Ident, Item, Result, parse_quote, spanned::Spanned};
use syn_ext::ext::*;
use syn_ext::types::PunctuatedNestedMeta;
Expand All @@ -22,8 +23,8 @@ enum AttrName {
StructSequence,
}

impl std::fmt::Display for AttrName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl core::fmt::Display for AttrName {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let s = match self {
Self::Function => "pyfunction",
Self::Attr => "pyattr",
Expand All @@ -38,7 +39,7 @@ impl std::fmt::Display for AttrName {
impl FromStr for AttrName {
type Err = String;

fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
fn from_str(s: &str) -> core::result::Result<Self, Self::Err> {
Ok(match s {
"pyfunction" => Self::Function,
"pyattr" => Self::Attr,
Expand Down
2 changes: 1 addition & 1 deletion crates/derive-impl/src/pytraverse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ fn field_to_traverse_code(field: &Field) -> Result<TokenStream> {
.attrs
.iter()
.filter_map(pytraverse_arg)
.collect::<std::result::Result<Vec<_>, _>>()?;
.collect::<core::result::Result<Vec<_>, _>>()?;
let do_trace = if pytraverse_attrs.len() > 1 {
bail_span!(
field,
Expand Down
8 changes: 4 additions & 4 deletions crates/derive-impl/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ pub(crate) struct ContentItemInner<T> {
}

pub(crate) trait ContentItem {
type AttrName: std::str::FromStr + std::fmt::Display;
type AttrName: std::str::FromStr + core::fmt::Display;

fn inner(&self) -> &ContentItemInner<Self::AttrName>;
fn index(&self) -> usize {
Expand Down Expand Up @@ -125,7 +125,7 @@ impl ItemMetaInner {
allowed_names: &[&'static str],
) -> Result<Self>
where
I: std::iter::Iterator<Item = NestedMeta>,
I: core::iter::Iterator<Item = NestedMeta>,
{
let (meta_map, lits) = nested.into_unique_map_and_lits(|path| {
if let Some(ident) = path.get_ident() {
Expand Down Expand Up @@ -243,7 +243,7 @@ impl ItemMetaInner {
pub fn _optional_list(
&self,
key: &str,
) -> Result<Option<impl std::iter::Iterator<Item = &'_ NestedMeta>>> {
) -> Result<Option<impl core::iter::Iterator<Item = &'_ NestedMeta>>> {
let value = if let Some((_, meta)) = self.meta_map.get(key) {
let Meta::List(MetaList {
path: _, nested, ..
Expand All @@ -269,7 +269,7 @@ pub(crate) trait ItemMeta: Sized {

fn from_nested<I>(item_ident: Ident, meta_ident: Ident, nested: I) -> Result<Self>
where
I: std::iter::Iterator<Item = NestedMeta>,
I: core::iter::Iterator<Item = NestedMeta>,
{
Ok(Self::from_inner(ItemMetaInner::from_nested(
item_ident,
Expand Down
2 changes: 1 addition & 1 deletion crates/derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ impl derive_impl::Compiler for Compiler {
source: &str,
mode: rustpython_compiler::Mode,
module_name: String,
) -> Result<rustpython_compiler::CodeObject, Box<dyn std::error::Error>> {
) -> Result<rustpython_compiler::CodeObject, Box<dyn core::error::Error>> {
use rustpython_compiler::{CompileOpts, compile};
Ok(compile(source, mode, &module_name, CompileOpts::default())?)
}
Expand Down
Loading