Skip to content

Commit

Permalink
[flake8_builtins] implement builtin-[import,lambda-argument,module]…
Browse files Browse the repository at this point in the history
…-shadowing
  • Loading branch information
alex-700 committed Jul 28, 2024
1 parent f37b39d commit 698e7b5
Show file tree
Hide file tree
Showing 38 changed files with 582 additions and 15 deletions.
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
Empty file.
Empty file.
Empty file.
Empty file.
Empty file.
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: remove once A004 is stable
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: remove once A004 is stable
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
}
3 changes: 3 additions & 0 deletions crates/ruff_linter/src/codes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,9 @@ 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),
(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
@@ -0,0 +1,49 @@
use crate::checkers::ast::Checker;
use crate::rules::flake8_builtins::helpers::shadows_builtin;
use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::Alias;

/// ## What it does
/// Checks for any import statement that use the same name as a builtin.
///
/// ## Why is this bad?
/// Reusing a builtin name 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 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,55 @@
use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::ExprLambda;

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

/// ## What it does
/// Checks for any lambda argument that use the same name as a builtin.
///
/// ## 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 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,
));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
use std::path::Path;

use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_stdlib::path::is_module_file;
use ruff_python_stdlib::sys::is_known_standard_library;
use ruff_text_size::TextRange;

use crate::settings::types::PythonVersion;

/// ## What it does
/// Checks for any module that use the same name as a builtin module.
///
/// ## Why is this bad?
/// Reusing a builtin module name for the name of a module 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.
///
/// Builtin modules can be marked as exceptions to this rule via the
/// [`lint.flake8-builtins.builtins-allowed-modules`] configuration option.
///
/// ## Options
/// - `lint.flake8-builtins.builtins-allowed-modules`
#[violation]
pub struct BuiltinModuleShadowing {
name: String,
}

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

/// A005
pub(crate) fn builtin_module_shadowing(
path: &Path,
package: Option<&Path>,
allowed_modules: &[String],
target_version: PythonVersion,
) -> Option<Diagnostic> {
if !path
.extension()
.is_some_and(|ext| ext == "py" || ext == "pyi")
{
return None;
}

if let Some(package) = package {
let module_name = if is_module_file(path) {
package.file_name()
} else {
path.file_stem()
}
.unwrap()
.to_string_lossy();

if is_known_standard_library(target_version.minor(), &module_name)
&& allowed_modules
.iter()
.all(|allowed_module| allowed_module != &module_name)
{
return Some(Diagnostic::new(
BuiltinModuleShadowing {
name: module_name.to_string(),
},
TextRange::default(),
));
}
}
None
}
Loading

0 comments on commit 698e7b5

Please sign in to comment.