Skip to content

Commit

Permalink
rule 7/7: Drop RuleCode, use human-friendly variants
Browse files Browse the repository at this point in the history
  • Loading branch information
not-my-profile committed Jan 18, 2023
1 parent 2a3da1d commit ee947df
Show file tree
Hide file tree
Showing 91 changed files with 2,449 additions and 1,598 deletions.
2 changes: 1 addition & 1 deletion ruff_cli/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ pub fn run(
.unwrap_or_else(|(path, message)| {
if let Some(path) = &path {
let settings = resolver.resolve(path, pyproject_strategy);
if settings.rules.enabled(&Rule::E902) {
if settings.rules.enabled(&Rule::IOError) {
Diagnostics::new(vec![Message {
kind: IOError(message).into(),
location: Location::default(),
Expand Down
25 changes: 16 additions & 9 deletions ruff_macros/src/define_rule_mapping.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::collections::HashMap;

use proc_macro2::Span;
use quote::quote;
use syn::parse::Parse;
Expand All @@ -17,17 +19,17 @@ pub fn define_rule_mapping(mapping: &Mapping) -> proc_macro2::TokenStream {
let mut from_impls_for_diagkind = quote!();

for (code, path, name) in &mapping.entries {
rule_variants.extend(quote! {#code,});
rule_variants.extend(quote! {#name,});
diagkind_variants.extend(quote! {#name(#path),});
rule_kind_match_arms.extend(
quote! {Self::#code => DiagnosticKind::#name(<#path as Violation>::placeholder()),},
quote! {Self::#name => DiagnosticKind::#name(<#path as Violation>::placeholder()),},
);
let origin = get_origin(code);
rule_origin_match_arms.extend(quote! {Self::#code => RuleOrigin::#origin,});
rule_origin_match_arms.extend(quote! {Self::#name => RuleOrigin::#origin,});
let code_str = LitStr::new(&code.to_string(), Span::call_site());
rule_code_match_arms.extend(quote! {Self::#code => #code_str,});
rule_from_code_match_arms.extend(quote! {#code_str => Ok(&RuleCode::#code), });
diagkind_code_match_arms.extend(quote! {Self::#name(..) => &RuleCode::#code, });
rule_code_match_arms.extend(quote! {Self::#name => #code_str,});
rule_from_code_match_arms.extend(quote! {#code_str => Ok(&Rule::#name), });
diagkind_code_match_arms.extend(quote! {Self::#name(..) => &Rule::#name, });
diagkind_body_match_arms.extend(quote! {Self::#name(x) => Violation::message(x), });
diagkind_fixable_match_arms
.extend(quote! {Self::#name(x) => x.autofix_title_formatter().is_some(),});
Expand All @@ -42,10 +44,17 @@ pub fn define_rule_mapping(mapping: &Mapping) -> proc_macro2::TokenStream {
});
}

let code_to_name: HashMap<_, _> = mapping
.entries
.iter()
.map(|(code, _, name)| (code.to_string(), name))
.collect();

let rulecodeprefix = super::rule_code_prefix::expand(
&Ident::new("RuleCode", Span::call_site()),
&Ident::new("Rule", Span::call_site()),
&Ident::new("RuleCodePrefix", Span::call_site()),
mapping.entries.iter().map(|(code, ..)| code),
|code| code_to_name[code],
);

quote! {
Expand All @@ -61,8 +70,6 @@ pub fn define_rule_mapping(mapping: &Mapping) -> proc_macro2::TokenStream {
)]
pub enum Rule { #rule_variants }

pub use Rule as RuleCode; // TODO(martin): Remove

#[derive(AsRefStr, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum DiagnosticKind { #diagkind_variants }

Expand Down
11 changes: 7 additions & 4 deletions ruff_macros/src/rule_code_prefix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ pub fn expand<'a>(
rule_type: &Ident,
prefix_ident: &Ident,
variants: impl Iterator<Item = &'a Ident>,
variant_name: impl Fn(&str) -> &'a Ident,
) -> proc_macro2::TokenStream {
// Build up a map from prefix to matching RuleCodes.
let mut prefix_to_codes: BTreeMap<Ident, BTreeSet<String>> = BTreeMap::default();
Expand Down Expand Up @@ -129,7 +130,7 @@ pub fn expand<'a>(
}
});

let prefix_impl = generate_impls(rule_type, prefix_ident, &prefix_to_codes);
let prefix_impl = generate_impls(rule_type, prefix_ident, &prefix_to_codes, variant_name);

let prefix_redirects = PREFIX_REDIRECTS.iter().map(|(alias, rule_code)| {
let code = Ident::new(rule_code, Span::call_site());
Expand Down Expand Up @@ -177,16 +178,18 @@ pub fn expand<'a>(
}
}

fn generate_impls(
fn generate_impls<'a>(
rule_type: &Ident,
prefix_ident: &Ident,
prefix_to_codes: &BTreeMap<Ident, BTreeSet<String>>,
// variant_name: impl Fn(&str) -> &Ident,
variant_name: impl Fn(&str) -> &'a Ident,
) -> proc_macro2::TokenStream {
let codes_match_arms = prefix_to_codes.iter().map(|(prefix, codes)| {
let codes = codes.iter().map(|code| {
let code = Ident::new(code, Span::call_site());
let rule_variant = variant_name(code);
quote! {
#rule_type::#code
#rule_type::#rule_variant
}
});
let prefix_str = prefix.to_string();
Expand Down
4 changes: 2 additions & 2 deletions scripts/add_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,11 @@ def main(*, plugin: str, url: str) -> None:
use anyhow::Result;
use test_case::test_case;
use crate::registry::RuleCode;
use crate::registry::Rule;
use crate::linter::test_path;
use crate::settings;
fn rules(rule_code: RuleCode, path: &Path) -> Result<()> {
fn rules(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", rule_code.as_ref(), path.to_string_lossy());
let diagnostics =test_path(
Path::new("./resources/test/fixtures/%s")
Expand Down
6 changes: 3 additions & 3 deletions scripts/add_rule.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ def main(*, name: str, code: str, origin: str) -> None:

with open(mod_rs, "w") as fp:
for line in content.splitlines():
if line.strip() == "fn rules(rule_code: RuleCode, path: &Path) -> Result<()> {":
indent = line.split("fn rules(rule_code: RuleCode, path: &Path) -> Result<()> {")[0]
fp.write(f'{indent}#[test_case(RuleCode::{code}, Path::new("{code}.py"); "{code}")]')
if line.strip() == "fn rules(rule_code: Rule, path: &Path) -> Result<()> {":
indent = line.split("fn rules(rule_code: Rule, path: &Path) -> Result<()> {")[0]
fp.write(f'{indent}#[test_case(Rule::{name}, Path::new("{code}.py"); "{code}")]')
fp.write("\n")

fp.write(line)
Expand Down
Loading

0 comments on commit ee947df

Please sign in to comment.