Use `semantic().global()` to power `global-statement` rule (#5795)

## Summary

The intent of this rule is to always flag the `global` declaration, not
the usage. The current implementation does the wrong thing if a global
is assigned multiple times. Using `semantic().global()` is also more
efficient.
This commit is contained in:
Charlie Marsh 2023-07-16 00:34:42 -04:00 committed by GitHub
parent b01a4d8446
commit c7ff743d30
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 17 additions and 20 deletions

View File

@ -80,3 +80,8 @@ def multiple_assignment():
global CONSTANT # [global-statement] global CONSTANT # [global-statement]
CONSTANT = 1 CONSTANT = 1
CONSTANT = 2 CONSTANT = 2
def no_assignment():
"""Shouldn't warn"""
global CONSTANT

View File

@ -1,5 +1,3 @@
use rustpython_parser::ast::Ranged;
use ruff_diagnostics::{Diagnostic, Violation}; use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
@ -55,21 +53,14 @@ impl Violation for GlobalStatement {
/// PLW0603 /// PLW0603
pub(crate) fn global_statement(checker: &mut Checker, name: &str) { pub(crate) fn global_statement(checker: &mut Checker, name: &str) {
let scope = checker.semantic().scope(); if let Some(range) = checker.semantic().global(name) {
if let Some(binding_id) = scope.get(name) {
let binding = checker.semantic().binding(binding_id);
if binding.is_global() {
if let Some(source) = binding.source {
let source = checker.semantic().stmts[source];
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
GlobalStatement { GlobalStatement {
name: name.to_string(), name: name.to_string(),
}, },
// Match Pylint's behavior by reporting on the `global` statement`, rather // Match Pylint's behavior by reporting on the `global` statement`, rather
// than the variable usage. // than the variable usage.
source.range(), range,
)); ));
} }
}
}
} }

View File

@ -89,12 +89,13 @@ global_statement.py:80:5: PLW0603 Using the global statement to update `CONSTANT
82 | CONSTANT = 2 82 | CONSTANT = 2
| |
global_statement.py:81:5: PLW0603 Using the global statement to update `CONSTANT` is discouraged global_statement.py:80:5: PLW0603 Using the global statement to update `CONSTANT` is discouraged
| |
78 | def multiple_assignment():
79 | """Should warn on every assignment.""" 79 | """Should warn on every assignment."""
80 | global CONSTANT # [global-statement] 80 | global CONSTANT # [global-statement]
| ^^^^^^^^^^^^^^^ PLW0603
81 | CONSTANT = 1 81 | CONSTANT = 1
| ^^^^^^^^^^^^ PLW0603
82 | CONSTANT = 2 82 | CONSTANT = 2
| |