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

[flake8-builtins] Implement import, lambda, and module shadowing #12546

Merged
merged 3 commits into from
Jul 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ linter.flake8_bandit.hardcoded_tmp_directory = [
]
linter.flake8_bandit.check_typed_exception = false
linter.flake8_bugbear.extend_immutable_calls = []
linter.flake8_builtins.builtins_allowed_modules = []
linter.flake8_builtins.builtins_ignorelist = []
linter.flake8_comprehensions.allow_dict_calls_with_keyword_arguments = false
linter.flake8_copyright.notice_rgx = (?i)Copyright\s+((?:\(C\)|©)\s+)?\d{4}((-|,\s)\d{4})*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import some as sum
import float
from some import other as int
from some import input, exec
from directory import new as dir
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
lambda print, copyright: print
lambda x, float, y: x + y
lambda min, max: min
lambda id: id
lambda dir: dir
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use ruff_python_ast::Expr;

use crate::checkers::ast::Checker;
use crate::codes::Rule;
use crate::rules::{flake8_pie, pylint, refurb};
use crate::rules::{flake8_builtins, flake8_pie, pylint, refurb};

/// Run lint rules over all deferred lambdas in the [`SemanticModel`].
pub(crate) fn deferred_lambdas(checker: &mut Checker) {
Expand All @@ -24,6 +24,9 @@ pub(crate) fn deferred_lambdas(checker: &mut Checker) {
if checker.enabled(Rule::ReimplementedOperator) {
refurb::rules::reimplemented_operator(checker, &lambda.into());
}
if checker.enabled(Rule::BuiltinLambdaArgumentShadowing) {
flake8_builtins::rules::builtin_lambda_argument_shadowing(checker, lambda);
}
}
}
}
16 changes: 14 additions & 2 deletions crates/ruff_linter/src/checkers/ast/analyze/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -597,8 +597,11 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
if checker.enabled(Rule::NonAsciiImportName) {
pylint::rules::non_ascii_module_import(checker, alias);
}
// TODO(charlie): Remove when stabilizing A004.
if let Some(asname) = &alias.asname {
if checker.enabled(Rule::BuiltinVariableShadowing) {
if checker.settings.preview.is_disabled()
&& checker.enabled(Rule::BuiltinVariableShadowing)
{
flake8_builtins::rules::builtin_variable_shadowing(
checker,
asname,
Expand Down Expand Up @@ -739,6 +742,9 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
checker.diagnostics.push(diagnostic);
}
}
if checker.enabled(Rule::BuiltinImportShadowing) {
flake8_builtins::rules::builtin_import_shadowing(checker, alias);
}
}
}
Stmt::ImportFrom(
Expand Down Expand Up @@ -917,8 +923,11 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
));
}
} else {
// TODO(charlie): Remove when stabilizing A004.
if let Some(asname) = &alias.asname {
if checker.enabled(Rule::BuiltinVariableShadowing) {
if checker.settings.preview.is_disabled()
&& checker.enabled(Rule::BuiltinVariableShadowing)
{
flake8_builtins::rules::builtin_variable_shadowing(
checker,
asname,
Expand Down Expand Up @@ -1030,6 +1039,9 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
}
}
}
if checker.enabled(Rule::BuiltinImportShadowing) {
flake8_builtins::rules::builtin_import_shadowing(checker, alias);
}
}
if checker.enabled(Rule::ImportSelf) {
if let Some(diagnostic) = pylint::rules::import_from_self(
Expand Down
13 changes: 13 additions & 0 deletions crates/ruff_linter/src/checkers/filesystem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use ruff_python_trivia::CommentRanges;
use ruff_source_file::Locator;

use crate::registry::Rule;
use crate::rules::flake8_builtins::rules::builtin_module_shadowing;
use crate::rules::flake8_no_pep420::rules::implicit_namespace_package;
use crate::rules::pep8_naming::rules::invalid_module_name;
use crate::settings::LinterSettings;
Expand Down Expand Up @@ -41,5 +42,17 @@ pub(crate) fn check_file_path(
}
}

// flake8-builtins
if settings.rules.enabled(Rule::BuiltinModuleShadowing) {
if let Some(diagnostic) = builtin_module_shadowing(
path,
package,
&settings.flake8_builtins.builtins_allowed_modules,
settings.target_version,
) {
diagnostics.push(diagnostic);
}
}

diagnostics
}
4 changes: 4 additions & 0 deletions crates/ruff_linter/src/codes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,10 @@ pub fn code_to_rule(linter: Linter, code: &str) -> Option<(RuleGroup, Rule)> {
(Flake8Builtins, "001") => (RuleGroup::Stable, rules::flake8_builtins::rules::BuiltinVariableShadowing),
(Flake8Builtins, "002") => (RuleGroup::Stable, rules::flake8_builtins::rules::BuiltinArgumentShadowing),
(Flake8Builtins, "003") => (RuleGroup::Stable, rules::flake8_builtins::rules::BuiltinAttributeShadowing),
// TODO(charlie): When stabilizing, remove preview gating for A001's treatment of imports.
(Flake8Builtins, "004") => (RuleGroup::Preview, rules::flake8_builtins::rules::BuiltinImportShadowing),
(Flake8Builtins, "005") => (RuleGroup::Preview, rules::flake8_builtins::rules::BuiltinModuleShadowing),
(Flake8Builtins, "006") => (RuleGroup::Preview, rules::flake8_builtins::rules::BuiltinLambdaArgumentShadowing),

// flake8-bugbear
(Flake8Bugbear, "002") => (RuleGroup::Stable, rules::flake8_bugbear::rules::UnaryPrefixIncrementDecrement),
Expand Down
4 changes: 3 additions & 1 deletion crates/ruff_linter/src/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,9 @@ impl Rule {
| Rule::UTF8EncodingDeclaration => LintSource::Tokens,
Rule::IOError => LintSource::Io,
Rule::UnsortedImports | Rule::MissingRequiredImport => LintSource::Imports,
Rule::ImplicitNamespacePackage | Rule::InvalidModuleName => LintSource::Filesystem,
Rule::ImplicitNamespacePackage
| Rule::InvalidModuleName
| Rule::BuiltinModuleShadowing => LintSource::Filesystem,
Rule::IndentationWithInvalidMultiple
| Rule::IndentationWithInvalidMultipleComment
| Rule::MissingWhitespace
Expand Down
61 changes: 61 additions & 0 deletions crates/ruff_linter/src/rules/flake8_builtins/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,25 @@ mod tests {
#[test_case(Rule::BuiltinVariableShadowing, Path::new("A001.py"))]
#[test_case(Rule::BuiltinArgumentShadowing, Path::new("A002.py"))]
#[test_case(Rule::BuiltinAttributeShadowing, Path::new("A003.py"))]
#[test_case(Rule::BuiltinImportShadowing, Path::new("A004.py"))]
#[test_case(
Rule::BuiltinModuleShadowing,
Path::new("A005/modules/non_builtin/__init__.py")
)]
#[test_case(
Rule::BuiltinModuleShadowing,
Path::new("A005/modules/logging/__init__.py")
)]
#[test_case(
Rule::BuiltinModuleShadowing,
Path::new("A005/modules/string/__init__.py")
)]
#[test_case(
Rule::BuiltinModuleShadowing,
Path::new("A005/modules/package/bisect.py")
)]
#[test_case(Rule::BuiltinModuleShadowing, Path::new("A005/modules/package/xml.py"))]
#[test_case(Rule::BuiltinLambdaArgumentShadowing, Path::new("A006.py"))]
fn rules(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", rule_code.noqa_code(), path.to_string_lossy());
let diagnostics = test_path(
Expand All @@ -31,6 +50,8 @@ mod tests {
#[test_case(Rule::BuiltinVariableShadowing, Path::new("A001.py"))]
#[test_case(Rule::BuiltinArgumentShadowing, Path::new("A002.py"))]
#[test_case(Rule::BuiltinAttributeShadowing, Path::new("A003.py"))]
#[test_case(Rule::BuiltinImportShadowing, Path::new("A004.py"))]
#[test_case(Rule::BuiltinLambdaArgumentShadowing, Path::new("A006.py"))]
fn builtins_ignorelist(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!(
"{}_{}_builtins_ignorelist",
Expand All @@ -43,6 +64,46 @@ mod tests {
&LinterSettings {
flake8_builtins: super::settings::Settings {
builtins_ignorelist: vec!["id".to_string(), "dir".to_string()],
..Default::default()
},
..LinterSettings::for_rules(vec![rule_code])
},
)?;

assert_messages!(snapshot, diagnostics);
Ok(())
}

#[test_case(
Rule::BuiltinModuleShadowing,
Path::new("A005/modules/non_builtin/__init__.py")
)]
#[test_case(
Rule::BuiltinModuleShadowing,
Path::new("A005/modules/logging/__init__.py")
)]
#[test_case(
Rule::BuiltinModuleShadowing,
Path::new("A005/modules/string/__init__.py")
)]
#[test_case(
Rule::BuiltinModuleShadowing,
Path::new("A005/modules/package/bisect.py")
)]
#[test_case(Rule::BuiltinModuleShadowing, Path::new("A005/modules/package/xml.py"))]
fn builtins_allowed_modules(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!(
"{}_{}_builtins_allowed_modules",
rule_code.noqa_code(),
path.to_string_lossy()
);

let diagnostics = test_path(
Path::new("flake8_builtins").join(path).as_path(),
&LinterSettings {
flake8_builtins: super::settings::Settings {
builtins_allowed_modules: vec!["xml".to_string(), "logging".to_string()],
..Default::default()
},
..LinterSettings::for_rules(vec![rule_code])
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use ruff_python_ast::Parameter;

use ruff_diagnostics::Diagnostic;
use ruff_diagnostics::Violation;
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::Parameter;
use ruff_python_semantic::analyze::visibility::{is_overload, is_override};
use ruff_text_size::Ranged;

Expand All @@ -11,7 +10,7 @@ use crate::checkers::ast::Checker;
use super::super::helpers::shadows_builtin;

/// ## What it does
/// Checks for any function arguments that use the same name as a builtin.
/// Checks for function arguments that use the same names as builtins.
///
/// ## Why is this bad?
/// Reusing a builtin name for the name of an argument increases the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ use crate::checkers::ast::Checker;
use crate::rules::flake8_builtins::helpers::shadows_builtin;

/// ## What it does
/// Checks for any class attributes or methods that use the same name as a
/// builtin.
/// Checks for class attributes and methods that use the same names as
/// Python builtins.
///
/// ## Why is this bad?
/// Reusing a builtin name for the name of an attribute increases the
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::Alias;

use crate::checkers::ast::Checker;
use crate::rules::flake8_builtins::helpers::shadows_builtin;

/// ## What it does
/// Checks for imports that use the same names as builtins.
///
/// ## Why is this bad?
/// Reusing a builtin for the name of an import 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
/// [`lint.flake8-builtins.builtins-ignorelist`] configuration option.
///
/// ## Options
/// - `lint.flake8-builtins.builtins-ignorelist`
#[violation]
pub struct BuiltinImportShadowing {
name: String,
}

impl Violation for BuiltinImportShadowing {
#[derive_message_formats]
fn message(&self) -> String {
let BuiltinImportShadowing { name } = self;
format!("Import `{name}` is shadowing a Python builtin")
}
}

/// A004
pub(crate) fn builtin_import_shadowing(checker: &mut Checker, alias: &Alias) {
let name = alias.asname.as_ref().unwrap_or(&alias.name);
if shadows_builtin(
name.as_str(),
&checker.settings.flake8_builtins.builtins_ignorelist,
checker.source_type,
) {
checker.diagnostics.push(Diagnostic::new(
BuiltinImportShadowing {
name: name.to_string(),
},
name.range,
));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::ExprLambda;
use ruff_text_size::Ranged;

use crate::checkers::ast::Checker;
use crate::rules::flake8_builtins::helpers::shadows_builtin;

/// ## What it does
/// Checks for lambda arguments that use the same names as Python builtins.
///
/// ## Why is this bad?
/// Reusing a builtin name for the name of a lambda argument 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
/// [`lint.flake8-builtins.builtins-ignorelist`] configuration option.
///
/// ## Options
/// - `lint.flake8-builtins.builtins-ignorelist`
#[violation]
pub struct BuiltinLambdaArgumentShadowing {
name: String,
}

impl Violation for BuiltinLambdaArgumentShadowing {
#[derive_message_formats]
fn message(&self) -> String {
let BuiltinLambdaArgumentShadowing { name } = self;
format!("Lambda argument `{name}` is shadowing a Python builtin")
}
}

/// A006
pub(crate) fn builtin_lambda_argument_shadowing(checker: &mut Checker, lambda: &ExprLambda) {
let Some(parameters) = lambda.parameters.as_ref() else {
return;
};
for param in parameters.iter_non_variadic_params() {
let name = &param.parameter.name;
if shadows_builtin(
name.as_ref(),
&checker.settings.flake8_builtins.builtins_ignorelist,
checker.source_type,
) {
checker.diagnostics.push(Diagnostic::new(
BuiltinLambdaArgumentShadowing {
name: name.to_string(),
},
name.range(),
));
}
}
}
Loading
Loading