diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8d3054d978..86150fba6b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -104,7 +104,7 @@ At a high level, the steps involved in adding a new lint rule are as follows: 1. Determine a name for the new rule as per our [rule naming convention](#rule-naming-convention). 1. Create a file for your rule (e.g., `crates/ruff/src/rules/flake8_bugbear/rules/abstract_base_class.rs`). -1. In that file, define a violation struct. You can grep for `define_violation!` to see examples. +1. In that file, define a violation struct. You can grep for `#[violation]` to see examples. 1. Map the violation struct to a rule code in `crates/ruff/src/registry.rs` (e.g., `E402`). 1. Define the logic for triggering the violation in `crates/ruff/src/checkers/ast.rs` (for AST-based checks), `crates/ruff/src/checkers/tokens.rs` (for token-based checks), `crates/ruff/src/checkers/lines.rs` @@ -115,7 +115,7 @@ At a high level, the steps involved in adding a new lint rule are as follows: To define the violation, start by creating a dedicated file for your rule under the appropriate rule linter (e.g., `crates/ruff/src/rules/flake8_bugbear/rules/abstract_base_class.rs`). That file should -contain a struct defined via `define_violation!`, along with a function that creates the violation +contain a struct defined via `#[violation]`, along with a function that creates the violation based on any required inputs. (Many of the existing examples live in `crates/ruff/src/violations.rs`, but we're looking to place new rules in their own files.) diff --git a/crates/ruff/src/rules/eradicate/rules.rs b/crates/ruff/src/rules/eradicate/rules.rs index 66524c4912..bcebc67ce1 100644 --- a/crates/ruff/src/rules/eradicate/rules.rs +++ b/crates/ruff/src/rules/eradicate/rules.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Location; use super::detection::comment_contains_code; @@ -9,20 +9,20 @@ use crate::settings::{flags, Settings}; use crate::source_code::Locator; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - /// ## What it does - /// Checks for commented-out Python code. - /// - /// ## Why is this bad? - /// Commented-out code is dead code, and is often included inadvertently. - /// It should be removed. - /// - /// ## Example - /// ```python - /// # print('foo') - /// ``` - pub struct CommentedOutCode; -); +/// ## What it does +/// Checks for commented-out Python code. +/// +/// ## Why is this bad? +/// Commented-out code is dead code, and is often included inadvertently. +/// It should be removed. +/// +/// ## Example +/// ```python +/// # print('foo') +/// ``` +#[violation] +pub struct CommentedOutCode; + impl AlwaysAutofixableViolation for CommentedOutCode { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_2020/rules.rs b/crates/ruff/src/rules/flake8_2020/rules.rs index 6d1963e189..c976fb81aa 100644 --- a/crates/ruff/src/rules/flake8_2020/rules.rs +++ b/crates/ruff/src/rules/flake8_2020/rules.rs @@ -1,5 +1,5 @@ use num_bigint::BigInt; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Cmpop, Constant, Expr, ExprKind, Located}; use crate::ast::types::Range; @@ -7,9 +7,9 @@ use crate::checkers::ast::Checker; use crate::registry::{Diagnostic, Rule}; use crate::violation::Violation; -define_violation!( - pub struct SysVersionSlice3Referenced; -); +#[violation] +pub struct SysVersionSlice3Referenced; + impl Violation for SysVersionSlice3Referenced { #[derive_message_formats] fn message(&self) -> String { @@ -17,9 +17,9 @@ impl Violation for SysVersionSlice3Referenced { } } -define_violation!( - pub struct SysVersion2Referenced; -); +#[violation] +pub struct SysVersion2Referenced; + impl Violation for SysVersion2Referenced { #[derive_message_formats] fn message(&self) -> String { @@ -27,9 +27,9 @@ impl Violation for SysVersion2Referenced { } } -define_violation!( - pub struct SysVersionCmpStr3; -); +#[violation] +pub struct SysVersionCmpStr3; + impl Violation for SysVersionCmpStr3 { #[derive_message_formats] fn message(&self) -> String { @@ -37,9 +37,9 @@ impl Violation for SysVersionCmpStr3 { } } -define_violation!( - pub struct SysVersionInfo0Eq3Referenced; -); +#[violation] +pub struct SysVersionInfo0Eq3Referenced; + impl Violation for SysVersionInfo0Eq3Referenced { #[derive_message_formats] fn message(&self) -> String { @@ -47,9 +47,9 @@ impl Violation for SysVersionInfo0Eq3Referenced { } } -define_violation!( - pub struct SixPY3Referenced; -); +#[violation] +pub struct SixPY3Referenced; + impl Violation for SixPY3Referenced { #[derive_message_formats] fn message(&self) -> String { @@ -57,9 +57,9 @@ impl Violation for SixPY3Referenced { } } -define_violation!( - pub struct SysVersionInfo1CmpInt; -); +#[violation] +pub struct SysVersionInfo1CmpInt; + impl Violation for SysVersionInfo1CmpInt { #[derive_message_formats] fn message(&self) -> String { @@ -70,9 +70,9 @@ impl Violation for SysVersionInfo1CmpInt { } } -define_violation!( - pub struct SysVersionInfoMinorCmpInt; -); +#[violation] +pub struct SysVersionInfoMinorCmpInt; + impl Violation for SysVersionInfoMinorCmpInt { #[derive_message_formats] fn message(&self) -> String { @@ -83,9 +83,9 @@ impl Violation for SysVersionInfoMinorCmpInt { } } -define_violation!( - pub struct SysVersion0Referenced; -); +#[violation] +pub struct SysVersion0Referenced; + impl Violation for SysVersion0Referenced { #[derive_message_formats] fn message(&self) -> String { @@ -93,9 +93,9 @@ impl Violation for SysVersion0Referenced { } } -define_violation!( - pub struct SysVersionCmpStr10; -); +#[violation] +pub struct SysVersionCmpStr10; + impl Violation for SysVersionCmpStr10 { #[derive_message_formats] fn message(&self) -> String { @@ -103,9 +103,9 @@ impl Violation for SysVersionCmpStr10 { } } -define_violation!( - pub struct SysVersionSlice1Referenced; -); +#[violation] +pub struct SysVersionSlice1Referenced; + impl Violation for SysVersionSlice1Referenced { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_annotations/rules.rs b/crates/ruff/src/rules/flake8_annotations/rules.rs index 16043d3c5e..f15b7d19d7 100644 --- a/crates/ruff/src/rules/flake8_annotations/rules.rs +++ b/crates/ruff/src/rules/flake8_annotations/rules.rs @@ -1,5 +1,5 @@ use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprKind, Stmt}; use super::fixes; @@ -15,30 +15,30 @@ use crate::violation::{AlwaysAutofixableViolation, Violation}; use crate::visibility; use crate::visibility::Visibility; -define_violation!( - /// ## What it does - /// Checks that function arguments have type annotations. - /// - /// ## Why is this bad? - /// Type annotations are a good way to document the types of function arguments. They also - /// help catch bugs, when used alongside a type checker, by ensuring that the types of - /// any provided arguments match expectation. - /// - /// ## Example - /// ```python - /// def foo(x): - /// ... - /// ``` - /// - /// Use instead: - /// ```python - /// def foo(x: int): - /// ... - /// ``` - pub struct MissingTypeFunctionArgument { - pub name: String, - } -); +/// ## What it does +/// Checks that function arguments have type annotations. +/// +/// ## Why is this bad? +/// Type annotations are a good way to document the types of function arguments. They also +/// help catch bugs, when used alongside a type checker, by ensuring that the types of +/// any provided arguments match expectation. +/// +/// ## Example +/// ```python +/// def foo(x): +/// ... +/// ``` +/// +/// Use instead: +/// ```python +/// def foo(x: int): +/// ... +/// ``` +#[violation] +pub struct MissingTypeFunctionArgument { + pub name: String, +} + impl Violation for MissingTypeFunctionArgument { #[derive_message_formats] fn message(&self) -> String { @@ -47,30 +47,30 @@ impl Violation for MissingTypeFunctionArgument { } } -define_violation!( - /// ## What it does - /// Checks that function `*args` arguments have type annotations. - /// - /// ## Why is this bad? - /// Type annotations are a good way to document the types of function arguments. They also - /// help catch bugs, when used alongside a type checker, by ensuring that the types of - /// any provided arguments match expectation. - /// - /// ## Example - /// ```python - /// def foo(*args): - /// ... - /// ``` - /// - /// Use instead: - /// ```python - /// def foo(*args: int): - /// ... - /// ``` - pub struct MissingTypeArgs { - pub name: String, - } -); +/// ## What it does +/// Checks that function `*args` arguments have type annotations. +/// +/// ## Why is this bad? +/// Type annotations are a good way to document the types of function arguments. They also +/// help catch bugs, when used alongside a type checker, by ensuring that the types of +/// any provided arguments match expectation. +/// +/// ## Example +/// ```python +/// def foo(*args): +/// ... +/// ``` +/// +/// Use instead: +/// ```python +/// def foo(*args: int): +/// ... +/// ``` +#[violation] +pub struct MissingTypeArgs { + pub name: String, +} + impl Violation for MissingTypeArgs { #[derive_message_formats] fn message(&self) -> String { @@ -79,30 +79,30 @@ impl Violation for MissingTypeArgs { } } -define_violation!( - /// ## What it does - /// Checks that function `**kwargs` arguments have type annotations. - /// - /// ## Why is this bad? - /// Type annotations are a good way to document the types of function arguments. They also - /// help catch bugs, when used alongside a type checker, by ensuring that the types of - /// any provided arguments match expectation. - /// - /// ## Example - /// ```python - /// def foo(**kwargs): - /// ... - /// ``` - /// - /// Use instead: - /// ```python - /// def foo(**kwargs: int): - /// ... - /// ``` - pub struct MissingTypeKwargs { - pub name: String, - } -); +/// ## What it does +/// Checks that function `**kwargs` arguments have type annotations. +/// +/// ## Why is this bad? +/// Type annotations are a good way to document the types of function arguments. They also +/// help catch bugs, when used alongside a type checker, by ensuring that the types of +/// any provided arguments match expectation. +/// +/// ## Example +/// ```python +/// def foo(**kwargs): +/// ... +/// ``` +/// +/// Use instead: +/// ```python +/// def foo(**kwargs: int): +/// ... +/// ``` +#[violation] +pub struct MissingTypeKwargs { + pub name: String, +} + impl Violation for MissingTypeKwargs { #[derive_message_formats] fn message(&self) -> String { @@ -111,35 +111,35 @@ impl Violation for MissingTypeKwargs { } } -define_violation!( - /// ## What it does - /// Checks that instance method `self` arguments have type annotations. - /// - /// ## Why is this bad? - /// Type annotations are a good way to document the types of function arguments. They also - /// help catch bugs, when used alongside a type checker, by ensuring that the types of - /// any provided arguments match expectation. - /// - /// Note that many type checkers will infer the type of `self` automatically, so this - /// annotation is not strictly necessary. - /// - /// ## Example - /// ```python - /// class Foo: - /// def bar(self): - /// ... - /// ``` - /// - /// Use instead: - /// ```python - /// class Foo: - /// def bar(self: "Foo"): - /// ... - /// ``` - pub struct MissingTypeSelf { - pub name: String, - } -); +/// ## What it does +/// Checks that instance method `self` arguments have type annotations. +/// +/// ## Why is this bad? +/// Type annotations are a good way to document the types of function arguments. They also +/// help catch bugs, when used alongside a type checker, by ensuring that the types of +/// any provided arguments match expectation. +/// +/// Note that many type checkers will infer the type of `self` automatically, so this +/// annotation is not strictly necessary. +/// +/// ## Example +/// ```python +/// class Foo: +/// def bar(self): +/// ... +/// ``` +/// +/// Use instead: +/// ```python +/// class Foo: +/// def bar(self: "Foo"): +/// ... +/// ``` +#[violation] +pub struct MissingTypeSelf { + pub name: String, +} + impl Violation for MissingTypeSelf { #[derive_message_formats] fn message(&self) -> String { @@ -148,37 +148,37 @@ impl Violation for MissingTypeSelf { } } -define_violation!( - /// ## What it does - /// Checks that class method `cls` arguments have type annotations. - /// - /// ## Why is this bad? - /// Type annotations are a good way to document the types of function arguments. They also - /// help catch bugs, when used alongside a type checker, by ensuring that the types of - /// any provided arguments match expectation. - /// - /// Note that many type checkers will infer the type of `cls` automatically, so this - /// annotation is not strictly necessary. - /// - /// ## Example - /// ```python - /// class Foo: - /// @classmethod - /// def bar(cls): - /// ... - /// ``` - /// - /// Use instead: - /// ```python - /// class Foo: - /// @classmethod - /// def bar(cls: Type["Foo"]): - /// ... - /// ``` - pub struct MissingTypeCls { - pub name: String, - } -); +/// ## What it does +/// Checks that class method `cls` arguments have type annotations. +/// +/// ## Why is this bad? +/// Type annotations are a good way to document the types of function arguments. They also +/// help catch bugs, when used alongside a type checker, by ensuring that the types of +/// any provided arguments match expectation. +/// +/// Note that many type checkers will infer the type of `cls` automatically, so this +/// annotation is not strictly necessary. +/// +/// ## Example +/// ```python +/// class Foo: +/// @classmethod +/// def bar(cls): +/// ... +/// ``` +/// +/// Use instead: +/// ```python +/// class Foo: +/// @classmethod +/// def bar(cls: Type["Foo"]): +/// ... +/// ``` +#[violation] +pub struct MissingTypeCls { + pub name: String, +} + impl Violation for MissingTypeCls { #[derive_message_formats] fn message(&self) -> String { @@ -187,30 +187,30 @@ impl Violation for MissingTypeCls { } } -define_violation!( - /// ## What it does - /// Checks that public functions and methods have return type annotations. - /// - /// ## Why is this bad? - /// Type annotations are a good way to document the return types of functions. They also - /// help catch bugs, when used alongside a type checker, by ensuring that the types of - /// any returned values, and the types expected by callers, match expectation. - /// - /// ## Example - /// ```python - /// def add(a, b): - /// return a + b - /// ``` - /// - /// Use instead: - /// ```python - /// def add(a: int, b: int) -> int: - /// return a + b - /// ``` - pub struct MissingReturnTypePublicFunction { - pub name: String, - } -); +/// ## What it does +/// Checks that public functions and methods have return type annotations. +/// +/// ## Why is this bad? +/// Type annotations are a good way to document the return types of functions. They also +/// help catch bugs, when used alongside a type checker, by ensuring that the types of +/// any returned values, and the types expected by callers, match expectation. +/// +/// ## Example +/// ```python +/// def add(a, b): +/// return a + b +/// ``` +/// +/// Use instead: +/// ```python +/// def add(a: int, b: int) -> int: +/// return a + b +/// ``` +#[violation] +pub struct MissingReturnTypePublicFunction { + pub name: String, +} + impl Violation for MissingReturnTypePublicFunction { #[derive_message_formats] fn message(&self) -> String { @@ -219,30 +219,30 @@ impl Violation for MissingReturnTypePublicFunction { } } -define_violation!( - /// ## What it does - /// Checks that private functions and methods have return type annotations. - /// - /// ## Why is this bad? - /// Type annotations are a good way to document the return types of functions. They also - /// help catch bugs, when used alongside a type checker, by ensuring that the types of - /// any returned values, and the types expected by callers, match expectation. - /// - /// ## Example - /// ```python - /// def _add(a, b): - /// return a + b - /// ``` - /// - /// Use instead: - /// ```python - /// def _add(a: int, b: int) -> int: - /// return a + b - /// ``` - pub struct MissingReturnTypePrivateFunction { - pub name: String, - } -); +/// ## What it does +/// Checks that private functions and methods have return type annotations. +/// +/// ## Why is this bad? +/// Type annotations are a good way to document the return types of functions. They also +/// help catch bugs, when used alongside a type checker, by ensuring that the types of +/// any returned values, and the types expected by callers, match expectation. +/// +/// ## Example +/// ```python +/// def _add(a, b): +/// return a + b +/// ``` +/// +/// Use instead: +/// ```python +/// def _add(a: int, b: int) -> int: +/// return a + b +/// ``` +#[violation] +pub struct MissingReturnTypePrivateFunction { + pub name: String, +} + impl Violation for MissingReturnTypePrivateFunction { #[derive_message_formats] fn message(&self) -> String { @@ -251,43 +251,43 @@ impl Violation for MissingReturnTypePrivateFunction { } } -define_violation!( - /// ## What it does - /// Checks that "special" methods, like `__init__`, `__new__`, and `__call__`, have - /// return type annotations. - /// - /// ## Why is this bad? - /// Type annotations are a good way to document the return types of functions. They also - /// help catch bugs, when used alongside a type checker, by ensuring that the types of - /// any returned values, and the types expected by callers, match expectation. - /// - /// Note that type checkers often allow you to omit the return type annotation for - /// `__init__` methods, as long as at least one argument has a type annotation. To - /// opt-in to this behavior, use the `mypy-init-return` setting in your `pyproject.toml` - /// or `ruff.toml` file: - /// - /// ```toml - /// [tool.ruff.flake8-annotations] - /// mypy-init-return = true - /// ``` - /// - /// ## Example - /// ```python - /// class Foo: - /// def __init__(self, x: int): - /// self.x = x - /// ``` - /// - /// Use instead: - /// ```python - /// class Foo: - /// def __init__(self, x: int) -> None: - /// self.x = x - /// ``` - pub struct MissingReturnTypeSpecialMethod { - pub name: String, - } -); +/// ## What it does +/// Checks that "special" methods, like `__init__`, `__new__`, and `__call__`, have +/// return type annotations. +/// +/// ## Why is this bad? +/// Type annotations are a good way to document the return types of functions. They also +/// help catch bugs, when used alongside a type checker, by ensuring that the types of +/// any returned values, and the types expected by callers, match expectation. +/// +/// Note that type checkers often allow you to omit the return type annotation for +/// `__init__` methods, as long as at least one argument has a type annotation. To +/// opt-in to this behavior, use the `mypy-init-return` setting in your `pyproject.toml` +/// or `ruff.toml` file: +/// +/// ```toml +/// [tool.ruff.flake8-annotations] +/// mypy-init-return = true +/// ``` +/// +/// ## Example +/// ```python +/// class Foo: +/// def __init__(self, x: int): +/// self.x = x +/// ``` +/// +/// Use instead: +/// ```python +/// class Foo: +/// def __init__(self, x: int) -> None: +/// self.x = x +/// ``` +#[violation] +pub struct MissingReturnTypeSpecialMethod { + pub name: String, +} + impl AlwaysAutofixableViolation for MissingReturnTypeSpecialMethod { #[derive_message_formats] fn message(&self) -> String { @@ -300,34 +300,34 @@ impl AlwaysAutofixableViolation for MissingReturnTypeSpecialMethod { } } -define_violation!( - /// ## What it does - /// Checks that static methods have return type annotations. - /// - /// ## Why is this bad? - /// Type annotations are a good way to document the return types of functions. They also - /// help catch bugs, when used alongside a type checker, by ensuring that the types of - /// any returned values, and the types expected by callers, match expectation. - /// - /// ## Example - /// ```python - /// class Foo: - /// @staticmethod - /// def bar(): - /// return 1 - /// ``` - /// - /// Use instead: - /// ```python - /// class Foo: - /// @staticmethod - /// def bar() -> int: - /// return 1 - /// ``` - pub struct MissingReturnTypeStaticMethod { - pub name: String, - } -); +/// ## What it does +/// Checks that static methods have return type annotations. +/// +/// ## Why is this bad? +/// Type annotations are a good way to document the return types of functions. They also +/// help catch bugs, when used alongside a type checker, by ensuring that the types of +/// any returned values, and the types expected by callers, match expectation. +/// +/// ## Example +/// ```python +/// class Foo: +/// @staticmethod +/// def bar(): +/// return 1 +/// ``` +/// +/// Use instead: +/// ```python +/// class Foo: +/// @staticmethod +/// def bar() -> int: +/// return 1 +/// ``` +#[violation] +pub struct MissingReturnTypeStaticMethod { + pub name: String, +} + impl Violation for MissingReturnTypeStaticMethod { #[derive_message_formats] fn message(&self) -> String { @@ -336,34 +336,34 @@ impl Violation for MissingReturnTypeStaticMethod { } } -define_violation!( - /// ## What it does - /// Checks that class methods have return type annotations. - /// - /// ## Why is this bad? - /// Type annotations are a good way to document the return types of functions. They also - /// help catch bugs, when used alongside a type checker, by ensuring that the types of - /// any returned values, and the types expected by callers, match expectation. - /// - /// ## Example - /// ```python - /// class Foo: - /// @classmethod - /// def bar(cls): - /// return 1 - /// ``` - /// - /// Use instead: - /// ```python - /// class Foo: - /// @classmethod - /// def bar(cls) -> int: - /// return 1 - /// ``` - pub struct MissingReturnTypeClassMethod { - pub name: String, - } -); +/// ## What it does +/// Checks that class methods have return type annotations. +/// +/// ## Why is this bad? +/// Type annotations are a good way to document the return types of functions. They also +/// help catch bugs, when used alongside a type checker, by ensuring that the types of +/// any returned values, and the types expected by callers, match expectation. +/// +/// ## Example +/// ```python +/// class Foo: +/// @classmethod +/// def bar(cls): +/// return 1 +/// ``` +/// +/// Use instead: +/// ```python +/// class Foo: +/// @classmethod +/// def bar(cls) -> int: +/// return 1 +/// ``` +#[violation] +pub struct MissingReturnTypeClassMethod { + pub name: String, +} + impl Violation for MissingReturnTypeClassMethod { #[derive_message_formats] fn message(&self) -> String { @@ -372,39 +372,39 @@ impl Violation for MissingReturnTypeClassMethod { } } -define_violation!( - /// ## What it does - /// Checks that an expression is annotated with a more specific type than - /// `Any`. - /// - /// ## Why is this bad? - /// `Any` is a special type indicating an unconstrained type. When an - /// expression is annotated with type `Any`, type checkers will allow all - /// operations on it. - /// - /// It's better to be explicit about the type of an expression, and to use - /// `Any` as an "escape hatch" only when it is really needed. - /// - /// ## Example - /// ```python - /// def foo(x: Any): - /// ... - /// ``` - /// - /// Use instead: - /// ```python - /// def foo(x: int): - /// ... - /// ``` - /// - /// ## References - /// - [PEP 484](https://www.python.org/dev/peps/pep-0484/#the-any-type) - /// - [`typing.Any`](https://docs.python.org/3/library/typing.html#typing.Any) - /// - [Mypy: The Any type](https://mypy.readthedocs.io/en/stable/kinds_of_types.html#the-any-type) - pub struct AnyType { - pub name: String, - } -); +/// ## What it does +/// Checks that an expression is annotated with a more specific type than +/// `Any`. +/// +/// ## Why is this bad? +/// `Any` is a special type indicating an unconstrained type. When an +/// expression is annotated with type `Any`, type checkers will allow all +/// operations on it. +/// +/// It's better to be explicit about the type of an expression, and to use +/// `Any` as an "escape hatch" only when it is really needed. +/// +/// ## Example +/// ```python +/// def foo(x: Any): +/// ... +/// ``` +/// +/// Use instead: +/// ```python +/// def foo(x: int): +/// ... +/// ``` +/// +/// ## References +/// - [PEP 484](https://www.python.org/dev/peps/pep-0484/#the-any-type) +/// - [`typing.Any`](https://docs.python.org/3/library/typing.html#typing.Any) +/// - [Mypy: The Any type](https://mypy.readthedocs.io/en/stable/kinds_of_types.html#the-any-type) +#[violation] +pub struct AnyType { + pub name: String, +} + impl Violation for AnyType { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bandit/rules/assert_used.rs b/crates/ruff/src/rules/flake8_bandit/rules/assert_used.rs index a1b254eab3..e7310b94b7 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/assert_used.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/assert_used.rs @@ -1,14 +1,14 @@ use rustpython_parser::ast::Stmt; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct Assert; -); +#[violation] +pub struct Assert; + impl Violation for Assert { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bandit/rules/bad_file_permissions.rs b/crates/ruff/src/rules/flake8_bandit/rules/bad_file_permissions.rs index 1436959b7e..39e10637f5 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/bad_file_permissions.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/bad_file_permissions.rs @@ -1,6 +1,6 @@ use num_traits::ToPrimitive; use once_cell::sync::Lazy; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustc_hash::FxHashMap; use rustpython_parser::ast::{Constant, Expr, ExprKind, Keyword, Operator}; @@ -10,11 +10,11 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct BadFilePermissions { - pub mask: u16, - } -); +#[violation] +pub struct BadFilePermissions { + pub mask: u16, +} + impl Violation for BadFilePermissions { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bandit/rules/exec_used.rs b/crates/ruff/src/rules/flake8_bandit/rules/exec_used.rs index 2f0fd377e0..57161c5a79 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/exec_used.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/exec_used.rs @@ -1,13 +1,13 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct ExecBuiltin; -); +#[violation] +pub struct ExecBuiltin; + impl Violation for ExecBuiltin { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_bind_all_interfaces.rs b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_bind_all_interfaces.rs index 34ed637aff..3822b81e5d 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_bind_all_interfaces.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_bind_all_interfaces.rs @@ -1,12 +1,12 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct HardcodedBindAllInterfaces; -); +#[violation] +pub struct HardcodedBindAllInterfaces; + impl Violation for HardcodedBindAllInterfaces { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_default.rs b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_default.rs index 001994c931..d68d7ac288 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_default.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_default.rs @@ -1,6 +1,6 @@ use rustpython_parser::ast::{Arg, Arguments, Expr}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::registry::Diagnostic; @@ -8,11 +8,11 @@ use crate::violation::Violation; use super::super::helpers::{matches_password_name, string_literal}; -define_violation!( - pub struct HardcodedPasswordDefault { - pub string: String, - } -); +#[violation] +pub struct HardcodedPasswordDefault { + pub string: String, +} + impl Violation for HardcodedPasswordDefault { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_func_arg.rs b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_func_arg.rs index 388a3eddcf..573be4164b 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_func_arg.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_func_arg.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Keyword; use super::super::helpers::{matches_password_name, string_literal}; @@ -6,11 +6,11 @@ use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct HardcodedPasswordFuncArg { - pub string: String, - } -); +#[violation] +pub struct HardcodedPasswordFuncArg { + pub string: String, +} + impl Violation for HardcodedPasswordFuncArg { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_string.rs b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_string.rs index 8cca63835a..03c37d7894 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_string.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_password_string.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprKind}; use super::super::helpers::{matches_password_name, string_literal}; @@ -6,11 +6,11 @@ use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct HardcodedPasswordString { - pub string: String, - } -); +#[violation] +pub struct HardcodedPasswordString { + pub string: String, +} + impl Violation for HardcodedPasswordString { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_sql_expression.rs b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_sql_expression.rs index f105f1de2a..b33504b132 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_sql_expression.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_sql_expression.rs @@ -1,6 +1,6 @@ use once_cell::sync::Lazy; use regex::Regex; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind, Operator}; use super::super::helpers::string_literal; @@ -15,28 +15,28 @@ static SQL_REGEX: Lazy = Lazy::new(|| { .unwrap() }); -define_violation!( - /// ## What it does - /// Checks for strings that resemble SQL statements involved in some form - /// string building operation. - /// - /// ## Why is this bad? - /// SQL injection is a common attack vector for web applications. Directly - /// interpolating user input into SQL statements should always be avoided. - /// Instead, favor parameterized queries, in which the SQL statement is - /// provided separately from its parameters, as supported by `psycopg3` - /// and other database drivers and ORMs. - /// - /// ## Example - /// ```python - /// query = "DELETE FROM foo WHERE id = '%s'" % identifier - /// ``` - /// - /// ## References - /// - [B608: Test for SQL injection](https://bandit.readthedocs.io/en/latest/plugins/b608_hardcoded_sql_expressions.html) - /// - [psycopg3: Server-side binding](https://www.psycopg.org/psycopg3/docs/basic/from_pg2.html#server-side-binding) - pub struct HardcodedSQLExpression; -); +/// ## What it does +/// Checks for strings that resemble SQL statements involved in some form +/// string building operation. +/// +/// ## Why is this bad? +/// SQL injection is a common attack vector for web applications. Directly +/// interpolating user input into SQL statements should always be avoided. +/// Instead, favor parameterized queries, in which the SQL statement is +/// provided separately from its parameters, as supported by `psycopg3` +/// and other database drivers and ORMs. +/// +/// ## Example +/// ```python +/// query = "DELETE FROM foo WHERE id = '%s'" % identifier +/// ``` +/// +/// ## References +/// - [B608: Test for SQL injection](https://bandit.readthedocs.io/en/latest/plugins/b608_hardcoded_sql_expressions.html) +/// - [psycopg3: Server-side binding](https://www.psycopg.org/psycopg3/docs/basic/from_pg2.html#server-side-binding) +#[violation] +pub struct HardcodedSQLExpression; + impl Violation for HardcodedSQLExpression { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_tmp_directory.rs b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_tmp_directory.rs index de17104aa2..96cdcddeda 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_tmp_directory.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/hardcoded_tmp_directory.rs @@ -1,15 +1,15 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Expr; use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct HardcodedTempFile { - pub string: String, - } -); +#[violation] +pub struct HardcodedTempFile { + pub string: String, +} + impl Violation for HardcodedTempFile { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bandit/rules/hashlib_insecure_hash_functions.rs b/crates/ruff/src/rules/flake8_bandit/rules/hashlib_insecure_hash_functions.rs index 14366e74bb..8e24631a6a 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/hashlib_insecure_hash_functions.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/hashlib_insecure_hash_functions.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprKind, Keyword}; use super::super::helpers::string_literal; @@ -8,11 +8,11 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct HashlibInsecureHashFunction { - pub string: String, - } -); +#[violation] +pub struct HashlibInsecureHashFunction { + pub string: String, +} + impl Violation for HashlibInsecureHashFunction { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bandit/rules/jinja2_autoescape_false.rs b/crates/ruff/src/rules/flake8_bandit/rules/jinja2_autoescape_false.rs index 8df19a8ed1..dffe400d61 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/jinja2_autoescape_false.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/jinja2_autoescape_false.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprKind, Keyword}; use crate::ast::helpers::SimpleCallArgs; @@ -7,11 +7,11 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct Jinja2AutoescapeFalse { - pub value: bool, - } -); +#[violation] +pub struct Jinja2AutoescapeFalse { + pub value: bool, +} + impl Violation for Jinja2AutoescapeFalse { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bandit/rules/logging_config_insecure_listen.rs b/crates/ruff/src/rules/flake8_bandit/rules/logging_config_insecure_listen.rs index 9acf38a0eb..07c50c519e 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/logging_config_insecure_listen.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/logging_config_insecure_listen.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, Keyword}; use crate::ast::helpers::SimpleCallArgs; @@ -7,9 +7,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct LoggingConfigInsecureListen; -); +#[violation] +pub struct LoggingConfigInsecureListen; + impl Violation for LoggingConfigInsecureListen { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bandit/rules/request_with_no_cert_validation.rs b/crates/ruff/src/rules/flake8_bandit/rules/request_with_no_cert_validation.rs index e50c61cc50..eb07edb2f4 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/request_with_no_cert_validation.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/request_with_no_cert_validation.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprKind, Keyword}; use crate::ast::helpers::SimpleCallArgs; @@ -7,11 +7,11 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct RequestWithNoCertValidation { - pub string: String, - } -); +#[violation] +pub struct RequestWithNoCertValidation { + pub string: String, +} + impl Violation for RequestWithNoCertValidation { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bandit/rules/request_without_timeout.rs b/crates/ruff/src/rules/flake8_bandit/rules/request_without_timeout.rs index 7dd6adc0e0..350e725272 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/request_without_timeout.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/request_without_timeout.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprKind, Keyword}; use crate::ast::helpers::{unparse_constant, SimpleCallArgs}; @@ -7,11 +7,11 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct RequestWithoutTimeout { - pub timeout: Option, - } -); +#[violation] +pub struct RequestWithoutTimeout { + pub timeout: Option, +} + impl Violation for RequestWithoutTimeout { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bandit/rules/snmp_insecure_version.rs b/crates/ruff/src/rules/flake8_bandit/rules/snmp_insecure_version.rs index a3c47695b5..516b16f2dd 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/snmp_insecure_version.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/snmp_insecure_version.rs @@ -1,5 +1,5 @@ use num_traits::{One, Zero}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprKind, Keyword}; use crate::ast::helpers::SimpleCallArgs; @@ -8,9 +8,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct SnmpInsecureVersion; -); +#[violation] +pub struct SnmpInsecureVersion; + impl Violation for SnmpInsecureVersion { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bandit/rules/snmp_weak_cryptography.rs b/crates/ruff/src/rules/flake8_bandit/rules/snmp_weak_cryptography.rs index 4a7527b4b9..21fab35ffc 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/snmp_weak_cryptography.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/snmp_weak_cryptography.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, Keyword}; use crate::ast::helpers::SimpleCallArgs; @@ -7,9 +7,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct SnmpWeakCryptography; -); +#[violation] +pub struct SnmpWeakCryptography; + impl Violation for SnmpWeakCryptography { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bandit/rules/try_except_continue.rs b/crates/ruff/src/rules/flake8_bandit/rules/try_except_continue.rs index 8c6871fef1..86f78de5b9 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/try_except_continue.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/try_except_continue.rs @@ -1,6 +1,6 @@ use rustpython_parser::ast::{Excepthandler, Expr, Stmt, StmtKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; @@ -8,9 +8,9 @@ use crate::registry::Diagnostic; use crate::rules::flake8_bandit::helpers::is_untyped_exception; use crate::violation::Violation; -define_violation!( - pub struct TryExceptContinue; -); +#[violation] +pub struct TryExceptContinue; + impl Violation for TryExceptContinue { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bandit/rules/try_except_pass.rs b/crates/ruff/src/rules/flake8_bandit/rules/try_except_pass.rs index d9c4f4bf46..0f2a5e4f51 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/try_except_pass.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/try_except_pass.rs @@ -1,6 +1,6 @@ use rustpython_parser::ast::{Excepthandler, Expr, Stmt, StmtKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; @@ -8,9 +8,9 @@ use crate::registry::Diagnostic; use crate::rules::flake8_bandit::helpers::is_untyped_exception; use crate::violation::Violation; -define_violation!( - pub struct TryExceptPass; -); +#[violation] +pub struct TryExceptPass; + impl Violation for TryExceptPass { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bandit/rules/unsafe_yaml_load.rs b/crates/ruff/src/rules/flake8_bandit/rules/unsafe_yaml_load.rs index a8e9fd5c72..bd24d8abf0 100644 --- a/crates/ruff/src/rules/flake8_bandit/rules/unsafe_yaml_load.rs +++ b/crates/ruff/src/rules/flake8_bandit/rules/unsafe_yaml_load.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind, Keyword}; use crate::ast::helpers::SimpleCallArgs; @@ -7,11 +7,11 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct UnsafeYAMLLoad { - pub loader: Option, - } -); +#[violation] +pub struct UnsafeYAMLLoad { + pub loader: Option, +} + impl Violation for UnsafeYAMLLoad { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_blind_except/rules.rs b/crates/ruff/src/rules/flake8_blind_except/rules.rs index d37bce40c5..3dcd9fb9fa 100644 --- a/crates/ruff/src/rules/flake8_blind_except/rules.rs +++ b/crates/ruff/src/rules/flake8_blind_except/rules.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind, Stmt, StmtKind}; use crate::ast::helpers; @@ -8,11 +8,11 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct BlindExcept { - pub name: String, - } -); +#[violation] +pub struct BlindExcept { + pub name: String, +} + impl Violation for BlindExcept { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_boolean_trap/rules.rs b/crates/ruff/src/rules/flake8_boolean_trap/rules.rs index f6cc121e7e..b19ad37b1d 100644 --- a/crates/ruff/src/rules/flake8_boolean_trap/rules.rs +++ b/crates/ruff/src/rules/flake8_boolean_trap/rules.rs @@ -1,6 +1,6 @@ use rustpython_parser::ast::{Arguments, Constant, Expr, ExprKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::helpers::collect_call_path; use crate::ast::types::Range; @@ -8,9 +8,9 @@ use crate::checkers::ast::Checker; use crate::registry::{Diagnostic, DiagnosticKind}; use crate::violation::Violation; -define_violation!( - pub struct BooleanPositionalArgInFunctionDefinition; -); +#[violation] +pub struct BooleanPositionalArgInFunctionDefinition; + impl Violation for BooleanPositionalArgInFunctionDefinition { #[derive_message_formats] fn message(&self) -> String { @@ -18,9 +18,9 @@ impl Violation for BooleanPositionalArgInFunctionDefinition { } } -define_violation!( - pub struct BooleanDefaultValueInFunctionDefinition; -); +#[violation] +pub struct BooleanDefaultValueInFunctionDefinition; + impl Violation for BooleanDefaultValueInFunctionDefinition { #[derive_message_formats] fn message(&self) -> String { @@ -28,9 +28,9 @@ impl Violation for BooleanDefaultValueInFunctionDefinition { } } -define_violation!( - pub struct BooleanPositionalValueInFunctionCall; -); +#[violation] +pub struct BooleanPositionalValueInFunctionCall; + impl Violation for BooleanPositionalValueInFunctionCall { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/abstract_base_class.rs b/crates/ruff/src/rules/flake8_bugbear/rules/abstract_base_class.rs index 51d24d3153..aae830be19 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/abstract_base_class.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/abstract_base_class.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprKind, Keyword, Stmt, StmtKind}; use crate::ast::types::Range; @@ -7,11 +7,11 @@ use crate::registry::{Diagnostic, Rule}; use crate::violation::Violation; use crate::visibility::{is_abstract, is_overload}; -define_violation!( - pub struct AbstractBaseClassWithoutAbstractMethod { - pub name: String, - } -); +#[violation] +pub struct AbstractBaseClassWithoutAbstractMethod { + pub name: String, +} + impl Violation for AbstractBaseClassWithoutAbstractMethod { #[derive_message_formats] fn message(&self) -> String { @@ -19,11 +19,11 @@ impl Violation for AbstractBaseClassWithoutAbstractMethod { format!("`{name}` is an abstract base class, but it has no abstract methods") } } -define_violation!( - pub struct EmptyMethodWithoutAbstractDecorator { - pub name: String, - } -); +#[violation] +pub struct EmptyMethodWithoutAbstractDecorator { + pub name: String, +} + impl Violation for EmptyMethodWithoutAbstractDecorator { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/assert_false.rs b/crates/ruff/src/rules/flake8_bugbear/rules/assert_false.rs index 440b4df157..985406d7ff 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/assert_false.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/assert_false.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprContext, ExprKind, Location, Stmt, StmtKind}; use crate::ast::helpers::unparse_stmt; @@ -8,9 +8,9 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct AssertFalse; -); +#[violation] +pub struct AssertFalse; + impl AlwaysAutofixableViolation for AssertFalse { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/assert_raises_exception.rs b/crates/ruff/src/rules/flake8_bugbear/rules/assert_raises_exception.rs index 64bd84f943..129f5f454a 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/assert_raises_exception.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/assert_raises_exception.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{ExprKind, Stmt, Withitem}; use crate::ast::types::Range; @@ -6,28 +6,28 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for `self.assertRaises(Exception)`. - /// - /// ## Why is this bad? - /// `assertRaises(Exception)` can lead to your test passing even if the - /// code being tested is never executed due to a typo. - /// - /// Either assert for a more specific exception (builtin or custom), use - /// `assertRaisesRegex` or the context manager form of `assertRaises`. - /// - /// ## Example - /// ```python - /// self.assertRaises(Exception, foo) - /// ``` - /// - /// Use instead: - /// ```python - /// self.assertRaises(SomeSpecificException, foo) - /// ``` - pub struct AssertRaisesException; -); +/// ## What it does +/// Checks for `self.assertRaises(Exception)`. +/// +/// ## Why is this bad? +/// `assertRaises(Exception)` can lead to your test passing even if the +/// code being tested is never executed due to a typo. +/// +/// Either assert for a more specific exception (builtin or custom), use +/// `assertRaisesRegex` or the context manager form of `assertRaises`. +/// +/// ## Example +/// ```python +/// self.assertRaises(Exception, foo) +/// ``` +/// +/// Use instead: +/// ```python +/// self.assertRaises(SomeSpecificException, foo) +/// ``` +#[violation] +pub struct AssertRaisesException; + impl Violation for AssertRaisesException { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/assignment_to_os_environ.rs b/crates/ruff/src/rules/flake8_bugbear/rules/assignment_to_os_environ.rs index 9e8508e520..faf99e6a1f 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/assignment_to_os_environ.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/assignment_to_os_environ.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use crate::ast::types::Range; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct AssignmentToOsEnviron; -); +#[violation] +pub struct AssignmentToOsEnviron; + impl Violation for AssignmentToOsEnviron { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/cached_instance_method.rs b/crates/ruff/src/rules/flake8_bugbear/rules/cached_instance_method.rs index 82744f96d2..278c2df6df 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/cached_instance_method.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/cached_instance_method.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use crate::ast::types::{Range, ScopeKind}; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct CachedInstanceMethod; -); +#[violation] +pub struct CachedInstanceMethod; + impl Violation for CachedInstanceMethod { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/cannot_raise_literal.rs b/crates/ruff/src/rules/flake8_bugbear/rules/cannot_raise_literal.rs index 0ac87133c6..552ba54f22 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/cannot_raise_literal.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/cannot_raise_literal.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use crate::ast::types::Range; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct CannotRaiseLiteral; -); +#[violation] +pub struct CannotRaiseLiteral; + impl Violation for CannotRaiseLiteral { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/duplicate_exceptions.rs b/crates/ruff/src/rules/flake8_bugbear/rules/duplicate_exceptions.rs index 38394e1c53..6cb86e8c62 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/duplicate_exceptions.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/duplicate_exceptions.rs @@ -1,5 +1,5 @@ use itertools::Itertools; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustc_hash::{FxHashMap, FxHashSet}; use rustpython_parser::ast::{ Excepthandler, ExcepthandlerKind, Expr, ExprContext, ExprKind, Location, @@ -13,11 +13,11 @@ use crate::fix::Fix; use crate::registry::{Diagnostic, Rule}; use crate::violation::{AlwaysAutofixableViolation, Violation}; -define_violation!( - pub struct DuplicateTryBlockException { - pub name: String, - } -); +#[violation] +pub struct DuplicateTryBlockException { + pub name: String, +} + impl Violation for DuplicateTryBlockException { #[derive_message_formats] fn message(&self) -> String { @@ -25,11 +25,11 @@ impl Violation for DuplicateTryBlockException { format!("try-except block with duplicate exception `{name}`") } } -define_violation!( - pub struct DuplicateHandlerException { - pub names: Vec, - } -); +#[violation] +pub struct DuplicateHandlerException { + pub names: Vec, +} + impl AlwaysAutofixableViolation for DuplicateHandlerException { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/except_with_empty_tuple.rs b/crates/ruff/src/rules/flake8_bugbear/rules/except_with_empty_tuple.rs index c9e4e7f682..b4ded3bd75 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/except_with_empty_tuple.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/except_with_empty_tuple.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Excepthandler; use crate::ast::types::Range; @@ -8,9 +8,9 @@ use crate::violation::Violation; use rustpython_parser::ast::{ExcepthandlerKind, ExprKind}; -define_violation!( - pub struct ExceptWithEmptyTuple; -); +#[violation] +pub struct ExceptWithEmptyTuple; + impl Violation for ExceptWithEmptyTuple { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/f_string_docstring.rs b/crates/ruff/src/rules/flake8_bugbear/rules/f_string_docstring.rs index 9367a0b565..d12b772dd6 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/f_string_docstring.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/f_string_docstring.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{ExprKind, Stmt, StmtKind}; use crate::ast::helpers; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct FStringDocstring; -); +#[violation] +pub struct FStringDocstring; + impl Violation for FStringDocstring { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/function_call_argument_default.rs b/crates/ruff/src/rules/flake8_bugbear/rules/function_call_argument_default.rs index f8f9914fce..0bd2d5c0b7 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/function_call_argument_default.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/function_call_argument_default.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Arguments, Constant, Expr, ExprKind}; use super::mutable_argument_default::is_mutable_func; @@ -10,11 +10,11 @@ use crate::checkers::ast::Checker; use crate::registry::{Diagnostic, DiagnosticKind}; use crate::violation::Violation; -define_violation!( - pub struct FunctionCallArgumentDefault { - pub name: Option, - } -); +#[violation] +pub struct FunctionCallArgumentDefault { + pub name: Option, +} + impl Violation for FunctionCallArgumentDefault { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/function_uses_loop_variable.rs b/crates/ruff/src/rules/flake8_bugbear/rules/function_uses_loop_variable.rs index 652e14503b..7aa759ebe1 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/function_uses_loop_variable.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/function_uses_loop_variable.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustc_hash::FxHashSet; use rustpython_parser::ast::{Comprehension, Expr, ExprContext, ExprKind, Stmt, StmtKind}; @@ -10,11 +10,11 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct FunctionUsesLoopVariable { - pub name: String, - } -); +#[violation] +pub struct FunctionUsesLoopVariable { + pub name: String, +} + impl Violation for FunctionUsesLoopVariable { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/getattr_with_constant.rs b/crates/ruff/src/rules/flake8_bugbear/rules/getattr_with_constant.rs index 34741d6267..c0b2081d2e 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/getattr_with_constant.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/getattr_with_constant.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use ruff_python::identifiers::{is_identifier, is_mangled_private}; use ruff_python::keyword::KWLIST; use rustpython_parser::ast::{Constant, Expr, ExprContext, ExprKind, Location}; @@ -10,9 +10,9 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct GetAttrWithConstant; -); +#[violation] +pub struct GetAttrWithConstant; + impl AlwaysAutofixableViolation for GetAttrWithConstant { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/jump_statement_in_finally.rs b/crates/ruff/src/rules/flake8_bugbear/rules/jump_statement_in_finally.rs index 611159ad13..d370953240 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/jump_statement_in_finally.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/jump_statement_in_finally.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Stmt, StmtKind}; use crate::ast::types::Range; @@ -6,11 +6,11 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct JumpStatementInFinally { - pub name: String, - } -); +#[violation] +pub struct JumpStatementInFinally { + pub name: String, +} + impl Violation for JumpStatementInFinally { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/loop_variable_overrides_iterator.rs b/crates/ruff/src/rules/flake8_bugbear/rules/loop_variable_overrides_iterator.rs index 6ada187162..0e593d1c72 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/loop_variable_overrides_iterator.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/loop_variable_overrides_iterator.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustc_hash::FxHashMap; use rustpython_parser::ast::{Expr, ExprKind}; @@ -9,11 +9,11 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct LoopVariableOverridesIterator { - pub name: String, - } -); +#[violation] +pub struct LoopVariableOverridesIterator { + pub name: String, +} + impl Violation for LoopVariableOverridesIterator { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/mutable_argument_default.rs b/crates/ruff/src/rules/flake8_bugbear/rules/mutable_argument_default.rs index 732ba217c6..e2f89fc55b 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/mutable_argument_default.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/mutable_argument_default.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Arguments, Constant, Expr, ExprKind, Operator}; use crate::ast::types::Range; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct MutableArgumentDefault; -); +#[violation] +pub struct MutableArgumentDefault; + impl Violation for MutableArgumentDefault { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/raise_without_from_inside_except.rs b/crates/ruff/src/rules/flake8_bugbear/rules/raise_without_from_inside_except.rs index a4c0a28943..72aeef3e26 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/raise_without_from_inside_except.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/raise_without_from_inside_except.rs @@ -1,6 +1,6 @@ use rustpython_parser::ast::{ExprKind, Stmt}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use ruff_python::str::is_lower; use crate::ast::helpers::RaiseStatementVisitor; @@ -9,9 +9,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct RaiseWithoutFromInsideExcept; -); +#[violation] +pub struct RaiseWithoutFromInsideExcept; + impl Violation for RaiseWithoutFromInsideExcept { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/redundant_tuple_in_exception_handler.rs b/crates/ruff/src/rules/flake8_bugbear/rules/redundant_tuple_in_exception_handler.rs index 40c973fc17..ec56f223d3 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/redundant_tuple_in_exception_handler.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/redundant_tuple_in_exception_handler.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Excepthandler, ExcepthandlerKind, ExprKind}; use crate::ast::helpers::unparse_expr; @@ -8,11 +8,11 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct RedundantTupleInExceptionHandler { - pub name: String, - } -); +#[violation] +pub struct RedundantTupleInExceptionHandler { + pub name: String, +} + impl AlwaysAutofixableViolation for RedundantTupleInExceptionHandler { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/setattr_with_constant.rs b/crates/ruff/src/rules/flake8_bugbear/rules/setattr_with_constant.rs index 76af140368..dcb583ca65 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/setattr_with_constant.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/setattr_with_constant.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use ruff_python::identifiers::{is_identifier, is_mangled_private}; use ruff_python::keyword::KWLIST; use rustpython_parser::ast::{Constant, Expr, ExprContext, ExprKind, Location, Stmt, StmtKind}; @@ -11,9 +11,9 @@ use crate::registry::Diagnostic; use crate::source_code::Stylist; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct SetAttrWithConstant; -); +#[violation] +pub struct SetAttrWithConstant; + impl AlwaysAutofixableViolation for SetAttrWithConstant { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/star_arg_unpacking_after_keyword_arg.rs b/crates/ruff/src/rules/flake8_bugbear/rules/star_arg_unpacking_after_keyword_arg.rs index 7e59e954c9..d4af4d11f3 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/star_arg_unpacking_after_keyword_arg.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/star_arg_unpacking_after_keyword_arg.rs @@ -7,7 +7,7 @@ //! by the unpacked sequence, and this change of ordering can surprise and //! mislead readers. -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind, Keyword}; use crate::ast::types::Range; @@ -15,9 +15,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct StarArgUnpackingAfterKeywordArg; -); +#[violation] +pub struct StarArgUnpackingAfterKeywordArg; + impl Violation for StarArgUnpackingAfterKeywordArg { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/strip_with_multi_characters.rs b/crates/ruff/src/rules/flake8_bugbear/rules/strip_with_multi_characters.rs index 5859ad2f4a..f1e4cfaf78 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/strip_with_multi_characters.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/strip_with_multi_characters.rs @@ -1,5 +1,5 @@ use itertools::Itertools; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprKind}; use crate::ast::types::Range; @@ -7,9 +7,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct StripWithMultiCharacters; -); +#[violation] +pub struct StripWithMultiCharacters; + impl Violation for StripWithMultiCharacters { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/unary_prefix_increment.rs b/crates/ruff/src/rules/flake8_bugbear/rules/unary_prefix_increment.rs index a98cb37257..d9e67c34b5 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/unary_prefix_increment.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/unary_prefix_increment.rs @@ -17,7 +17,7 @@ //! n += 1 //! ``` -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind, Unaryop}; use crate::ast::types::Range; @@ -25,9 +25,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct UnaryPrefixIncrement; -); +#[violation] +pub struct UnaryPrefixIncrement; + impl Violation for UnaryPrefixIncrement { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/unintentional_type_annotation.rs b/crates/ruff/src/rules/flake8_bugbear/rules/unintentional_type_annotation.rs index 255f8e5833..9b1a3abbd2 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/unintentional_type_annotation.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/unintentional_type_annotation.rs @@ -1,31 +1,31 @@ use rustpython_parser::ast::{Expr, ExprKind, Stmt}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for the unintentional use of type annotations. - /// - /// ## Why is this bad? - /// The use of a colon (`:`) in lieu of an assignment (`=`) can be syntactically valid, but - /// is almost certainly a mistake when used in a subscript or attribute assignment. - /// - /// ## Example - /// ```python - /// a["b"]: 1 - /// ``` - /// - /// Use instead: - /// ```python - /// a["b"] = 1 - /// ``` - pub struct UnintentionalTypeAnnotation; -); +/// ## What it does +/// Checks for the unintentional use of type annotations. +/// +/// ## Why is this bad? +/// The use of a colon (`:`) in lieu of an assignment (`=`) can be syntactically valid, but +/// is almost certainly a mistake when used in a subscript or attribute assignment. +/// +/// ## Example +/// ```python +/// a["b"]: 1 +/// ``` +/// +/// Use instead: +/// ```python +/// a["b"] = 1 +/// ``` +#[violation] +pub struct UnintentionalTypeAnnotation; + impl Violation for UnintentionalTypeAnnotation { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/unreliable_callable_check.rs b/crates/ruff/src/rules/flake8_bugbear/rules/unreliable_callable_check.rs index 4212320ea4..f44a0e5a59 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/unreliable_callable_check.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/unreliable_callable_check.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprKind}; use crate::ast::types::Range; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct UnreliableCallableCheck; -); +#[violation] +pub struct UnreliableCallableCheck; + impl Violation for UnreliableCallableCheck { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/unused_loop_control_variable.rs b/crates/ruff/src/rules/flake8_bugbear/rules/unused_loop_control_variable.rs index 7db53a3762..12e37a8bb4 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/unused_loop_control_variable.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/unused_loop_control_variable.rs @@ -18,7 +18,7 @@ //! method() //! ``` -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustc_hash::FxHashMap; use rustpython_parser::ast::{Expr, ExprKind, Stmt}; use serde::{Deserialize, Serialize}; @@ -37,20 +37,20 @@ pub enum Certainty { Uncertain, } -define_violation!( - pub struct UnusedLoopControlVariable { - /// The name of the loop control variable. - pub name: String, - /// The name to which the variable should be renamed, if it can be - /// safely renamed. - pub rename: Option, - /// Whether the variable is certain to be unused in the loop body, or - /// merely suspect. A variable _may_ be used, but undetectably - /// so, if the loop incorporates by magic control flow (e.g., - /// `locals()`). - pub certainty: Certainty, - } -); +#[violation] +pub struct UnusedLoopControlVariable { + /// The name of the loop control variable. + pub name: String, + /// The name to which the variable should be renamed, if it can be + /// safely renamed. + pub rename: Option, + /// Whether the variable is certain to be unused in the loop body, or + /// merely suspect. A variable _may_ be used, but undetectably + /// so, if the loop incorporates by magic control flow (e.g., + /// `locals()`). + pub certainty: Certainty, +} + impl Violation for UnusedLoopControlVariable { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Sometimes)); diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/useless_comparison.rs b/crates/ruff/src/rules/flake8_bugbear/rules/useless_comparison.rs index 687edf785f..cd98b20e02 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/useless_comparison.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/useless_comparison.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use crate::ast::types::Range; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct UselessComparison; -); +#[violation] +pub struct UselessComparison; + impl Violation for UselessComparison { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/useless_contextlib_suppress.rs b/crates/ruff/src/rules/flake8_bugbear/rules/useless_contextlib_suppress.rs index ee73ff1200..21138b1b59 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/useless_contextlib_suppress.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/useless_contextlib_suppress.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Expr; use crate::ast::types::Range; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct UselessContextlibSuppress; -); +#[violation] +pub struct UselessContextlibSuppress; + impl Violation for UselessContextlibSuppress { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/useless_expression.rs b/crates/ruff/src/rules/flake8_bugbear/rules/useless_expression.rs index 26e3080b2b..03a2a1742c 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/useless_expression.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/useless_expression.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, ExprKind, Stmt, StmtKind}; use crate::ast::types::Range; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct UselessExpression; -); +#[violation] +pub struct UselessExpression; + impl Violation for UselessExpression { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_bugbear/rules/zip_without_explicit_strict.rs b/crates/ruff/src/rules/flake8_bugbear/rules/zip_without_explicit_strict.rs index 1a99f3c8ff..e274428e99 100644 --- a/crates/ruff/src/rules/flake8_bugbear/rules/zip_without_explicit_strict.rs +++ b/crates/ruff/src/rules/flake8_bugbear/rules/zip_without_explicit_strict.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind, Keyword}; use crate::ast::types::Range; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct ZipWithoutExplicitStrict; -); +#[violation] +pub struct ZipWithoutExplicitStrict; + impl Violation for ZipWithoutExplicitStrict { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_builtins/rules.rs b/crates/ruff/src/rules/flake8_builtins/rules.rs index 4871732a12..6b32f83a2b 100644 --- a/crates/ruff/src/rules/flake8_builtins/rules.rs +++ b/crates/ruff/src/rules/flake8_builtins/rules.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use ruff_python::builtins::BUILTINS; use rustpython_parser::ast::Located; @@ -7,49 +7,49 @@ use crate::ast::types::Range; use crate::registry::{Diagnostic, DiagnosticKind}; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for variable (and function) assignments that use the same name - /// as a builtin. - /// - /// ## Why is this bad? - /// Reusing a builtin name for the name of a variable increases the - /// difficulty of reading and maintaining the code, and can cause - /// non-obvious errors, as readers may mistake the variable for the - /// builtin and vice versa. - /// - /// Builtins can be marked as exceptions to this rule via the - /// [`flake8-builtins.builtins-ignorelist`] configuration option. - /// - /// ## Options - /// - /// - `flake8-builtins.builtins-ignorelist` - /// - /// ## Example - /// ```python - /// def find_max(list_of_lists): - /// max = 0 - /// for flat_list in list_of_lists: - /// for value in flat_list: - /// max = max(max, value) # TypeError: 'int' object is not callable - /// return max - /// ``` - /// - /// Use instead: - /// ```python - /// def find_max(list_of_lists): - /// result = 0 - /// for flat_list in list_of_lists: - /// for value in flat_list: - /// result = max(result, value) - /// return result - /// ``` - /// - /// - [_Why is it a bad idea to name a variable `id` in Python?_](https://stackoverflow.com/questions/77552/id-is-a-bad-variable-name-in-python) - pub struct BuiltinVariableShadowing { - pub name: String, - } -); +/// ## What it does +/// Checks for variable (and function) assignments that use the same name +/// as a builtin. +/// +/// ## Why is this bad? +/// Reusing a builtin name for the name of a variable increases the +/// difficulty of reading and maintaining the code, and can cause +/// non-obvious errors, as readers may mistake the variable for the +/// builtin and vice versa. +/// +/// Builtins can be marked as exceptions to this rule via the +/// [`flake8-builtins.builtins-ignorelist`] configuration option. +/// +/// ## Options +/// +/// - `flake8-builtins.builtins-ignorelist` +/// +/// ## Example +/// ```python +/// def find_max(list_of_lists): +/// max = 0 +/// for flat_list in list_of_lists: +/// for value in flat_list: +/// max = max(max, value) # TypeError: 'int' object is not callable +/// return max +/// ``` +/// +/// Use instead: +/// ```python +/// def find_max(list_of_lists): +/// result = 0 +/// for flat_list in list_of_lists: +/// for value in flat_list: +/// result = max(result, value) +/// return result +/// ``` +/// +/// - [_Why is it a bad idea to name a variable `id` in Python?_](https://stackoverflow.com/questions/77552/id-is-a-bad-variable-name-in-python) +#[violation] +pub struct BuiltinVariableShadowing { + pub name: String, +} + impl Violation for BuiltinVariableShadowing { #[derive_message_formats] fn message(&self) -> String { @@ -58,52 +58,52 @@ impl Violation for BuiltinVariableShadowing { } } -define_violation!( - /// ## What it does - /// Checks for any function arguments that use the same name as a builtin. - /// - /// ## Why is this bad? - /// Reusing a builtin name for the name of an argument increases the - /// difficulty of reading and maintaining the code, and can cause - /// non-obvious errors, as readers may mistake the argument for the - /// builtin and vice versa. - /// - /// Builtins can be marked as exceptions to this rule via the - /// [`flake8-builtins.builtins-ignorelist`] configuration option. - /// - /// ## Options - /// - /// - `flake8-builtins.builtins-ignorelist` - /// - /// ## Example - /// ```python - /// def remove_duplicates(list, list2): - /// result = set() - /// for value in list: - /// result.add(value) - /// for value in list2: - /// result.add(value) - /// return list(result) # TypeError: 'list' object is not callable - /// ``` - /// - /// Use instead: - /// ```python - /// def remove_duplicates(list1, list2): - /// result = set() - /// for value in list1: - /// result.add(value) - /// for value in list2: - /// result.add(value) - /// return list(result) - /// ``` - /// - /// ## References - /// - [_Is it bad practice to use a built-in function name as an attribute or method identifier?_](https://stackoverflow.com/questions/9109333/is-it-bad-practice-to-use-a-built-in-function-name-as-an-attribute-or-method-ide) - /// - [_Why is it a bad idea to name a variable `id` in Python?_](https://stackoverflow.com/questions/77552/id-is-a-bad-variable-name-in-python) - pub struct BuiltinArgumentShadowing { - pub name: String, - } -); +/// ## What it does +/// Checks for any function arguments that use the same name as a builtin. +/// +/// ## Why is this bad? +/// Reusing a builtin name for the name of an argument increases the +/// difficulty of reading and maintaining the code, and can cause +/// non-obvious errors, as readers may mistake the argument for the +/// builtin and vice versa. +/// +/// Builtins can be marked as exceptions to this rule via the +/// [`flake8-builtins.builtins-ignorelist`] configuration option. +/// +/// ## Options +/// +/// - `flake8-builtins.builtins-ignorelist` +/// +/// ## Example +/// ```python +/// def remove_duplicates(list, list2): +/// result = set() +/// for value in list: +/// result.add(value) +/// for value in list2: +/// result.add(value) +/// return list(result) # TypeError: 'list' object is not callable +/// ``` +/// +/// Use instead: +/// ```python +/// def remove_duplicates(list1, list2): +/// result = set() +/// for value in list1: +/// result.add(value) +/// for value in list2: +/// result.add(value) +/// return list(result) +/// ``` +/// +/// ## References +/// - [_Is it bad practice to use a built-in function name as an attribute or method identifier?_](https://stackoverflow.com/questions/9109333/is-it-bad-practice-to-use-a-built-in-function-name-as-an-attribute-or-method-ide) +/// - [_Why is it a bad idea to name a variable `id` in Python?_](https://stackoverflow.com/questions/77552/id-is-a-bad-variable-name-in-python) +#[violation] +pub struct BuiltinArgumentShadowing { + pub name: String, +} + impl Violation for BuiltinArgumentShadowing { #[derive_message_formats] fn message(&self) -> String { @@ -112,53 +112,53 @@ impl Violation for BuiltinArgumentShadowing { } } -define_violation!( - /// ## What it does - /// Checks for any class attributes that use the same name as a builtin. - /// - /// ## Why is this bad? - /// Reusing a builtin name for the name of an attribute increases the - /// difficulty of reading and maintaining the code, and can cause - /// non-obvious errors, as readers may mistake the attribute for the - /// builtin and vice versa. - /// - /// Builtins can be marked as exceptions to this rule via the - /// [`flake8-builtins.builtins-ignorelist`] configuration option, or - /// converted to the appropriate dunder method. - /// - /// ## Options - /// - /// - `flake8-builtins.builtins-ignorelist` - /// - /// ## Example - /// ```python - /// class Shadow: - /// def int(): - /// return 0 - /// ``` - /// - /// Use instead: - /// ```python - /// class Shadow: - /// def to_int(): - /// return 0 - /// ``` - /// - /// Or: - /// ```python - /// class Shadow: - /// # Callable as `int(shadow)` - /// def __int__(): - /// return 0 - /// ``` - /// - /// ## References - /// - [_Is it bad practice to use a built-in function name as an attribute or method identifier?_](https://stackoverflow.com/questions/9109333/is-it-bad-practice-to-use-a-built-in-function-name-as-an-attribute-or-method-ide) - /// - [_Why is it a bad idea to name a variable `id` in Python?_](https://stackoverflow.com/questions/77552/id-is-a-bad-variable-name-in-python) - pub struct BuiltinAttributeShadowing { - pub name: String, - } -); +/// ## What it does +/// Checks for any class attributes that use the same name as a builtin. +/// +/// ## Why is this bad? +/// Reusing a builtin name for the name of an attribute increases the +/// difficulty of reading and maintaining the code, and can cause +/// non-obvious errors, as readers may mistake the attribute for the +/// builtin and vice versa. +/// +/// Builtins can be marked as exceptions to this rule via the +/// [`flake8-builtins.builtins-ignorelist`] configuration option, or +/// converted to the appropriate dunder method. +/// +/// ## Options +/// +/// - `flake8-builtins.builtins-ignorelist` +/// +/// ## Example +/// ```python +/// class Shadow: +/// def int(): +/// return 0 +/// ``` +/// +/// Use instead: +/// ```python +/// class Shadow: +/// def to_int(): +/// return 0 +/// ``` +/// +/// Or: +/// ```python +/// class Shadow: +/// # Callable as `int(shadow)` +/// def __int__(): +/// return 0 +/// ``` +/// +/// ## References +/// - [_Is it bad practice to use a built-in function name as an attribute or method identifier?_](https://stackoverflow.com/questions/9109333/is-it-bad-practice-to-use-a-built-in-function-name-as-an-attribute-or-method-ide) +/// - [_Why is it a bad idea to name a variable `id` in Python?_](https://stackoverflow.com/questions/77552/id-is-a-bad-variable-name-in-python) +#[violation] +pub struct BuiltinAttributeShadowing { + pub name: String, +} + impl Violation for BuiltinAttributeShadowing { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_commas/rules.rs b/crates/ruff/src/rules/flake8_commas/rules.rs index 62ba53d114..846a9f479b 100644 --- a/crates/ruff/src/rules/flake8_commas/rules.rs +++ b/crates/ruff/src/rules/flake8_commas/rules.rs @@ -1,5 +1,5 @@ use itertools::Itertools; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::lexer::{LexResult, Spanned}; use rustpython_parser::Tok; @@ -109,9 +109,9 @@ impl Context { } } -define_violation!( - pub struct TrailingCommaMissing; -); +#[violation] +pub struct TrailingCommaMissing; + impl AlwaysAutofixableViolation for TrailingCommaMissing { #[derive_message_formats] fn message(&self) -> String { @@ -123,9 +123,9 @@ impl AlwaysAutofixableViolation for TrailingCommaMissing { } } -define_violation!( - pub struct TrailingCommaOnBareTupleProhibited; -); +#[violation] +pub struct TrailingCommaOnBareTupleProhibited; + impl Violation for TrailingCommaOnBareTupleProhibited { #[derive_message_formats] fn message(&self) -> String { @@ -133,9 +133,9 @@ impl Violation for TrailingCommaOnBareTupleProhibited { } } -define_violation!( - pub struct TrailingCommaProhibited; -); +#[violation] +pub struct TrailingCommaProhibited; + impl AlwaysAutofixableViolation for TrailingCommaProhibited { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_call_around_sorted.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_call_around_sorted.rs index 38858fcb76..b58906cdc2 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_call_around_sorted.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_call_around_sorted.rs @@ -1,5 +1,5 @@ use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use super::helpers; @@ -9,34 +9,34 @@ use crate::registry::Diagnostic; use crate::rules::flake8_comprehensions::fixes; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - /// ## What it does - /// Checks for unnecessary `list` or `reversed` calls around `sorted` - /// calls. - /// - /// ## Why is this bad? - /// It is unnecessary to use `list` around `sorted`, as the latter already - /// returns a list. - /// - /// It is also unnecessary to use `reversed` around `sorted`, as the latter - /// has a `reverse` argument that can be used in lieu of an additional - /// `reversed` call. - /// - /// In both cases, it's clearer to avoid the redundant call. - /// - /// ## Examples - /// ```python - /// reversed(sorted(iterable)) - /// ``` - /// - /// Use instead: - /// ```python - /// sorted(iterable, reverse=True) - /// ``` - pub struct UnnecessaryCallAroundSorted { - pub func: String, - } -); +/// ## What it does +/// Checks for unnecessary `list` or `reversed` calls around `sorted` +/// calls. +/// +/// ## Why is this bad? +/// It is unnecessary to use `list` around `sorted`, as the latter already +/// returns a list. +/// +/// It is also unnecessary to use `reversed` around `sorted`, as the latter +/// has a `reverse` argument that can be used in lieu of an additional +/// `reversed` call. +/// +/// In both cases, it's clearer to avoid the redundant call. +/// +/// ## Examples +/// ```python +/// reversed(sorted(iterable)) +/// ``` +/// +/// Use instead: +/// ```python +/// sorted(iterable, reverse=True) +/// ``` +#[violation] +pub struct UnnecessaryCallAroundSorted { + pub func: String, +} + impl AlwaysAutofixableViolation for UnnecessaryCallAroundSorted { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_collection_call.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_collection_call.rs index 4ae011faca..5069a112c1 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_collection_call.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_collection_call.rs @@ -1,5 +1,5 @@ use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, Keyword}; use super::helpers; @@ -10,11 +10,11 @@ use crate::rules::flake8_comprehensions::fixes; use crate::rules::flake8_comprehensions::settings::Settings; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct UnnecessaryCollectionCall { - pub obj_type: String, - } -); +#[violation] +pub struct UnnecessaryCollectionCall { + pub obj_type: String, +} + impl AlwaysAutofixableViolation for UnnecessaryCollectionCall { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_comprehension.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_comprehension.rs index 926ab356b5..a9d9ddc1cd 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_comprehension.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_comprehension.rs @@ -1,5 +1,5 @@ use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Comprehension, Expr, ExprKind}; use super::helpers; @@ -9,11 +9,11 @@ use crate::registry::Diagnostic; use crate::rules::flake8_comprehensions::fixes; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct UnnecessaryComprehension { - pub obj_type: String, - } -); +#[violation] +pub struct UnnecessaryComprehension { + pub obj_type: String, +} + impl AlwaysAutofixableViolation for UnnecessaryComprehension { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_double_cast_or_process.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_double_cast_or_process.rs index 21442c4fd1..bcb7677220 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_double_cast_or_process.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_double_cast_or_process.rs @@ -1,6 +1,6 @@ use rustpython_parser::ast::{Expr, ExprKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; @@ -10,46 +10,46 @@ use crate::violation::AlwaysAutofixableViolation; use super::helpers; -define_violation!( - /// ## What it does - /// Checks for unnecessary `list`, `reversed`, `set`, `sorted`, and `tuple` - /// call within `list`, `set`, `sorted`, and `tuple` calls. - /// - /// ## Why is this bad? - /// It's unnecessary to double-cast or double-process iterables by wrapping - /// the listed functions within an additional `list`, `set`, `sorted`, or - /// `tuple` call. Doing so is redundant and can be confusing for readers. - /// - /// ## Examples - /// ```python - /// list(tuple(iterable)) - /// ``` - /// - /// Use instead: - /// ```python - /// list(iterable) - /// ``` - /// - /// This rule applies to a variety of functions, including `list`, `reversed`, - /// `set`, `sorted`, and `tuple`. For example: - /// - Instead of `list(list(iterable))`, use `list(iterable)`. - /// - Instead of `list(tuple(iterable))`, use `list(iterable)`. - /// - Instead of `tuple(list(iterable))`, use `tuple(iterable)`. - /// - Instead of `tuple(tuple(iterable))`, use `tuple(iterable)`. - /// - Instead of `set(set(iterable))`, use `set(iterable)`. - /// - Instead of `set(list(iterable))`, use `set(iterable)`. - /// - Instead of `set(tuple(iterable))`, use `set(iterable)`. - /// - Instead of `set(sorted(iterable))`, use `set(iterable)`. - /// - Instead of `set(reversed(iterable))`, use `set(iterable)`. - /// - Instead of `sorted(list(iterable))`, use `sorted(iterable)`. - /// - Instead of `sorted(tuple(iterable))`, use `sorted(iterable)`. - /// - Instead of `sorted(sorted(iterable))`, use `sorted(iterable)`. - /// - Instead of `sorted(reversed(iterable))`, use `sorted(iterable)`. - pub struct UnnecessaryDoubleCastOrProcess { - pub inner: String, - pub outer: String, - } -); +/// ## What it does +/// Checks for unnecessary `list`, `reversed`, `set`, `sorted`, and `tuple` +/// call within `list`, `set`, `sorted`, and `tuple` calls. +/// +/// ## Why is this bad? +/// It's unnecessary to double-cast or double-process iterables by wrapping +/// the listed functions within an additional `list`, `set`, `sorted`, or +/// `tuple` call. Doing so is redundant and can be confusing for readers. +/// +/// ## Examples +/// ```python +/// list(tuple(iterable)) +/// ``` +/// +/// Use instead: +/// ```python +/// list(iterable) +/// ``` +/// +/// This rule applies to a variety of functions, including `list`, `reversed`, +/// `set`, `sorted`, and `tuple`. For example: +/// - Instead of `list(list(iterable))`, use `list(iterable)`. +/// - Instead of `list(tuple(iterable))`, use `list(iterable)`. +/// - Instead of `tuple(list(iterable))`, use `tuple(iterable)`. +/// - Instead of `tuple(tuple(iterable))`, use `tuple(iterable)`. +/// - Instead of `set(set(iterable))`, use `set(iterable)`. +/// - Instead of `set(list(iterable))`, use `set(iterable)`. +/// - Instead of `set(tuple(iterable))`, use `set(iterable)`. +/// - Instead of `set(sorted(iterable))`, use `set(iterable)`. +/// - Instead of `set(reversed(iterable))`, use `set(iterable)`. +/// - Instead of `sorted(list(iterable))`, use `sorted(iterable)`. +/// - Instead of `sorted(tuple(iterable))`, use `sorted(iterable)`. +/// - Instead of `sorted(sorted(iterable))`, use `sorted(iterable)`. +/// - Instead of `sorted(reversed(iterable))`, use `sorted(iterable)`. +#[violation] +pub struct UnnecessaryDoubleCastOrProcess { + pub inner: String, + pub outer: String, +} + impl AlwaysAutofixableViolation for UnnecessaryDoubleCastOrProcess { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_dict.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_dict.rs index 46322bac26..b666f5afef 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_dict.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_dict.rs @@ -1,5 +1,5 @@ use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind, Keyword}; use super::helpers; @@ -9,27 +9,27 @@ use crate::registry::Diagnostic; use crate::rules::flake8_comprehensions::fixes; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - /// ## What it does - /// Checks for unnecessary generators that can be rewritten as `dict` - /// comprehensions. - /// - /// ## Why is this bad? - /// It is unnecessary to use `dict` around a generator expression, since - /// there are equivalent comprehensions for these types. Using a - /// comprehension is clearer and more idiomatic. - /// - /// ## Examples - /// ```python - /// dict((x, f(x)) for x in foo) - /// ``` - /// - /// Use instead: - /// ```python - /// {x: f(x) for x in foo} - /// ``` - pub struct UnnecessaryGeneratorDict; -); +/// ## What it does +/// Checks for unnecessary generators that can be rewritten as `dict` +/// comprehensions. +/// +/// ## Why is this bad? +/// It is unnecessary to use `dict` around a generator expression, since +/// there are equivalent comprehensions for these types. Using a +/// comprehension is clearer and more idiomatic. +/// +/// ## Examples +/// ```python +/// dict((x, f(x)) for x in foo) +/// ``` +/// +/// Use instead: +/// ```python +/// {x: f(x) for x in foo} +/// ``` +#[violation] +pub struct UnnecessaryGeneratorDict; + impl AlwaysAutofixableViolation for UnnecessaryGeneratorDict { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_list.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_list.rs index 43f0974c17..22e135e076 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_list.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_list.rs @@ -1,5 +1,5 @@ use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind, Keyword}; use super::helpers; @@ -9,27 +9,27 @@ use crate::registry::Diagnostic; use crate::rules::flake8_comprehensions::fixes; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - /// ## What it does - /// Checks for unnecessary generators that can be rewritten as `list` - /// comprehensions. - /// - /// ## Why is this bad? - /// It is unnecessary to use `list` around a generator expression, since - /// there are equivalent comprehensions for these types. Using a - /// comprehension is clearer and more idiomatic. - /// - /// ## Examples - /// ```python - /// list(f(x) for x in foo) - /// ``` - /// - /// Use instead: - /// ```python - /// [f(x) for x in foo] - /// ``` - pub struct UnnecessaryGeneratorList; -); +/// ## What it does +/// Checks for unnecessary generators that can be rewritten as `list` +/// comprehensions. +/// +/// ## Why is this bad? +/// It is unnecessary to use `list` around a generator expression, since +/// there are equivalent comprehensions for these types. Using a +/// comprehension is clearer and more idiomatic. +/// +/// ## Examples +/// ```python +/// list(f(x) for x in foo) +/// ``` +/// +/// Use instead: +/// ```python +/// [f(x) for x in foo] +/// ``` +#[violation] +pub struct UnnecessaryGeneratorList; + impl AlwaysAutofixableViolation for UnnecessaryGeneratorList { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_set.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_set.rs index 29d54e4177..3c0837f982 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_set.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_generator_set.rs @@ -1,5 +1,5 @@ use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind, Keyword}; use super::helpers; @@ -9,27 +9,27 @@ use crate::registry::Diagnostic; use crate::rules::flake8_comprehensions::fixes; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - /// ## What it does - /// Checks for unnecessary generators that can be rewritten as `set` - /// comprehensions. - /// - /// ## Why is this bad? - /// It is unnecessary to use `set` around a generator expression, since - /// there are equivalent comprehensions for these types. Using a - /// comprehension is clearer and more idiomatic. - /// - /// ## Examples - /// ```python - /// set(f(x) for x in foo) - /// ``` - /// - /// Use instead: - /// ```python - /// {f(x) for x in foo} - /// ``` - pub struct UnnecessaryGeneratorSet; -); +/// ## What it does +/// Checks for unnecessary generators that can be rewritten as `set` +/// comprehensions. +/// +/// ## Why is this bad? +/// It is unnecessary to use `set` around a generator expression, since +/// there are equivalent comprehensions for these types. Using a +/// comprehension is clearer and more idiomatic. +/// +/// ## Examples +/// ```python +/// set(f(x) for x in foo) +/// ``` +/// +/// Use instead: +/// ```python +/// {f(x) for x in foo} +/// ``` +#[violation] +pub struct UnnecessaryGeneratorSet; + impl AlwaysAutofixableViolation for UnnecessaryGeneratorSet { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_call.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_call.rs index 596954fa10..3d762b852e 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_call.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_call.rs @@ -1,5 +1,5 @@ use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use super::helpers; @@ -9,9 +9,9 @@ use crate::registry::Diagnostic; use crate::rules::flake8_comprehensions::fixes; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct UnnecessaryListCall; -); +#[violation] +pub struct UnnecessaryListCall; + impl AlwaysAutofixableViolation for UnnecessaryListCall { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_dict.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_dict.rs index 55f5c4c613..01f628a92c 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_dict.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_dict.rs @@ -1,5 +1,5 @@ use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind, Keyword}; use super::helpers; @@ -9,9 +9,9 @@ use crate::registry::Diagnostic; use crate::rules::flake8_comprehensions::fixes; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct UnnecessaryListComprehensionDict; -); +#[violation] +pub struct UnnecessaryListComprehensionDict; + impl AlwaysAutofixableViolation for UnnecessaryListComprehensionDict { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_set.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_set.rs index 2fde071a85..728693b55e 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_set.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_list_comprehension_set.rs @@ -1,5 +1,5 @@ use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind, Keyword}; use super::helpers; @@ -9,9 +9,9 @@ use crate::registry::Diagnostic; use crate::rules::flake8_comprehensions::fixes; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct UnnecessaryListComprehensionSet; -); +#[violation] +pub struct UnnecessaryListComprehensionSet; + impl AlwaysAutofixableViolation for UnnecessaryListComprehensionSet { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_dict.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_dict.rs index ce62230872..200f450fde 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_dict.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_dict.rs @@ -1,5 +1,5 @@ use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind, Keyword}; use super::helpers; @@ -9,11 +9,11 @@ use crate::registry::Diagnostic; use crate::rules::flake8_comprehensions::fixes; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct UnnecessaryLiteralDict { - pub obj_type: String, - } -); +#[violation] +pub struct UnnecessaryLiteralDict { + pub obj_type: String, +} + impl AlwaysAutofixableViolation for UnnecessaryLiteralDict { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_set.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_set.rs index f4f6b2e85d..1ad274a3bc 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_set.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_set.rs @@ -1,5 +1,5 @@ use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind, Keyword}; use super::helpers; @@ -9,11 +9,11 @@ use crate::registry::Diagnostic; use crate::rules::flake8_comprehensions::fixes; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct UnnecessaryLiteralSet { - pub obj_type: String, - } -); +#[violation] +pub struct UnnecessaryLiteralSet { + pub obj_type: String, +} + impl AlwaysAutofixableViolation for UnnecessaryLiteralSet { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_list_call.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_list_call.rs index 3832ff2927..844e693218 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_list_call.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_list_call.rs @@ -1,5 +1,5 @@ use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use super::helpers; @@ -9,11 +9,11 @@ use crate::registry::Diagnostic; use crate::rules::flake8_comprehensions::fixes; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct UnnecessaryLiteralWithinListCall { - pub literal: String, - } -); +#[violation] +pub struct UnnecessaryLiteralWithinListCall { + pub literal: String, +} + impl AlwaysAutofixableViolation for UnnecessaryLiteralWithinListCall { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_tuple_call.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_tuple_call.rs index 4782c598e8..f77110f6d1 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_tuple_call.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_literal_within_tuple_call.rs @@ -1,5 +1,5 @@ use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use super::helpers; @@ -9,11 +9,11 @@ use crate::registry::Diagnostic; use crate::rules::flake8_comprehensions::fixes; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct UnnecessaryLiteralWithinTupleCall { - pub literal: String, - } -); +#[violation] +pub struct UnnecessaryLiteralWithinTupleCall { + pub literal: String, +} + impl AlwaysAutofixableViolation for UnnecessaryLiteralWithinTupleCall { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_map.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_map.rs index 95d49c7a5b..c7d8f09937 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_map.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_map.rs @@ -1,7 +1,7 @@ use log::error; use rustpython_parser::ast::{Expr, ExprKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; @@ -11,37 +11,37 @@ use crate::violation::{AutofixKind, Availability, Violation}; use super::helpers; -define_violation!( - /// ## What it does - /// Checks for unnecessary `map` calls with `lambda` functions. - /// - /// ## Why is this bad? - /// Using `map(func, iterable)` when `func` is a `lambda` is slower than - /// using a generator expression or a comprehension, as the latter approach - /// avoids the function call overhead, in addition to being more readable. - /// - /// ## Examples - /// ```python - /// map(lambda x: x + 1, iterable) - /// ``` - /// - /// Use instead: - /// ```python - /// (x + 1 for x in iterable) - /// ``` - /// - /// This rule also applies to `map` calls within `list`, `set`, and `dict` - /// calls. For example: - /// - Instead of `list(map(lambda num: num * 2, nums))`, use - /// `[num * 2 for num in nums]`. - /// - Instead of `set(map(lambda num: num % 2 == 0, nums))`, use - /// `{num % 2 == 0 for num in nums}`. - /// - Instead of `dict(map(lambda v: (v, v ** 2), values))`, use - /// `{v: v ** 2 for v in values}`. - pub struct UnnecessaryMap { - pub obj_type: String, - } -); +/// ## What it does +/// Checks for unnecessary `map` calls with `lambda` functions. +/// +/// ## Why is this bad? +/// Using `map(func, iterable)` when `func` is a `lambda` is slower than +/// using a generator expression or a comprehension, as the latter approach +/// avoids the function call overhead, in addition to being more readable. +/// +/// ## Examples +/// ```python +/// map(lambda x: x + 1, iterable) +/// ``` +/// +/// Use instead: +/// ```python +/// (x + 1 for x in iterable) +/// ``` +/// +/// This rule also applies to `map` calls within `list`, `set`, and `dict` +/// calls. For example: +/// - Instead of `list(map(lambda num: num * 2, nums))`, use +/// `[num * 2 for num in nums]`. +/// - Instead of `set(map(lambda num: num % 2 == 0, nums))`, use +/// `{num % 2 == 0 for num in nums}`. +/// - Instead of `dict(map(lambda v: (v, v ** 2), values))`, use +/// `{v: v ** 2 for v in values}`. +#[violation] +pub struct UnnecessaryMap { + pub obj_type: String, +} + impl Violation for UnnecessaryMap { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Sometimes)); diff --git a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_subscript_reversal.rs b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_subscript_reversal.rs index 63b6434c5e..ebbe735d55 100644 --- a/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_subscript_reversal.rs +++ b/crates/ruff/src/rules/flake8_comprehensions/rules/unnecessary_subscript_reversal.rs @@ -1,5 +1,5 @@ use num_bigint::BigInt; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprKind, Unaryop}; use super::helpers; @@ -8,11 +8,11 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct UnnecessarySubscriptReversal { - pub func: String, - } -); +#[violation] +pub struct UnnecessarySubscriptReversal { + pub func: String, +} + impl Violation for UnnecessarySubscriptReversal { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_datetimez/rules.rs b/crates/ruff/src/rules/flake8_datetimez/rules.rs index 19e155a595..9fb2cdd73f 100644 --- a/crates/ruff/src/rules/flake8_datetimez/rules.rs +++ b/crates/ruff/src/rules/flake8_datetimez/rules.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprKind, Keyword}; use crate::ast::helpers::{has_non_none_keyword, is_const_none}; @@ -7,9 +7,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct CallDatetimeWithoutTzinfo; -); +#[violation] +pub struct CallDatetimeWithoutTzinfo; + impl Violation for CallDatetimeWithoutTzinfo { #[derive_message_formats] fn message(&self) -> String { @@ -17,9 +17,9 @@ impl Violation for CallDatetimeWithoutTzinfo { } } -define_violation!( - pub struct CallDatetimeToday; -); +#[violation] +pub struct CallDatetimeToday; + impl Violation for CallDatetimeToday { #[derive_message_formats] fn message(&self) -> String { @@ -30,9 +30,9 @@ impl Violation for CallDatetimeToday { } } -define_violation!( - pub struct CallDatetimeUtcnow; -); +#[violation] +pub struct CallDatetimeUtcnow; + impl Violation for CallDatetimeUtcnow { #[derive_message_formats] fn message(&self) -> String { @@ -43,9 +43,9 @@ impl Violation for CallDatetimeUtcnow { } } -define_violation!( - pub struct CallDatetimeUtcfromtimestamp; -); +#[violation] +pub struct CallDatetimeUtcfromtimestamp; + impl Violation for CallDatetimeUtcfromtimestamp { #[derive_message_formats] fn message(&self) -> String { @@ -56,9 +56,9 @@ impl Violation for CallDatetimeUtcfromtimestamp { } } -define_violation!( - pub struct CallDatetimeNowWithoutTzinfo; -); +#[violation] +pub struct CallDatetimeNowWithoutTzinfo; + impl Violation for CallDatetimeNowWithoutTzinfo { #[derive_message_formats] fn message(&self) -> String { @@ -66,9 +66,9 @@ impl Violation for CallDatetimeNowWithoutTzinfo { } } -define_violation!( - pub struct CallDatetimeFromtimestamp; -); +#[violation] +pub struct CallDatetimeFromtimestamp; + impl Violation for CallDatetimeFromtimestamp { #[derive_message_formats] fn message(&self) -> String { @@ -78,9 +78,9 @@ impl Violation for CallDatetimeFromtimestamp { } } -define_violation!( - pub struct CallDatetimeStrptimeWithoutZone; -); +#[violation] +pub struct CallDatetimeStrptimeWithoutZone; + impl Violation for CallDatetimeStrptimeWithoutZone { #[derive_message_formats] fn message(&self) -> String { @@ -91,9 +91,9 @@ impl Violation for CallDatetimeStrptimeWithoutZone { } } -define_violation!( - pub struct CallDateToday; -); +#[violation] +pub struct CallDateToday; + impl Violation for CallDateToday { #[derive_message_formats] fn message(&self) -> String { @@ -104,9 +104,9 @@ impl Violation for CallDateToday { } } -define_violation!( - pub struct CallDateFromtimestamp; -); +#[violation] +pub struct CallDateFromtimestamp; + impl Violation for CallDateFromtimestamp { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_debugger/rules.rs b/crates/ruff/src/rules/flake8_debugger/rules.rs index 9bbf1dbeb9..0efb2ee0d0 100644 --- a/crates/ruff/src/rules/flake8_debugger/rules.rs +++ b/crates/ruff/src/rules/flake8_debugger/rules.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, Stmt}; use super::types::DebuggerUsingType; @@ -10,11 +10,11 @@ use crate::violation::Violation; // flake8-debugger -define_violation!( - pub struct Debugger { - pub using_type: DebuggerUsingType, - } -); +#[violation] +pub struct Debugger { + pub using_type: DebuggerUsingType, +} + impl Violation for Debugger { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_django/rules/all_with_model_form.rs b/crates/ruff/src/rules/flake8_django/rules/all_with_model_form.rs index 150723d117..e636900902 100644 --- a/crates/ruff/src/rules/flake8_django/rules/all_with_model_form.rs +++ b/crates/ruff/src/rules/flake8_django/rules/all_with_model_form.rs @@ -1,44 +1,44 @@ use rustpython_parser::ast::{Constant, Expr, ExprKind, Stmt, StmtKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::rules::flake8_django::rules::helpers::is_model_form; use crate::violation::Violation; use crate::{checkers::ast::Checker, registry::Diagnostic, Range}; -define_violation!( - /// ## What it does - /// Checks for the use of `fields = "__all__"` in Django `ModelForm` - /// classes. - /// - /// ## Why is this bad? - /// If a `ModelForm` includes the `fields = "__all__"` attribute, any new - /// field that is added to the model will automatically be exposed for - /// modification. - /// - /// ## Example - /// ```python - /// from django.forms import ModelForm - /// - /// - /// class PostForm(ModelForm): - /// class Meta: - /// model = Post - /// fields = "__all__" - /// ``` - /// - /// Use instead: - /// ```python - /// from django.forms import ModelForm - /// - /// - /// class PostForm(ModelForm): - /// class Meta: - /// model = Post - /// fields = ["title", "content"] - /// ``` - pub struct AllWithModelForm; -); +/// ## What it does +/// Checks for the use of `fields = "__all__"` in Django `ModelForm` +/// classes. +/// +/// ## Why is this bad? +/// If a `ModelForm` includes the `fields = "__all__"` attribute, any new +/// field that is added to the model will automatically be exposed for +/// modification. +/// +/// ## Example +/// ```python +/// from django.forms import ModelForm +/// +/// +/// class PostForm(ModelForm): +/// class Meta: +/// model = Post +/// fields = "__all__" +/// ``` +/// +/// Use instead: +/// ```python +/// from django.forms import ModelForm +/// +/// +/// class PostForm(ModelForm): +/// class Meta: +/// model = Post +/// fields = ["title", "content"] +/// ``` +#[violation] +pub struct AllWithModelForm; + impl Violation for AllWithModelForm { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_django/rules/exclude_with_model_form.rs b/crates/ruff/src/rules/flake8_django/rules/exclude_with_model_form.rs index f64f3df49b..3cf69749db 100644 --- a/crates/ruff/src/rules/flake8_django/rules/exclude_with_model_form.rs +++ b/crates/ruff/src/rules/flake8_django/rules/exclude_with_model_form.rs @@ -1,40 +1,40 @@ use rustpython_parser::ast::{Expr, ExprKind, Stmt, StmtKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::rules::flake8_django::rules::helpers::is_model_form; use crate::violation::Violation; use crate::{checkers::ast::Checker, registry::Diagnostic, Range}; -define_violation!( - /// ## What it does - /// Checks for the use of `exclude` in Django `ModelForm` classes. - /// - /// ## Why is this bad? - /// If a `ModelForm` includes the `exclude` attribute, any new field that - /// is added to the model will automatically be exposed for modification. - /// - /// ## Example - /// ```python - /// from django.forms import ModelForm - /// - /// class PostForm(ModelForm): - /// class Meta: - /// model = Post - /// exclude = ["author"] - /// ``` - /// - /// Use instead: - /// ```python - /// from django.forms import ModelForm - /// - /// class PostForm(ModelForm): - /// class Meta: - /// model = Post - /// fields = ["title", "content"] - /// ``` - pub struct ExcludeWithModelForm; -); +/// ## What it does +/// Checks for the use of `exclude` in Django `ModelForm` classes. +/// +/// ## Why is this bad? +/// If a `ModelForm` includes the `exclude` attribute, any new field that +/// is added to the model will automatically be exposed for modification. +/// +/// ## Example +/// ```python +/// from django.forms import ModelForm +/// +/// class PostForm(ModelForm): +/// class Meta: +/// model = Post +/// exclude = ["author"] +/// ``` +/// +/// Use instead: +/// ```python +/// from django.forms import ModelForm +/// +/// class PostForm(ModelForm): +/// class Meta: +/// model = Post +/// fields = ["title", "content"] +/// ``` +#[violation] +pub struct ExcludeWithModelForm; + impl Violation for ExcludeWithModelForm { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_django/rules/locals_in_render_function.rs b/crates/ruff/src/rules/flake8_django/rules/locals_in_render_function.rs index 7bfde268df..45a82dca92 100644 --- a/crates/ruff/src/rules/flake8_django/rules/locals_in_render_function.rs +++ b/crates/ruff/src/rules/flake8_django/rules/locals_in_render_function.rs @@ -1,37 +1,37 @@ use rustpython_parser::ast::{Expr, ExprKind, Keyword}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::{checkers::ast::Checker, registry::Diagnostic, violation::Violation, Range}; -define_violation!( - /// ## What it does - /// Checks for the use of `locals()` in `render` functions. - /// - /// ## Why is this bad? - /// Using `locals()` can expose internal variables or other unintentional - /// data to the rendered template. - /// - /// ## Example - /// ```python - /// from django.shortcuts import render - /// - /// def index(request): - /// posts = Post.objects.all() - /// return render(request, "app/index.html", locals()) - /// ``` - /// - /// Use instead: - /// ```python - /// from django.shortcuts import render - /// - /// def index(request): - /// posts = Post.objects.all() - /// context = {"posts": posts} - /// return render(request, "app/index.html", context) - /// ``` - pub struct LocalsInRenderFunction; -); +/// ## What it does +/// Checks for the use of `locals()` in `render` functions. +/// +/// ## Why is this bad? +/// Using `locals()` can expose internal variables or other unintentional +/// data to the rendered template. +/// +/// ## Example +/// ```python +/// from django.shortcuts import render +/// +/// def index(request): +/// posts = Post.objects.all() +/// return render(request, "app/index.html", locals()) +/// ``` +/// +/// Use instead: +/// ```python +/// from django.shortcuts import render +/// +/// def index(request): +/// posts = Post.objects.all() +/// context = {"posts": posts} +/// return render(request, "app/index.html", context) +/// ``` +#[violation] +pub struct LocalsInRenderFunction; + impl Violation for LocalsInRenderFunction { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_django/rules/model_without_dunder_str.rs b/crates/ruff/src/rules/flake8_django/rules/model_without_dunder_str.rs index b9e87543cf..abcb2e5ec2 100644 --- a/crates/ruff/src/rules/flake8_django/rules/model_without_dunder_str.rs +++ b/crates/ruff/src/rules/flake8_django/rules/model_without_dunder_str.rs @@ -1,7 +1,7 @@ use rustpython_parser::ast::{Constant, Expr, StmtKind}; use rustpython_parser::ast::{ExprKind, Stmt}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; @@ -10,40 +10,40 @@ use crate::violation::Violation; use super::helpers; -define_violation!( - /// ## What it does - /// Checks that `__str__` method is defined in Django models. - /// - /// ## Why is this bad? - /// Django models should define `__str__` method to return a string representation - /// of the model instance, as Django calls this method to display the object in - /// the Django Admin and elsewhere. - /// - /// Models without `__str__` method will display a non-meaningful representation - /// of the object in the Django Admin. - /// - /// ## Example - /// ```python - /// from django.db import models - /// - /// - /// class MyModel(models.Model): - /// field = models.CharField(max_length=255) - /// ``` - /// - /// Use instead: - /// ```python - /// from django.db import models - /// - /// - /// class MyModel(models.Model): - /// field = models.CharField(max_length=255) - /// - /// def __str__(self): - /// return f"{self.field}" - /// ``` - pub struct ModelWithoutDunderStr; -); +/// ## What it does +/// Checks that `__str__` method is defined in Django models. +/// +/// ## Why is this bad? +/// Django models should define `__str__` method to return a string representation +/// of the model instance, as Django calls this method to display the object in +/// the Django Admin and elsewhere. +/// +/// Models without `__str__` method will display a non-meaningful representation +/// of the object in the Django Admin. +/// +/// ## Example +/// ```python +/// from django.db import models +/// +/// +/// class MyModel(models.Model): +/// field = models.CharField(max_length=255) +/// ``` +/// +/// Use instead: +/// ```python +/// from django.db import models +/// +/// +/// class MyModel(models.Model): +/// field = models.CharField(max_length=255) +/// +/// def __str__(self): +/// return f"{self.field}" +/// ``` +#[violation] +pub struct ModelWithoutDunderStr; + impl Violation for ModelWithoutDunderStr { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_django/rules/non_leading_receiver_decorator.rs b/crates/ruff/src/rules/flake8_django/rules/non_leading_receiver_decorator.rs index fe9563349b..186f20d1fe 100644 --- a/crates/ruff/src/rules/flake8_django/rules/non_leading_receiver_decorator.rs +++ b/crates/ruff/src/rules/flake8_django/rules/non_leading_receiver_decorator.rs @@ -1,47 +1,47 @@ use rustpython_parser::ast::{Expr, ExprKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::{CallPath, Range}; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks that Django's `@receiver` decorator is listed first, prior to - /// any other decorators. - /// - /// ## Why is this bad? - /// Django's `@receiver` decorator is special in that it does not return - /// a wrapped function. Rather, `@receiver` connects the decorated function - /// to a signal. If any other decorators are listed before `@receiver`, - /// the decorated function will not be connected to the signal. - /// - /// ## Example - /// ```python - /// from django.dispatch import receiver - /// from django.db.models.signals import post_save - /// - /// - /// @transaction.atomic - /// @receiver(post_save, sender=MyModel) - /// def my_handler(sender, instance, created, **kwargs): - /// pass - /// ``` - /// - /// Use instead: - /// ```python - /// from django.dispatch import receiver - /// from django.db.models.signals import post_save - /// - /// - /// @receiver(post_save, sender=MyModel) - /// @transaction.atomic - /// def my_handler(sender, instance, created, **kwargs): - /// pass - /// ``` - pub struct NonLeadingReceiverDecorator; -); +/// ## What it does +/// Checks that Django's `@receiver` decorator is listed first, prior to +/// any other decorators. +/// +/// ## Why is this bad? +/// Django's `@receiver` decorator is special in that it does not return +/// a wrapped function. Rather, `@receiver` connects the decorated function +/// to a signal. If any other decorators are listed before `@receiver`, +/// the decorated function will not be connected to the signal. +/// +/// ## Example +/// ```python +/// from django.dispatch import receiver +/// from django.db.models.signals import post_save +/// +/// +/// @transaction.atomic +/// @receiver(post_save, sender=MyModel) +/// def my_handler(sender, instance, created, **kwargs): +/// pass +/// ``` +/// +/// Use instead: +/// ```python +/// from django.dispatch import receiver +/// from django.db.models.signals import post_save +/// +/// +/// @receiver(post_save, sender=MyModel) +/// @transaction.atomic +/// def my_handler(sender, instance, created, **kwargs): +/// pass +/// ``` +#[violation] +pub struct NonLeadingReceiverDecorator; + impl Violation for NonLeadingReceiverDecorator { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_django/rules/nullable_model_string_field.rs b/crates/ruff/src/rules/flake8_django/rules/nullable_model_string_field.rs index 2ef6425b52..b251eb6352 100644 --- a/crates/ruff/src/rules/flake8_django/rules/nullable_model_string_field.rs +++ b/crates/ruff/src/rules/flake8_django/rules/nullable_model_string_field.rs @@ -1,7 +1,7 @@ use rustpython_parser::ast::Constant::Bool; use rustpython_parser::ast::{Expr, ExprKind, Stmt, StmtKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; @@ -10,41 +10,41 @@ use crate::violation::Violation; use super::helpers; -define_violation!( - /// ## What it does - /// Checks nullable string-based fields (like `CharField` and `TextField`) - /// in Django models. - /// - /// ## Why is this bad? - /// If a string-based field is nullable, then your model will have two possible - /// representations for "no data": `None` and the empty string. This can lead to - /// confusion, as clients of the API have to check for both `None` and the - /// empty string when trying to determine if the field has data. - /// - /// The Django convention is to use the empty string in lieu of `None` for - /// string-based fields. - /// - /// ## Example - /// ```python - /// from django.db import models - /// - /// - /// class MyModel(models.Model): - /// field = models.CharField(max_length=255, null=True) - /// ``` - /// - /// Use instead: - /// ```python - /// from django.db import models - /// - /// - /// class MyModel(models.Model): - /// field = models.CharField(max_length=255, default="") - /// ``` - pub struct NullableModelStringField { - pub field_name: String, - } -); +/// ## What it does +/// Checks nullable string-based fields (like `CharField` and `TextField`) +/// in Django models. +/// +/// ## Why is this bad? +/// If a string-based field is nullable, then your model will have two possible +/// representations for "no data": `None` and the empty string. This can lead to +/// confusion, as clients of the API have to check for both `None` and the +/// empty string when trying to determine if the field has data. +/// +/// The Django convention is to use the empty string in lieu of `None` for +/// string-based fields. +/// +/// ## Example +/// ```python +/// from django.db import models +/// +/// +/// class MyModel(models.Model): +/// field = models.CharField(max_length=255, null=True) +/// ``` +/// +/// Use instead: +/// ```python +/// from django.db import models +/// +/// +/// class MyModel(models.Model): +/// field = models.CharField(max_length=255, default="") +/// ``` +#[violation] +pub struct NullableModelStringField { + pub field_name: String, +} + impl Violation for NullableModelStringField { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_errmsg/rules.rs b/crates/ruff/src/rules/flake8_errmsg/rules.rs index 73ac4a84ae..7969de58cc 100644 --- a/crates/ruff/src/rules/flake8_errmsg/rules.rs +++ b/crates/ruff/src/rules/flake8_errmsg/rules.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprKind}; use crate::ast::types::Range; @@ -6,46 +6,46 @@ use crate::checkers::ast::Checker; use crate::registry::{Diagnostic, Rule}; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for the use of string literals in exception constructors. - /// - /// ## Why is this bad? - /// Python includes the `raise` in the default traceback (and formatters - /// like Rich and IPython do too). - /// - /// By using a string literal, the error message will be duplicated in the - /// traceback, which can make the traceback less readable. - /// - /// ## Example - /// Given: - /// ```python - /// raise RuntimeError("'Some value' is incorrect") - /// ``` - /// - /// Python will produce a traceback like: - /// ```console - /// Traceback (most recent call last): - /// File "tmp.py", line 2, in - /// raise RuntimeError("Some value is incorrect") - /// RuntimeError: 'Some value' is incorrect - /// ``` - /// - /// Instead, assign the string to a variable: - /// ```python - /// msg = "'Some value' is incorrect" - /// raise RuntimeError(msg) - /// ``` - /// - /// Which will produce a traceback like: - /// ```console - /// Traceback (most recent call last): - /// File "tmp.py", line 3, in - /// raise RuntimeError(msg) - /// RuntimeError: 'Some value' is incorrect - /// ``` - pub struct RawStringInException; -); +/// ## What it does +/// Checks for the use of string literals in exception constructors. +/// +/// ## Why is this bad? +/// Python includes the `raise` in the default traceback (and formatters +/// like Rich and IPython do too). +/// +/// By using a string literal, the error message will be duplicated in the +/// traceback, which can make the traceback less readable. +/// +/// ## Example +/// Given: +/// ```python +/// raise RuntimeError("'Some value' is incorrect") +/// ``` +/// +/// Python will produce a traceback like: +/// ```console +/// Traceback (most recent call last): +/// File "tmp.py", line 2, in +/// raise RuntimeError("Some value is incorrect") +/// RuntimeError: 'Some value' is incorrect +/// ``` +/// +/// Instead, assign the string to a variable: +/// ```python +/// msg = "'Some value' is incorrect" +/// raise RuntimeError(msg) +/// ``` +/// +/// Which will produce a traceback like: +/// ```console +/// Traceback (most recent call last): +/// File "tmp.py", line 3, in +/// raise RuntimeError(msg) +/// RuntimeError: 'Some value' is incorrect +/// ``` +#[violation] +pub struct RawStringInException; + impl Violation for RawStringInException { #[derive_message_formats] fn message(&self) -> String { @@ -53,47 +53,47 @@ impl Violation for RawStringInException { } } -define_violation!( - /// ## What it does - /// Checks for the use of f-strings in exception constructors. - /// - /// ## Why is this bad? - /// Python includes the `raise` in the default traceback (and formatters - /// like Rich and IPython do too). - /// - /// By using an f-string, the error message will be duplicated in the - /// traceback, which can make the traceback less readable. - /// - /// ## Example - /// Given: - /// ```python - /// sub = "Some value" - /// raise RuntimeError(f"{sub!r} is incorrect") - /// ``` - /// - /// Python will produce a traceback like: - /// ```console - /// Traceback (most recent call last): - /// File "tmp.py", line 2, in - /// raise RuntimeError(f"{sub!r} is incorrect") - /// RuntimeError: 'Some value' is incorrect - /// ``` - /// - /// Instead, assign the string to a variable: - /// ```python - /// sub = "Some value" - /// msg = f"{sub!r} is incorrect" - /// raise RuntimeError(msg) - /// ``` - /// - /// Which will produce a traceback like: - /// ```console - /// File "tmp.py", line 3, in - /// raise RuntimeError(msg) - /// RuntimeError: 'Some value' is incorrect - /// ``` - pub struct FStringInException; -); +/// ## What it does +/// Checks for the use of f-strings in exception constructors. +/// +/// ## Why is this bad? +/// Python includes the `raise` in the default traceback (and formatters +/// like Rich and IPython do too). +/// +/// By using an f-string, the error message will be duplicated in the +/// traceback, which can make the traceback less readable. +/// +/// ## Example +/// Given: +/// ```python +/// sub = "Some value" +/// raise RuntimeError(f"{sub!r} is incorrect") +/// ``` +/// +/// Python will produce a traceback like: +/// ```console +/// Traceback (most recent call last): +/// File "tmp.py", line 2, in +/// raise RuntimeError(f"{sub!r} is incorrect") +/// RuntimeError: 'Some value' is incorrect +/// ``` +/// +/// Instead, assign the string to a variable: +/// ```python +/// sub = "Some value" +/// msg = f"{sub!r} is incorrect" +/// raise RuntimeError(msg) +/// ``` +/// +/// Which will produce a traceback like: +/// ```console +/// File "tmp.py", line 3, in +/// raise RuntimeError(msg) +/// RuntimeError: 'Some value' is incorrect +/// ``` +#[violation] +pub struct FStringInException; + impl Violation for FStringInException { #[derive_message_formats] fn message(&self) -> String { @@ -101,49 +101,49 @@ impl Violation for FStringInException { } } -define_violation!( - /// ## What it does - /// Checks for the use of `.format` calls on string literals in exception - /// constructors. - /// - /// ## Why is this bad? - /// Python includes the `raise` in the default traceback (and formatters - /// like Rich and IPython do too). - /// - /// By using a `.format` call, the error message will be duplicated in the - /// traceback, which can make the traceback less readable. - /// - /// ## Example - /// Given: - /// ```python - /// sub = "Some value" - /// raise RuntimeError("'{}' is incorrect".format(sub)) - /// ``` - /// - /// Python will produce a traceback like: - /// ```console - /// Traceback (most recent call last): - /// File "tmp.py", line 2, in - /// raise RuntimeError("'{}' is incorrect".format(sub)) - /// RuntimeError: 'Some value' is incorrect - /// ``` - /// - /// Instead, assign the string to a variable: - /// ```python - /// sub = "Some value" - /// msg = "'{}' is incorrect".format(sub) - /// raise RuntimeError(msg) - /// ``` - /// - /// Which will produce a traceback like: - /// ```console - /// Traceback (most recent call last): - /// File "tmp.py", line 3, in - /// raise RuntimeError(msg) - /// RuntimeError: 'Some value' is incorrect - /// ``` - pub struct DotFormatInException; -); +/// ## What it does +/// Checks for the use of `.format` calls on string literals in exception +/// constructors. +/// +/// ## Why is this bad? +/// Python includes the `raise` in the default traceback (and formatters +/// like Rich and IPython do too). +/// +/// By using a `.format` call, the error message will be duplicated in the +/// traceback, which can make the traceback less readable. +/// +/// ## Example +/// Given: +/// ```python +/// sub = "Some value" +/// raise RuntimeError("'{}' is incorrect".format(sub)) +/// ``` +/// +/// Python will produce a traceback like: +/// ```console +/// Traceback (most recent call last): +/// File "tmp.py", line 2, in +/// raise RuntimeError("'{}' is incorrect".format(sub)) +/// RuntimeError: 'Some value' is incorrect +/// ``` +/// +/// Instead, assign the string to a variable: +/// ```python +/// sub = "Some value" +/// msg = "'{}' is incorrect".format(sub) +/// raise RuntimeError(msg) +/// ``` +/// +/// Which will produce a traceback like: +/// ```console +/// Traceback (most recent call last): +/// File "tmp.py", line 3, in +/// raise RuntimeError(msg) +/// RuntimeError: 'Some value' is incorrect +/// ``` +#[violation] +pub struct DotFormatInException; + impl Violation for DotFormatInException { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_executable/rules/shebang_missing.rs b/crates/ruff/src/rules/flake8_executable/rules/shebang_missing.rs index 2b41916a35..1805c5ebab 100644 --- a/crates/ruff/src/rules/flake8_executable/rules/shebang_missing.rs +++ b/crates/ruff/src/rules/flake8_executable/rules/shebang_missing.rs @@ -2,7 +2,7 @@ use std::path::Path; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::registry::Diagnostic; @@ -10,9 +10,9 @@ use crate::registry::Diagnostic; use crate::rules::flake8_executable::helpers::is_executable; use crate::violation::Violation; -define_violation!( - pub struct ShebangMissingExecutableFile; -); +#[violation] +pub struct ShebangMissingExecutableFile; + impl Violation for ShebangMissingExecutableFile { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_executable/rules/shebang_newline.rs b/crates/ruff/src/rules/flake8_executable/rules/shebang_newline.rs index dbd9eb7704..67f9d3d275 100644 --- a/crates/ruff/src/rules/flake8_executable/rules/shebang_newline.rs +++ b/crates/ruff/src/rules/flake8_executable/rules/shebang_newline.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Location; use crate::ast::types::Range; @@ -6,9 +6,9 @@ use crate::registry::Diagnostic; use crate::rules::flake8_executable::helpers::ShebangDirective; use crate::violation::Violation; -define_violation!( - pub struct ShebangNewline; -); +#[violation] +pub struct ShebangNewline; + impl Violation for ShebangNewline { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_executable/rules/shebang_not_executable.rs b/crates/ruff/src/rules/flake8_executable/rules/shebang_not_executable.rs index 5ad400610a..e73676fd8f 100644 --- a/crates/ruff/src/rules/flake8_executable/rules/shebang_not_executable.rs +++ b/crates/ruff/src/rules/flake8_executable/rules/shebang_not_executable.rs @@ -4,7 +4,7 @@ use std::path::Path; use rustpython_parser::ast::Location; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::registry::Diagnostic; @@ -13,9 +13,9 @@ use crate::rules::flake8_executable::helpers::is_executable; use crate::rules::flake8_executable::helpers::ShebangDirective; use crate::violation::Violation; -define_violation!( - pub struct ShebangNotExecutable; -); +#[violation] +pub struct ShebangNotExecutable; + impl Violation for ShebangNotExecutable { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_executable/rules/shebang_python.rs b/crates/ruff/src/rules/flake8_executable/rules/shebang_python.rs index 833d71f47a..3b0df0b5f1 100644 --- a/crates/ruff/src/rules/flake8_executable/rules/shebang_python.rs +++ b/crates/ruff/src/rules/flake8_executable/rules/shebang_python.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Location; use crate::ast::types::Range; @@ -6,9 +6,9 @@ use crate::registry::Diagnostic; use crate::rules::flake8_executable::helpers::ShebangDirective; use crate::violation::Violation; -define_violation!( - pub struct ShebangPython; -); +#[violation] +pub struct ShebangPython; + impl Violation for ShebangPython { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_executable/rules/shebang_whitespace.rs b/crates/ruff/src/rules/flake8_executable/rules/shebang_whitespace.rs index e4a66c5b88..121184f13f 100644 --- a/crates/ruff/src/rules/flake8_executable/rules/shebang_whitespace.rs +++ b/crates/ruff/src/rules/flake8_executable/rules/shebang_whitespace.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Location; use crate::ast::types::Range; @@ -7,9 +7,9 @@ use crate::registry::Diagnostic; use crate::rules::flake8_executable::helpers::ShebangDirective; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct ShebangWhitespace; -); +#[violation] +pub struct ShebangWhitespace; + impl AlwaysAutofixableViolation for ShebangWhitespace { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_implicit_str_concat/rules.rs b/crates/ruff/src/rules/flake8_implicit_str_concat/rules.rs index ec4c166e6f..8507064ac7 100644 --- a/crates/ruff/src/rules/flake8_implicit_str_concat/rules.rs +++ b/crates/ruff/src/rules/flake8_implicit_str_concat/rules.rs @@ -1,5 +1,5 @@ use itertools::Itertools; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprKind, Operator}; use rustpython_parser::lexer::LexResult; use rustpython_parser::Tok; @@ -9,30 +9,30 @@ use crate::registry::Diagnostic; use crate::rules::flake8_implicit_str_concat::settings::Settings; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for implicitly concatenated strings on a single line. - /// - /// ## Why is this bad? - /// While it is valid Python syntax to concatenate multiple string or byte - /// literals implicitly (via whitespace delimiters), it is unnecessary and - /// negatively affects code readability. - /// - /// In some cases, the implicit concatenation may also be unintentional, as - /// autoformatters are capable of introducing single-line implicit - /// concatenations when collapsing long lines. - /// - /// ## Example - /// ```python - /// z = "The quick " "brown fox." - /// ``` - /// - /// Use instead: - /// ```python - /// z = "The quick brown fox." - /// ``` - pub struct SingleLineImplicitStringConcatenation; -); +/// ## What it does +/// Checks for implicitly concatenated strings on a single line. +/// +/// ## Why is this bad? +/// While it is valid Python syntax to concatenate multiple string or byte +/// literals implicitly (via whitespace delimiters), it is unnecessary and +/// negatively affects code readability. +/// +/// In some cases, the implicit concatenation may also be unintentional, as +/// autoformatters are capable of introducing single-line implicit +/// concatenations when collapsing long lines. +/// +/// ## Example +/// ```python +/// z = "The quick " "brown fox." +/// ``` +/// +/// Use instead: +/// ```python +/// z = "The quick brown fox." +/// ``` +#[violation] +pub struct SingleLineImplicitStringConcatenation; + impl Violation for SingleLineImplicitStringConcatenation { #[derive_message_formats] fn message(&self) -> String { @@ -40,42 +40,42 @@ impl Violation for SingleLineImplicitStringConcatenation { } } -define_violation!( - /// ## What it does - /// Checks for implicitly concatenated strings that span multiple lines. - /// - /// ## Why is this bad? - /// For string literals that wrap across multiple lines, PEP 8 recommends - /// the use of implicit string concatenation within parentheses instead of - /// using a backslash for line continuation, as the former is more readable - /// than the latter. - /// - /// By default, this rule will only trigger if the string literal is - /// concatenated via a backslash. To disallow implicit string concatenation - /// altogether, set the `flake8-implicit-str-concat.allow-multiline` option - /// to `false`. - /// - /// ## Options - /// - `flake8-implicit-str-concat.allow-multiline` - /// - /// ## Example - /// ```python - /// z = "The quick brown fox jumps over the lazy "\ - /// "dog." - /// ``` - /// - /// Use instead: - /// ```python - /// z = ( - /// "The quick brown fox jumps over the lazy " - /// "dog." - /// ) - /// ``` - /// - /// ## References - /// - [PEP 8](https://peps.python.org/pep-0008/#maximum-line-length) - pub struct MultiLineImplicitStringConcatenation; -); +/// ## What it does +/// Checks for implicitly concatenated strings that span multiple lines. +/// +/// ## Why is this bad? +/// For string literals that wrap across multiple lines, PEP 8 recommends +/// the use of implicit string concatenation within parentheses instead of +/// using a backslash for line continuation, as the former is more readable +/// than the latter. +/// +/// By default, this rule will only trigger if the string literal is +/// concatenated via a backslash. To disallow implicit string concatenation +/// altogether, set the `flake8-implicit-str-concat.allow-multiline` option +/// to `false`. +/// +/// ## Options +/// - `flake8-implicit-str-concat.allow-multiline` +/// +/// ## Example +/// ```python +/// z = "The quick brown fox jumps over the lazy "\ +/// "dog." +/// ``` +/// +/// Use instead: +/// ```python +/// z = ( +/// "The quick brown fox jumps over the lazy " +/// "dog." +/// ) +/// ``` +/// +/// ## References +/// - [PEP 8](https://peps.python.org/pep-0008/#maximum-line-length) +#[violation] +pub struct MultiLineImplicitStringConcatenation; + impl Violation for MultiLineImplicitStringConcatenation { #[derive_message_formats] fn message(&self) -> String { @@ -83,33 +83,33 @@ impl Violation for MultiLineImplicitStringConcatenation { } } -define_violation!( - /// ## What it does - /// Checks for string literals that are explicitly concatenated (using the - /// `+` operator). - /// - /// ## Why is this bad? - /// For string literals that wrap across multiple lines, implicit string - /// concatenation within parentheses is preferred over explicit - /// concatenation using the `+` operator, as the former is more readable. - /// - /// ## Example - /// ```python - /// z = ( - /// "The quick brown fox jumps over the lazy " - /// + "dog" - /// ) - /// ``` - /// - /// Use instead: - /// ```python - /// z = ( - /// "The quick brown fox jumps over the lazy " - /// "dog" - /// ) - /// ``` - pub struct ExplicitStringConcatenation; -); +/// ## What it does +/// Checks for string literals that are explicitly concatenated (using the +/// `+` operator). +/// +/// ## Why is this bad? +/// For string literals that wrap across multiple lines, implicit string +/// concatenation within parentheses is preferred over explicit +/// concatenation using the `+` operator, as the former is more readable. +/// +/// ## Example +/// ```python +/// z = ( +/// "The quick brown fox jumps over the lazy " +/// + "dog" +/// ) +/// ``` +/// +/// Use instead: +/// ```python +/// z = ( +/// "The quick brown fox jumps over the lazy " +/// "dog" +/// ) +/// ``` +#[violation] +pub struct ExplicitStringConcatenation; + impl Violation for ExplicitStringConcatenation { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_import_conventions/rules.rs b/crates/ruff/src/rules/flake8_import_conventions/rules.rs index b4c9cc0cc5..ea55dddc61 100644 --- a/crates/ruff/src/rules/flake8_import_conventions/rules.rs +++ b/crates/ruff/src/rules/flake8_import_conventions/rules.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustc_hash::FxHashMap; use rustpython_parser::ast::Stmt; @@ -6,30 +6,30 @@ use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for imports that are typically imported using a common convention, - /// like `import pandas as pd`, and enforces that convention. - /// - /// ## Why is this bad? - /// Consistency is good. Use a common convention for imports to make your code - /// more readable and idiomatic. - /// - /// For example, `import pandas as pd` is a common - /// convention for importing the `pandas` library, and users typically expect - /// Pandas to be aliased as `pd`. - /// - /// ## Example - /// ```python - /// import pandas - /// ``` - /// - /// Use instead: - /// ```python - /// import pandas as pd - /// ``` - pub struct UnconventionalImportAlias(pub String, pub String); -); +/// ## What it does +/// Checks for imports that are typically imported using a common convention, +/// like `import pandas as pd`, and enforces that convention. +/// +/// ## Why is this bad? +/// Consistency is good. Use a common convention for imports to make your code +/// more readable and idiomatic. +/// +/// For example, `import pandas as pd` is a common +/// convention for importing the `pandas` library, and users typically expect +/// Pandas to be aliased as `pd`. +/// +/// ## Example +/// ```python +/// import pandas +/// ``` +/// +/// Use instead: +/// ```python +/// import pandas as pd +/// ``` +#[violation] +pub struct UnconventionalImportAlias(pub String, pub String); + impl Violation for UnconventionalImportAlias { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_logging_format/violations.rs b/crates/ruff/src/rules/flake8_logging_format/violations.rs index 438c7ce01f..ad7b297061 100644 --- a/crates/ruff/src/rules/flake8_logging_format/violations.rs +++ b/crates/ruff/src/rules/flake8_logging_format/violations.rs @@ -1,10 +1,10 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::violation::{AlwaysAutofixableViolation, Violation}; -define_violation!( - pub struct LoggingStringFormat; -); +#[violation] +pub struct LoggingStringFormat; + impl Violation for LoggingStringFormat { #[derive_message_formats] fn message(&self) -> String { @@ -12,9 +12,9 @@ impl Violation for LoggingStringFormat { } } -define_violation!( - pub struct LoggingPercentFormat; -); +#[violation] +pub struct LoggingPercentFormat; + impl Violation for LoggingPercentFormat { #[derive_message_formats] fn message(&self) -> String { @@ -22,9 +22,9 @@ impl Violation for LoggingPercentFormat { } } -define_violation!( - pub struct LoggingStringConcat; -); +#[violation] +pub struct LoggingStringConcat; + impl Violation for LoggingStringConcat { #[derive_message_formats] fn message(&self) -> String { @@ -32,9 +32,9 @@ impl Violation for LoggingStringConcat { } } -define_violation!( - pub struct LoggingFString; -); +#[violation] +pub struct LoggingFString; + impl Violation for LoggingFString { #[derive_message_formats] fn message(&self) -> String { @@ -42,9 +42,9 @@ impl Violation for LoggingFString { } } -define_violation!( - pub struct LoggingWarn; -); +#[violation] +pub struct LoggingWarn; + impl AlwaysAutofixableViolation for LoggingWarn { #[derive_message_formats] fn message(&self) -> String { @@ -56,9 +56,9 @@ impl AlwaysAutofixableViolation for LoggingWarn { } } -define_violation!( - pub struct LoggingExtraAttrClash(pub String); -); +#[violation] +pub struct LoggingExtraAttrClash(pub String); + impl Violation for LoggingExtraAttrClash { #[derive_message_formats] fn message(&self) -> String { @@ -69,9 +69,9 @@ impl Violation for LoggingExtraAttrClash { } } -define_violation!( - pub struct LoggingExcInfo; -); +#[violation] +pub struct LoggingExcInfo; + impl Violation for LoggingExcInfo { #[derive_message_formats] fn message(&self) -> String { @@ -79,9 +79,9 @@ impl Violation for LoggingExcInfo { } } -define_violation!( - pub struct LoggingRedundantExcInfo; -); +#[violation] +pub struct LoggingRedundantExcInfo; + impl Violation for LoggingRedundantExcInfo { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_no_pep420/rules.rs b/crates/ruff/src/rules/flake8_no_pep420/rules.rs index ff5eb2e336..5e02024cdb 100644 --- a/crates/ruff/src/rules/flake8_no_pep420/rules.rs +++ b/crates/ruff/src/rules/flake8_no_pep420/rules.rs @@ -1,35 +1,35 @@ use std::path::{Path, PathBuf}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::fs; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for packages that are missing an `__init__.py` file. - /// - /// ## Why is this bad? - /// Python packages are directories that contain a file named `__init__.py`. - /// The existence of this file indicates that the directory is a Python - /// package, and so it can be imported the same way a module can be - /// imported. - /// - /// Directories that lack an `__init__.py` file can still be imported, but - /// they're indicative of a special kind of package, known as a "namespace - /// package" (see: [PEP 420](https://www.python.org/dev/peps/pep-0420/)). - /// Namespace packages are less widely used, so a package that lacks an - /// `__init__.py` file is typically meant to be a regular package, and - /// the absence of the `__init__.py` file is probably an oversight. - /// - /// ## Options - /// - `namespace-packages` - pub struct ImplicitNamespacePackage { - pub filename: String, - } -); +/// ## What it does +/// Checks for packages that are missing an `__init__.py` file. +/// +/// ## Why is this bad? +/// Python packages are directories that contain a file named `__init__.py`. +/// The existence of this file indicates that the directory is a Python +/// package, and so it can be imported the same way a module can be +/// imported. +/// +/// Directories that lack an `__init__.py` file can still be imported, but +/// they're indicative of a special kind of package, known as a "namespace +/// package" (see: [PEP 420](https://www.python.org/dev/peps/pep-0420/)). +/// Namespace packages are less widely used, so a package that lacks an +/// `__init__.py` file is typically meant to be a regular package, and +/// the absence of the `__init__.py` file is probably an oversight. +/// +/// ## Options +/// - `namespace-packages` +#[violation] +pub struct ImplicitNamespacePackage { + pub filename: String, +} + impl Violation for ImplicitNamespacePackage { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_pie/rules.rs b/crates/ruff/src/rules/flake8_pie/rules.rs index 389e43b659..a51b93ccbd 100644 --- a/crates/ruff/src/rules/flake8_pie/rules.rs +++ b/crates/ruff/src/rules/flake8_pie/rules.rs @@ -1,5 +1,5 @@ use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use ruff_python::identifiers::is_identifier; use ruff_python::keyword::KWLIST; use rustc_hash::FxHashSet; @@ -17,9 +17,9 @@ use crate::violation::{AlwaysAutofixableViolation, Violation}; use super::fixes; -define_violation!( - pub struct UnnecessaryPass; -); +#[violation] +pub struct UnnecessaryPass; + impl AlwaysAutofixableViolation for UnnecessaryPass { #[derive_message_formats] fn message(&self) -> String { @@ -31,9 +31,9 @@ impl AlwaysAutofixableViolation for UnnecessaryPass { } } -define_violation!( - pub struct DupeClassFieldDefinitions(pub String); -); +#[violation] +pub struct DupeClassFieldDefinitions(pub String); + impl AlwaysAutofixableViolation for DupeClassFieldDefinitions { #[derive_message_formats] fn message(&self) -> String { @@ -47,11 +47,11 @@ impl AlwaysAutofixableViolation for DupeClassFieldDefinitions { } } -define_violation!( - pub struct PreferUniqueEnums { - pub value: String, - } -); +#[violation] +pub struct PreferUniqueEnums { + pub value: String, +} + impl Violation for PreferUniqueEnums { #[derive_message_formats] fn message(&self) -> String { @@ -60,39 +60,39 @@ impl Violation for PreferUniqueEnums { } } -define_violation!( - /// ## What it does - /// Checks for unnecessary list comprehensions passed to `any` and `all`. - /// - /// ## Why is this bad? - /// `any` and `all` take any iterators, including generators. Converting a generator to a list - /// by way of a list comprehension is unnecessary and reduces performance due to the - /// overhead of creating the list. - /// - /// For example, compare the performance of `all` with a list comprehension against that - /// of a generator (~40x faster here): - /// - /// ```console - /// In [1]: %timeit all([i for i in range(1000)]) - /// 8.14 µs ± 25.4 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each) - /// - /// In [2]: %timeit all(i for i in range(1000)) - /// 212 ns ± 0.892 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each) - /// ``` - /// - /// ## Examples - /// ```python - /// any([x.id for x in bar]) - /// all([x.id for x in bar]) - /// ``` - /// - /// Use instead: - /// ```python - /// any(x.id for x in bar) - /// all(x.id for x in bar) - /// ``` - pub struct UnnecessaryComprehensionAnyAll; -); +/// ## What it does +/// Checks for unnecessary list comprehensions passed to `any` and `all`. +/// +/// ## Why is this bad? +/// `any` and `all` take any iterators, including generators. Converting a generator to a list +/// by way of a list comprehension is unnecessary and reduces performance due to the +/// overhead of creating the list. +/// +/// For example, compare the performance of `all` with a list comprehension against that +/// of a generator (~40x faster here): +/// +/// ```console +/// In [1]: %timeit all([i for i in range(1000)]) +/// 8.14 µs ± 25.4 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each) +/// +/// In [2]: %timeit all(i for i in range(1000)) +/// 212 ns ± 0.892 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each) +/// ``` +/// +/// ## Examples +/// ```python +/// any([x.id for x in bar]) +/// all([x.id for x in bar]) +/// ``` +/// +/// Use instead: +/// ```python +/// any(x.id for x in bar) +/// all(x.id for x in bar) +/// ``` +#[violation] +pub struct UnnecessaryComprehensionAnyAll; + impl AlwaysAutofixableViolation for UnnecessaryComprehensionAnyAll { #[derive_message_formats] fn message(&self) -> String { @@ -104,9 +104,9 @@ impl AlwaysAutofixableViolation for UnnecessaryComprehensionAnyAll { } } -define_violation!( - pub struct UnnecessarySpread; -); +#[violation] +pub struct UnnecessarySpread; + impl Violation for UnnecessarySpread { #[derive_message_formats] fn message(&self) -> String { @@ -114,11 +114,11 @@ impl Violation for UnnecessarySpread { } } -define_violation!( - pub struct SingleStartsEndsWith { - pub attr: String, - } -); +#[violation] +pub struct SingleStartsEndsWith { + pub attr: String, +} + impl Violation for SingleStartsEndsWith { #[derive_message_formats] fn message(&self) -> String { @@ -127,9 +127,9 @@ impl Violation for SingleStartsEndsWith { } } -define_violation!( - pub struct UnnecessaryDictKwargs; -); +#[violation] +pub struct UnnecessaryDictKwargs; + impl Violation for UnnecessaryDictKwargs { #[derive_message_formats] fn message(&self) -> String { @@ -137,9 +137,9 @@ impl Violation for UnnecessaryDictKwargs { } } -define_violation!( - pub struct PreferListBuiltin; -); +#[violation] +pub struct PreferListBuiltin; + impl AlwaysAutofixableViolation for PreferListBuiltin { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_print/rules/print_call.rs b/crates/ruff/src/rules/flake8_print/rules/print_call.rs index 820af8dd61..a0fe4ef068 100644 --- a/crates/ruff/src/rules/flake8_print/rules/print_call.rs +++ b/crates/ruff/src/rules/flake8_print/rules/print_call.rs @@ -1,6 +1,6 @@ use rustpython_parser::ast::{Expr, Keyword}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::helpers::is_const_none; use crate::ast::types::Range; @@ -8,9 +8,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct PrintFound; -); +#[violation] +pub struct PrintFound; + impl Violation for PrintFound { #[derive_message_formats] fn message(&self) -> String { @@ -18,9 +18,9 @@ impl Violation for PrintFound { } } -define_violation!( - pub struct PPrintFound; -); +#[violation] +pub struct PPrintFound; + impl Violation for PPrintFound { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_pyi/rules/bad_version_info_comparison.rs b/crates/ruff/src/rules/flake8_pyi/rules/bad_version_info_comparison.rs index 4eb26b147e..293152c236 100644 --- a/crates/ruff/src/rules/flake8_pyi/rules/bad_version_info_comparison.rs +++ b/crates/ruff/src/rules/flake8_pyi/rules/bad_version_info_comparison.rs @@ -1,56 +1,56 @@ use rustpython_parser::ast::{Cmpop, Expr}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; use crate::Range; -define_violation!( - /// ## What it does - /// Checks for usages of comparators other than `<` and `>=` for - /// `sys.version_info` checks in `.pyi` files. All other comparators, such - /// as `>`, `<=`, and `==`, are banned. - /// - /// ## Why is this bad? - /// Comparing `sys.version_info` with `==` or `<=` has unexpected behavior - /// and can lead to bugs. - /// - /// For example, `sys.version_info > (3, 8)` will also match `3.8.10`, - /// while `sys.version_info <= (3, 8)` will _not_ match `3.8.10`: - /// - /// ```python - /// >>> import sys - /// >>> print(sys.version_info) - /// sys.version_info(major=3, minor=8, micro=10, releaselevel='final', serial=0) - /// >>> print(sys.version_info > (3, 8)) - /// True - /// >>> print(sys.version_info == (3, 8)) - /// False - /// >>> print(sys.version_info <= (3, 8)) - /// False - /// >>> print(sys.version_info in (3, 8)) - /// False - /// ``` - /// - /// ## Example - /// ```python - /// import sys - /// - /// if sys.version_info > (3, 8): - /// ... - /// ``` - /// - /// Use instead: - /// ```python - /// import sys - /// - /// if sys.version_info >= (3, 9): - /// ... - /// ``` - pub struct BadVersionInfoComparison; -); +/// ## What it does +/// Checks for usages of comparators other than `<` and `>=` for +/// `sys.version_info` checks in `.pyi` files. All other comparators, such +/// as `>`, `<=`, and `==`, are banned. +/// +/// ## Why is this bad? +/// Comparing `sys.version_info` with `==` or `<=` has unexpected behavior +/// and can lead to bugs. +/// +/// For example, `sys.version_info > (3, 8)` will also match `3.8.10`, +/// while `sys.version_info <= (3, 8)` will _not_ match `3.8.10`: +/// +/// ```python +/// >>> import sys +/// >>> print(sys.version_info) +/// sys.version_info(major=3, minor=8, micro=10, releaselevel='final', serial=0) +/// >>> print(sys.version_info > (3, 8)) +/// True +/// >>> print(sys.version_info == (3, 8)) +/// False +/// >>> print(sys.version_info <= (3, 8)) +/// False +/// >>> print(sys.version_info in (3, 8)) +/// False +/// ``` +/// +/// ## Example +/// ```python +/// import sys +/// +/// if sys.version_info > (3, 8): +/// ... +/// ``` +/// +/// Use instead: +/// ```python +/// import sys +/// +/// if sys.version_info >= (3, 9): +/// ... +/// ``` +#[violation] +pub struct BadVersionInfoComparison; + impl Violation for BadVersionInfoComparison { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_pyi/rules/docstring_in_stubs.rs b/crates/ruff/src/rules/flake8_pyi/rules/docstring_in_stubs.rs index 7265f585f3..c71350094a 100644 --- a/crates/ruff/src/rules/flake8_pyi/rules/docstring_in_stubs.rs +++ b/crates/ruff/src/rules/flake8_pyi/rules/docstring_in_stubs.rs @@ -1,15 +1,15 @@ use rustpython_parser::ast::Expr; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct DocstringInStub; -); +#[violation] +pub struct DocstringInStub; + impl Violation for DocstringInStub { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_pyi/rules/non_empty_stub_body.rs b/crates/ruff/src/rules/flake8_pyi/rules/non_empty_stub_body.rs index 2a064a9387..9dad99ed51 100644 --- a/crates/ruff/src/rules/flake8_pyi/rules/non_empty_stub_body.rs +++ b/crates/ruff/src/rules/flake8_pyi/rules/non_empty_stub_body.rs @@ -1,15 +1,15 @@ use rustpython_parser::ast::{Constant, ExprKind, Stmt, StmtKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct NonEmptyStubBody; -); +#[violation] +pub struct NonEmptyStubBody; + impl Violation for NonEmptyStubBody { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_pyi/rules/pass_statement_stub_body.rs b/crates/ruff/src/rules/flake8_pyi/rules/pass_statement_stub_body.rs index 31693ae314..ca559e71c8 100644 --- a/crates/ruff/src/rules/flake8_pyi/rules/pass_statement_stub_body.rs +++ b/crates/ruff/src/rules/flake8_pyi/rules/pass_statement_stub_body.rs @@ -1,15 +1,15 @@ use rustpython_parser::ast::{Stmt, StmtKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct PassStatementStubBody; -); +#[violation] +pub struct PassStatementStubBody; + impl Violation for PassStatementStubBody { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_pyi/rules/prefix_type_params.rs b/crates/ruff/src/rules/flake8_pyi/rules/prefix_type_params.rs index e5f9911f0e..89550bbef5 100644 --- a/crates/ruff/src/rules/flake8_pyi/rules/prefix_type_params.rs +++ b/crates/ruff/src/rules/flake8_pyi/rules/prefix_type_params.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use serde::{Deserialize, Serialize}; use std::fmt; @@ -25,32 +25,32 @@ impl fmt::Display for VarKind { } } -define_violation!( - /// ## What it does - /// Checks that type `TypeVar`, `ParamSpec`, and `TypeVarTuple` definitions in - /// stubs are prefixed with `_`. - /// - /// ## Why is this bad? - /// By prefixing type parameters with `_`, we can avoid accidentally exposing - /// names internal to the stub. - /// - /// ## Example - /// ```python - /// from typing import TypeVar - /// - /// T = TypeVar("T") - /// ``` - /// - /// Use instead: - /// ```python - /// from typing import TypeVar - /// - /// _T = TypeVar("_T") - /// ``` - pub struct PrefixTypeParams { - pub kind: VarKind, - } -); +/// ## What it does +/// Checks that type `TypeVar`, `ParamSpec`, and `TypeVarTuple` definitions in +/// stubs are prefixed with `_`. +/// +/// ## Why is this bad? +/// By prefixing type parameters with `_`, we can avoid accidentally exposing +/// names internal to the stub. +/// +/// ## Example +/// ```python +/// from typing import TypeVar +/// +/// T = TypeVar("T") +/// ``` +/// +/// Use instead: +/// ```python +/// from typing import TypeVar +/// +/// _T = TypeVar("_T") +/// ``` +#[violation] +pub struct PrefixTypeParams { + pub kind: VarKind, +} + impl Violation for PrefixTypeParams { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_pyi/rules/simple_defaults.rs b/crates/ruff/src/rules/flake8_pyi/rules/simple_defaults.rs index b411366d96..55089b4b09 100644 --- a/crates/ruff/src/rules/flake8_pyi/rules/simple_defaults.rs +++ b/crates/ruff/src/rules/flake8_pyi/rules/simple_defaults.rs @@ -1,15 +1,15 @@ use rustpython_parser::ast::{Arguments, Constant, Expr, ExprKind, Operator, Unaryop}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct TypedArgumentSimpleDefaults; -); +#[violation] +pub struct TypedArgumentSimpleDefaults; + /// PYI011 impl Violation for TypedArgumentSimpleDefaults { #[derive_message_formats] @@ -18,9 +18,9 @@ impl Violation for TypedArgumentSimpleDefaults { } } -define_violation!( - pub struct ArgumentSimpleDefaults; -); +#[violation] +pub struct ArgumentSimpleDefaults; + /// PYI014 impl Violation for ArgumentSimpleDefaults { #[derive_message_formats] diff --git a/crates/ruff/src/rules/flake8_pyi/rules/unrecognized_platform.rs b/crates/ruff/src/rules/flake8_pyi/rules/unrecognized_platform.rs index b591b7c15b..03dd68d1d3 100644 --- a/crates/ruff/src/rules/flake8_pyi/rules/unrecognized_platform.rs +++ b/crates/ruff/src/rules/flake8_pyi/rules/unrecognized_platform.rs @@ -1,48 +1,48 @@ use rustpython_parser::ast::{Cmpop, Constant, Expr, ExprKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; use crate::registry::{Diagnostic, Rule}; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Check for unrecognized `sys.platform` checks. Platform checks should be - /// simple string comparisons. - /// - /// **Note**: this rule is only enabled in `.pyi` stub files. - /// - /// ## Why is this bad? - /// Some `sys.platform` checks are too complex for type checkers to - /// understand, and thus result in false positives. `sys.platform` checks - /// should be simple string comparisons, like `sys.platform == "linux"`. - /// - /// ## Example - /// ```python - /// if sys.platform.startswith("linux"): - /// # Linux specific definitions - /// ... - /// else: - /// # Posix specific definitions - /// ... - /// ``` - /// - /// Instead, use a simple string comparison, such as `==` or `!=`: - /// ```python - /// if sys.platform == "linux": - /// # Linux specific definitions - /// ... - /// else: - /// # Posix specific definitions - /// ... - /// ``` - /// - /// ## References - /// - [PEP 484](https://peps.python.org/pep-0484/#version-and-platform-checking) - pub struct UnrecognizedPlatformCheck; -); +/// ## What it does +/// Check for unrecognized `sys.platform` checks. Platform checks should be +/// simple string comparisons. +/// +/// **Note**: this rule is only enabled in `.pyi` stub files. +/// +/// ## Why is this bad? +/// Some `sys.platform` checks are too complex for type checkers to +/// understand, and thus result in false positives. `sys.platform` checks +/// should be simple string comparisons, like `sys.platform == "linux"`. +/// +/// ## Example +/// ```python +/// if sys.platform.startswith("linux"): +/// # Linux specific definitions +/// ... +/// else: +/// # Posix specific definitions +/// ... +/// ``` +/// +/// Instead, use a simple string comparison, such as `==` or `!=`: +/// ```python +/// if sys.platform == "linux": +/// # Linux specific definitions +/// ... +/// else: +/// # Posix specific definitions +/// ... +/// ``` +/// +/// ## References +/// - [PEP 484](https://peps.python.org/pep-0484/#version-and-platform-checking) +#[violation] +pub struct UnrecognizedPlatformCheck; + impl Violation for UnrecognizedPlatformCheck { #[derive_message_formats] fn message(&self) -> String { @@ -50,37 +50,37 @@ impl Violation for UnrecognizedPlatformCheck { } } -define_violation!( - /// ## What it does - /// Check for unrecognized platform names in `sys.platform` checks. - /// - /// **Note**: this rule is only enabled in `.pyi` stub files. - /// - /// ## Why is this bad? - /// If a `sys.platform` check compares to a platform name outside of a - /// small set of known platforms (e.g. "linux", "win32", etc.), it's likely - /// a typo or a platform name that is not recognized by type checkers. - /// - /// The list of known platforms is: "linux", "win32", "cygwin", "darwin". - /// - /// ## Example - /// ```python - /// if sys.platform == "linus": - /// ... - /// ``` - /// - /// Use instead: - /// ```python - /// if sys.platform == "linux": - /// ... - /// ``` - /// - /// ## References - /// - [PEP 484](https://peps.python.org/pep-0484/#version-and-platform-checking) - pub struct UnrecognizedPlatformName { - pub platform: String, - } -); +/// ## What it does +/// Check for unrecognized platform names in `sys.platform` checks. +/// +/// **Note**: this rule is only enabled in `.pyi` stub files. +/// +/// ## Why is this bad? +/// If a `sys.platform` check compares to a platform name outside of a +/// small set of known platforms (e.g. "linux", "win32", etc.), it's likely +/// a typo or a platform name that is not recognized by type checkers. +/// +/// The list of known platforms is: "linux", "win32", "cygwin", "darwin". +/// +/// ## Example +/// ```python +/// if sys.platform == "linus": +/// ... +/// ``` +/// +/// Use instead: +/// ```python +/// if sys.platform == "linux": +/// ... +/// ``` +/// +/// ## References +/// - [PEP 484](https://peps.python.org/pep-0484/#version-and-platform-checking) +#[violation] +pub struct UnrecognizedPlatformName { + pub platform: String, +} + impl Violation for UnrecognizedPlatformName { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_pytest_style/rules/assertion.rs b/crates/ruff/src/rules/flake8_pytest_style/rules/assertion.rs index fc01b9a840..2bde099fdc 100644 --- a/crates/ruff/src/rules/flake8_pytest_style/rules/assertion.rs +++ b/crates/ruff/src/rules/flake8_pytest_style/rules/assertion.rs @@ -10,7 +10,7 @@ use rustpython_parser::ast::{ Unaryop, }; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::helpers::{has_comments_in, unparse_stmt}; use crate::ast::types::Range; @@ -26,39 +26,39 @@ use crate::violation::{AutofixKind, Availability, Violation}; use super::helpers::is_falsy_constant; use super::unittest_assert::UnittestAssert; -define_violation!( - /// ## What it does - /// Checks for assertions that combine multiple independent conditions. - /// - /// ## Why is this bad? - /// Composite assertion statements are harder debug upon failure, as the - /// failure message will not indicate which condition failed. - /// - /// ## Example - /// ```python - /// def test_foo(): - /// assert something and something_else - /// - /// - /// def test_bar(): - /// assert not (something or something_else) - /// ``` - /// - /// Use instead: - /// ```python - /// def test_foo(): - /// assert something - /// assert something_else - /// - /// - /// def test_bar(): - /// assert not something - /// assert not something_else - /// ``` - pub struct CompositeAssertion { - pub fixable: bool, - } -); +/// ## What it does +/// Checks for assertions that combine multiple independent conditions. +/// +/// ## Why is this bad? +/// Composite assertion statements are harder debug upon failure, as the +/// failure message will not indicate which condition failed. +/// +/// ## Example +/// ```python +/// def test_foo(): +/// assert something and something_else +/// +/// +/// def test_bar(): +/// assert not (something or something_else) +/// ``` +/// +/// Use instead: +/// ```python +/// def test_foo(): +/// assert something +/// assert something_else +/// +/// +/// def test_bar(): +/// assert not something +/// assert not something_else +/// ``` +#[violation] +pub struct CompositeAssertion { + pub fixable: bool, +} + impl Violation for CompositeAssertion { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Sometimes)); @@ -73,11 +73,11 @@ impl Violation for CompositeAssertion { } } -define_violation!( - pub struct AssertInExcept { - pub name: String, - } -); +#[violation] +pub struct AssertInExcept { + pub name: String, +} + impl Violation for AssertInExcept { #[derive_message_formats] fn message(&self) -> String { @@ -88,9 +88,9 @@ impl Violation for AssertInExcept { } } -define_violation!( - pub struct AssertAlwaysFalse; -); +#[violation] +pub struct AssertAlwaysFalse; + impl Violation for AssertAlwaysFalse { #[derive_message_formats] fn message(&self) -> String { @@ -98,12 +98,12 @@ impl Violation for AssertAlwaysFalse { } } -define_violation!( - pub struct UnittestAssertion { - pub assertion: String, - pub fixable: bool, - } -); +#[violation] +pub struct UnittestAssertion { + pub assertion: String, + pub fixable: bool, +} + impl Violation for UnittestAssertion { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Sometimes)); diff --git a/crates/ruff/src/rules/flake8_pytest_style/rules/fail.rs b/crates/ruff/src/rules/flake8_pytest_style/rules/fail.rs index 046755e079..0233712c92 100644 --- a/crates/ruff/src/rules/flake8_pytest_style/rules/fail.rs +++ b/crates/ruff/src/rules/flake8_pytest_style/rules/fail.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, Keyword}; use super::helpers::{is_empty_or_null_string, is_pytest_fail}; @@ -8,9 +8,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct FailWithoutMessage; -); +#[violation] +pub struct FailWithoutMessage; + impl Violation for FailWithoutMessage { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_pytest_style/rules/fixture.rs b/crates/ruff/src/rules/flake8_pytest_style/rules/fixture.rs index 9a74f86599..6a41096302 100644 --- a/crates/ruff/src/rules/flake8_pytest_style/rules/fixture.rs +++ b/crates/ruff/src/rules/flake8_pytest_style/rules/fixture.rs @@ -1,6 +1,6 @@ use anyhow::Result; use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Arguments, Expr, ExprKind, Keyword, Location, Stmt, StmtKind}; use super::helpers::{ @@ -18,12 +18,12 @@ use crate::registry::{Diagnostic, Rule}; use crate::source_code::Locator; use crate::violation::{AlwaysAutofixableViolation, Violation}; -define_violation!( - pub struct IncorrectFixtureParenthesesStyle { - pub expected_parens: String, - pub actual_parens: String, - } -); +#[violation] +pub struct IncorrectFixtureParenthesesStyle { + pub expected_parens: String, + pub actual_parens: String, +} + impl AlwaysAutofixableViolation for IncorrectFixtureParenthesesStyle { #[derive_message_formats] fn message(&self) -> String { @@ -39,11 +39,11 @@ impl AlwaysAutofixableViolation for IncorrectFixtureParenthesesStyle { } } -define_violation!( - pub struct FixturePositionalArgs { - pub function: String, - } -); +#[violation] +pub struct FixturePositionalArgs { + pub function: String, +} + impl Violation for FixturePositionalArgs { #[derive_message_formats] fn message(&self) -> String { @@ -52,9 +52,9 @@ impl Violation for FixturePositionalArgs { } } -define_violation!( - pub struct ExtraneousScopeFunction; -); +#[violation] +pub struct ExtraneousScopeFunction; + impl AlwaysAutofixableViolation for ExtraneousScopeFunction { #[derive_message_formats] fn message(&self) -> String { @@ -66,11 +66,11 @@ impl AlwaysAutofixableViolation for ExtraneousScopeFunction { } } -define_violation!( - pub struct MissingFixtureNameUnderscore { - pub function: String, - } -); +#[violation] +pub struct MissingFixtureNameUnderscore { + pub function: String, +} + impl Violation for MissingFixtureNameUnderscore { #[derive_message_formats] fn message(&self) -> String { @@ -79,11 +79,11 @@ impl Violation for MissingFixtureNameUnderscore { } } -define_violation!( - pub struct IncorrectFixtureNameUnderscore { - pub function: String, - } -); +#[violation] +pub struct IncorrectFixtureNameUnderscore { + pub function: String, +} + impl Violation for IncorrectFixtureNameUnderscore { #[derive_message_formats] fn message(&self) -> String { @@ -92,11 +92,11 @@ impl Violation for IncorrectFixtureNameUnderscore { } } -define_violation!( - pub struct FixtureParamWithoutValue { - pub name: String, - } -); +#[violation] +pub struct FixtureParamWithoutValue { + pub name: String, +} + impl Violation for FixtureParamWithoutValue { #[derive_message_formats] fn message(&self) -> String { @@ -108,9 +108,9 @@ impl Violation for FixtureParamWithoutValue { } } -define_violation!( - pub struct DeprecatedYieldFixture; -); +#[violation] +pub struct DeprecatedYieldFixture; + impl Violation for DeprecatedYieldFixture { #[derive_message_formats] fn message(&self) -> String { @@ -118,9 +118,9 @@ impl Violation for DeprecatedYieldFixture { } } -define_violation!( - pub struct FixtureFinalizerCallback; -); +#[violation] +pub struct FixtureFinalizerCallback; + impl Violation for FixtureFinalizerCallback { #[derive_message_formats] fn message(&self) -> String { @@ -128,11 +128,11 @@ impl Violation for FixtureFinalizerCallback { } } -define_violation!( - pub struct UselessYieldFixture { - pub name: String, - } -); +#[violation] +pub struct UselessYieldFixture { + pub name: String, +} + impl AlwaysAutofixableViolation for UselessYieldFixture { #[derive_message_formats] fn message(&self) -> String { @@ -145,9 +145,9 @@ impl AlwaysAutofixableViolation for UselessYieldFixture { } } -define_violation!( - pub struct ErroneousUseFixturesOnFixture; -); +#[violation] +pub struct ErroneousUseFixturesOnFixture; + impl AlwaysAutofixableViolation for ErroneousUseFixturesOnFixture { #[derive_message_formats] fn message(&self) -> String { @@ -159,9 +159,9 @@ impl AlwaysAutofixableViolation for ErroneousUseFixturesOnFixture { } } -define_violation!( - pub struct UnnecessaryAsyncioMarkOnFixture; -); +#[violation] +pub struct UnnecessaryAsyncioMarkOnFixture; + impl AlwaysAutofixableViolation for UnnecessaryAsyncioMarkOnFixture { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_pytest_style/rules/imports.rs b/crates/ruff/src/rules/flake8_pytest_style/rules/imports.rs index a46671f089..eed821d5b7 100644 --- a/crates/ruff/src/rules/flake8_pytest_style/rules/imports.rs +++ b/crates/ruff/src/rules/flake8_pytest_style/rules/imports.rs @@ -1,13 +1,13 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Stmt; use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct IncorrectPytestImport; -); +#[violation] +pub struct IncorrectPytestImport; + impl Violation for IncorrectPytestImport { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_pytest_style/rules/marks.rs b/crates/ruff/src/rules/flake8_pytest_style/rules/marks.rs index 7ffa9aff0b..29cb185d58 100644 --- a/crates/ruff/src/rules/flake8_pytest_style/rules/marks.rs +++ b/crates/ruff/src/rules/flake8_pytest_style/rules/marks.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind, Location}; use super::helpers::{get_mark_decorators, get_mark_name}; @@ -8,13 +8,13 @@ use crate::fix::Fix; use crate::registry::{Diagnostic, Rule}; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct IncorrectMarkParenthesesStyle { - pub mark_name: String, - pub expected_parens: String, - pub actual_parens: String, - } -); +#[violation] +pub struct IncorrectMarkParenthesesStyle { + pub mark_name: String, + pub expected_parens: String, + pub actual_parens: String, +} + impl AlwaysAutofixableViolation for IncorrectMarkParenthesesStyle { #[derive_message_formats] fn message(&self) -> String { @@ -34,9 +34,9 @@ impl AlwaysAutofixableViolation for IncorrectMarkParenthesesStyle { } } -define_violation!( - pub struct UseFixturesWithoutParameters; -); +#[violation] +pub struct UseFixturesWithoutParameters; + impl AlwaysAutofixableViolation for UseFixturesWithoutParameters { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_pytest_style/rules/parametrize.rs b/crates/ruff/src/rules/flake8_pytest_style/rules/parametrize.rs index b3637456c2..8e4d120d43 100644 --- a/crates/ruff/src/rules/flake8_pytest_style/rules/parametrize.rs +++ b/crates/ruff/src/rules/flake8_pytest_style/rules/parametrize.rs @@ -1,6 +1,6 @@ use rustpython_parser::ast::{Constant, Expr, ExprContext, ExprKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::helpers::{create_expr, unparse_expr}; use crate::ast::types::Range; @@ -12,11 +12,11 @@ use crate::violation::{AlwaysAutofixableViolation, Violation}; use super::super::types; use super::helpers::{is_pytest_parametrize, split_names}; -define_violation!( - pub struct ParametrizeNamesWrongType { - pub expected: types::ParametrizeNameType, - } -); +#[violation] +pub struct ParametrizeNamesWrongType { + pub expected: types::ParametrizeNameType, +} + impl AlwaysAutofixableViolation for ParametrizeNamesWrongType { #[derive_message_formats] fn message(&self) -> String { @@ -30,12 +30,12 @@ impl AlwaysAutofixableViolation for ParametrizeNamesWrongType { } } -define_violation!( - pub struct ParametrizeValuesWrongType { - pub values: types::ParametrizeValuesType, - pub row: types::ParametrizeValuesRowType, - } -); +#[violation] +pub struct ParametrizeValuesWrongType { + pub values: types::ParametrizeValuesType, + pub row: types::ParametrizeValuesRowType, +} + impl Violation for ParametrizeValuesWrongType { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_pytest_style/rules/patch.rs b/crates/ruff/src/rules/flake8_pytest_style/rules/patch.rs index 1cde90afc9..044fcac691 100644 --- a/crates/ruff/src/rules/flake8_pytest_style/rules/patch.rs +++ b/crates/ruff/src/rules/flake8_pytest_style/rules/patch.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustc_hash::FxHashSet; use rustpython_parser::ast::{Expr, ExprKind, Keyword}; @@ -9,9 +9,9 @@ use crate::ast::visitor::Visitor; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct PatchWithLambda; -); +#[violation] +pub struct PatchWithLambda; + impl Violation for PatchWithLambda { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_pytest_style/rules/raises.rs b/crates/ruff/src/rules/flake8_pytest_style/rules/raises.rs index 73fdbb1ab3..b19c55ad60 100644 --- a/crates/ruff/src/rules/flake8_pytest_style/rules/raises.rs +++ b/crates/ruff/src/rules/flake8_pytest_style/rules/raises.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind, Keyword, Stmt, StmtKind, Withitem}; use super::helpers::is_empty_or_null_string; @@ -8,9 +8,9 @@ use crate::checkers::ast::Checker; use crate::registry::{Diagnostic, Rule}; use crate::violation::Violation; -define_violation!( - pub struct RaisesWithMultipleStatements; -); +#[violation] +pub struct RaisesWithMultipleStatements; + impl Violation for RaisesWithMultipleStatements { #[derive_message_formats] fn message(&self) -> String { @@ -18,11 +18,11 @@ impl Violation for RaisesWithMultipleStatements { } } -define_violation!( - pub struct RaisesTooBroad { - pub exception: String, - } -); +#[violation] +pub struct RaisesTooBroad { + pub exception: String, +} + impl Violation for RaisesTooBroad { #[derive_message_formats] fn message(&self) -> String { @@ -34,9 +34,9 @@ impl Violation for RaisesTooBroad { } } -define_violation!( - pub struct RaisesWithoutException; -); +#[violation] +pub struct RaisesWithoutException; + impl Violation for RaisesWithoutException { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_quotes/rules.rs b/crates/ruff/src/rules/flake8_quotes/rules.rs index 191cc6b7c0..f2b3c10e23 100644 --- a/crates/ruff/src/rules/flake8_quotes/rules.rs +++ b/crates/ruff/src/rules/flake8_quotes/rules.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Location; use rustpython_parser::lexer::LexResult; use rustpython_parser::Tok; @@ -12,31 +12,31 @@ use crate::settings::{flags, Settings}; use crate::source_code::Locator; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - /// ## What it does - /// Checks for inline strings that use single quotes or double quotes, - /// depending on the value of the [`flake8-quotes.inline-quotes`] option. - /// - /// ## Why is this bad? - /// Consistency is good. Use either single or double quotes for inline - /// strings, but be consistent. - /// - /// ## Options - /// - `flake8-quotes.inline-quotes` - /// - /// ## Example - /// ```python - /// foo = 'bar' - /// ``` - /// - /// Assuming `inline-quotes` is set to `double`, use instead: - /// ```python - /// foo = "bar" - /// ``` - pub struct BadQuotesInlineString { - pub quote: Quote, - } -); +/// ## What it does +/// Checks for inline strings that use single quotes or double quotes, +/// depending on the value of the [`flake8-quotes.inline-quotes`] option. +/// +/// ## Why is this bad? +/// Consistency is good. Use either single or double quotes for inline +/// strings, but be consistent. +/// +/// ## Options +/// - `flake8-quotes.inline-quotes` +/// +/// ## Example +/// ```python +/// foo = 'bar' +/// ``` +/// +/// Assuming `inline-quotes` is set to `double`, use instead: +/// ```python +/// foo = "bar" +/// ``` +#[violation] +pub struct BadQuotesInlineString { + pub quote: Quote, +} + impl AlwaysAutofixableViolation for BadQuotesInlineString { #[derive_message_formats] fn message(&self) -> String { @@ -56,36 +56,36 @@ impl AlwaysAutofixableViolation for BadQuotesInlineString { } } -define_violation!( - /// ## What it does - /// Checks for multiline strings that use single quotes or double quotes, - /// depending on the value of the [`flake8-quotes.multiline-quotes`] - /// setting. - /// - /// ## Why is this bad? - /// Consistency is good. Use either single or double quotes for multiline - /// strings, but be consistent. - /// - /// ## Options - /// - `flake8-quotes.multiline-quotes` - /// - /// ## Example - /// ```python - /// foo = ''' - /// bar - /// ''' - /// ``` - /// - /// Assuming `multiline-quotes` is set to `double`, use instead: - /// ```python - /// foo = """ - /// bar - /// """ - /// ``` - pub struct BadQuotesMultilineString { - pub quote: Quote, - } -); +/// ## What it does +/// Checks for multiline strings that use single quotes or double quotes, +/// depending on the value of the [`flake8-quotes.multiline-quotes`] +/// setting. +/// +/// ## Why is this bad? +/// Consistency is good. Use either single or double quotes for multiline +/// strings, but be consistent. +/// +/// ## Options +/// - `flake8-quotes.multiline-quotes` +/// +/// ## Example +/// ```python +/// foo = ''' +/// bar +/// ''' +/// ``` +/// +/// Assuming `multiline-quotes` is set to `double`, use instead: +/// ```python +/// foo = """ +/// bar +/// """ +/// ``` +#[violation] +pub struct BadQuotesMultilineString { + pub quote: Quote, +} + impl AlwaysAutofixableViolation for BadQuotesMultilineString { #[derive_message_formats] fn message(&self) -> String { @@ -105,35 +105,35 @@ impl AlwaysAutofixableViolation for BadQuotesMultilineString { } } -define_violation!( - /// ## What it does - /// Checks for docstrings that use single quotes or double quotes, depending - /// on the value of the [`flake8-quotes.docstring-quotes`] setting. - /// - /// ## Why is this bad? - /// Consistency is good. Use either single or double quotes for docstring - /// strings, but be consistent. - /// - /// ## Options - /// - `flake8-quotes.docstring-quotes` - /// - /// ## Example - /// ```python - /// ''' - /// bar - /// ''' - /// ``` - /// - /// Assuming `docstring-quotes` is set to `double`, use instead: - /// ```python - /// """ - /// bar - /// """ - /// ``` - pub struct BadQuotesDocstring { - pub quote: Quote, - } -); +/// ## What it does +/// Checks for docstrings that use single quotes or double quotes, depending +/// on the value of the [`flake8-quotes.docstring-quotes`] setting. +/// +/// ## Why is this bad? +/// Consistency is good. Use either single or double quotes for docstring +/// strings, but be consistent. +/// +/// ## Options +/// - `flake8-quotes.docstring-quotes` +/// +/// ## Example +/// ```python +/// ''' +/// bar +/// ''' +/// ``` +/// +/// Assuming `docstring-quotes` is set to `double`, use instead: +/// ```python +/// """ +/// bar +/// """ +/// ``` +#[violation] +pub struct BadQuotesDocstring { + pub quote: Quote, +} + impl AlwaysAutofixableViolation for BadQuotesDocstring { #[derive_message_formats] fn message(&self) -> String { @@ -153,26 +153,26 @@ impl AlwaysAutofixableViolation for BadQuotesDocstring { } } -define_violation!( - /// ## What it does - /// Checks for strings that include escaped quotes, and suggests changing - /// the quote style to avoid the need to escape them. - /// - /// ## Why is this bad? - /// It's preferable to avoid escaped quotes in strings. By changing the - /// outer quote style, you can avoid escaping inner quotes. - /// - /// ## Example - /// ```python - /// foo = 'bar\'s' - /// ``` - /// - /// Use instead: - /// ```python - /// foo = "bar's" - /// ``` - pub struct AvoidableEscapedQuote; -); +/// ## What it does +/// Checks for strings that include escaped quotes, and suggests changing +/// the quote style to avoid the need to escape them. +/// +/// ## Why is this bad? +/// It's preferable to avoid escaped quotes in strings. By changing the +/// outer quote style, you can avoid escaping inner quotes. +/// +/// ## Example +/// ```python +/// foo = 'bar\'s' +/// ``` +/// +/// Use instead: +/// ```python +/// foo = "bar's" +/// ``` +#[violation] +pub struct AvoidableEscapedQuote; + impl AlwaysAutofixableViolation for AvoidableEscapedQuote { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_raise/rules/unnecessary_paren_on_raise_exception.rs b/crates/ruff/src/rules/flake8_raise/rules/unnecessary_paren_on_raise_exception.rs index f14fd9eef4..d70eea62e8 100644 --- a/crates/ruff/src/rules/flake8_raise/rules/unnecessary_paren_on_raise_exception.rs +++ b/crates/ruff/src/rules/flake8_raise/rules/unnecessary_paren_on_raise_exception.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use crate::ast::helpers::match_parens; @@ -7,9 +7,9 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct UnnecessaryParenOnRaiseException; -); +#[violation] +pub struct UnnecessaryParenOnRaiseException; + impl AlwaysAutofixableViolation for UnnecessaryParenOnRaiseException { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_return/rules.rs b/crates/ruff/src/rules/flake8_return/rules.rs index 01d7412d5c..26a26e50ad 100644 --- a/crates/ruff/src/rules/flake8_return/rules.rs +++ b/crates/ruff/src/rules/flake8_return/rules.rs @@ -1,7 +1,7 @@ use itertools::Itertools; use rustpython_parser::ast::{Constant, Expr, ExprKind, Location, Stmt, StmtKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::helpers::{elif_else_range, end_of_statement}; use crate::ast::types::Range; @@ -16,9 +16,9 @@ use super::branch::Branch; use super::helpers::result_exists; use super::visitor::{ReturnVisitor, Stack}; -define_violation!( - pub struct UnnecessaryReturnNone; -); +#[violation] +pub struct UnnecessaryReturnNone; + impl AlwaysAutofixableViolation for UnnecessaryReturnNone { #[derive_message_formats] fn message(&self) -> String { @@ -32,9 +32,9 @@ impl AlwaysAutofixableViolation for UnnecessaryReturnNone { } } -define_violation!( - pub struct ImplicitReturnValue; -); +#[violation] +pub struct ImplicitReturnValue; + impl AlwaysAutofixableViolation for ImplicitReturnValue { #[derive_message_formats] fn message(&self) -> String { @@ -46,9 +46,9 @@ impl AlwaysAutofixableViolation for ImplicitReturnValue { } } -define_violation!( - pub struct ImplicitReturn; -); +#[violation] +pub struct ImplicitReturn; + impl AlwaysAutofixableViolation for ImplicitReturn { #[derive_message_formats] fn message(&self) -> String { @@ -60,9 +60,9 @@ impl AlwaysAutofixableViolation for ImplicitReturn { } } -define_violation!( - pub struct UnnecessaryAssign; -); +#[violation] +pub struct UnnecessaryAssign; + impl Violation for UnnecessaryAssign { #[derive_message_formats] fn message(&self) -> String { @@ -70,11 +70,11 @@ impl Violation for UnnecessaryAssign { } } -define_violation!( - pub struct SuperfluousElseReturn { - pub branch: Branch, - } -); +#[violation] +pub struct SuperfluousElseReturn { + pub branch: Branch, +} + impl Violation for SuperfluousElseReturn { #[derive_message_formats] fn message(&self) -> String { @@ -83,11 +83,11 @@ impl Violation for SuperfluousElseReturn { } } -define_violation!( - pub struct SuperfluousElseRaise { - pub branch: Branch, - } -); +#[violation] +pub struct SuperfluousElseRaise { + pub branch: Branch, +} + impl Violation for SuperfluousElseRaise { #[derive_message_formats] fn message(&self) -> String { @@ -96,11 +96,11 @@ impl Violation for SuperfluousElseRaise { } } -define_violation!( - pub struct SuperfluousElseContinue { - pub branch: Branch, - } -); +#[violation] +pub struct SuperfluousElseContinue { + pub branch: Branch, +} + impl Violation for SuperfluousElseContinue { #[derive_message_formats] fn message(&self) -> String { @@ -109,11 +109,11 @@ impl Violation for SuperfluousElseContinue { } } -define_violation!( - pub struct SuperfluousElseBreak { - pub branch: Branch, - } -); +#[violation] +pub struct SuperfluousElseBreak { + pub branch: Branch, +} + impl Violation for SuperfluousElseBreak { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_self/rules/private_member_access.rs b/crates/ruff/src/rules/flake8_self/rules/private_member_access.rs index d8828c7777..3197c6b537 100644 --- a/crates/ruff/src/rules/flake8_self/rules/private_member_access.rs +++ b/crates/ruff/src/rules/flake8_self/rules/private_member_access.rs @@ -1,6 +1,6 @@ use rustpython_parser::ast::{Expr, ExprKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::helpers::collect_call_path; use crate::ast::types::{Range, ScopeKind}; @@ -8,51 +8,51 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for accesses on "private" class members. - /// - /// ## Why is this bad? - /// In Python, the convention is such that class members that are prefixed - /// with a single underscore, or prefixed but not suffixed with a double - /// underscore, are considered private and intended for internal use. - /// - /// Using such "private" members is considered a misuse of the class, as - /// there are no guarantees that the member will be present in future - /// versions, that it will have the same type, or that it will have the same - /// behavior. Instead, use the class's public interface. - /// - /// ## Options - /// - `flake8-self.ignore-names` - /// - /// ## Example - /// ```python - /// class Class: - /// def __init__(self): - /// self._private_member = "..." - /// - /// - /// var = Class() - /// print(var._private_member) - /// ``` - /// - /// Use instead: - /// ```python - /// class Class: - /// def __init__(self): - /// self.public_member = "..." - /// - /// - /// var = Class() - /// print(var.public_member) - /// ``` - /// - /// ## References - /// - [_What is the meaning of single or double underscores before an object name?_](https://stackoverflow.com/questions/1301346/what-is-the-meaning-of-single-and-double-underscore-before-an-object-name) - pub struct PrivateMemberAccess { - pub access: String, - } -); +/// ## What it does +/// Checks for accesses on "private" class members. +/// +/// ## Why is this bad? +/// In Python, the convention is such that class members that are prefixed +/// with a single underscore, or prefixed but not suffixed with a double +/// underscore, are considered private and intended for internal use. +/// +/// Using such "private" members is considered a misuse of the class, as +/// there are no guarantees that the member will be present in future +/// versions, that it will have the same type, or that it will have the same +/// behavior. Instead, use the class's public interface. +/// +/// ## Options +/// - `flake8-self.ignore-names` +/// +/// ## Example +/// ```python +/// class Class: +/// def __init__(self): +/// self._private_member = "..." +/// +/// +/// var = Class() +/// print(var._private_member) +/// ``` +/// +/// Use instead: +/// ```python +/// class Class: +/// def __init__(self): +/// self.public_member = "..." +/// +/// +/// var = Class() +/// print(var.public_member) +/// ``` +/// +/// ## References +/// - [_What is the meaning of single or double underscores before an object name?_](https://stackoverflow.com/questions/1301346/what-is-the-meaning-of-single-and-double-underscore-before-an-object-name) +#[violation] +pub struct PrivateMemberAccess { + pub access: String, +} + impl Violation for PrivateMemberAccess { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_simplify/rules/ast_bool_op.rs b/crates/ruff/src/rules/flake8_simplify/rules/ast_bool_op.rs index d98b2db3a7..4511171404 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/ast_bool_op.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/ast_bool_op.rs @@ -2,7 +2,7 @@ use std::collections::BTreeMap; use std::iter; use itertools::Either::{Left, Right}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Boolop, Cmpop, Constant, Expr, ExprContext, ExprKind, Unaryop}; use crate::ast::helpers::{contains_effect, create_expr, has_comments, unparse_expr}; @@ -12,37 +12,37 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - /// ## What it does - /// Checks for multiple `isinstance` calls on the same target. - /// - /// ## Why is this bad? - /// To check if an object is an instance of any one of multiple types - /// or classes, it is unnecessary to use multiple `isinstance` calls, as - /// the second argument of the `isinstance` built-in function accepts a - /// tuple of types and classes. - /// - /// Using a single `isinstance` call implements the same behavior with more - /// concise code and clearer intent. - /// - /// ## Example - /// ```python - /// if isinstance(obj, int) or isinstance(obj, float): - /// pass - /// ``` - /// - /// Use instead: - /// ```python - /// if isinstance(obj, (int, float)): - /// pass - /// ``` - /// - /// ## References - /// - [Python: "isinstance"](https://docs.python.org/3/library/functions.html#isinstance) - pub struct DuplicateIsinstanceCall { - pub name: String, - } -); +/// ## What it does +/// Checks for multiple `isinstance` calls on the same target. +/// +/// ## Why is this bad? +/// To check if an object is an instance of any one of multiple types +/// or classes, it is unnecessary to use multiple `isinstance` calls, as +/// the second argument of the `isinstance` built-in function accepts a +/// tuple of types and classes. +/// +/// Using a single `isinstance` call implements the same behavior with more +/// concise code and clearer intent. +/// +/// ## Example +/// ```python +/// if isinstance(obj, int) or isinstance(obj, float): +/// pass +/// ``` +/// +/// Use instead: +/// ```python +/// if isinstance(obj, (int, float)): +/// pass +/// ``` +/// +/// ## References +/// - [Python: "isinstance"](https://docs.python.org/3/library/functions.html#isinstance) +#[violation] +pub struct DuplicateIsinstanceCall { + pub name: String, +} + impl AlwaysAutofixableViolation for DuplicateIsinstanceCall { #[derive_message_formats] fn message(&self) -> String { @@ -56,11 +56,11 @@ impl AlwaysAutofixableViolation for DuplicateIsinstanceCall { } } -define_violation!( - pub struct CompareWithTuple { - pub replacement: String, - } -); +#[violation] +pub struct CompareWithTuple { + pub replacement: String, +} + impl AlwaysAutofixableViolation for CompareWithTuple { #[derive_message_formats] fn message(&self) -> String { @@ -74,11 +74,11 @@ impl AlwaysAutofixableViolation for CompareWithTuple { } } -define_violation!( - pub struct ExprAndNotExpr { - pub name: String, - } -); +#[violation] +pub struct ExprAndNotExpr { + pub name: String, +} + impl AlwaysAutofixableViolation for ExprAndNotExpr { #[derive_message_formats] fn message(&self) -> String { @@ -91,11 +91,11 @@ impl AlwaysAutofixableViolation for ExprAndNotExpr { } } -define_violation!( - pub struct ExprOrNotExpr { - pub name: String, - } -); +#[violation] +pub struct ExprOrNotExpr { + pub name: String, +} + impl AlwaysAutofixableViolation for ExprOrNotExpr { #[derive_message_formats] fn message(&self) -> String { @@ -108,9 +108,9 @@ impl AlwaysAutofixableViolation for ExprOrNotExpr { } } -define_violation!( - pub struct ExprOrTrue; -); +#[violation] +pub struct ExprOrTrue; + impl AlwaysAutofixableViolation for ExprOrTrue { #[derive_message_formats] fn message(&self) -> String { @@ -122,9 +122,9 @@ impl AlwaysAutofixableViolation for ExprOrTrue { } } -define_violation!( - pub struct ExprAndFalse; -); +#[violation] +pub struct ExprAndFalse; + impl AlwaysAutofixableViolation for ExprAndFalse { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_simplify/rules/ast_expr.rs b/crates/ruff/src/rules/flake8_simplify/rules/ast_expr.rs index 5dfa853ef1..a23d8a458f 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/ast_expr.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/ast_expr.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprKind}; use crate::ast::helpers::{create_expr, unparse_expr}; @@ -8,12 +8,12 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct UseCapitalEnvironmentVariables { - pub expected: String, - pub original: String, - } -); +#[violation] +pub struct UseCapitalEnvironmentVariables { + pub expected: String, + pub original: String, +} + impl AlwaysAutofixableViolation for UseCapitalEnvironmentVariables { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_simplify/rules/ast_if.rs b/crates/ruff/src/rules/flake8_simplify/rules/ast_if.rs index b1413e357a..3ac8b6bbb4 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/ast_if.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/ast_if.rs @@ -2,7 +2,7 @@ use log::error; use rustc_hash::FxHashSet; use rustpython_parser::ast::{Cmpop, Constant, Expr, ExprContext, ExprKind, Stmt, StmtKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::comparable::{ComparableConstant, ComparableExpr, ComparableStmt}; use crate::ast::helpers::{ @@ -34,11 +34,11 @@ fn compare_body(body1: &[Stmt], body2: &[Stmt]) -> bool { .all(|(stmt1, stmt2)| compare_stmt(&stmt1.into(), &stmt2.into())) } -define_violation!( - pub struct CollapsibleIf { - pub fixable: bool, - } -); +#[violation] +pub struct CollapsibleIf { + pub fixable: bool, +} + impl Violation for CollapsibleIf { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Sometimes)); @@ -53,12 +53,12 @@ impl Violation for CollapsibleIf { } } -define_violation!( - pub struct NeedlessBool { - pub condition: String, - pub fixable: bool, - } -); +#[violation] +pub struct NeedlessBool { + pub condition: String, + pub fixable: bool, +} + impl Violation for NeedlessBool { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Sometimes)); @@ -75,29 +75,29 @@ impl Violation for NeedlessBool { } } -define_violation!( - /// ## What it does - /// Checks for three or more consecutive if-statements with direct returns - /// - /// ## Why is this bad? - /// These can be simplified by using a dictionary - /// - /// ## Example - /// ```python - /// if x == 1: - /// return "Hello" - /// elif x == 2: - /// return "Goodbye" - /// else: - /// return "Goodnight" - /// ``` - /// - /// Use instead: - /// ```python - /// return {1: "Hello", 2: "Goodbye"}.get(x, "Goodnight") - /// ``` - pub struct ManualDictLookup; -); +/// ## What it does +/// Checks for three or more consecutive if-statements with direct returns +/// +/// ## Why is this bad? +/// These can be simplified by using a dictionary +/// +/// ## Example +/// ```python +/// if x == 1: +/// return "Hello" +/// elif x == 2: +/// return "Goodbye" +/// else: +/// return "Goodnight" +/// ``` +/// +/// Use instead: +/// ```python +/// return {1: "Hello", 2: "Goodbye"}.get(x, "Goodnight") +/// ``` +#[violation] +pub struct ManualDictLookup; + impl Violation for ManualDictLookup { #[derive_message_formats] fn message(&self) -> String { @@ -105,12 +105,12 @@ impl Violation for ManualDictLookup { } } -define_violation!( - pub struct UseTernaryOperator { - pub contents: String, - pub fixable: bool, - } -); +#[violation] +pub struct UseTernaryOperator { + pub contents: String, + pub fixable: bool, +} + impl Violation for UseTernaryOperator { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Sometimes)); @@ -128,29 +128,29 @@ impl Violation for UseTernaryOperator { } } -define_violation!( - /// ## What it does - /// Checks for `if` branches with identical arm bodies. - /// - /// ## Why is this bad? - /// If multiple arms of an `if` statement have the same body, using `or` - /// better signals the intent of the statement. - /// - /// ## Example - /// ```python - /// if x == 1: - /// print("Hello") - /// elif x == 2: - /// print("Hello") - /// ``` - /// - /// Use instead: - /// ```python - /// if x == 1 or x == 2: - /// print("Hello") - /// ``` - pub struct IfWithSameArms; -); +/// ## What it does +/// Checks for `if` branches with identical arm bodies. +/// +/// ## Why is this bad? +/// If multiple arms of an `if` statement have the same body, using `or` +/// better signals the intent of the statement. +/// +/// ## Example +/// ```python +/// if x == 1: +/// print("Hello") +/// elif x == 2: +/// print("Hello") +/// ``` +/// +/// Use instead: +/// ```python +/// if x == 1 or x == 2: +/// print("Hello") +/// ``` +#[violation] +pub struct IfWithSameArms; + impl Violation for IfWithSameArms { #[derive_message_formats] fn message(&self) -> String { @@ -158,12 +158,12 @@ impl Violation for IfWithSameArms { } } -define_violation!( - pub struct DictGetWithDefault { - pub contents: String, - pub fixable: bool, - } -); +#[violation] +pub struct DictGetWithDefault { + pub contents: String, + pub fixable: bool, +} + impl Violation for DictGetWithDefault { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Sometimes)); diff --git a/crates/ruff/src/rules/flake8_simplify/rules/ast_ifexp.rs b/crates/ruff/src/rules/flake8_simplify/rules/ast_ifexp.rs index a807cfdda0..77d597c499 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/ast_ifexp.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/ast_ifexp.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprContext, ExprKind, Unaryop}; use crate::ast::helpers::{create_expr, unparse_expr}; @@ -8,11 +8,11 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct IfExprWithTrueFalse { - pub expr: String, - } -); +#[violation] +pub struct IfExprWithTrueFalse { + pub expr: String, +} + impl AlwaysAutofixableViolation for IfExprWithTrueFalse { #[derive_message_formats] fn message(&self) -> String { @@ -26,11 +26,11 @@ impl AlwaysAutofixableViolation for IfExprWithTrueFalse { } } -define_violation!( - pub struct IfExprWithFalseTrue { - pub expr: String, - } -); +#[violation] +pub struct IfExprWithFalseTrue { + pub expr: String, +} + impl AlwaysAutofixableViolation for IfExprWithFalseTrue { #[derive_message_formats] fn message(&self) -> String { @@ -44,12 +44,12 @@ impl AlwaysAutofixableViolation for IfExprWithFalseTrue { } } -define_violation!( - pub struct IfExprWithTwistedArms { - pub expr_body: String, - pub expr_else: String, - } -); +#[violation] +pub struct IfExprWithTwistedArms { + pub expr_body: String, + pub expr_else: String, +} + impl AlwaysAutofixableViolation for IfExprWithTwistedArms { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_simplify/rules/ast_unary_op.rs b/crates/ruff/src/rules/flake8_simplify/rules/ast_unary_op.rs index 37947310e5..532ba74a51 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/ast_unary_op.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/ast_unary_op.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Cmpop, Expr, ExprKind, Stmt, StmtKind, Unaryop}; use crate::ast::helpers::{create_expr, unparse_expr}; @@ -8,12 +8,12 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct NegateEqualOp { - pub left: String, - pub right: String, - } -); +#[violation] +pub struct NegateEqualOp { + pub left: String, + pub right: String, +} + impl AlwaysAutofixableViolation for NegateEqualOp { #[derive_message_formats] fn message(&self) -> String { @@ -26,12 +26,12 @@ impl AlwaysAutofixableViolation for NegateEqualOp { } } -define_violation!( - pub struct NegateNotEqualOp { - pub left: String, - pub right: String, - } -); +#[violation] +pub struct NegateNotEqualOp { + pub left: String, + pub right: String, +} + impl AlwaysAutofixableViolation for NegateNotEqualOp { #[derive_message_formats] fn message(&self) -> String { @@ -44,11 +44,11 @@ impl AlwaysAutofixableViolation for NegateNotEqualOp { } } -define_violation!( - pub struct DoubleNegation { - pub expr: String, - } -); +#[violation] +pub struct DoubleNegation { + pub expr: String, +} + impl AlwaysAutofixableViolation for DoubleNegation { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_simplify/rules/ast_with.rs b/crates/ruff/src/rules/flake8_simplify/rules/ast_with.rs index b2c5503778..db62e60010 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/ast_with.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/ast_with.rs @@ -1,7 +1,7 @@ use log::error; use rustpython_parser::ast::{Located, Stmt, StmtKind, Withitem}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::helpers::{first_colon_range, has_comments_in}; use crate::ast::types::Range; @@ -11,38 +11,38 @@ use crate::violation::{AutofixKind, Availability, Violation}; use super::fix_with; -define_violation!( - /// ## What it does - /// Checks for the unnecessary nesting of multiple consecutive context - /// managers. - /// - /// ## Why is this bad? - /// In Python 3, a single `with` block can include multiple context - /// managers. - /// - /// Combining multiple context managers into a single `with` statement - /// will minimize the indentation depth of the code, making it more - /// readable. - /// - /// ## Example - /// ```python - /// with A() as a: - /// with B() as b: - /// pass - /// ``` - /// - /// Use instead: - /// ```python - /// with A() as a, B() as b: - /// pass - /// ``` - /// - /// ## References - /// - [Python: "The with statement"](https://docs.python.org/3/reference/compound_stmts.html#the-with-statement) - pub struct MultipleWithStatements { - pub fixable: bool, - } -); +/// ## What it does +/// Checks for the unnecessary nesting of multiple consecutive context +/// managers. +/// +/// ## Why is this bad? +/// In Python 3, a single `with` block can include multiple context +/// managers. +/// +/// Combining multiple context managers into a single `with` statement +/// will minimize the indentation depth of the code, making it more +/// readable. +/// +/// ## Example +/// ```python +/// with A() as a: +/// with B() as b: +/// pass +/// ``` +/// +/// Use instead: +/// ```python +/// with A() as a, B() as b: +/// pass +/// ``` +/// +/// ## References +/// - [Python: "The with statement"](https://docs.python.org/3/reference/compound_stmts.html#the-with-statement) +#[violation] +pub struct MultipleWithStatements { + pub fixable: bool, +} + impl Violation for MultipleWithStatements { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Sometimes)); diff --git a/crates/ruff/src/rules/flake8_simplify/rules/key_in_dict.rs b/crates/ruff/src/rules/flake8_simplify/rules/key_in_dict.rs index badf528c5f..b37c7aedb3 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/key_in_dict.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/key_in_dict.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Cmpop, Expr, ExprKind}; use crate::ast::types::Range; @@ -7,12 +7,12 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct KeyInDict { - pub key: String, - pub dict: String, - } -); +#[violation] +pub struct KeyInDict { + pub key: String, + pub dict: String, +} + impl AlwaysAutofixableViolation for KeyInDict { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_simplify/rules/open_file_with_context_handler.rs b/crates/ruff/src/rules/flake8_simplify/rules/open_file_with_context_handler.rs index d93556002d..b425920efd 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/open_file_with_context_handler.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/open_file_with_context_handler.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind, StmtKind}; use crate::ast::types::Range; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct OpenFileWithContextHandler; -); +#[violation] +pub struct OpenFileWithContextHandler; + impl Violation for OpenFileWithContextHandler { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_simplify/rules/reimplemented_builtin.rs b/crates/ruff/src/rules/flake8_simplify/rules/reimplemented_builtin.rs index 18c5b7bd1c..0e02f3fe9b 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/reimplemented_builtin.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/reimplemented_builtin.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{ Cmpop, Comprehension, Constant, Expr, ExprContext, ExprKind, Location, Stmt, StmtKind, Unaryop, }; @@ -11,11 +11,11 @@ use crate::registry::{Diagnostic, Rule}; use crate::source_code::Stylist; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct ReimplementedBuiltin { - pub repl: String, - } -); +#[violation] +pub struct ReimplementedBuiltin { + pub repl: String, +} + impl AlwaysAutofixableViolation for ReimplementedBuiltin { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_simplify/rules/return_in_try_except_finally.rs b/crates/ruff/src/rules/flake8_simplify/rules/return_in_try_except_finally.rs index d61e014cec..14cef82272 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/return_in_try_except_finally.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/return_in_try_except_finally.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Excepthandler, ExcepthandlerKind, Stmt, StmtKind}; use crate::ast::types::Range; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct ReturnInTryExceptFinally; -); +#[violation] +pub struct ReturnInTryExceptFinally; + impl Violation for ReturnInTryExceptFinally { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_simplify/rules/use_contextlib_suppress.rs b/crates/ruff/src/rules/flake8_simplify/rules/use_contextlib_suppress.rs index ecdf70a12f..8f8695fd3d 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/use_contextlib_suppress.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/use_contextlib_suppress.rs @@ -1,6 +1,6 @@ use rustpython_parser::ast::{Excepthandler, ExcepthandlerKind, Located, Stmt, StmtKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::helpers; use crate::ast::helpers::compose_call_path; @@ -9,11 +9,11 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct UseContextlibSuppress { - pub exception: String, - } -); +#[violation] +pub struct UseContextlibSuppress { + pub exception: String, +} + impl Violation for UseContextlibSuppress { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_simplify/rules/yoda_conditions.rs b/crates/ruff/src/rules/flake8_simplify/rules/yoda_conditions.rs index fc56e232bf..892cd2a023 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/yoda_conditions.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/yoda_conditions.rs @@ -1,6 +1,6 @@ use anyhow::Result; use libcst_native::{Codegen, CodegenState, CompOp}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use ruff_python::str::{self}; use rustpython_parser::ast::{Cmpop, Expr, ExprKind, Unaryop}; @@ -12,11 +12,11 @@ use crate::registry::Diagnostic; use crate::source_code::{Locator, Stylist}; use crate::violation::{AutofixKind, Availability, Violation}; -define_violation!( - pub struct YodaConditions { - pub suggestion: Option, - } -); +#[violation] +pub struct YodaConditions { + pub suggestion: Option, +} + impl Violation for YodaConditions { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Sometimes)); diff --git a/crates/ruff/src/rules/flake8_tidy_imports/banned_api.rs b/crates/ruff/src/rules/flake8_tidy_imports/banned_api.rs index be97eeaba2..4e22c2642c 100644 --- a/crates/ruff/src/rules/flake8_tidy_imports/banned_api.rs +++ b/crates/ruff/src/rules/flake8_tidy_imports/banned_api.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats, CacheKey}; +use ruff_macros::{derive_message_formats, violation, CacheKey}; use rustc_hash::FxHashMap; use rustpython_parser::ast::{Alias, Expr, Located}; use schemars::JsonSchema; @@ -18,29 +18,29 @@ pub struct ApiBan { pub msg: String, } -define_violation!( - /// ## What it does - /// Checks for banned imports. - /// - /// ## Why is this bad? - /// Projects may want to ensure that specific modules or module members are - /// not be imported or accessed. - /// - /// Security or other company policies may be a reason to impose - /// restrictions on importing external Python libraries. In some cases, - /// projects may adopt conventions around the use of certain modules or - /// module members that are not enforceable by the language itself. - /// - /// This rule enforces certain import conventions project-wide in an - /// automatic way. - /// - /// ## Options - /// - `flake8-tidy-imports.banned-api` - pub struct BannedApi { - pub name: String, - pub message: String, - } -); +/// ## What it does +/// Checks for banned imports. +/// +/// ## Why is this bad? +/// Projects may want to ensure that specific modules or module members are +/// not be imported or accessed. +/// +/// Security or other company policies may be a reason to impose +/// restrictions on importing external Python libraries. In some cases, +/// projects may adopt conventions around the use of certain modules or +/// module members that are not enforceable by the language itself. +/// +/// This rule enforces certain import conventions project-wide in an +/// automatic way. +/// +/// ## Options +/// - `flake8-tidy-imports.banned-api` +#[violation] +pub struct BannedApi { + pub name: String, + pub message: String, +} + impl Violation for BannedApi { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_tidy_imports/relative_imports.rs b/crates/ruff/src/rules/flake8_tidy_imports/relative_imports.rs index 3658f74355..d267176b1c 100644 --- a/crates/ruff/src/rules/flake8_tidy_imports/relative_imports.rs +++ b/crates/ruff/src/rules/flake8_tidy_imports/relative_imports.rs @@ -1,10 +1,9 @@ +use ruff_macros::{derive_message_formats, violation, CacheKey}; +use ruff_python::identifiers::is_module_name; use rustpython_parser::ast::{Stmt, StmtKind}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use ruff_macros::{define_violation, derive_message_formats, CacheKey}; -use ruff_python::identifiers::is_module_name; - use crate::ast::helpers::{create_stmt, from_relative_import, unparse_stmt}; use crate::ast::types::Range; use crate::checkers::ast::Checker; @@ -25,45 +24,45 @@ pub enum Strictness { All, } -define_violation!( - /// ## What it does - /// Checks for relative imports. - /// - /// ## Why is this bad? - /// Absolute imports, or relative imports from siblings, are recommended by [PEP 8]: - /// - /// > Absolute imports are recommended, as they are usually more readable and tend to be better behaved... - /// > ```python - /// > import mypkg.sibling - /// > from mypkg import sibling - /// > from mypkg.sibling import example - /// > ``` - /// > However, explicit relative imports are an acceptable alternative to absolute imports, - /// > especially when dealing with complex package layouts where using absolute imports would be - /// > unnecessarily verbose: - /// > ```python - /// > from . import sibling - /// > from .sibling import example - /// > ``` - /// - /// ## Options - /// - `flake8-tidy-imports.ban-relative-imports` - /// - /// ## Example - /// ```python - /// from .. import foo - /// ``` - /// - /// Use instead: - /// ```python - /// from mypkg import foo - /// ``` - /// - /// [PEP 8]: https://peps.python.org/pep-0008/#imports - pub struct RelativeImports { - pub strictness: Strictness, - } -); +/// ## What it does +/// Checks for relative imports. +/// +/// ## Why is this bad? +/// Absolute imports, or relative imports from siblings, are recommended by [PEP 8]: +/// +/// > Absolute imports are recommended, as they are usually more readable and tend to be better behaved... +/// > ```python +/// > import mypkg.sibling +/// > from mypkg import sibling +/// > from mypkg.sibling import example +/// > ``` +/// > However, explicit relative imports are an acceptable alternative to absolute imports, +/// > especially when dealing with complex package layouts where using absolute imports would be +/// > unnecessarily verbose: +/// > ```python +/// > from . import sibling +/// > from .sibling import example +/// > ``` +/// +/// ## Options +/// - `flake8-tidy-imports.ban-relative-imports` +/// +/// ## Example +/// ```python +/// from .. import foo +/// ``` +/// +/// Use instead: +/// ```python +/// from mypkg import foo +/// ``` +/// +/// [PEP 8]: https://peps.python.org/pep-0008/#imports +#[violation] +pub struct RelativeImports { + pub strictness: Strictness, +} + impl Violation for RelativeImports { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Sometimes)); diff --git a/crates/ruff/src/rules/flake8_type_checking/rules/empty_type_checking_block.rs b/crates/ruff/src/rules/flake8_type_checking/rules/empty_type_checking_block.rs index 250189bf45..dd89bcb2d9 100644 --- a/crates/ruff/src/rules/flake8_type_checking/rules/empty_type_checking_block.rs +++ b/crates/ruff/src/rules/flake8_type_checking/rules/empty_type_checking_block.rs @@ -1,5 +1,5 @@ use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Stmt, StmtKind}; use crate::ast::types::{Range, RefEquality}; @@ -8,9 +8,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct EmptyTypeCheckingBlock; -); +#[violation] +pub struct EmptyTypeCheckingBlock; + impl AlwaysAutofixableViolation for EmptyTypeCheckingBlock { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_type_checking/rules/runtime_import_in_type_checking_block.rs b/crates/ruff/src/rules/flake8_type_checking/rules/runtime_import_in_type_checking_block.rs index 847f7cdf39..a44d17b3ac 100644 --- a/crates/ruff/src/rules/flake8_type_checking/rules/runtime_import_in_type_checking_block.rs +++ b/crates/ruff/src/rules/flake8_type_checking/rules/runtime_import_in_type_checking_block.rs @@ -1,14 +1,14 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::{Binding, BindingKind, ExecutionContext}; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct RuntimeImportInTypeCheckingBlock { - pub full_name: String, - } -); +#[violation] +pub struct RuntimeImportInTypeCheckingBlock { + pub full_name: String, +} + impl Violation for RuntimeImportInTypeCheckingBlock { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_type_checking/rules/typing_only_runtime_import.rs b/crates/ruff/src/rules/flake8_type_checking/rules/typing_only_runtime_import.rs index 32703f40c7..38da83d3c8 100644 --- a/crates/ruff/src/rules/flake8_type_checking/rules/typing_only_runtime_import.rs +++ b/crates/ruff/src/rules/flake8_type_checking/rules/typing_only_runtime_import.rs @@ -1,6 +1,6 @@ use std::path::Path; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::{Binding, BindingKind, ExecutionContext}; use crate::registry::Diagnostic; @@ -8,11 +8,11 @@ use crate::rules::isort::{categorize, ImportType}; use crate::settings::Settings; use crate::violation::Violation; -define_violation!( - pub struct TypingOnlyFirstPartyImport { - pub full_name: String, - } -); +#[violation] +pub struct TypingOnlyFirstPartyImport { + pub full_name: String, +} + impl Violation for TypingOnlyFirstPartyImport { #[derive_message_formats] fn message(&self) -> String { @@ -23,11 +23,11 @@ impl Violation for TypingOnlyFirstPartyImport { } } -define_violation!( - pub struct TypingOnlyThirdPartyImport { - pub full_name: String, - } -); +#[violation] +pub struct TypingOnlyThirdPartyImport { + pub full_name: String, +} + impl Violation for TypingOnlyThirdPartyImport { #[derive_message_formats] fn message(&self) -> String { @@ -38,11 +38,11 @@ impl Violation for TypingOnlyThirdPartyImport { } } -define_violation!( - pub struct TypingOnlyStandardLibraryImport { - pub full_name: String, - } -); +#[violation] +pub struct TypingOnlyStandardLibraryImport { + pub full_name: String, +} + impl Violation for TypingOnlyStandardLibraryImport { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_unused_arguments/rules.rs b/crates/ruff/src/rules/flake8_unused_arguments/rules.rs index 537ca85a1a..8842a994a9 100644 --- a/crates/ruff/src/rules/flake8_unused_arguments/rules.rs +++ b/crates/ruff/src/rules/flake8_unused_arguments/rules.rs @@ -1,7 +1,7 @@ use std::iter; use regex::Regex; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustc_hash::FxHashMap; use rustpython_parser::ast::{Arg, Arguments}; @@ -15,11 +15,11 @@ use crate::registry::Diagnostic; use crate::violation::Violation; use crate::visibility; -define_violation!( - pub struct UnusedFunctionArgument { - pub name: String, - } -); +#[violation] +pub struct UnusedFunctionArgument { + pub name: String, +} + impl Violation for UnusedFunctionArgument { #[derive_message_formats] fn message(&self) -> String { @@ -28,11 +28,11 @@ impl Violation for UnusedFunctionArgument { } } -define_violation!( - pub struct UnusedMethodArgument { - pub name: String, - } -); +#[violation] +pub struct UnusedMethodArgument { + pub name: String, +} + impl Violation for UnusedMethodArgument { #[derive_message_formats] fn message(&self) -> String { @@ -41,11 +41,11 @@ impl Violation for UnusedMethodArgument { } } -define_violation!( - pub struct UnusedClassMethodArgument { - pub name: String, - } -); +#[violation] +pub struct UnusedClassMethodArgument { + pub name: String, +} + impl Violation for UnusedClassMethodArgument { #[derive_message_formats] fn message(&self) -> String { @@ -54,11 +54,11 @@ impl Violation for UnusedClassMethodArgument { } } -define_violation!( - pub struct UnusedStaticMethodArgument { - pub name: String, - } -); +#[violation] +pub struct UnusedStaticMethodArgument { + pub name: String, +} + impl Violation for UnusedStaticMethodArgument { #[derive_message_formats] fn message(&self) -> String { @@ -67,11 +67,11 @@ impl Violation for UnusedStaticMethodArgument { } } -define_violation!( - pub struct UnusedLambdaArgument { - pub name: String, - } -); +#[violation] +pub struct UnusedLambdaArgument { + pub name: String, +} + impl Violation for UnusedLambdaArgument { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/flake8_use_pathlib/violations.rs b/crates/ruff/src/rules/flake8_use_pathlib/violations.rs index a2d1b224bb..f0cef2a7e8 100644 --- a/crates/ruff/src/rules/flake8_use_pathlib/violations.rs +++ b/crates/ruff/src/rules/flake8_use_pathlib/violations.rs @@ -1,11 +1,11 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::violation::Violation; // PTH100 -define_violation!( - pub struct PathlibAbspath; -); +#[violation] +pub struct PathlibAbspath; + impl Violation for PathlibAbspath { #[derive_message_formats] fn message(&self) -> String { @@ -14,9 +14,9 @@ impl Violation for PathlibAbspath { } // PTH101 -define_violation!( - pub struct PathlibChmod; -); +#[violation] +pub struct PathlibChmod; + impl Violation for PathlibChmod { #[derive_message_formats] fn message(&self) -> String { @@ -25,9 +25,9 @@ impl Violation for PathlibChmod { } // PTH102 -define_violation!( - pub struct PathlibMakedirs; -); +#[violation] +pub struct PathlibMakedirs; + impl Violation for PathlibMakedirs { #[derive_message_formats] fn message(&self) -> String { @@ -36,9 +36,9 @@ impl Violation for PathlibMakedirs { } // PTH103 -define_violation!( - pub struct PathlibMkdir; -); +#[violation] +pub struct PathlibMkdir; + impl Violation for PathlibMkdir { #[derive_message_formats] fn message(&self) -> String { @@ -47,9 +47,9 @@ impl Violation for PathlibMkdir { } // PTH104 -define_violation!( - pub struct PathlibRename; -); +#[violation] +pub struct PathlibRename; + impl Violation for PathlibRename { #[derive_message_formats] fn message(&self) -> String { @@ -58,9 +58,9 @@ impl Violation for PathlibRename { } // PTH105 -define_violation!( - pub struct PathlibReplace; -); +#[violation] +pub struct PathlibReplace; + impl Violation for PathlibReplace { #[derive_message_formats] fn message(&self) -> String { @@ -69,9 +69,9 @@ impl Violation for PathlibReplace { } // PTH106 -define_violation!( - pub struct PathlibRmdir; -); +#[violation] +pub struct PathlibRmdir; + impl Violation for PathlibRmdir { #[derive_message_formats] fn message(&self) -> String { @@ -80,9 +80,9 @@ impl Violation for PathlibRmdir { } // PTH107 -define_violation!( - pub struct PathlibRemove; -); +#[violation] +pub struct PathlibRemove; + impl Violation for PathlibRemove { #[derive_message_formats] fn message(&self) -> String { @@ -91,9 +91,9 @@ impl Violation for PathlibRemove { } // PTH108 -define_violation!( - pub struct PathlibUnlink; -); +#[violation] +pub struct PathlibUnlink; + impl Violation for PathlibUnlink { #[derive_message_formats] fn message(&self) -> String { @@ -102,9 +102,9 @@ impl Violation for PathlibUnlink { } // PTH109 -define_violation!( - pub struct PathlibGetcwd; -); +#[violation] +pub struct PathlibGetcwd; + impl Violation for PathlibGetcwd { #[derive_message_formats] fn message(&self) -> String { @@ -113,9 +113,9 @@ impl Violation for PathlibGetcwd { } // PTH110 -define_violation!( - pub struct PathlibExists; -); +#[violation] +pub struct PathlibExists; + impl Violation for PathlibExists { #[derive_message_formats] fn message(&self) -> String { @@ -124,9 +124,9 @@ impl Violation for PathlibExists { } // PTH111 -define_violation!( - pub struct PathlibExpanduser; -); +#[violation] +pub struct PathlibExpanduser; + impl Violation for PathlibExpanduser { #[derive_message_formats] fn message(&self) -> String { @@ -135,9 +135,9 @@ impl Violation for PathlibExpanduser { } // PTH112 -define_violation!( - pub struct PathlibIsDir; -); +#[violation] +pub struct PathlibIsDir; + impl Violation for PathlibIsDir { #[derive_message_formats] fn message(&self) -> String { @@ -146,9 +146,9 @@ impl Violation for PathlibIsDir { } // PTH113 -define_violation!( - pub struct PathlibIsFile; -); +#[violation] +pub struct PathlibIsFile; + impl Violation for PathlibIsFile { #[derive_message_formats] fn message(&self) -> String { @@ -157,9 +157,9 @@ impl Violation for PathlibIsFile { } // PTH114 -define_violation!( - pub struct PathlibIsLink; -); +#[violation] +pub struct PathlibIsLink; + impl Violation for PathlibIsLink { #[derive_message_formats] fn message(&self) -> String { @@ -168,9 +168,9 @@ impl Violation for PathlibIsLink { } // PTH115 -define_violation!( - pub struct PathlibReadlink; -); +#[violation] +pub struct PathlibReadlink; + impl Violation for PathlibReadlink { #[derive_message_formats] fn message(&self) -> String { @@ -179,9 +179,9 @@ impl Violation for PathlibReadlink { } // PTH116 -define_violation!( - pub struct PathlibStat; -); +#[violation] +pub struct PathlibStat; + impl Violation for PathlibStat { #[derive_message_formats] fn message(&self) -> String { @@ -192,9 +192,9 @@ impl Violation for PathlibStat { } // PTH117 -define_violation!( - pub struct PathlibIsAbs; -); +#[violation] +pub struct PathlibIsAbs; + impl Violation for PathlibIsAbs { #[derive_message_formats] fn message(&self) -> String { @@ -203,9 +203,9 @@ impl Violation for PathlibIsAbs { } // PTH118 -define_violation!( - pub struct PathlibJoin; -); +#[violation] +pub struct PathlibJoin; + impl Violation for PathlibJoin { #[derive_message_formats] fn message(&self) -> String { @@ -214,9 +214,9 @@ impl Violation for PathlibJoin { } // PTH119 -define_violation!( - pub struct PathlibBasename; -); +#[violation] +pub struct PathlibBasename; + impl Violation for PathlibBasename { #[derive_message_formats] fn message(&self) -> String { @@ -225,9 +225,9 @@ impl Violation for PathlibBasename { } // PTH120 -define_violation!( - pub struct PathlibDirname; -); +#[violation] +pub struct PathlibDirname; + impl Violation for PathlibDirname { #[derive_message_formats] fn message(&self) -> String { @@ -236,9 +236,9 @@ impl Violation for PathlibDirname { } // PTH121 -define_violation!( - pub struct PathlibSamefile; -); +#[violation] +pub struct PathlibSamefile; + impl Violation for PathlibSamefile { #[derive_message_formats] fn message(&self) -> String { @@ -247,9 +247,9 @@ impl Violation for PathlibSamefile { } // PTH122 -define_violation!( - pub struct PathlibSplitext; -); +#[violation] +pub struct PathlibSplitext; + impl Violation for PathlibSplitext { #[derive_message_formats] fn message(&self) -> String { @@ -258,9 +258,9 @@ impl Violation for PathlibSplitext { } // PTH123 -define_violation!( - pub struct PathlibOpen; -); +#[violation] +pub struct PathlibOpen; + impl Violation for PathlibOpen { #[derive_message_formats] fn message(&self) -> String { @@ -269,9 +269,9 @@ impl Violation for PathlibOpen { } // PTH124 -define_violation!( - pub struct PathlibPyPath; -); +#[violation] +pub struct PathlibPyPath; + impl Violation for PathlibPyPath { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/isort/rules/add_required_imports.rs b/crates/ruff/src/rules/isort/rules/add_required_imports.rs index f1b9bf02e2..b6ab7dd5a5 100644 --- a/crates/ruff/src/rules/isort/rules/add_required_imports.rs +++ b/crates/ruff/src/rules/isort/rules/add_required_imports.rs @@ -1,7 +1,7 @@ use std::fmt; use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser as parser; use rustpython_parser::ast::{Location, StmtKind, Suite}; @@ -15,32 +15,32 @@ use crate::settings::{flags, Settings}; use crate::source_code::{Locator, Stylist}; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - /// ## What it does - /// Adds any required imports, as specified by the user, to the top of the - /// file. - /// - /// ## Why is this bad? - /// In some projects, certain imports are required to be present in all - /// files. For example, some projects assume that - /// `from __future__ import annotations` is enabled, - /// and thus require that import to be - /// present in all files. Omitting a "required" import (as specified by - /// the user) can cause errors or unexpected behavior. - /// - /// ## Example - /// ```python - /// import typing - /// ``` - /// - /// Use instead: - /// ```python - /// from __future__ import annotations - /// - /// import typing - /// ``` - pub struct MissingRequiredImport(pub String); -); +/// ## What it does +/// Adds any required imports, as specified by the user, to the top of the +/// file. +/// +/// ## Why is this bad? +/// In some projects, certain imports are required to be present in all +/// files. For example, some projects assume that +/// `from __future__ import annotations` is enabled, +/// and thus require that import to be +/// present in all files. Omitting a "required" import (as specified by +/// the user) can cause errors or unexpected behavior. +/// +/// ## Example +/// ```python +/// import typing +/// ``` +/// +/// Use instead: +/// ```python +/// from __future__ import annotations +/// +/// import typing +/// ``` +#[violation] +pub struct MissingRequiredImport(pub String); + impl AlwaysAutofixableViolation for MissingRequiredImport { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/isort/rules/organize_imports.rs b/crates/ruff/src/rules/isort/rules/organize_imports.rs index 5b7d946203..112d455d2b 100644 --- a/crates/ruff/src/rules/isort/rules/organize_imports.rs +++ b/crates/ruff/src/rules/isort/rules/organize_imports.rs @@ -1,7 +1,7 @@ use std::path::Path; use itertools::{EitherOrBoth, Itertools}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Location, Stmt}; use textwrap::indent; @@ -18,27 +18,27 @@ use crate::settings::{flags, Settings}; use crate::source_code::{Indexer, Locator, Stylist}; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - /// ## What it does - /// De-duplicates, groups, and sorts imports based on the provided `isort` settings. - /// - /// ## Why is this bad? - /// Consistency is good. Use a common convention for imports to make your code - /// more readable and idiomatic. - /// - /// ## Example - /// ```python - /// import pandas - /// import numpy as np - /// ``` - /// - /// Use instead: - /// ```python - /// import numpy as np - /// import pandas - /// ``` - pub struct UnsortedImports; -); +/// ## What it does +/// De-duplicates, groups, and sorts imports based on the provided `isort` settings. +/// +/// ## Why is this bad? +/// Consistency is good. Use a common convention for imports to make your code +/// more readable and idiomatic. +/// +/// ## Example +/// ```python +/// import pandas +/// import numpy as np +/// ``` +/// +/// Use instead: +/// ```python +/// import numpy as np +/// import pandas +/// ``` +#[violation] +pub struct UnsortedImports; + impl AlwaysAutofixableViolation for UnsortedImports { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/mccabe/rules.rs b/crates/ruff/src/rules/mccabe/rules.rs index fc2240cc6c..1949d2788c 100644 --- a/crates/ruff/src/rules/mccabe/rules.rs +++ b/crates/ruff/src/rules/mccabe/rules.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{ExcepthandlerKind, ExprKind, Stmt, StmtKind}; use crate::ast::helpers::identifier_range; @@ -6,53 +6,53 @@ use crate::registry::Diagnostic; use crate::source_code::Locator; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for functions with a high `McCabe` complexity. - /// - /// The `McCabe` complexity of a function is a measure of the complexity of - /// the control flow graph of the function. It is calculated by adding - /// one to the number of decision points in the function. A decision - /// point is a place in the code where the program has a choice of two - /// or more paths to follow. - /// - /// ## Why is this bad? - /// Functions with a high complexity are hard to understand and maintain. - /// - /// ## Options - /// - `mccabe.max-complexity` - /// - /// ## Example - /// ```python - /// def foo(a, b, c): - /// if a: - /// if b: - /// if c: - /// return 1 - /// else: - /// return 2 - /// else: - /// return 3 - /// else: - /// return 4 - /// ``` - /// - /// Use instead: - /// ```python - /// def foo(a, b, c): - /// if not a: - /// return 4 - /// if not b: - /// return 3 - /// if not c: - /// return 2 - /// return 1 - /// ``` - pub struct ComplexStructure { - pub name: String, - pub complexity: usize, - } -); +/// ## What it does +/// Checks for functions with a high `McCabe` complexity. +/// +/// The `McCabe` complexity of a function is a measure of the complexity of +/// the control flow graph of the function. It is calculated by adding +/// one to the number of decision points in the function. A decision +/// point is a place in the code where the program has a choice of two +/// or more paths to follow. +/// +/// ## Why is this bad? +/// Functions with a high complexity are hard to understand and maintain. +/// +/// ## Options +/// - `mccabe.max-complexity` +/// +/// ## Example +/// ```python +/// def foo(a, b, c): +/// if a: +/// if b: +/// if c: +/// return 1 +/// else: +/// return 2 +/// else: +/// return 3 +/// else: +/// return 4 +/// ``` +/// +/// Use instead: +/// ```python +/// def foo(a, b, c): +/// if not a: +/// return 4 +/// if not b: +/// return 3 +/// if not c: +/// return 2 +/// return 1 +/// ``` +#[violation] +pub struct ComplexStructure { + pub name: String, + pub complexity: usize, +} + impl Violation for ComplexStructure { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/numpy/rules/deprecated_type_alias.rs b/crates/ruff/src/rules/numpy/rules/deprecated_type_alias.rs index cfb2f1edab..612047f941 100644 --- a/crates/ruff/src/rules/numpy/rules/deprecated_type_alias.rs +++ b/crates/ruff/src/rules/numpy/rules/deprecated_type_alias.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Expr; use crate::ast::types::Range; @@ -7,33 +7,33 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - /// ## What it does - /// Checks for deprecated NumPy type aliases. - /// - /// ## Why is this bad? - /// NumPy's `np.int` has long been an alias of the builtin `int`. The same - /// goes for `np.float`, `np.bool`, and others. These aliases exist - /// primarily primarily for historic reasons, and have been a cause of - /// frequent confusion for newcomers. - /// - /// These aliases were been deprecated in 1.20, and removed in 1.24. - /// - /// ## Examples - /// ```python - /// import numpy as np - /// - /// np.bool - /// ``` - /// - /// Use instead: - /// ```python - /// bool - /// ``` - pub struct NumpyDeprecatedTypeAlias { - pub type_name: String, - } -); +/// ## What it does +/// Checks for deprecated NumPy type aliases. +/// +/// ## Why is this bad? +/// NumPy's `np.int` has long been an alias of the builtin `int`. The same +/// goes for `np.float`, `np.bool`, and others. These aliases exist +/// primarily primarily for historic reasons, and have been a cause of +/// frequent confusion for newcomers. +/// +/// These aliases were been deprecated in 1.20, and removed in 1.24. +/// +/// ## Examples +/// ```python +/// import numpy as np +/// +/// np.bool +/// ``` +/// +/// Use instead: +/// ```python +/// bool +/// ``` +#[violation] +pub struct NumpyDeprecatedTypeAlias { + pub type_name: String, +} + impl AlwaysAutofixableViolation for NumpyDeprecatedTypeAlias { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/numpy/rules/numpy_legacy_random.rs b/crates/ruff/src/rules/numpy/rules/numpy_legacy_random.rs index 175bdff585..74aaef947a 100644 --- a/crates/ruff/src/rules/numpy/rules/numpy_legacy_random.rs +++ b/crates/ruff/src/rules/numpy/rules/numpy_legacy_random.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Expr; use crate::ast::types::Range; @@ -6,49 +6,49 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for the use of legacy `np.random` function calls. - /// - /// ## Why is this bad? - /// According to the NumPy documentation's [Legacy Random Generation]: - /// - /// > The `RandomState` provides access to legacy generators... This class - /// > should only be used if it is essential to have randoms that are - /// > identical to what would have been produced by previous versions of - /// > NumPy. - /// - /// The members exposed directly on the `random` module are convenience - /// functions that alias to methods on a global singleton `RandomState` - /// instance. NumPy recommends using a dedicated `Generator` instance - /// rather than the random variate generation methods exposed directly on - /// the `random` module, as the new `Generator` is both faster and has - /// better statistical properties. - /// - /// See the documentation on [Random Sampling] and [NEP 19] for further - /// details. - /// - /// ## Examples - /// ```python - /// import numpy as np - /// - /// np.random.seed(1337) - /// np.random.normal() - /// ``` - /// - /// Use instead: - /// ```python - /// rng = np.random.default_rng(1337) - /// rng.normal() - /// ``` - /// - /// [Legacy Random Generation]: https://numpy.org/doc/stable/reference/random/legacy.html#legacy - /// [Random Sampling]: https://numpy.org/doc/stable/reference/random/index.html#random-quick-start - /// [NEP 19]: https://numpy.org/neps/nep-0019-rng-policy.html - pub struct NumpyLegacyRandom { - pub method_name: String, - } -); +/// ## What it does +/// Checks for the use of legacy `np.random` function calls. +/// +/// ## Why is this bad? +/// According to the NumPy documentation's [Legacy Random Generation]: +/// +/// > The `RandomState` provides access to legacy generators... This class +/// > should only be used if it is essential to have randoms that are +/// > identical to what would have been produced by previous versions of +/// > NumPy. +/// +/// The members exposed directly on the `random` module are convenience +/// functions that alias to methods on a global singleton `RandomState` +/// instance. NumPy recommends using a dedicated `Generator` instance +/// rather than the random variate generation methods exposed directly on +/// the `random` module, as the new `Generator` is both faster and has +/// better statistical properties. +/// +/// See the documentation on [Random Sampling] and [NEP 19] for further +/// details. +/// +/// ## Examples +/// ```python +/// import numpy as np +/// +/// np.random.seed(1337) +/// np.random.normal() +/// ``` +/// +/// Use instead: +/// ```python +/// rng = np.random.default_rng(1337) +/// rng.normal() +/// ``` +/// +/// [Legacy Random Generation]: https://numpy.org/doc/stable/reference/random/legacy.html#legacy +/// [Random Sampling]: https://numpy.org/doc/stable/reference/random/index.html#random-quick-start +/// [NEP 19]: https://numpy.org/neps/nep-0019-rng-policy.html +#[violation] +pub struct NumpyLegacyRandom { + pub method_name: String, +} + impl Violation for NumpyLegacyRandom { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pandas_vet/rules/assignment_to_df.rs b/crates/ruff/src/rules/pandas_vet/rules/assignment_to_df.rs index f5fa707ff0..be926fb5f4 100644 --- a/crates/ruff/src/rules/pandas_vet/rules/assignment_to_df.rs +++ b/crates/ruff/src/rules/pandas_vet/rules/assignment_to_df.rs @@ -1,13 +1,13 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct DfIsABadVariableName; -); +#[violation] +pub struct DfIsABadVariableName; + impl Violation for DfIsABadVariableName { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pandas_vet/rules/check_attr.rs b/crates/ruff/src/rules/pandas_vet/rules/check_attr.rs index efe541d0cf..afbd4675ab 100644 --- a/crates/ruff/src/rules/pandas_vet/rules/check_attr.rs +++ b/crates/ruff/src/rules/pandas_vet/rules/check_attr.rs @@ -1,6 +1,6 @@ use rustpython_parser::ast::{Expr, ExprKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::{BindingKind, Range}; use crate::checkers::ast::Checker; @@ -8,9 +8,9 @@ use crate::registry::{Diagnostic, DiagnosticKind, Rule}; use crate::rules::pandas_vet::helpers::is_dataframe_candidate; use crate::violation::Violation; -define_violation!( - pub struct UseOfDotIx; -); +#[violation] +pub struct UseOfDotIx; + impl Violation for UseOfDotIx { #[derive_message_formats] fn message(&self) -> String { @@ -18,9 +18,9 @@ impl Violation for UseOfDotIx { } } -define_violation!( - pub struct UseOfDotAt; -); +#[violation] +pub struct UseOfDotAt; + impl Violation for UseOfDotAt { #[derive_message_formats] fn message(&self) -> String { @@ -28,9 +28,9 @@ impl Violation for UseOfDotAt { } } -define_violation!( - pub struct UseOfDotIat; -); +#[violation] +pub struct UseOfDotIat; + impl Violation for UseOfDotIat { #[derive_message_formats] fn message(&self) -> String { @@ -38,9 +38,9 @@ impl Violation for UseOfDotIat { } } -define_violation!( - pub struct UseOfDotValues; -); +#[violation] +pub struct UseOfDotValues; + impl Violation for UseOfDotValues { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pandas_vet/rules/check_call.rs b/crates/ruff/src/rules/pandas_vet/rules/check_call.rs index 5bc8adb3c5..57f6570904 100644 --- a/crates/ruff/src/rules/pandas_vet/rules/check_call.rs +++ b/crates/ruff/src/rules/pandas_vet/rules/check_call.rs @@ -1,6 +1,6 @@ use rustpython_parser::ast::{Expr, ExprKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::{BindingKind, Range}; use crate::checkers::ast::Checker; @@ -8,9 +8,9 @@ use crate::registry::{Diagnostic, DiagnosticKind, Rule}; use crate::rules::pandas_vet::helpers::is_dataframe_candidate; use crate::violation::Violation; -define_violation!( - pub struct UseOfDotIsNull; -); +#[violation] +pub struct UseOfDotIsNull; + impl Violation for UseOfDotIsNull { #[derive_message_formats] fn message(&self) -> String { @@ -18,9 +18,9 @@ impl Violation for UseOfDotIsNull { } } -define_violation!( - pub struct UseOfDotNotNull; -); +#[violation] +pub struct UseOfDotNotNull; + impl Violation for UseOfDotNotNull { #[derive_message_formats] fn message(&self) -> String { @@ -28,9 +28,9 @@ impl Violation for UseOfDotNotNull { } } -define_violation!( - pub struct UseOfDotPivotOrUnstack; -); +#[violation] +pub struct UseOfDotPivotOrUnstack; + impl Violation for UseOfDotPivotOrUnstack { #[derive_message_formats] fn message(&self) -> String { @@ -40,9 +40,9 @@ impl Violation for UseOfDotPivotOrUnstack { } } -define_violation!( - pub struct UseOfDotReadTable; -); +#[violation] +pub struct UseOfDotReadTable; + impl Violation for UseOfDotReadTable { #[derive_message_formats] fn message(&self) -> String { @@ -50,9 +50,9 @@ impl Violation for UseOfDotReadTable { } } -define_violation!( - pub struct UseOfDotStack; -); +#[violation] +pub struct UseOfDotStack; + impl Violation for UseOfDotStack { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pandas_vet/rules/inplace_argument.rs b/crates/ruff/src/rules/pandas_vet/rules/inplace_argument.rs index 28960ab546..cb2e9afd10 100644 --- a/crates/ruff/src/rules/pandas_vet/rules/inplace_argument.rs +++ b/crates/ruff/src/rules/pandas_vet/rules/inplace_argument.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprKind, Keyword}; use crate::ast::types::Range; @@ -7,33 +7,33 @@ use crate::registry::Diagnostic; use crate::rules::pandas_vet::fixes::fix_inplace_argument; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - /// ## What it does - /// Checks for `inplace=True` usages in `pandas` function and method - /// calls. - /// - /// ## Why is this bad? - /// Using `inplace=True` encourages mutation rather than immutable data, - /// which is harder to reason about and may cause bugs. It also removes the - /// ability to use the method chaining style for `pandas` operations. - /// - /// Further, in many cases, `inplace=True` does not provide a performance - /// benefit, as `pandas` will often copy `DataFrames` in the background. - /// - /// ## Example - /// ```python - /// df.sort_values("col1", inplace=True) - /// ``` - /// - /// Use instead: - /// ```python - /// sorted_df = df.sort_values("col1") - /// ``` - /// - /// ## References - /// - [_Why You Should Probably Never Use pandas inplace=True_](https://towardsdatascience.com/why-you-should-probably-never-use-pandas-inplace-true-9f9f211849e4) - pub struct UseOfInplaceArgument; -); +/// ## What it does +/// Checks for `inplace=True` usages in `pandas` function and method +/// calls. +/// +/// ## Why is this bad? +/// Using `inplace=True` encourages mutation rather than immutable data, +/// which is harder to reason about and may cause bugs. It also removes the +/// ability to use the method chaining style for `pandas` operations. +/// +/// Further, in many cases, `inplace=True` does not provide a performance +/// benefit, as `pandas` will often copy `DataFrames` in the background. +/// +/// ## Example +/// ```python +/// df.sort_values("col1", inplace=True) +/// ``` +/// +/// Use instead: +/// ```python +/// sorted_df = df.sort_values("col1") +/// ``` +/// +/// ## References +/// - [_Why You Should Probably Never Use pandas inplace=True_](https://towardsdatascience.com/why-you-should-probably-never-use-pandas-inplace-true-9f9f211849e4) +#[violation] +pub struct UseOfInplaceArgument; + impl AlwaysAutofixableViolation for UseOfInplaceArgument { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pandas_vet/rules/pd_merge.rs b/crates/ruff/src/rules/pandas_vet/rules/pd_merge.rs index 5d60f10099..9ccc3c586d 100644 --- a/crates/ruff/src/rules/pandas_vet/rules/pd_merge.rs +++ b/crates/ruff/src/rules/pandas_vet/rules/pd_merge.rs @@ -1,13 +1,13 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct UseOfPdMerge; -); +#[violation] +pub struct UseOfPdMerge; + impl Violation for UseOfPdMerge { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_acronym.rs b/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_acronym.rs index e396510f07..cdf2d3a801 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_acronym.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_acronym.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use ruff_python::str::{self}; use rustpython_parser::ast::Stmt; @@ -8,38 +8,38 @@ use crate::rules::pep8_naming::helpers; use crate::source_code::Locator; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for `CamelCase` imports that are aliased as acronyms. - /// - /// ## Why is this bad? - /// [PEP 8] recommends naming conventions for classes, functions, - /// constants, and more. The use of inconsistent naming styles between - /// import and alias names may lead readers to expect an import to be of - /// another type (e.g., confuse a Python class with a constant). - /// - /// Import aliases should thus follow the same naming style as the member - /// being imported. - /// - /// Note that this rule is distinct from `camelcase-imported-as-constant` - /// to accommodate selective enforcement. - /// - /// ## Example - /// ```python - /// from example import MyClassName as MCN - /// ``` - /// - /// Use instead: - /// ```python - /// from example import MyClassName - /// ``` - /// - /// [PEP 8]: https://peps.python.org/pep-0008/ - pub struct CamelcaseImportedAsAcronym { - pub name: String, - pub asname: String, - } -); +/// ## What it does +/// Checks for `CamelCase` imports that are aliased as acronyms. +/// +/// ## Why is this bad? +/// [PEP 8] recommends naming conventions for classes, functions, +/// constants, and more. The use of inconsistent naming styles between +/// import and alias names may lead readers to expect an import to be of +/// another type (e.g., confuse a Python class with a constant). +/// +/// Import aliases should thus follow the same naming style as the member +/// being imported. +/// +/// Note that this rule is distinct from `camelcase-imported-as-constant` +/// to accommodate selective enforcement. +/// +/// ## Example +/// ```python +/// from example import MyClassName as MCN +/// ``` +/// +/// Use instead: +/// ```python +/// from example import MyClassName +/// ``` +/// +/// [PEP 8]: https://peps.python.org/pep-0008/ +#[violation] +pub struct CamelcaseImportedAsAcronym { + pub name: String, + pub asname: String, +} + impl Violation for CamelcaseImportedAsAcronym { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_constant.rs b/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_constant.rs index 763d47fd5b..1410fedb03 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_constant.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_constant.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use ruff_python::str::{self}; use rustpython_parser::ast::Stmt; @@ -8,35 +8,35 @@ use crate::rules::pep8_naming::helpers; use crate::source_code::Locator; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for `CamelCase` imports that are aliased to constant-style names. - /// - /// ## Why is this bad? - /// [PEP 8] recommends naming conventions for classes, functions, - /// constants, and more. The use of inconsistent naming styles between - /// import and alias names may lead readers to expect an import to be of - /// another type (e.g., confuse a Python class with a constant). - /// - /// Import aliases should thus follow the same naming style as the member - /// being imported. - /// - /// ## Example - /// ```python - /// from example import MyClassName as MY_CLASS_NAME - /// ``` - /// - /// Use instead: - /// ```python - /// from example import MyClassName - /// ``` - /// - /// [PEP 8]: https://peps.python.org/pep-0008/ - pub struct CamelcaseImportedAsConstant { - pub name: String, - pub asname: String, - } -); +/// ## What it does +/// Checks for `CamelCase` imports that are aliased to constant-style names. +/// +/// ## Why is this bad? +/// [PEP 8] recommends naming conventions for classes, functions, +/// constants, and more. The use of inconsistent naming styles between +/// import and alias names may lead readers to expect an import to be of +/// another type (e.g., confuse a Python class with a constant). +/// +/// Import aliases should thus follow the same naming style as the member +/// being imported. +/// +/// ## Example +/// ```python +/// from example import MyClassName as MY_CLASS_NAME +/// ``` +/// +/// Use instead: +/// ```python +/// from example import MyClassName +/// ``` +/// +/// [PEP 8]: https://peps.python.org/pep-0008/ +#[violation] +pub struct CamelcaseImportedAsConstant { + pub name: String, + pub asname: String, +} + impl Violation for CamelcaseImportedAsConstant { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_lowercase.rs b/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_lowercase.rs index 95edf8156a..151baeeb31 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_lowercase.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/camelcase_imported_as_lowercase.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use ruff_python::str; use rustpython_parser::ast::Stmt; @@ -8,35 +8,35 @@ use crate::rules::pep8_naming::helpers; use crate::source_code::Locator; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for `CamelCase` imports that are aliased to lowercase names. - /// - /// ## Why is this bad? - /// [PEP 8] recommends naming conventions for classes, functions, - /// constants, and more. The use of inconsistent naming styles between - /// import and alias names may lead readers to expect an import to be of - /// another type (e.g., confuse a Python class with a constant). - /// - /// Import aliases should thus follow the same naming style as the member - /// being imported. - /// - /// ## Example - /// ```python - /// from example import MyClassName as myclassname - /// ``` - /// - /// Use instead: - /// ```python - /// from example import MyClassName - /// ``` - /// - /// [PEP 8]: https://peps.python.org/pep-0008/ - pub struct CamelcaseImportedAsLowercase { - pub name: String, - pub asname: String, - } -); +/// ## What it does +/// Checks for `CamelCase` imports that are aliased to lowercase names. +/// +/// ## Why is this bad? +/// [PEP 8] recommends naming conventions for classes, functions, +/// constants, and more. The use of inconsistent naming styles between +/// import and alias names may lead readers to expect an import to be of +/// another type (e.g., confuse a Python class with a constant). +/// +/// Import aliases should thus follow the same naming style as the member +/// being imported. +/// +/// ## Example +/// ```python +/// from example import MyClassName as myclassname +/// ``` +/// +/// Use instead: +/// ```python +/// from example import MyClassName +/// ``` +/// +/// [PEP 8]: https://peps.python.org/pep-0008/ +#[violation] +pub struct CamelcaseImportedAsLowercase { + pub name: String, + pub asname: String, +} + impl Violation for CamelcaseImportedAsLowercase { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pep8_naming/rules/constant_imported_as_non_constant.rs b/crates/ruff/src/rules/pep8_naming/rules/constant_imported_as_non_constant.rs index 883c0a82e6..47bdbf31df 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/constant_imported_as_non_constant.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/constant_imported_as_non_constant.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use ruff_python::str; use rustpython_parser::ast::Stmt; @@ -7,36 +7,36 @@ use crate::registry::Diagnostic; use crate::source_code::Locator; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for constant imports that are aliased to non-constant-style - /// names. - /// - /// ## Why is this bad? - /// [PEP 8] recommends naming conventions for classes, functions, - /// constants, and more. The use of inconsistent naming styles between - /// import and alias names may lead readers to expect an import to be of - /// another type (e.g., confuse a Python class with a constant). - /// - /// Import aliases should thus follow the same naming style as the member - /// being imported. - /// - /// ## Example - /// ```python - /// from example import CONSTANT_VALUE as ConstantValue - /// ``` - /// - /// Use instead: - /// ```python - /// from example import CONSTANT_VALUE - /// ``` - /// - /// [PEP 8]: https://peps.python.org/pep-0008/ - pub struct ConstantImportedAsNonConstant { - pub name: String, - pub asname: String, - } -); +/// ## What it does +/// Checks for constant imports that are aliased to non-constant-style +/// names. +/// +/// ## Why is this bad? +/// [PEP 8] recommends naming conventions for classes, functions, +/// constants, and more. The use of inconsistent naming styles between +/// import and alias names may lead readers to expect an import to be of +/// another type (e.g., confuse a Python class with a constant). +/// +/// Import aliases should thus follow the same naming style as the member +/// being imported. +/// +/// ## Example +/// ```python +/// from example import CONSTANT_VALUE as ConstantValue +/// ``` +/// +/// Use instead: +/// ```python +/// from example import CONSTANT_VALUE +/// ``` +/// +/// [PEP 8]: https://peps.python.org/pep-0008/ +#[violation] +pub struct ConstantImportedAsNonConstant { + pub name: String, + pub asname: String, +} + impl Violation for ConstantImportedAsNonConstant { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pep8_naming/rules/dunder_function_name.rs b/crates/ruff/src/rules/pep8_naming/rules/dunder_function_name.rs index 801d4a6243..4a688cc8ff 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/dunder_function_name.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/dunder_function_name.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Stmt; use crate::ast::helpers::identifier_range; @@ -7,33 +7,33 @@ use crate::registry::Diagnostic; use crate::source_code::Locator; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for functions with "dunder" names (that is, names with two - /// leading and trailing underscores) that are not documented. - /// - /// ## Why is this bad? - /// [PEP 8] recommends that only documented "dunder" methods are used: - /// - /// > ..."magic" objects or attributes that live in user-controlled - /// > namespaces. E.g. `__init__`, `__import__` or `__file__`. Never invent - /// > such names; only use them as documented. - /// - /// ## Example - /// ```python - /// def __my_function__(): - /// pass - /// ``` - /// - /// Use instead: - /// ```python - /// def my_function(): - /// pass - /// ``` - /// - /// [PEP 8]: https://peps.python.org/pep-0008/ - pub struct DunderFunctionName; -); +/// ## What it does +/// Checks for functions with "dunder" names (that is, names with two +/// leading and trailing underscores) that are not documented. +/// +/// ## Why is this bad? +/// [PEP 8] recommends that only documented "dunder" methods are used: +/// +/// > ..."magic" objects or attributes that live in user-controlled +/// > namespaces. E.g. `__init__`, `__import__` or `__file__`. Never invent +/// > such names; only use them as documented. +/// +/// ## Example +/// ```python +/// def __my_function__(): +/// pass +/// ``` +/// +/// Use instead: +/// ```python +/// def my_function(): +/// pass +/// ``` +/// +/// [PEP 8]: https://peps.python.org/pep-0008/ +#[violation] +pub struct DunderFunctionName; + impl Violation for DunderFunctionName { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pep8_naming/rules/error_suffix_on_exception_name.rs b/crates/ruff/src/rules/pep8_naming/rules/error_suffix_on_exception_name.rs index 07488cb033..9e829ced41 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/error_suffix_on_exception_name.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/error_suffix_on_exception_name.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind, Stmt}; use crate::ast::helpers::identifier_range; @@ -6,34 +6,34 @@ use crate::registry::Diagnostic; use crate::source_code::Locator; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for custom exception definitions that omit the `Error` suffix. - /// - /// ## Why is this bad? - /// The `Error` suffix is recommended by [PEP 8]: - /// - /// > Because exceptions should be classes, the class naming convention - /// > applies here. However, you should use the suffix `"Error"` on your - /// > exception names (if the exception actually is an error). - /// - /// ## Example - /// ```python - /// class Validation(Exception): - /// ... - /// ``` - /// - /// Use instead: - /// ```python - /// class ValidationError(Exception): - /// ... - /// ``` - /// - /// [PEP 8]: https://peps.python.org/pep-0008/#exception-names - pub struct ErrorSuffixOnExceptionName { - pub name: String, - } -); +/// ## What it does +/// Checks for custom exception definitions that omit the `Error` suffix. +/// +/// ## Why is this bad? +/// The `Error` suffix is recommended by [PEP 8]: +/// +/// > Because exceptions should be classes, the class naming convention +/// > applies here. However, you should use the suffix `"Error"` on your +/// > exception names (if the exception actually is an error). +/// +/// ## Example +/// ```python +/// class Validation(Exception): +/// ... +/// ``` +/// +/// Use instead: +/// ```python +/// class ValidationError(Exception): +/// ... +/// ``` +/// +/// [PEP 8]: https://peps.python.org/pep-0008/#exception-names +#[violation] +pub struct ErrorSuffixOnExceptionName { + pub name: String, +} + impl Violation for ErrorSuffixOnExceptionName { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pep8_naming/rules/invalid_argument_name.rs b/crates/ruff/src/rules/pep8_naming/rules/invalid_argument_name.rs index b867dc7d0c..98accf7384 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/invalid_argument_name.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/invalid_argument_name.rs @@ -1,15 +1,15 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Arg; use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct InvalidArgumentName { - pub name: String, - } -); +#[violation] +pub struct InvalidArgumentName { + pub name: String, +} + impl Violation for InvalidArgumentName { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pep8_naming/rules/invalid_class_name.rs b/crates/ruff/src/rules/pep8_naming/rules/invalid_class_name.rs index 42459e067c..9da62360ff 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/invalid_class_name.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/invalid_class_name.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Stmt; use crate::ast::helpers::identifier_range; @@ -6,40 +6,40 @@ use crate::registry::Diagnostic; use crate::source_code::Locator; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for class names that do not follow the `CamelCase` convention. - /// - /// ## Why is this bad? - /// [PEP 8] recommends the use of the `CapWords` (or `CamelCase`) convention - /// for class names: - /// - /// > Class names should normally use the `CapWords` convention. - /// > - /// > The naming convention for functions may be used instead in cases where the interface is - /// > documented and used primarily as a callable. - /// > - /// > Note that there is a separate convention for builtin names: most builtin names are single - /// > words (or two words run together), with the `CapWords` convention used only for exception - /// > names and builtin constants. - /// - /// ## Example - /// ```python - /// class my_class: - /// pass - /// ``` - /// - /// Use instead: - /// ```python - /// class MyClass: - /// pass - /// ``` - /// - /// [PEP 8]: https://peps.python.org/pep-0008/#class-names - pub struct InvalidClassName { - pub name: String, - } -); +/// ## What it does +/// Checks for class names that do not follow the `CamelCase` convention. +/// +/// ## Why is this bad? +/// [PEP 8] recommends the use of the `CapWords` (or `CamelCase`) convention +/// for class names: +/// +/// > Class names should normally use the `CapWords` convention. +/// > +/// > The naming convention for functions may be used instead in cases where the interface is +/// > documented and used primarily as a callable. +/// > +/// > Note that there is a separate convention for builtin names: most builtin names are single +/// > words (or two words run together), with the `CapWords` convention used only for exception +/// > names and builtin constants. +/// +/// ## Example +/// ```python +/// class my_class: +/// pass +/// ``` +/// +/// Use instead: +/// ```python +/// class MyClass: +/// pass +/// ``` +/// +/// [PEP 8]: https://peps.python.org/pep-0008/#class-names +#[violation] +pub struct InvalidClassName { + pub name: String, +} + impl Violation for InvalidClassName { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pep8_naming/rules/invalid_first_argument_name_for_class_method.rs b/crates/ruff/src/rules/pep8_naming/rules/invalid_first_argument_name_for_class_method.rs index e99ba1c132..035cdee741 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/invalid_first_argument_name_for_class_method.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/invalid_first_argument_name_for_class_method.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Arguments, Expr}; use crate::ast::function_type; @@ -7,46 +7,46 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for class methods that use a name other than `cls` for their - /// first argument. - /// - /// ## Why is this bad? - /// [PEP 8] recommends the use of `cls` as the first argument for all class - /// methods: - /// - /// > Always use `cls` for the first argument to class methods. - /// > - /// > If a function argument’s name clashes with a reserved keyword, it is generally better to - /// > append a single trailing underscore rather than use an abbreviation or spelling corruption. - /// > Thus `class_` is better than `clss`. (Perhaps better is to avoid such clashes by using a synonym.) - /// - /// ## Options - /// - `pep8-naming.classmethod-decorators` - /// - `pep8-naming.staticmethod-decorators` - /// - `pep8-naming.ignore-names` - /// - /// ## Example - /// ```python - /// class Example: - /// @classmethod - /// def function(self, data): - /// ... - /// ``` - /// - /// Use instead: - /// ```python - /// class Example: - /// @classmethod - /// def function(cls, data): - /// ... - /// ``` - /// - /// [PEP 8]: https://peps.python.org/pep-0008/#function-and-method-arguments - /// - pub struct InvalidFirstArgumentNameForClassMethod; -); +/// ## What it does +/// Checks for class methods that use a name other than `cls` for their +/// first argument. +/// +/// ## Why is this bad? +/// [PEP 8] recommends the use of `cls` as the first argument for all class +/// methods: +/// +/// > Always use `cls` for the first argument to class methods. +/// > +/// > If a function argument’s name clashes with a reserved keyword, it is generally better to +/// > append a single trailing underscore rather than use an abbreviation or spelling corruption. +/// > Thus `class_` is better than `clss`. (Perhaps better is to avoid such clashes by using a synonym.) +/// +/// ## Options +/// - `pep8-naming.classmethod-decorators` +/// - `pep8-naming.staticmethod-decorators` +/// - `pep8-naming.ignore-names` +/// +/// ## Example +/// ```python +/// class Example: +/// @classmethod +/// def function(self, data): +/// ... +/// ``` +/// +/// Use instead: +/// ```python +/// class Example: +/// @classmethod +/// def function(cls, data): +/// ... +/// ``` +/// +/// [PEP 8]: https://peps.python.org/pep-0008/#function-and-method-arguments +/// +#[violation] +pub struct InvalidFirstArgumentNameForClassMethod; + impl Violation for InvalidFirstArgumentNameForClassMethod { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pep8_naming/rules/invalid_first_argument_name_for_method.rs b/crates/ruff/src/rules/pep8_naming/rules/invalid_first_argument_name_for_method.rs index fbad2f9121..d753d3df3d 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/invalid_first_argument_name_for_method.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/invalid_first_argument_name_for_method.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Arguments, Expr}; use crate::ast::function_type; @@ -7,43 +7,43 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for instance methods that use a name other than `self` for their - /// first argument. - /// - /// ## Why is this bad? - /// [PEP 8] recommends the use of `self` as first argument for all instance - /// methods: - /// - /// > Always use self for the first argument to instance methods. - /// > - /// > If a function argument’s name clashes with a reserved keyword, it is generally better to - /// > append a single trailing underscore rather than use an abbreviation or spelling corruption. - /// > Thus `class_` is better than `clss`. (Perhaps better is to avoid such clashes by using a synonym.) - /// - /// ## Options - /// - `pep8-naming.classmethod-decorators` - /// - `pep8-naming.staticmethod-decorators` - /// - `pep8-naming.ignore-names` - /// - /// ## Example - /// ```python - /// class Example: - /// def function(cls, data): - /// ... - /// ``` - /// - /// Use instead: - /// ```python - /// class Example: - /// def function(self, data): - /// ... - /// ``` - /// - /// [PEP 8]: https://peps.python.org/pep-0008/#function-and-method-arguments - pub struct InvalidFirstArgumentNameForMethod; -); +/// ## What it does +/// Checks for instance methods that use a name other than `self` for their +/// first argument. +/// +/// ## Why is this bad? +/// [PEP 8] recommends the use of `self` as first argument for all instance +/// methods: +/// +/// > Always use self for the first argument to instance methods. +/// > +/// > If a function argument’s name clashes with a reserved keyword, it is generally better to +/// > append a single trailing underscore rather than use an abbreviation or spelling corruption. +/// > Thus `class_` is better than `clss`. (Perhaps better is to avoid such clashes by using a synonym.) +/// +/// ## Options +/// - `pep8-naming.classmethod-decorators` +/// - `pep8-naming.staticmethod-decorators` +/// - `pep8-naming.ignore-names` +/// +/// ## Example +/// ```python +/// class Example: +/// def function(cls, data): +/// ... +/// ``` +/// +/// Use instead: +/// ```python +/// class Example: +/// def function(self, data): +/// ... +/// ``` +/// +/// [PEP 8]: https://peps.python.org/pep-0008/#function-and-method-arguments +#[violation] +pub struct InvalidFirstArgumentNameForMethod; + impl Violation for InvalidFirstArgumentNameForMethod { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pep8_naming/rules/invalid_function_name.rs b/crates/ruff/src/rules/pep8_naming/rules/invalid_function_name.rs index c1b0112c29..bcf2b3b56d 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/invalid_function_name.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/invalid_function_name.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Stmt; use crate::ast::helpers::identifier_range; @@ -6,38 +6,38 @@ use crate::registry::Diagnostic; use crate::source_code::Locator; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for functions names that do not follow the `snake_case` naming - /// convention. - /// - /// ## Why is this bad? - /// [PEP 8] recommends that function names follow `snake_case`: - /// - /// > Function names should be lowercase, with words separated by underscores as necessary to - /// > improve readability. mixedCase is allowed only in contexts where that’s already the - /// > prevailing style (e.g. threading.py), to retain backwards compatibility. - /// - /// ## Options - /// - `pep8-naming.ignore-names` - /// - /// ## Example - /// ```python - /// def myFunction(): - /// pass - /// ``` - /// - /// Use instead: - /// ```python - /// def my_function(): - /// pass - /// ``` - /// - /// [PEP 8]: https://peps.python.org/pep-0008/#function-and-variable-names - pub struct InvalidFunctionName { - pub name: String, - } -); +/// ## What it does +/// Checks for functions names that do not follow the `snake_case` naming +/// convention. +/// +/// ## Why is this bad? +/// [PEP 8] recommends that function names follow `snake_case`: +/// +/// > Function names should be lowercase, with words separated by underscores as necessary to +/// > improve readability. mixedCase is allowed only in contexts where that’s already the +/// > prevailing style (e.g. threading.py), to retain backwards compatibility. +/// +/// ## Options +/// - `pep8-naming.ignore-names` +/// +/// ## Example +/// ```python +/// def myFunction(): +/// pass +/// ``` +/// +/// Use instead: +/// ```python +/// def my_function(): +/// pass +/// ``` +/// +/// [PEP 8]: https://peps.python.org/pep-0008/#function-and-variable-names +#[violation] +pub struct InvalidFunctionName { + pub name: String, +} + impl Violation for InvalidFunctionName { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pep8_naming/rules/invalid_module_name.rs b/crates/ruff/src/rules/pep8_naming/rules/invalid_module_name.rs index 10e4ab3192..c99c25492f 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/invalid_module_name.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/invalid_module_name.rs @@ -1,38 +1,38 @@ use std::path::Path; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use ruff_python::identifiers::is_module_name; use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for module names that do not follow the `snake_case` naming - /// convention. - /// - /// ## Why is this bad? - /// [PEP 8] recommends the use of the `snake_case` naming convention for - /// module names: - /// - /// > Modules should have short, all-lowercase names. Underscores can be used in the - /// > module name if it improves readability. Python packages should also have short, - /// > all-lowercase names, although the use of underscores is discouraged. - /// > - /// > When an extension module written in C or C++ has an accompanying Python module that - /// > provides a higher level (e.g. more object oriented) interface, the C/C++ module has - /// > a leading underscore (e.g. `_socket`). - /// - /// ## Example - /// - Instead of `example-module-name` or `example module name`, use `example_module_name`. - /// - Instead of `ExampleModule`, use `example_module`. - /// - /// [PEP 8]: https://peps.python.org/pep-0008/#package-and-module-names - pub struct InvalidModuleName { - pub name: String, - } -); +/// ## What it does +/// Checks for module names that do not follow the `snake_case` naming +/// convention. +/// +/// ## Why is this bad? +/// [PEP 8] recommends the use of the `snake_case` naming convention for +/// module names: +/// +/// > Modules should have short, all-lowercase names. Underscores can be used in the +/// > module name if it improves readability. Python packages should also have short, +/// > all-lowercase names, although the use of underscores is discouraged. +/// > +/// > When an extension module written in C or C++ has an accompanying Python module that +/// > provides a higher level (e.g. more object oriented) interface, the C/C++ module has +/// > a leading underscore (e.g. `_socket`). +/// +/// ## Example +/// - Instead of `example-module-name` or `example module name`, use `example_module_name`. +/// - Instead of `ExampleModule`, use `example_module`. +/// +/// [PEP 8]: https://peps.python.org/pep-0008/#package-and-module-names +#[violation] +pub struct InvalidModuleName { + pub name: String, +} + impl Violation for InvalidModuleName { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pep8_naming/rules/lowercase_imported_as_non_lowercase.rs b/crates/ruff/src/rules/pep8_naming/rules/lowercase_imported_as_non_lowercase.rs index 5547fc8252..e91ff6c189 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/lowercase_imported_as_non_lowercase.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/lowercase_imported_as_non_lowercase.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use ruff_python::str; use rustpython_parser::ast::Stmt; @@ -7,35 +7,35 @@ use crate::registry::Diagnostic; use crate::source_code::Locator; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for lowercase imports that are aliased to non-lowercase names. - /// - /// ## Why is this bad? - /// [PEP 8] recommends naming conventions for classes, functions, - /// constants, and more. The use of inconsistent naming styles between - /// import and alias names may lead readers to expect an import to be of - /// another type (e.g., confuse a Python class with a constant). - /// - /// Import aliases should thus follow the same naming style as the member - /// being imported. - /// - /// ## Example - /// ```python - /// from example import myclassname as MyClassName - /// ``` - /// - /// Use instead: - /// ```python - /// from example import myclassname - /// ``` - /// - /// [PEP 8]: https://peps.python.org/pep-0008/ - pub struct LowercaseImportedAsNonLowercase { - pub name: String, - pub asname: String, - } -); +/// ## What it does +/// Checks for lowercase imports that are aliased to non-lowercase names. +/// +/// ## Why is this bad? +/// [PEP 8] recommends naming conventions for classes, functions, +/// constants, and more. The use of inconsistent naming styles between +/// import and alias names may lead readers to expect an import to be of +/// another type (e.g., confuse a Python class with a constant). +/// +/// Import aliases should thus follow the same naming style as the member +/// being imported. +/// +/// ## Example +/// ```python +/// from example import myclassname as MyClassName +/// ``` +/// +/// Use instead: +/// ```python +/// from example import myclassname +/// ``` +/// +/// [PEP 8]: https://peps.python.org/pep-0008/ +#[violation] +pub struct LowercaseImportedAsNonLowercase { + pub name: String, + pub asname: String, +} + impl Violation for LowercaseImportedAsNonLowercase { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pep8_naming/rules/mixed_case_variable_in_class_scope.rs b/crates/ruff/src/rules/pep8_naming/rules/mixed_case_variable_in_class_scope.rs index 22f0d4c228..dde630d38f 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/mixed_case_variable_in_class_scope.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/mixed_case_variable_in_class_scope.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, Stmt}; use crate::ast::types::Range; @@ -7,11 +7,11 @@ use crate::registry::Diagnostic; use crate::rules::pep8_naming::helpers; use crate::violation::Violation; -define_violation!( - pub struct MixedCaseVariableInClassScope { - pub name: String, - } -); +#[violation] +pub struct MixedCaseVariableInClassScope { + pub name: String, +} + impl Violation for MixedCaseVariableInClassScope { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pep8_naming/rules/mixed_case_variable_in_global_scope.rs b/crates/ruff/src/rules/pep8_naming/rules/mixed_case_variable_in_global_scope.rs index 83707e0771..46d1ad5d63 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/mixed_case_variable_in_global_scope.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/mixed_case_variable_in_global_scope.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, Stmt}; use crate::ast::types::Range; @@ -7,11 +7,11 @@ use crate::registry::Diagnostic; use crate::rules::pep8_naming::helpers; use crate::violation::Violation; -define_violation!( - pub struct MixedCaseVariableInGlobalScope { - pub name: String, - } -); +#[violation] +pub struct MixedCaseVariableInGlobalScope { + pub name: String, +} + impl Violation for MixedCaseVariableInGlobalScope { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pep8_naming/rules/non_lowercase_variable_in_function.rs b/crates/ruff/src/rules/pep8_naming/rules/non_lowercase_variable_in_function.rs index 80ec2e7219..c64e933a8d 100644 --- a/crates/ruff/src/rules/pep8_naming/rules/non_lowercase_variable_in_function.rs +++ b/crates/ruff/src/rules/pep8_naming/rules/non_lowercase_variable_in_function.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, Stmt}; use crate::ast::types::Range; @@ -7,40 +7,40 @@ use crate::registry::Diagnostic; use crate::rules::pep8_naming::helpers; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for the use of non-lowercase variable names in functions. - /// - /// ## Why is this bad? - /// [PEP 8] recommends that all function variables use lowercase names: - /// - /// > Function names should be lowercase, with words separated by underscores as necessary to - /// > improve readability. Variable names follow the same convention as function names. mixedCase - /// > is allowed only in contexts where that's already the prevailing style (e.g. threading.py), - /// > to retain backwards compatibility. - /// - /// ## Options - /// - `pep8-naming.ignore-names` - /// - /// ## Example - /// ```python - /// def my_function(a): - /// B = a + 3 - /// return B - /// ``` - /// - /// Use instead: - /// ```python - /// def my_function(a): - /// b = a + 3 - /// return b - /// ``` - /// - /// [PEP 8]: https://peps.python.org/pep-0008/#function-and-variable-names - pub struct NonLowercaseVariableInFunction { - pub name: String, - } -); +/// ## What it does +/// Checks for the use of non-lowercase variable names in functions. +/// +/// ## Why is this bad? +/// [PEP 8] recommends that all function variables use lowercase names: +/// +/// > Function names should be lowercase, with words separated by underscores as necessary to +/// > improve readability. Variable names follow the same convention as function names. mixedCase +/// > is allowed only in contexts where that's already the prevailing style (e.g. threading.py), +/// > to retain backwards compatibility. +/// +/// ## Options +/// - `pep8-naming.ignore-names` +/// +/// ## Example +/// ```python +/// def my_function(a): +/// B = a + 3 +/// return B +/// ``` +/// +/// Use instead: +/// ```python +/// def my_function(a): +/// b = a + 3 +/// return b +/// ``` +/// +/// [PEP 8]: https://peps.python.org/pep-0008/#function-and-variable-names +#[violation] +pub struct NonLowercaseVariableInFunction { + pub name: String, +} + impl Violation for NonLowercaseVariableInFunction { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/ambiguous_class_name.rs b/crates/ruff/src/rules/pycodestyle/rules/ambiguous_class_name.rs index f8e1b26270..feeba4ab33 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/ambiguous_class_name.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/ambiguous_class_name.rs @@ -1,13 +1,13 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::rules::pycodestyle::helpers::is_ambiguous_name; use crate::violation::Violation; -define_violation!( - pub struct AmbiguousClassName(pub String); -); +#[violation] +pub struct AmbiguousClassName(pub String); + impl Violation for AmbiguousClassName { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/ambiguous_function_name.rs b/crates/ruff/src/rules/pycodestyle/rules/ambiguous_function_name.rs index 70f4916e43..42cf4d9abd 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/ambiguous_function_name.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/ambiguous_function_name.rs @@ -1,13 +1,13 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::rules::pycodestyle::helpers::is_ambiguous_name; use crate::violation::Violation; -define_violation!( - pub struct AmbiguousFunctionName(pub String); -); +#[violation] +pub struct AmbiguousFunctionName(pub String); + impl Violation for AmbiguousFunctionName { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/ambiguous_variable_name.rs b/crates/ruff/src/rules/pycodestyle/rules/ambiguous_variable_name.rs index f1078500c0..515e3225cc 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/ambiguous_variable_name.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/ambiguous_variable_name.rs @@ -1,13 +1,13 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::rules::pycodestyle::helpers::is_ambiguous_name; use crate::violation::Violation; -define_violation!( - pub struct AmbiguousVariableName(pub String); -); +#[violation] +pub struct AmbiguousVariableName(pub String); + impl Violation for AmbiguousVariableName { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/bare_except.rs b/crates/ruff/src/rules/pycodestyle/rules/bare_except.rs index bea4cd4d0c..63a017f6d7 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/bare_except.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/bare_except.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Excepthandler, Expr, Stmt, StmtKind}; use crate::ast::helpers::except_range; @@ -6,38 +6,38 @@ use crate::registry::Diagnostic; use crate::source_code::Locator; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for bare `except` catches in `try`-`except` statements. - /// - /// ## Why is this bad? - /// A bare `except` catches `BaseException` which includes - /// `KeyboardInterrupt`, `SystemExit`, `Exception`, and others. Catching - /// `BaseException` can make it hard to interrupt the program (e.g., with - /// Ctrl-C) and disguise other problems. - /// - /// ## Example - /// ```python - /// try: - /// raise KeyboardInterrupt("You probably don't mean to break CTRL-C.") - /// except: - /// print("But a bare `except` will ignore keyboard interrupts.") - /// ``` - /// - /// Use instead: - /// ```python - /// try: - /// do_something_that_might_break() - /// except MoreSpecificException as e: - /// handle_error(e) - /// ``` - /// - /// ## References - /// - [PEP 8](https://www.python.org/dev/peps/pep-0008/#programming-recommendations) - /// - [Python: "Exception hierarchy"](https://docs.python.org/3/library/exceptions.html#exception-hierarchy) - /// - [Google Python Style Guide: "Exceptions"](https://google.github.io/styleguide/pyguide.html#24-exceptions) - pub struct BareExcept; -); +/// ## What it does +/// Checks for bare `except` catches in `try`-`except` statements. +/// +/// ## Why is this bad? +/// A bare `except` catches `BaseException` which includes +/// `KeyboardInterrupt`, `SystemExit`, `Exception`, and others. Catching +/// `BaseException` can make it hard to interrupt the program (e.g., with +/// Ctrl-C) and disguise other problems. +/// +/// ## Example +/// ```python +/// try: +/// raise KeyboardInterrupt("You probably don't mean to break CTRL-C.") +/// except: +/// print("But a bare `except` will ignore keyboard interrupts.") +/// ``` +/// +/// Use instead: +/// ```python +/// try: +/// do_something_that_might_break() +/// except MoreSpecificException as e: +/// handle_error(e) +/// ``` +/// +/// ## References +/// - [PEP 8](https://www.python.org/dev/peps/pep-0008/#programming-recommendations) +/// - [Python: "Exception hierarchy"](https://docs.python.org/3/library/exceptions.html#exception-hierarchy) +/// - [Google Python Style Guide: "Exceptions"](https://google.github.io/styleguide/pyguide.html#24-exceptions) +#[violation] +pub struct BareExcept; + impl Violation for BareExcept { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/compound_statements.rs b/crates/ruff/src/rules/pycodestyle/rules/compound_statements.rs index 8138cd70cd..62f0dcfbb2 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/compound_statements.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/compound_statements.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::lexer::LexResult; use rustpython_parser::Tok; @@ -8,9 +8,9 @@ use crate::registry::{Diagnostic, Rule}; use crate::settings::{flags, Settings}; use crate::violation::{AlwaysAutofixableViolation, Violation}; -define_violation!( - pub struct MultipleStatementsOnOneLineColon; -); +#[violation] +pub struct MultipleStatementsOnOneLineColon; + impl Violation for MultipleStatementsOnOneLineColon { #[derive_message_formats] fn message(&self) -> String { @@ -18,9 +18,9 @@ impl Violation for MultipleStatementsOnOneLineColon { } } -define_violation!( - pub struct MultipleStatementsOnOneLineSemicolon; -); +#[violation] +pub struct MultipleStatementsOnOneLineSemicolon; + impl Violation for MultipleStatementsOnOneLineSemicolon { #[derive_message_formats] fn message(&self) -> String { @@ -28,9 +28,9 @@ impl Violation for MultipleStatementsOnOneLineSemicolon { } } -define_violation!( - pub struct UselessSemicolon; -); +#[violation] +pub struct UselessSemicolon; + impl AlwaysAutofixableViolation for UselessSemicolon { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/doc_line_too_long.rs b/crates/ruff/src/rules/pycodestyle/rules/doc_line_too_long.rs index 91ffdc60be..97825fc26c 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/doc_line_too_long.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/doc_line_too_long.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Location; use crate::ast::types::Range; @@ -7,9 +7,9 @@ use crate::rules::pycodestyle::helpers::is_overlong; use crate::settings::Settings; use crate::violation::Violation; -define_violation!( - pub struct DocLineTooLong(pub usize, pub usize); -); +#[violation] +pub struct DocLineTooLong(pub usize, pub usize); + impl Violation for DocLineTooLong { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/errors.rs b/crates/ruff/src/rules/pycodestyle/rules/errors.rs index 498485fb55..6333b09a35 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/errors.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/errors.rs @@ -1,15 +1,15 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ParseError; use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct IOError { - pub message: String, - } -); +#[violation] +pub struct IOError { + pub message: String, +} + impl Violation for IOError { #[derive_message_formats] fn message(&self) -> String { @@ -18,11 +18,11 @@ impl Violation for IOError { } } -define_violation!( - pub struct SyntaxError { - pub message: String, - } -); +#[violation] +pub struct SyntaxError { + pub message: String, +} + impl Violation for SyntaxError { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/extraneous_whitespace.rs b/crates/ruff/src/rules/pycodestyle/rules/extraneous_whitespace.rs index 478180bca3..0c0c965718 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/extraneous_whitespace.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/extraneous_whitespace.rs @@ -2,14 +2,14 @@ use once_cell::sync::Lazy; use regex::Regex; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::registry::DiagnosticKind; use crate::violation::Violation; -define_violation!( - pub struct WhitespaceAfterOpenBracket; -); +#[violation] +pub struct WhitespaceAfterOpenBracket; + impl Violation for WhitespaceAfterOpenBracket { #[derive_message_formats] fn message(&self) -> String { @@ -17,9 +17,9 @@ impl Violation for WhitespaceAfterOpenBracket { } } -define_violation!( - pub struct WhitespaceBeforeCloseBracket; -); +#[violation] +pub struct WhitespaceBeforeCloseBracket; + impl Violation for WhitespaceBeforeCloseBracket { #[derive_message_formats] fn message(&self) -> String { @@ -27,9 +27,9 @@ impl Violation for WhitespaceBeforeCloseBracket { } } -define_violation!( - pub struct WhitespaceBeforePunctuation; -); +#[violation] +pub struct WhitespaceBeforePunctuation; + impl Violation for WhitespaceBeforePunctuation { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/imports.rs b/crates/ruff/src/rules/pycodestyle/rules/imports.rs index bd9fcb9d4c..fc27ea04fb 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/imports.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/imports.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Alias, Stmt}; use crate::ast::types::Range; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct MultipleImportsOnOneLine; -); +#[violation] +pub struct MultipleImportsOnOneLine; + impl Violation for MultipleImportsOnOneLine { #[derive_message_formats] fn message(&self) -> String { @@ -16,9 +16,9 @@ impl Violation for MultipleImportsOnOneLine { } } -define_violation!( - pub struct ModuleImportNotAtTopOfFile; -); +#[violation] +pub struct ModuleImportNotAtTopOfFile; + impl Violation for ModuleImportNotAtTopOfFile { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/indentation.rs b/crates/ruff/src/rules/pycodestyle/rules/indentation.rs index 91dbbb9186..18630ece02 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/indentation.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/indentation.rs @@ -1,16 +1,16 @@ #![allow(dead_code, unused_imports, unused_variables)] -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::registry::DiagnosticKind; use crate::rules::pycodestyle::logical_lines::LogicalLine; use crate::violation::Violation; -define_violation!( - pub struct IndentationWithInvalidMultiple { - pub indent_size: usize, - } -); +#[violation] +pub struct IndentationWithInvalidMultiple { + pub indent_size: usize, +} + impl Violation for IndentationWithInvalidMultiple { #[derive_message_formats] fn message(&self) -> String { @@ -19,11 +19,11 @@ impl Violation for IndentationWithInvalidMultiple { } } -define_violation!( - pub struct IndentationWithInvalidMultipleComment { - pub indent_size: usize, - } -); +#[violation] +pub struct IndentationWithInvalidMultipleComment { + pub indent_size: usize, +} + impl Violation for IndentationWithInvalidMultipleComment { #[derive_message_formats] fn message(&self) -> String { @@ -32,9 +32,9 @@ impl Violation for IndentationWithInvalidMultipleComment { } } -define_violation!( - pub struct NoIndentedBlock; -); +#[violation] +pub struct NoIndentedBlock; + impl Violation for NoIndentedBlock { #[derive_message_formats] fn message(&self) -> String { @@ -42,9 +42,9 @@ impl Violation for NoIndentedBlock { } } -define_violation!( - pub struct NoIndentedBlockComment; -); +#[violation] +pub struct NoIndentedBlockComment; + impl Violation for NoIndentedBlockComment { #[derive_message_formats] fn message(&self) -> String { @@ -52,9 +52,9 @@ impl Violation for NoIndentedBlockComment { } } -define_violation!( - pub struct UnexpectedIndentation; -); +#[violation] +pub struct UnexpectedIndentation; + impl Violation for UnexpectedIndentation { #[derive_message_formats] fn message(&self) -> String { @@ -62,9 +62,9 @@ impl Violation for UnexpectedIndentation { } } -define_violation!( - pub struct UnexpectedIndentationComment; -); +#[violation] +pub struct UnexpectedIndentationComment; + impl Violation for UnexpectedIndentationComment { #[derive_message_formats] fn message(&self) -> String { @@ -72,9 +72,9 @@ impl Violation for UnexpectedIndentationComment { } } -define_violation!( - pub struct OverIndented; -); +#[violation] +pub struct OverIndented; + impl Violation for OverIndented { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/indentation_contains_tabs.rs b/crates/ruff/src/rules/pycodestyle/rules/indentation_contains_tabs.rs index 3ec3600984..ebe9f79075 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/indentation_contains_tabs.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/indentation_contains_tabs.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Location; use crate::ast::types::Range; @@ -6,9 +6,9 @@ use crate::ast::whitespace::leading_space; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct IndentationContainsTabs; -); +#[violation] +pub struct IndentationContainsTabs; + impl Violation for IndentationContainsTabs { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/invalid_escape_sequence.rs b/crates/ruff/src/rules/pycodestyle/rules/invalid_escape_sequence.rs index 4fa5fbf38d..837f9d1168 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/invalid_escape_sequence.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/invalid_escape_sequence.rs @@ -2,7 +2,7 @@ use anyhow::{bail, Result}; use log::error; use rustpython_parser::ast::Location; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::fix::Fix; @@ -10,9 +10,9 @@ use crate::registry::Diagnostic; use crate::source_code::Locator; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct InvalidEscapeSequence(pub char); -); +#[violation] +pub struct InvalidEscapeSequence(pub char); + impl AlwaysAutofixableViolation for InvalidEscapeSequence { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/lambda_assignment.rs b/crates/ruff/src/rules/pycodestyle/rules/lambda_assignment.rs index adad2e0ed7..1ffbdae22f 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/lambda_assignment.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/lambda_assignment.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Arguments, Expr, ExprKind, Location, Stmt, StmtKind}; use crate::ast::helpers::{match_leading_content, match_trailing_content, unparse_stmt}; @@ -10,12 +10,12 @@ use crate::registry::Diagnostic; use crate::source_code::Stylist; use crate::violation::{AutofixKind, Availability, Violation}; -define_violation!( - pub struct LambdaAssignment { - pub name: String, - pub fixable: bool, - } -); +#[violation] +pub struct LambdaAssignment { + pub name: String, + pub fixable: bool, +} + impl Violation for LambdaAssignment { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Sometimes)); diff --git a/crates/ruff/src/rules/pycodestyle/rules/line_too_long.rs b/crates/ruff/src/rules/pycodestyle/rules/line_too_long.rs index 8ef2a0d42b..f598816452 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/line_too_long.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/line_too_long.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Location; use crate::ast::types::Range; @@ -7,9 +7,9 @@ use crate::rules::pycodestyle::helpers::is_overlong; use crate::settings::Settings; use crate::violation::Violation; -define_violation!( - pub struct LineTooLong(pub usize, pub usize); -); +#[violation] +pub struct LineTooLong(pub usize, pub usize); + impl Violation for LineTooLong { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/literal_comparisons.rs b/crates/ruff/src/rules/pycodestyle/rules/literal_comparisons.rs index 36d46ae124..2698c8197a 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/literal_comparisons.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/literal_comparisons.rs @@ -1,5 +1,5 @@ use itertools::izip; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustc_hash::FxHashMap; use rustpython_parser::ast::{Cmpop, Constant, Expr, ExprKind}; use serde::{Deserialize, Serialize}; @@ -28,9 +28,9 @@ impl From<&Cmpop> for EqCmpop { } } -define_violation!( - pub struct NoneComparison(pub EqCmpop); -); +#[violation] +pub struct NoneComparison(pub EqCmpop); + impl AlwaysAutofixableViolation for NoneComparison { #[derive_message_formats] fn message(&self) -> String { @@ -50,9 +50,9 @@ impl AlwaysAutofixableViolation for NoneComparison { } } -define_violation!( - pub struct TrueFalseComparison(pub bool, pub EqCmpop); -); +#[violation] +pub struct TrueFalseComparison(pub bool, pub EqCmpop); + impl AlwaysAutofixableViolation for TrueFalseComparison { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/missing_whitespace_after_keyword.rs b/crates/ruff/src/rules/pycodestyle/rules/missing_whitespace_after_keyword.rs index 0262744760..ddcbd4e2bd 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/missing_whitespace_after_keyword.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/missing_whitespace_after_keyword.rs @@ -3,15 +3,15 @@ use rustpython_parser::ast::Location; use rustpython_parser::Tok; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::registry::DiagnosticKind; use crate::rules::pycodestyle::helpers::{is_keyword_token, is_singleton_token}; use crate::violation::Violation; -define_violation!( - pub struct MissingWhitespaceAfterKeyword; -); +#[violation] +pub struct MissingWhitespaceAfterKeyword; + impl Violation for MissingWhitespaceAfterKeyword { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/mixed_spaces_and_tabs.rs b/crates/ruff/src/rules/pycodestyle/rules/mixed_spaces_and_tabs.rs index 765c3b1010..12c53e6ac3 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/mixed_spaces_and_tabs.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/mixed_spaces_and_tabs.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Location; use crate::ast::types::Range; @@ -6,9 +6,9 @@ use crate::ast::whitespace::leading_space; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct MixedSpacesAndTabs; -); +#[violation] +pub struct MixedSpacesAndTabs; + impl Violation for MixedSpacesAndTabs { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/no_newline_at_end_of_file.rs b/crates/ruff/src/rules/pycodestyle/rules/no_newline_at_end_of_file.rs index 424fbce48a..226a85b1bb 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/no_newline_at_end_of_file.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/no_newline_at_end_of_file.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Location; use crate::ast::types::Range; @@ -7,9 +7,9 @@ use crate::registry::Diagnostic; use crate::source_code::Stylist; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct NoNewLineAtEndOfFile; -); +#[violation] +pub struct NoNewLineAtEndOfFile; + impl AlwaysAutofixableViolation for NoNewLineAtEndOfFile { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/not_tests.rs b/crates/ruff/src/rules/pycodestyle/rules/not_tests.rs index ff99e80d28..32b3008c54 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/not_tests.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/not_tests.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Cmpop, Expr, ExprKind, Unaryop}; use crate::ast::types::Range; @@ -8,9 +8,9 @@ use crate::registry::Diagnostic; use crate::rules::pycodestyle::helpers::compare; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct NotInTest; -); +#[violation] +pub struct NotInTest; + impl AlwaysAutofixableViolation for NotInTest { #[derive_message_formats] fn message(&self) -> String { @@ -22,9 +22,9 @@ impl AlwaysAutofixableViolation for NotInTest { } } -define_violation!( - pub struct NotIsTest; -); +#[violation] +pub struct NotIsTest; + impl AlwaysAutofixableViolation for NotIsTest { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/space_around_operator.rs b/crates/ruff/src/rules/pycodestyle/rules/space_around_operator.rs index adfee0d4bd..753380b77f 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/space_around_operator.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/space_around_operator.rs @@ -2,14 +2,14 @@ use once_cell::sync::Lazy; use regex::Regex; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::registry::DiagnosticKind; use crate::violation::Violation; -define_violation!( - pub struct TabBeforeOperator; -); +#[violation] +pub struct TabBeforeOperator; + impl Violation for TabBeforeOperator { #[derive_message_formats] fn message(&self) -> String { @@ -17,9 +17,9 @@ impl Violation for TabBeforeOperator { } } -define_violation!( - pub struct MultipleSpacesBeforeOperator; -); +#[violation] +pub struct MultipleSpacesBeforeOperator; + impl Violation for MultipleSpacesBeforeOperator { #[derive_message_formats] fn message(&self) -> String { @@ -27,9 +27,9 @@ impl Violation for MultipleSpacesBeforeOperator { } } -define_violation!( - pub struct TabAfterOperator; -); +#[violation] +pub struct TabAfterOperator; + impl Violation for TabAfterOperator { #[derive_message_formats] fn message(&self) -> String { @@ -37,9 +37,9 @@ impl Violation for TabAfterOperator { } } -define_violation!( - pub struct MultipleSpacesAfterOperator; -); +#[violation] +pub struct MultipleSpacesAfterOperator; + impl Violation for MultipleSpacesAfterOperator { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/trailing_whitespace.rs b/crates/ruff/src/rules/pycodestyle/rules/trailing_whitespace.rs index 46c5fb191a..b6b615ad7b 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/trailing_whitespace.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/trailing_whitespace.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Location; use crate::ast::types::Range; @@ -7,9 +7,9 @@ use crate::registry::{Diagnostic, Rule}; use crate::settings::{flags, Settings}; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct TrailingWhitespace; -); +#[violation] +pub struct TrailingWhitespace; + impl AlwaysAutofixableViolation for TrailingWhitespace { #[derive_message_formats] fn message(&self) -> String { @@ -21,9 +21,9 @@ impl AlwaysAutofixableViolation for TrailingWhitespace { } } -define_violation!( - pub struct BlankLineContainsWhitespace; -); +#[violation] +pub struct BlankLineContainsWhitespace; + impl AlwaysAutofixableViolation for BlankLineContainsWhitespace { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/type_comparison.rs b/crates/ruff/src/rules/pycodestyle/rules/type_comparison.rs index 50baaeb715..3bc76cabe4 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/type_comparison.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/type_comparison.rs @@ -1,14 +1,14 @@ use itertools::izip; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Cmpop, Constant, Expr, ExprKind}; use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct TypeComparison; -); +#[violation] +pub struct TypeComparison; + impl Violation for TypeComparison { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/whitespace_around_keywords.rs b/crates/ruff/src/rules/pycodestyle/rules/whitespace_around_keywords.rs index f887df81b7..f2c654ca87 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/whitespace_around_keywords.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/whitespace_around_keywords.rs @@ -3,14 +3,14 @@ use once_cell::sync::Lazy; use regex::Regex; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::registry::DiagnosticKind; use crate::violation::Violation; -define_violation!( - pub struct MultipleSpacesAfterKeyword; -); +#[violation] +pub struct MultipleSpacesAfterKeyword; + impl Violation for MultipleSpacesAfterKeyword { #[derive_message_formats] fn message(&self) -> String { @@ -18,9 +18,9 @@ impl Violation for MultipleSpacesAfterKeyword { } } -define_violation!( - pub struct MultipleSpacesBeforeKeyword; -); +#[violation] +pub struct MultipleSpacesBeforeKeyword; + impl Violation for MultipleSpacesBeforeKeyword { #[derive_message_formats] fn message(&self) -> String { @@ -28,9 +28,9 @@ impl Violation for MultipleSpacesBeforeKeyword { } } -define_violation!( - pub struct TabAfterKeyword; -); +#[violation] +pub struct TabAfterKeyword; + impl Violation for TabAfterKeyword { #[derive_message_formats] fn message(&self) -> String { @@ -38,9 +38,9 @@ impl Violation for TabAfterKeyword { } } -define_violation!( - pub struct TabBeforeKeyword; -); +#[violation] +pub struct TabBeforeKeyword; + impl Violation for TabBeforeKeyword { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/whitespace_around_named_parameter_equals.rs b/crates/ruff/src/rules/pycodestyle/rules/whitespace_around_named_parameter_equals.rs index 7b257caae9..a34c3141e5 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/whitespace_around_named_parameter_equals.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/whitespace_around_named_parameter_equals.rs @@ -5,7 +5,7 @@ use rustpython_parser::Tok; use once_cell::sync::Lazy; use regex::Regex; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; #[cfg(feature = "logical_lines")] use crate::rules::pycodestyle::helpers::is_op_token; @@ -13,9 +13,9 @@ use crate::rules::pycodestyle::helpers::is_op_token; use crate::registry::DiagnosticKind; use crate::violation::Violation; -define_violation!( - pub struct UnexpectedSpacesAroundKeywordParameterEquals; -); +#[violation] +pub struct UnexpectedSpacesAroundKeywordParameterEquals; + impl Violation for UnexpectedSpacesAroundKeywordParameterEquals { #[derive_message_formats] fn message(&self) -> String { @@ -23,9 +23,9 @@ impl Violation for UnexpectedSpacesAroundKeywordParameterEquals { } } -define_violation!( - pub struct MissingWhitespaceAroundParameterEquals; -); +#[violation] +pub struct MissingWhitespaceAroundParameterEquals; + impl Violation for MissingWhitespaceAroundParameterEquals { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pycodestyle/rules/whitespace_before_comment.rs b/crates/ruff/src/rules/pycodestyle/rules/whitespace_before_comment.rs index 133aa3735c..0c5d7b479d 100644 --- a/crates/ruff/src/rules/pycodestyle/rules/whitespace_before_comment.rs +++ b/crates/ruff/src/rules/pycodestyle/rules/whitespace_before_comment.rs @@ -1,6 +1,6 @@ #![allow(dead_code, unused_imports, unused_variables)] -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Location; use rustpython_parser::Tok; @@ -9,9 +9,9 @@ use crate::registry::DiagnosticKind; use crate::source_code::Locator; use crate::violation::Violation; -define_violation!( - pub struct TooFewSpacesBeforeInlineComment; -); +#[violation] +pub struct TooFewSpacesBeforeInlineComment; + impl Violation for TooFewSpacesBeforeInlineComment { #[derive_message_formats] fn message(&self) -> String { @@ -19,9 +19,9 @@ impl Violation for TooFewSpacesBeforeInlineComment { } } -define_violation!( - pub struct NoSpaceAfterInlineComment; -); +#[violation] +pub struct NoSpaceAfterInlineComment; + impl Violation for NoSpaceAfterInlineComment { #[derive_message_formats] fn message(&self) -> String { @@ -29,9 +29,9 @@ impl Violation for NoSpaceAfterInlineComment { } } -define_violation!( - pub struct NoSpaceAfterBlockComment; -); +#[violation] +pub struct NoSpaceAfterBlockComment; + impl Violation for NoSpaceAfterBlockComment { #[derive_message_formats] fn message(&self) -> String { @@ -39,9 +39,9 @@ impl Violation for NoSpaceAfterBlockComment { } } -define_violation!( - pub struct MultipleLeadingHashesForBlockComment; -); +#[violation] +pub struct MultipleLeadingHashesForBlockComment; + impl Violation for MultipleLeadingHashesForBlockComment { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pydocstyle/rules/backslashes.rs b/crates/ruff/src/rules/pydocstyle/rules/backslashes.rs index 5094a54fbf..82e26cda99 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/backslashes.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/backslashes.rs @@ -1,6 +1,6 @@ use once_cell::sync::Lazy; use regex::Regex; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; @@ -8,9 +8,9 @@ use crate::docstrings::definition::Docstring; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct EscapeSequenceInDocstring; -); +#[violation] +pub struct EscapeSequenceInDocstring; + impl Violation for EscapeSequenceInDocstring { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pydocstyle/rules/blank_after_summary.rs b/crates/ruff/src/rules/pydocstyle/rules/blank_after_summary.rs index dfd5673505..69de33d7c4 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/blank_after_summary.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/blank_after_summary.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; @@ -8,11 +8,11 @@ use crate::message::Location; use crate::registry::Diagnostic; use crate::violation::{AutofixKind, Availability, Violation}; -define_violation!( - pub struct BlankLineAfterSummary { - pub num_lines: usize, - } -); +#[violation] +pub struct BlankLineAfterSummary { + pub num_lines: usize, +} + fn fmt_blank_line_after_summary_autofix_msg(_: &BlankLineAfterSummary) -> String { "Insert single blank line".to_string() } diff --git a/crates/ruff/src/rules/pydocstyle/rules/blank_before_after_class.rs b/crates/ruff/src/rules/pydocstyle/rules/blank_before_after_class.rs index e1455dffbb..9bf75d4f08 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/blank_before_after_class.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/blank_before_after_class.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; @@ -8,11 +8,11 @@ use crate::message::Location; use crate::registry::{Diagnostic, Rule}; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct OneBlankLineBeforeClass { - pub lines: usize, - } -); +#[violation] +pub struct OneBlankLineBeforeClass { + pub lines: usize, +} + impl AlwaysAutofixableViolation for OneBlankLineBeforeClass { #[derive_message_formats] fn message(&self) -> String { @@ -24,11 +24,11 @@ impl AlwaysAutofixableViolation for OneBlankLineBeforeClass { } } -define_violation!( - pub struct OneBlankLineAfterClass { - pub lines: usize, - } -); +#[violation] +pub struct OneBlankLineAfterClass { + pub lines: usize, +} + impl AlwaysAutofixableViolation for OneBlankLineAfterClass { #[derive_message_formats] fn message(&self) -> String { @@ -40,11 +40,11 @@ impl AlwaysAutofixableViolation for OneBlankLineAfterClass { } } -define_violation!( - pub struct NoBlankLineBeforeClass { - pub lines: usize, - } -); +#[violation] +pub struct NoBlankLineBeforeClass { + pub lines: usize, +} + impl AlwaysAutofixableViolation for NoBlankLineBeforeClass { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pydocstyle/rules/blank_before_after_function.rs b/crates/ruff/src/rules/pydocstyle/rules/blank_before_after_function.rs index ffd9c8da13..fa67fe279d 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/blank_before_after_function.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/blank_before_after_function.rs @@ -1,6 +1,6 @@ use once_cell::sync::Lazy; use regex::Regex; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; @@ -10,11 +10,11 @@ use crate::message::Location; use crate::registry::{Diagnostic, Rule}; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct NoBlankLineBeforeFunction { - pub num_lines: usize, - } -); +#[violation] +pub struct NoBlankLineBeforeFunction { + pub num_lines: usize, +} + impl AlwaysAutofixableViolation for NoBlankLineBeforeFunction { #[derive_message_formats] fn message(&self) -> String { @@ -27,11 +27,11 @@ impl AlwaysAutofixableViolation for NoBlankLineBeforeFunction { } } -define_violation!( - pub struct NoBlankLineAfterFunction { - pub num_lines: usize, - } -); +#[violation] +pub struct NoBlankLineAfterFunction { + pub num_lines: usize, +} + impl AlwaysAutofixableViolation for NoBlankLineAfterFunction { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pydocstyle/rules/capitalized.rs b/crates/ruff/src/rules/pydocstyle/rules/capitalized.rs index bcc1a780e2..e0898d30a5 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/capitalized.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/capitalized.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; @@ -6,9 +6,9 @@ use crate::docstrings::definition::{DefinitionKind, Docstring}; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct FirstLineCapitalized; -); +#[violation] +pub struct FirstLineCapitalized; + impl Violation for FirstLineCapitalized { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pydocstyle/rules/ends_with_period.rs b/crates/ruff/src/rules/pydocstyle/rules/ends_with_period.rs index 0b4ccd4b3a..4b89bc8d0b 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/ends_with_period.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/ends_with_period.rs @@ -1,6 +1,6 @@ use strum::IntoEnumIterator; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; @@ -12,9 +12,9 @@ use crate::registry::Diagnostic; use crate::rules::pydocstyle::helpers::{leading_quote, logical_line}; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct EndsInPeriod; -); +#[violation] +pub struct EndsInPeriod; + impl AlwaysAutofixableViolation for EndsInPeriod { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pydocstyle/rules/ends_with_punctuation.rs b/crates/ruff/src/rules/pydocstyle/rules/ends_with_punctuation.rs index 73f583effb..da3e47765a 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/ends_with_punctuation.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/ends_with_punctuation.rs @@ -1,6 +1,6 @@ use strum::IntoEnumIterator; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; @@ -12,9 +12,9 @@ use crate::registry::Diagnostic; use crate::rules::pydocstyle::helpers::{leading_quote, logical_line}; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct EndsInPunctuation; -); +#[violation] +pub struct EndsInPunctuation; + impl AlwaysAutofixableViolation for EndsInPunctuation { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pydocstyle/rules/if_needed.rs b/crates/ruff/src/rules/pydocstyle/rules/if_needed.rs index c4ff1309cc..c7ba405d79 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/if_needed.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/if_needed.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::cast; use crate::ast::helpers::identifier_range; @@ -8,9 +8,9 @@ use crate::registry::Diagnostic; use crate::violation::Violation; use crate::visibility::is_overload; -define_violation!( - pub struct OverloadWithDocstring; -); +#[violation] +pub struct OverloadWithDocstring; + impl Violation for OverloadWithDocstring { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pydocstyle/rules/indent.rs b/crates/ruff/src/rules/pydocstyle/rules/indent.rs index 8024a75978..6711f6a564 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/indent.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/indent.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::ast::whitespace; @@ -10,9 +10,9 @@ use crate::message::Location; use crate::registry::{Diagnostic, Rule}; use crate::violation::{AlwaysAutofixableViolation, Violation}; -define_violation!( - pub struct IndentWithSpaces; -); +#[violation] +pub struct IndentWithSpaces; + impl Violation for IndentWithSpaces { #[derive_message_formats] fn message(&self) -> String { @@ -20,9 +20,9 @@ impl Violation for IndentWithSpaces { } } -define_violation!( - pub struct NoUnderIndentation; -); +#[violation] +pub struct NoUnderIndentation; + impl AlwaysAutofixableViolation for NoUnderIndentation { #[derive_message_formats] fn message(&self) -> String { @@ -34,9 +34,9 @@ impl AlwaysAutofixableViolation for NoUnderIndentation { } } -define_violation!( - pub struct NoOverIndentation; -); +#[violation] +pub struct NoOverIndentation; + impl AlwaysAutofixableViolation for NoOverIndentation { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pydocstyle/rules/multi_line_summary_start.rs b/crates/ruff/src/rules/pydocstyle/rules/multi_line_summary_start.rs index c8b51e9344..19af4edcf8 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/multi_line_summary_start.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/multi_line_summary_start.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use ruff_python::str::TRIPLE_QUOTE_PREFIXES; use crate::ast::types::Range; @@ -11,9 +11,9 @@ use crate::registry::{Diagnostic, Rule}; use crate::rules::pydocstyle::helpers::leading_quote; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct MultiLineSummaryFirstLine; -); +#[violation] +pub struct MultiLineSummaryFirstLine; + impl AlwaysAutofixableViolation for MultiLineSummaryFirstLine { #[derive_message_formats] fn message(&self) -> String { @@ -25,9 +25,9 @@ impl AlwaysAutofixableViolation for MultiLineSummaryFirstLine { } } -define_violation!( - pub struct MultiLineSummarySecondLine; -); +#[violation] +pub struct MultiLineSummarySecondLine; + impl AlwaysAutofixableViolation for MultiLineSummarySecondLine { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pydocstyle/rules/newline_after_last_paragraph.rs b/crates/ruff/src/rules/pydocstyle/rules/newline_after_last_paragraph.rs index 7872652dae..f5b00b1d7d 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/newline_after_last_paragraph.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/newline_after_last_paragraph.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::ast::whitespace; @@ -10,9 +10,9 @@ use crate::message::Location; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct NewLineAfterLastParagraph; -); +#[violation] +pub struct NewLineAfterLastParagraph; + impl AlwaysAutofixableViolation for NewLineAfterLastParagraph { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pydocstyle/rules/no_signature.rs b/crates/ruff/src/rules/pydocstyle/rules/no_signature.rs index 77744e0e3f..349aaeda37 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/no_signature.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/no_signature.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::StmtKind; use crate::ast::types::Range; @@ -7,9 +7,9 @@ use crate::docstrings::definition::{DefinitionKind, Docstring}; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct NoSignature; -); +#[violation] +pub struct NoSignature; + impl Violation for NoSignature { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pydocstyle/rules/no_surrounding_whitespace.rs b/crates/ruff/src/rules/pydocstyle/rules/no_surrounding_whitespace.rs index ccfa90d885..a4f86b43b0 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/no_surrounding_whitespace.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/no_surrounding_whitespace.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::ast::whitespace::LinesWithTrailingNewline; @@ -10,9 +10,9 @@ use crate::registry::Diagnostic; use crate::rules::pydocstyle::helpers::leading_quote; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct NoSurroundingWhitespace; -); +#[violation] +pub struct NoSurroundingWhitespace; + impl AlwaysAutofixableViolation for NoSurroundingWhitespace { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pydocstyle/rules/non_imperative_mood.rs b/crates/ruff/src/rules/pydocstyle/rules/non_imperative_mood.rs index c68c006a0f..ba99d93801 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/non_imperative_mood.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/non_imperative_mood.rs @@ -2,7 +2,7 @@ use std::collections::BTreeSet; use imperative::Mood; use once_cell::sync::Lazy; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::cast; use crate::ast::helpers::to_call_path; @@ -69,9 +69,9 @@ pub fn non_imperative_mood( } } -define_violation!( - pub struct NonImperativeMood(pub String); -); +#[violation] +pub struct NonImperativeMood(pub String); + impl Violation for NonImperativeMood { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pydocstyle/rules/not_empty.rs b/crates/ruff/src/rules/pydocstyle/rules/not_empty.rs index 274abf4a98..67807d22e5 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/not_empty.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/not_empty.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; @@ -6,9 +6,9 @@ use crate::docstrings::definition::Docstring; use crate::registry::{Diagnostic, Rule}; use crate::violation::Violation; -define_violation!( - pub struct EmptyDocstring; -); +#[violation] +pub struct EmptyDocstring; + impl Violation for EmptyDocstring { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pydocstyle/rules/not_missing.rs b/crates/ruff/src/rules/pydocstyle/rules/not_missing.rs index 867ce6c87c..86a1c65136 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/not_missing.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/not_missing.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::cast; use crate::ast::helpers::identifier_range; @@ -10,9 +10,9 @@ use crate::registry::{Diagnostic, Rule}; use crate::violation::Violation; use crate::visibility::{is_call, is_init, is_magic, is_new, is_overload, is_override, Visibility}; -define_violation!( - pub struct PublicModule; -); +#[violation] +pub struct PublicModule; + impl Violation for PublicModule { #[derive_message_formats] fn message(&self) -> String { @@ -20,9 +20,9 @@ impl Violation for PublicModule { } } -define_violation!( - pub struct PublicClass; -); +#[violation] +pub struct PublicClass; + impl Violation for PublicClass { #[derive_message_formats] fn message(&self) -> String { @@ -30,9 +30,9 @@ impl Violation for PublicClass { } } -define_violation!( - pub struct PublicMethod; -); +#[violation] +pub struct PublicMethod; + impl Violation for PublicMethod { #[derive_message_formats] fn message(&self) -> String { @@ -40,9 +40,9 @@ impl Violation for PublicMethod { } } -define_violation!( - pub struct PublicFunction; -); +#[violation] +pub struct PublicFunction; + impl Violation for PublicFunction { #[derive_message_formats] fn message(&self) -> String { @@ -50,9 +50,9 @@ impl Violation for PublicFunction { } } -define_violation!( - pub struct PublicPackage; -); +#[violation] +pub struct PublicPackage; + impl Violation for PublicPackage { #[derive_message_formats] fn message(&self) -> String { @@ -60,9 +60,9 @@ impl Violation for PublicPackage { } } -define_violation!( - pub struct MagicMethod; -); +#[violation] +pub struct MagicMethod; + impl Violation for MagicMethod { #[derive_message_formats] fn message(&self) -> String { @@ -70,9 +70,9 @@ impl Violation for MagicMethod { } } -define_violation!( - pub struct PublicNestedClass; -); +#[violation] +pub struct PublicNestedClass; + impl Violation for PublicNestedClass { #[derive_message_formats] fn message(&self) -> String { @@ -80,9 +80,9 @@ impl Violation for PublicNestedClass { } } -define_violation!( - pub struct PublicInit; -); +#[violation] +pub struct PublicInit; + impl Violation for PublicInit { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pydocstyle/rules/one_liner.rs b/crates/ruff/src/rules/pydocstyle/rules/one_liner.rs index cf981c1f27..8e0f0dd459 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/one_liner.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/one_liner.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::ast::whitespace::LinesWithTrailingNewline; @@ -9,9 +9,9 @@ use crate::registry::Diagnostic; use crate::rules::pydocstyle::helpers; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct FitsOnOneLine; -); +#[violation] +pub struct FitsOnOneLine; + impl AlwaysAutofixableViolation for FitsOnOneLine { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pydocstyle/rules/sections.rs b/crates/ruff/src/rules/pydocstyle/rules/sections.rs index 1aa54a213c..5b1966af07 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/sections.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/sections.rs @@ -4,7 +4,7 @@ use regex::Regex; use rustc_hash::FxHashSet; use rustpython_parser::ast::StmtKind; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::helpers::identifier_range; use crate::ast::types::Range; @@ -21,11 +21,11 @@ use crate::rules::pydocstyle::settings::Convention; use crate::violation::{AlwaysAutofixableViolation, Violation}; use crate::visibility::is_staticmethod; -define_violation!( - pub struct SectionNotOverIndented { - pub name: String, - } -); +#[violation] +pub struct SectionNotOverIndented { + pub name: String, +} + impl AlwaysAutofixableViolation for SectionNotOverIndented { #[derive_message_formats] fn message(&self) -> String { @@ -39,11 +39,11 @@ impl AlwaysAutofixableViolation for SectionNotOverIndented { } } -define_violation!( - pub struct SectionUnderlineNotOverIndented { - pub name: String, - } -); +#[violation] +pub struct SectionUnderlineNotOverIndented { + pub name: String, +} + impl AlwaysAutofixableViolation for SectionUnderlineNotOverIndented { #[derive_message_formats] fn message(&self) -> String { @@ -57,11 +57,11 @@ impl AlwaysAutofixableViolation for SectionUnderlineNotOverIndented { } } -define_violation!( - pub struct CapitalizeSectionName { - pub name: String, - } -); +#[violation] +pub struct CapitalizeSectionName { + pub name: String, +} + impl AlwaysAutofixableViolation for CapitalizeSectionName { #[derive_message_formats] fn message(&self) -> String { @@ -75,11 +75,11 @@ impl AlwaysAutofixableViolation for CapitalizeSectionName { } } -define_violation!( - pub struct NewLineAfterSectionName { - pub name: String, - } -); +#[violation] +pub struct NewLineAfterSectionName { + pub name: String, +} + impl AlwaysAutofixableViolation for NewLineAfterSectionName { #[derive_message_formats] fn message(&self) -> String { @@ -93,11 +93,11 @@ impl AlwaysAutofixableViolation for NewLineAfterSectionName { } } -define_violation!( - pub struct DashedUnderlineAfterSection { - pub name: String, - } -); +#[violation] +pub struct DashedUnderlineAfterSection { + pub name: String, +} + impl AlwaysAutofixableViolation for DashedUnderlineAfterSection { #[derive_message_formats] fn message(&self) -> String { @@ -111,11 +111,11 @@ impl AlwaysAutofixableViolation for DashedUnderlineAfterSection { } } -define_violation!( - pub struct SectionUnderlineAfterName { - pub name: String, - } -); +#[violation] +pub struct SectionUnderlineAfterName { + pub name: String, +} + impl AlwaysAutofixableViolation for SectionUnderlineAfterName { #[derive_message_formats] fn message(&self) -> String { @@ -129,11 +129,11 @@ impl AlwaysAutofixableViolation for SectionUnderlineAfterName { } } -define_violation!( - pub struct SectionUnderlineMatchesSectionLength { - pub name: String, - } -); +#[violation] +pub struct SectionUnderlineMatchesSectionLength { + pub name: String, +} + impl AlwaysAutofixableViolation for SectionUnderlineMatchesSectionLength { #[derive_message_formats] fn message(&self) -> String { @@ -147,11 +147,11 @@ impl AlwaysAutofixableViolation for SectionUnderlineMatchesSectionLength { } } -define_violation!( - pub struct BlankLineAfterSection { - pub name: String, - } -); +#[violation] +pub struct BlankLineAfterSection { + pub name: String, +} + impl AlwaysAutofixableViolation for BlankLineAfterSection { #[derive_message_formats] fn message(&self) -> String { @@ -165,11 +165,11 @@ impl AlwaysAutofixableViolation for BlankLineAfterSection { } } -define_violation!( - pub struct BlankLineBeforeSection { - pub name: String, - } -); +#[violation] +pub struct BlankLineBeforeSection { + pub name: String, +} + impl AlwaysAutofixableViolation for BlankLineBeforeSection { #[derive_message_formats] fn message(&self) -> String { @@ -183,11 +183,11 @@ impl AlwaysAutofixableViolation for BlankLineBeforeSection { } } -define_violation!( - pub struct BlankLineAfterLastSection { - pub name: String, - } -); +#[violation] +pub struct BlankLineAfterLastSection { + pub name: String, +} + impl AlwaysAutofixableViolation for BlankLineAfterLastSection { #[derive_message_formats] fn message(&self) -> String { @@ -201,11 +201,11 @@ impl AlwaysAutofixableViolation for BlankLineAfterLastSection { } } -define_violation!( - pub struct EmptyDocstringSection { - pub name: String, - } -); +#[violation] +pub struct EmptyDocstringSection { + pub name: String, +} + impl Violation for EmptyDocstringSection { #[derive_message_formats] fn message(&self) -> String { @@ -214,11 +214,11 @@ impl Violation for EmptyDocstringSection { } } -define_violation!( - pub struct SectionNameEndsInColon { - pub name: String, - } -); +#[violation] +pub struct SectionNameEndsInColon { + pub name: String, +} + impl AlwaysAutofixableViolation for SectionNameEndsInColon { #[derive_message_formats] fn message(&self) -> String { @@ -232,11 +232,11 @@ impl AlwaysAutofixableViolation for SectionNameEndsInColon { } } -define_violation!( - pub struct UndocumentedParam { - pub names: Vec, - } -); +#[violation] +pub struct UndocumentedParam { + pub names: Vec, +} + impl Violation for UndocumentedParam { #[derive_message_formats] fn message(&self) -> String { @@ -251,11 +251,11 @@ impl Violation for UndocumentedParam { } } -define_violation!( - pub struct NoBlankLinesBetweenHeaderAndContent { - pub name: String, - } -); +#[violation] +pub struct NoBlankLinesBetweenHeaderAndContent { + pub name: String, +} + impl AlwaysAutofixableViolation for NoBlankLinesBetweenHeaderAndContent { #[derive_message_formats] fn message(&self) -> String { @@ -796,7 +796,7 @@ fn missing_args(checker: &mut Checker, docstring: &Docstring, docstrings_args: & | DefinitionKind::NestedFunction(parent) | DefinitionKind::Method(parent) ) = docstring.kind else { - return + return; }; let ( StmtKind::FunctionDef { @@ -806,7 +806,7 @@ fn missing_args(checker: &mut Checker, docstring: &Docstring, docstrings_args: & args: arguments, .. } ) = &parent.node else { - return + return; }; // Look for arguments that weren't included in the docstring. diff --git a/crates/ruff/src/rules/pydocstyle/rules/starts_with_this.rs b/crates/ruff/src/rules/pydocstyle/rules/starts_with_this.rs index 9d9c98bdd2..c4f61883df 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/starts_with_this.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/starts_with_this.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; @@ -7,9 +7,9 @@ use crate::registry::Diagnostic; use crate::rules::pydocstyle::helpers::normalize_word; use crate::violation::Violation; -define_violation!( - pub struct DocstringStartsWithThis; -); +#[violation] +pub struct DocstringStartsWithThis; + impl Violation for DocstringStartsWithThis { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pydocstyle/rules/triple_quotes.rs b/crates/ruff/src/rules/pydocstyle/rules/triple_quotes.rs index d9dc2fe36c..f41ea1755a 100644 --- a/crates/ruff/src/rules/pydocstyle/rules/triple_quotes.rs +++ b/crates/ruff/src/rules/pydocstyle/rules/triple_quotes.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; @@ -6,9 +6,9 @@ use crate::docstrings::definition::Docstring; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct TripleSingleQuotes; -); +#[violation] +pub struct TripleSingleQuotes; + impl Violation for TripleSingleQuotes { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyflakes/rules/assert_tuple.rs b/crates/ruff/src/rules/pyflakes/rules/assert_tuple.rs index 4ca4eea914..b31003984c 100644 --- a/crates/ruff/src/rules/pyflakes/rules/assert_tuple.rs +++ b/crates/ruff/src/rules/pyflakes/rules/assert_tuple.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind, Stmt}; use crate::ast::types::Range; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct AssertTuple; -); +#[violation] +pub struct AssertTuple; + impl Violation for AssertTuple { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyflakes/rules/break_outside_loop.rs b/crates/ruff/src/rules/pyflakes/rules/break_outside_loop.rs index eae30067d6..f54ae5f58c 100644 --- a/crates/ruff/src/rules/pyflakes/rules/break_outside_loop.rs +++ b/crates/ruff/src/rules/pyflakes/rules/break_outside_loop.rs @@ -1,13 +1,13 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Stmt, StmtKind}; use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct BreakOutsideLoop; -); +#[violation] +pub struct BreakOutsideLoop; + impl Violation for BreakOutsideLoop { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyflakes/rules/continue_outside_loop.rs b/crates/ruff/src/rules/pyflakes/rules/continue_outside_loop.rs index 6bee1a0125..fb3d214aaf 100644 --- a/crates/ruff/src/rules/pyflakes/rules/continue_outside_loop.rs +++ b/crates/ruff/src/rules/pyflakes/rules/continue_outside_loop.rs @@ -1,13 +1,13 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Stmt, StmtKind}; use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct ContinueOutsideLoop; -); +#[violation] +pub struct ContinueOutsideLoop; + impl Violation for ContinueOutsideLoop { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyflakes/rules/default_except_not_last.rs b/crates/ruff/src/rules/pyflakes/rules/default_except_not_last.rs index 7a1654bf8b..bd373f4e00 100644 --- a/crates/ruff/src/rules/pyflakes/rules/default_except_not_last.rs +++ b/crates/ruff/src/rules/pyflakes/rules/default_except_not_last.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Excepthandler, ExcepthandlerKind}; use crate::ast::helpers::except_range; @@ -6,9 +6,9 @@ use crate::registry::Diagnostic; use crate::source_code::Locator; use crate::violation::Violation; -define_violation!( - pub struct DefaultExceptNotLast; -); +#[violation] +pub struct DefaultExceptNotLast; + impl Violation for DefaultExceptNotLast { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyflakes/rules/f_string_missing_placeholders.rs b/crates/ruff/src/rules/pyflakes/rules/f_string_missing_placeholders.rs index 6dd18b5529..e6a1043a1e 100644 --- a/crates/ruff/src/rules/pyflakes/rules/f_string_missing_placeholders.rs +++ b/crates/ruff/src/rules/pyflakes/rules/f_string_missing_placeholders.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use crate::ast::helpers::find_useless_f_strings; @@ -8,34 +8,34 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - /// ## What it does - /// Checks for f-strings that do not contain any placeholder expressions. - /// - /// ## Why is this bad? - /// F-strings are a convenient way to format strings, but they are not - /// necessary if there are no placeholder expressions to format. In this - /// case, a regular string should be used instead, as an f-string without - /// placeholders can be confusing for readers, who may expect such a - /// placeholder to be present. - /// - /// An f-string without any placeholders could also indicate that the - /// author forgot to add a placeholder expression. - /// - /// ## Example - /// ```python - /// f"Hello, world!" - /// ``` - /// - /// Use instead: - /// ```python - /// "Hello, world!" - /// ``` - /// - /// ## References - /// - [PEP 498](https://www.python.org/dev/peps/pep-0498/) - pub struct FStringMissingPlaceholders; -); +/// ## What it does +/// Checks for f-strings that do not contain any placeholder expressions. +/// +/// ## Why is this bad? +/// F-strings are a convenient way to format strings, but they are not +/// necessary if there are no placeholder expressions to format. In this +/// case, a regular string should be used instead, as an f-string without +/// placeholders can be confusing for readers, who may expect such a +/// placeholder to be present. +/// +/// An f-string without any placeholders could also indicate that the +/// author forgot to add a placeholder expression. +/// +/// ## Example +/// ```python +/// f"Hello, world!" +/// ``` +/// +/// Use instead: +/// ```python +/// "Hello, world!" +/// ``` +/// +/// ## References +/// - [PEP 498](https://www.python.org/dev/peps/pep-0498/) +#[violation] +pub struct FStringMissingPlaceholders; + impl AlwaysAutofixableViolation for FStringMissingPlaceholders { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyflakes/rules/forward_annotation_syntax_error.rs b/crates/ruff/src/rules/pyflakes/rules/forward_annotation_syntax_error.rs index d344f30acf..0249f82297 100644 --- a/crates/ruff/src/rules/pyflakes/rules/forward_annotation_syntax_error.rs +++ b/crates/ruff/src/rules/pyflakes/rules/forward_annotation_syntax_error.rs @@ -1,12 +1,12 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::violation::Violation; -define_violation!( - pub struct ForwardAnnotationSyntaxError { - pub body: String, - } -); +#[violation] +pub struct ForwardAnnotationSyntaxError { + pub body: String, +} + impl Violation for ForwardAnnotationSyntaxError { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyflakes/rules/if_tuple.rs b/crates/ruff/src/rules/pyflakes/rules/if_tuple.rs index 506d096616..f2c2a07a26 100644 --- a/crates/ruff/src/rules/pyflakes/rules/if_tuple.rs +++ b/crates/ruff/src/rules/pyflakes/rules/if_tuple.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind, Stmt}; use crate::ast::types::Range; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct IfTuple; -); +#[violation] +pub struct IfTuple; + impl Violation for IfTuple { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyflakes/rules/imports.rs b/crates/ruff/src/rules/pyflakes/rules/imports.rs index 8372c92743..d8ca6ddebd 100644 --- a/crates/ruff/src/rules/pyflakes/rules/imports.rs +++ b/crates/ruff/src/rules/pyflakes/rules/imports.rs @@ -1,5 +1,5 @@ use itertools::Itertools; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use ruff_python::future::ALL_FEATURE_NAMES; use rustpython_parser::ast::Alias; @@ -8,13 +8,13 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::{AutofixKind, Availability, Violation}; -define_violation!( - pub struct UnusedImport { - pub name: String, - pub ignore_init: bool, - pub multiple: bool, - } -); +#[violation] +pub struct UnusedImport { + pub name: String, + pub ignore_init: bool, + pub multiple: bool, +} + fn fmt_unused_import_autofix_msg(unused_import: &UnusedImport) -> String { let UnusedImport { name, multiple, .. } = unused_import; if *multiple { @@ -50,12 +50,12 @@ impl Violation for UnusedImport { } } } -define_violation!( - pub struct ImportShadowedByLoopVar { - pub name: String, - pub line: usize, - } -); +#[violation] +pub struct ImportShadowedByLoopVar { + pub name: String, + pub line: usize, +} + impl Violation for ImportShadowedByLoopVar { #[derive_message_formats] fn message(&self) -> String { @@ -64,11 +64,11 @@ impl Violation for ImportShadowedByLoopVar { } } -define_violation!( - pub struct ImportStar { - pub name: String, - } -); +#[violation] +pub struct ImportStar { + pub name: String, +} + impl Violation for ImportStar { #[derive_message_formats] fn message(&self) -> String { @@ -77,9 +77,9 @@ impl Violation for ImportStar { } } -define_violation!( - pub struct LateFutureImport; -); +#[violation] +pub struct LateFutureImport; + impl Violation for LateFutureImport { #[derive_message_formats] fn message(&self) -> String { @@ -87,12 +87,12 @@ impl Violation for LateFutureImport { } } -define_violation!( - pub struct ImportStarUsage { - pub name: String, - pub sources: Vec, - } -); +#[violation] +pub struct ImportStarUsage { + pub name: String, + pub sources: Vec, +} + impl Violation for ImportStarUsage { #[derive_message_formats] fn message(&self) -> String { @@ -105,11 +105,11 @@ impl Violation for ImportStarUsage { } } -define_violation!( - pub struct ImportStarNotPermitted { - pub name: String, - } -); +#[violation] +pub struct ImportStarNotPermitted { + pub name: String, +} + impl Violation for ImportStarNotPermitted { #[derive_message_formats] fn message(&self) -> String { @@ -118,11 +118,11 @@ impl Violation for ImportStarNotPermitted { } } -define_violation!( - pub struct FutureFeatureNotDefined { - pub name: String, - } -); +#[violation] +pub struct FutureFeatureNotDefined { + pub name: String, +} + impl Violation for FutureFeatureNotDefined { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyflakes/rules/invalid_literal_comparisons.rs b/crates/ruff/src/rules/pyflakes/rules/invalid_literal_comparisons.rs index 70813907ce..7280ff78e0 100644 --- a/crates/ruff/src/rules/pyflakes/rules/invalid_literal_comparisons.rs +++ b/crates/ruff/src/rules/pyflakes/rules/invalid_literal_comparisons.rs @@ -1,7 +1,7 @@ use itertools::izip; use log::error; use once_cell::unsync::Lazy; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Cmpop, Expr}; use serde::{Deserialize, Serialize}; @@ -29,11 +29,11 @@ impl From<&Cmpop> for IsCmpop { } } -define_violation!( - pub struct IsLiteral { - pub cmpop: IsCmpop, - } -); +#[violation] +pub struct IsLiteral { + pub cmpop: IsCmpop, +} + impl AlwaysAutofixableViolation for IsLiteral { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyflakes/rules/invalid_print_syntax.rs b/crates/ruff/src/rules/pyflakes/rules/invalid_print_syntax.rs index 013157b354..2b6f467186 100644 --- a/crates/ruff/src/rules/pyflakes/rules/invalid_print_syntax.rs +++ b/crates/ruff/src/rules/pyflakes/rules/invalid_print_syntax.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use crate::ast::types::Range; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct InvalidPrintSyntax; -); +#[violation] +pub struct InvalidPrintSyntax; + impl Violation for InvalidPrintSyntax { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyflakes/rules/raise_not_implemented.rs b/crates/ruff/src/rules/pyflakes/rules/raise_not_implemented.rs index 329d9f226b..1777006ea8 100644 --- a/crates/ruff/src/rules/pyflakes/rules/raise_not_implemented.rs +++ b/crates/ruff/src/rules/pyflakes/rules/raise_not_implemented.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use crate::ast::types::Range; @@ -7,9 +7,9 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct RaiseNotImplemented; -); +#[violation] +pub struct RaiseNotImplemented; + impl AlwaysAutofixableViolation for RaiseNotImplemented { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyflakes/rules/redefined_while_unused.rs b/crates/ruff/src/rules/pyflakes/rules/redefined_while_unused.rs index 5e4eabd0e9..475556664a 100644 --- a/crates/ruff/src/rules/pyflakes/rules/redefined_while_unused.rs +++ b/crates/ruff/src/rules/pyflakes/rules/redefined_while_unused.rs @@ -1,13 +1,13 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::violation::Violation; -define_violation!( - pub struct RedefinedWhileUnused { - pub name: String, - pub line: usize, - } -); +#[violation] +pub struct RedefinedWhileUnused { + pub name: String, + pub line: usize, +} + impl Violation for RedefinedWhileUnused { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyflakes/rules/repeated_keys.rs b/crates/ruff/src/rules/pyflakes/rules/repeated_keys.rs index f368b40dbb..ccb8c5829e 100644 --- a/crates/ruff/src/rules/pyflakes/rules/repeated_keys.rs +++ b/crates/ruff/src/rules/pyflakes/rules/repeated_keys.rs @@ -1,6 +1,6 @@ use std::hash::{BuildHasherDefault, Hash}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustc_hash::{FxHashMap, FxHashSet}; use rustpython_parser::ast::{Expr, ExprKind}; @@ -12,12 +12,12 @@ use crate::fix::Fix; use crate::registry::{Diagnostic, Rule}; use crate::violation::{AutofixKind, Availability, Violation}; -define_violation!( - pub struct MultiValueRepeatedKeyLiteral { - pub name: String, - pub repeated_value: bool, - } -); +#[violation] +pub struct MultiValueRepeatedKeyLiteral { + pub name: String, + pub repeated_value: bool, +} + impl Violation for MultiValueRepeatedKeyLiteral { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Sometimes)); @@ -38,12 +38,12 @@ impl Violation for MultiValueRepeatedKeyLiteral { } } } -define_violation!( - pub struct MultiValueRepeatedKeyVariable { - pub name: String, - pub repeated_value: bool, - } -); +#[violation] +pub struct MultiValueRepeatedKeyVariable { + pub name: String, + pub repeated_value: bool, +} + impl Violation for MultiValueRepeatedKeyVariable { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Sometimes)); diff --git a/crates/ruff/src/rules/pyflakes/rules/return_outside_function.rs b/crates/ruff/src/rules/pyflakes/rules/return_outside_function.rs index aa1200e925..cd214cac46 100644 --- a/crates/ruff/src/rules/pyflakes/rules/return_outside_function.rs +++ b/crates/ruff/src/rules/pyflakes/rules/return_outside_function.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Stmt; use crate::ast::types::{Range, ScopeKind}; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct ReturnOutsideFunction; -); +#[violation] +pub struct ReturnOutsideFunction; + impl Violation for ReturnOutsideFunction { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyflakes/rules/starred_expressions.rs b/crates/ruff/src/rules/pyflakes/rules/starred_expressions.rs index 34c787a0c6..e2ea5cb5f2 100644 --- a/crates/ruff/src/rules/pyflakes/rules/starred_expressions.rs +++ b/crates/ruff/src/rules/pyflakes/rules/starred_expressions.rs @@ -1,13 +1,13 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct ExpressionsInStarAssignment; -); +#[violation] +pub struct ExpressionsInStarAssignment; + impl Violation for ExpressionsInStarAssignment { #[derive_message_formats] fn message(&self) -> String { @@ -15,9 +15,9 @@ impl Violation for ExpressionsInStarAssignment { } } -define_violation!( - pub struct TwoStarredExpressions; -); +#[violation] +pub struct TwoStarredExpressions; + impl Violation for TwoStarredExpressions { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyflakes/rules/strings.rs b/crates/ruff/src/rules/pyflakes/rules/strings.rs index 118c20b365..00cd690223 100644 --- a/crates/ruff/src/rules/pyflakes/rules/strings.rs +++ b/crates/ruff/src/rules/pyflakes/rules/strings.rs @@ -1,7 +1,7 @@ use std::string::ToString; use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustc_hash::FxHashSet; use rustpython_parser::ast::{Constant, Expr, ExprKind, Keyword, KeywordData}; @@ -15,11 +15,11 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::{AlwaysAutofixableViolation, Violation}; -define_violation!( - pub struct PercentFormatInvalidFormat { - pub message: String, - } -); +#[violation] +pub struct PercentFormatInvalidFormat { + pub message: String, +} + impl Violation for PercentFormatInvalidFormat { #[derive_message_formats] fn message(&self) -> String { @@ -28,9 +28,9 @@ impl Violation for PercentFormatInvalidFormat { } } -define_violation!( - pub struct PercentFormatExpectedMapping; -); +#[violation] +pub struct PercentFormatExpectedMapping; + impl Violation for PercentFormatExpectedMapping { #[derive_message_formats] fn message(&self) -> String { @@ -38,9 +38,9 @@ impl Violation for PercentFormatExpectedMapping { } } -define_violation!( - pub struct PercentFormatExpectedSequence; -); +#[violation] +pub struct PercentFormatExpectedSequence; + impl Violation for PercentFormatExpectedSequence { #[derive_message_formats] fn message(&self) -> String { @@ -48,11 +48,11 @@ impl Violation for PercentFormatExpectedSequence { } } -define_violation!( - pub struct PercentFormatExtraNamedArguments { - pub missing: Vec, - } -); +#[violation] +pub struct PercentFormatExtraNamedArguments { + pub missing: Vec, +} + impl AlwaysAutofixableViolation for PercentFormatExtraNamedArguments { #[derive_message_formats] fn message(&self) -> String { @@ -68,11 +68,11 @@ impl AlwaysAutofixableViolation for PercentFormatExtraNamedArguments { } } -define_violation!( - pub struct PercentFormatMissingArgument { - pub missing: Vec, - } -); +#[violation] +pub struct PercentFormatMissingArgument { + pub missing: Vec, +} + impl Violation for PercentFormatMissingArgument { #[derive_message_formats] fn message(&self) -> String { @@ -82,9 +82,9 @@ impl Violation for PercentFormatMissingArgument { } } -define_violation!( - pub struct PercentFormatMixedPositionalAndNamed; -); +#[violation] +pub struct PercentFormatMixedPositionalAndNamed; + impl Violation for PercentFormatMixedPositionalAndNamed { #[derive_message_formats] fn message(&self) -> String { @@ -92,12 +92,12 @@ impl Violation for PercentFormatMixedPositionalAndNamed { } } -define_violation!( - pub struct PercentFormatPositionalCountMismatch { - pub wanted: usize, - pub got: usize, - } -); +#[violation] +pub struct PercentFormatPositionalCountMismatch { + pub wanted: usize, + pub got: usize, +} + impl Violation for PercentFormatPositionalCountMismatch { #[derive_message_formats] fn message(&self) -> String { @@ -106,9 +106,9 @@ impl Violation for PercentFormatPositionalCountMismatch { } } -define_violation!( - pub struct PercentFormatStarRequiresSequence; -); +#[violation] +pub struct PercentFormatStarRequiresSequence; + impl Violation for PercentFormatStarRequiresSequence { #[derive_message_formats] fn message(&self) -> String { @@ -116,11 +116,11 @@ impl Violation for PercentFormatStarRequiresSequence { } } -define_violation!( - pub struct PercentFormatUnsupportedFormatCharacter { - pub char: char, - } -); +#[violation] +pub struct PercentFormatUnsupportedFormatCharacter { + pub char: char, +} + impl Violation for PercentFormatUnsupportedFormatCharacter { #[derive_message_formats] fn message(&self) -> String { @@ -129,11 +129,11 @@ impl Violation for PercentFormatUnsupportedFormatCharacter { } } -define_violation!( - pub struct StringDotFormatInvalidFormat { - pub message: String, - } -); +#[violation] +pub struct StringDotFormatInvalidFormat { + pub message: String, +} + impl Violation for StringDotFormatInvalidFormat { #[derive_message_formats] fn message(&self) -> String { @@ -142,11 +142,11 @@ impl Violation for StringDotFormatInvalidFormat { } } -define_violation!( - pub struct StringDotFormatExtraNamedArguments { - pub missing: Vec, - } -); +#[violation] +pub struct StringDotFormatExtraNamedArguments { + pub missing: Vec, +} + impl AlwaysAutofixableViolation for StringDotFormatExtraNamedArguments { #[derive_message_formats] fn message(&self) -> String { @@ -162,11 +162,11 @@ impl AlwaysAutofixableViolation for StringDotFormatExtraNamedArguments { } } -define_violation!( - pub struct StringDotFormatExtraPositionalArguments { - pub missing: Vec, - } -); +#[violation] +pub struct StringDotFormatExtraPositionalArguments { + pub missing: Vec, +} + impl Violation for StringDotFormatExtraPositionalArguments { #[derive_message_formats] fn message(&self) -> String { @@ -176,11 +176,11 @@ impl Violation for StringDotFormatExtraPositionalArguments { } } -define_violation!( - pub struct StringDotFormatMissingArguments { - pub missing: Vec, - } -); +#[violation] +pub struct StringDotFormatMissingArguments { + pub missing: Vec, +} + impl Violation for StringDotFormatMissingArguments { #[derive_message_formats] fn message(&self) -> String { @@ -190,9 +190,9 @@ impl Violation for StringDotFormatMissingArguments { } } -define_violation!( - pub struct StringDotFormatMixingAutomatic; -); +#[violation] +pub struct StringDotFormatMixingAutomatic; + impl Violation for StringDotFormatMixingAutomatic { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyflakes/rules/undefined_export.rs b/crates/ruff/src/rules/pyflakes/rules/undefined_export.rs index b401eb4a52..4e1aca0eb0 100644 --- a/crates/ruff/src/rules/pyflakes/rules/undefined_export.rs +++ b/crates/ruff/src/rules/pyflakes/rules/undefined_export.rs @@ -1,15 +1,15 @@ use crate::ast::types::{Range, Scope}; use crate::registry::Diagnostic; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use std::path::Path; use crate::violation::Violation; -define_violation!( - pub struct UndefinedExport { - pub name: String, - } -); +#[violation] +pub struct UndefinedExport { + pub name: String, +} + impl Violation for UndefinedExport { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyflakes/rules/undefined_local.rs b/crates/ruff/src/rules/pyflakes/rules/undefined_local.rs index 5021aa5911..8246861ee8 100644 --- a/crates/ruff/src/rules/pyflakes/rules/undefined_local.rs +++ b/crates/ruff/src/rules/pyflakes/rules/undefined_local.rs @@ -1,16 +1,16 @@ use std::string::ToString; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::{Binding, Scope, ScopeKind}; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct UndefinedLocal { - pub name: String, - } -); +#[violation] +pub struct UndefinedLocal { + pub name: String, +} + impl Violation for UndefinedLocal { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyflakes/rules/undefined_name.rs b/crates/ruff/src/rules/pyflakes/rules/undefined_name.rs index 2bc55fe3fd..be3bf26bd2 100644 --- a/crates/ruff/src/rules/pyflakes/rules/undefined_name.rs +++ b/crates/ruff/src/rules/pyflakes/rules/undefined_name.rs @@ -1,12 +1,12 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::violation::Violation; -define_violation!( - pub struct UndefinedName { - pub name: String, - } -); +#[violation] +pub struct UndefinedName { + pub name: String, +} + impl Violation for UndefinedName { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyflakes/rules/unused_annotation.rs b/crates/ruff/src/rules/pyflakes/rules/unused_annotation.rs index 7aae3212cd..f839fa5f86 100644 --- a/crates/ruff/src/rules/pyflakes/rules/unused_annotation.rs +++ b/crates/ruff/src/rules/pyflakes/rules/unused_annotation.rs @@ -1,14 +1,14 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct UnusedAnnotation { - pub name: String, - } -); +#[violation] +pub struct UnusedAnnotation { + pub name: String, +} + impl Violation for UnusedAnnotation { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyflakes/rules/unused_variable.rs b/crates/ruff/src/rules/pyflakes/rules/unused_variable.rs index 4cb54c05d3..bf67ee56ea 100644 --- a/crates/ruff/src/rules/pyflakes/rules/unused_variable.rs +++ b/crates/ruff/src/rules/pyflakes/rules/unused_variable.rs @@ -1,6 +1,6 @@ use itertools::Itertools; use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{ExprKind, Located, Stmt, StmtKind}; use rustpython_parser::{lexer, Mode, Tok}; @@ -13,39 +13,39 @@ use crate::registry::Diagnostic; use crate::source_code::Locator; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - /// ## What it does - /// Checks for the presence of unused variables in function scopes. - /// - /// ## Why is this bad? - /// A variable that is defined but not used is likely a mistake, and should - /// be removed to avoid confusion. - /// - /// If a variable is intentionally defined-but-not-used, it should be - /// prefixed with an underscore, or some other value that adheres to the - /// [`dummy-variable-rgx`] pattern. - /// - /// ## Options - /// - `dummy-variable-rgx` - /// - /// ## Example - /// ```python - /// def foo(): - /// x = 1 - /// y = 2 - /// return x - /// ``` - /// - /// Use instead: - /// ```python - /// def foo(): - /// x = 1 - /// return x - /// ``` - pub struct UnusedVariable { - pub name: String, - } -); +/// ## What it does +/// Checks for the presence of unused variables in function scopes. +/// +/// ## Why is this bad? +/// A variable that is defined but not used is likely a mistake, and should +/// be removed to avoid confusion. +/// +/// If a variable is intentionally defined-but-not-used, it should be +/// prefixed with an underscore, or some other value that adheres to the +/// [`dummy-variable-rgx`] pattern. +/// +/// ## Options +/// - `dummy-variable-rgx` +/// +/// ## Example +/// ```python +/// def foo(): +/// x = 1 +/// y = 2 +/// return x +/// ``` +/// +/// Use instead: +/// ```python +/// def foo(): +/// x = 1 +/// return x +/// ``` +#[violation] +pub struct UnusedVariable { + pub name: String, +} + impl AlwaysAutofixableViolation for UnusedVariable { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyflakes/rules/yield_outside_function.rs b/crates/ruff/src/rules/pyflakes/rules/yield_outside_function.rs index cf789fbd45..c3011e9dfd 100644 --- a/crates/ruff/src/rules/pyflakes/rules/yield_outside_function.rs +++ b/crates/ruff/src/rules/pyflakes/rules/yield_outside_function.rs @@ -1,6 +1,6 @@ use std::fmt; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use serde::{Deserialize, Serialize}; @@ -26,11 +26,11 @@ impl fmt::Display for DeferralKeyword { } } -define_violation!( - pub struct YieldOutsideFunction { - pub keyword: DeferralKeyword, - } -); +#[violation] +pub struct YieldOutsideFunction { + pub keyword: DeferralKeyword, +} + impl Violation for YieldOutsideFunction { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pygrep_hooks/rules/blanket_noqa.rs b/crates/ruff/src/rules/pygrep_hooks/rules/blanket_noqa.rs index d4006bd8be..a760c56fcd 100644 --- a/crates/ruff/src/rules/pygrep_hooks/rules/blanket_noqa.rs +++ b/crates/ruff/src/rules/pygrep_hooks/rules/blanket_noqa.rs @@ -1,15 +1,15 @@ use once_cell::sync::Lazy; use regex::Regex; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Location; use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct BlanketNOQA; -); +#[violation] +pub struct BlanketNOQA; + impl Violation for BlanketNOQA { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pygrep_hooks/rules/blanket_type_ignore.rs b/crates/ruff/src/rules/pygrep_hooks/rules/blanket_type_ignore.rs index 4663402437..eed4708512 100644 --- a/crates/ruff/src/rules/pygrep_hooks/rules/blanket_type_ignore.rs +++ b/crates/ruff/src/rules/pygrep_hooks/rules/blanket_type_ignore.rs @@ -1,15 +1,15 @@ use once_cell::sync::Lazy; use regex::Regex; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Location; use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct BlanketTypeIgnore; -); +#[violation] +pub struct BlanketTypeIgnore; + impl Violation for BlanketTypeIgnore { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pygrep_hooks/rules/deprecated_log_warn.rs b/crates/ruff/src/rules/pygrep_hooks/rules/deprecated_log_warn.rs index 694c1dacf5..e42df518eb 100644 --- a/crates/ruff/src/rules/pygrep_hooks/rules/deprecated_log_warn.rs +++ b/crates/ruff/src/rules/pygrep_hooks/rules/deprecated_log_warn.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Expr; use crate::ast::types::Range; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct DeprecatedLogWarn; -); +#[violation] +pub struct DeprecatedLogWarn; + impl Violation for DeprecatedLogWarn { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pygrep_hooks/rules/no_eval.rs b/crates/ruff/src/rules/pygrep_hooks/rules/no_eval.rs index ac7d98ed4b..5fe24b7e49 100644 --- a/crates/ruff/src/rules/pygrep_hooks/rules/no_eval.rs +++ b/crates/ruff/src/rules/pygrep_hooks/rules/no_eval.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use crate::ast::types::Range; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct NoEval; -); +#[violation] +pub struct NoEval; + impl Violation for NoEval { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pylint/rules/await_outside_async.rs b/crates/ruff/src/rules/pylint/rules/await_outside_async.rs index 8ba3601bad..22c196c6b7 100644 --- a/crates/ruff/src/rules/pylint/rules/await_outside_async.rs +++ b/crates/ruff/src/rules/pylint/rules/await_outside_async.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Expr; use crate::ast::types::{FunctionDef, Range, ScopeKind}; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct AwaitOutsideAsync; -); +#[violation] +pub struct AwaitOutsideAsync; + impl Violation for AwaitOutsideAsync { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pylint/rules/bad_str_strip_call.rs b/crates/ruff/src/rules/pylint/rules/bad_str_strip_call.rs index 27277870d4..32d0d05bf6 100644 --- a/crates/ruff/src/rules/pylint/rules/bad_str_strip_call.rs +++ b/crates/ruff/src/rules/pylint/rules/bad_str_strip_call.rs @@ -1,6 +1,6 @@ use std::fmt; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustc_hash::FxHashSet; use rustpython_parser::ast::{Constant, Expr, ExprKind}; use serde::{Deserialize, Serialize}; @@ -11,12 +11,12 @@ use crate::registry::Diagnostic; use crate::settings::types::PythonVersion; use crate::violation::Violation; -define_violation!( - pub struct BadStrStripCall { - strip: StripKind, - removal: Option, - } -); +#[violation] +pub struct BadStrStripCall { + strip: StripKind, + removal: Option, +} + impl Violation for BadStrStripCall { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pylint/rules/bad_string_format_type.rs b/crates/ruff/src/rules/pylint/rules/bad_string_format_type.rs index 8cc696a363..cf8896c3ec 100644 --- a/crates/ruff/src/rules/pylint/rules/bad_string_format_type.rs +++ b/crates/ruff/src/rules/pylint/rules/bad_string_format_type.rs @@ -1,6 +1,6 @@ use std::str::FromStr; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustc_hash::FxHashMap; use rustpython_common::cformat::{CFormatPart, CFormatSpec, CFormatStrOrBytes, CFormatString}; use rustpython_parser::ast::{Constant, Expr, ExprKind, Location, Operator}; @@ -12,25 +12,25 @@ use crate::registry::Diagnostic; use crate::rules::pydocstyle::helpers::{leading_quote, trailing_quote}; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for mismatched argument types in "old-style" format strings. - /// - /// ## Why is this bad? - /// The format string is not checked at compile time, so it is easy to - /// introduce bugs by mistyping the format string. - /// - /// ## Example - /// ```python - /// print("%d" % "1") - /// ``` - /// - /// Use instead: - /// ```python - /// print("%d" % 1) - /// ``` - pub struct BadStringFormatType; -); +/// ## What it does +/// Checks for mismatched argument types in "old-style" format strings. +/// +/// ## Why is this bad? +/// The format string is not checked at compile time, so it is easy to +/// introduce bugs by mistyping the format string. +/// +/// ## Example +/// ```python +/// print("%d" % "1") +/// ``` +/// +/// Use instead: +/// ```python +/// print("%d" % 1) +/// ``` +#[violation] +pub struct BadStringFormatType; + impl Violation for BadStringFormatType { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pylint/rules/bidirectional_unicode.rs b/crates/ruff/src/rules/pylint/rules/bidirectional_unicode.rs index 674cfcfe09..0bcd7d0476 100644 --- a/crates/ruff/src/rules/pylint/rules/bidirectional_unicode.rs +++ b/crates/ruff/src/rules/pylint/rules/bidirectional_unicode.rs @@ -1,6 +1,6 @@ use rustpython_parser::ast::Location; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::registry::Diagnostic; @@ -26,9 +26,9 @@ const BIDI_UNICODE: [char; 10] = [ // to hide code ]; -define_violation!( - pub struct BidirectionalUnicode; -); +#[violation] +pub struct BidirectionalUnicode; + impl Violation for BidirectionalUnicode { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pylint/rules/collapsible_else_if.rs b/crates/ruff/src/rules/pylint/rules/collapsible_else_if.rs index 4328bddaee..3b594bbe3a 100644 --- a/crates/ruff/src/rules/pylint/rules/collapsible_else_if.rs +++ b/crates/ruff/src/rules/pylint/rules/collapsible_else_if.rs @@ -1,15 +1,14 @@ use rustpython_parser::ast::{Stmt, StmtKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::source_code::Locator; use crate::violation::Violation; -define_violation!( - pub struct CollapsibleElseIf; -); +#[violation] +pub struct CollapsibleElseIf; impl Violation for CollapsibleElseIf { #[derive_message_formats] diff --git a/crates/ruff/src/rules/pylint/rules/comparison_of_constant.rs b/crates/ruff/src/rules/pylint/rules/comparison_of_constant.rs index 91789c764d..a407bab143 100644 --- a/crates/ruff/src/rules/pylint/rules/comparison_of_constant.rs +++ b/crates/ruff/src/rules/pylint/rules/comparison_of_constant.rs @@ -1,7 +1,7 @@ use std::fmt; use itertools::Itertools; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Cmpop, Expr, ExprKind, Located}; use serde::{Deserialize, Serialize}; @@ -60,13 +60,13 @@ impl fmt::Display for ViolationsCmpop { } } -define_violation!( - pub struct ComparisonOfConstant { - pub left_constant: String, - pub op: ViolationsCmpop, - pub right_constant: String, - } -); +#[violation] +pub struct ComparisonOfConstant { + pub left_constant: String, + pub op: ViolationsCmpop, + pub right_constant: String, +} + impl Violation for ComparisonOfConstant { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pylint/rules/consider_using_sys_exit.rs b/crates/ruff/src/rules/pylint/rules/consider_using_sys_exit.rs index a166691145..7b4b063182 100644 --- a/crates/ruff/src/rules/pylint/rules/consider_using_sys_exit.rs +++ b/crates/ruff/src/rules/pylint/rules/consider_using_sys_exit.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use crate::ast::types::{BindingKind, Range}; @@ -7,11 +7,11 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::{AutofixKind, Availability, Violation}; -define_violation!( - pub struct ConsiderUsingSysExit { - pub name: String, - } -); +#[violation] +pub struct ConsiderUsingSysExit { + pub name: String, +} + impl Violation for ConsiderUsingSysExit { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Sometimes)); diff --git a/crates/ruff/src/rules/pylint/rules/global_statement.rs b/crates/ruff/src/rules/pylint/rules/global_statement.rs index 1dd2198358..3180c7ec8a 100644 --- a/crates/ruff/src/rules/pylint/rules/global_statement.rs +++ b/crates/ruff/src/rules/pylint/rules/global_statement.rs @@ -1,46 +1,46 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; use crate::Range; -define_violation!( - /// ## What it does - /// Checks for the use of `global` statements to update identifiers. - /// - /// ## Why is this bad? - /// Pylint discourages the use of `global` variables as global mutable - /// state is a common source of bugs and confusing behavior. - /// - /// ## Example - /// ```python - /// var = 1 - /// - /// def foo(): - /// global var # [global-statement] - /// var = 10 - /// print(var) - /// - /// foo() - /// print(var) - /// ``` - /// - /// Use instead: - /// ```python - /// var = 1 - /// - /// def foo(): - /// print(var) - /// return 10 - /// - /// var = foo() - /// print(var) - /// ``` - pub struct GlobalStatement { - pub name: String, - } -); +/// ## What it does +/// Checks for the use of `global` statements to update identifiers. +/// +/// ## Why is this bad? +/// Pylint discourages the use of `global` variables as global mutable +/// state is a common source of bugs and confusing behavior. +/// +/// ## Example +/// ```python +/// var = 1 +/// +/// def foo(): +/// global var # [global-statement] +/// var = 10 +/// print(var) +/// +/// foo() +/// print(var) +/// ``` +/// +/// Use instead: +/// ```python +/// var = 1 +/// +/// def foo(): +/// print(var) +/// return 10 +/// +/// var = foo() +/// print(var) +/// ``` +#[violation] +pub struct GlobalStatement { + pub name: String, +} + impl Violation for GlobalStatement { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pylint/rules/global_variable_not_assigned.rs b/crates/ruff/src/rules/pylint/rules/global_variable_not_assigned.rs index 7196e995e6..3edeb86fb6 100644 --- a/crates/ruff/src/rules/pylint/rules/global_variable_not_assigned.rs +++ b/crates/ruff/src/rules/pylint/rules/global_variable_not_assigned.rs @@ -1,12 +1,12 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::violation::Violation; -define_violation!( - pub struct GlobalVariableNotAssigned { - pub name: String, - } -); +#[violation] +pub struct GlobalVariableNotAssigned { + pub name: String, +} + impl Violation for GlobalVariableNotAssigned { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pylint/rules/invalid_all_format.rs b/crates/ruff/src/rules/pylint/rules/invalid_all_format.rs index 8a728a4cdb..1c7aa2a06e 100644 --- a/crates/ruff/src/rules/pylint/rules/invalid_all_format.rs +++ b/crates/ruff/src/rules/pylint/rules/invalid_all_format.rs @@ -1,14 +1,14 @@ use rustpython_parser::ast::Expr; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct InvalidAllFormat; -); +#[violation] +pub struct InvalidAllFormat; + impl Violation for InvalidAllFormat { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pylint/rules/invalid_all_object.rs b/crates/ruff/src/rules/pylint/rules/invalid_all_object.rs index 012b616138..5443081aeb 100644 --- a/crates/ruff/src/rules/pylint/rules/invalid_all_object.rs +++ b/crates/ruff/src/rules/pylint/rules/invalid_all_object.rs @@ -1,14 +1,14 @@ use rustpython_parser::ast::Expr; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct InvalidAllObject; -); +#[violation] +pub struct InvalidAllObject; + impl Violation for InvalidAllObject { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pylint/rules/logging.rs b/crates/ruff/src/rules/pylint/rules/logging.rs index 976a716d36..594e84103c 100644 --- a/crates/ruff/src/rules/pylint/rules/logging.rs +++ b/crates/ruff/src/rules/pylint/rules/logging.rs @@ -1,6 +1,6 @@ use rustpython_parser::ast::{Constant, Expr, ExprKind, Keyword}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::helpers::{is_logger_candidate, SimpleCallArgs}; use crate::ast::logging::LoggingLevel; @@ -10,36 +10,36 @@ use crate::registry::{Diagnostic, Rule}; use crate::rules::pyflakes::cformat::CFormatSummary; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for too few positional arguments for a `logging` format string. - /// - /// ## Why is this bad? - /// A `TypeError` will be raised if the statement is run. - /// - /// ## Example - /// ```python - /// import logging - /// - /// try: - /// function() - /// except Exception as e: - /// logging.error("%s error occurred: %s", e) - /// raise - /// ``` - /// - /// Use instead: - /// ```python - /// import logging - /// - /// try: - /// function() - /// except Exception as e: - /// logging.error("%s error occurred: %s", type(e), e) - /// raise - /// ``` - pub struct LoggingTooFewArgs; -); +/// ## What it does +/// Checks for too few positional arguments for a `logging` format string. +/// +/// ## Why is this bad? +/// A `TypeError` will be raised if the statement is run. +/// +/// ## Example +/// ```python +/// import logging +/// +/// try: +/// function() +/// except Exception as e: +/// logging.error("%s error occurred: %s", e) +/// raise +/// ``` +/// +/// Use instead: +/// ```python +/// import logging +/// +/// try: +/// function() +/// except Exception as e: +/// logging.error("%s error occurred: %s", type(e), e) +/// raise +/// ``` +#[violation] +pub struct LoggingTooFewArgs; + impl Violation for LoggingTooFewArgs { #[derive_message_formats] fn message(&self) -> String { @@ -47,36 +47,36 @@ impl Violation for LoggingTooFewArgs { } } -define_violation!( - /// ## What it does - /// Checks for too many positional arguments for a `logging` format string. - /// - /// ## Why is this bad? - /// A `TypeError` will be raised if the statement is run. - /// - /// ## Example - /// ```python - /// import logging - /// - /// try: - /// function() - /// except Exception as e: - /// logging.error("Error occurred: %s", type(e), e) - /// raise - /// ``` - /// - /// Use instead: - /// ```python - /// import logging - /// - /// try: - /// function() - /// except Exception as e: - /// logging.error("%s error occurred: %s", type(e), e) - /// raise - /// ``` - pub struct LoggingTooManyArgs; -); +/// ## What it does +/// Checks for too many positional arguments for a `logging` format string. +/// +/// ## Why is this bad? +/// A `TypeError` will be raised if the statement is run. +/// +/// ## Example +/// ```python +/// import logging +/// +/// try: +/// function() +/// except Exception as e: +/// logging.error("Error occurred: %s", type(e), e) +/// raise +/// ``` +/// +/// Use instead: +/// ```python +/// import logging +/// +/// try: +/// function() +/// except Exception as e: +/// logging.error("%s error occurred: %s", type(e), e) +/// raise +/// ``` +#[violation] +pub struct LoggingTooManyArgs; + impl Violation for LoggingTooManyArgs { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pylint/rules/magic_value_comparison.rs b/crates/ruff/src/rules/pylint/rules/magic_value_comparison.rs index c1a0f490e7..fbed10b760 100644 --- a/crates/ruff/src/rules/pylint/rules/magic_value_comparison.rs +++ b/crates/ruff/src/rules/pylint/rules/magic_value_comparison.rs @@ -1,7 +1,7 @@ use itertools::Itertools; use rustpython_parser::ast::{Constant, Expr, ExprKind, Unaryop}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::helpers::unparse_expr; use crate::ast::types::Range; @@ -10,11 +10,11 @@ use crate::registry::Diagnostic; use crate::rules::pylint::settings::ConstantType; use crate::violation::Violation; -define_violation!( - pub struct MagicValueComparison { - pub value: String, - } -); +#[violation] +pub struct MagicValueComparison { + pub value: String, +} + impl Violation for MagicValueComparison { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pylint/rules/merge_isinstance.rs b/crates/ruff/src/rules/pylint/rules/merge_isinstance.rs index 6d1d5b689d..bd1ae5b4e7 100644 --- a/crates/ruff/src/rules/pylint/rules/merge_isinstance.rs +++ b/crates/ruff/src/rules/pylint/rules/merge_isinstance.rs @@ -1,5 +1,5 @@ use itertools::Itertools; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustc_hash::{FxHashMap, FxHashSet}; use rustpython_parser::ast::{Boolop, Expr, ExprKind}; @@ -10,12 +10,12 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct ConsiderMergingIsinstance { - pub obj: String, - pub types: Vec, - } -); +#[violation] +pub struct ConsiderMergingIsinstance { + pub obj: String, + pub types: Vec, +} + impl Violation for ConsiderMergingIsinstance { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pylint/rules/nonlocal_without_binding.rs b/crates/ruff/src/rules/pylint/rules/nonlocal_without_binding.rs index e9faa9ba8f..77aa3c6ba1 100644 --- a/crates/ruff/src/rules/pylint/rules/nonlocal_without_binding.rs +++ b/crates/ruff/src/rules/pylint/rules/nonlocal_without_binding.rs @@ -1,12 +1,12 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::violation::Violation; -define_violation!( - pub struct NonlocalWithoutBinding { - pub name: String, - } -); +#[violation] +pub struct NonlocalWithoutBinding { + pub name: String, +} + impl Violation for NonlocalWithoutBinding { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pylint/rules/property_with_parameters.rs b/crates/ruff/src/rules/pylint/rules/property_with_parameters.rs index fba8f85dce..c8886ff1dc 100644 --- a/crates/ruff/src/rules/pylint/rules/property_with_parameters.rs +++ b/crates/ruff/src/rules/pylint/rules/property_with_parameters.rs @@ -1,15 +1,15 @@ use rustpython_parser::ast::{Arguments, Expr, ExprKind, Stmt}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::helpers::identifier_range; use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct PropertyWithParameters; -); +#[violation] +pub struct PropertyWithParameters; + impl Violation for PropertyWithParameters { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pylint/rules/redefined_loop_name.rs b/crates/ruff/src/rules/pylint/rules/redefined_loop_name.rs index 55e399fa36..ae4c2c0d71 100644 --- a/crates/ruff/src/rules/pylint/rules/redefined_loop_name.rs +++ b/crates/ruff/src/rules/pylint/rules/redefined_loop_name.rs @@ -4,7 +4,7 @@ use std::{fmt, iter}; use rustpython_parser::ast::{Expr, ExprContext, ExprKind, Stmt, StmtKind, Withitem}; use serde::{Deserialize, Serialize}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::comparable::ComparableExpr; use crate::ast::helpers::unparse_expr; @@ -57,49 +57,49 @@ impl PartialEq for OuterBindingKind { } } -define_violation!( - /// ## What it does - /// Checks for variables defined in `for` loops and `with` statements that - /// get overwritten within the body, for example by another `for` loop or - /// `with` statement or by direct assignment. - /// - /// ## Why is this bad? - /// Redefinition of a loop variable inside the loop's body causes its value - /// to differ from the original loop iteration for the remainder of the - /// block, in a way that will likely cause bugs. - /// - /// In Python, unlike many other languages, `for` loops and `with` - /// statements don't define their own scopes. Therefore, a nested loop that - /// uses the same target variable name as an outer loop will reuse the same - /// actual variable, and the value from the last iteration will "leak out" - /// into the remainder of the enclosing loop. - /// - /// While this mistake is easy to spot in small examples, it can be hidden - /// in larger blocks of code where the definition and redefinition of the - /// variable may not be visible at the same time. - /// - /// ## Example - /// ```python - /// for i in range(10): - /// i = 9 - /// print(i) # prints 9 every iteration - /// - /// for i in range(10): - /// for i in range(10): # original value overwritten - /// pass - /// print(i) # also prints 9 every iteration - /// - /// with path1.open() as f: - /// with path2.open() as f: - /// f = path2.open() - /// print(f.readline()) # prints a line from path2 - /// ``` - pub struct RedefinedLoopName { - pub name: String, - pub outer_kind: OuterBindingKind, - pub inner_kind: InnerBindingKind, - } -); +/// ## What it does +/// Checks for variables defined in `for` loops and `with` statements that +/// get overwritten within the body, for example by another `for` loop or +/// `with` statement or by direct assignment. +/// +/// ## Why is this bad? +/// Redefinition of a loop variable inside the loop's body causes its value +/// to differ from the original loop iteration for the remainder of the +/// block, in a way that will likely cause bugs. +/// +/// In Python, unlike many other languages, `for` loops and `with` +/// statements don't define their own scopes. Therefore, a nested loop that +/// uses the same target variable name as an outer loop will reuse the same +/// actual variable, and the value from the last iteration will "leak out" +/// into the remainder of the enclosing loop. +/// +/// While this mistake is easy to spot in small examples, it can be hidden +/// in larger blocks of code where the definition and redefinition of the +/// variable may not be visible at the same time. +/// +/// ## Example +/// ```python +/// for i in range(10): +/// i = 9 +/// print(i) # prints 9 every iteration +/// +/// for i in range(10): +/// for i in range(10): # original value overwritten +/// pass +/// print(i) # also prints 9 every iteration +/// +/// with path1.open() as f: +/// with path2.open() as f: +/// f = path2.open() +/// print(f.readline()) # prints a line from path2 +/// ``` +#[violation] +pub struct RedefinedLoopName { + pub name: String, + pub outer_kind: OuterBindingKind, + pub inner_kind: InnerBindingKind, +} + impl Violation for RedefinedLoopName { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pylint/rules/return_in_init.rs b/crates/ruff/src/rules/pylint/rules/return_in_init.rs index 56cc420eee..966d7e09c7 100644 --- a/crates/ruff/src/rules/pylint/rules/return_in_init.rs +++ b/crates/ruff/src/rules/pylint/rules/return_in_init.rs @@ -1,6 +1,6 @@ use rustpython_parser::ast::{Constant, ExprKind, Stmt, StmtKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; @@ -8,35 +8,35 @@ use crate::registry::Diagnostic; use crate::rules::pylint::helpers::in_dunder_init; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for `__init__` methods that return values. - /// - /// ## Why is this bad? - /// The `__init__` method is the constructor for a given Python class, - /// responsible for initializing, rather than creating, new objects. - /// - /// The `__init__` method has to return `None`. Returning any value from - /// an `__init__` method will result in a runtime error. - /// - /// ## Example - /// ```python - /// class Example: - /// def __init__(self): - /// return [] - /// ``` - /// - /// Use instead: - /// ```python - /// class Example: - /// def __init__(self): - /// self.value = [] - /// ``` - /// - /// ## References - /// - [CodeQL: `py-explicit-return-in-init`](https://codeql.github.com/codeql-query-help/python/py-explicit-return-in-init/) - pub struct ReturnInInit; -); +/// ## What it does +/// Checks for `__init__` methods that return values. +/// +/// ## Why is this bad? +/// The `__init__` method is the constructor for a given Python class, +/// responsible for initializing, rather than creating, new objects. +/// +/// The `__init__` method has to return `None`. Returning any value from +/// an `__init__` method will result in a runtime error. +/// +/// ## Example +/// ```python +/// class Example: +/// def __init__(self): +/// return [] +/// ``` +/// +/// Use instead: +/// ```python +/// class Example: +/// def __init__(self): +/// self.value = [] +/// ``` +/// +/// ## References +/// - [CodeQL: `py-explicit-return-in-init`](https://codeql.github.com/codeql-query-help/python/py-explicit-return-in-init/) +#[violation] +pub struct ReturnInInit; + impl Violation for ReturnInInit { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pylint/rules/too_many_arguments.rs b/crates/ruff/src/rules/pylint/rules/too_many_arguments.rs index 0ff44358cd..9ab77b2410 100644 --- a/crates/ruff/src/rules/pylint/rules/too_many_arguments.rs +++ b/crates/ruff/src/rules/pylint/rules/too_many_arguments.rs @@ -1,18 +1,17 @@ use rustpython_parser::ast::{Arguments, Stmt}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::helpers::identifier_range; use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct TooManyArguments { - pub c_args: usize, - pub max_args: usize, - } -); +#[violation] +pub struct TooManyArguments { + pub c_args: usize, + pub max_args: usize, +} impl Violation for TooManyArguments { #[derive_message_formats] diff --git a/crates/ruff/src/rules/pylint/rules/too_many_branches.rs b/crates/ruff/src/rules/pylint/rules/too_many_branches.rs index 202c183741..e8a11d28f3 100644 --- a/crates/ruff/src/rules/pylint/rules/too_many_branches.rs +++ b/crates/ruff/src/rules/pylint/rules/too_many_branches.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{ExcepthandlerKind, Stmt, StmtKind}; use crate::ast::helpers::identifier_range; @@ -6,12 +6,11 @@ use crate::registry::Diagnostic; use crate::source_code::Locator; use crate::violation::Violation; -define_violation!( - pub struct TooManyBranches { - pub branches: usize, - pub max_branches: usize, - } -); +#[violation] +pub struct TooManyBranches { + pub branches: usize, + pub max_branches: usize, +} impl Violation for TooManyBranches { #[derive_message_formats] diff --git a/crates/ruff/src/rules/pylint/rules/too_many_return_statements.rs b/crates/ruff/src/rules/pylint/rules/too_many_return_statements.rs index 57b2fa1f4d..be0726330f 100644 --- a/crates/ruff/src/rules/pylint/rules/too_many_return_statements.rs +++ b/crates/ruff/src/rules/pylint/rules/too_many_return_statements.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Stmt; use crate::ast::helpers::{identifier_range, ReturnStatementVisitor}; @@ -7,12 +7,12 @@ use crate::registry::Diagnostic; use crate::source_code::Locator; use crate::violation::Violation; -define_violation!( - pub struct TooManyReturnStatements { - pub returns: usize, - pub max_returns: usize, - } -); +#[violation] +pub struct TooManyReturnStatements { + pub returns: usize, + pub max_returns: usize, +} + impl Violation for TooManyReturnStatements { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pylint/rules/too_many_statements.rs b/crates/ruff/src/rules/pylint/rules/too_many_statements.rs index d72f1c5224..b058fed91f 100644 --- a/crates/ruff/src/rules/pylint/rules/too_many_statements.rs +++ b/crates/ruff/src/rules/pylint/rules/too_many_statements.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{ExcepthandlerKind, Stmt, StmtKind}; use crate::ast::helpers::identifier_range; @@ -6,12 +6,12 @@ use crate::registry::Diagnostic; use crate::source_code::Locator; use crate::violation::Violation; -define_violation!( - pub struct TooManyStatements { - pub statements: usize, - pub max_statements: usize, - } -); +#[violation] +pub struct TooManyStatements { + pub statements: usize, + pub max_statements: usize, +} + impl Violation for TooManyStatements { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pylint/rules/unnecessary_direct_lambda_call.rs b/crates/ruff/src/rules/pylint/rules/unnecessary_direct_lambda_call.rs index 64602d7d04..a614ca89ec 100644 --- a/crates/ruff/src/rules/pylint/rules/unnecessary_direct_lambda_call.rs +++ b/crates/ruff/src/rules/pylint/rules/unnecessary_direct_lambda_call.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use crate::ast::types::Range; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct UnnecessaryDirectLambdaCall; -); +#[violation] +pub struct UnnecessaryDirectLambdaCall; + impl Violation for UnnecessaryDirectLambdaCall { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pylint/rules/use_from_import.rs b/crates/ruff/src/rules/pylint/rules/use_from_import.rs index 3798c024f4..8eadf98858 100644 --- a/crates/ruff/src/rules/pylint/rules/use_from_import.rs +++ b/crates/ruff/src/rules/pylint/rules/use_from_import.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Alias, AliasData, Located, Stmt, StmtKind}; use crate::ast::helpers::{create_stmt, unparse_stmt}; @@ -8,13 +8,13 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::{AutofixKind, Availability, Violation}; -define_violation!( - pub struct ConsiderUsingFromImport { - pub module: String, - pub name: String, - pub fixable: bool, - } -); +#[violation] +pub struct ConsiderUsingFromImport { + pub module: String, + pub name: String, + pub fixable: bool, +} + impl Violation for ConsiderUsingFromImport { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Sometimes)); diff --git a/crates/ruff/src/rules/pylint/rules/used_prior_global_declaration.rs b/crates/ruff/src/rules/pylint/rules/used_prior_global_declaration.rs index bbfbfa1858..150f199bad 100644 --- a/crates/ruff/src/rules/pylint/rules/used_prior_global_declaration.rs +++ b/crates/ruff/src/rules/pylint/rules/used_prior_global_declaration.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Expr; use crate::ast::types::{Range, ScopeKind}; @@ -6,12 +6,12 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct UsedPriorGlobalDeclaration { - pub name: String, - pub line: usize, - } -); +#[violation] +pub struct UsedPriorGlobalDeclaration { + pub name: String, + pub line: usize, +} + impl Violation for UsedPriorGlobalDeclaration { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pylint/rules/useless_else_on_loop.rs b/crates/ruff/src/rules/pylint/rules/useless_else_on_loop.rs index f370a7142a..924d8c9931 100644 --- a/crates/ruff/src/rules/pylint/rules/useless_else_on_loop.rs +++ b/crates/ruff/src/rules/pylint/rules/useless_else_on_loop.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{ExcepthandlerKind, MatchCase, Stmt, StmtKind}; use crate::ast::helpers; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct UselessElseOnLoop; -); +#[violation] +pub struct UselessElseOnLoop; + impl Violation for UselessElseOnLoop { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pylint/rules/useless_import_alias.rs b/crates/ruff/src/rules/pylint/rules/useless_import_alias.rs index 88d9f73921..02cc6e0ee3 100644 --- a/crates/ruff/src/rules/pylint/rules/useless_import_alias.rs +++ b/crates/ruff/src/rules/pylint/rules/useless_import_alias.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Alias; use crate::ast::types::Range; @@ -7,9 +7,9 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct UselessImportAlias; -); +#[violation] +pub struct UselessImportAlias; + impl AlwaysAutofixableViolation for UselessImportAlias { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pylint/rules/yield_in_init.rs b/crates/ruff/src/rules/pylint/rules/yield_in_init.rs index 07bc0f09b9..f741dc0bdf 100644 --- a/crates/ruff/src/rules/pylint/rules/yield_in_init.rs +++ b/crates/ruff/src/rules/pylint/rules/yield_in_init.rs @@ -1,36 +1,35 @@ use rustpython_parser::ast::Expr; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::rules::pylint::helpers::in_dunder_init; use crate::{ ast::types::Range, checkers::ast::Checker, registry::Diagnostic, violation::Violation, }; -define_violation!( - /// ## What it does - /// Checks for `__init__` methods that are turned into generators by the - /// inclusion of `yield` or `yield from` expressions. - /// - /// ## Why is this bad? - /// The `__init__` method is the constructor for a given Python class, - /// responsible for initializing, rather than creating, new objects. - /// - /// The `__init__` method has to return `None`. By including a `yield` or - /// `yield from` expression in an `__init__`, the method will return a - /// generator object when called at runtime, resulting in a runtime error. - /// - /// ## Example - /// ```python - /// class InitIsGenerator: - /// def __init__(self, i): - /// yield i - /// ``` - /// - /// ## References - /// - [CodeQL: `py-init-method-is-generator`](https://codeql.github.com/codeql-query-help/python/py-init-method-is-generator/) - pub struct YieldInInit; -); +/// ## What it does +/// Checks for `__init__` methods that are turned into generators by the +/// inclusion of `yield` or `yield from` expressions. +/// +/// ## Why is this bad? +/// The `__init__` method is the constructor for a given Python class, +/// responsible for initializing, rather than creating, new objects. +/// +/// The `__init__` method has to return `None`. By including a `yield` or +/// `yield from` expression in an `__init__`, the method will return a +/// generator object when called at runtime, resulting in a runtime error. +/// +/// ## Example +/// ```python +/// class InitIsGenerator: +/// def __init__(self, i): +/// yield i +/// ``` +/// +/// ## References +/// - [CodeQL: `py-init-method-is-generator`](https://codeql.github.com/codeql-query-help/python/py-init-method-is-generator/) +#[violation] +pub struct YieldInInit; impl Violation for YieldInInit { #[derive_message_formats] diff --git a/crates/ruff/src/rules/pyupgrade/rules/convert_named_tuple_functional_to_class.rs b/crates/ruff/src/rules/pyupgrade/rules/convert_named_tuple_functional_to_class.rs index 702a5e114b..35ed751c1c 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/convert_named_tuple_functional_to_class.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/convert_named_tuple_functional_to_class.rs @@ -2,7 +2,7 @@ use anyhow::{bail, Result}; use log::debug; use rustpython_parser::ast::{Constant, Expr, ExprContext, ExprKind, Keyword, Stmt, StmtKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use ruff_python::identifiers::is_identifier; use ruff_python::keyword::KWLIST; @@ -15,12 +15,12 @@ use crate::source_code::Stylist; use crate::violation::{Availability, Violation}; use crate::AutofixKind; -define_violation!( - pub struct ConvertNamedTupleFunctionalToClass { - pub name: String, - pub fixable: bool, - } -); +#[violation] +pub struct ConvertNamedTupleFunctionalToClass { + pub name: String, + pub fixable: bool, +} + impl Violation for ConvertNamedTupleFunctionalToClass { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Sometimes)); diff --git a/crates/ruff/src/rules/pyupgrade/rules/convert_typed_dict_functional_to_class.rs b/crates/ruff/src/rules/pyupgrade/rules/convert_typed_dict_functional_to_class.rs index 0e81da92c0..fdb387fb84 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/convert_typed_dict_functional_to_class.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/convert_typed_dict_functional_to_class.rs @@ -2,7 +2,7 @@ use anyhow::{bail, Result}; use log::debug; use rustpython_parser::ast::{Constant, Expr, ExprContext, ExprKind, Keyword, Stmt, StmtKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use ruff_python::identifiers::is_identifier; use ruff_python::keyword::KWLIST; @@ -15,12 +15,12 @@ use crate::source_code::Stylist; use crate::violation::{Availability, Violation}; use crate::AutofixKind; -define_violation!( - pub struct ConvertTypedDictFunctionalToClass { - pub name: String, - pub fixable: bool, - } -); +#[violation] +pub struct ConvertTypedDictFunctionalToClass { + pub name: String, + pub fixable: bool, +} + impl Violation for ConvertTypedDictFunctionalToClass { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Sometimes)); diff --git a/crates/ruff/src/rules/pyupgrade/rules/datetime_utc_alias.rs b/crates/ruff/src/rules/pyupgrade/rules/datetime_utc_alias.rs index cc62c524ef..77cf046034 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/datetime_utc_alias.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/datetime_utc_alias.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Expr; use crate::ast::helpers::collect_call_path; @@ -8,11 +8,11 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::{AutofixKind, Availability, Violation}; -define_violation!( - pub struct DatetimeTimezoneUTC { - pub straight_import: bool, - } -); +#[violation] +pub struct DatetimeTimezoneUTC { + pub straight_import: bool, +} + impl Violation for DatetimeTimezoneUTC { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Sometimes)); diff --git a/crates/ruff/src/rules/pyupgrade/rules/deprecated_unittest_alias.rs b/crates/ruff/src/rules/pyupgrade/rules/deprecated_unittest_alias.rs index 158c5fd2fc..bb2eefabff 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/deprecated_unittest_alias.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/deprecated_unittest_alias.rs @@ -1,5 +1,5 @@ use once_cell::sync::Lazy; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustc_hash::FxHashMap; use rustpython_parser::ast::{Expr, ExprKind}; @@ -9,12 +9,12 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct DeprecatedUnittestAlias { - pub alias: String, - pub target: String, - } -); +#[violation] +pub struct DeprecatedUnittestAlias { + pub alias: String, + pub target: String, +} + impl AlwaysAutofixableViolation for DeprecatedUnittestAlias { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/extraneous_parentheses.rs b/crates/ruff/src/rules/pyupgrade/rules/extraneous_parentheses.rs index f2121e5675..edd0cf3897 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/extraneous_parentheses.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/extraneous_parentheses.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::lexer::LexResult; use rustpython_parser::Tok; @@ -9,9 +9,9 @@ use crate::settings::{flags, Settings}; use crate::source_code::Locator; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct ExtraneousParentheses; -); +#[violation] +pub struct ExtraneousParentheses; + impl AlwaysAutofixableViolation for ExtraneousParentheses { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/f_strings.rs b/crates/ruff/src/rules/pyupgrade/rules/f_strings.rs index e77dca6b2c..76e1e6a82c 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/f_strings.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/f_strings.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustc_hash::FxHashMap; use rustpython_common::format::{ FieldName, FieldNamePart, FieldType, FormatPart, FormatString, FromTemplate, @@ -15,9 +15,9 @@ use crate::rules::pyflakes::format::FormatSummary; use crate::rules::pyupgrade::helpers::curly_escape; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct FString; -); +#[violation] +pub struct FString; + impl AlwaysAutofixableViolation for FString { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/format_literals.rs b/crates/ruff/src/rules/pyupgrade/rules/format_literals.rs index 25672f3264..c04d5f8ab4 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/format_literals.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/format_literals.rs @@ -2,7 +2,7 @@ use anyhow::{anyhow, bail, Result}; use libcst_native::{Arg, Codegen, CodegenState, Expression}; use once_cell::sync::Lazy; use regex::Regex; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Expr; use crate::ast::types::Range; @@ -14,9 +14,9 @@ use crate::rules::pyflakes::format::FormatSummary; use crate::source_code::{Locator, Stylist}; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct FormatLiterals; -); +#[violation] +pub struct FormatLiterals; + impl AlwaysAutofixableViolation for FormatLiterals { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/functools_cache.rs b/crates/ruff/src/rules/pyupgrade/rules/functools_cache.rs index bd28d0b895..555d438fb0 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/functools_cache.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/functools_cache.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprKind, KeywordData}; use crate::ast::helpers::{create_expr, unparse_expr}; @@ -8,9 +8,9 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct FunctoolsCache; -); +#[violation] +pub struct FunctoolsCache; + impl AlwaysAutofixableViolation for FunctoolsCache { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/import_replacements.rs b/crates/ruff/src/rules/pyupgrade/rules/import_replacements.rs index 4192a2b081..18c32d6648 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/import_replacements.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/import_replacements.rs @@ -1,5 +1,5 @@ use itertools::Itertools; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Alias, AliasData, Stmt}; use crate::ast::types::Range; @@ -12,13 +12,13 @@ use crate::settings::types::PythonVersion; use crate::source_code::{Locator, Stylist}; use crate::violation::{AutofixKind, Availability, Violation}; -define_violation!( - pub struct ImportReplacements { - pub module: String, - pub members: Vec, - pub fixable: bool, - } -); +#[violation] +pub struct ImportReplacements { + pub module: String, + pub members: Vec, + pub fixable: bool, +} + impl Violation for ImportReplacements { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Sometimes)); diff --git a/crates/ruff/src/rules/pyupgrade/rules/lru_cache_without_parameters.rs b/crates/ruff/src/rules/pyupgrade/rules/lru_cache_without_parameters.rs index 2d457605b4..946637b298 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/lru_cache_without_parameters.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/lru_cache_without_parameters.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use crate::ast::helpers::unparse_expr; @@ -8,9 +8,9 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct LRUCacheWithoutParameters; -); +#[violation] +pub struct LRUCacheWithoutParameters; + impl AlwaysAutofixableViolation for LRUCacheWithoutParameters { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/native_literals.rs b/crates/ruff/src/rules/pyupgrade/rules/native_literals.rs index 8e71124118..7ccbbaa5ef 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/native_literals.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/native_literals.rs @@ -1,6 +1,6 @@ use std::fmt; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprKind, Keyword}; use rustpython_parser::{lexer, Mode, Tok}; use serde::{Deserialize, Serialize}; @@ -26,11 +26,11 @@ impl fmt::Display for LiteralType { } } -define_violation!( - pub struct NativeLiterals { - pub literal_type: LiteralType, - } -); +#[violation] +pub struct NativeLiterals { + pub literal_type: LiteralType, +} + impl AlwaysAutofixableViolation for NativeLiterals { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/open_alias.rs b/crates/ruff/src/rules/pyupgrade/rules/open_alias.rs index b21d4dab30..180e061680 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/open_alias.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/open_alias.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Expr; use crate::ast::types::Range; @@ -7,9 +7,9 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct OpenAlias; -); +#[violation] +pub struct OpenAlias; + impl AlwaysAutofixableViolation for OpenAlias { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/os_error_alias.rs b/crates/ruff/src/rules/pyupgrade/rules/os_error_alias.rs index aa51f4bf18..71c6ba077f 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/os_error_alias.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/os_error_alias.rs @@ -1,7 +1,7 @@ use itertools::Itertools; use rustpython_parser::ast::{Excepthandler, ExcepthandlerKind, Expr, ExprKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::helpers::compose_call_path; use crate::ast::types::Range; @@ -10,11 +10,11 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct OSErrorAlias { - pub name: Option, - } -); +#[violation] +pub struct OSErrorAlias { + pub name: Option, +} + impl AlwaysAutofixableViolation for OSErrorAlias { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/outdated_version_block.rs b/crates/ruff/src/rules/pyupgrade/rules/outdated_version_block.rs index 45b8eeeff1..d7da7135b3 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/outdated_version_block.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/outdated_version_block.rs @@ -2,7 +2,7 @@ use std::cmp::Ordering; use log::error; use num_bigint::{BigInt, Sign}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Cmpop, Constant, Expr, ExprKind, Located, Location, Stmt}; use rustpython_parser::{lexer, Mode, Tok}; @@ -17,9 +17,9 @@ use crate::settings::types::PythonVersion; use crate::source_code::Locator; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct OutdatedVersionBlock; -); +#[violation] +pub struct OutdatedVersionBlock; + impl AlwaysAutofixableViolation for OutdatedVersionBlock { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/printf_string_formatting.rs b/crates/ruff/src/rules/pyupgrade/rules/printf_string_formatting.rs index 149b0db234..bf7ecba582 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/printf_string_formatting.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/printf_string_formatting.rs @@ -1,6 +1,6 @@ use std::str::FromStr; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use ruff_python::identifiers::is_identifier; use ruff_python::keyword::KWLIST; use rustpython_common::cformat::{ @@ -18,9 +18,9 @@ use crate::rules::pydocstyle::helpers::{leading_quote, trailing_quote}; use crate::rules::pyupgrade::helpers::curly_escape; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct PrintfStringFormatting; -); +#[violation] +pub struct PrintfStringFormatting; + impl AlwaysAutofixableViolation for PrintfStringFormatting { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/quoted_annotation.rs b/crates/ruff/src/rules/pyupgrade/rules/quoted_annotation.rs index 368ae7d5af..78bb2e6566 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/quoted_annotation.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/quoted_annotation.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::checkers::ast::Checker; @@ -6,9 +6,9 @@ use crate::fix::Fix; use crate::registry::{Diagnostic, Rule}; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct QuotedAnnotation; -); +#[violation] +pub struct QuotedAnnotation; + impl AlwaysAutofixableViolation for QuotedAnnotation { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/redundant_open_modes.rs b/crates/ruff/src/rules/pyupgrade/rules/redundant_open_modes.rs index ad59678368..797598cecc 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/redundant_open_modes.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/redundant_open_modes.rs @@ -2,7 +2,7 @@ use std::str::FromStr; use anyhow::{anyhow, Result}; use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprKind, Keyword, Location}; use rustpython_parser::{lexer, Mode, Tok}; @@ -14,11 +14,11 @@ use crate::registry::{Diagnostic, Rule}; use crate::source_code::Locator; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct RedundantOpenModes { - pub replacement: Option, - } -); +#[violation] +pub struct RedundantOpenModes { + pub replacement: Option, +} + impl AlwaysAutofixableViolation for RedundantOpenModes { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/replace_stdout_stderr.rs b/crates/ruff/src/rules/pyupgrade/rules/replace_stdout_stderr.rs index ae1c137eed..ff0f35e71c 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/replace_stdout_stderr.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/replace_stdout_stderr.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, Keyword}; use crate::ast::helpers::find_keyword; @@ -10,9 +10,9 @@ use crate::registry::Diagnostic; use crate::source_code::{Locator, Stylist}; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct ReplaceStdoutStderr; -); +#[violation] +pub struct ReplaceStdoutStderr; + impl AlwaysAutofixableViolation for ReplaceStdoutStderr { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/replace_universal_newlines.rs b/crates/ruff/src/rules/pyupgrade/rules/replace_universal_newlines.rs index 7db1fbf039..93dd182677 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/replace_universal_newlines.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/replace_universal_newlines.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, Keyword, Location}; use crate::ast::helpers::find_keyword; @@ -8,9 +8,9 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct ReplaceUniversalNewlines; -); +#[violation] +pub struct ReplaceUniversalNewlines; + impl AlwaysAutofixableViolation for ReplaceUniversalNewlines { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/rewrite_c_element_tree.rs b/crates/ruff/src/rules/pyupgrade/rules/rewrite_c_element_tree.rs index 4ece48ed97..df81517633 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/rewrite_c_element_tree.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/rewrite_c_element_tree.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Located, Stmt, StmtKind}; use crate::ast::types::Range; @@ -7,9 +7,9 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct RewriteCElementTree; -); +#[violation] +pub struct RewriteCElementTree; + impl AlwaysAutofixableViolation for RewriteCElementTree { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/rewrite_mock_import.rs b/crates/ruff/src/rules/pyupgrade/rules/rewrite_mock_import.rs index c100f2d65c..799c6327ad 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/rewrite_mock_import.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/rewrite_mock_import.rs @@ -4,7 +4,7 @@ use libcst_native::{ ImportAlias, ImportFrom, ImportNames, Name, NameOrAttribute, ParenthesizableWhitespace, }; use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind, Stmt, StmtKind}; use serde::{Deserialize, Serialize}; @@ -24,11 +24,11 @@ pub enum MockReference { Attribute, } -define_violation!( - pub struct RewriteMockImport { - pub reference_type: MockReference, - } -); +#[violation] +pub struct RewriteMockImport { + pub reference_type: MockReference, +} + impl AlwaysAutofixableViolation for RewriteMockImport { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/rewrite_unicode_literal.rs b/crates/ruff/src/rules/pyupgrade/rules/rewrite_unicode_literal.rs index 2416425a99..eb34d83dfe 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/rewrite_unicode_literal.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/rewrite_unicode_literal.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, Location}; use crate::ast::types::Range; @@ -7,9 +7,9 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct RewriteUnicodeLiteral; -); +#[violation] +pub struct RewriteUnicodeLiteral; + impl AlwaysAutofixableViolation for RewriteUnicodeLiteral { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/rewrite_yield_from.rs b/crates/ruff/src/rules/pyupgrade/rules/rewrite_yield_from.rs index 9f0a7914ac..22a4786226 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/rewrite_yield_from.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/rewrite_yield_from.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustc_hash::FxHashMap; use rustpython_parser::ast::{Expr, ExprContext, ExprKind, Stmt, StmtKind}; @@ -10,9 +10,9 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct RewriteYieldFrom; -); +#[violation] +pub struct RewriteYieldFrom; + impl AlwaysAutofixableViolation for RewriteYieldFrom { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/super_call_with_parameters.rs b/crates/ruff/src/rules/pyupgrade/rules/super_call_with_parameters.rs index 5718f59c67..adada32ea0 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/super_call_with_parameters.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/super_call_with_parameters.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{ArgData, Expr, ExprKind, Stmt, StmtKind}; use crate::ast::types::{Range, ScopeKind}; @@ -7,9 +7,9 @@ use crate::registry::Diagnostic; use crate::rules::pyupgrade::fixes; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct SuperCallWithParameters; -); +#[violation] +pub struct SuperCallWithParameters; + impl AlwaysAutofixableViolation for SuperCallWithParameters { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/type_of_primitive.rs b/crates/ruff/src/rules/pyupgrade/rules/type_of_primitive.rs index 4abc74b3ef..7cf022dd22 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/type_of_primitive.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/type_of_primitive.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use super::super::types::Primitive; @@ -8,11 +8,11 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct TypeOfPrimitive { - pub primitive: Primitive, - } -); +#[violation] +pub struct TypeOfPrimitive { + pub primitive: Primitive, +} + impl AlwaysAutofixableViolation for TypeOfPrimitive { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/typing_text_str_alias.rs b/crates/ruff/src/rules/pyupgrade/rules/typing_text_str_alias.rs index 4c66830caa..3833cdfa5f 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/typing_text_str_alias.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/typing_text_str_alias.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Expr; use crate::ast::types::Range; @@ -7,9 +7,9 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct TypingTextStrAlias; -); +#[violation] +pub struct TypingTextStrAlias; + impl AlwaysAutofixableViolation for TypingTextStrAlias { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/unnecessary_builtin_import.rs b/crates/ruff/src/rules/pyupgrade/rules/unnecessary_builtin_import.rs index 2b1dd48a20..a0fe5f1cda 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/unnecessary_builtin_import.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/unnecessary_builtin_import.rs @@ -1,6 +1,6 @@ use itertools::Itertools; use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Alias, AliasData, Located, Stmt}; use crate::ast::types::Range; @@ -9,11 +9,11 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct UnnecessaryBuiltinImport { - pub names: Vec, - } -); +#[violation] +pub struct UnnecessaryBuiltinImport { + pub names: Vec, +} + impl AlwaysAutofixableViolation for UnnecessaryBuiltinImport { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/unnecessary_coding_comment.rs b/crates/ruff/src/rules/pyupgrade/rules/unnecessary_coding_comment.rs index fe3d2ff864..bd53aaf2b9 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/unnecessary_coding_comment.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/unnecessary_coding_comment.rs @@ -1,6 +1,6 @@ use once_cell::sync::Lazy; use regex::Regex; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Location; use crate::ast::types::Range; @@ -8,10 +8,10 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - // TODO: document referencing [PEP 3120]: https://peps.python.org/pep-3120/ - pub struct UTF8EncodingDeclaration; -); +// TODO: document referencing [PEP 3120]: https://peps.python.org/pep-3120/ +#[violation] +pub struct UTF8EncodingDeclaration; + impl AlwaysAutofixableViolation for UTF8EncodingDeclaration { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/unnecessary_encode_utf8.rs b/crates/ruff/src/rules/pyupgrade/rules/unnecessary_encode_utf8.rs index d59889de4c..05972ee2ef 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/unnecessary_encode_utf8.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/unnecessary_encode_utf8.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprKind, Keyword}; use crate::ast::types::Range; @@ -8,9 +8,9 @@ use crate::registry::{Diagnostic, Rule}; use crate::source_code::Locator; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct UnnecessaryEncodeUTF8; -); +#[violation] +pub struct UnnecessaryEncodeUTF8; + impl AlwaysAutofixableViolation for UnnecessaryEncodeUTF8 { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/unnecessary_future_import.rs b/crates/ruff/src/rules/pyupgrade/rules/unnecessary_future_import.rs index 91c1391c99..96d50ee92a 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/unnecessary_future_import.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/unnecessary_future_import.rs @@ -1,6 +1,6 @@ use itertools::Itertools; use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Alias, AliasData, Located, Stmt}; use crate::ast::types::Range; @@ -9,11 +9,11 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct UnnecessaryFutureImport { - pub names: Vec, - } -); +#[violation] +pub struct UnnecessaryFutureImport { + pub names: Vec, +} + impl AlwaysAutofixableViolation for UnnecessaryFutureImport { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/unpack_list_comprehension.rs b/crates/ruff/src/rules/pyupgrade/rules/unpack_list_comprehension.rs index ac33a3aef4..42bd1642f2 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/unpack_list_comprehension.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/unpack_list_comprehension.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use crate::ast::types::Range; @@ -7,9 +7,9 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct RewriteListComprehension; -); +#[violation] +pub struct RewriteListComprehension; + impl AlwaysAutofixableViolation for RewriteListComprehension { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/use_pep585_annotation.rs b/crates/ruff/src/rules/pyupgrade/rules/use_pep585_annotation.rs index fef21d0988..5ce157d526 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/use_pep585_annotation.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/use_pep585_annotation.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::Expr; use crate::ast::types::Range; @@ -7,12 +7,12 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - // TODO: document referencing [PEP 585]: https://peps.python.org/pep-0585/ - pub struct DeprecatedCollectionType { - pub name: String, - } -); +// TODO: document referencing [PEP 585]: https://peps.python.org/pep-0585/ +#[violation] +pub struct DeprecatedCollectionType { + pub name: String, +} + impl AlwaysAutofixableViolation for DeprecatedCollectionType { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/use_pep604_annotation.rs b/crates/ruff/src/rules/pyupgrade/rules/use_pep604_annotation.rs index 977378f3a6..f1fe64f850 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/use_pep604_annotation.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/use_pep604_annotation.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprKind, Location, Operator}; use crate::ast::helpers::unparse_expr; @@ -8,10 +8,10 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - // TODO: document referencing [PEP 604]: https://peps.python.org/pep-0604/ - pub struct TypingUnion; -); +// TODO: document referencing [PEP 604]: https://peps.python.org/pep-0604/ +#[violation] +pub struct TypingUnion; + impl AlwaysAutofixableViolation for TypingUnion { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/useless_metaclass_type.rs b/crates/ruff/src/rules/pyupgrade/rules/useless_metaclass_type.rs index 6b61112c78..749a381e23 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/useless_metaclass_type.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/useless_metaclass_type.rs @@ -1,5 +1,5 @@ use log::error; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind, Stmt}; use crate::ast::types::Range; @@ -8,9 +8,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct UselessMetaclassType; -); +#[violation] +pub struct UselessMetaclassType; + impl AlwaysAutofixableViolation for UselessMetaclassType { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/pyupgrade/rules/useless_object_inheritance.rs b/crates/ruff/src/rules/pyupgrade/rules/useless_object_inheritance.rs index 21434ea8aa..e66d62b4f5 100644 --- a/crates/ruff/src/rules/pyupgrade/rules/useless_object_inheritance.rs +++ b/crates/ruff/src/rules/pyupgrade/rules/useless_object_inheritance.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind, Keyword, Stmt}; use super::super::fixes; @@ -7,11 +7,11 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct UselessObjectInheritance { - pub name: String, - } -); +#[violation] +pub struct UselessObjectInheritance { + pub name: String, +} + impl AlwaysAutofixableViolation for UselessObjectInheritance { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/ruff/rules/ambiguous_unicode_character.rs b/crates/ruff/src/rules/ruff/rules/ambiguous_unicode_character.rs index 7014f47fc6..a7f2cfe817 100644 --- a/crates/ruff/src/rules/ruff/rules/ambiguous_unicode_character.rs +++ b/crates/ruff/src/rules/ruff/rules/ambiguous_unicode_character.rs @@ -1,5 +1,5 @@ use once_cell::sync::Lazy; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustc_hash::FxHashMap; use crate::ast::types::Range; @@ -11,12 +11,12 @@ use crate::settings::{flags, Settings}; use crate::source_code::Locator; use crate::violation::AlwaysAutofixableViolation; -define_violation!( - pub struct AmbiguousUnicodeCharacterString { - pub confusable: char, - pub representant: char, - } -); +#[violation] +pub struct AmbiguousUnicodeCharacterString { + pub confusable: char, + pub representant: char, +} + impl AlwaysAutofixableViolation for AmbiguousUnicodeCharacterString { #[derive_message_formats] fn message(&self) -> String { @@ -39,12 +39,12 @@ impl AlwaysAutofixableViolation for AmbiguousUnicodeCharacterString { } } -define_violation!( - pub struct AmbiguousUnicodeCharacterDocstring { - pub confusable: char, - pub representant: char, - } -); +#[violation] +pub struct AmbiguousUnicodeCharacterDocstring { + pub confusable: char, + pub representant: char, +} + impl AlwaysAutofixableViolation for AmbiguousUnicodeCharacterDocstring { #[derive_message_formats] fn message(&self) -> String { @@ -67,12 +67,12 @@ impl AlwaysAutofixableViolation for AmbiguousUnicodeCharacterDocstring { } } -define_violation!( - pub struct AmbiguousUnicodeCharacterComment { - pub confusable: char, - pub representant: char, - } -); +#[violation] +pub struct AmbiguousUnicodeCharacterComment { + pub confusable: char, + pub representant: char, +} + impl AlwaysAutofixableViolation for AmbiguousUnicodeCharacterComment { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/ruff/rules/asyncio_dangling_task.rs b/crates/ruff/src/rules/ruff/rules/asyncio_dangling_task.rs index 15a0698848..073bdbb30d 100644 --- a/crates/ruff/src/rules/ruff/rules/asyncio_dangling_task.rs +++ b/crates/ruff/src/rules/ruff/rules/asyncio_dangling_task.rs @@ -3,58 +3,57 @@ use rustpython_parser::ast::{Expr, ExprKind}; use crate::ast::types::{CallPath, Range}; use crate::registry::Diagnostic; use crate::violation::Violation; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use serde::{Deserialize, Serialize}; use std::fmt; -define_violation!( - /// ## What it does - /// Checks for `asyncio.create_task` and `asyncio.ensure_future` calls - /// that do not store a reference to the returned result. - /// - /// ## Why is this bad? - /// Per the `asyncio` documentation, the event loop only retains a weak - /// reference to tasks. If the task returned by `asyncio.create_task` and - /// `asyncio.ensure_future` is not stored in a variable, or a collection, - /// or otherwise referenced, it may be garbage collected at any time. This - /// can lead to unexpected and inconsistent behavior, as your tasks may or - /// may not run to completion. - /// - /// ## Example - /// ```python - /// import asyncio - /// - /// for i in range(10): - /// # This creates a weak reference to the task, which may be garbage - /// # collected at any time. - /// asyncio.create_task(some_coro(param=i)) - /// ``` - /// - /// Use instead: - /// ```python - /// import asyncio - /// - /// background_tasks = set() - /// - /// for i in range(10): - /// task = asyncio.create_task(some_coro(param=i)) - /// - /// # Add task to the set. This creates a strong reference. - /// background_tasks.add(task) - /// - /// # To prevent keeping references to finished tasks forever, - /// # make each task remove its own reference from the set after - /// # completion: - /// task.add_done_callback(background_tasks.discard) - /// ``` - /// - /// ## References - /// - [_The Heisenbug lurking in your async code_](https://textual.textualize.io/blog/2023/02/11/the-heisenbug-lurking-in-your-async-code/) - /// - [The Python Standard Library](https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task) - pub struct AsyncioDanglingTask { - pub method: Method, - } -); +/// ## What it does +/// Checks for `asyncio.create_task` and `asyncio.ensure_future` calls +/// that do not store a reference to the returned result. +/// +/// ## Why is this bad? +/// Per the `asyncio` documentation, the event loop only retains a weak +/// reference to tasks. If the task returned by `asyncio.create_task` and +/// `asyncio.ensure_future` is not stored in a variable, or a collection, +/// or otherwise referenced, it may be garbage collected at any time. This +/// can lead to unexpected and inconsistent behavior, as your tasks may or +/// may not run to completion. +/// +/// ## Example +/// ```python +/// import asyncio +/// +/// for i in range(10): +/// # This creates a weak reference to the task, which may be garbage +/// # collected at any time. +/// asyncio.create_task(some_coro(param=i)) +/// ``` +/// +/// Use instead: +/// ```python +/// import asyncio +/// +/// background_tasks = set() +/// +/// for i in range(10): +/// task = asyncio.create_task(some_coro(param=i)) +/// +/// # Add task to the set. This creates a strong reference. +/// background_tasks.add(task) +/// +/// # To prevent keeping references to finished tasks forever, +/// # make each task remove its own reference from the set after +/// # completion: +/// task.add_done_callback(background_tasks.discard) +/// ``` +/// +/// ## References +/// - [_The Heisenbug lurking in your async code_](https://textual.textualize.io/blog/2023/02/11/the-heisenbug-lurking-in-your-async-code/) +/// - [The Python Standard Library](https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task) +#[violation] +pub struct AsyncioDanglingTask { + pub method: Method, +} impl Violation for AsyncioDanglingTask { #[derive_message_formats] diff --git a/crates/ruff/src/rules/ruff/rules/unpack_instead_of_concatenating_to_collection_literal.rs b/crates/ruff/src/rules/ruff/rules/unpack_instead_of_concatenating_to_collection_literal.rs index d7218c071a..3b71bbc4e3 100644 --- a/crates/ruff/src/rules/ruff/rules/unpack_instead_of_concatenating_to_collection_literal.rs +++ b/crates/ruff/src/rules/ruff/rules/unpack_instead_of_concatenating_to_collection_literal.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprContext, ExprKind, Operator}; use crate::ast::helpers::{create_expr, has_comments, unparse_expr}; @@ -8,12 +8,12 @@ use crate::fix::Fix; use crate::registry::Diagnostic; use crate::violation::{AutofixKind, Availability, Violation}; -define_violation!( - pub struct UnpackInsteadOfConcatenatingToCollectionLiteral { - pub expr: String, - pub fixable: bool, - } -); +#[violation] +pub struct UnpackInsteadOfConcatenatingToCollectionLiteral { + pub expr: String, + pub fixable: bool, +} + impl Violation for UnpackInsteadOfConcatenatingToCollectionLiteral { const AUTOFIX: Option = Some(AutofixKind::new(Availability::Sometimes)); diff --git a/crates/ruff/src/rules/ruff/rules/unused_noqa.rs b/crates/ruff/src/rules/ruff/rules/unused_noqa.rs index cf80378d83..8255e6244a 100644 --- a/crates/ruff/src/rules/ruff/rules/unused_noqa.rs +++ b/crates/ruff/src/rules/ruff/rules/unused_noqa.rs @@ -1,5 +1,5 @@ use itertools::Itertools; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use serde::{Deserialize, Serialize}; use crate::violation::AlwaysAutofixableViolation; @@ -11,11 +11,11 @@ pub struct UnusedCodes { pub unmatched: Vec, } -define_violation!( - pub struct UnusedNOQA { - pub codes: Option, - } -); +#[violation] +pub struct UnusedNOQA { + pub codes: Option, +} + impl AlwaysAutofixableViolation for UnusedNOQA { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/tryceratops/rules/error_instead_of_exception.rs b/crates/ruff/src/rules/tryceratops/rules/error_instead_of_exception.rs index 882b4dea59..86f875a6f8 100644 --- a/crates/ruff/src/rules/tryceratops/rules/error_instead_of_exception.rs +++ b/crates/ruff/src/rules/tryceratops/rules/error_instead_of_exception.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Excepthandler, ExcepthandlerKind, ExprKind}; use crate::ast::types::Range; @@ -8,9 +8,9 @@ use crate::registry::Diagnostic; use crate::rules::tryceratops::helpers::LoggerCandidateVisitor; use crate::violation::Violation; -define_violation!( - pub struct ErrorInsteadOfException; -); +#[violation] +pub struct ErrorInsteadOfException; + impl Violation for ErrorInsteadOfException { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/tryceratops/rules/prefer_type_error.rs b/crates/ruff/src/rules/tryceratops/rules/prefer_type_error.rs index 5ca443bcd1..599d2bcc3c 100644 --- a/crates/ruff/src/rules/tryceratops/rules/prefer_type_error.rs +++ b/crates/ruff/src/rules/tryceratops/rules/prefer_type_error.rs @@ -1,6 +1,6 @@ use rustpython_parser::ast::{Expr, ExprKind, Stmt, StmtKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::ast::visitor; @@ -9,9 +9,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct PreferTypeError; -); +#[violation] +pub struct PreferTypeError; + impl Violation for PreferTypeError { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/tryceratops/rules/raise_vanilla_args.rs b/crates/ruff/src/rules/tryceratops/rules/raise_vanilla_args.rs index 0eed6dacbf..c18058509f 100644 --- a/crates/ruff/src/rules/tryceratops/rules/raise_vanilla_args.rs +++ b/crates/ruff/src/rules/tryceratops/rules/raise_vanilla_args.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Constant, Expr, ExprKind}; use crate::ast::types::Range; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct RaiseVanillaArgs; -); +#[violation] +pub struct RaiseVanillaArgs; + impl Violation for RaiseVanillaArgs { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/tryceratops/rules/raise_vanilla_class.rs b/crates/ruff/src/rules/tryceratops/rules/raise_vanilla_class.rs index 155ed7c27b..8b44c272d1 100644 --- a/crates/ruff/src/rules/tryceratops/rules/raise_vanilla_class.rs +++ b/crates/ruff/src/rules/tryceratops/rules/raise_vanilla_class.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Expr, ExprKind}; use crate::ast::types::Range; @@ -6,54 +6,54 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for code that raises `Exception` directly. - /// - /// ## Why is this bad? - /// Handling such exceptions requires the use of `except Exception`, which - /// captures _any_ raised exception, including failed assertions, - /// division by zero, and more. - /// - /// Prefer to raise your own exception, or a more specific built-in - /// exception, so that you can avoid over-capturing exceptions that you - /// don't intend to handle. - /// - /// ## Example - /// ```python - /// def main_function(): - /// if not cond: - /// raise Exception() - /// - /// - /// def consumer_func(): - /// try: - /// do_step() - /// prepare() - /// main_function() - /// except Exception: - /// logger.error("Oops") - /// ``` - /// - /// Use instead: - /// ```python - /// def main_function(): - /// if not cond: - /// raise CustomException() - /// - /// - /// def consumer_func(): - /// try: - /// do_step() - /// prepare() - /// main_function() - /// except CustomException: - /// logger.error("Main function failed") - /// except Exception: - /// logger.error("Oops") - /// ``` - pub struct RaiseVanillaClass; -); +/// ## What it does +/// Checks for code that raises `Exception` directly. +/// +/// ## Why is this bad? +/// Handling such exceptions requires the use of `except Exception`, which +/// captures _any_ raised exception, including failed assertions, +/// division by zero, and more. +/// +/// Prefer to raise your own exception, or a more specific built-in +/// exception, so that you can avoid over-capturing exceptions that you +/// don't intend to handle. +/// +/// ## Example +/// ```python +/// def main_function(): +/// if not cond: +/// raise Exception() +/// +/// +/// def consumer_func(): +/// try: +/// do_step() +/// prepare() +/// main_function() +/// except Exception: +/// logger.error("Oops") +/// ``` +/// +/// Use instead: +/// ```python +/// def main_function(): +/// if not cond: +/// raise CustomException() +/// +/// +/// def consumer_func(): +/// try: +/// do_step() +/// prepare() +/// main_function() +/// except CustomException: +/// logger.error("Main function failed") +/// except Exception: +/// logger.error("Oops") +/// ``` +#[violation] +pub struct RaiseVanillaClass; + impl Violation for RaiseVanillaClass { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/tryceratops/rules/raise_within_try.rs b/crates/ruff/src/rules/tryceratops/rules/raise_within_try.rs index 76e555cacc..b94e9c1bda 100644 --- a/crates/ruff/src/rules/tryceratops/rules/raise_within_try.rs +++ b/crates/ruff/src/rules/tryceratops/rules/raise_within_try.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Stmt, StmtKind}; use crate::ast::types::Range; @@ -7,9 +7,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct RaiseWithinTry; -); +#[violation] +pub struct RaiseWithinTry; + impl Violation for RaiseWithinTry { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/tryceratops/rules/reraise_no_cause.rs b/crates/ruff/src/rules/tryceratops/rules/reraise_no_cause.rs index 2485424a2d..f68ceb6f07 100644 --- a/crates/ruff/src/rules/tryceratops/rules/reraise_no_cause.rs +++ b/crates/ruff/src/rules/tryceratops/rules/reraise_no_cause.rs @@ -1,6 +1,6 @@ use rustpython_parser::ast::{ExprKind, Stmt}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::helpers::RaiseStatementVisitor; use crate::ast::visitor::Visitor; @@ -8,9 +8,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct ReraiseNoCause; -); +#[violation] +pub struct ReraiseNoCause; + impl Violation for ReraiseNoCause { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/tryceratops/rules/try_consider_else.rs b/crates/ruff/src/rules/tryceratops/rules/try_consider_else.rs index fe2f1f6337..b55b25609b 100644 --- a/crates/ruff/src/rules/tryceratops/rules/try_consider_else.rs +++ b/crates/ruff/src/rules/tryceratops/rules/try_consider_else.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Stmt, StmtKind}; use crate::ast::types::Range; @@ -6,9 +6,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct TryConsiderElse; -); +#[violation] +pub struct TryConsiderElse; + impl Violation for TryConsiderElse { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/tryceratops/rules/verbose_log_message.rs b/crates/ruff/src/rules/tryceratops/rules/verbose_log_message.rs index 28c07c08b6..8f3852fd8b 100644 --- a/crates/ruff/src/rules/tryceratops/rules/verbose_log_message.rs +++ b/crates/ruff/src/rules/tryceratops/rules/verbose_log_message.rs @@ -1,6 +1,6 @@ use rustpython_parser::ast::{Excepthandler, ExcepthandlerKind, Expr, ExprContext, ExprKind}; -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use crate::ast::types::Range; use crate::ast::visitor; @@ -10,32 +10,32 @@ use crate::registry::Diagnostic; use crate::rules::tryceratops::helpers::LoggerCandidateVisitor; use crate::violation::Violation; -define_violation!( - /// ## What it does - /// Checks for excessive logging of exception objects. - /// - /// ## Why is this bad? - /// When logging exceptions via `logging.exception`, the exception object - /// is logged automatically. Including the exception object in the log - /// message is redundant and can lead to excessive logging. - /// - /// ## Example - /// ```python - /// try: - /// ... - /// except ValueError as e: - /// logger.exception(f"Found an error: {e}") - /// ``` - /// - /// Use instead: - /// ```python - /// try: - /// ... - /// except ValueError as e: - /// logger.exception(f"Found an error") - /// ``` - pub struct VerboseLogMessage; -); +/// ## What it does +/// Checks for excessive logging of exception objects. +/// +/// ## Why is this bad? +/// When logging exceptions via `logging.exception`, the exception object +/// is logged automatically. Including the exception object in the log +/// message is redundant and can lead to excessive logging. +/// +/// ## Example +/// ```python +/// try: +/// ... +/// except ValueError as e: +/// logger.exception(f"Found an error: {e}") +/// ``` +/// +/// Use instead: +/// ```python +/// try: +/// ... +/// except ValueError as e: +/// logger.exception(f"Found an error") +/// ``` +#[violation] +pub struct VerboseLogMessage; + impl Violation for VerboseLogMessage { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff/src/rules/tryceratops/rules/verbose_raise.rs b/crates/ruff/src/rules/tryceratops/rules/verbose_raise.rs index ad57a076bc..94276c3ecc 100644 --- a/crates/ruff/src/rules/tryceratops/rules/verbose_raise.rs +++ b/crates/ruff/src/rules/tryceratops/rules/verbose_raise.rs @@ -1,4 +1,4 @@ -use ruff_macros::{define_violation, derive_message_formats}; +use ruff_macros::{derive_message_formats, violation}; use rustpython_parser::ast::{Excepthandler, ExcepthandlerKind, Expr, ExprKind, Stmt, StmtKind}; use crate::ast::types::Range; @@ -8,9 +8,9 @@ use crate::checkers::ast::Checker; use crate::registry::Diagnostic; use crate::violation::Violation; -define_violation!( - pub struct VerboseRaise; -); +#[violation] +pub struct VerboseRaise; + impl Violation for VerboseRaise { #[derive_message_formats] fn message(&self) -> String { diff --git a/crates/ruff_macros/src/define_violation.rs b/crates/ruff_macros/src/define_violation.rs index fcce73cc8a..16eb7a3e4f 100644 --- a/crates/ruff_macros/src/define_violation.rs +++ b/crates/ruff_macros/src/define_violation.rs @@ -1,7 +1,7 @@ use proc_macro2::TokenStream; use quote::quote; use syn::parse::{Parse, ParseStream}; -use syn::{Attribute, Error, Ident, Lit, LitStr, Meta, Result, Token}; +use syn::{Attribute, Error, Ident, ItemStruct, Lit, LitStr, Meta, Result, Token}; fn parse_attr(path: [&'static str; LEN], attr: &Attribute) -> Option { if let Meta::NameValue(name_value) = attr.parse_meta().ok()? { @@ -73,3 +73,45 @@ pub fn define_violation(input: &TokenStream, meta: LintMeta) -> TokenStream { } } } + +/// Collect all doc comment attributes into a string +fn get_docs(attrs: &[Attribute]) -> Result { + let mut explanation = String::new(); + for attr in attrs { + if attr.path.is_ident("doc") { + if let Some(lit) = parse_attr(["doc"], attr) { + let value = lit.value(); + // `/// ` adds + let line = value.strip_prefix(' ').unwrap_or(&value); + explanation.push_str(line); + explanation.push('\n'); + } else { + return Err(Error::new_spanned(attr, "unimplemented doc comment style")); + } + } + } + Ok(explanation) +} + +pub fn violation(violation: &ItemStruct) -> Result { + let ident = &violation.ident; + let explanation = get_docs(&violation.attrs)?; + let violation = if explanation.trim().is_empty() { + quote! { + #[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] + #violation + } + } else { + quote! { + #[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] + #violation + + impl #ident { + pub fn explanation() -> Option<&'static str> { + Some(#explanation) + } + } + } + }; + Ok(violation) +} diff --git a/crates/ruff_macros/src/lib.rs b/crates/ruff_macros/src/lib.rs index 6c6811ba45..3d63e6eaae 100644 --- a/crates/ruff_macros/src/lib.rs +++ b/crates/ruff_macros/src/lib.rs @@ -2,7 +2,7 @@ use crate::cache_key::derive_cache_key; use proc_macro::TokenStream; -use syn::{parse_macro_input, DeriveInput, ItemFn}; +use syn::{parse_macro_input, DeriveInput, ItemFn, ItemStruct}; mod cache_key; mod config; @@ -45,6 +45,16 @@ pub fn define_violation(item: proc_macro::TokenStream) -> proc_macro::TokenStrea define_violation::define_violation(&item.into(), meta).into() } +/// Adds an `explanation()` method from the doc comment and +/// `#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]` +#[proc_macro_attribute] +pub fn violation(_attr: TokenStream, item: TokenStream) -> TokenStream { + let violation = parse_macro_input!(item as ItemStruct); + define_violation::violation(&violation) + .unwrap_or_else(syn::Error::into_compile_error) + .into() +} + #[proc_macro_derive(RuleNamespace, attributes(prefix))] pub fn derive_rule_namespace(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = parse_macro_input!(input as DeriveInput); diff --git a/scripts/add_rule.py b/scripts/add_rule.py index b1d9c3ee08..fa2c3df31f 100755 --- a/scripts/add_rule.py +++ b/scripts/add_rule.py @@ -81,13 +81,12 @@ def main(*, name: str, code: str, linter: str) -> None: fp.write( """use ruff_macros::derive_message_formats; -use ruff_macros::define_violation; +use ruff_macros::violation; use crate::violation::Violation; use crate::checkers::ast::Checker; -define_violation!( - pub struct %s; -); +#[violation] +pub struct %s; impl Violation for %s { #[derive_message_formats] fn message(&self) -> String {