Skip to content
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
3 changes: 0 additions & 3 deletions crates/ruff_linter/src/checkers/ast/analyze/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -337,9 +337,6 @@ pub(crate) fn expression(expr: &Expr, checker: &Checker) {
if checker.enabled(Rule::UndocumentedWarn) {
flake8_logging::rules::undocumented_warn(checker, expr);
}
if checker.enabled(Rule::LoadBeforeGlobalDeclaration) {
pylint::rules::load_before_global_declaration(checker, id, expr);
}
}
Expr::Attribute(attribute) => {
if attribute.ctx == ExprContext::Load {
Expand Down
20 changes: 20 additions & 0 deletions crates/ruff_linter/src/checkers/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ use crate::noqa::NoqaMapping;
use crate::package::PackageRoot;
use crate::registry::Rule;
use crate::rules::pyflakes::rules::LateFutureImport;
use crate::rules::pylint::rules::LoadBeforeGlobalDeclaration;
use crate::rules::{flake8_pyi, flake8_type_checking, pyflakes, pyupgrade};
use crate::settings::{flags, LinterSettings};
use crate::{docstrings, noqa, Locator};
Expand Down Expand Up @@ -540,13 +541,32 @@ impl SemanticSyntaxContext for Checker<'_> {
self.target_version
}

fn global(&self, name: &str) -> Option<TextRange> {
self.semantic.global(name)
}

fn report_semantic_error(&self, error: SemanticSyntaxError) {
match error.kind {
SemanticSyntaxErrorKind::LateFutureImport => {
if self.settings.rules.enabled(Rule::LateFutureImport) {
self.report_diagnostic(Diagnostic::new(LateFutureImport, error.range));
}
}
SemanticSyntaxErrorKind::LoadBeforeGlobalDeclaration { name, start } => {
if self
.settings
.rules
.enabled(Rule::LoadBeforeGlobalDeclaration)
{
self.report_diagnostic(Diagnostic::new(
LoadBeforeGlobalDeclaration {
name,
row: self.compute_source_row(start),
},
error.range,
));
}
}
SemanticSyntaxErrorKind::ReboundComprehensionVariable
| SemanticSyntaxErrorKind::DuplicateTypeParameter
| SemanticSyntaxErrorKind::MultipleCaseAssignment(_)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
use ruff_python_ast::Expr;

use ruff_diagnostics::{Diagnostic, Violation};
use ruff_diagnostics::Violation;
use ruff_macros::{derive_message_formats, ViolationMetadata};
use ruff_source_file::SourceRow;
use ruff_text_size::Ranged;

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

/// ## What it does
/// Checks for uses of names that are declared as `global` prior to the
Expand Down Expand Up @@ -42,8 +37,8 @@ use crate::checkers::ast::Checker;
/// - [Python documentation: The `global` statement](https://docs.python.org/3/reference/simple_stmts.html#the-global-statement)
#[derive(ViolationMetadata)]
pub(crate) struct LoadBeforeGlobalDeclaration {
name: String,
row: SourceRow,
pub(crate) name: String,
pub(crate) row: SourceRow,
}

impl Violation for LoadBeforeGlobalDeclaration {
Expand All @@ -53,18 +48,3 @@ impl Violation for LoadBeforeGlobalDeclaration {
format!("Name `{name}` is used prior to global declaration on {row}")
}
}

/// PLE0118
pub(crate) fn load_before_global_declaration(checker: &Checker, name: &str, expr: &Expr) {
if let Some(stmt) = checker.semantic().global(name) {
if expr.start() < stmt.start() {
checker.report_diagnostic(Diagnostic::new(
LoadBeforeGlobalDeclaration {
name: name.to_string(),
row: checker.compute_source_row(stmt.start()),
},
expr.range(),
));
}
}
}
36 changes: 35 additions & 1 deletion crates/ruff_python_parser/src/semantic_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use ruff_python_ast::{
Expr, ExprContext, IrrefutablePatternKind, Pattern, PythonVersion, Stmt, StmtExpr,
StmtImportFrom,
};
use ruff_text_size::{Ranged, TextRange};
use ruff_text_size::{Ranged, TextRange, TextSize};
use rustc_hash::FxHashSet;

#[derive(Debug)]
Expand Down Expand Up @@ -397,6 +397,21 @@ impl SemanticSyntaxChecker {
_ => {}
};
}

// PLE0118
if let Some(stmt) = ctx.global(id) {
let start = stmt.start();
if expr.start() < start {
Self::add_error(
ctx,
SemanticSyntaxErrorKind::LoadBeforeGlobalDeclaration {
name: id.to_string(),
start,
},
expr.range(),
);
}
}
}
Expr::Yield(ast::ExprYield {
value: Some(value), ..
Expand Down Expand Up @@ -499,6 +514,9 @@ impl Display for SemanticSyntaxError {
write!(f, "cannot delete `__debug__` on Python {python_version} (syntax was removed in 3.9)")
}
},
SemanticSyntaxErrorKind::LoadBeforeGlobalDeclaration { name, start: _ } => {
write!(f, "name `{name}` is used prior to global declaration")
}
SemanticSyntaxErrorKind::InvalidStarExpression => {
f.write_str("can't use starred expression here")
}
Expand Down Expand Up @@ -616,6 +634,19 @@ pub enum SemanticSyntaxErrorKind {
/// [BPO 45000]: https://github.com/python/cpython/issues/89163
WriteToDebug(WriteToDebugKind),

/// Represents the use of a `global` variable before its `global` declaration.
///
/// ## Examples
///
/// ```python
/// counter = 1
/// def increment():
/// print(f"Adding 1 to {counter}")
/// global counter
/// counter += 1
/// ```
LoadBeforeGlobalDeclaration { name: String, start: TextSize },

/// Represents the use of a starred expression in an invalid location, such as a `return` or
/// `yield` statement.
///
Expand Down Expand Up @@ -758,6 +789,9 @@ pub trait SemanticSyntaxContext {
/// The target Python version for detecting backwards-incompatible syntax changes.
fn python_version(&self) -> PythonVersion;

/// Return the [`TextRange`] at which a name is declared as `global` in the current scope.
fn global(&self, name: &str) -> Option<TextRange>;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Red Knot doesn't support globals yet, so it's hard to say if this will be supported in Red Knot and how ;)

It does have the downside that this check will not work in the test context. And it also means that it requires one extra traversal of the body to get the globals first but I don't see how we can avoid that.

But we (you) can worry about that later ;)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Haha sounds good :)


fn report_semantic_error(&self, error: SemanticSyntaxError);
}

Expand Down
4 changes: 4 additions & 0 deletions crates/ruff_python_parser/tests/fixtures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -488,4 +488,8 @@ impl SemanticSyntaxContext for TestContext {
fn report_semantic_error(&self, error: SemanticSyntaxError) {
self.diagnostics.borrow_mut().push(error);
}

fn global(&self, _name: &str) -> Option<TextRange> {
None
}
}
Loading