Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New rule category XP, implement not-array-agnostic-numpy (XP001) #8910

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions crates/ruff_linter/src/checkers/ast/analyze/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use crate::rules::{
flake8_logging_format, flake8_pie, flake8_print, flake8_pyi, flake8_pytest_style, flake8_self,
flake8_simplify, flake8_tidy_imports, flake8_trio, flake8_use_pathlib, flynt, numpy,
pandas_vet, pep8_naming, pycodestyle, pyflakes, pygrep_hooks, pylint, pyupgrade, refurb, ruff,
xp,
};
use crate::settings::types::PythonVersion;

Expand Down Expand Up @@ -164,6 +165,9 @@ pub(crate) fn expression(expr: &Expr, checker: &mut Checker) {
if checker.enabled(Rule::CollectionsNamedTuple) {
flake8_pyi::rules::collections_named_tuple(checker, expr);
}
if checker.enabled(Rule::NotArrayAgnosticNumPy) {
xp::rules::not_array_agnostic_numpy(checker, expr);
}

// Ex) List[...]
if checker.any_enabled(&[
Expand Down Expand Up @@ -338,6 +342,9 @@ pub(crate) fn expression(expr: &Expr, checker: &mut Checker) {
if checker.enabled(Rule::UndocumentedWarn) {
flake8_logging::rules::undocumented_warn(checker, expr);
}
if checker.enabled(Rule::NotArrayAgnosticNumPy) {
xp::rules::not_array_agnostic_numpy(checker, expr);
}
pandas_vet::rules::attr(checker, attribute);
}
Expr::Call(
Expand Down
3 changes: 3 additions & 0 deletions crates/ruff_linter/src/codes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -967,6 +967,9 @@ pub fn code_to_rule(linter: Linter, code: &str) -> Option<(RuleGroup, Rule)> {
(Flake8Logging, "007") => (RuleGroup::Preview, rules::flake8_logging::rules::ExceptionWithoutExcInfo),
(Flake8Logging, "009") => (RuleGroup::Preview, rules::flake8_logging::rules::UndocumentedWarn),

// array-agnosticism (xp)
(XP, "001") => (RuleGroup::Preview, rules::xp::rules::NotArrayAgnosticNumPy),

_ => return None,
})
}
3 changes: 3 additions & 0 deletions crates/ruff_linter/src/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,9 @@ pub enum Linter {
/// Ruff-specific rules
#[prefix = "RUF"]
Ruff,
/// [Array-agnosticism](https://data-apis.org/array-api/latest/)
lucascolley marked this conversation as resolved.
Show resolved Hide resolved
#[prefix = "XP"]
XP,
}

pub trait RuleNamespace: Sized {
Expand Down
1 change: 1 addition & 0 deletions crates/ruff_linter/src/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,4 @@ pub mod pyupgrade;
pub mod refurb;
pub mod ruff;
pub mod tryceratops;
pub mod xp;
26 changes: 26 additions & 0 deletions crates/ruff_linter/src/rules/xp/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
//! NumPy-specific rules.
pub(crate) mod rules;

#[cfg(test)]
mod tests {
use std::convert::AsRef;
use std::path::Path;

use anyhow::Result;
use test_case::test_case;

use crate::registry::Rule;
use crate::test::test_path;
use crate::{assert_messages, settings};

#[test_case(Rule::NotArrayAgnosticNumPy, Path::new("XP001.py"))]
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("xp").join(path).as_path(),
&settings::LinterSettings::for_rule(rule_code),
)?;
assert_messages!(snapshot, diagnostics);
Ok(())
}
}
3 changes: 3 additions & 0 deletions crates/ruff_linter/src/rules/xp/rules/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pub(crate) use not_array_agnostic_numpy::*;

mod not_array_agnostic_numpy;
119 changes: 119 additions & 0 deletions crates/ruff_linter/src/rules/xp/rules/not_array_agnostic_numpy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
/// use ...
use ruff_diagnostics::{Diagnostic, Edit, Fix, FixAvailability, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::Expr;
use ruff_text_size::Ranged;

use crate::checkers::ast::Checker;
use crate::importer::ImportRequest;

/// ## What it does
///

#[violation]
pub struct NotArrayAgnosticNumPy {
existing: String,
migration_guide: Option<String>,
code_action: Option<String>,
}

impl Violation for NotArrayAgnosticNumPy {
const FIX_AVAILABILITY: FixAvailability = FixAvailability::Sometimes;

#[derive_message_formats]
fn message(&self) -> String {
let NotArrayAgnosticNumPy {
existing,
migration_guide,
code_action: _,
} = self;
match migration_guide {
Some(migration_guide) => {
format!("`{existing}` is not in the array API standard. {migration_guide}",)
}
None => format!("`{existing}` is not in the array API standard."),
}
}

fn fix_title(&self) -> Option<String> {
let NotArrayAgnosticNumPy {
existing: _,
migration_guide: _,
code_action,
} = self;
code_action.clone()
}
}

#[derive(Debug)]
struct Replacement<'a> {
existing: &'a str,
details: Details<'a>,
}

#[derive(Debug)]
enum Details<'a> {
/// There is a direct replacement in the array API standard.
AutoImport { path: &'a str, name: &'a str },
/// There is no direct replacement in the standard.
Manual { guideline: Option<&'a str> },
}

impl Details<'_> {
fn guideline(&self) -> Option<String> {
match self {
Details::AutoImport { path, name } => Some(format!("Use `{path}.{name}` instead.")),
Details::Manual { guideline } => guideline.map(ToString::to_string),
}
}

fn code_action(&self) -> Option<String> {
match self {
Details::AutoImport { path, name } => Some(format!("Replace with `{path}.{name}`")),
Details::Manual { guideline: _ } => None,
}
}
}

///XP001
pub(crate) fn not_array_agnostic_numpy(checker: &mut Checker, expr: &Expr) {
let maybe_replacement = checker
.semantic()
.resolve_call_path(expr)
.and_then(|call_path| match call_path.as_slice() {
["numpy", "arccos"] => Some(Replacement {
existing: "arccos",
details: Details::AutoImport {
path: "numpy",
name: "acos",
},
}),
_ => None,
});

if let Some(replacement) = maybe_replacement {
let mut diagnostic = Diagnostic::new(
NotArrayAgnosticNumPy {
existing: replacement.existing.to_string(),
migration_guide: replacement.details.guideline(),
code_action: replacement.details.code_action(),
},
expr.range(),
);
match replacement.details {
Details::AutoImport { path, name } => {
diagnostic.try_set_fix(|| {
let (import_edit, binding) = checker.importer().get_or_import_symbol(
&ImportRequest::import_from(path, name),
expr.start(),
checker.semantic(),
)?;
let replacement_edit = Edit::range_replacement(binding, expr.range());
Ok(Fix::unsafe_edits(import_edit, [replacement_edit]))
});
}
Details::Manual { guideline: _ } => {}
};
checker.diagnostics.push(diagnostic);
}
}
4 changes: 4 additions & 0 deletions ruff.schema.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading