diff --git a/.cargo/config.toml b/.cargo/config.toml index 31fb7bc8ca..5fef0dd0b6 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -9,9 +9,7 @@ rustflags = [ # `https://github.com/EmbarkStudios/rust-ecosystem/issues/22#issuecomment-947011395` "-Dunsafe_code", "-Wclippy::pedantic", - "-Wclippy::print_stdout", - "-Wclippy::print_stderr", - "-Wclippy::dbg_macro", + # Allowed pedantic lints "-Wclippy::char_lit_as_u8", "-Aclippy::collapsible_else_if", "-Aclippy::collapsible_if", @@ -22,5 +20,9 @@ rustflags = [ "-Aclippy::module_name_repetitions", "-Aclippy::must_use_candidate", "-Aclippy::similar_names", - "-Aclippy::too_many_lines" + "-Aclippy::too_many_lines", + # Disallowed restriction lints + "-Wclippy::print_stdout", + "-Wclippy::print_stderr", + "-Wclippy::dbg_macro", ] diff --git a/ruff_cli/src/args.rs b/ruff_cli/src/args.rs index eef8f82940..e797548a22 100644 --- a/ruff_cli/src/args.rs +++ b/ruff_cli/src/args.rs @@ -313,13 +313,13 @@ pub struct LogLevelArgs { impl From<&LogLevelArgs> for LogLevel { fn from(args: &LogLevelArgs) -> Self { if args.silent { - LogLevel::Silent + Self::Silent } else if args.quiet { - LogLevel::Quiet + Self::Quiet } else if args.verbose { - LogLevel::Verbose + Self::Verbose } else { - LogLevel::Default + Self::Default } } } diff --git a/ruff_cli/src/printer.rs b/ruff_cli/src/printer.rs index 63d8a140e9..652afa7f37 100644 --- a/ruff_cli/src/printer.rs +++ b/ruff_cli/src/printer.rs @@ -75,7 +75,7 @@ pub struct Printer<'a> { } impl<'a> Printer<'a> { - pub fn new( + pub const fn new( format: &'a SerializationFormat, log_level: &'a LogLevel, autofix: &'a fix::FixMode, diff --git a/ruff_macros/src/config.rs b/ruff_macros/src/config.rs index b23935ea99..7f52e690e1 100644 --- a/ruff_macros/src/config.rs +++ b/ruff_macros/src/config.rs @@ -176,7 +176,7 @@ impl Parse for FieldAttributes { input.parse::()?; } - Ok(FieldAttributes { + Ok(Self { default, value_type, example: textwrap::dedent(&example).trim_matches('\n').to_string(), diff --git a/ruff_macros/src/define_rule_mapping.rs b/ruff_macros/src/define_rule_mapping.rs index 1171854152..b2e70dbca9 100644 --- a/ruff_macros/src/define_rule_mapping.rs +++ b/ruff_macros/src/define_rule_mapping.rs @@ -148,6 +148,6 @@ impl Parse for Mapping { let _: Token![,] = input.parse()?; entries.push((code, path, name)); } - Ok(Mapping { entries }) + Ok(Self { entries }) } } diff --git a/src/ast/hashable.rs b/src/ast/hashable.rs index 2344ef007e..71d77e4972 100644 --- a/src/ast/hashable.rs +++ b/src/ast/hashable.rs @@ -30,11 +30,11 @@ impl<'a> From<&'a Expr> for HashableExpr<'a> { } impl<'a> HashableExpr<'a> { - pub(crate) fn from_expr(expr: &'a Expr) -> Self { + pub(crate) const fn from_expr(expr: &'a Expr) -> Self { Self(expr) } - pub(crate) fn as_expr(&self) -> &'a Expr { + pub(crate) const fn as_expr(&self) -> &'a Expr { self.0 } } diff --git a/src/ast/helpers.rs b/src/ast/helpers.rs index 0ecd8b8a52..0706af5aab 100644 --- a/src/ast/helpers.rs +++ b/src/ast/helpers.rs @@ -445,7 +445,7 @@ pub fn is_assignment_to_a_dunder(stmt: &Stmt) -> bool { /// Return `true` if the [`Expr`] is a singleton (`None`, `True`, `False`, or /// `...`). -pub fn is_singleton(expr: &Expr) -> bool { +pub const fn is_singleton(expr: &Expr) -> bool { matches!( expr.node, ExprKind::Constant { @@ -479,7 +479,7 @@ pub fn find_keyword<'a>(keywords: &'a [Keyword], keyword_name: &str) -> Option<& } /// Return `true` if an [`Expr`] is `None`. -pub fn is_const_none(expr: &Expr) -> bool { +pub const fn is_const_none(expr: &Expr) -> bool { matches!( &expr.node, ExprKind::Constant { @@ -490,7 +490,7 @@ pub fn is_const_none(expr: &Expr) -> bool { } /// Return `true` if an [`Expr`] is `True`. -pub fn is_const_true(expr: &Expr) -> bool { +pub const fn is_const_true(expr: &Expr) -> bool { matches!( &expr.node, ExprKind::Constant { @@ -753,11 +753,10 @@ pub fn binding_range(binding: &Binding, locator: &Locator) -> Range { binding.kind, BindingKind::ClassDefinition | BindingKind::FunctionDefinition ) { - if let Some(source) = &binding.source { - identifier_range(source, locator) - } else { - binding.range - } + binding + .source + .as_ref() + .map_or(binding.range, |source| identifier_range(source, locator)) } else { binding.range } @@ -959,7 +958,7 @@ pub fn followed_by_multi_statement_line(stmt: &Stmt, locator: &Locator) -> bool } /// Return `true` if a `Stmt` is a docstring. -pub fn is_docstring_stmt(stmt: &Stmt) -> bool { +pub const fn is_docstring_stmt(stmt: &Stmt) -> bool { if let StmtKind::Expr { value } = &stmt.node { matches!( value.node, diff --git a/src/ast/types.rs b/src/ast/types.rs index 8dc70e0145..1c105dd726 100644 --- a/src/ast/types.rs +++ b/src/ast/types.rs @@ -23,7 +23,7 @@ pub struct Range { } impl Range { - pub fn new(location: Location, end_location: Location) -> Self { + pub const fn new(location: Location, end_location: Location) -> Self { Self { location, end_location, @@ -179,13 +179,13 @@ impl<'a> Binding<'a> { } } - pub fn used(&self) -> bool { + pub const fn used(&self) -> bool { self.runtime_usage.is_some() || self.synthetic_usage.is_some() || self.typing_usage.is_some() } - pub fn is_definition(&self) -> bool { + pub const fn is_definition(&self) -> bool { matches!( self.kind, BindingKind::ClassDefinition diff --git a/src/checkers/ast.rs b/src/checkers/ast.rs index fb38f6de56..f922b5b3f5 100644 --- a/src/checkers/ast.rs +++ b/src/checkers/ast.rs @@ -3785,11 +3785,11 @@ impl<'a> Checker<'a> { .map(|index| &self.scopes[*index]) } - pub fn in_exception_handler(&self) -> bool { + pub const fn in_exception_handler(&self) -> bool { self.in_exception_handler } - pub fn execution_context(&self) -> ExecutionContext { + pub const fn execution_context(&self) -> ExecutionContext { if self.in_type_checking_block || self.in_annotation || self.in_deferred_string_type_definition diff --git a/src/cst/helpers.rs b/src/cst/helpers.rs index 942ee625e1..2235afeb7f 100644 --- a/src/cst/helpers.rs +++ b/src/cst/helpers.rs @@ -32,11 +32,7 @@ pub fn compose_module_path(module: &NameOrAttribute) -> String { NameOrAttribute::A(attr) => { let name = attr.attr.value; let prefix = compose_call_path(&attr.value); - if let Some(prefix) = prefix { - format!("{prefix}.{name}") - } else { - name.to_string() - } + prefix.map_or_else(|| name.to_string(), |prefix| format!("{prefix}.{name}")) } } } diff --git a/src/directives.rs b/src/directives.rs index b42add3fc8..c459c8fdac 100644 --- a/src/directives.rs +++ b/src/directives.rs @@ -22,9 +22,9 @@ impl Flags { .iter_enabled() .any(|rule_code| matches!(rule_code.lint_source(), LintSource::Imports)) { - Flags::NOQA | Flags::ISORT + Self::NOQA | Self::ISORT } else { - Flags::NOQA + Self::NOQA } } } diff --git a/src/docstrings/sections.rs b/src/docstrings/sections.rs index b4661bacb3..4954049055 100644 --- a/src/docstrings/sections.rs +++ b/src/docstrings/sections.rs @@ -84,11 +84,9 @@ pub(crate) fn section_contexts<'a>( section_name: context.section_name, previous_line: context.previous_line, line: context.line, - following_lines: if let Some(end) = end { + following_lines: end.map_or(context.following_lines, |end| { &lines[context.original_index + 1..end] - } else { - context.following_lines - }, + }), original_index: context.original_index, is_last_section: end.is_none(), }); diff --git a/src/fix.rs b/src/fix.rs index 1f4a8273a5..0900bf8687 100644 --- a/src/fix.rs +++ b/src/fix.rs @@ -12,9 +12,9 @@ pub enum FixMode { impl From for FixMode { fn from(value: bool) -> Self { if value { - FixMode::Apply + Self::Apply } else { - FixMode::None + Self::None } } } @@ -27,7 +27,7 @@ pub struct Fix { } impl Fix { - pub fn deletion(start: Location, end: Location) -> Self { + pub const fn deletion(start: Location, end: Location) -> Self { Self { content: String::new(), location: start, diff --git a/src/flake8_to_ruff/parser.rs b/src/flake8_to_ruff/parser.rs index b0ca075fe7..7086a28b33 100644 --- a/src/flake8_to_ruff/parser.rs +++ b/src/flake8_to_ruff/parser.rs @@ -72,7 +72,7 @@ struct State { } impl State { - fn new() -> Self { + const fn new() -> Self { Self { seen_sep: true, seen_colon: false, diff --git a/src/lex/docstring_detection.rs b/src/lex/docstring_detection.rs index dfb95f50d6..7c27375289 100644 --- a/src/lex/docstring_detection.rs +++ b/src/lex/docstring_detection.rs @@ -35,7 +35,7 @@ impl Default for StateMachine { } impl StateMachine { - pub fn new() -> Self { + pub const fn new() -> Self { Self { state: State::ExpectModuleDocstring, bracket_count: 0, diff --git a/src/linter.rs b/src/linter.rs index d43c865b56..88de2d3889 100644 --- a/src/linter.rs +++ b/src/linter.rs @@ -34,8 +34,8 @@ pub struct LinterResult { } impl LinterResult { - fn new(data: T, error: Option) -> Self { - LinterResult { data, error } + const fn new(data: T, error: Option) -> Self { + Self { data, error } } fn map U>(self, f: F) -> LinterResult { diff --git a/src/logging.rs b/src/logging.rs index 4d9ede5ada..6921e2efc1 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -61,7 +61,7 @@ pub enum LogLevel { impl LogLevel { #[allow(clippy::trivially_copy_pass_by_ref)] - fn level_filter(&self) -> log::LevelFilter { + const fn level_filter(&self) -> log::LevelFilter { match self { LogLevel::Default => log::LevelFilter::Info, LogLevel::Verbose => log::LevelFilter::Debug, diff --git a/src/registry.rs b/src/registry.rs index fcb3d9b57a..a235950189 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -648,7 +648,7 @@ pub trait RuleNamespace: Sized { pub struct UpstreamCategory(pub RuleCodePrefix, pub &'static str); impl Linter { - pub fn upstream_categories(&self) -> Option<&'static [UpstreamCategory]> { + pub const fn upstream_categories(&self) -> Option<&'static [UpstreamCategory]> { match self { Linter::Pycodestyle => Some(&[ UpstreamCategory(RuleCodePrefix::E, "Error"), @@ -678,7 +678,7 @@ pub enum LintSource { impl Rule { /// The source for the diagnostic (either the AST, the filesystem, or the /// physical lines). - pub fn lint_source(&self) -> &'static LintSource { + pub const fn lint_source(&self) -> &'static LintSource { match self { Rule::UnusedNOQA => &LintSource::NoQa, Rule::BlanketNOQA diff --git a/src/rules/flake8_bandit/rules/bad_file_permissions.rs b/src/rules/flake8_bandit/rules/bad_file_permissions.rs index c37b117323..989b4541f1 100644 --- a/src/rules/flake8_bandit/rules/bad_file_permissions.rs +++ b/src/rules/flake8_bandit/rules/bad_file_permissions.rs @@ -76,11 +76,7 @@ fn get_int_value(expr: &Expr) -> Option { .. } => value.to_u16(), ExprKind::Attribute { .. } => { - if let Some(path) = compose_call_path(expr) { - PYSTAT_MAPPING.get(path.as_str()).copied() - } else { - None - } + compose_call_path(expr).and_then(|path| PYSTAT_MAPPING.get(path.as_str()).copied()) } ExprKind::BinOp { left, op, right } => { if let (Some(left_value), Some(right_value)) = diff --git a/src/rules/flake8_boolean_trap/rules.rs b/src/rules/flake8_boolean_trap/rules.rs index e24cb056be..2d6b8c1938 100644 --- a/src/rules/flake8_boolean_trap/rules.rs +++ b/src/rules/flake8_boolean_trap/rules.rs @@ -69,7 +69,7 @@ fn allow_boolean_trap(func: &Expr) -> bool { false } -fn is_boolean_arg(arg: &Expr) -> bool { +const fn is_boolean_arg(arg: &Expr) -> bool { matches!( &arg.node, ExprKind::Constant { diff --git a/src/rules/flake8_commas/rules.rs b/src/rules/flake8_commas/rules.rs index 248c673d91..bd45dc7855 100644 --- a/src/rules/flake8_commas/rules.rs +++ b/src/rules/flake8_commas/rules.rs @@ -37,14 +37,14 @@ struct Token<'tok> { } impl<'tok> Token<'tok> { - fn irrelevant() -> Token<'static> { + const fn irrelevant() -> Token<'static> { Token { type_: TokenType::Irrelevant, spanned: None, } } - fn from_spanned(spanned: &'tok Spanned) -> Token<'tok> { + const fn from_spanned(spanned: &'tok Spanned) -> Token<'tok> { let type_ = match &spanned.1 { Tok::NonLogicalNewline => TokenType::NonLogicalNewline, Tok::Newline => TokenType::Newline, @@ -97,8 +97,8 @@ struct Context { } impl Context { - fn new(type_: ContextType) -> Self { - Context { + const fn new(type_: ContextType) -> Self { + Self { type_, num_commas: 0, } diff --git a/src/rules/flake8_pytest_style/rules/assertion.rs b/src/rules/flake8_pytest_style/rules/assertion.rs index f034e79050..de6ec9e171 100644 --- a/src/rules/flake8_pytest_style/rules/assertion.rs +++ b/src/rules/flake8_pytest_style/rules/assertion.rs @@ -77,7 +77,7 @@ struct ExceptionHandlerVisitor<'a> { } impl<'a> ExceptionHandlerVisitor<'a> { - fn new(exception_name: &'a str) -> Self { + const fn new(exception_name: &'a str) -> Self { Self { exception_name, current_assert: None, @@ -123,7 +123,7 @@ where /// Check if the test expression is a composite condition. /// For example, `a and b` or `not (a or b)`. The latter is equivalent /// to `not a and not b` by De Morgan's laws. -fn is_composite_condition(test: &Expr) -> bool { +const fn is_composite_condition(test: &Expr) -> bool { match &test.node { ExprKind::BoolOp { op: Boolop::And, .. diff --git a/src/rules/flake8_pytest_style/rules/raises.rs b/src/rules/flake8_pytest_style/rules/raises.rs index a7bb907afd..fc14e3d7f5 100644 --- a/src/rules/flake8_pytest_style/rules/raises.rs +++ b/src/rules/flake8_pytest_style/rules/raises.rs @@ -51,7 +51,7 @@ fn is_pytest_raises(checker: &Checker, func: &Expr) -> bool { }) } -fn is_non_trivial_with_body(body: &[Stmt]) -> bool { +const fn is_non_trivial_with_body(body: &[Stmt]) -> bool { if body.len() > 1 { true } else if let Some(first_body_stmt) = body.first() { diff --git a/src/rules/flake8_quotes/rules.rs b/src/rules/flake8_quotes/rules.rs index a05c0802be..6849c250ab 100644 --- a/src/rules/flake8_quotes/rules.rs +++ b/src/rules/flake8_quotes/rules.rs @@ -98,35 +98,35 @@ impl AlwaysAutofixableViolation for AvoidQuoteEscape { } } -fn good_single(quote: &Quote) -> char { +const fn good_single(quote: &Quote) -> char { match quote { Quote::Single => '\'', Quote::Double => '"', } } -fn bad_single(quote: &Quote) -> char { +const fn bad_single(quote: &Quote) -> char { match quote { Quote::Double => '\'', Quote::Single => '"', } } -fn good_multiline(quote: &Quote) -> &str { +const fn good_multiline(quote: &Quote) -> &str { match quote { Quote::Single => "'''", Quote::Double => "\"\"\"", } } -fn good_multiline_ending(quote: &Quote) -> &str { +const fn good_multiline_ending(quote: &Quote) -> &str { match quote { Quote::Single => "'\"\"\"", Quote::Double => "\"'''", } } -fn good_docstring(quote: &Quote) -> &str { +const fn good_docstring(quote: &Quote) -> &str { match quote { Quote::Single => "'", Quote::Double => "\"", diff --git a/src/rules/flake8_type_checking/helpers.rs b/src/rules/flake8_type_checking/helpers.rs index 9b5041d252..c75eea0127 100644 --- a/src/rules/flake8_type_checking/helpers.rs +++ b/src/rules/flake8_type_checking/helpers.rs @@ -38,7 +38,7 @@ pub fn is_type_checking_block(checker: &Checker, test: &Expr) -> bool { false } -pub fn is_valid_runtime_import(binding: &Binding) -> bool { +pub const fn is_valid_runtime_import(binding: &Binding) -> bool { if matches!( binding.kind, BindingKind::Importation(..) diff --git a/src/rules/flake8_unused_arguments/types.rs b/src/rules/flake8_unused_arguments/types.rs index b5acdb624e..60dc02f4ef 100644 --- a/src/rules/flake8_unused_arguments/types.rs +++ b/src/rules/flake8_unused_arguments/types.rs @@ -13,21 +13,21 @@ pub enum Argumentable { impl Argumentable { pub fn check_for(&self, name: String) -> DiagnosticKind { match self { - Argumentable::Function => rules::UnusedFunctionArgument { name }.into(), - Argumentable::Method => rules::UnusedMethodArgument { name }.into(), - Argumentable::ClassMethod => rules::UnusedClassMethodArgument { name }.into(), - Argumentable::StaticMethod => rules::UnusedStaticMethodArgument { name }.into(), - Argumentable::Lambda => rules::UnusedLambdaArgument { name }.into(), + Self::Function => rules::UnusedFunctionArgument { name }.into(), + Self::Method => rules::UnusedMethodArgument { name }.into(), + Self::ClassMethod => rules::UnusedClassMethodArgument { name }.into(), + Self::StaticMethod => rules::UnusedStaticMethodArgument { name }.into(), + Self::Lambda => rules::UnusedLambdaArgument { name }.into(), } } - pub fn rule_code(&self) -> &Rule { + pub const fn rule_code(&self) -> &Rule { match self { - Argumentable::Function => &Rule::UnusedFunctionArgument, - Argumentable::Method => &Rule::UnusedMethodArgument, - Argumentable::ClassMethod => &Rule::UnusedClassMethodArgument, - Argumentable::StaticMethod => &Rule::UnusedStaticMethodArgument, - Argumentable::Lambda => &Rule::UnusedLambdaArgument, + Self::Function => &Rule::UnusedFunctionArgument, + Self::Method => &Rule::UnusedMethodArgument, + Self::ClassMethod => &Rule::UnusedClassMethodArgument, + Self::StaticMethod => &Rule::UnusedStaticMethodArgument, + Self::Lambda => &Rule::UnusedLambdaArgument, } } } diff --git a/src/rules/pandas_vet/helpers.rs b/src/rules/pandas_vet/helpers.rs index ea3d6ee630..cde99d802a 100644 --- a/src/rules/pandas_vet/helpers.rs +++ b/src/rules/pandas_vet/helpers.rs @@ -2,7 +2,7 @@ use rustpython_ast::{Expr, ExprKind}; /// Return `true` if an `Expr` _could_ be a `DataFrame`. This rules out /// obviously-wrong cases, like constants and literals. -pub fn is_dataframe_candidate(expr: &Expr) -> bool { +pub const fn is_dataframe_candidate(expr: &Expr) -> bool { !matches!( expr.node, ExprKind::Constant { .. } diff --git a/src/rules/pydocstyle/settings.rs b/src/rules/pydocstyle/settings.rs index 1cfa4ae9cd..ea944bf71d 100644 --- a/src/rules/pydocstyle/settings.rs +++ b/src/rules/pydocstyle/settings.rs @@ -18,7 +18,7 @@ pub enum Convention { } impl Convention { - pub fn rules_to_be_ignored(self) -> &'static [Rule] { + pub const fn rules_to_be_ignored(self) -> &'static [Rule] { match self { Convention::Google => &[ Rule::OneBlankLineBeforeClass, diff --git a/src/rules/pyupgrade/rules/import_replacements.rs b/src/rules/pyupgrade/rules/import_replacements.rs index dfcfe1674b..96d758272e 100644 --- a/src/rules/pyupgrade/rules/import_replacements.rs +++ b/src/rules/pyupgrade/rules/import_replacements.rs @@ -225,7 +225,7 @@ struct ImportReplacer<'a> { } impl<'a> ImportReplacer<'a> { - fn new( + const fn new( stmt: &'a Stmt, module: &'a str, members: &'a [AliasData], diff --git a/src/rules/pyupgrade/rules/outdated_version_block.rs b/src/rules/pyupgrade/rules/outdated_version_block.rs index b2153aa837..3fc9541e17 100644 --- a/src/rules/pyupgrade/rules/outdated_version_block.rs +++ b/src/rules/pyupgrade/rules/outdated_version_block.rs @@ -46,7 +46,7 @@ struct BlockMetadata { } impl BlockMetadata { - fn new(starter: Tok, elif: Option, else_: Option) -> Self { + const fn new(starter: Tok, elif: Option, else_: Option) -> Self { Self { starter, elif, diff --git a/src/rules/pyupgrade/rules/redundant_open_modes.rs b/src/rules/pyupgrade/rules/redundant_open_modes.rs index 60493af16f..a1ffe8eac8 100644 --- a/src/rules/pyupgrade/rules/redundant_open_modes.rs +++ b/src/rules/pyupgrade/rules/redundant_open_modes.rs @@ -63,13 +63,13 @@ impl FromStr for OpenMode { fn from_str(string: &str) -> Result { match string { - "U" => Ok(OpenMode::U), - "Ur" => Ok(OpenMode::Ur), - "Ub" => Ok(OpenMode::Ub), - "rUb" => Ok(OpenMode::RUb), - "r" => Ok(OpenMode::R), - "rt" => Ok(OpenMode::Rt), - "wt" => Ok(OpenMode::Wt), + "U" => Ok(Self::U), + "Ur" => Ok(Self::Ur), + "Ub" => Ok(Self::Ub), + "rUb" => Ok(Self::RUb), + "r" => Ok(Self::R), + "rt" => Ok(Self::Rt), + "wt" => Ok(Self::Wt), _ => Err(anyhow!("Unknown open mode: {}", string)), } } @@ -78,13 +78,13 @@ impl FromStr for OpenMode { impl OpenMode { fn replacement_value(&self) -> Option { match *self { - OpenMode::U => None, - OpenMode::Ur => None, - OpenMode::Ub => Some(String::from("\"rb\"")), - OpenMode::RUb => Some(String::from("\"rb\"")), - OpenMode::R => None, - OpenMode::Rt => None, - OpenMode::Wt => Some(String::from("\"w\"")), + Self::U => None, + Self::Ur => None, + Self::Ub => Some(String::from("\"rb\"")), + Self::RUb => Some(String::from("\"rb\"")), + Self::R => None, + Self::Rt => None, + Self::Wt => Some(String::from("\"w\"")), } } } diff --git a/src/rules/pyupgrade/types.rs b/src/rules/pyupgrade/types.rs index 66b908128c..73ebcd30c6 100644 --- a/src/rules/pyupgrade/types.rs +++ b/src/rules/pyupgrade/types.rs @@ -12,26 +12,26 @@ pub enum Primitive { } impl Primitive { - pub fn from_constant(constant: &Constant) -> Option { + pub const fn from_constant(constant: &Constant) -> Option { match constant { - Constant::Bool(_) => Some(Primitive::Bool), - Constant::Str(_) => Some(Primitive::Str), - Constant::Bytes(_) => Some(Primitive::Bytes), - Constant::Int(_) => Some(Primitive::Int), - Constant::Float(_) => Some(Primitive::Float), - Constant::Complex { .. } => Some(Primitive::Complex), + Constant::Bool(_) => Some(Self::Bool), + Constant::Str(_) => Some(Self::Str), + Constant::Bytes(_) => Some(Self::Bytes), + Constant::Int(_) => Some(Self::Int), + Constant::Float(_) => Some(Self::Float), + Constant::Complex { .. } => Some(Self::Complex), _ => None, } } pub fn builtin(self) -> String { match self { - Primitive::Bool => "bool".to_string(), - Primitive::Str => "str".to_string(), - Primitive::Bytes => "bytes".to_string(), - Primitive::Int => "int".to_string(), - Primitive::Float => "float".to_string(), - Primitive::Complex => "complex".to_string(), + Self::Bool => "bool".to_string(), + Self::Str => "str".to_string(), + Self::Bytes => "bytes".to_string(), + Self::Int => "int".to_string(), + Self::Float => "float".to_string(), + Self::Complex => "complex".to_string(), } } } diff --git a/src/rules/tryceratops/rules/prefer_type_error.rs b/src/rules/tryceratops/rules/prefer_type_error.rs index 273e8ff29d..bcf1ceb88b 100644 --- a/src/rules/tryceratops/rules/prefer_type_error.rs +++ b/src/rules/tryceratops/rules/prefer_type_error.rs @@ -91,7 +91,7 @@ fn check_type_check_test(checker: &mut Checker, test: &Expr) -> bool { } /// Returns the [`Expr`] representing the name of the exception. -fn match_name(exc: &Expr) -> Option<&Expr> { +const fn match_name(exc: &Expr) -> Option<&Expr> { match &exc.node { ExprKind::Name { .. } => Some(exc), ExprKind::Call { func, .. } => { diff --git a/src/settings/configuration.rs b/src/settings/configuration.rs index 06d9d273f3..cf82b1be4b 100644 --- a/src/settings/configuration.rs +++ b/src/settings/configuration.rs @@ -86,7 +86,7 @@ pub struct Configuration { impl Configuration { pub fn from_options(options: Options, project_root: &Path) -> Result { - Ok(Configuration { + Ok(Self { rule_selections: vec![RuleSelection { select: options.select, ignore: options @@ -197,7 +197,7 @@ impl Configuration { } #[must_use] - pub fn combine(self, config: Configuration) -> Self { + pub fn combine(self, config: Self) -> Self { Self { rule_selections: config .rule_selections diff --git a/src/settings/flags.rs b/src/settings/flags.rs index cfb47464d0..e6c6a604bc 100644 --- a/src/settings/flags.rs +++ b/src/settings/flags.rs @@ -9,9 +9,9 @@ pub enum Autofix { impl From for Autofix { fn from(value: bool) -> Self { if value { - Autofix::Enabled + Self::Enabled } else { - Autofix::Disabled + Self::Disabled } } } @@ -19,8 +19,8 @@ impl From for Autofix { impl From for Autofix { fn from(value: fix::FixMode) -> Self { match value { - fix::FixMode::Generate | fix::FixMode::Diff | fix::FixMode::Apply => Autofix::Enabled, - fix::FixMode::None => Autofix::Disabled, + fix::FixMode::Generate | fix::FixMode::Diff | fix::FixMode::Apply => Self::Enabled, + fix::FixMode::None => Self::Disabled, } } } @@ -34,9 +34,9 @@ pub enum Noqa { impl From for Noqa { fn from(value: bool) -> Self { if value { - Noqa::Enabled + Self::Enabled } else { - Noqa::Disabled + Self::Disabled } } } @@ -50,9 +50,9 @@ pub enum Cache { impl From for Cache { fn from(value: bool) -> Self { if value { - Cache::Enabled + Self::Enabled } else { - Cache::Disabled + Self::Disabled } } } diff --git a/src/settings/mod.rs b/src/settings/mod.rs index ff900ec574..646a3c2970 100644 --- a/src/settings/mod.rs +++ b/src/settings/mod.rs @@ -225,7 +225,7 @@ impl Settings { pub fn for_rule(rule_code: Rule) -> Self { Self { rules: [rule_code].into(), - ..Settings::default() + ..Self::default() } } @@ -233,7 +233,7 @@ impl Settings { pub fn for_rules(rules: impl IntoIterator) -> Self { Self { rules: rules.into(), - ..Settings::default() + ..Self::default() } } } @@ -361,7 +361,7 @@ impl From<&Configuration> for RuleTable { crate::warn_user!("`{from}` has been remapped to `{}`.", target.as_ref()); } - let mut rules = RuleTable::empty(); + let mut rules = Self::empty(); for rule in select_set { let fix = fixable_set.contains(&rule); diff --git a/src/settings/pyproject.rs b/src/settings/pyproject.rs index 3cc649414c..fdd0884221 100644 --- a/src/settings/pyproject.rs +++ b/src/settings/pyproject.rs @@ -19,7 +19,7 @@ pub struct Pyproject { } impl Pyproject { - pub fn new(options: Options) -> Self { + pub const fn new(options: Options) -> Self { Self { tool: Some(Tools { ruff: Some(options), diff --git a/src/settings/types.rs b/src/settings/types.rs index 324adf3450..59755e12f8 100644 --- a/src/settings/types.rs +++ b/src/settings/types.rs @@ -37,26 +37,26 @@ impl FromStr for PythonVersion { "Specified a version below the minimum supported Python version. Defaulting \ to Python 3.7." ); - Ok(PythonVersion::Py37) + Ok(Self::Py37) } - "py37" => Ok(PythonVersion::Py37), - "py38" => Ok(PythonVersion::Py38), - "py39" => Ok(PythonVersion::Py39), - "py310" => Ok(PythonVersion::Py310), - "py311" => Ok(PythonVersion::Py311), + "py37" => Ok(Self::Py37), + "py38" => Ok(Self::Py38), + "py39" => Ok(Self::Py39), + "py310" => Ok(Self::Py310), + "py311" => Ok(Self::Py311), _ => Err(anyhow!("Unknown version: {string} (try: \"py37\")")), } } } impl PythonVersion { - pub fn as_tuple(&self) -> (u32, u32) { + pub const fn as_tuple(&self) -> (u32, u32) { match self { - PythonVersion::Py37 => (3, 7), - PythonVersion::Py38 => (3, 8), - PythonVersion::Py39 => (3, 9), - PythonVersion::Py310 => (3, 10), - PythonVersion::Py311 => (3, 11), + Self::Py37 => (3, 7), + Self::Py38 => (3, 8), + Self::Py39 => (3, 9), + Self::Py310 => (3, 10), + Self::Py311 => (3, 11), } } } diff --git a/src/source_code/generator.rs b/src/source_code/generator.rs index 0502978812..d92bb4f72b 100644 --- a/src/source_code/generator.rs +++ b/src/source_code/generator.rs @@ -57,8 +57,12 @@ impl<'a> From<&'a Stylist<'a>> for Generator<'a> { } impl<'a> Generator<'a> { - pub fn new(indent: &'a Indentation, quote: &'a Quote, line_ending: &'a LineEnding) -> Self { - Generator { + pub const fn new( + indent: &'a Indentation, + quote: &'a Quote, + line_ending: &'a LineEnding, + ) -> Self { + Self { // Style preferences. indent, quote, diff --git a/src/source_code/locator.rs b/src/source_code/locator.rs index 575b13fa31..cfa430eae6 100644 --- a/src/source_code/locator.rs +++ b/src/source_code/locator.rs @@ -93,8 +93,8 @@ fn truncate(location: Location, index: &Index, contents: &str) -> usize { } impl<'a> Locator<'a> { - pub fn new(contents: &'a str) -> Self { - Locator { + pub const fn new(contents: &'a str) -> Self { + Self { contents, index: OnceCell::new(), } @@ -140,11 +140,11 @@ impl<'a> Locator<'a> { ) } - pub fn len(&self) -> usize { + pub const fn len(&self) -> usize { self.contents.len() } - pub fn is_empty(&self) -> bool { + pub const fn is_empty(&self) -> bool { self.contents.is_empty() } } diff --git a/src/source_code/stylist.rs b/src/source_code/stylist.rs index cd30473d19..bdaac5c162 100644 --- a/src/source_code/stylist.rs +++ b/src/source_code/stylist.rs @@ -97,7 +97,7 @@ impl From<&Quote> for char { pub struct Indentation(String); impl Indentation { - pub fn new(indentation: String) -> Self { + pub const fn new(indentation: String) -> Self { Self(indentation) } } @@ -142,7 +142,7 @@ impl Default for LineEnding { } impl LineEnding { - pub fn as_str(&self) -> &'static str { + pub const fn as_str(&self) -> &'static str { match self { LineEnding::CrLf => "\r\n", LineEnding::Lf => "\n", diff --git a/src/vendor/str.rs b/src/vendor/str.rs index fa6c9eed7f..42920dda22 100644 --- a/src/vendor/str.rs +++ b/src/vendor/str.rs @@ -154,7 +154,7 @@ impl fmt::Display for Repr<'_> { /// Returns the outer quotes to use and the number of quotes that need to be /// escaped. -pub(crate) fn choose_quotes_for_repr( +pub(crate) const fn choose_quotes_for_repr( num_squotes: usize, num_dquotes: usize, quote: Quote,