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

[pylint] Implement potential-index-error (PLE0643) #9545

Merged
merged 6 commits into from
Jan 21, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
@@ -0,0 +1,9 @@
print([1, 2, 3][3]) # PLE0643
print([1, 2, 3][-4]) # PLE0643
print([1, 2, 3][999999999999999999999999999999999999999999]) # PLE0643
print([1, 2, 3][-999999999999999999999999999999999999999999]) # PLE0643

print([1, 2, 3][2]) # OK
print([1, 2, 3][0]) # OK
print([1, 2, 3][-3]) # OK
print([1, 2, 3][3:]) # OK
3 changes: 3 additions & 0 deletions crates/ruff_linter/src/checkers/ast/analyze/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,9 @@ pub(crate) fn expression(expr: &Expr, checker: &mut Checker) {
if checker.enabled(Rule::SliceCopy) {
refurb::rules::slice_copy(checker, subscript);
}
if checker.enabled(Rule::PotentialIndexError) {
pylint::rules::potential_index_error(checker, value, slice);
}

pandas_vet::rules::subscript(checker, value, expr);
}
Expand Down
1 change: 1 addition & 0 deletions crates/ruff_linter/src/codes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,7 @@ pub fn code_to_rule(linter: Linter, code: &str) -> Option<(RuleGroup, Rule)> {
(Pylint, "E0307") => (RuleGroup::Stable, rules::pylint::rules::InvalidStrReturnType),
(Pylint, "E0604") => (RuleGroup::Stable, rules::pylint::rules::InvalidAllObject),
(Pylint, "E0605") => (RuleGroup::Stable, rules::pylint::rules::InvalidAllFormat),
(Pylint, "E0643") => (RuleGroup::Preview, rules::pylint::rules::PotentialIndexError),
(Pylint, "E0704") => (RuleGroup::Preview, rules::pylint::rules::MisplacedBareRaise),
(Pylint, "E1132") => (RuleGroup::Preview, rules::pylint::rules::RepeatedKeywordArgument),
(Pylint, "E1142") => (RuleGroup::Stable, rules::pylint::rules::AwaitOutsideAsync),
Expand Down
1 change: 1 addition & 0 deletions crates/ruff_linter/src/rules/pylint/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ mod tests {
#[test_case(Rule::NoClassmethodDecorator, Path::new("no_method_decorator.py"))]
#[test_case(Rule::UnnecessaryDunderCall, Path::new("unnecessary_dunder_call.py"))]
#[test_case(Rule::NoStaticmethodDecorator, Path::new("no_method_decorator.py"))]
#[test_case(Rule::PotentialIndexError, Path::new("potential_index_error.py"))]
#[test_case(Rule::SuperWithoutBrackets, Path::new("super_without_brackets.py"))]
#[test_case(
Rule::UnnecessaryDictIndexLookup,
Expand Down
2 changes: 2 additions & 0 deletions crates/ruff_linter/src/rules/pylint/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ pub(crate) use no_self_use::*;
pub(crate) use non_ascii_module_import::*;
pub(crate) use non_ascii_name::*;
pub(crate) use nonlocal_without_binding::*;
pub(crate) use potential_index_error::*;
pub(crate) use property_with_parameters::*;
pub(crate) use redefined_argument_from_local::*;
pub(crate) use redefined_loop_name::*;
Expand Down Expand Up @@ -124,6 +125,7 @@ mod no_self_use;
mod non_ascii_module_import;
mod non_ascii_name;
mod nonlocal_without_binding;
mod potential_index_error;
mod property_with_parameters;
mod redefined_argument_from_local;
mod redefined_loop_name;
Expand Down
80 changes: 80 additions & 0 deletions crates/ruff_linter/src/rules/pylint/rules/potential_index_error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
use std::str::FromStr;

use ruff_python_ast::{self as ast, Expr};

use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};

use crate::checkers::ast::Checker;

/// ## What it does
/// Checks for potential hard-coded IndexErrors, which occurs when accessing
/// a list or tuple with an index that is known to be out of bounds.
///
/// ## Why is this bad?
/// This will cause a runtime error.
///
/// ## Example
/// ```python
/// print([1, 2, 3][123])
/// ```
///
#[violation]
pub struct PotentialIndexError;

impl Violation for PotentialIndexError {
#[derive_message_formats]
fn message(&self) -> String {
format!("Potential IndexError")
}
}

/// PLE0643
pub(crate) fn potential_index_error(checker: &mut Checker, value: &Expr, slice: &Expr) {
let length = match value {
Expr::Tuple(ast::ExprTuple { elts, .. }) | Expr::List(ast::ExprList { elts, .. }) => {
match i64::try_from(elts.len()) {
Ok(length) => length,
Err(_) => return,
}
}
_ => {
return;
}
};

let (number_value, range) = match slice {
Expr::NumberLiteral(ast::ExprNumberLiteral {
value: ast::Number::Int(number_value),
range,
}) => (number_value.to_owned(), *range),
Expr::UnaryOp(ast::ExprUnaryOp {
op: ast::UnaryOp::USub,
operand,
range,
}) => match operand.as_ref() {
Expr::NumberLiteral(ast::ExprNumberLiteral {
value: ast::Number::Int(number_value),
..
}) => (
ast::Int::from_str(&format!("-{number_value}")).unwrap(),
*range,
),
_ => return,
},
_ => return,
};

let emit = if let Some(number) = number_value.as_i64() {
number >= length || number < -length
} else {
// this should be impossible
true
};

if emit {
checker
.diagnostics
.push(Diagnostic::new(PotentialIndexError, range));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
---
source: crates/ruff_linter/src/rules/pylint/mod.rs
---
potential_index_error.py:1:17: PLE0643 Potential IndexError
|
1 | print([1, 2, 3][3]) # PLE0643
| ^ PLE0643
2 | print([1, 2, 3][-4]) # PLE0643
3 | print([1, 2, 3][999999999999999999999999999999999999999999]) # PLE0643
|

potential_index_error.py:2:17: PLE0643 Potential IndexError
|
1 | print([1, 2, 3][3]) # PLE0643
2 | print([1, 2, 3][-4]) # PLE0643
| ^^ PLE0643
3 | print([1, 2, 3][999999999999999999999999999999999999999999]) # PLE0643
4 | print([1, 2, 3][-999999999999999999999999999999999999999999]) # PLE0643
|

potential_index_error.py:3:17: PLE0643 Potential IndexError
|
1 | print([1, 2, 3][3]) # PLE0643
2 | print([1, 2, 3][-4]) # PLE0643
3 | print([1, 2, 3][999999999999999999999999999999999999999999]) # PLE0643
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ PLE0643
4 | print([1, 2, 3][-999999999999999999999999999999999999999999]) # PLE0643
|

potential_index_error.py:4:17: PLE0643 Potential IndexError
|
2 | print([1, 2, 3][-4]) # PLE0643
3 | print([1, 2, 3][999999999999999999999999999999999999999999]) # PLE0643
4 | print([1, 2, 3][-999999999999999999999999999999999999999999]) # PLE0643
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ PLE0643
5 |
6 | print([1, 2, 3][2]) # OK
|


2 changes: 2 additions & 0 deletions ruff.schema.json

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

Loading