|
| 1 | +use ruff_python_ast::Expr; |
| 2 | + |
| 3 | +use ruff_diagnostics::{Diagnostic, Violation}; |
| 4 | +use ruff_macros::{derive_message_formats, violation}; |
| 5 | +use ruff_text_size::Ranged; |
| 6 | + |
| 7 | +use crate::checkers::ast::Checker; |
| 8 | + |
| 9 | +/// ## What it does |
| 10 | +/// Checks for named assignment expressions (e.g., `x := 0`) in `assert` |
| 11 | +/// statements. |
| 12 | +/// |
| 13 | +/// ## Why is this bad? |
| 14 | +/// Named assignment expressions (also known as "walrus operators") are used to |
| 15 | +/// assign a value to a variable as part of a larger expression. |
| 16 | +/// |
| 17 | +/// Named assignments are syntactically valid in `assert` statements. However, |
| 18 | +/// when the Python interpreter is run under the `-O` flag, `assert` statements |
| 19 | +/// are not executed. In this case, the named assignment will also be ignored, |
| 20 | +/// which may result in unexpected behavior (e.g., undefined variable |
| 21 | +/// accesses). |
| 22 | +/// |
| 23 | +/// ## Examples |
| 24 | +/// ```python |
| 25 | +/// assert (x := 0) == 0 |
| 26 | +/// ``` |
| 27 | +/// |
| 28 | +/// Use instead: |
| 29 | +/// ```python |
| 30 | +/// x = 0 |
| 31 | +/// assert x == 0 |
| 32 | +/// ``` |
| 33 | +/// |
| 34 | +/// ## References |
| 35 | +/// - [Python documentation: `-O`](https://docs.python.org/3/using/cmdline.html#cmdoption-O) |
| 36 | +#[violation] |
| 37 | +pub struct AssignmentInAssert; |
| 38 | + |
| 39 | +impl Violation for AssignmentInAssert { |
| 40 | + #[derive_message_formats] |
| 41 | + fn message(&self) -> String { |
| 42 | + format!("Avoid assignment expressions in `assert` statements") |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +/// RUF018 |
| 47 | +pub(crate) fn assignment_in_assert(checker: &mut Checker, value: &Expr) { |
| 48 | + if checker.semantic().current_statement().is_assert_stmt() { |
| 49 | + checker |
| 50 | + .diagnostics |
| 51 | + .push(Diagnostic::new(AssignmentInAssert, value.range())); |
| 52 | + } |
| 53 | +} |
0 commit comments