mirror of
https://github.com/astral-sh/ruff.git
synced 2025-09-27 04:19:18 +00:00
[syntax-errors] nonlocal
declaration at module level (#17559)
## Summary Part of #17412 Add a new compile-time syntax error for detecting `nonlocal` declarations at a module level. ## Test Plan - Added new inline tests for the syntax error - Updated existing tests for `nonlocal` statement parsing to be inside a function scope Co-authored-by: Brent Westbrook <36778786+ntBre@users.noreply.github.com>
This commit is contained in:
parent
538393d1f3
commit
cf59cee928
16 changed files with 363 additions and 131 deletions
|
@ -142,6 +142,22 @@ impl SemanticSyntaxChecker {
|
|||
AwaitOutsideAsyncFunctionKind::AsyncWith,
|
||||
);
|
||||
}
|
||||
Stmt::Nonlocal(ast::StmtNonlocal { range, .. }) => {
|
||||
// test_ok nonlocal_declaration_at_module_level
|
||||
// def _():
|
||||
// nonlocal x
|
||||
|
||||
// test_err nonlocal_declaration_at_module_level
|
||||
// nonlocal x
|
||||
// nonlocal x, y
|
||||
if ctx.in_module_scope() {
|
||||
Self::add_error(
|
||||
ctx,
|
||||
SemanticSyntaxErrorKind::NonlocalDeclarationAtModuleLevel,
|
||||
*range,
|
||||
);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
|
@ -933,6 +949,9 @@ impl Display for SemanticSyntaxError {
|
|||
SemanticSyntaxErrorKind::DuplicateParameter(name) => {
|
||||
write!(f, r#"Duplicate parameter "{name}""#)
|
||||
}
|
||||
SemanticSyntaxErrorKind::NonlocalDeclarationAtModuleLevel => {
|
||||
write!(f, "nonlocal declaration not allowed at module level")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1254,6 +1273,9 @@ pub enum SemanticSyntaxErrorKind {
|
|||
/// lambda x, x: ...
|
||||
/// ```
|
||||
DuplicateParameter(String),
|
||||
|
||||
/// Represents a nonlocal declaration at module level
|
||||
NonlocalDeclarationAtModuleLevel,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue