diff --git a/src/lib.rs b/src/lib.rs index 62ff1f15e6..e1743eb76c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -75,6 +75,7 @@ pub mod source_code_generator; pub mod source_code_locator; pub mod source_code_style; mod vendor; +mod violation; pub mod visibility; cfg_if! { diff --git a/src/violation.rs b/src/violation.rs new file mode 100644 index 0000000000..2f7d3204d4 --- /dev/null +++ b/src/violation.rs @@ -0,0 +1,60 @@ +use std::fmt::Debug; + +use serde::de::DeserializeOwned; +use serde::Serialize; + +pub trait Violation: Debug + PartialEq + Eq + Serialize + DeserializeOwned { + /// The message used to describe the violation. + fn message(&self) -> String; + + /// If autofix is (potentially) available for this violation returns another + /// function that in turn can be used to obtain a string describing the + /// autofix. + fn autofix_title_formatter(&self) -> Option String> { + None + } + + /// A placeholder instance of the violation. + fn placeholder() -> Self; +} + +/// This trait exists just to make implementing the [`Violation`] trait more +/// convenient for violations that can always be autofixed. +pub trait AlwaysAutofixableViolation: + Debug + PartialEq + Eq + Serialize + DeserializeOwned +{ + /// The message used to describe the violation. + fn message(&self) -> String; + + /// The title displayed for the available autofix. + fn autofix_title(&self) -> String; + + /// A placeholder instance of the violation. + fn placeholder() -> Self; +} + +/// A blanket implementation. +impl Violation for VA { + fn message(&self) -> String { + ::message(self) + } + + fn autofix_title_formatter(&self) -> Option String> { + Some(Self::autofix_title) + } + + fn placeholder() -> Self { + ::placeholder() + } +} + +/// This macro just exists so that you don't have to add the `#[derive]` +/// attribute every time you define a new violation. And so that new traits can +/// be easily derived everywhere by just changing a single line. +#[macro_export] +macro_rules! define_violation { + ($($struct:tt)*) => { + #[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] + $($struct)* + }; +}