Rename `Arguments` to `Parameters` in the AST (#6253)

## Summary

This PR renames a few AST nodes for clarity:

- `Arguments` is now `Parameters`
- `Arg` is now `Parameter`
- `ArgWithDefault` is now `ParameterWithDefault`

For now, the attribute names that reference `Parameters` directly are
changed (e.g., on `StmtFunctionDef`), but the attributes on `Parameters`
itself are not (e.g., `vararg`). We may revisit that decision in the
future.

For context, the AST node formerly known as `Arguments` is used in
function definitions. Formally (outside of the Python context),
"arguments" typically refers to "the values passed to a function", while
"parameters" typically refers to "the variables used in a function
definition". E.g., if you Google "arguments vs parameters", you'll get
some explanation like:

> A parameter is a variable in a function definition. It is a
placeholder and hence does not have a concrete value. An argument is a
value passed during function invocation.

We're thus deviating from Python's nomenclature in favor of a scheme
that we find to be more precise.
This commit is contained in:
Charlie Marsh 2023-08-01 13:53:28 -04:00 committed by GitHub
parent a82eb9544c
commit adc8bb7821
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
102 changed files with 2585 additions and 2529 deletions

View File

@ -1256,7 +1256,7 @@ pub(crate) fn expression(expr: &Expr, checker: &mut Checker) {
} }
Expr::Lambda( Expr::Lambda(
lambda @ ast::ExprLambda { lambda @ ast::ExprLambda {
args: _, parameters: _,
body: _, body: _,
range: _, range: _,
}, },

View File

@ -1,5 +1,3 @@
pub(super) use argument::argument;
pub(super) use arguments::arguments;
pub(super) use bindings::bindings; pub(super) use bindings::bindings;
pub(super) use comprehension::comprehension; pub(super) use comprehension::comprehension;
pub(super) use deferred_for_loops::deferred_for_loops; pub(super) use deferred_for_loops::deferred_for_loops;
@ -8,12 +6,12 @@ pub(super) use definitions::definitions;
pub(super) use except_handler::except_handler; pub(super) use except_handler::except_handler;
pub(super) use expression::expression; pub(super) use expression::expression;
pub(super) use module::module; pub(super) use module::module;
pub(super) use parameter::parameter;
pub(super) use parameters::parameters;
pub(super) use statement::statement; pub(super) use statement::statement;
pub(super) use suite::suite; pub(super) use suite::suite;
pub(super) use unresolved_references::unresolved_references; pub(super) use unresolved_references::unresolved_references;
mod argument;
mod arguments;
mod bindings; mod bindings;
mod comprehension; mod comprehension;
mod deferred_for_loops; mod deferred_for_loops;
@ -22,6 +20,8 @@ mod definitions;
mod except_handler; mod except_handler;
mod expression; mod expression;
mod module; mod module;
mod parameter;
mod parameters;
mod statement; mod statement;
mod suite; mod suite;
mod unresolved_references; mod unresolved_references;

View File

@ -1,27 +1,28 @@
use ruff_python_ast::{Arg, Ranged}; use ruff_python_ast::{Parameter, Ranged};
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::codes::Rule; use crate::codes::Rule;
use crate::rules::{flake8_builtins, pep8_naming, pycodestyle}; use crate::rules::{flake8_builtins, pep8_naming, pycodestyle};
/// Run lint rules over an [`Arg`] syntax node. /// Run lint rules over a [`Parameter`] syntax node.
pub(crate) fn argument(arg: &Arg, checker: &mut Checker) { pub(crate) fn parameter(parameter: &Parameter, checker: &mut Checker) {
if checker.enabled(Rule::AmbiguousVariableName) { if checker.enabled(Rule::AmbiguousVariableName) {
if let Some(diagnostic) = pycodestyle::rules::ambiguous_variable_name(&arg.arg, arg.range()) if let Some(diagnostic) =
pycodestyle::rules::ambiguous_variable_name(&parameter.arg, parameter.range())
{ {
checker.diagnostics.push(diagnostic); checker.diagnostics.push(diagnostic);
} }
} }
if checker.enabled(Rule::InvalidArgumentName) { if checker.enabled(Rule::InvalidArgumentName) {
if let Some(diagnostic) = pep8_naming::rules::invalid_argument_name( if let Some(diagnostic) = pep8_naming::rules::invalid_argument_name(
&arg.arg, &parameter.arg,
arg, parameter,
&checker.settings.pep8_naming.ignore_names, &checker.settings.pep8_naming.ignore_names,
) { ) {
checker.diagnostics.push(diagnostic); checker.diagnostics.push(diagnostic);
} }
} }
if checker.enabled(Rule::BuiltinArgumentShadowing) { if checker.enabled(Rule::BuiltinArgumentShadowing) {
flake8_builtins::rules::builtin_argument_shadowing(checker, arg); flake8_builtins::rules::builtin_argument_shadowing(checker, parameter);
} }
} }

View File

@ -1,26 +1,26 @@
use ruff_python_ast::Arguments; use ruff_python_ast::Parameters;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::codes::Rule; use crate::codes::Rule;
use crate::rules::{flake8_bugbear, flake8_pyi, ruff}; use crate::rules::{flake8_bugbear, flake8_pyi, ruff};
/// Run lint rules over a [`Arguments`] syntax node. /// Run lint rules over a [`Parameters`] syntax node.
pub(crate) fn arguments(arguments: &Arguments, checker: &mut Checker) { pub(crate) fn parameters(parameters: &Parameters, checker: &mut Checker) {
if checker.enabled(Rule::MutableArgumentDefault) { if checker.enabled(Rule::MutableArgumentDefault) {
flake8_bugbear::rules::mutable_argument_default(checker, arguments); flake8_bugbear::rules::mutable_argument_default(checker, parameters);
} }
if checker.enabled(Rule::FunctionCallInDefaultArgument) { if checker.enabled(Rule::FunctionCallInDefaultArgument) {
flake8_bugbear::rules::function_call_in_argument_default(checker, arguments); flake8_bugbear::rules::function_call_in_argument_default(checker, parameters);
} }
if checker.settings.rules.enabled(Rule::ImplicitOptional) { if checker.settings.rules.enabled(Rule::ImplicitOptional) {
ruff::rules::implicit_optional(checker, arguments); ruff::rules::implicit_optional(checker, parameters);
} }
if checker.is_stub { if checker.is_stub {
if checker.enabled(Rule::TypedArgumentDefaultInStub) { if checker.enabled(Rule::TypedArgumentDefaultInStub) {
flake8_pyi::rules::typed_argument_simple_defaults(checker, arguments); flake8_pyi::rules::typed_argument_simple_defaults(checker, parameters);
} }
if checker.enabled(Rule::ArgumentDefaultInStub) { if checker.enabled(Rule::ArgumentDefaultInStub) {
flake8_pyi::rules::argument_simple_defaults(checker, arguments); flake8_pyi::rules::argument_simple_defaults(checker, parameters);
} }
} }
} }

View File

@ -73,7 +73,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
name, name,
decorator_list, decorator_list,
returns, returns,
args, parameters,
body, body,
.. ..
}) })
@ -81,7 +81,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
name, name,
decorator_list, decorator_list,
returns, returns,
args, parameters,
body, body,
.. ..
}) => { }) => {
@ -114,7 +114,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
checker.semantic.scope(), checker.semantic.scope(),
name, name,
decorator_list, decorator_list,
args, parameters,
) )
{ {
checker.diagnostics.push(diagnostic); checker.diagnostics.push(diagnostic);
@ -126,7 +126,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
checker.semantic.scope(), checker.semantic.scope(),
name, name,
decorator_list, decorator_list,
args, parameters,
) { ) {
checker.diagnostics.push(diagnostic); checker.diagnostics.push(diagnostic);
} }
@ -142,7 +142,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
flake8_pyi::rules::stub_body_multiple_statements(checker, stmt, body); flake8_pyi::rules::stub_body_multiple_statements(checker, stmt, body);
} }
if checker.enabled(Rule::AnyEqNeAnnotation) { if checker.enabled(Rule::AnyEqNeAnnotation) {
flake8_pyi::rules::any_eq_ne_annotation(checker, name, args); flake8_pyi::rules::any_eq_ne_annotation(checker, name, parameters);
} }
if checker.enabled(Rule::NonSelfReturnType) { if checker.enabled(Rule::NonSelfReturnType) {
flake8_pyi::rules::non_self_return_type( flake8_pyi::rules::non_self_return_type(
@ -151,7 +151,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
name, name,
decorator_list, decorator_list,
returns.as_ref().map(AsRef::as_ref), returns.as_ref().map(AsRef::as_ref),
args, parameters,
stmt.is_async_function_def_stmt(), stmt.is_async_function_def_stmt(),
); );
} }
@ -159,18 +159,18 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
flake8_pyi::rules::str_or_repr_defined_in_stub(checker, stmt); flake8_pyi::rules::str_or_repr_defined_in_stub(checker, stmt);
} }
if checker.enabled(Rule::NoReturnArgumentAnnotationInStub) { if checker.enabled(Rule::NoReturnArgumentAnnotationInStub) {
flake8_pyi::rules::no_return_argument_annotation(checker, args); flake8_pyi::rules::no_return_argument_annotation(checker, parameters);
} }
if checker.enabled(Rule::BadExitAnnotation) { if checker.enabled(Rule::BadExitAnnotation) {
flake8_pyi::rules::bad_exit_annotation( flake8_pyi::rules::bad_exit_annotation(
checker, checker,
stmt.is_async_function_def_stmt(), stmt.is_async_function_def_stmt(),
name, name,
args, parameters,
); );
} }
if checker.enabled(Rule::RedundantNumericUnion) { if checker.enabled(Rule::RedundantNumericUnion) {
flake8_pyi::rules::redundant_numeric_union(checker, args); flake8_pyi::rules::redundant_numeric_union(checker, parameters);
} }
} }
if checker.enabled(Rule::DunderFunctionName) { if checker.enabled(Rule::DunderFunctionName) {
@ -230,13 +230,13 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
} }
} }
if checker.enabled(Rule::HardcodedPasswordDefault) { if checker.enabled(Rule::HardcodedPasswordDefault) {
flake8_bandit::rules::hardcoded_password_default(checker, args); flake8_bandit::rules::hardcoded_password_default(checker, parameters);
} }
if checker.enabled(Rule::PropertyWithParameters) { if checker.enabled(Rule::PropertyWithParameters) {
pylint::rules::property_with_parameters(checker, stmt, decorator_list, args); pylint::rules::property_with_parameters(checker, stmt, decorator_list, parameters);
} }
if checker.enabled(Rule::TooManyArguments) { if checker.enabled(Rule::TooManyArguments) {
pylint::rules::too_many_arguments(checker, args, stmt); pylint::rules::too_many_arguments(checker, parameters, stmt);
} }
if checker.enabled(Rule::TooManyReturnStatements) { if checker.enabled(Rule::TooManyReturnStatements) {
if let Some(diagnostic) = pylint::rules::too_many_return_statements( if let Some(diagnostic) = pylint::rules::too_many_return_statements(
@ -282,7 +282,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
checker, checker,
stmt, stmt,
name, name,
args, parameters,
decorator_list, decorator_list,
body, body,
); );
@ -304,7 +304,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
checker, checker,
name, name,
decorator_list, decorator_list,
args, parameters,
); );
} }
if checker.enabled(Rule::BooleanDefaultValueInFunctionDefinition) { if checker.enabled(Rule::BooleanDefaultValueInFunctionDefinition) {
@ -312,7 +312,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
checker, checker,
name, name,
decorator_list, decorator_list,
args, parameters,
); );
} }
if checker.enabled(Rule::UnexpectedSpecialMethodSignature) { if checker.enabled(Rule::UnexpectedSpecialMethodSignature) {
@ -321,7 +321,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
stmt, stmt,
name, name,
decorator_list, decorator_list,
args, parameters,
); );
} }
if checker.enabled(Rule::FStringDocstring) { if checker.enabled(Rule::FStringDocstring) {

View File

@ -31,8 +31,8 @@ use std::path::Path;
use itertools::Itertools; use itertools::Itertools;
use log::error; use log::error;
use ruff_python_ast::{ use ruff_python_ast::{
self as ast, Arg, ArgWithDefault, Arguments, Comprehension, Constant, ElifElseClause, self as ast, Comprehension, Constant, ElifElseClause, ExceptHandler, Expr, ExprContext,
ExceptHandler, Expr, ExprContext, Keyword, Pattern, Ranged, Stmt, Suite, UnaryOp, Keyword, Parameter, ParameterWithDefault, Parameters, Pattern, Ranged, Stmt, Suite, UnaryOp,
}; };
use ruff_text_size::{TextRange, TextSize}; use ruff_text_size::{TextRange, TextSize};
@ -455,7 +455,7 @@ where
match stmt { match stmt {
Stmt::FunctionDef(ast::StmtFunctionDef { Stmt::FunctionDef(ast::StmtFunctionDef {
body, body,
args, parameters,
decorator_list, decorator_list,
returns, returns,
type_params, type_params,
@ -463,7 +463,7 @@ where
}) })
| Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef { | Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef {
body, body,
args, parameters,
decorator_list, decorator_list,
type_params, type_params,
returns, returns,
@ -485,24 +485,24 @@ where
self.visit_type_param(type_param); self.visit_type_param(type_param);
} }
for arg_with_default in args for parameter_with_default in parameters
.posonlyargs .posonlyargs
.iter() .iter()
.chain(&args.args) .chain(&parameters.args)
.chain(&args.kwonlyargs) .chain(&parameters.kwonlyargs)
{ {
if let Some(expr) = &arg_with_default.def.annotation { if let Some(expr) = &parameter_with_default.def.annotation {
if runtime_annotation { if runtime_annotation {
self.visit_runtime_annotation(expr); self.visit_runtime_annotation(expr);
} else { } else {
self.visit_annotation(expr); self.visit_annotation(expr);
}; };
} }
if let Some(expr) = &arg_with_default.default { if let Some(expr) = &parameter_with_default.default {
self.visit_expr(expr); self.visit_expr(expr);
} }
} }
if let Some(arg) = &args.vararg { if let Some(arg) = &parameters.vararg {
if let Some(expr) = &arg.annotation { if let Some(expr) = &arg.annotation {
if runtime_annotation { if runtime_annotation {
self.visit_runtime_annotation(expr); self.visit_runtime_annotation(expr);
@ -511,7 +511,7 @@ where
}; };
} }
} }
if let Some(arg) = &args.kwarg { if let Some(arg) = &parameters.kwarg {
if let Some(expr) = &arg.annotation { if let Some(expr) = &arg.annotation {
if runtime_annotation { if runtime_annotation {
self.visit_runtime_annotation(expr); self.visit_runtime_annotation(expr);
@ -888,21 +888,21 @@ where
} }
Expr::Lambda( Expr::Lambda(
lambda @ ast::ExprLambda { lambda @ ast::ExprLambda {
args, parameters,
body: _, body: _,
range: _, range: _,
}, },
) => { ) => {
// Visit the default arguments, but avoid the body, which will be deferred. // Visit the default arguments, but avoid the body, which will be deferred.
for ArgWithDefault { for ParameterWithDefault {
default, default,
def: _, def: _,
range: _, range: _,
} in args } in parameters
.posonlyargs .posonlyargs
.iter() .iter()
.chain(&args.args) .chain(&parameters.args)
.chain(&args.kwonlyargs) .chain(&parameters.kwonlyargs)
{ {
if let Some(expr) = &default { if let Some(expr) = &default {
self.visit_expr(expr); self.visit_expr(expr);
@ -1293,43 +1293,43 @@ where
} }
} }
fn visit_arguments(&mut self, arguments: &'b Arguments) { fn visit_parameters(&mut self, parameters: &'b Parameters) {
// Step 1: Binding. // Step 1: Binding.
// Bind, but intentionally avoid walking default expressions, as we handle them // Bind, but intentionally avoid walking default expressions, as we handle them
// upstream. // upstream.
for arg_with_default in &arguments.posonlyargs { for parameter_with_default in &parameters.posonlyargs {
self.visit_arg(&arg_with_default.def); self.visit_parameter(&parameter_with_default.def);
} }
for arg_with_default in &arguments.args { for parameter_with_default in &parameters.args {
self.visit_arg(&arg_with_default.def); self.visit_parameter(&parameter_with_default.def);
} }
if let Some(arg) = &arguments.vararg { if let Some(arg) = &parameters.vararg {
self.visit_arg(arg); self.visit_parameter(arg);
} }
for arg_with_default in &arguments.kwonlyargs { for parameter_with_default in &parameters.kwonlyargs {
self.visit_arg(&arg_with_default.def); self.visit_parameter(&parameter_with_default.def);
} }
if let Some(arg) = &arguments.kwarg { if let Some(arg) = &parameters.kwarg {
self.visit_arg(arg); self.visit_parameter(arg);
} }
// Step 4: Analysis // Step 4: Analysis
analyze::arguments(arguments, self); analyze::parameters(parameters, self);
} }
fn visit_arg(&mut self, arg: &'b Arg) { fn visit_parameter(&mut self, parameter: &'b Parameter) {
// Step 1: Binding. // Step 1: Binding.
// Bind, but intentionally avoid walking the annotation, as we handle it // Bind, but intentionally avoid walking the annotation, as we handle it
// upstream. // upstream.
self.add_binding( self.add_binding(
&arg.arg, &parameter.arg,
arg.identifier(), parameter.identifier(),
BindingKind::Argument, BindingKind::Argument,
BindingFlags::empty(), BindingFlags::empty(),
); );
// Step 4: Analysis // Step 4: Analysis
analyze::argument(arg, self); analyze::parameter(parameter, self);
} }
fn visit_pattern(&mut self, pattern: &'b Pattern) { fn visit_pattern(&mut self, pattern: &'b Pattern) {
@ -1824,9 +1824,13 @@ impl<'a> Checker<'a> {
self.semantic.restore(snapshot); self.semantic.restore(snapshot);
match &self.semantic.stmt() { match &self.semantic.stmt() {
Stmt::FunctionDef(ast::StmtFunctionDef { body, args, .. }) Stmt::FunctionDef(ast::StmtFunctionDef {
| Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef { body, args, .. }) => { body, parameters, ..
self.visit_arguments(args); })
| Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef {
body, parameters, ..
}) => {
self.visit_parameters(parameters);
self.visit_body(body); self.visit_body(body);
} }
_ => { _ => {
@ -1846,12 +1850,12 @@ impl<'a> Checker<'a> {
self.semantic.restore(snapshot); self.semantic.restore(snapshot);
if let Expr::Lambda(ast::ExprLambda { if let Expr::Lambda(ast::ExprLambda {
args, parameters,
body, body,
range: _, range: _,
}) = expr }) = expr
{ {
self.visit_arguments(args); self.visit_parameters(parameters);
self.visit_expr(body); self.visit_expr(body);
} else { } else {
unreachable!("Expected Expr::Lambda"); unreachable!("Expected Expr::Lambda");

View File

@ -1,4 +1,4 @@
use ruff_python_ast::{self as ast, Arguments, Expr, Stmt}; use ruff_python_ast::{self as ast, Expr, Parameters, Stmt};
use ruff_python_ast::cast; use ruff_python_ast::cast;
use ruff_python_semantic::analyze::visibility; use ruff_python_semantic::analyze::visibility;
@ -6,11 +6,11 @@ use ruff_python_semantic::{Definition, Member, MemberKind, SemanticModel};
pub(super) fn match_function_def( pub(super) fn match_function_def(
stmt: &Stmt, stmt: &Stmt,
) -> (&str, &Arguments, Option<&Expr>, &[Stmt], &[ast::Decorator]) { ) -> (&str, &Parameters, Option<&Expr>, &[Stmt], &[ast::Decorator]) {
match stmt { match stmt {
Stmt::FunctionDef(ast::StmtFunctionDef { Stmt::FunctionDef(ast::StmtFunctionDef {
name, name,
args, parameters,
returns, returns,
body, body,
decorator_list, decorator_list,
@ -18,14 +18,14 @@ pub(super) fn match_function_def(
}) })
| Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef { | Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef {
name, name,
args, parameters,
returns, returns,
body, body,
decorator_list, decorator_list,
.. ..
}) => ( }) => (
name, name,
args, parameters,
returns.as_ref().map(AsRef::as_ref), returns.as_ref().map(AsRef::as_ref),
body, body,
decorator_list, decorator_list,

View File

@ -1,4 +1,4 @@
use ruff_python_ast::{self as ast, ArgWithDefault, Constant, Expr, Ranged, Stmt}; use ruff_python_ast::{self as ast, Constant, Expr, ParameterWithDefault, Ranged, Stmt};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Fix, Violation}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Fix, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
@ -524,7 +524,7 @@ pub(crate) fn definition(
let is_overridden = visibility::is_override(decorator_list, checker.semantic()); let is_overridden = visibility::is_override(decorator_list, checker.semantic());
// ANN001, ANN401 // ANN001, ANN401
for ArgWithDefault { for ParameterWithDefault {
def, def,
default: _, default: _,
range: _, range: _,
@ -627,7 +627,7 @@ pub(crate) fn definition(
// ANN101, ANN102 // ANN101, ANN102
if is_method && !visibility::is_staticmethod(cast::decorator_list(stmt), checker.semantic()) { if is_method && !visibility::is_staticmethod(cast::decorator_list(stmt), checker.semantic()) {
if let Some(ArgWithDefault { if let Some(ParameterWithDefault {
def, def,
default: _, default: _,
range: _, range: _,

View File

@ -1,4 +1,4 @@
use ruff_python_ast::{Arg, ArgWithDefault, Arguments, Expr, Ranged}; use ruff_python_ast::{Expr, Parameter, ParameterWithDefault, Parameters, 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};
@ -53,9 +53,9 @@ impl Violation for HardcodedPasswordDefault {
} }
} }
fn check_password_kwarg(arg: &Arg, default: &Expr) -> Option<Diagnostic> { fn check_password_kwarg(parameter: &Parameter, default: &Expr) -> Option<Diagnostic> {
string_literal(default).filter(|string| !string.is_empty())?; string_literal(default).filter(|string| !string.is_empty())?;
let kwarg_name = &arg.arg; let kwarg_name = &parameter.arg;
if !matches_password_name(kwarg_name) { if !matches_password_name(kwarg_name) {
return None; return None;
} }
@ -68,16 +68,16 @@ fn check_password_kwarg(arg: &Arg, default: &Expr) -> Option<Diagnostic> {
} }
/// S107 /// S107
pub(crate) fn hardcoded_password_default(checker: &mut Checker, arguments: &Arguments) { pub(crate) fn hardcoded_password_default(checker: &mut Checker, parameters: &Parameters) {
for ArgWithDefault { for ParameterWithDefault {
def, def,
default, default,
range: _, range: _,
} in arguments } in parameters
.posonlyargs .posonlyargs
.iter() .iter()
.chain(&arguments.args) .chain(&parameters.args)
.chain(&arguments.kwonlyargs) .chain(&parameters.kwonlyargs)
{ {
let Some(default) = default else { let Some(default) = default else {
continue; continue;

View File

@ -1,4 +1,4 @@
use ruff_python_ast::{ArgWithDefault, Arguments, Decorator}; use ruff_python_ast::{Decorator, ParameterWithDefault, Parameters};
use ruff_diagnostics::Violation; use ruff_diagnostics::Violation;
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
@ -59,7 +59,7 @@ pub(crate) fn check_boolean_default_value_in_function_definition(
checker: &mut Checker, checker: &mut Checker,
name: &str, name: &str,
decorator_list: &[Decorator], decorator_list: &[Decorator],
arguments: &Arguments, parameters: &Parameters,
) { ) {
if is_allowed_func_def(name) { if is_allowed_func_def(name) {
return; return;
@ -72,11 +72,11 @@ pub(crate) fn check_boolean_default_value_in_function_definition(
return; return;
} }
for ArgWithDefault { for ParameterWithDefault {
def: _, def: _,
default, default,
range: _, range: _,
} in arguments.args.iter().chain(&arguments.posonlyargs) } in parameters.args.iter().chain(&parameters.posonlyargs)
{ {
let Some(default) = default else { let Some(default) = default else {
continue; continue;

View File

@ -1,4 +1,6 @@
use ruff_python_ast::{self as ast, ArgWithDefault, Arguments, Constant, Decorator, Expr, Ranged}; use ruff_python_ast::{
self as ast, Constant, Decorator, Expr, ParameterWithDefault, Parameters, Ranged,
};
use ruff_diagnostics::Diagnostic; use ruff_diagnostics::Diagnostic;
use ruff_diagnostics::Violation; use ruff_diagnostics::Violation;
@ -80,7 +82,7 @@ pub(crate) fn check_positional_boolean_in_def(
checker: &mut Checker, checker: &mut Checker,
name: &str, name: &str,
decorator_list: &[Decorator], decorator_list: &[Decorator],
arguments: &Arguments, parameters: &Parameters,
) { ) {
if is_allowed_func_def(name) { if is_allowed_func_def(name) {
return; return;
@ -93,11 +95,11 @@ pub(crate) fn check_positional_boolean_in_def(
return; return;
} }
for ArgWithDefault { for ParameterWithDefault {
def, def,
default: _, default: _,
range: _, range: _,
} in arguments.posonlyargs.iter().chain(&arguments.args) } in parameters.posonlyargs.iter().chain(&parameters.args)
{ {
if def.annotation.is_none() { if def.annotation.is_none() {
continue; continue;

View File

@ -1,4 +1,4 @@
use ruff_python_ast::{self as ast, ArgWithDefault, Arguments, Expr, Ranged}; use ruff_python_ast::{self as ast, Expr, ParameterWithDefault, Parameters, Ranged};
use ruff_text_size::TextRange; use ruff_text_size::TextRange;
use ruff_diagnostics::Violation; use ruff_diagnostics::Violation;
@ -105,7 +105,7 @@ where
} }
/// B008 /// B008
pub(crate) fn function_call_in_argument_default(checker: &mut Checker, arguments: &Arguments) { pub(crate) fn function_call_in_argument_default(checker: &mut Checker, parameters: &Parameters) {
// Map immutable calls to (module, member) format. // Map immutable calls to (module, member) format.
let extend_immutable_calls: Vec<CallPath> = checker let extend_immutable_calls: Vec<CallPath> = checker
.settings .settings
@ -116,15 +116,15 @@ pub(crate) fn function_call_in_argument_default(checker: &mut Checker, arguments
.collect(); .collect();
let diagnostics = { let diagnostics = {
let mut visitor = ArgumentDefaultVisitor::new(checker.semantic(), extend_immutable_calls); let mut visitor = ArgumentDefaultVisitor::new(checker.semantic(), extend_immutable_calls);
for ArgWithDefault { for ParameterWithDefault {
default, default,
def: _, def: _,
range: _, range: _,
} in arguments } in parameters
.posonlyargs .posonlyargs
.iter() .iter()
.chain(&arguments.args) .chain(&parameters.args)
.chain(&arguments.kwonlyargs) .chain(&parameters.kwonlyargs)
{ {
if let Some(expr) = &default { if let Some(expr) = &default {
visitor.visit_expr(expr); visitor.visit_expr(expr);

View File

@ -86,8 +86,12 @@ struct SuspiciousVariablesVisitor<'a> {
impl<'a> Visitor<'a> for SuspiciousVariablesVisitor<'a> { impl<'a> Visitor<'a> for SuspiciousVariablesVisitor<'a> {
fn visit_stmt(&mut self, stmt: &'a Stmt) { fn visit_stmt(&mut self, stmt: &'a Stmt) {
match stmt { match stmt {
Stmt::FunctionDef(ast::StmtFunctionDef { args, body, .. }) Stmt::FunctionDef(ast::StmtFunctionDef {
| Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef { args, body, .. }) => { parameters, body, ..
})
| Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef {
parameters, body, ..
}) => {
// Collect all loaded variable names. // Collect all loaded variable names.
let mut visitor = LoadedNamesVisitor::default(); let mut visitor = LoadedNamesVisitor::default();
visitor.visit_body(body); visitor.visit_body(body);
@ -99,7 +103,7 @@ impl<'a> Visitor<'a> for SuspiciousVariablesVisitor<'a> {
return false; return false;
} }
if includes_arg_name(&loaded.id, args) { if includes_arg_name(&loaded.id, parameters) {
return false; return false;
} }
@ -165,7 +169,7 @@ impl<'a> Visitor<'a> for SuspiciousVariablesVisitor<'a> {
} }
} }
Expr::Lambda(ast::ExprLambda { Expr::Lambda(ast::ExprLambda {
args, parameters,
body, body,
range: _, range: _,
}) => { }) => {
@ -181,7 +185,7 @@ impl<'a> Visitor<'a> for SuspiciousVariablesVisitor<'a> {
return false; return false;
} }
if includes_arg_name(&loaded.id, args) { if includes_arg_name(&loaded.id, parameters) {
return false; return false;
} }

View File

@ -1,4 +1,4 @@
use ruff_python_ast::{self as ast, ArgWithDefault, Expr, Ranged}; use ruff_python_ast::{self as ast, Expr, ParameterWithDefault, Ranged};
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use ruff_diagnostics::{Diagnostic, Violation}; use ruff_diagnostics::{Diagnostic, Violation};
@ -71,20 +71,20 @@ where
} }
} }
Expr::Lambda(ast::ExprLambda { Expr::Lambda(ast::ExprLambda {
args, parameters,
body, body,
range: _, range: _,
}) => { }) => {
visitor::walk_expr(self, body); visitor::walk_expr(self, body);
for ArgWithDefault { for ParameterWithDefault {
def, def,
default: _, default: _,
range: _, range: _,
} in args } in parameters
.posonlyargs .posonlyargs
.iter() .iter()
.chain(&args.args) .chain(&parameters.args)
.chain(&args.kwonlyargs) .chain(&parameters.kwonlyargs)
{ {
self.names.remove(def.arg.as_str()); self.names.remove(def.arg.as_str());
} }

View File

@ -1,4 +1,4 @@
use ruff_python_ast::{ArgWithDefault, Arguments, Ranged}; use ruff_python_ast::{ParameterWithDefault, Parameters, 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};
@ -57,17 +57,17 @@ impl Violation for MutableArgumentDefault {
} }
/// B006 /// B006
pub(crate) fn mutable_argument_default(checker: &mut Checker, arguments: &Arguments) { pub(crate) fn mutable_argument_default(checker: &mut Checker, parameters: &Parameters) {
// Scan in reverse order to right-align zip(). // Scan in reverse order to right-align zip().
for ArgWithDefault { for ParameterWithDefault {
def, def,
default, default,
range: _, range: _,
} in arguments } in parameters
.posonlyargs .posonlyargs
.iter() .iter()
.chain(&arguments.args) .chain(&parameters.args)
.chain(&arguments.kwonlyargs) .chain(&parameters.kwonlyargs)
{ {
let Some(default) = default else { let Some(default) = default else {
continue; continue;

View File

@ -1,4 +1,4 @@
use ruff_python_ast::{Arg, Ranged}; use ruff_python_ast::{Parameter, Ranged};
use ruff_diagnostics::Diagnostic; use ruff_diagnostics::Diagnostic;
use ruff_diagnostics::Violation; use ruff_diagnostics::Violation;
@ -62,16 +62,16 @@ impl Violation for BuiltinArgumentShadowing {
} }
/// A002 /// A002
pub(crate) fn builtin_argument_shadowing(checker: &mut Checker, argument: &Arg) { pub(crate) fn builtin_argument_shadowing(checker: &mut Checker, parameter: &Parameter) {
if shadows_builtin( if shadows_builtin(
argument.arg.as_str(), parameter.arg.as_str(),
&checker.settings.flake8_builtins.builtins_ignorelist, &checker.settings.flake8_builtins.builtins_ignorelist,
) { ) {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
BuiltinArgumentShadowing { BuiltinArgumentShadowing {
name: argument.arg.to_string(), name: parameter.arg.to_string(),
}, },
argument.range(), parameter.range(),
)); ));
} }
} }

View File

@ -1,6 +1,6 @@
use std::fmt; use std::fmt;
use ruff_python_ast::{self as ast, Arguments, Expr, ExprContext, Ranged, Stmt}; use ruff_python_ast::{self as ast, Expr, ExprContext, Parameters, Ranged, Stmt};
use ruff_diagnostics::{AutofixKind, Violation}; use ruff_diagnostics::{AutofixKind, Violation};
use ruff_diagnostics::{Diagnostic, Fix}; use ruff_diagnostics::{Diagnostic, Fix};
@ -98,11 +98,14 @@ pub(crate) fn unnecessary_map(
}; };
// Only flag, e.g., `map(lambda x: x + 1, iterable)`. // Only flag, e.g., `map(lambda x: x + 1, iterable)`.
let [Expr::Lambda(ast::ExprLambda { args, body, .. }), _] = args else { let [Expr::Lambda(ast::ExprLambda {
parameters, body, ..
}), _] = args
else {
return; return;
}; };
if late_binding(args, body) { if late_binding(parameters, body) {
return; return;
} }
} }
@ -121,11 +124,14 @@ pub(crate) fn unnecessary_map(
return; return;
}; };
let Expr::Lambda(ast::ExprLambda { args, body, .. }) = argument else { let Expr::Lambda(ast::ExprLambda {
parameters, body, ..
}) = argument
else {
return; return;
}; };
if late_binding(args, body) { if late_binding(parameters, body) {
return; return;
} }
} }
@ -140,7 +146,10 @@ pub(crate) fn unnecessary_map(
return; return;
}; };
let Expr::Lambda(ast::ExprLambda { args, body, .. }) = argument else { let Expr::Lambda(ast::ExprLambda {
parameters, body, ..
}) = argument
else {
return; return;
}; };
@ -154,7 +163,7 @@ pub(crate) fn unnecessary_map(
return; return;
} }
if late_binding(args, body) { if late_binding(parameters, body) {
return; return;
} }
} }
@ -195,7 +204,7 @@ impl fmt::Display for ObjectType {
} }
} }
/// Returns `true` if the lambda defined by the given arguments and body contains any names that /// Returns `true` if the lambda defined by the given parameters and body contains any names that
/// are late-bound within nested lambdas. /// are late-bound within nested lambdas.
/// ///
/// For example, given: /// For example, given:
@ -212,8 +221,8 @@ impl fmt::Display for ObjectType {
/// ///
/// Would yield an incorrect result, as the `x` in the inner lambda would be bound to the last /// Would yield an incorrect result, as the `x` in the inner lambda would be bound to the last
/// value of `x` in the comprehension. /// value of `x` in the comprehension.
fn late_binding(args: &Arguments, body: &Expr) -> bool { fn late_binding(parameters: &Parameters, body: &Expr) -> bool {
let mut visitor = LateBindingVisitor::new(args); let mut visitor = LateBindingVisitor::new(parameters);
visitor.visit_expr(body); visitor.visit_expr(body);
visitor.late_bound visitor.late_bound
} }
@ -221,17 +230,17 @@ fn late_binding(args: &Arguments, body: &Expr) -> bool {
#[derive(Debug)] #[derive(Debug)]
struct LateBindingVisitor<'a> { struct LateBindingVisitor<'a> {
/// The arguments to the current lambda. /// The arguments to the current lambda.
args: &'a Arguments, parameters: &'a Parameters,
/// The arguments to any lambdas within the current lambda body. /// The arguments to any lambdas within the current lambda body.
lambdas: Vec<&'a Arguments>, lambdas: Vec<&'a Parameters>,
/// Whether any names within the current lambda body are late-bound within nested lambdas. /// Whether any names within the current lambda body are late-bound within nested lambdas.
late_bound: bool, late_bound: bool,
} }
impl<'a> LateBindingVisitor<'a> { impl<'a> LateBindingVisitor<'a> {
fn new(args: &'a Arguments) -> Self { fn new(parameters: &'a Parameters) -> Self {
Self { Self {
args, parameters,
lambdas: Vec::new(), lambdas: Vec::new(),
late_bound: false, late_bound: false,
} }
@ -243,8 +252,8 @@ impl<'a> Visitor<'a> for LateBindingVisitor<'a> {
fn visit_expr(&mut self, expr: &'a Expr) { fn visit_expr(&mut self, expr: &'a Expr) {
match expr { match expr {
Expr::Lambda(ast::ExprLambda { args, .. }) => { Expr::Lambda(ast::ExprLambda { parameters, .. }) => {
self.lambdas.push(args); self.lambdas.push(parameters);
visitor::walk_expr(self, expr); visitor::walk_expr(self, expr);
self.lambdas.pop(); self.lambdas.pop();
} }
@ -256,7 +265,7 @@ impl<'a> Visitor<'a> for LateBindingVisitor<'a> {
// If we're within a nested lambda... // If we're within a nested lambda...
if !self.lambdas.is_empty() { if !self.lambdas.is_empty() {
// If the name is defined in the current lambda... // If the name is defined in the current lambda...
if includes_arg_name(id, self.args) { if includes_arg_name(id, self.parameters) {
// And isn't overridden by any nested lambdas... // And isn't overridden by any nested lambdas...
if !self.lambdas.iter().any(|args| includes_arg_name(id, args)) { if !self.lambdas.iter().any(|args| includes_arg_name(id, args)) {
// Then it's late-bound. // Then it's late-bound.

View File

@ -54,16 +54,16 @@ impl Violation for ReimplementedListBuiltin {
/// PIE807 /// PIE807
pub(crate) fn reimplemented_list_builtin(checker: &mut Checker, expr: &ExprLambda) { pub(crate) fn reimplemented_list_builtin(checker: &mut Checker, expr: &ExprLambda) {
let ExprLambda { let ExprLambda {
args, parameters,
body, body,
range: _, range: _,
} = expr; } = expr;
if args.args.is_empty() if parameters.args.is_empty()
&& args.kwonlyargs.is_empty() && parameters.kwonlyargs.is_empty()
&& args.posonlyargs.is_empty() && parameters.posonlyargs.is_empty()
&& args.vararg.is_none() && parameters.vararg.is_none()
&& args.kwarg.is_none() && parameters.kwarg.is_none()
{ {
if let Expr::List(ast::ExprList { elts, .. }) = body.as_ref() { if let Expr::List(ast::ExprList { elts, .. }) = body.as_ref() {
if elts.is_empty() { if elts.is_empty() {

View File

@ -1,4 +1,4 @@
use ruff_python_ast::{Arguments, Ranged}; use ruff_python_ast::{Parameters, Ranged};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
@ -53,16 +53,16 @@ impl AlwaysAutofixableViolation for AnyEqNeAnnotation {
} }
/// PYI032 /// PYI032
pub(crate) fn any_eq_ne_annotation(checker: &mut Checker, name: &str, args: &Arguments) { pub(crate) fn any_eq_ne_annotation(checker: &mut Checker, name: &str, parameters: &Parameters) {
if !matches!(name, "__eq__" | "__ne__") { if !matches!(name, "__eq__" | "__ne__") {
return; return;
} }
if args.args.len() != 2 { if parameters.args.len() != 2 {
return; return;
} }
let Some(annotation) = &args.args[1].def.annotation else { let Some(annotation) = &parameters.args[1].def.annotation else {
return; return;
}; };

View File

@ -1,8 +1,8 @@
use std::fmt::{Display, Formatter}; use std::fmt::{Display, Formatter};
use ruff_python_ast::{ use ruff_python_ast::{
ArgWithDefault, Arguments, Expr, ExprBinOp, ExprSubscript, ExprTuple, Identifier, Operator, Expr, ExprBinOp, ExprSubscript, ExprTuple, Identifier, Operator, ParameterWithDefault,
Ranged, Parameters, Ranged,
}; };
use smallvec::SmallVec; use smallvec::SmallVec;
@ -104,7 +104,7 @@ pub(crate) fn bad_exit_annotation(
checker: &mut Checker, checker: &mut Checker,
is_async: bool, is_async: bool,
name: &Identifier, name: &Identifier,
args: &Arguments, parameters: &Parameters,
) { ) {
let func_kind = match name.as_str() { let func_kind = match name.as_str() {
"__exit__" if !is_async => FuncKind::Sync, "__exit__" if !is_async => FuncKind::Sync,
@ -112,41 +112,45 @@ pub(crate) fn bad_exit_annotation(
_ => return, _ => return,
}; };
let positional_args = args let positional_args = parameters
.args .args
.iter() .iter()
.chain(args.posonlyargs.iter()) .chain(parameters.posonlyargs.iter())
.collect::<SmallVec<[&ArgWithDefault; 4]>>(); .collect::<SmallVec<[&ParameterWithDefault; 4]>>();
// If there are less than three positional arguments, at least one of them must be a star-arg, // If there are less than three positional arguments, at least one of them must be a star-arg,
// and it must be annotated with `object`. // and it must be annotated with `object`.
if positional_args.len() < 4 { if positional_args.len() < 4 {
check_short_args_list(checker, args, func_kind); check_short_args_list(checker, parameters, func_kind);
} }
// Every positional argument (beyond the first four) must have a default. // Every positional argument (beyond the first four) must have a default.
for arg_with_default in positional_args for parameter in positional_args
.iter() .iter()
.skip(4) .skip(4)
.filter(|arg_with_default| arg_with_default.default.is_none()) .filter(|parameter| parameter.default.is_none())
{ {
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
BadExitAnnotation { BadExitAnnotation {
func_kind, func_kind,
error_kind: ErrorKind::ArgsAfterFirstFourMustHaveDefault, error_kind: ErrorKind::ArgsAfterFirstFourMustHaveDefault,
}, },
arg_with_default.range(), parameter.range(),
)); ));
} }
// ...as should all keyword-only arguments. // ...as should all keyword-only arguments.
for arg_with_default in args.kwonlyargs.iter().filter(|arg| arg.default.is_none()) { for parameter in parameters
.kwonlyargs
.iter()
.filter(|arg| arg.default.is_none())
{
checker.diagnostics.push(Diagnostic::new( checker.diagnostics.push(Diagnostic::new(
BadExitAnnotation { BadExitAnnotation {
func_kind, func_kind,
error_kind: ErrorKind::AllKwargsMustHaveDefault, error_kind: ErrorKind::AllKwargsMustHaveDefault,
}, },
arg_with_default.range(), parameter.range(),
)); ));
} }
@ -155,8 +159,8 @@ pub(crate) fn bad_exit_annotation(
/// Determine whether a "short" argument list (i.e., an argument list with less than four elements) /// Determine whether a "short" argument list (i.e., an argument list with less than four elements)
/// contains a star-args argument annotated with `object`. If not, report an error. /// contains a star-args argument annotated with `object`. If not, report an error.
fn check_short_args_list(checker: &mut Checker, args: &Arguments, func_kind: FuncKind) { fn check_short_args_list(checker: &mut Checker, parameters: &Parameters, func_kind: FuncKind) {
if let Some(varargs) = &args.vararg { if let Some(varargs) = &parameters.vararg {
if let Some(annotation) = varargs if let Some(annotation) = varargs
.annotation .annotation
.as_ref() .as_ref()
@ -187,7 +191,7 @@ fn check_short_args_list(checker: &mut Checker, args: &Arguments, func_kind: Fun
func_kind, func_kind,
error_kind: ErrorKind::MissingArgs, error_kind: ErrorKind::MissingArgs,
}, },
args.range(), parameters.range(),
)); ));
} }
} }
@ -196,7 +200,7 @@ fn check_short_args_list(checker: &mut Checker, args: &Arguments, func_kind: Fun
/// annotated correctly. /// annotated correctly.
fn check_positional_args( fn check_positional_args(
checker: &mut Checker, checker: &mut Checker,
positional_args: &[&ArgWithDefault], positional_args: &[&ParameterWithDefault],
kind: FuncKind, kind: FuncKind,
) { ) {
// For each argument, define the predicate against which to check the annotation. // For each argument, define the predicate against which to check the annotation.

View File

@ -4,7 +4,7 @@ use ruff_python_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};
use ruff_python_ast::Arguments; use ruff_python_ast::Parameters;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::settings::types::PythonVersion::Py311; use crate::settings::types::PythonVersion::Py311;
@ -47,12 +47,12 @@ impl Violation for NoReturnArgumentAnnotationInStub {
} }
/// PYI050 /// PYI050
pub(crate) fn no_return_argument_annotation(checker: &mut Checker, args: &Arguments) { pub(crate) fn no_return_argument_annotation(checker: &mut Checker, parameters: &Parameters) {
for annotation in args for annotation in parameters
.posonlyargs .posonlyargs
.iter() .iter()
.chain(&args.args) .chain(&parameters.args)
.chain(&args.kwonlyargs) .chain(&parameters.kwonlyargs)
.filter_map(|arg| arg.def.annotation.as_ref()) .filter_map(|arg| arg.def.annotation.as_ref())
{ {
if checker.semantic().match_typing_expr(annotation, "NoReturn") { if checker.semantic().match_typing_expr(annotation, "NoReturn") {

View File

@ -1,4 +1,4 @@
use ruff_python_ast::{self as ast, Arguments, Decorator, Expr, Stmt}; use ruff_python_ast::{self as ast, Decorator, Expr, Parameters, Stmt};
use ruff_diagnostics::{Diagnostic, Violation}; use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
@ -116,14 +116,14 @@ pub(crate) fn non_self_return_type(
name: &str, name: &str,
decorator_list: &[Decorator], decorator_list: &[Decorator],
returns: Option<&Expr>, returns: Option<&Expr>,
args: &Arguments, parameters: &Parameters,
async_: bool, async_: bool,
) { ) {
let ScopeKind::Class(class_def) = checker.semantic().scope().kind else { let ScopeKind::Class(class_def) = checker.semantic().scope().kind else {
return; return;
}; };
if args.args.is_empty() && args.posonlyargs.is_empty() { if parameters.args.is_empty() && parameters.posonlyargs.is_empty() {
return; return;
} }

View File

@ -1,4 +1,4 @@
use ruff_python_ast::{Arguments, Expr, Ranged}; use ruff_python_ast::{Expr, Parameters, 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};
@ -53,12 +53,12 @@ impl Violation for RedundantNumericUnion {
} }
/// PYI041 /// PYI041
pub(crate) fn redundant_numeric_union(checker: &mut Checker, args: &Arguments) { pub(crate) fn redundant_numeric_union(checker: &mut Checker, parameters: &Parameters) {
for annotation in args for annotation in parameters
.args .args
.iter() .iter()
.chain(args.posonlyargs.iter()) .chain(parameters.posonlyargs.iter())
.chain(args.kwonlyargs.iter()) .chain(parameters.kwonlyargs.iter())
.filter_map(|arg| arg.def.annotation.as_ref()) .filter_map(|arg| arg.def.annotation.as_ref())
{ {
check_annotation(checker, annotation); check_annotation(checker, annotation);
@ -67,10 +67,10 @@ pub(crate) fn redundant_numeric_union(checker: &mut Checker, args: &Arguments) {
// If annotations on `args` or `kwargs` are flagged by this rule, the annotations themselves // If annotations on `args` or `kwargs` are flagged by this rule, the annotations themselves
// are not accurate, but check them anyway. It's possible that flagging them will help the user // are not accurate, but check them anyway. It's possible that flagging them will help the user
// realize they're incorrect. // realize they're incorrect.
for annotation in args for annotation in parameters
.vararg .vararg
.iter() .iter()
.chain(args.kwarg.iter()) .chain(parameters.kwarg.iter())
.filter_map(|arg| arg.annotation.as_ref()) .filter_map(|arg| arg.annotation.as_ref())
{ {
check_annotation(checker, annotation); check_annotation(checker, annotation);

View File

@ -1,5 +1,5 @@
use ruff_python_ast::{ use ruff_python_ast::{
self as ast, ArgWithDefault, Arguments, Constant, Expr, Operator, Ranged, Stmt, UnaryOp, self as ast, Constant, Expr, Operator, ParameterWithDefault, Parameters, Ranged, Stmt, UnaryOp,
}; };
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix, Violation};
@ -400,16 +400,16 @@ fn is_annotatable_type_alias(value: &Expr, semantic: &SemanticModel) -> bool {
} }
/// PYI011 /// PYI011
pub(crate) fn typed_argument_simple_defaults(checker: &mut Checker, arguments: &Arguments) { pub(crate) fn typed_argument_simple_defaults(checker: &mut Checker, parameters: &Parameters) {
for ArgWithDefault { for ParameterWithDefault {
def, def,
default, default,
range: _, range: _,
} in arguments } in parameters
.posonlyargs .posonlyargs
.iter() .iter()
.chain(&arguments.args) .chain(&parameters.args)
.chain(&arguments.kwonlyargs) .chain(&parameters.kwonlyargs)
{ {
let Some(default) = default else { let Some(default) = default else {
continue; continue;
@ -437,16 +437,16 @@ pub(crate) fn typed_argument_simple_defaults(checker: &mut Checker, arguments: &
} }
/// PYI014 /// PYI014
pub(crate) fn argument_simple_defaults(checker: &mut Checker, arguments: &Arguments) { pub(crate) fn argument_simple_defaults(checker: &mut Checker, parameters: &Parameters) {
for ArgWithDefault { for ParameterWithDefault {
def, def,
default, default,
range: _, range: _,
} in arguments } in parameters
.posonlyargs .posonlyargs
.iter() .iter()
.chain(&arguments.args) .chain(&parameters.args)
.chain(&arguments.kwonlyargs) .chain(&parameters.kwonlyargs)
{ {
let Some(default) = default else { let Some(default) = default else {
continue; continue;

View File

@ -48,7 +48,7 @@ pub(crate) fn str_or_repr_defined_in_stub(checker: &mut Checker, stmt: &Stmt) {
name, name,
decorator_list, decorator_list,
returns, returns,
args, parameters,
.. ..
}) = stmt }) = stmt
else { else {
@ -69,7 +69,9 @@ pub(crate) fn str_or_repr_defined_in_stub(checker: &mut Checker, stmt: &Stmt) {
// It is a violation only if the method signature matches that of `object.__str__` // It is a violation only if the method signature matches that of `object.__str__`
// or `object.__repr__` exactly and the method is not decorated as abstract. // or `object.__repr__` exactly and the method is not decorated as abstract.
if !args.kwonlyargs.is_empty() || (args.args.len() + args.posonlyargs.len()) > 1 { if !parameters.kwonlyargs.is_empty()
|| (parameters.args.len() + parameters.posonlyargs.len()) > 1
{
return; return;
} }

View File

@ -1,7 +1,7 @@
use std::fmt; use std::fmt;
use ruff_python_ast::Decorator; use ruff_python_ast::Decorator;
use ruff_python_ast::{self as ast, ArgWithDefault, Arguments, Expr, Ranged, Stmt}; use ruff_python_ast::{self as ast, Expr, ParameterWithDefault, Parameters, Ranged, Stmt};
use ruff_text_size::{TextLen, TextRange}; use ruff_text_size::{TextLen, TextRange};
use ruff_diagnostics::{AlwaysAutofixableViolation, Violation}; use ruff_diagnostics::{AlwaysAutofixableViolation, Violation};
@ -607,14 +607,14 @@ fn check_fixture_returns(checker: &mut Checker, stmt: &Stmt, name: &str, body: &
} }
/// PT019 /// PT019
fn check_test_function_args(checker: &mut Checker, arguments: &Arguments) { fn check_test_function_args(checker: &mut Checker, parameters: &Parameters) {
arguments parameters
.posonlyargs .posonlyargs
.iter() .iter()
.chain(&arguments.args) .chain(&parameters.args)
.chain(&arguments.kwonlyargs) .chain(&parameters.kwonlyargs)
.for_each( .for_each(
|ArgWithDefault { |ParameterWithDefault {
def, def,
default: _, default: _,
range: _, range: _,
@ -643,8 +643,8 @@ fn check_fixture_decorator_name(checker: &mut Checker, decorator: &Decorator) {
} }
/// PT021 /// PT021
fn check_fixture_addfinalizer(checker: &mut Checker, args: &Arguments, body: &[Stmt]) { fn check_fixture_addfinalizer(checker: &mut Checker, parameters: &Parameters, body: &[Stmt]) {
if !includes_arg_name("request", args) { if !includes_arg_name("request", parameters) {
return; return;
} }
@ -696,7 +696,7 @@ pub(crate) fn fixture(
checker: &mut Checker, checker: &mut Checker,
stmt: &Stmt, stmt: &Stmt,
name: &str, name: &str,
args: &Arguments, parameters: &Parameters,
decorators: &[Decorator], decorators: &[Decorator],
body: &[Stmt], body: &[Stmt],
) { ) {
@ -724,7 +724,7 @@ pub(crate) fn fixture(
} }
if checker.enabled(Rule::PytestFixtureFinalizerCallback) { if checker.enabled(Rule::PytestFixtureFinalizerCallback) {
check_fixture_addfinalizer(checker, args, body); check_fixture_addfinalizer(checker, parameters, body);
} }
if checker.enabled(Rule::PytestUnnecessaryAsyncioMarkOnFixture) if checker.enabled(Rule::PytestUnnecessaryAsyncioMarkOnFixture)
@ -735,6 +735,6 @@ pub(crate) fn fixture(
} }
if checker.enabled(Rule::PytestFixtureParamWithoutValue) && name.starts_with("test_") { if checker.enabled(Rule::PytestFixtureParamWithoutValue) && name.starts_with("test_") {
check_test_function_args(checker, args); check_test_function_args(checker, parameters);
} }
} }

View File

@ -1,4 +1,4 @@
use ruff_python_ast::{self as ast, Arguments, Expr, Keyword, Ranged}; use ruff_python_ast::{self as ast, Expr, Keyword, Parameters, 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};
@ -20,7 +20,7 @@ impl Violation for PytestPatchWithLambda {
/// Visitor that checks references the argument names in the lambda body. /// Visitor that checks references the argument names in the lambda body.
#[derive(Debug)] #[derive(Debug)]
struct LambdaBodyVisitor<'a> { struct LambdaBodyVisitor<'a> {
arguments: &'a Arguments, parameters: &'a Parameters,
uses_args: bool, uses_args: bool,
} }
@ -31,7 +31,7 @@ where
fn visit_expr(&mut self, expr: &'b Expr) { fn visit_expr(&mut self, expr: &'b Expr) {
match expr { match expr {
Expr::Name(ast::ExprName { id, .. }) => { Expr::Name(ast::ExprName { id, .. }) => {
if includes_arg_name(id, self.arguments) { if includes_arg_name(id, self.parameters) {
self.uses_args = true; self.uses_args = true;
} }
} }
@ -55,7 +55,7 @@ fn check_patch_call(
} }
let ast::ExprLambda { let ast::ExprLambda {
args, parameters,
body, body,
range: _, range: _,
} = CallArguments::new(args, keywords) } = CallArguments::new(args, keywords)
@ -64,7 +64,7 @@ fn check_patch_call(
// Walk the lambda body. // Walk the lambda body.
let mut visitor = LambdaBodyVisitor { let mut visitor = LambdaBodyVisitor {
arguments: args, parameters,
uses_args: false, uses_args: false,
}; };
visitor.visit_expr(body); visitor.visit_expr(body);

View File

@ -46,13 +46,13 @@ impl<'a> Visitor<'a> for ReturnVisitor<'a> {
return; return;
} }
Stmt::FunctionDef(ast::StmtFunctionDef { Stmt::FunctionDef(ast::StmtFunctionDef {
args, parameters,
decorator_list, decorator_list,
returns, returns,
.. ..
}) })
| Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef { | Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef {
args, parameters,
decorator_list, decorator_list,
returns, returns,
.. ..
@ -66,7 +66,7 @@ impl<'a> Visitor<'a> for ReturnVisitor<'a> {
if let Some(returns) = returns { if let Some(returns) = returns {
visitor::walk_expr(self, returns); visitor::walk_expr(self, returns);
} }
visitor::walk_arguments(self, args); visitor::walk_parameters(self, parameters);
self.parents.pop(); self.parents.pop();
// But don't recurse into the body. // But don't recurse into the body.

View File

@ -2,7 +2,7 @@ use std::iter;
use regex::Regex; use regex::Regex;
use ruff_python_ast as ast; use ruff_python_ast as ast;
use ruff_python_ast::{Arg, Arguments}; use ruff_python_ast::{Parameter, Parameters};
use ruff_diagnostics::DiagnosticKind; use ruff_diagnostics::DiagnosticKind;
use ruff_diagnostics::{Diagnostic, Violation}; use ruff_diagnostics::{Diagnostic, Violation};
@ -215,26 +215,26 @@ impl Argumentable {
/// Check a plain function for unused arguments. /// Check a plain function for unused arguments.
fn function( fn function(
argumentable: Argumentable, argumentable: Argumentable,
args: &Arguments, parameters: &Parameters,
values: &Scope, values: &Scope,
semantic: &SemanticModel, semantic: &SemanticModel,
dummy_variable_rgx: &Regex, dummy_variable_rgx: &Regex,
ignore_variadic_names: bool, ignore_variadic_names: bool,
diagnostics: &mut Vec<Diagnostic>, diagnostics: &mut Vec<Diagnostic>,
) { ) {
let args = args let args = parameters
.posonlyargs .posonlyargs
.iter() .iter()
.chain(&args.args) .chain(&parameters.args)
.chain(&args.kwonlyargs) .chain(&parameters.kwonlyargs)
.map(|arg_with_default| &arg_with_default.def) .map(|parameter_with_default| &parameter_with_default.def)
.chain( .chain(
iter::once::<Option<&Arg>>(args.vararg.as_deref()) iter::once::<Option<&Parameter>>(parameters.vararg.as_deref())
.flatten() .flatten()
.skip(usize::from(ignore_variadic_names)), .skip(usize::from(ignore_variadic_names)),
) )
.chain( .chain(
iter::once::<Option<&Arg>>(args.kwarg.as_deref()) iter::once::<Option<&Parameter>>(parameters.kwarg.as_deref())
.flatten() .flatten()
.skip(usize::from(ignore_variadic_names)), .skip(usize::from(ignore_variadic_names)),
); );
@ -251,27 +251,27 @@ fn function(
/// Check a method for unused arguments. /// Check a method for unused arguments.
fn method( fn method(
argumentable: Argumentable, argumentable: Argumentable,
args: &Arguments, parameters: &Parameters,
values: &Scope, values: &Scope,
semantic: &SemanticModel, semantic: &SemanticModel,
dummy_variable_rgx: &Regex, dummy_variable_rgx: &Regex,
ignore_variadic_names: bool, ignore_variadic_names: bool,
diagnostics: &mut Vec<Diagnostic>, diagnostics: &mut Vec<Diagnostic>,
) { ) {
let args = args let args = parameters
.posonlyargs .posonlyargs
.iter() .iter()
.chain(&args.args) .chain(&parameters.args)
.chain(&args.kwonlyargs) .chain(&parameters.kwonlyargs)
.skip(1) .skip(1)
.map(|arg_with_default| &arg_with_default.def) .map(|parameter_with_default| &parameter_with_default.def)
.chain( .chain(
iter::once::<Option<&Arg>>(args.vararg.as_deref()) iter::once::<Option<&Parameter>>(parameters.vararg.as_deref())
.flatten() .flatten()
.skip(usize::from(ignore_variadic_names)), .skip(usize::from(ignore_variadic_names)),
) )
.chain( .chain(
iter::once::<Option<&Arg>>(args.kwarg.as_deref()) iter::once::<Option<&Parameter>>(parameters.kwarg.as_deref())
.flatten() .flatten()
.skip(usize::from(ignore_variadic_names)), .skip(usize::from(ignore_variadic_names)),
); );
@ -287,13 +287,13 @@ fn method(
fn call<'a>( fn call<'a>(
argumentable: Argumentable, argumentable: Argumentable,
args: impl Iterator<Item = &'a Arg>, parameters: impl Iterator<Item = &'a Parameter>,
values: &Scope, values: &Scope,
semantic: &SemanticModel, semantic: &SemanticModel,
dummy_variable_rgx: &Regex, dummy_variable_rgx: &Regex,
diagnostics: &mut Vec<Diagnostic>, diagnostics: &mut Vec<Diagnostic>,
) { ) {
diagnostics.extend(args.filter_map(|arg| { diagnostics.extend(parameters.filter_map(|arg| {
let binding = values let binding = values
.get(arg.arg.as_str()) .get(arg.arg.as_str())
.map(|binding_id| semantic.binding(binding_id))?; .map(|binding_id| semantic.binding(binding_id))?;
@ -324,14 +324,14 @@ pub(crate) fn unused_arguments(
match &scope.kind { match &scope.kind {
ScopeKind::Function(ast::StmtFunctionDef { ScopeKind::Function(ast::StmtFunctionDef {
name, name,
args, parameters,
body, body,
decorator_list, decorator_list,
.. ..
}) })
| ScopeKind::AsyncFunction(ast::StmtAsyncFunctionDef { | ScopeKind::AsyncFunction(ast::StmtAsyncFunctionDef {
name, name,
args, parameters,
body, body,
decorator_list, decorator_list,
.. ..
@ -350,7 +350,7 @@ pub(crate) fn unused_arguments(
{ {
function( function(
Argumentable::Function, Argumentable::Function,
args, parameters,
scope, scope,
checker.semantic(), checker.semantic(),
&checker.settings.dummy_variable_rgx, &checker.settings.dummy_variable_rgx,
@ -375,7 +375,7 @@ pub(crate) fn unused_arguments(
{ {
method( method(
Argumentable::Method, Argumentable::Method,
args, parameters,
scope, scope,
checker.semantic(), checker.semantic(),
&checker.settings.dummy_variable_rgx, &checker.settings.dummy_variable_rgx,
@ -400,7 +400,7 @@ pub(crate) fn unused_arguments(
{ {
method( method(
Argumentable::ClassMethod, Argumentable::ClassMethod,
args, parameters,
scope, scope,
checker.semantic(), checker.semantic(),
&checker.settings.dummy_variable_rgx, &checker.settings.dummy_variable_rgx,
@ -425,7 +425,7 @@ pub(crate) fn unused_arguments(
{ {
function( function(
Argumentable::StaticMethod, Argumentable::StaticMethod,
args, parameters,
scope, scope,
checker.semantic(), checker.semantic(),
&checker.settings.dummy_variable_rgx, &checker.settings.dummy_variable_rgx,
@ -439,11 +439,11 @@ pub(crate) fn unused_arguments(
} }
} }
} }
ScopeKind::Lambda(ast::ExprLambda { args, .. }) => { ScopeKind::Lambda(ast::ExprLambda { parameters, .. }) => {
if checker.enabled(Argumentable::Lambda.rule_code()) { if checker.enabled(Argumentable::Lambda.rule_code()) {
function( function(
Argumentable::Lambda, Argumentable::Lambda,
args, parameters,
scope, scope,
checker.semantic(), checker.semantic(),
&checker.settings.dummy_variable_rgx, &checker.settings.dummy_variable_rgx,

View File

@ -1,4 +1,4 @@
use ruff_python_ast::{Arg, Ranged}; use ruff_python_ast::{Parameter, 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};
@ -50,7 +50,7 @@ impl Violation for InvalidArgumentName {
/// N803 /// N803
pub(crate) fn invalid_argument_name( pub(crate) fn invalid_argument_name(
name: &str, name: &str,
arg: &Arg, parameter: &Parameter,
ignore_names: &[IdentifierPattern], ignore_names: &[IdentifierPattern],
) -> Option<Diagnostic> { ) -> Option<Diagnostic> {
if ignore_names if ignore_names
@ -64,7 +64,7 @@ pub(crate) fn invalid_argument_name(
InvalidArgumentName { InvalidArgumentName {
name: name.to_string(), name: name.to_string(),
}, },
arg.range(), parameter.range(),
)); ));
} }
None None

View File

@ -1,4 +1,4 @@
use ruff_python_ast::{ArgWithDefault, Arguments, Decorator, Ranged}; use ruff_python_ast::{Decorator, ParameterWithDefault, Parameters, 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};
@ -59,7 +59,7 @@ pub(crate) fn invalid_first_argument_name_for_class_method(
scope: &Scope, scope: &Scope,
name: &str, name: &str,
decorator_list: &[Decorator], decorator_list: &[Decorator],
args: &Arguments, parameters: &Parameters,
) -> Option<Diagnostic> { ) -> Option<Diagnostic> {
if !matches!( if !matches!(
function_type::classify( function_type::classify(
@ -74,11 +74,14 @@ pub(crate) fn invalid_first_argument_name_for_class_method(
) { ) {
return None; return None;
} }
if let Some(ArgWithDefault { if let Some(ParameterWithDefault {
def, def,
default: _, default: _,
range: _, range: _,
}) = args.posonlyargs.first().or_else(|| args.args.first()) }) = parameters
.posonlyargs
.first()
.or_else(|| parameters.args.first())
{ {
if &def.arg != "cls" { if &def.arg != "cls" {
if checker if checker

View File

@ -1,4 +1,4 @@
use ruff_python_ast::{Arguments, Decorator, Ranged}; use ruff_python_ast::{Decorator, Parameters, 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};
@ -57,7 +57,7 @@ pub(crate) fn invalid_first_argument_name_for_method(
scope: &Scope, scope: &Scope,
name: &str, name: &str,
decorator_list: &[Decorator], decorator_list: &[Decorator],
args: &Arguments, parameters: &Parameters,
) -> Option<Diagnostic> { ) -> Option<Diagnostic> {
if !matches!( if !matches!(
function_type::classify( function_type::classify(
@ -72,7 +72,10 @@ pub(crate) fn invalid_first_argument_name_for_method(
) { ) {
return None; return None;
} }
let arg = args.posonlyargs.first().or_else(|| args.args.first())?; let arg = parameters
.posonlyargs
.first()
.or_else(|| parameters.args.first())?;
if &arg.def.arg == "self" { if &arg.def.arg == "self" {
return None; return None;
} }

View File

@ -1,5 +1,6 @@
use ruff_python_ast::{ use ruff_python_ast::{
self as ast, Arg, ArgWithDefault, Arguments, Constant, Expr, Identifier, Ranged, Stmt, self as ast, Constant, Expr, Identifier, Parameter, ParameterWithDefault, Parameters, Ranged,
Stmt,
}; };
use ruff_text_size::TextRange; use ruff_text_size::TextRange;
@ -67,7 +68,10 @@ pub(crate) fn lambda_assignment(
return; return;
}; };
let Expr::Lambda(ast::ExprLambda { args, body, .. }) = value else { let Expr::Lambda(ast::ExprLambda {
parameters, body, ..
}) = value
else {
return; return;
}; };
@ -87,7 +91,7 @@ pub(crate) fn lambda_assignment(
let mut indented = String::new(); let mut indented = String::new();
for (idx, line) in function( for (idx, line) in function(
id, id,
args, parameters,
body, body,
annotation, annotation,
checker.semantic(), checker.semantic(),
@ -173,7 +177,7 @@ fn extract_types(annotation: &Expr, semantic: &SemanticModel) -> Option<(Vec<Exp
fn function( fn function(
name: &str, name: &str,
args: &Arguments, parameters: &Parameters,
body: &Expr, body: &Expr,
annotation: Option<&Expr>, annotation: Option<&Expr>,
semantic: &SemanticModel, semantic: &SemanticModel,
@ -187,40 +191,40 @@ fn function(
if let Some((arg_types, return_type)) = extract_types(annotation, semantic) { if let Some((arg_types, return_type)) = extract_types(annotation, semantic) {
// A `lambda` expression can only have positional and positional-only // A `lambda` expression can only have positional and positional-only
// arguments. The order is always positional-only first, then positional. // arguments. The order is always positional-only first, then positional.
let new_posonlyargs = args let new_posonlyargs = parameters
.posonlyargs .posonlyargs
.iter() .iter()
.enumerate() .enumerate()
.map(|(idx, arg_with_default)| ArgWithDefault { .map(|(idx, parameter)| ParameterWithDefault {
def: Arg { def: Parameter {
annotation: arg_types annotation: arg_types
.get(idx) .get(idx)
.map(|arg_type| Box::new(arg_type.clone())), .map(|arg_type| Box::new(arg_type.clone())),
..arg_with_default.def.clone() ..parameter.def.clone()
}, },
..arg_with_default.clone() ..parameter.clone()
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let new_args = args let new_args = parameters
.args .args
.iter() .iter()
.enumerate() .enumerate()
.map(|(idx, arg_with_default)| ArgWithDefault { .map(|(idx, parameter)| ParameterWithDefault {
def: Arg { def: Parameter {
annotation: arg_types annotation: arg_types
.get(idx + new_posonlyargs.len()) .get(idx + new_posonlyargs.len())
.map(|arg_type| Box::new(arg_type.clone())), .map(|arg_type| Box::new(arg_type.clone())),
..arg_with_default.def.clone() ..parameter.def.clone()
}, },
..arg_with_default.clone() ..parameter.clone()
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let func = Stmt::FunctionDef(ast::StmtFunctionDef { let func = Stmt::FunctionDef(ast::StmtFunctionDef {
name: Identifier::new(name.to_string(), TextRange::default()), name: Identifier::new(name.to_string(), TextRange::default()),
args: Box::new(Arguments { parameters: Box::new(Parameters {
posonlyargs: new_posonlyargs, posonlyargs: new_posonlyargs,
args: new_args, args: new_args,
..args.clone() ..parameters.clone()
}), }),
body: vec![body], body: vec![body],
decorator_list: vec![], decorator_list: vec![],
@ -233,7 +237,7 @@ fn function(
} }
let func = Stmt::FunctionDef(ast::StmtFunctionDef { let func = Stmt::FunctionDef(ast::StmtFunctionDef {
name: Identifier::new(name.to_string(), TextRange::default()), name: Identifier::new(name.to_string(), TextRange::default()),
args: Box::new(args.clone()), parameters: Box::new(parameters.clone()),
body: vec![body], body: vec![body],
decorator_list: vec![], decorator_list: vec![],
returns: None, returns: None,

View File

@ -1,7 +1,7 @@
use itertools::Itertools; use itertools::Itertools;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use ruff_python_ast::{self as ast, ArgWithDefault, Stmt}; use ruff_python_ast::{self as ast, ParameterWithDefault, Stmt};
use ruff_text_size::{TextLen, TextRange, TextSize}; use ruff_text_size::{TextLen, TextRange, TextSize};
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
@ -1726,27 +1726,23 @@ fn missing_args(checker: &mut Checker, docstring: &Docstring, docstrings_args: &
return; return;
}; };
let (Stmt::FunctionDef(ast::StmtFunctionDef { let (Stmt::FunctionDef(ast::StmtFunctionDef { parameters, .. })
args: arguments, .. | Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef { parameters, .. })) = stmt
})
| Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef {
args: arguments, ..
})) = stmt
else { else {
return; return;
}; };
// Look for arguments that weren't included in the docstring. // Look for arguments that weren't included in the docstring.
let mut missing_arg_names: FxHashSet<String> = FxHashSet::default(); let mut missing_arg_names: FxHashSet<String> = FxHashSet::default();
for ArgWithDefault { for ParameterWithDefault {
def, def,
default: _, default: _,
range: _, range: _,
} in arguments } in parameters
.posonlyargs .posonlyargs
.iter() .iter()
.chain(&arguments.args) .chain(&parameters.args)
.chain(&arguments.kwonlyargs) .chain(&parameters.kwonlyargs)
.skip( .skip(
// If this is a non-static method, skip `cls` or `self`. // If this is a non-static method, skip `cls` or `self`.
usize::from( usize::from(
@ -1763,7 +1759,7 @@ fn missing_args(checker: &mut Checker, docstring: &Docstring, docstrings_args: &
// Check specifically for `vararg` and `kwarg`, which can be prefixed with a // Check specifically for `vararg` and `kwarg`, which can be prefixed with a
// single or double star, respectively. // single or double star, respectively.
if let Some(arg) = &arguments.vararg { if let Some(arg) = &parameters.vararg {
let arg_name = arg.arg.as_str(); let arg_name = arg.arg.as_str();
let starred_arg_name = format!("*{arg_name}"); let starred_arg_name = format!("*{arg_name}");
if !arg_name.starts_with('_') if !arg_name.starts_with('_')
@ -1773,7 +1769,7 @@ fn missing_args(checker: &mut Checker, docstring: &Docstring, docstrings_args: &
missing_arg_names.insert(starred_arg_name); missing_arg_names.insert(starred_arg_name);
} }
} }
if let Some(arg) = &arguments.kwarg { if let Some(arg) = &parameters.kwarg {
let arg_name = arg.arg.as_str(); let arg_name = arg.arg.as_str();
let starred_arg_name = format!("**{arg_name}"); let starred_arg_name = format!("**{arg_name}");
if !arg_name.starts_with('_') if !arg_name.starts_with('_')

View File

@ -1,4 +1,4 @@
use ruff_python_ast::{self as ast, Arguments, Decorator, Expr, Stmt}; use ruff_python_ast::{self as ast, Decorator, Expr, Parameters, Stmt};
use ruff_diagnostics::{Diagnostic, Violation}; use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
@ -51,7 +51,7 @@ pub(crate) fn property_with_parameters(
checker: &mut Checker, checker: &mut Checker,
stmt: &Stmt, stmt: &Stmt,
decorator_list: &[Decorator], decorator_list: &[Decorator],
args: &Arguments, parameters: &Parameters,
) { ) {
if !decorator_list if !decorator_list
.iter() .iter()
@ -59,11 +59,11 @@ pub(crate) fn property_with_parameters(
{ {
return; return;
} }
if args if parameters
.posonlyargs .posonlyargs
.iter() .iter()
.chain(&args.args) .chain(&parameters.args)
.chain(&args.kwonlyargs) .chain(&parameters.kwonlyargs)
.count() .count()
> 1 > 1
&& checker.semantic().is_builtin("property") && checker.semantic().is_builtin("property")

View File

@ -1,4 +1,4 @@
use ruff_python_ast::{Arguments, Stmt}; use ruff_python_ast::{Parameters, Stmt};
use ruff_diagnostics::{Diagnostic, Violation}; use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
@ -58,12 +58,12 @@ impl Violation for TooManyArguments {
} }
/// PLR0913 /// PLR0913
pub(crate) fn too_many_arguments(checker: &mut Checker, arguments: &Arguments, stmt: &Stmt) { pub(crate) fn too_many_arguments(checker: &mut Checker, parameters: &Parameters, stmt: &Stmt) {
let num_arguments = arguments let num_arguments = parameters
.args .args
.iter() .iter()
.chain(&arguments.kwonlyargs) .chain(&parameters.kwonlyargs)
.chain(&arguments.posonlyargs) .chain(&parameters.posonlyargs)
.filter(|arg| !checker.settings.dummy_variable_rgx.is_match(&arg.def.arg)) .filter(|arg| !checker.settings.dummy_variable_rgx.is_match(&arg.def.arg))
.count(); .count();
if num_arguments > checker.settings.pylint.max_args { if num_arguments > checker.settings.pylint.max_args {

View File

@ -1,6 +1,6 @@
use std::cmp::Ordering; use std::cmp::Ordering;
use ruff_python_ast::{Arguments, Decorator, Stmt}; use ruff_python_ast::{Decorator, Parameters, Stmt};
use ruff_diagnostics::{Diagnostic, Violation}; use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
@ -141,24 +141,31 @@ pub(crate) fn unexpected_special_method_signature(
stmt: &Stmt, stmt: &Stmt,
name: &str, name: &str,
decorator_list: &[Decorator], decorator_list: &[Decorator],
args: &Arguments, parameters: &Parameters,
) { ) {
if !checker.semantic().scope().kind.is_class() { if !checker.semantic().scope().kind.is_class() {
return; return;
} }
// Ignore methods with positional-only or keyword-only parameters, or variadic parameters. // Ignore methods with positional-only or keyword-only parameters, or variadic parameters.
if !args.posonlyargs.is_empty() || !args.kwonlyargs.is_empty() || args.kwarg.is_some() { if !parameters.posonlyargs.is_empty()
|| !parameters.kwonlyargs.is_empty()
|| parameters.kwarg.is_some()
{
return; return;
} }
// Method has no parameter, will be caught by no-method-argument (E0211/N805). // Method has no parameter, will be caught by no-method-argument (E0211/N805).
if args.args.is_empty() && args.vararg.is_none() { if parameters.args.is_empty() && parameters.vararg.is_none() {
return; return;
} }
let actual_params = args.args.len(); let actual_params = parameters.args.len();
let mandatory_params = args.args.iter().filter(|arg| arg.default.is_none()).count(); let mandatory_params = parameters
.args
.iter()
.filter(|arg| arg.default.is_none())
.count();
let Some(expected_params) = let Some(expected_params) =
ExpectedParams::from_method(name, is_staticmethod(decorator_list, checker.semantic())) ExpectedParams::from_method(name, is_staticmethod(decorator_list, checker.semantic()))
@ -171,12 +178,12 @@ pub(crate) fn unexpected_special_method_signature(
if mandatory_params >= min { if mandatory_params >= min {
mandatory_params <= max mandatory_params <= max
} else { } else {
args.vararg.is_some() || actual_params <= max parameters.vararg.is_some() || actual_params <= max
} }
} }
ExpectedParams::Fixed(expected) => match expected.cmp(&mandatory_params) { ExpectedParams::Fixed(expected) => match expected.cmp(&mandatory_params) {
Ordering::Less => false, Ordering::Less => false,
Ordering::Greater => args.vararg.is_some() || actual_params >= expected, Ordering::Greater => parameters.vararg.is_some() || actual_params >= expected,
Ordering::Equal => true, Ordering::Equal => true,
}, },
}; };

View File

@ -1,4 +1,4 @@
use ruff_python_ast::{self as ast, Arg, ArgWithDefault, Expr, Ranged, Stmt}; use ruff_python_ast::{self as ast, Expr, Parameter, ParameterWithDefault, Ranged, Stmt};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Fix}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Fix};
use ruff_macros::{derive_message_formats, violation}; use ruff_macros::{derive_message_formats, violation};
@ -98,19 +98,20 @@ pub(crate) fn super_call_with_parameters(
// Find the enclosing function definition (if any). // Find the enclosing function definition (if any).
let Some(Stmt::FunctionDef(ast::StmtFunctionDef { let Some(Stmt::FunctionDef(ast::StmtFunctionDef {
args: parent_args, .. parameters: parent_parameters,
..
})) = parents.find(|stmt| stmt.is_function_def_stmt()) })) = parents.find(|stmt| stmt.is_function_def_stmt())
else { else {
return; return;
}; };
// Extract the name of the first argument to the enclosing function. // Extract the name of the first argument to the enclosing function.
let Some(ArgWithDefault { let Some(ParameterWithDefault {
def: Arg { def: Parameter {
arg: parent_arg, .. arg: parent_arg, ..
}, },
.. ..
}) = parent_args.args.first() }) = parent_parameters.args.first()
else { else {
return; return;
}; };

View File

@ -1,7 +1,9 @@
use std::fmt; use std::fmt;
use anyhow::Result; use anyhow::Result;
use ruff_python_ast::{self as ast, ArgWithDefault, Arguments, Constant, Expr, Operator, Ranged}; use ruff_python_ast::{
self as ast, Constant, Expr, Operator, ParameterWithDefault, Parameters, Ranged,
};
use ruff_text_size::TextRange; use ruff_text_size::TextRange;
use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation}; use ruff_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation};
@ -165,16 +167,16 @@ fn generate_fix(checker: &Checker, conversion_type: ConversionType, expr: &Expr)
} }
/// RUF013 /// RUF013
pub(crate) fn implicit_optional(checker: &mut Checker, arguments: &Arguments) { pub(crate) fn implicit_optional(checker: &mut Checker, parameters: &Parameters) {
for ArgWithDefault { for ParameterWithDefault {
def, def,
default, default,
range: _, range: _,
} in arguments } in parameters
.posonlyargs .posonlyargs
.iter() .iter()
.chain(&arguments.args) .chain(&parameters.args)
.chain(&arguments.kwonlyargs) .chain(&parameters.kwonlyargs)
{ {
let Some(default) = default else { continue }; let Some(default) = default else { continue };
if !is_const_none(default) { if !is_const_none(default) {

View File

@ -340,46 +340,46 @@ impl<'a> From<&'a ast::Constant> for ComparableConstant<'a> {
} }
#[derive(Debug, PartialEq, Eq, Hash)] #[derive(Debug, PartialEq, Eq, Hash)]
pub struct ComparableArguments<'a> { pub struct ComparableParameters<'a> {
posonlyargs: Vec<ComparableArgWithDefault<'a>>, posonlyargs: Vec<ComparableParameterWithDefault<'a>>,
args: Vec<ComparableArgWithDefault<'a>>, args: Vec<ComparableParameterWithDefault<'a>>,
vararg: Option<ComparableArg<'a>>, vararg: Option<ComparableParameter<'a>>,
kwonlyargs: Vec<ComparableArgWithDefault<'a>>, kwonlyargs: Vec<ComparableParameterWithDefault<'a>>,
kwarg: Option<ComparableArg<'a>>, kwarg: Option<ComparableParameter<'a>>,
} }
impl<'a> From<&'a ast::Arguments> for ComparableArguments<'a> { impl<'a> From<&'a ast::Parameters> for ComparableParameters<'a> {
fn from(arguments: &'a ast::Arguments) -> Self { fn from(parameters: &'a ast::Parameters) -> Self {
Self { Self {
posonlyargs: arguments.posonlyargs.iter().map(Into::into).collect(), posonlyargs: parameters.posonlyargs.iter().map(Into::into).collect(),
args: arguments.args.iter().map(Into::into).collect(), args: parameters.args.iter().map(Into::into).collect(),
vararg: arguments.vararg.as_ref().map(Into::into), vararg: parameters.vararg.as_ref().map(Into::into),
kwonlyargs: arguments.kwonlyargs.iter().map(Into::into).collect(), kwonlyargs: parameters.kwonlyargs.iter().map(Into::into).collect(),
kwarg: arguments.kwarg.as_ref().map(Into::into), kwarg: parameters.kwarg.as_ref().map(Into::into),
} }
} }
} }
impl<'a> From<&'a Box<ast::Arguments>> for ComparableArguments<'a> { impl<'a> From<&'a Box<ast::Parameters>> for ComparableParameters<'a> {
fn from(arguments: &'a Box<ast::Arguments>) -> Self { fn from(parameters: &'a Box<ast::Parameters>) -> Self {
(arguments.as_ref()).into() (parameters.as_ref()).into()
} }
} }
impl<'a> From<&'a Box<ast::Arg>> for ComparableArg<'a> { impl<'a> From<&'a Box<ast::Parameter>> for ComparableParameter<'a> {
fn from(arg: &'a Box<ast::Arg>) -> Self { fn from(arg: &'a Box<ast::Parameter>) -> Self {
(arg.as_ref()).into() (arg.as_ref()).into()
} }
} }
#[derive(Debug, PartialEq, Eq, Hash)] #[derive(Debug, PartialEq, Eq, Hash)]
pub struct ComparableArg<'a> { pub struct ComparableParameter<'a> {
arg: &'a str, arg: &'a str,
annotation: Option<Box<ComparableExpr<'a>>>, annotation: Option<Box<ComparableExpr<'a>>>,
} }
impl<'a> From<&'a ast::Arg> for ComparableArg<'a> { impl<'a> From<&'a ast::Parameter> for ComparableParameter<'a> {
fn from(arg: &'a ast::Arg) -> Self { fn from(arg: &'a ast::Parameter) -> Self {
Self { Self {
arg: arg.arg.as_str(), arg: arg.arg.as_str(),
annotation: arg.annotation.as_ref().map(Into::into), annotation: arg.annotation.as_ref().map(Into::into),
@ -388,13 +388,13 @@ impl<'a> From<&'a ast::Arg> for ComparableArg<'a> {
} }
#[derive(Debug, PartialEq, Eq, Hash)] #[derive(Debug, PartialEq, Eq, Hash)]
pub struct ComparableArgWithDefault<'a> { pub struct ComparableParameterWithDefault<'a> {
def: ComparableArg<'a>, def: ComparableParameter<'a>,
default: Option<ComparableExpr<'a>>, default: Option<ComparableExpr<'a>>,
} }
impl<'a> From<&'a ast::ArgWithDefault> for ComparableArgWithDefault<'a> { impl<'a> From<&'a ast::ParameterWithDefault> for ComparableParameterWithDefault<'a> {
fn from(arg: &'a ast::ArgWithDefault) -> Self { fn from(arg: &'a ast::ParameterWithDefault) -> Self {
Self { Self {
def: (&arg.def).into(), def: (&arg.def).into(),
default: arg.default.as_ref().map(Into::into), default: arg.default.as_ref().map(Into::into),
@ -511,7 +511,7 @@ pub struct ExprUnaryOp<'a> {
#[derive(Debug, PartialEq, Eq, Hash)] #[derive(Debug, PartialEq, Eq, Hash)]
pub struct ExprLambda<'a> { pub struct ExprLambda<'a> {
args: ComparableArguments<'a>, parameters: ComparableParameters<'a>,
body: Box<ComparableExpr<'a>>, body: Box<ComparableExpr<'a>>,
} }
@ -739,11 +739,11 @@ impl<'a> From<&'a ast::Expr> for ComparableExpr<'a> {
operand: operand.into(), operand: operand.into(),
}), }),
ast::Expr::Lambda(ast::ExprLambda { ast::Expr::Lambda(ast::ExprLambda {
args, parameters,
body, body,
range: _range, range: _range,
}) => Self::Lambda(ExprLambda { }) => Self::Lambda(ExprLambda {
args: (args.as_ref()).into(), parameters: (parameters.as_ref()).into(),
body: body.into(), body: body.into(),
}), }),
ast::Expr::IfExp(ast::ExprIfExp { ast::Expr::IfExp(ast::ExprIfExp {
@ -948,7 +948,7 @@ impl<'a> From<&'a ast::Expr> for ComparableExpr<'a> {
#[derive(Debug, PartialEq, Eq, Hash)] #[derive(Debug, PartialEq, Eq, Hash)]
pub struct StmtFunctionDef<'a> { pub struct StmtFunctionDef<'a> {
name: &'a str, name: &'a str,
args: ComparableArguments<'a>, parameters: ComparableParameters<'a>,
body: Vec<ComparableStmt<'a>>, body: Vec<ComparableStmt<'a>>,
decorator_list: Vec<ComparableDecorator<'a>>, decorator_list: Vec<ComparableDecorator<'a>>,
type_params: Vec<ComparableTypeParam<'a>>, type_params: Vec<ComparableTypeParam<'a>>,
@ -958,7 +958,7 @@ pub struct StmtFunctionDef<'a> {
#[derive(Debug, PartialEq, Eq, Hash)] #[derive(Debug, PartialEq, Eq, Hash)]
pub struct StmtAsyncFunctionDef<'a> { pub struct StmtAsyncFunctionDef<'a> {
name: &'a str, name: &'a str,
args: ComparableArguments<'a>, parameters: ComparableParameters<'a>,
body: Vec<ComparableStmt<'a>>, body: Vec<ComparableStmt<'a>>,
decorator_list: Vec<ComparableDecorator<'a>>, decorator_list: Vec<ComparableDecorator<'a>>,
type_params: Vec<ComparableTypeParam<'a>>, type_params: Vec<ComparableTypeParam<'a>>,
@ -1208,7 +1208,7 @@ impl<'a> From<&'a ast::Stmt> for ComparableStmt<'a> {
match stmt { match stmt {
ast::Stmt::FunctionDef(ast::StmtFunctionDef { ast::Stmt::FunctionDef(ast::StmtFunctionDef {
name, name,
args, parameters,
body, body,
decorator_list, decorator_list,
returns, returns,
@ -1216,7 +1216,7 @@ impl<'a> From<&'a ast::Stmt> for ComparableStmt<'a> {
range: _range, range: _range,
}) => Self::FunctionDef(StmtFunctionDef { }) => Self::FunctionDef(StmtFunctionDef {
name: name.as_str(), name: name.as_str(),
args: args.into(), parameters: parameters.into(),
body: body.iter().map(Into::into).collect(), body: body.iter().map(Into::into).collect(),
decorator_list: decorator_list.iter().map(Into::into).collect(), decorator_list: decorator_list.iter().map(Into::into).collect(),
returns: returns.as_ref().map(Into::into), returns: returns.as_ref().map(Into::into),
@ -1224,7 +1224,7 @@ impl<'a> From<&'a ast::Stmt> for ComparableStmt<'a> {
}), }),
ast::Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef { ast::Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef {
name, name,
args, parameters,
body, body,
decorator_list, decorator_list,
returns, returns,
@ -1232,7 +1232,7 @@ impl<'a> From<&'a ast::Stmt> for ComparableStmt<'a> {
range: _range, range: _range,
}) => Self::AsyncFunctionDef(StmtAsyncFunctionDef { }) => Self::AsyncFunctionDef(StmtAsyncFunctionDef {
name: name.as_str(), name: name.as_str(),
args: args.into(), parameters: parameters.into(),
body: body.iter().map(Into::into).collect(), body: body.iter().map(Into::into).collect(),
decorator_list: decorator_list.iter().map(Into::into).collect(), decorator_list: decorator_list.iter().map(Into::into).collect(),
returns: returns.as_ref().map(Into::into), returns: returns.as_ref().map(Into::into),

View File

@ -1,6 +1,6 @@
use crate::node::AnyNodeRef; use crate::node::AnyNodeRef;
use crate::{ use crate::{
Arguments, Decorator, Expr, Identifier, Ranged, StmtAsyncFunctionDef, StmtFunctionDef, Suite, Decorator, Expr, Identifier, Parameters, Ranged, StmtAsyncFunctionDef, StmtFunctionDef, Suite,
}; };
use ruff_text_size::TextRange; use ruff_text_size::TextRange;
@ -49,10 +49,10 @@ impl<'a> AnyFunctionDefinition<'a> {
} }
/// Returns the function arguments (parameters). /// Returns the function arguments (parameters).
pub fn arguments(self) -> &'a Arguments { pub fn arguments(self) -> &'a Parameters {
match self { match self {
Self::FunctionDefinition(definition) => definition.args.as_ref(), Self::FunctionDefinition(definition) => definition.parameters.as_ref(),
Self::AsyncFunctionDefinition(definition) => definition.args.as_ref(), Self::AsyncFunctionDefinition(definition) => definition.parameters.as_ref(),
} }
} }

View File

@ -2,7 +2,7 @@ use std::borrow::Cow;
use std::path::Path; use std::path::Path;
use crate::{ use crate::{
self as ast, Arguments, Constant, ExceptHandler, Expr, Keyword, MatchCase, Pattern, Ranged, self as ast, Constant, ExceptHandler, Expr, Keyword, MatchCase, Parameters, Pattern, Ranged,
Stmt, TypeParam, Stmt, TypeParam,
}; };
use num_traits::Zero; use num_traits::Zero;
@ -347,40 +347,43 @@ where
{ {
match stmt { match stmt {
Stmt::FunctionDef(ast::StmtFunctionDef { Stmt::FunctionDef(ast::StmtFunctionDef {
args, parameters,
body, body,
decorator_list, decorator_list,
returns, returns,
.. ..
}) })
| Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef { | Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef {
args, parameters,
body, body,
decorator_list, decorator_list,
returns, returns,
.. ..
}) => { }) => {
args.posonlyargs parameters
.posonlyargs
.iter() .iter()
.chain(args.args.iter().chain(args.kwonlyargs.iter())) .chain(parameters.args.iter().chain(parameters.kwonlyargs.iter()))
.any(|arg_with_default| { .any(|parameter| {
arg_with_default parameter
.default .default
.as_ref() .as_ref()
.is_some_and(|expr| any_over_expr(expr, func)) .is_some_and(|expr| any_over_expr(expr, func))
|| arg_with_default || parameter
.def .def
.annotation .annotation
.as_ref() .as_ref()
.is_some_and(|expr| any_over_expr(expr, func)) .is_some_and(|expr| any_over_expr(expr, func))
}) })
|| args.vararg.as_ref().is_some_and(|arg| { || parameters.vararg.as_ref().is_some_and(|parameter| {
arg.annotation parameter
.annotation
.as_ref() .as_ref()
.is_some_and(|expr| any_over_expr(expr, func)) .is_some_and(|expr| any_over_expr(expr, func))
}) })
|| args.kwarg.as_ref().is_some_and(|arg| { || parameters.kwarg.as_ref().is_some_and(|parameter| {
arg.annotation parameter
.annotation
.as_ref() .as_ref()
.is_some_and(|expr| any_over_expr(expr, func)) .is_some_and(|expr| any_over_expr(expr, func))
}) })
@ -709,23 +712,23 @@ pub fn extract_handled_exceptions(handlers: &[ExceptHandler]) -> Vec<&Expr> {
handled_exceptions handled_exceptions
} }
/// Returns `true` if the given name is included in the given [`Arguments`]. /// Returns `true` if the given name is included in the given [`Parameters`].
pub fn includes_arg_name(name: &str, arguments: &Arguments) -> bool { pub fn includes_arg_name(name: &str, parameters: &Parameters) -> bool {
if arguments if parameters
.posonlyargs .posonlyargs
.iter() .iter()
.chain(&arguments.args) .chain(&parameters.args)
.chain(&arguments.kwonlyargs) .chain(&parameters.kwonlyargs)
.any(|arg| arg.def.arg.as_str() == name) .any(|arg| arg.def.arg.as_str() == name)
{ {
return true; return true;
} }
if let Some(arg) = &arguments.vararg { if let Some(arg) = &parameters.vararg {
if arg.arg.as_str() == name { if arg.arg.as_str() == name {
return true; return true;
} }
} }
if let Some(arg) = &arguments.kwarg { if let Some(arg) = &parameters.kwarg {
if arg.arg.as_str() == name { if arg.arg.as_str() == name {
return true; return true;
} }

View File

@ -10,7 +10,7 @@
//! //!
//! This module can be used to identify the [`TextRange`] of the `except` token. //! This module can be used to identify the [`TextRange`] of the `except` token.
use crate::{self as ast, Alias, Arg, ArgWithDefault, ExceptHandler, Ranged, Stmt}; use crate::{self as ast, Alias, ExceptHandler, Parameter, ParameterWithDefault, Ranged, Stmt};
use ruff_text_size::{TextLen, TextRange, TextSize}; use ruff_text_size::{TextLen, TextRange, TextSize};
use ruff_python_trivia::{is_python_whitespace, Cursor}; use ruff_python_trivia::{is_python_whitespace, Cursor};
@ -38,8 +38,8 @@ impl Identifier for Stmt {
} }
} }
impl Identifier for Arg { impl Identifier for Parameter {
/// Return the [`TextRange`] for the identifier defining an [`Arg`]. /// Return the [`TextRange`] for the identifier defining an [`Parameter`].
/// ///
/// For example, return the range of `x` in: /// For example, return the range of `x` in:
/// ```python /// ```python
@ -51,8 +51,8 @@ impl Identifier for Arg {
} }
} }
impl Identifier for ArgWithDefault { impl Identifier for ParameterWithDefault {
/// Return the [`TextRange`] for the identifier defining an [`ArgWithDefault`]. /// Return the [`TextRange`] for the identifier defining an [`ParameterWithDefault`].
/// ///
/// For example, return the range of `x` in: /// For example, return the range of `x` in:
/// ```python /// ```python

View File

@ -1,7 +1,7 @@
use crate::{ use crate::{
self as ast, Alias, Arg, ArgWithDefault, Arguments, Comprehension, Decorator, ExceptHandler, self as ast, Alias, Comprehension, Decorator, ExceptHandler, Expr, Keyword, MatchCase, Mod,
Expr, Keyword, MatchCase, Mod, Pattern, Ranged, Stmt, TypeParam, TypeParamParamSpec, Parameter, ParameterWithDefault, Parameters, Pattern, Ranged, Stmt, TypeParam,
TypeParamTypeVar, TypeParamTypeVarTuple, WithItem, TypeParamParamSpec, TypeParamTypeVar, TypeParamTypeVarTuple, WithItem,
}; };
use ruff_text_size::TextRange; use ruff_text_size::TextRange;
use std::ptr::NonNull; use std::ptr::NonNull;
@ -90,9 +90,9 @@ pub enum AnyNode {
PatternMatchAs(ast::PatternMatchAs), PatternMatchAs(ast::PatternMatchAs),
PatternMatchOr(ast::PatternMatchOr), PatternMatchOr(ast::PatternMatchOr),
Comprehension(Comprehension), Comprehension(Comprehension),
Arguments(Arguments), Parameters(Parameters),
Arg(Arg), Parameter(Parameter),
ArgWithDefault(ArgWithDefault), ParameterWithDefault(ParameterWithDefault),
Keyword(Keyword), Keyword(Keyword),
Alias(Alias), Alias(Alias),
WithItem(WithItem), WithItem(WithItem),
@ -177,9 +177,9 @@ impl AnyNode {
| AnyNode::PatternMatchAs(_) | AnyNode::PatternMatchAs(_)
| AnyNode::PatternMatchOr(_) | AnyNode::PatternMatchOr(_)
| AnyNode::Comprehension(_) | AnyNode::Comprehension(_)
| AnyNode::Arguments(_) | AnyNode::Parameters(_)
| AnyNode::Arg(_) | AnyNode::Parameter(_)
| AnyNode::ArgWithDefault(_) | AnyNode::ParameterWithDefault(_)
| AnyNode::Keyword(_) | AnyNode::Keyword(_)
| AnyNode::Alias(_) | AnyNode::Alias(_)
| AnyNode::WithItem(_) | AnyNode::WithItem(_)
@ -264,9 +264,9 @@ impl AnyNode {
| AnyNode::PatternMatchAs(_) | AnyNode::PatternMatchAs(_)
| AnyNode::PatternMatchOr(_) | AnyNode::PatternMatchOr(_)
| AnyNode::Comprehension(_) | AnyNode::Comprehension(_)
| AnyNode::Arguments(_) | AnyNode::Parameters(_)
| AnyNode::Arg(_) | AnyNode::Parameter(_)
| AnyNode::ArgWithDefault(_) | AnyNode::ParameterWithDefault(_)
| AnyNode::Keyword(_) | AnyNode::Keyword(_)
| AnyNode::Alias(_) | AnyNode::Alias(_)
| AnyNode::WithItem(_) | AnyNode::WithItem(_)
@ -351,9 +351,9 @@ impl AnyNode {
| AnyNode::PatternMatchAs(_) | AnyNode::PatternMatchAs(_)
| AnyNode::PatternMatchOr(_) | AnyNode::PatternMatchOr(_)
| AnyNode::Comprehension(_) | AnyNode::Comprehension(_)
| AnyNode::Arguments(_) | AnyNode::Parameters(_)
| AnyNode::Arg(_) | AnyNode::Parameter(_)
| AnyNode::ArgWithDefault(_) | AnyNode::ParameterWithDefault(_)
| AnyNode::Keyword(_) | AnyNode::Keyword(_)
| AnyNode::Alias(_) | AnyNode::Alias(_)
| AnyNode::WithItem(_) | AnyNode::WithItem(_)
@ -438,9 +438,9 @@ impl AnyNode {
| AnyNode::ExprLineMagic(_) | AnyNode::ExprLineMagic(_)
| AnyNode::ExceptHandlerExceptHandler(_) | AnyNode::ExceptHandlerExceptHandler(_)
| AnyNode::Comprehension(_) | AnyNode::Comprehension(_)
| AnyNode::Arguments(_) | AnyNode::Parameters(_)
| AnyNode::Arg(_) | AnyNode::Parameter(_)
| AnyNode::ArgWithDefault(_) | AnyNode::ParameterWithDefault(_)
| AnyNode::Keyword(_) | AnyNode::Keyword(_)
| AnyNode::Alias(_) | AnyNode::Alias(_)
| AnyNode::WithItem(_) | AnyNode::WithItem(_)
@ -525,9 +525,9 @@ impl AnyNode {
| AnyNode::PatternMatchAs(_) | AnyNode::PatternMatchAs(_)
| AnyNode::PatternMatchOr(_) | AnyNode::PatternMatchOr(_)
| AnyNode::Comprehension(_) | AnyNode::Comprehension(_)
| AnyNode::Arguments(_) | AnyNode::Parameters(_)
| AnyNode::Arg(_) | AnyNode::Parameter(_)
| AnyNode::ArgWithDefault(_) | AnyNode::ParameterWithDefault(_)
| AnyNode::Keyword(_) | AnyNode::Keyword(_)
| AnyNode::Alias(_) | AnyNode::Alias(_)
| AnyNode::WithItem(_) | AnyNode::WithItem(_)
@ -631,9 +631,9 @@ impl AnyNode {
Self::PatternMatchAs(node) => AnyNodeRef::PatternMatchAs(node), Self::PatternMatchAs(node) => AnyNodeRef::PatternMatchAs(node),
Self::PatternMatchOr(node) => AnyNodeRef::PatternMatchOr(node), Self::PatternMatchOr(node) => AnyNodeRef::PatternMatchOr(node),
Self::Comprehension(node) => AnyNodeRef::Comprehension(node), Self::Comprehension(node) => AnyNodeRef::Comprehension(node),
Self::Arguments(node) => AnyNodeRef::Arguments(node), Self::Parameters(node) => AnyNodeRef::Parameters(node),
Self::Arg(node) => AnyNodeRef::Arg(node), Self::Parameter(node) => AnyNodeRef::Parameter(node),
Self::ArgWithDefault(node) => AnyNodeRef::ArgWithDefault(node), Self::ParameterWithDefault(node) => AnyNodeRef::ParameterWithDefault(node),
Self::Keyword(node) => AnyNodeRef::Keyword(node), Self::Keyword(node) => AnyNodeRef::Keyword(node),
Self::Alias(node) => AnyNodeRef::Alias(node), Self::Alias(node) => AnyNodeRef::Alias(node),
Self::WithItem(node) => AnyNodeRef::WithItem(node), Self::WithItem(node) => AnyNodeRef::WithItem(node),
@ -2613,12 +2613,12 @@ impl AstNode for Comprehension {
AnyNode::from(self) AnyNode::from(self)
} }
} }
impl AstNode for Arguments { impl AstNode for Parameters {
fn cast(kind: AnyNode) -> Option<Self> fn cast(kind: AnyNode) -> Option<Self>
where where
Self: Sized, Self: Sized,
{ {
if let AnyNode::Arguments(node) = kind { if let AnyNode::Parameters(node) = kind {
Some(node) Some(node)
} else { } else {
None None
@ -2626,7 +2626,7 @@ impl AstNode for Arguments {
} }
fn cast_ref(kind: AnyNodeRef) -> Option<&Self> { fn cast_ref(kind: AnyNodeRef) -> Option<&Self> {
if let AnyNodeRef::Arguments(node) = kind { if let AnyNodeRef::Parameters(node) = kind {
Some(node) Some(node)
} else { } else {
None None
@ -2641,12 +2641,12 @@ impl AstNode for Arguments {
AnyNode::from(self) AnyNode::from(self)
} }
} }
impl AstNode for Arg { impl AstNode for Parameter {
fn cast(kind: AnyNode) -> Option<Self> fn cast(kind: AnyNode) -> Option<Self>
where where
Self: Sized, Self: Sized,
{ {
if let AnyNode::Arg(node) = kind { if let AnyNode::Parameter(node) = kind {
Some(node) Some(node)
} else { } else {
None None
@ -2654,7 +2654,7 @@ impl AstNode for Arg {
} }
fn cast_ref(kind: AnyNodeRef) -> Option<&Self> { fn cast_ref(kind: AnyNodeRef) -> Option<&Self> {
if let AnyNodeRef::Arg(node) = kind { if let AnyNodeRef::Parameter(node) = kind {
Some(node) Some(node)
} else { } else {
None None
@ -2669,12 +2669,12 @@ impl AstNode for Arg {
AnyNode::from(self) AnyNode::from(self)
} }
} }
impl AstNode for ArgWithDefault { impl AstNode for ParameterWithDefault {
fn cast(kind: AnyNode) -> Option<Self> fn cast(kind: AnyNode) -> Option<Self>
where where
Self: Sized, Self: Sized,
{ {
if let AnyNode::ArgWithDefault(node) = kind { if let AnyNode::ParameterWithDefault(node) = kind {
Some(node) Some(node)
} else { } else {
None None
@ -2682,7 +2682,7 @@ impl AstNode for ArgWithDefault {
} }
fn cast_ref(kind: AnyNodeRef) -> Option<&Self> { fn cast_ref(kind: AnyNodeRef) -> Option<&Self> {
if let AnyNodeRef::ArgWithDefault(node) = kind { if let AnyNodeRef::ParameterWithDefault(node) = kind {
Some(node) Some(node)
} else { } else {
None None
@ -3444,19 +3444,19 @@ impl From<Comprehension> for AnyNode {
AnyNode::Comprehension(node) AnyNode::Comprehension(node)
} }
} }
impl From<Arguments> for AnyNode { impl From<Parameters> for AnyNode {
fn from(node: Arguments) -> Self { fn from(node: Parameters) -> Self {
AnyNode::Arguments(node) AnyNode::Parameters(node)
} }
} }
impl From<Arg> for AnyNode { impl From<Parameter> for AnyNode {
fn from(node: Arg) -> Self { fn from(node: Parameter) -> Self {
AnyNode::Arg(node) AnyNode::Parameter(node)
} }
} }
impl From<ArgWithDefault> for AnyNode { impl From<ParameterWithDefault> for AnyNode {
fn from(node: ArgWithDefault) -> Self { fn from(node: ParameterWithDefault) -> Self {
AnyNode::ArgWithDefault(node) AnyNode::ParameterWithDefault(node)
} }
} }
impl From<Keyword> for AnyNode { impl From<Keyword> for AnyNode {
@ -3574,9 +3574,9 @@ impl Ranged for AnyNode {
AnyNode::PatternMatchAs(node) => node.range(), AnyNode::PatternMatchAs(node) => node.range(),
AnyNode::PatternMatchOr(node) => node.range(), AnyNode::PatternMatchOr(node) => node.range(),
AnyNode::Comprehension(node) => node.range(), AnyNode::Comprehension(node) => node.range(),
AnyNode::Arguments(node) => node.range(), AnyNode::Parameters(node) => node.range(),
AnyNode::Arg(node) => node.range(), AnyNode::Parameter(node) => node.range(),
AnyNode::ArgWithDefault(node) => node.range(), AnyNode::ParameterWithDefault(node) => node.range(),
AnyNode::Keyword(node) => node.range(), AnyNode::Keyword(node) => node.range(),
AnyNode::Alias(node) => node.range(), AnyNode::Alias(node) => node.range(),
AnyNode::WithItem(node) => node.range(), AnyNode::WithItem(node) => node.range(),
@ -3661,9 +3661,9 @@ pub enum AnyNodeRef<'a> {
PatternMatchAs(&'a ast::PatternMatchAs), PatternMatchAs(&'a ast::PatternMatchAs),
PatternMatchOr(&'a ast::PatternMatchOr), PatternMatchOr(&'a ast::PatternMatchOr),
Comprehension(&'a Comprehension), Comprehension(&'a Comprehension),
Arguments(&'a Arguments), Parameters(&'a Parameters),
Arg(&'a Arg), Parameter(&'a Parameter),
ArgWithDefault(&'a ArgWithDefault), ParameterWithDefault(&'a ParameterWithDefault),
Keyword(&'a Keyword), Keyword(&'a Keyword),
Alias(&'a Alias), Alias(&'a Alias),
WithItem(&'a WithItem), WithItem(&'a WithItem),
@ -3747,9 +3747,9 @@ impl AnyNodeRef<'_> {
AnyNodeRef::PatternMatchAs(node) => NonNull::from(*node).cast(), AnyNodeRef::PatternMatchAs(node) => NonNull::from(*node).cast(),
AnyNodeRef::PatternMatchOr(node) => NonNull::from(*node).cast(), AnyNodeRef::PatternMatchOr(node) => NonNull::from(*node).cast(),
AnyNodeRef::Comprehension(node) => NonNull::from(*node).cast(), AnyNodeRef::Comprehension(node) => NonNull::from(*node).cast(),
AnyNodeRef::Arguments(node) => NonNull::from(*node).cast(), AnyNodeRef::Parameters(node) => NonNull::from(*node).cast(),
AnyNodeRef::Arg(node) => NonNull::from(*node).cast(), AnyNodeRef::Parameter(node) => NonNull::from(*node).cast(),
AnyNodeRef::ArgWithDefault(node) => NonNull::from(*node).cast(), AnyNodeRef::ParameterWithDefault(node) => NonNull::from(*node).cast(),
AnyNodeRef::Keyword(node) => NonNull::from(*node).cast(), AnyNodeRef::Keyword(node) => NonNull::from(*node).cast(),
AnyNodeRef::Alias(node) => NonNull::from(*node).cast(), AnyNodeRef::Alias(node) => NonNull::from(*node).cast(),
AnyNodeRef::WithItem(node) => NonNull::from(*node).cast(), AnyNodeRef::WithItem(node) => NonNull::from(*node).cast(),
@ -3839,9 +3839,9 @@ impl AnyNodeRef<'_> {
AnyNodeRef::PatternMatchAs(_) => NodeKind::PatternMatchAs, AnyNodeRef::PatternMatchAs(_) => NodeKind::PatternMatchAs,
AnyNodeRef::PatternMatchOr(_) => NodeKind::PatternMatchOr, AnyNodeRef::PatternMatchOr(_) => NodeKind::PatternMatchOr,
AnyNodeRef::Comprehension(_) => NodeKind::Comprehension, AnyNodeRef::Comprehension(_) => NodeKind::Comprehension,
AnyNodeRef::Arguments(_) => NodeKind::Arguments, AnyNodeRef::Parameters(_) => NodeKind::Parameters,
AnyNodeRef::Arg(_) => NodeKind::Arg, AnyNodeRef::Parameter(_) => NodeKind::Parameter,
AnyNodeRef::ArgWithDefault(_) => NodeKind::ArgWithDefault, AnyNodeRef::ParameterWithDefault(_) => NodeKind::ParameterWithDefault,
AnyNodeRef::Keyword(_) => NodeKind::Keyword, AnyNodeRef::Keyword(_) => NodeKind::Keyword,
AnyNodeRef::Alias(_) => NodeKind::Alias, AnyNodeRef::Alias(_) => NodeKind::Alias,
AnyNodeRef::WithItem(_) => NodeKind::WithItem, AnyNodeRef::WithItem(_) => NodeKind::WithItem,
@ -3926,9 +3926,9 @@ impl AnyNodeRef<'_> {
| AnyNodeRef::PatternMatchAs(_) | AnyNodeRef::PatternMatchAs(_)
| AnyNodeRef::PatternMatchOr(_) | AnyNodeRef::PatternMatchOr(_)
| AnyNodeRef::Comprehension(_) | AnyNodeRef::Comprehension(_)
| AnyNodeRef::Arguments(_) | AnyNodeRef::Parameters(_)
| AnyNodeRef::Arg(_) | AnyNodeRef::Parameter(_)
| AnyNodeRef::ArgWithDefault(_) | AnyNodeRef::ParameterWithDefault(_)
| AnyNodeRef::Keyword(_) | AnyNodeRef::Keyword(_)
| AnyNodeRef::Alias(_) | AnyNodeRef::Alias(_)
| AnyNodeRef::WithItem(_) | AnyNodeRef::WithItem(_)
@ -4013,9 +4013,9 @@ impl AnyNodeRef<'_> {
| AnyNodeRef::PatternMatchAs(_) | AnyNodeRef::PatternMatchAs(_)
| AnyNodeRef::PatternMatchOr(_) | AnyNodeRef::PatternMatchOr(_)
| AnyNodeRef::Comprehension(_) | AnyNodeRef::Comprehension(_)
| AnyNodeRef::Arguments(_) | AnyNodeRef::Parameters(_)
| AnyNodeRef::Arg(_) | AnyNodeRef::Parameter(_)
| AnyNodeRef::ArgWithDefault(_) | AnyNodeRef::ParameterWithDefault(_)
| AnyNodeRef::Keyword(_) | AnyNodeRef::Keyword(_)
| AnyNodeRef::Alias(_) | AnyNodeRef::Alias(_)
| AnyNodeRef::WithItem(_) | AnyNodeRef::WithItem(_)
@ -4099,9 +4099,9 @@ impl AnyNodeRef<'_> {
| AnyNodeRef::PatternMatchAs(_) | AnyNodeRef::PatternMatchAs(_)
| AnyNodeRef::PatternMatchOr(_) | AnyNodeRef::PatternMatchOr(_)
| AnyNodeRef::Comprehension(_) | AnyNodeRef::Comprehension(_)
| AnyNodeRef::Arguments(_) | AnyNodeRef::Parameters(_)
| AnyNodeRef::Arg(_) | AnyNodeRef::Parameter(_)
| AnyNodeRef::ArgWithDefault(_) | AnyNodeRef::ParameterWithDefault(_)
| AnyNodeRef::Keyword(_) | AnyNodeRef::Keyword(_)
| AnyNodeRef::Alias(_) | AnyNodeRef::Alias(_)
| AnyNodeRef::WithItem(_) | AnyNodeRef::WithItem(_)
@ -4186,9 +4186,9 @@ impl AnyNodeRef<'_> {
| AnyNodeRef::ExprLineMagic(_) | AnyNodeRef::ExprLineMagic(_)
| AnyNodeRef::ExceptHandlerExceptHandler(_) | AnyNodeRef::ExceptHandlerExceptHandler(_)
| AnyNodeRef::Comprehension(_) | AnyNodeRef::Comprehension(_)
| AnyNodeRef::Arguments(_) | AnyNodeRef::Parameters(_)
| AnyNodeRef::Arg(_) | AnyNodeRef::Parameter(_)
| AnyNodeRef::ArgWithDefault(_) | AnyNodeRef::ParameterWithDefault(_)
| AnyNodeRef::Keyword(_) | AnyNodeRef::Keyword(_)
| AnyNodeRef::Alias(_) | AnyNodeRef::Alias(_)
| AnyNodeRef::WithItem(_) | AnyNodeRef::WithItem(_)
@ -4273,9 +4273,9 @@ impl AnyNodeRef<'_> {
| AnyNodeRef::PatternMatchAs(_) | AnyNodeRef::PatternMatchAs(_)
| AnyNodeRef::PatternMatchOr(_) | AnyNodeRef::PatternMatchOr(_)
| AnyNodeRef::Comprehension(_) | AnyNodeRef::Comprehension(_)
| AnyNodeRef::Arguments(_) | AnyNodeRef::Parameters(_)
| AnyNodeRef::Arg(_) | AnyNodeRef::Parameter(_)
| AnyNodeRef::ArgWithDefault(_) | AnyNodeRef::ParameterWithDefault(_)
| AnyNodeRef::Keyword(_) | AnyNodeRef::Keyword(_)
| AnyNodeRef::Alias(_) | AnyNodeRef::Alias(_)
| AnyNodeRef::WithItem(_) | AnyNodeRef::WithItem(_)
@ -4877,19 +4877,19 @@ impl<'a> From<&'a Comprehension> for AnyNodeRef<'a> {
AnyNodeRef::Comprehension(node) AnyNodeRef::Comprehension(node)
} }
} }
impl<'a> From<&'a Arguments> for AnyNodeRef<'a> { impl<'a> From<&'a Parameters> for AnyNodeRef<'a> {
fn from(node: &'a Arguments) -> Self { fn from(node: &'a Parameters) -> Self {
AnyNodeRef::Arguments(node) AnyNodeRef::Parameters(node)
} }
} }
impl<'a> From<&'a Arg> for AnyNodeRef<'a> { impl<'a> From<&'a Parameter> for AnyNodeRef<'a> {
fn from(node: &'a Arg) -> Self { fn from(node: &'a Parameter) -> Self {
AnyNodeRef::Arg(node) AnyNodeRef::Parameter(node)
} }
} }
impl<'a> From<&'a ArgWithDefault> for AnyNodeRef<'a> { impl<'a> From<&'a ParameterWithDefault> for AnyNodeRef<'a> {
fn from(node: &'a ArgWithDefault) -> Self { fn from(node: &'a ParameterWithDefault) -> Self {
AnyNodeRef::ArgWithDefault(node) AnyNodeRef::ParameterWithDefault(node)
} }
} }
impl<'a> From<&'a Keyword> for AnyNodeRef<'a> { impl<'a> From<&'a Keyword> for AnyNodeRef<'a> {
@ -4985,9 +4985,9 @@ impl Ranged for AnyNodeRef<'_> {
AnyNodeRef::PatternMatchAs(node) => node.range(), AnyNodeRef::PatternMatchAs(node) => node.range(),
AnyNodeRef::PatternMatchOr(node) => node.range(), AnyNodeRef::PatternMatchOr(node) => node.range(),
AnyNodeRef::Comprehension(node) => node.range(), AnyNodeRef::Comprehension(node) => node.range(),
AnyNodeRef::Arguments(node) => node.range(), AnyNodeRef::Parameters(node) => node.range(),
AnyNodeRef::Arg(node) => node.range(), AnyNodeRef::Parameter(node) => node.range(),
AnyNodeRef::ArgWithDefault(node) => node.range(), AnyNodeRef::ParameterWithDefault(node) => node.range(),
AnyNodeRef::Keyword(node) => node.range(), AnyNodeRef::Keyword(node) => node.range(),
AnyNodeRef::Alias(node) => node.range(), AnyNodeRef::Alias(node) => node.range(),
AnyNodeRef::WithItem(node) => node.range(), AnyNodeRef::WithItem(node) => node.range(),
@ -5075,9 +5075,9 @@ pub enum NodeKind {
PatternMatchOr, PatternMatchOr,
TypeIgnoreTypeIgnore, TypeIgnoreTypeIgnore,
Comprehension, Comprehension,
Arguments, Parameters,
Arg, Parameter,
ArgWithDefault, ParameterWithDefault,
Keyword, Keyword,
Alias, Alias,
WithItem, WithItem,

View File

@ -122,7 +122,7 @@ impl From<StmtLineMagic> for Stmt {
pub struct StmtFunctionDef { pub struct StmtFunctionDef {
pub range: TextRange, pub range: TextRange,
pub name: Identifier, pub name: Identifier,
pub args: Box<Arguments>, pub parameters: Box<Parameters>,
pub body: Vec<Stmt>, pub body: Vec<Stmt>,
pub decorator_list: Vec<Decorator>, pub decorator_list: Vec<Decorator>,
pub returns: Option<Box<Expr>>, pub returns: Option<Box<Expr>>,
@ -140,7 +140,7 @@ impl From<StmtFunctionDef> for Stmt {
pub struct StmtAsyncFunctionDef { pub struct StmtAsyncFunctionDef {
pub range: TextRange, pub range: TextRange,
pub name: Identifier, pub name: Identifier,
pub args: Box<Arguments>, pub parameters: Box<Parameters>,
pub body: Vec<Stmt>, pub body: Vec<Stmt>,
pub decorator_list: Vec<Decorator>, pub decorator_list: Vec<Decorator>,
pub returns: Option<Box<Expr>>, pub returns: Option<Box<Expr>>,
@ -668,7 +668,7 @@ impl From<ExprUnaryOp> for Expr {
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub struct ExprLambda { pub struct ExprLambda {
pub range: TextRange, pub range: TextRange,
pub args: Box<Arguments>, pub parameters: Box<Parameters>,
pub body: Box<Expr>, pub body: Box<Expr>,
} }
@ -1822,22 +1822,9 @@ impl From<ExceptHandlerExceptHandler> for ExceptHandler {
} }
} }
/// See also [arguments](https://docs.python.org/3/library/ast.html#ast.arguments)
#[derive(Clone, Debug, PartialEq)]
pub struct PythonArguments {
pub range: TextRange,
pub posonlyargs: Vec<Arg>,
pub args: Vec<Arg>,
pub vararg: Option<Box<Arg>>,
pub kwonlyargs: Vec<Arg>,
pub kw_defaults: Vec<Expr>,
pub kwarg: Option<Box<Arg>>,
pub defaults: Vec<Expr>,
}
/// See also [arg](https://docs.python.org/3/library/ast.html#ast.arg) /// See also [arg](https://docs.python.org/3/library/ast.html#ast.arg)
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub struct Arg { pub struct Parameter {
pub range: TextRange, pub range: TextRange,
pub arg: Identifier, pub arg: Identifier,
pub annotation: Option<Box<Expr>>, pub annotation: Option<Box<Expr>>,
@ -2056,22 +2043,22 @@ pub struct Decorator {
/// An alternative type of AST `arguments`. This is ruff_python_parser-friendly and human-friendly definition of function arguments. /// An alternative type of AST `arguments`. This is ruff_python_parser-friendly and human-friendly definition of function arguments.
/// This form also has advantage to implement pre-order traverse. /// This form also has advantage to implement pre-order traverse.
/// `defaults` and `kw_defaults` fields are removed and the default values are placed under each `arg_with_default` typed argument. ///
/// `defaults` and `kw_defaults` fields are removed and the default values are placed under each [`ParameterWithDefault`] typed argument.
/// `vararg` and `kwarg` are still typed as `arg` because they never can have a default value. /// `vararg` and `kwarg` are still typed as `arg` because they never can have a default value.
/// ///
/// The matching Python style AST type is [`PythonArguments`]. While [`PythonArguments`] has ordered `kwonlyargs` fields by /// The original Python-style AST type orders `kwonlyargs` fields by default existence; [Parameters] has location-ordered `kwonlyargs` fields.
/// default existence, [Arguments] has location-ordered kwonlyargs fields.
/// ///
/// NOTE: This type is different from original Python AST. /// NOTE: This type differs from the original Python AST. See: [arguments](https://docs.python.org/3/library/ast.html#ast.arguments).
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub struct Arguments { pub struct Parameters {
pub range: TextRange, pub range: TextRange,
pub posonlyargs: Vec<ArgWithDefault>, pub posonlyargs: Vec<ParameterWithDefault>,
pub args: Vec<ArgWithDefault>, pub args: Vec<ParameterWithDefault>,
pub vararg: Option<Box<Arg>>, pub vararg: Option<Box<Parameter>>,
pub kwonlyargs: Vec<ArgWithDefault>, pub kwonlyargs: Vec<ParameterWithDefault>,
pub kwarg: Option<Box<Arg>>, pub kwarg: Option<Box<Parameter>>,
} }
/// An alternative type of AST `arg`. This is used for each function argument that might have a default value. /// An alternative type of AST `arg`. This is used for each function argument that might have a default value.
@ -2080,9 +2067,9 @@ pub struct Arguments {
/// NOTE: This type is different from original Python AST. /// NOTE: This type is different from original Python AST.
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub struct ArgWithDefault { pub struct ParameterWithDefault {
pub range: TextRange, pub range: TextRange,
pub def: Arg, pub def: Parameter,
pub default: Option<Box<Expr>>, pub default: Option<Box<Expr>>,
} }
@ -2105,7 +2092,7 @@ impl CmpOp {
} }
} }
impl Arguments { impl Parameters {
pub fn empty(range: TextRange) -> Self { pub fn empty(range: TextRange) -> Self {
Self { Self {
range, range,
@ -2124,21 +2111,21 @@ fn clone_boxed_expr(expr: &Box<Expr>) -> Box<Expr> {
Box::new(expr.clone()) Box::new(expr.clone())
} }
impl ArgWithDefault { impl ParameterWithDefault {
pub fn as_arg(&self) -> &Arg { pub fn as_parameter(&self) -> &Parameter {
&self.def &self.def
} }
pub fn to_arg(&self) -> (Arg, Option<Box<Expr>>) { pub fn to_parameter(&self) -> (Parameter, Option<Box<Expr>>) {
let ArgWithDefault { let ParameterWithDefault {
range: _, range: _,
def, def,
default, default,
} = self; } = self;
(def.clone(), default.as_ref().map(clone_boxed_expr)) (def.clone(), default.as_ref().map(clone_boxed_expr))
} }
pub fn into_arg(self) -> (Arg, Option<Box<Expr>>) { pub fn into_parameter(self) -> (Parameter, Option<Box<Expr>>) {
let ArgWithDefault { let ParameterWithDefault {
range: _, range: _,
def, def,
default, default,
@ -2147,7 +2134,7 @@ impl ArgWithDefault {
} }
} }
impl Arguments { impl Parameters {
pub fn defaults(&self) -> impl std::iter::Iterator<Item = &Expr> { pub fn defaults(&self) -> impl std::iter::Iterator<Item = &Expr> {
self.posonlyargs self.posonlyargs
.iter() .iter()
@ -2156,14 +2143,14 @@ impl Arguments {
} }
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
pub fn split_kwonlyargs(&self) -> (Vec<&Arg>, Vec<(&Arg, &Expr)>) { pub fn split_kwonlyargs(&self) -> (Vec<&Parameter>, Vec<(&Parameter, &Expr)>) {
let mut args = Vec::new(); let mut args = Vec::new();
let mut with_defaults = Vec::new(); let mut with_defaults = Vec::new();
for arg in &self.kwonlyargs { for arg in &self.kwonlyargs {
if let Some(ref default) = arg.default { if let Some(ref default) = arg.default {
with_defaults.push((arg.as_arg(), &**default)); with_defaults.push((arg.as_parameter(), &**default));
} else { } else {
args.push(arg.as_arg()); args.push(arg.as_parameter());
} }
} }
(args, with_defaults) (args, with_defaults)
@ -2838,12 +2825,7 @@ impl Ranged for crate::ExceptHandler {
} }
} }
impl Ranged for crate::nodes::PythonArguments { impl Ranged for crate::nodes::Parameter {
fn range(&self) -> TextRange {
self.range
}
}
impl Ranged for crate::nodes::Arg {
fn range(&self) -> TextRange { fn range(&self) -> TextRange {
self.range self.range
} }
@ -2952,12 +2934,12 @@ impl Ranged for crate::nodes::Decorator {
self.range self.range
} }
} }
impl Ranged for crate::nodes::Arguments { impl Ranged for crate::nodes::Parameters {
fn range(&self) -> TextRange { fn range(&self) -> TextRange {
self.range self.range
} }
} }
impl Ranged for crate::nodes::ArgWithDefault { impl Ranged for crate::nodes::ParameterWithDefault {
fn range(&self) -> TextRange { fn range(&self) -> TextRange {
self.range self.range
} }

View File

@ -3,9 +3,9 @@
pub mod preorder; pub mod preorder;
use crate::{ use crate::{
self as ast, Alias, Arg, Arguments, BoolOp, CmpOp, Comprehension, Decorator, ElifElseClause, self as ast, Alias, BoolOp, CmpOp, Comprehension, Decorator, ElifElseClause, ExceptHandler,
ExceptHandler, Expr, ExprContext, Keyword, MatchCase, Operator, Pattern, Stmt, TypeParam, Expr, ExprContext, Keyword, MatchCase, Operator, Parameter, Parameters, Pattern, Stmt,
TypeParamTypeVar, UnaryOp, WithItem, TypeParam, TypeParamTypeVar, UnaryOp, WithItem,
}; };
/// A trait for AST visitors. Visits all nodes in the AST recursively in evaluation-order. /// A trait for AST visitors. Visits all nodes in the AST recursively in evaluation-order.
@ -52,11 +52,11 @@ pub trait Visitor<'a> {
fn visit_format_spec(&mut self, format_spec: &'a Expr) { fn visit_format_spec(&mut self, format_spec: &'a Expr) {
walk_format_spec(self, format_spec); walk_format_spec(self, format_spec);
} }
fn visit_arguments(&mut self, arguments: &'a Arguments) { fn visit_parameters(&mut self, parameters: &'a Parameters) {
walk_arguments(self, arguments); walk_parameters(self, parameters);
} }
fn visit_arg(&mut self, arg: &'a Arg) { fn visit_parameter(&mut self, parameter: &'a Parameter) {
walk_arg(self, arg); walk_parameter(self, parameter);
} }
fn visit_keyword(&mut self, keyword: &'a Keyword) { fn visit_keyword(&mut self, keyword: &'a Keyword) {
walk_keyword(self, keyword); walk_keyword(self, keyword);
@ -103,7 +103,7 @@ pub fn walk_elif_else_clause<'a, V: Visitor<'a> + ?Sized>(
pub fn walk_stmt<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, stmt: &'a Stmt) { pub fn walk_stmt<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, stmt: &'a Stmt) {
match stmt { match stmt {
Stmt::FunctionDef(ast::StmtFunctionDef { Stmt::FunctionDef(ast::StmtFunctionDef {
args, parameters,
body, body,
decorator_list, decorator_list,
returns, returns,
@ -116,14 +116,14 @@ pub fn walk_stmt<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, stmt: &'a Stmt) {
for type_param in type_params { for type_param in type_params {
visitor.visit_type_param(type_param); visitor.visit_type_param(type_param);
} }
visitor.visit_arguments(args); visitor.visit_parameters(parameters);
for expr in returns { for expr in returns {
visitor.visit_annotation(expr); visitor.visit_annotation(expr);
} }
visitor.visit_body(body); visitor.visit_body(body);
} }
Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef { Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef {
args, parameters,
body, body,
decorator_list, decorator_list,
returns, returns,
@ -136,7 +136,7 @@ pub fn walk_stmt<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, stmt: &'a Stmt) {
for type_param in type_params { for type_param in type_params {
visitor.visit_type_param(type_param); visitor.visit_type_param(type_param);
} }
visitor.visit_arguments(args); visitor.visit_parameters(parameters);
for expr in returns { for expr in returns {
visitor.visit_annotation(expr); visitor.visit_annotation(expr);
} }
@ -411,11 +411,11 @@ pub fn walk_expr<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, expr: &'a Expr) {
visitor.visit_expr(operand); visitor.visit_expr(operand);
} }
Expr::Lambda(ast::ExprLambda { Expr::Lambda(ast::ExprLambda {
args, parameters,
body, body,
range: _range, range: _range,
}) => { }) => {
visitor.visit_arguments(args); visitor.visit_parameters(parameters);
visitor.visit_expr(body); visitor.visit_expr(body);
} }
Expr::IfExp(ast::ExprIfExp { Expr::IfExp(ast::ExprIfExp {
@ -645,43 +645,43 @@ pub fn walk_format_spec<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, format_spe
visitor.visit_expr(format_spec); visitor.visit_expr(format_spec);
} }
pub fn walk_arguments<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, arguments: &'a Arguments) { pub fn walk_parameters<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, parameters: &'a Parameters) {
// Defaults are evaluated before annotations. // Defaults are evaluated before annotations.
for arg in &arguments.posonlyargs { for arg in &parameters.posonlyargs {
if let Some(default) = &arg.default { if let Some(default) = &arg.default {
visitor.visit_expr(default); visitor.visit_expr(default);
} }
} }
for arg in &arguments.args { for arg in &parameters.args {
if let Some(default) = &arg.default { if let Some(default) = &arg.default {
visitor.visit_expr(default); visitor.visit_expr(default);
} }
} }
for arg in &arguments.kwonlyargs { for arg in &parameters.kwonlyargs {
if let Some(default) = &arg.default { if let Some(default) = &arg.default {
visitor.visit_expr(default); visitor.visit_expr(default);
} }
} }
for arg in &arguments.posonlyargs { for arg in &parameters.posonlyargs {
visitor.visit_arg(&arg.def); visitor.visit_parameter(&arg.def);
} }
for arg in &arguments.args { for arg in &parameters.args {
visitor.visit_arg(&arg.def); visitor.visit_parameter(&arg.def);
} }
if let Some(arg) = &arguments.vararg { if let Some(arg) = &parameters.vararg {
visitor.visit_arg(arg); visitor.visit_parameter(arg);
} }
for arg in &arguments.kwonlyargs { for arg in &parameters.kwonlyargs {
visitor.visit_arg(&arg.def); visitor.visit_parameter(&arg.def);
} }
if let Some(arg) = &arguments.kwarg { if let Some(arg) = &parameters.kwarg {
visitor.visit_arg(arg); visitor.visit_parameter(arg);
} }
} }
pub fn walk_arg<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, arg: &'a Arg) { pub fn walk_parameter<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, parameter: &'a Parameter) {
if let Some(expr) = &arg.annotation { if let Some(expr) = &parameter.annotation {
visitor.visit_annotation(expr); visitor.visit_annotation(expr);
} }
} }

View File

@ -1,7 +1,7 @@
use crate::{ use crate::{
self as ast, Alias, Arg, ArgWithDefault, Arguments, BoolOp, CmpOp, Comprehension, Constant, self as ast, Alias, BoolOp, CmpOp, Comprehension, Constant, Decorator, ElifElseClause,
Decorator, ElifElseClause, ExceptHandler, Expr, Keyword, MatchCase, Mod, Operator, Pattern, ExceptHandler, Expr, Keyword, MatchCase, Mod, Operator, Parameter, ParameterWithDefault,
Stmt, TypeParam, TypeParamTypeVar, UnaryOp, WithItem, Parameters, Pattern, Stmt, TypeParam, TypeParamTypeVar, UnaryOp, WithItem,
}; };
/// Visitor that traverses all nodes recursively in pre-order. /// Visitor that traverses all nodes recursively in pre-order.
@ -56,16 +56,16 @@ pub trait PreorderVisitor<'a> {
walk_format_spec(self, format_spec); walk_format_spec(self, format_spec);
} }
fn visit_arguments(&mut self, arguments: &'a Arguments) { fn visit_parameters(&mut self, parameters: &'a Parameters) {
walk_arguments(self, arguments); walk_parameters(self, parameters);
} }
fn visit_arg(&mut self, arg: &'a Arg) { fn visit_parameter(&mut self, arg: &'a Parameter) {
walk_arg(self, arg); walk_parameter(self, arg);
} }
fn visit_arg_with_default(&mut self, arg_with_default: &'a ArgWithDefault) { fn visit_parameter_with_default(&mut self, parameter_with_default: &'a ParameterWithDefault) {
walk_arg_with_default(self, arg_with_default); walk_parameter_with_default(self, parameter_with_default);
} }
fn visit_keyword(&mut self, keyword: &'a Keyword) { fn visit_keyword(&mut self, keyword: &'a Keyword) {
@ -133,7 +133,7 @@ where
}) => visitor.visit_expr(value), }) => visitor.visit_expr(value),
Stmt::FunctionDef(ast::StmtFunctionDef { Stmt::FunctionDef(ast::StmtFunctionDef {
args, parameters,
body, body,
decorator_list, decorator_list,
returns, returns,
@ -141,7 +141,7 @@ where
.. ..
}) })
| Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef { | Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef {
args, parameters,
body, body,
decorator_list, decorator_list,
returns, returns,
@ -156,7 +156,7 @@ where
visitor.visit_type_param(type_param); visitor.visit_type_param(type_param);
} }
visitor.visit_arguments(args); visitor.visit_parameters(parameters);
for expr in returns { for expr in returns {
visitor.visit_annotation(expr); visitor.visit_annotation(expr);
@ -469,11 +469,11 @@ where
} }
Expr::Lambda(ast::ExprLambda { Expr::Lambda(ast::ExprLambda {
args, parameters,
body, body,
range: _range, range: _range,
}) => { }) => {
visitor.visit_arguments(args); visitor.visit_parameters(parameters);
visitor.visit_expr(body); visitor.visit_expr(body);
} }
@ -749,42 +749,44 @@ pub fn walk_format_spec<'a, V: PreorderVisitor<'a> + ?Sized>(
visitor.visit_expr(format_spec); visitor.visit_expr(format_spec);
} }
pub fn walk_arguments<'a, V>(visitor: &mut V, arguments: &'a Arguments) pub fn walk_parameters<'a, V>(visitor: &mut V, parameters: &'a Parameters)
where where
V: PreorderVisitor<'a> + ?Sized, V: PreorderVisitor<'a> + ?Sized,
{ {
for arg in arguments.posonlyargs.iter().chain(&arguments.args) { for arg in parameters.posonlyargs.iter().chain(&parameters.args) {
visitor.visit_arg_with_default(arg); visitor.visit_parameter_with_default(arg);
} }
if let Some(arg) = &arguments.vararg { if let Some(arg) = &parameters.vararg {
visitor.visit_arg(arg); visitor.visit_parameter(arg);
} }
for arg in &arguments.kwonlyargs { for arg in &parameters.kwonlyargs {
visitor.visit_arg_with_default(arg); visitor.visit_parameter_with_default(arg);
} }
if let Some(arg) = &arguments.kwarg { if let Some(arg) = &parameters.kwarg {
visitor.visit_arg(arg); visitor.visit_parameter(arg);
} }
} }
pub fn walk_arg<'a, V>(visitor: &mut V, arg: &'a Arg) pub fn walk_parameter<'a, V>(visitor: &mut V, parameter: &'a Parameter)
where where
V: PreorderVisitor<'a> + ?Sized, V: PreorderVisitor<'a> + ?Sized,
{ {
if let Some(expr) = &arg.annotation { if let Some(expr) = &parameter.annotation {
visitor.visit_annotation(expr); visitor.visit_annotation(expr);
} }
} }
pub fn walk_arg_with_default<'a, V>(visitor: &mut V, arg_with_default: &'a ArgWithDefault) pub fn walk_parameter_with_default<'a, V>(
where visitor: &mut V,
parameter_with_default: &'a ParameterWithDefault,
) where
V: PreorderVisitor<'a> + ?Sized, V: PreorderVisitor<'a> + ?Sized,
{ {
visitor.visit_arg(&arg_with_default.def); visitor.visit_parameter(&parameter_with_default.def);
if let Some(expr) = &arg_with_default.default { if let Some(expr) = &parameter_with_default.default {
visitor.visit_expr(expr); visitor.visit_expr(expr);
} }
} }

View File

@ -4,13 +4,13 @@ use insta::assert_snapshot;
use ruff_python_ast::node::AnyNodeRef; use ruff_python_ast::node::AnyNodeRef;
use ruff_python_ast::visitor::preorder::{ use ruff_python_ast::visitor::preorder::{
walk_alias, walk_arg, walk_arguments, walk_comprehension, walk_except_handler, walk_expr, walk_alias, walk_comprehension, walk_except_handler, walk_expr, walk_keyword, walk_match_case,
walk_keyword, walk_match_case, walk_module, walk_pattern, walk_stmt, walk_type_param, walk_module, walk_parameter, walk_parameters, walk_pattern, walk_stmt, walk_type_param,
walk_with_item, PreorderVisitor, walk_with_item, PreorderVisitor,
}; };
use ruff_python_ast::{ use ruff_python_ast::{
Alias, Arg, Arguments, BoolOp, CmpOp, Comprehension, Constant, ExceptHandler, Expr, Keyword, Alias, BoolOp, CmpOp, Comprehension, Constant, ExceptHandler, Expr, Keyword, MatchCase, Mod,
MatchCase, Mod, Operator, Pattern, Stmt, TypeParam, UnaryOp, WithItem, Operator, Parameter, Parameters, Pattern, Stmt, TypeParam, UnaryOp, WithItem,
}; };
use ruff_python_parser::lexer::lex; use ruff_python_parser::lexer::lex;
use ruff_python_parser::{parse_tokens, Mode}; use ruff_python_parser::{parse_tokens, Mode};
@ -231,15 +231,15 @@ impl PreorderVisitor<'_> for RecordVisitor {
self.exit_node(); self.exit_node();
} }
fn visit_arguments(&mut self, arguments: &Arguments) { fn visit_parameters(&mut self, parameters: &Parameters) {
self.enter_node(arguments); self.enter_node(parameters);
walk_arguments(self, arguments); walk_parameters(self, parameters);
self.exit_node(); self.exit_node();
} }
fn visit_arg(&mut self, arg: &Arg) { fn visit_parameter(&mut self, parameter: &Parameter) {
self.enter_node(arg); self.enter_node(parameter);
walk_arg(self, arg); walk_parameter(self, parameter);
self.exit_node(); self.exit_node();
} }

View File

@ -5,7 +5,7 @@ expression: trace
- ModModule - ModModule
- StmtFunctionDef - StmtFunctionDef
- ExprName - ExprName
- Arguments - Parameters
- StmtPass - StmtPass
- StmtClassDef - StmtClassDef
- ExprName - ExprName

View File

@ -4,20 +4,20 @@ expression: trace
--- ---
- ModModule - ModModule
- StmtFunctionDef - StmtFunctionDef
- Arguments - Parameters
- Arg - Parameter
- Arg - Parameter
- Arg - Parameter
- Arg - Parameter
- ExprConstant - ExprConstant
- Int(20) - Int(20)
- Arg - Parameter
- Arg - Parameter
- ExprConstant - ExprConstant
- Int(5) - Int(5)
- Arg - Parameter
- ExprConstant - ExprConstant
- Int(20) - Int(20)
- Arg - Parameter
- StmtPass - StmtPass

View File

@ -4,14 +4,14 @@ expression: trace
--- ---
- ModModule - ModModule
- StmtFunctionDef - StmtFunctionDef
- Arguments - Parameters
- Arg - Parameter
- Arg - Parameter
- ExprConstant - ExprConstant
- Int(34) - Int(34)
- Arg - Parameter
- ExprConstant - ExprConstant
- Int(20) - Int(20)
- Arg - Parameter
- StmtPass - StmtPass

View File

@ -9,7 +9,7 @@ expression: trace
- TypeParamTypeVar - TypeParamTypeVar
- TypeParamTypeVarTuple - TypeParamTypeVarTuple
- TypeParamParamSpec - TypeParamParamSpec
- Arguments - Parameters
- StmtExpr - StmtExpr
- ExprConstant - ExprConstant
- Ellipsis - Ellipsis

View File

@ -4,7 +4,7 @@ expression: trace
--- ---
- StmtFunctionDef - StmtFunctionDef
- ExprName - ExprName
- Arguments - Parameters
- StmtPass - StmtPass
- StmtClassDef - StmtClassDef
- ExprName - ExprName

View File

@ -3,17 +3,17 @@ source: crates/ruff_python_ast/tests/visitor.rs
expression: trace expression: trace
--- ---
- StmtFunctionDef - StmtFunctionDef
- Arguments - Parameters
- ExprConstant - ExprConstant
- ExprConstant - ExprConstant
- ExprConstant - ExprConstant
- Arg - Parameter
- Arg - Parameter
- Arg - Parameter
- Arg - Parameter
- Arg - Parameter
- Arg - Parameter
- Arg - Parameter
- Arg - Parameter
- StmtPass - StmtPass

View File

@ -3,12 +3,12 @@ source: crates/ruff_python_ast/tests/visitor.rs
expression: trace expression: trace
--- ---
- StmtFunctionDef - StmtFunctionDef
- Arguments - Parameters
- ExprConstant - ExprConstant
- ExprConstant - ExprConstant
- Arg - Parameter
- Arg - Parameter
- Arg - Parameter
- Arg - Parameter
- StmtPass - StmtPass

View File

@ -8,7 +8,7 @@ expression: trace
- TypeParamTypeVar - TypeParamTypeVar
- TypeParamTypeVarTuple - TypeParamTypeVarTuple
- TypeParamParamSpec - TypeParamParamSpec
- Arguments - Parameters
- StmtExpr - StmtExpr
- ExprConstant - ExprConstant

View File

@ -7,13 +7,13 @@ use ruff_python_parser::{parse_tokens, Mode};
use ruff_python_ast::node::AnyNodeRef; use ruff_python_ast::node::AnyNodeRef;
use ruff_python_ast::visitor::{ use ruff_python_ast::visitor::{
walk_alias, walk_arg, walk_arguments, walk_comprehension, walk_except_handler, walk_expr, walk_alias, walk_comprehension, walk_except_handler, walk_expr, walk_keyword, walk_match_case,
walk_keyword, walk_match_case, walk_pattern, walk_stmt, walk_type_param, walk_with_item, walk_parameter, walk_parameters, walk_pattern, walk_stmt, walk_type_param, walk_with_item,
Visitor, Visitor,
}; };
use ruff_python_ast::{ use ruff_python_ast::{
Alias, Arg, Arguments, BoolOp, CmpOp, Comprehension, ExceptHandler, Expr, Keyword, MatchCase, Alias, BoolOp, CmpOp, Comprehension, ExceptHandler, Expr, Keyword, MatchCase, Operator,
Operator, Pattern, Stmt, TypeParam, UnaryOp, WithItem, Parameter, Parameters, Pattern, Stmt, TypeParam, UnaryOp, WithItem,
}; };
#[test] #[test]
@ -234,15 +234,15 @@ impl Visitor<'_> for RecordVisitor {
self.exit_node(); self.exit_node();
} }
fn visit_arguments(&mut self, arguments: &Arguments) { fn visit_parameters(&mut self, parameters: &Parameters) {
self.enter_node(arguments); self.enter_node(parameters);
walk_arguments(self, arguments); walk_parameters(self, parameters);
self.exit_node(); self.exit_node();
} }
fn visit_arg(&mut self, arg: &Arg) { fn visit_parameter(&mut self, parameter: &Parameter) {
self.enter_node(arg); self.enter_node(parameter);
walk_arg(self, arg); walk_parameter(self, parameter);
self.exit_node(); self.exit_node();
} }

View File

@ -1,12 +1,12 @@
//! Generate Python source code from an abstract syntax tree (AST). //! Generate Python source code from an abstract syntax tree (AST).
use ruff_python_ast::ArgWithDefault; use ruff_python_ast::ParameterWithDefault;
use std::ops::Deref; use std::ops::Deref;
use ruff_python_ast::{ use ruff_python_ast::{
self as ast, Alias, Arg, Arguments, BoolOp, CmpOp, Comprehension, Constant, ConversionFlag, self as ast, Alias, BoolOp, CmpOp, Comprehension, Constant, ConversionFlag, DebugText,
DebugText, ExceptHandler, Expr, Identifier, MatchCase, Operator, Pattern, Stmt, Suite, ExceptHandler, Expr, Identifier, MatchCase, Operator, Parameter, Parameters, Pattern, Stmt,
TypeParam, TypeParamParamSpec, TypeParamTypeVar, TypeParamTypeVarTuple, WithItem, Suite, TypeParam, TypeParamParamSpec, TypeParamTypeVar, TypeParamTypeVarTuple, WithItem,
}; };
use ruff_python_literal::escape::{AsciiEscape, Escape, UnicodeEscape}; use ruff_python_literal::escape::{AsciiEscape, Escape, UnicodeEscape};
@ -205,7 +205,7 @@ impl<'a> Generator<'a> {
match ast { match ast {
Stmt::FunctionDef(ast::StmtFunctionDef { Stmt::FunctionDef(ast::StmtFunctionDef {
name, name,
args, parameters,
body, body,
returns, returns,
decorator_list, decorator_list,
@ -224,7 +224,7 @@ impl<'a> Generator<'a> {
self.p_id(name); self.p_id(name);
self.unparse_type_params(type_params); self.unparse_type_params(type_params);
self.p("("); self.p("(");
self.unparse_args(args); self.unparse_parameters(parameters);
self.p(")"); self.p(")");
if let Some(returns) = returns { if let Some(returns) = returns {
self.p(" -> "); self.p(" -> ");
@ -239,7 +239,7 @@ impl<'a> Generator<'a> {
} }
Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef { Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef {
name, name,
args, parameters,
body, body,
returns, returns,
decorator_list, decorator_list,
@ -258,7 +258,7 @@ impl<'a> Generator<'a> {
self.p_id(name); self.p_id(name);
self.unparse_type_params(type_params); self.unparse_type_params(type_params);
self.p("("); self.p("(");
self.unparse_args(args); self.unparse_parameters(parameters);
self.p(")"); self.p(")");
if let Some(returns) = returns { if let Some(returns) = returns {
self.p(" -> "); self.p(" -> ");
@ -985,14 +985,14 @@ impl<'a> Generator<'a> {
}); });
} }
Expr::Lambda(ast::ExprLambda { Expr::Lambda(ast::ExprLambda {
args, parameters,
body, body,
range: _range, range: _range,
}) => { }) => {
group_if!(precedence::LAMBDA, { group_if!(precedence::LAMBDA, {
let npos = args.args.len() + args.posonlyargs.len(); let npos = parameters.args.len() + parameters.posonlyargs.len();
self.p(if npos > 0 { "lambda " } else { "lambda" }); self.p(if npos > 0 { "lambda " } else { "lambda" });
self.unparse_args(args); self.unparse_parameters(parameters);
self.p(": "); self.p(": ");
self.unparse_expr(body, precedence::LAMBDA); self.unparse_expr(body, precedence::LAMBDA);
}); });
@ -1324,42 +1324,47 @@ impl<'a> Generator<'a> {
} }
} }
fn unparse_args(&mut self, args: &Arguments) { fn unparse_parameters(&mut self, parameters: &Parameters) {
let mut first = true; let mut first = true;
for (i, arg_with_default) in args.posonlyargs.iter().chain(&args.args).enumerate() { for (i, parameter_with_default) in parameters
.posonlyargs
.iter()
.chain(&parameters.args)
.enumerate()
{
self.p_delim(&mut first, ", "); self.p_delim(&mut first, ", ");
self.unparse_arg_with_default(arg_with_default); self.unparse_parameter_with_default(parameter_with_default);
self.p_if(i + 1 == args.posonlyargs.len(), ", /"); self.p_if(i + 1 == parameters.posonlyargs.len(), ", /");
} }
if args.vararg.is_some() || !args.kwonlyargs.is_empty() { if parameters.vararg.is_some() || !parameters.kwonlyargs.is_empty() {
self.p_delim(&mut first, ", "); self.p_delim(&mut first, ", ");
self.p("*"); self.p("*");
} }
if let Some(vararg) = &args.vararg { if let Some(vararg) = &parameters.vararg {
self.unparse_arg(vararg); self.unparse_parameter(vararg);
} }
for kwarg in &args.kwonlyargs { for kwarg in &parameters.kwonlyargs {
self.p_delim(&mut first, ", "); self.p_delim(&mut first, ", ");
self.unparse_arg_with_default(kwarg); self.unparse_parameter_with_default(kwarg);
} }
if let Some(kwarg) = &args.kwarg { if let Some(kwarg) = &parameters.kwarg {
self.p_delim(&mut first, ", "); self.p_delim(&mut first, ", ");
self.p("**"); self.p("**");
self.unparse_arg(kwarg); self.unparse_parameter(kwarg);
} }
} }
fn unparse_arg(&mut self, arg: &Arg) { fn unparse_parameter(&mut self, parameter: &Parameter) {
self.p_id(&arg.arg); self.p_id(&parameter.arg);
if let Some(ann) = &arg.annotation { if let Some(ann) = &parameter.annotation {
self.p(": "); self.p(": ");
self.unparse_expr(ann, precedence::COMMA); self.unparse_expr(ann, precedence::COMMA);
} }
} }
fn unparse_arg_with_default(&mut self, arg_with_default: &ArgWithDefault) { fn unparse_parameter_with_default(&mut self, parameter_with_default: &ParameterWithDefault) {
self.unparse_arg(&arg_with_default.def); self.unparse_parameter(&parameter_with_default.def);
if let Some(default) = &arg_with_default.default { if let Some(default) = &parameter_with_default.default {
self.p("="); self.p("=");
self.unparse_expr(default, precedence::COMMA); self.unparse_expr(default, precedence::COMMA);
} }

View File

@ -1,8 +1,8 @@
use std::cmp::Ordering; use std::cmp::Ordering;
use ruff_python_ast::{ use ruff_python_ast::{
self as ast, Arguments, Comprehension, Expr, ExprAttribute, ExprBinOp, ExprIfExp, ExprSlice, self as ast, Comprehension, Expr, ExprAttribute, ExprBinOp, ExprIfExp, ExprSlice, ExprStarred,
ExprStarred, MatchCase, Ranged, MatchCase, Parameters, Ranged,
}; };
use ruff_text_size::TextRange; use ruff_text_size::TextRange;
@ -15,7 +15,7 @@ use ruff_source_file::{Locator, UniversalNewlines};
use crate::comments::visitor::{CommentPlacement, DecoratedComment}; use crate::comments::visitor::{CommentPlacement, DecoratedComment};
use crate::expression::expr_slice::{assign_comment_in_slice, ExprSliceCommentSection}; use crate::expression::expr_slice::{assign_comment_in_slice, ExprSliceCommentSection};
use crate::other::arguments::{ use crate::other::parameters::{
assign_argument_separator_comment_placement, find_argument_separators, assign_argument_separator_comment_placement, find_argument_separators,
}; };
@ -44,8 +44,8 @@ pub(super) fn place_comment<'a>(
// Change comment placement depending on the node type. These can be seen as node-specific // Change comment placement depending on the node type. These can be seen as node-specific
// fixups. // fixups.
match comment.enclosing_node() { match comment.enclosing_node() {
AnyNodeRef::Arguments(arguments) => { AnyNodeRef::Parameters(arguments) => {
handle_arguments_separator_comment(comment, arguments, locator) handle_parameters_separator_comment(comment, arguments, locator)
} }
AnyNodeRef::Comprehension(comprehension) => { AnyNodeRef::Comprehension(comprehension) => {
handle_comprehension_comment(comment, comprehension, locator) handle_comprehension_comment(comment, comprehension, locator)
@ -559,16 +559,16 @@ fn handle_own_line_comment_after_branch<'a>(
} }
} }
/// Attaches comments for the positional only arguments separator `/` or the keywords only arguments /// Attaches comments for the positional-only parameters separator `/` or the keywords-only
/// separator `*` as dangling comments to the enclosing [`Arguments`] node. /// parameters separator `*` as dangling comments to the enclosing [`Parameters`] node.
/// ///
/// See [`assign_argument_separator_comment_placement`] /// See [`assign_argument_separator_comment_placement`]
fn handle_arguments_separator_comment<'a>( fn handle_parameters_separator_comment<'a>(
comment: DecoratedComment<'a>, comment: DecoratedComment<'a>,
arguments: &Arguments, parameters: &Parameters,
locator: &Locator, locator: &Locator,
) -> CommentPlacement<'a> { ) -> CommentPlacement<'a> {
let (slash, star) = find_argument_separators(locator.contents(), arguments); let (slash, star) = find_argument_separators(locator.contents(), parameters);
let comment_range = comment.slice().range(); let comment_range = comment.slice().range();
let placement = assign_argument_separator_comment_placement( let placement = assign_argument_separator_comment_placement(
slash.as_ref(), slash.as_ref(),
@ -832,11 +832,11 @@ fn handle_leading_function_with_decorators_comment(comment: DecoratedComment) ->
.preceding_node() .preceding_node()
.is_some_and(|node| node.is_decorator()); .is_some_and(|node| node.is_decorator());
let is_following_arguments = comment let is_following_parameters = comment
.following_node() .following_node()
.is_some_and(|node| node.is_arguments()); .is_some_and(|node| node.is_parameters());
if comment.line_position().is_own_line() && is_preceding_decorator && is_following_arguments { if comment.line_position().is_own_line() && is_preceding_decorator && is_following_parameters {
CommentPlacement::dangling(comment.enclosing_node(), comment) CommentPlacement::dangling(comment.enclosing_node(), comment)
} else { } else {
CommentPlacement::Default(comment) CommentPlacement::Default(comment)

View File

@ -4,7 +4,7 @@ expression: comments.debug(test_case.source_code)
--- ---
{ {
Node { Node {
kind: Arguments, kind: Parameters,
range: 9..39, range: 9..39,
source: `(⏎`, source: `(⏎`,
}: { }: {

View File

@ -4,7 +4,7 @@ expression: comments.debug(test_case.source_code)
--- ---
{ {
Node { Node {
kind: Arguments, kind: Parameters,
range: 9..96, range: 9..96,
source: `(a=10,/, # trailing positio...t comment.⏎`, source: `(a=10,/, # trailing positio...t comment.⏎`,
}: { }: {
@ -19,7 +19,7 @@ expression: comments.debug(test_case.source_code)
"trailing": [], "trailing": [],
}, },
Node { Node {
kind: ArgWithDefault, kind: ParameterWithDefault,
range: 90..94, range: 90..94,
source: `b=20`, source: `b=20`,
}: { }: {

View File

@ -4,7 +4,7 @@ expression: comments.debug(test_case.source_code)
--- ---
{ {
Node { Node {
kind: Arguments, kind: Parameters,
range: 9..179, range: 9..179,
source: `(⏎`, source: `(⏎`,
}: { }: {
@ -24,7 +24,7 @@ expression: comments.debug(test_case.source_code)
"trailing": [], "trailing": [],
}, },
Node { Node {
kind: ArgWithDefault, kind: ParameterWithDefault,
range: 15..19, range: 15..19,
source: `a=10`, source: `a=10`,
}: { }: {
@ -39,7 +39,7 @@ expression: comments.debug(test_case.source_code)
], ],
}, },
Node { Node {
kind: ArgWithDefault, kind: ParameterWithDefault,
range: 173..177, range: 173..177,
source: `b=20`, source: `b=20`,
}: { }: {

View File

@ -4,7 +4,7 @@ expression: comments.debug(test_case.source_code)
--- ---
{ {
Node { Node {
kind: Arguments, kind: Parameters,
range: 9..170, range: 9..170,
source: `(⏎`, source: `(⏎`,
}: { }: {
@ -24,7 +24,7 @@ expression: comments.debug(test_case.source_code)
"trailing": [], "trailing": [],
}, },
Node { Node {
kind: ArgWithDefault, kind: ParameterWithDefault,
range: 15..16, range: 15..16,
source: `a`, source: `a`,
}: { }: {
@ -39,7 +39,7 @@ expression: comments.debug(test_case.source_code)
], ],
}, },
Node { Node {
kind: ArgWithDefault, kind: ParameterWithDefault,
range: 166..167, range: 166..167,
source: `b`, source: `b`,
}: { }: {

View File

@ -4,7 +4,7 @@ expression: comments.debug(test_case.source_code)
--- ---
{ {
Node { Node {
kind: Arguments, kind: Parameters,
range: 9..166, range: 9..166,
source: `(⏎`, source: `(⏎`,
}: { }: {
@ -24,7 +24,7 @@ expression: comments.debug(test_case.source_code)
"trailing": [], "trailing": [],
}, },
Node { Node {
kind: ArgWithDefault, kind: ParameterWithDefault,
range: 15..16, range: 15..16,
source: `a`, source: `a`,
}: { }: {

View File

@ -4,7 +4,7 @@ expression: comments.debug(test_case.source_code)
--- ---
{ {
Node { Node {
kind: Arguments, kind: Parameters,
range: 9..170, range: 9..170,
source: `(⏎`, source: `(⏎`,
}: { }: {
@ -24,7 +24,7 @@ expression: comments.debug(test_case.source_code)
"trailing": [], "trailing": [],
}, },
Node { Node {
kind: ArgWithDefault, kind: ParameterWithDefault,
range: 15..16, range: 15..16,
source: `a`, source: `a`,
}: { }: {
@ -39,7 +39,7 @@ expression: comments.debug(test_case.source_code)
], ],
}, },
Node { Node {
kind: ArgWithDefault, kind: ParameterWithDefault,
range: 166..167, range: 166..167,
source: `b`, source: `b`,
}: { }: {

View File

@ -4,7 +4,7 @@ expression: comments.debug(test_case.source_code)
--- ---
{ {
Node { Node {
kind: ArgWithDefault, kind: ParameterWithDefault,
range: 15..16, range: 15..16,
source: `a`, source: `a`,
}: { }: {

View File

@ -1,8 +1,8 @@
use std::iter::Peekable; use std::iter::Peekable;
use ruff_python_ast::{ use ruff_python_ast::{
Alias, Arg, ArgWithDefault, Arguments, Comprehension, Decorator, ElifElseClause, ExceptHandler, Alias, Comprehension, Decorator, ElifElseClause, ExceptHandler, Expr, Keyword, MatchCase, Mod,
Expr, Keyword, MatchCase, Mod, Pattern, Ranged, Stmt, TypeParam, WithItem, Parameter, ParameterWithDefault, Parameters, Pattern, Ranged, Stmt, TypeParam, WithItem,
}; };
use ruff_text_size::{TextRange, TextSize}; use ruff_text_size::{TextRange, TextSize};
@ -229,25 +229,25 @@ impl<'ast> PreorderVisitor<'ast> for CommentsVisitor<'ast> {
self.finish_node(format_spec); self.finish_node(format_spec);
} }
fn visit_arguments(&mut self, arguments: &'ast Arguments) { fn visit_parameters(&mut self, parameters: &'ast Parameters) {
if self.start_node(arguments).is_traverse() { if self.start_node(parameters).is_traverse() {
walk_arguments(self, arguments); walk_parameters(self, parameters);
} }
self.finish_node(arguments); self.finish_node(parameters);
} }
fn visit_arg(&mut self, arg: &'ast Arg) { fn visit_parameter(&mut self, arg: &'ast Parameter) {
if self.start_node(arg).is_traverse() { if self.start_node(arg).is_traverse() {
walk_arg(self, arg); walk_parameter(self, arg);
} }
self.finish_node(arg); self.finish_node(arg);
} }
fn visit_arg_with_default(&mut self, arg_with_default: &'ast ArgWithDefault) { fn visit_parameter_with_default(&mut self, parameter_with_default: &'ast ParameterWithDefault) {
if self.start_node(arg_with_default).is_traverse() { if self.start_node(parameter_with_default).is_traverse() {
walk_arg_with_default(self, arg_with_default); walk_parameter_with_default(self, parameter_with_default);
} }
self.finish_node(arg_with_default); self.finish_node(parameter_with_default);
} }
fn visit_keyword(&mut self, keyword: &'ast Keyword) { fn visit_keyword(&mut self, keyword: &'ast Keyword) {

View File

@ -1,7 +1,7 @@
use crate::comments::dangling_node_comments; use crate::comments::dangling_node_comments;
use crate::context::PyFormatContext; use crate::context::PyFormatContext;
use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses}; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses};
use crate::other::arguments::ArgumentsParentheses; use crate::other::parameters::ParametersParentheses;
use crate::AsFormat; use crate::AsFormat;
use crate::{FormatNodeRule, PyFormatter}; use crate::{FormatNodeRule, PyFormatter};
use ruff_formatter::prelude::{space, text}; use ruff_formatter::prelude::{space, text};
@ -16,18 +16,20 @@ impl FormatNodeRule<ExprLambda> for FormatExprLambda {
fn fmt_fields(&self, item: &ExprLambda, f: &mut PyFormatter) -> FormatResult<()> { fn fmt_fields(&self, item: &ExprLambda, f: &mut PyFormatter) -> FormatResult<()> {
let ExprLambda { let ExprLambda {
range: _, range: _,
args, parameters,
body, body,
} = item; } = item;
write!(f, [text("lambda")])?; write!(f, [text("lambda")])?;
if !args.args.is_empty() { if !parameters.args.is_empty() {
write!( write!(
f, f,
[ [
space(), space(),
args.format().with_options(ArgumentsParentheses::Never), parameters
.format()
.with_options(ParametersParentheses::Never),
] ]
)?; )?;
} }
@ -44,7 +46,7 @@ impl FormatNodeRule<ExprLambda> for FormatExprLambda {
// lambda # Dangling // lambda # Dangling
// : 1 // : 1
// ) // )
dangling_node_comments(args.as_ref()) dangling_node_comments(parameters.as_ref())
] ]
) )
} }

View File

@ -2617,95 +2617,108 @@ impl<'ast> IntoFormat<PyFormatContext<'ast>> for ast::Comprehension {
} }
} }
impl FormatRule<ast::Arguments, PyFormatContext<'_>> for crate::other::arguments::FormatArguments { impl FormatRule<ast::Parameters, PyFormatContext<'_>>
#[inline] for crate::other::parameters::FormatParameters
fn fmt(
&self,
node: &ast::Arguments,
f: &mut Formatter<PyFormatContext<'_>>,
) -> FormatResult<()> {
FormatNodeRule::<ast::Arguments>::fmt(self, node, f)
}
}
impl<'ast> AsFormat<PyFormatContext<'ast>> for ast::Arguments {
type Format<'a> = FormatRefWithRule<
'a,
ast::Arguments,
crate::other::arguments::FormatArguments,
PyFormatContext<'ast>,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(self, crate::other::arguments::FormatArguments::default())
}
}
impl<'ast> IntoFormat<PyFormatContext<'ast>> for ast::Arguments {
type Format = FormatOwnedWithRule<
ast::Arguments,
crate::other::arguments::FormatArguments,
PyFormatContext<'ast>,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(self, crate::other::arguments::FormatArguments::default())
}
}
impl FormatRule<ast::Arg, PyFormatContext<'_>> for crate::other::arg::FormatArg {
#[inline]
fn fmt(&self, node: &ast::Arg, f: &mut Formatter<PyFormatContext<'_>>) -> FormatResult<()> {
FormatNodeRule::<ast::Arg>::fmt(self, node, f)
}
}
impl<'ast> AsFormat<PyFormatContext<'ast>> for ast::Arg {
type Format<'a> =
FormatRefWithRule<'a, ast::Arg, crate::other::arg::FormatArg, PyFormatContext<'ast>>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(self, crate::other::arg::FormatArg::default())
}
}
impl<'ast> IntoFormat<PyFormatContext<'ast>> for ast::Arg {
type Format =
FormatOwnedWithRule<ast::Arg, crate::other::arg::FormatArg, PyFormatContext<'ast>>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(self, crate::other::arg::FormatArg::default())
}
}
impl FormatRule<ast::ArgWithDefault, PyFormatContext<'_>>
for crate::other::arg_with_default::FormatArgWithDefault
{ {
#[inline] #[inline]
fn fmt( fn fmt(
&self, &self,
node: &ast::ArgWithDefault, node: &ast::Parameters,
f: &mut Formatter<PyFormatContext<'_>>, f: &mut Formatter<PyFormatContext<'_>>,
) -> FormatResult<()> { ) -> FormatResult<()> {
FormatNodeRule::<ast::ArgWithDefault>::fmt(self, node, f) FormatNodeRule::<ast::Parameters>::fmt(self, node, f)
} }
} }
impl<'ast> AsFormat<PyFormatContext<'ast>> for ast::ArgWithDefault { impl<'ast> AsFormat<PyFormatContext<'ast>> for ast::Parameters {
type Format<'a> = FormatRefWithRule< type Format<'a> = FormatRefWithRule<
'a, 'a,
ast::ArgWithDefault, ast::Parameters,
crate::other::arg_with_default::FormatArgWithDefault, crate::other::parameters::FormatParameters,
PyFormatContext<'ast>,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(self, crate::other::parameters::FormatParameters::default())
}
}
impl<'ast> IntoFormat<PyFormatContext<'ast>> for ast::Parameters {
type Format = FormatOwnedWithRule<
ast::Parameters,
crate::other::parameters::FormatParameters,
PyFormatContext<'ast>,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(self, crate::other::parameters::FormatParameters::default())
}
}
impl FormatRule<ast::Parameter, PyFormatContext<'_>> for crate::other::parameter::FormatParameter {
#[inline]
fn fmt(
&self,
node: &ast::Parameter,
f: &mut Formatter<PyFormatContext<'_>>,
) -> FormatResult<()> {
FormatNodeRule::<ast::Parameter>::fmt(self, node, f)
}
}
impl<'ast> AsFormat<PyFormatContext<'ast>> for ast::Parameter {
type Format<'a> = FormatRefWithRule<
'a,
ast::Parameter,
crate::other::parameter::FormatParameter,
PyFormatContext<'ast>,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(self, crate::other::parameter::FormatParameter::default())
}
}
impl<'ast> IntoFormat<PyFormatContext<'ast>> for ast::Parameter {
type Format = FormatOwnedWithRule<
ast::Parameter,
crate::other::parameter::FormatParameter,
PyFormatContext<'ast>,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(self, crate::other::parameter::FormatParameter::default())
}
}
impl FormatRule<ast::ParameterWithDefault, PyFormatContext<'_>>
for crate::other::parameter_with_default::FormatParameterWithDefault
{
#[inline]
fn fmt(
&self,
node: &ast::ParameterWithDefault,
f: &mut Formatter<PyFormatContext<'_>>,
) -> FormatResult<()> {
FormatNodeRule::<ast::ParameterWithDefault>::fmt(self, node, f)
}
}
impl<'ast> AsFormat<PyFormatContext<'ast>> for ast::ParameterWithDefault {
type Format<'a> = FormatRefWithRule<
'a,
ast::ParameterWithDefault,
crate::other::parameter_with_default::FormatParameterWithDefault,
PyFormatContext<'ast>, PyFormatContext<'ast>,
>; >;
fn format(&self) -> Self::Format<'_> { fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new( FormatRefWithRule::new(
self, self,
crate::other::arg_with_default::FormatArgWithDefault::default(), crate::other::parameter_with_default::FormatParameterWithDefault::default(),
) )
} }
} }
impl<'ast> IntoFormat<PyFormatContext<'ast>> for ast::ArgWithDefault { impl<'ast> IntoFormat<PyFormatContext<'ast>> for ast::ParameterWithDefault {
type Format = FormatOwnedWithRule< type Format = FormatOwnedWithRule<
ast::ArgWithDefault, ast::ParameterWithDefault,
crate::other::arg_with_default::FormatArgWithDefault, crate::other::parameter_with_default::FormatParameterWithDefault,
PyFormatContext<'ast>, PyFormatContext<'ast>,
>; >;
fn into_format(self) -> Self::Format { fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new( FormatOwnedWithRule::new(
self, self,
crate::other::arg_with_default::FormatArgWithDefault::default(), crate::other::parameter_with_default::FormatParameterWithDefault::default(),
) )
} }
} }

View File

@ -1,7 +1,4 @@
pub(crate) mod alias; pub(crate) mod alias;
pub(crate) mod arg;
pub(crate) mod arg_with_default;
pub(crate) mod arguments;
pub(crate) mod comprehension; pub(crate) mod comprehension;
pub(crate) mod decorator; pub(crate) mod decorator;
pub(crate) mod elif_else_clause; pub(crate) mod elif_else_clause;
@ -9,4 +6,7 @@ pub(crate) mod except_handler_except_handler;
pub(crate) mod identifier; pub(crate) mod identifier;
pub(crate) mod keyword; pub(crate) mod keyword;
pub(crate) mod match_case; pub(crate) mod match_case;
pub(crate) mod parameter;
pub(crate) mod parameter_with_default;
pub(crate) mod parameters;
pub(crate) mod with_item; pub(crate) mod with_item;

View File

@ -1,14 +1,14 @@
use crate::prelude::*; use crate::prelude::*;
use crate::FormatNodeRule; use crate::FormatNodeRule;
use ruff_formatter::write; use ruff_formatter::write;
use ruff_python_ast::Arg; use ruff_python_ast::Parameter;
#[derive(Default)] #[derive(Default)]
pub struct FormatArg; pub struct FormatParameter;
impl FormatNodeRule<Arg> for FormatArg { impl FormatNodeRule<Parameter> for FormatParameter {
fn fmt_fields(&self, item: &Arg, f: &mut PyFormatter) -> FormatResult<()> { fn fmt_fields(&self, item: &Parameter, f: &mut PyFormatter) -> FormatResult<()> {
let Arg { let Parameter {
range: _, range: _,
arg, arg,
annotation, annotation,

View File

@ -1,15 +1,15 @@
use ruff_formatter::write; use ruff_formatter::write;
use ruff_python_ast::ArgWithDefault; use ruff_python_ast::ParameterWithDefault;
use crate::prelude::*; use crate::prelude::*;
use crate::FormatNodeRule; use crate::FormatNodeRule;
#[derive(Default)] #[derive(Default)]
pub struct FormatArgWithDefault; pub struct FormatParameterWithDefault;
impl FormatNodeRule<ArgWithDefault> for FormatArgWithDefault { impl FormatNodeRule<ParameterWithDefault> for FormatParameterWithDefault {
fn fmt_fields(&self, item: &ArgWithDefault, f: &mut PyFormatter) -> FormatResult<()> { fn fmt_fields(&self, item: &ParameterWithDefault, f: &mut PyFormatter) -> FormatResult<()> {
let ArgWithDefault { let ParameterWithDefault {
range: _, range: _,
def, def,
default, default,

View File

@ -1,6 +1,6 @@
use std::usize; use std::usize;
use ruff_python_ast::{Arguments, Ranged}; use ruff_python_ast::{Parameters, Ranged};
use ruff_text_size::{TextRange, TextSize}; use ruff_text_size::{TextRange, TextSize};
use ruff_formatter::{format_args, write, FormatRuleWithOptions}; use ruff_formatter::{format_args, write, FormatRuleWithOptions};
@ -17,14 +17,14 @@ use crate::prelude::*;
use crate::FormatNodeRule; use crate::FormatNodeRule;
#[derive(Eq, PartialEq, Debug, Default)] #[derive(Eq, PartialEq, Debug, Default)]
pub enum ArgumentsParentheses { pub enum ParametersParentheses {
/// By default, arguments will always preserve their surrounding parentheses. /// By default, parameters will always preserve their surrounding parentheses.
#[default] #[default]
Preserve, Preserve,
/// Handle special cases where parentheses should never be used. /// Handle special cases where parentheses should never be used.
/// ///
/// An example where parentheses are never used for arguments would be with lambda /// An example where parentheses are never used for parameters would be with lambda
/// expressions. The following is invalid syntax: /// expressions. The following is invalid syntax:
/// ```python /// ```python
/// lambda (x, y, z): ... /// lambda (x, y, z): ...
@ -37,12 +37,12 @@ pub enum ArgumentsParentheses {
} }
#[derive(Default)] #[derive(Default)]
pub struct FormatArguments { pub struct FormatParameters {
parentheses: ArgumentsParentheses, parentheses: ParametersParentheses,
} }
impl FormatRuleWithOptions<Arguments, PyFormatContext<'_>> for FormatArguments { impl FormatRuleWithOptions<Parameters, PyFormatContext<'_>> for FormatParameters {
type Options = ArgumentsParentheses; type Options = ParametersParentheses;
fn with_options(mut self, options: Self::Options) -> Self { fn with_options(mut self, options: Self::Options) -> Self {
self.parentheses = options; self.parentheses = options;
@ -50,9 +50,9 @@ impl FormatRuleWithOptions<Arguments, PyFormatContext<'_>> for FormatArguments {
} }
} }
impl FormatNodeRule<Arguments> for FormatArguments { impl FormatNodeRule<Parameters> for FormatParameters {
fn fmt_fields(&self, item: &Arguments, f: &mut PyFormatter) -> FormatResult<()> { fn fmt_fields(&self, item: &Parameters, f: &mut PyFormatter) -> FormatResult<()> {
let Arguments { let Parameters {
range: _, range: _,
posonlyargs, posonlyargs,
args, args,
@ -70,10 +70,10 @@ impl FormatNodeRule<Arguments> for FormatArguments {
let mut joiner = f.join_with(separator); let mut joiner = f.join_with(separator);
let mut last_node: Option<AnyNodeRef> = None; let mut last_node: Option<AnyNodeRef> = None;
for arg_with_default in posonlyargs { for parameter_with_default in posonlyargs {
joiner.entry(&arg_with_default.format()); joiner.entry(&parameter_with_default.format());
last_node = Some(arg_with_default.into()); last_node = Some(parameter_with_default.into());
} }
let slash_comments_end = if posonlyargs.is_empty() { let slash_comments_end = if posonlyargs.is_empty() {
@ -86,7 +86,7 @@ impl FormatNodeRule<Arguments> for FormatArguments {
comment.slice().range(), comment.slice().range(),
comment.line_position(), comment.line_position(),
) )
.expect("Unexpected dangling comment type in function arguments"); .expect("Unexpected dangling comment type in function parameters");
matches!( matches!(
assignment, assignment,
ArgumentSeparatorCommentLocation::SlashLeading ArgumentSeparatorCommentLocation::SlashLeading
@ -100,10 +100,10 @@ impl FormatNodeRule<Arguments> for FormatArguments {
slash_comments_end slash_comments_end
}; };
for arg_with_default in args { for parameter_with_default in args {
joiner.entry(&arg_with_default.format()); joiner.entry(&parameter_with_default.format());
last_node = Some(arg_with_default.into()); last_node = Some(parameter_with_default.into());
} }
// kw only args need either a `*args` ahead of them capturing all var args or a `*` // kw only args need either a `*args` ahead of them capturing all var args or a `*`
@ -139,10 +139,10 @@ impl FormatNodeRule<Arguments> for FormatArguments {
}); });
} }
for arg_with_default in kwonlyargs { for parameter_with_default in kwonlyargs {
joiner.entry(&arg_with_default.format()); joiner.entry(&parameter_with_default.format());
last_node = Some(arg_with_default.into()); last_node = Some(parameter_with_default.into());
} }
if let Some(kwarg) = kwarg { if let Some(kwarg) = kwarg {
@ -168,7 +168,7 @@ impl FormatNodeRule<Arguments> for FormatArguments {
// # Never expands, the comma is always preserved // # Never expands, the comma is always preserved
// x2 = lambda y,: 1 // x2 = lambda y,: 1
// ``` // ```
if self.parentheses == ArgumentsParentheses::Never { if self.parentheses == ParametersParentheses::Never {
// For lambdas (no parentheses), preserve the trailing comma. It doesn't // For lambdas (no parentheses), preserve the trailing comma. It doesn't
// behave like a magic trailing comma, it's just preserved // behave like a magic trailing comma, it's just preserved
if has_trailing_comma(item, last_node, f.context().source()) { if has_trailing_comma(item, last_node, f.context().source()) {
@ -190,16 +190,16 @@ impl FormatNodeRule<Arguments> for FormatArguments {
let mut f = WithNodeLevel::new(NodeLevel::ParenthesizedExpression, f); let mut f = WithNodeLevel::new(NodeLevel::ParenthesizedExpression, f);
let num_arguments = posonlyargs.len() let num_parameters = posonlyargs.len()
+ args.len() + args.len()
+ usize::from(vararg.is_some()) + usize::from(vararg.is_some())
+ kwonlyargs.len() + kwonlyargs.len()
+ usize::from(kwarg.is_some()); + usize::from(kwarg.is_some());
if self.parentheses == ArgumentsParentheses::Never { if self.parentheses == ParametersParentheses::Never {
write!(f, [group(&format_inner)]) write!(f, [group(&format_inner)])
} else if num_arguments == 0 { } else if num_parameters == 0 {
// No arguments, format any dangling comments between `()` // No parameters, format any dangling comments between `()`
write!( write!(
f, f,
[ [
@ -213,7 +213,7 @@ impl FormatNodeRule<Arguments> for FormatArguments {
} }
} }
fn fmt_dangling_comments(&self, _node: &Arguments, _f: &mut PyFormatter) -> FormatResult<()> { fn fmt_dangling_comments(&self, _node: &Parameters, _f: &mut PyFormatter) -> FormatResult<()> {
// Handled in `fmt_fields` // Handled in `fmt_fields`
Ok(()) Ok(())
} }
@ -283,18 +283,18 @@ pub(crate) struct ArgumentSeparator {
/// Returns slash and star /// Returns slash and star
pub(crate) fn find_argument_separators( pub(crate) fn find_argument_separators(
contents: &str, contents: &str,
arguments: &Arguments, parameters: &Parameters,
) -> (Option<ArgumentSeparator>, Option<ArgumentSeparator>) { ) -> (Option<ArgumentSeparator>, Option<ArgumentSeparator>) {
// We only compute preceding_end and token location here since following_start depends on the // We only compute preceding_end and token location here since following_start depends on the
// star location, but the star location depends on slash's position // star location, but the star location depends on slash's position
let slash = if let Some(preceding_end) = arguments.posonlyargs.last().map(Ranged::end) { let slash = if let Some(preceding_end) = parameters.posonlyargs.last().map(Ranged::end) {
// ```text // ```text
// def f(a1=1, a2=2, /, a3, a4): pass // def f(a1=1, a2=2, /, a3, a4): pass
// ^^^^^^^^^^^ the range (defaults) // ^^^^^^^^^^^ the range (defaults)
// def f(a1, a2, /, a3, a4): pass // def f(a1, a2, /, a3, a4): pass
// ^^^^^^^^^^^^ the range (no default) // ^^^^^^^^^^^^ the range (no default)
// ``` // ```
let range = TextRange::new(preceding_end, arguments.end()); let range = TextRange::new(preceding_end, parameters.end());
let mut tokens = SimpleTokenizer::new(contents, range).skip_trivia(); let mut tokens = SimpleTokenizer::new(contents, range).skip_trivia();
let comma = tokens let comma = tokens
@ -312,22 +312,22 @@ pub(crate) fn find_argument_separators(
}; };
// If we have a vararg we have a node that the comments attach to // If we have a vararg we have a node that the comments attach to
let star = if arguments.vararg.is_some() { let star = if parameters.vararg.is_some() {
// When the vararg is present the comments attach there and we don't need to do manual // When the vararg is present the comments attach there and we don't need to do manual
// formatting // formatting
None None
} else if let Some(first_keyword_argument) = arguments.kwonlyargs.first() { } else if let Some(first_keyword_argument) = parameters.kwonlyargs.first() {
// Check in that order: // Check in that order:
// * `f(a, /, b, *, c)` and `f(a=1, /, b=2, *, c)` // * `f(a, /, b, *, c)` and `f(a=1, /, b=2, *, c)`
// * `f(a, /, *, b)` // * `f(a, /, *, b)`
// * `f(*, b)` (else branch) // * `f(*, b)` (else branch)
let after_arguments = arguments let after_parameters = parameters
.args .args
.last() .last()
.map(|arg| arg.range.end()) .map(|arg| arg.range.end())
.or(slash.map(|(_, slash)| slash.end())); .or(slash.map(|(_, slash)| slash.end()));
if let Some(preceding_end) = after_arguments { if let Some(preceding_end) = after_parameters {
let range = TextRange::new(preceding_end, arguments.end()); let range = TextRange::new(preceding_end, parameters.end());
let mut tokens = SimpleTokenizer::new(contents, range).skip_trivia(); let mut tokens = SimpleTokenizer::new(contents, range).skip_trivia();
let comma = tokens let comma = tokens
@ -345,7 +345,7 @@ pub(crate) fn find_argument_separators(
following_start: first_keyword_argument.start(), following_start: first_keyword_argument.start(),
}) })
} else { } else {
let mut tokens = SimpleTokenizer::new(contents, arguments.range).skip_trivia(); let mut tokens = SimpleTokenizer::new(contents, parameters.range).skip_trivia();
let lparen = tokens let lparen = tokens
.next() .next()
@ -356,7 +356,7 @@ pub(crate) fn find_argument_separators(
.expect("The function definition can't end here"); .expect("The function definition can't end here");
debug_assert!(star.kind() == SimpleTokenKind::Star, "{star:?}"); debug_assert!(star.kind() == SimpleTokenKind::Star, "{star:?}");
Some(ArgumentSeparator { Some(ArgumentSeparator {
preceding_end: arguments.range.start(), preceding_end: parameters.range.start(),
separator: star.range, separator: star.range,
following_start: first_keyword_argument.start(), following_start: first_keyword_argument.start(),
}) })
@ -371,13 +371,13 @@ pub(crate) fn find_argument_separators(
// * `f(a, /, *b)` // * `f(a, /, *b)`
// * `f(a, /, *, b)` // * `f(a, /, *, b)`
// * `f(a, /)` // * `f(a, /)`
let slash_following_start = arguments let slash_following_start = parameters
.args .args
.first() .first()
.map(Ranged::start) .map(Ranged::start)
.or(arguments.vararg.as_ref().map(|first| first.start())) .or(parameters.vararg.as_ref().map(|first| first.start()))
.or(star.as_ref().map(|star| star.separator.start())) .or(star.as_ref().map(|star| star.separator.start()))
.unwrap_or(arguments.end()); .unwrap_or(parameters.end());
let slash = slash.map(|(preceding_end, slash)| ArgumentSeparator { let slash = slash.map(|(preceding_end, slash)| ArgumentSeparator {
preceding_end, preceding_end,
separator: slash, separator: slash,
@ -387,13 +387,13 @@ pub(crate) fn find_argument_separators(
(slash, star) (slash, star)
} }
/// Locates positional only arguments separator `/` or the keywords only arguments /// Locates positional only parameters separator `/` or the keywords only parameters
/// separator `*` comments. /// separator `*` comments.
/// ///
/// ```python /// ```python
/// def test( /// def test(
/// a, /// a,
/// # Positional only arguments after here /// # Positional only parameters after here
/// /, # trailing positional argument comment. /// /, # trailing positional argument comment.
/// b, /// b,
/// ): /// ):
@ -403,7 +403,7 @@ pub(crate) fn find_argument_separators(
/// ```python /// ```python
/// def f( /// def f(
/// a="", /// a="",
/// # Keyword only arguments only after here /// # Keyword only parameters only after here
/// *, # trailing keyword argument comment. /// *, # trailing keyword argument comment.
/// b="", /// b="",
/// ): /// ):
@ -439,43 +439,43 @@ pub(crate) fn find_argument_separators(
/// ///
/// ```text /// ```text
/// def f(a1, a2): pass /// def f(a1, a2): pass
/// ^^^^^^ arguments (args) /// ^^^^^^ parameters (args)
/// ``` /// ```
/// Use a star to separate keyword only arguments: /// Use a star to separate keyword only parameters:
/// ```text /// ```text
/// def f(a1, a2, *, a3, a4): pass /// def f(a1, a2, *, a3, a4): pass
/// ^^^^^^ arguments (args) /// ^^^^^^ parameters (args)
/// ^^^^^^ keyword only arguments (kwargs) /// ^^^^^^ keyword only parameters (kwargs)
/// ``` /// ```
/// Use a slash to separate positional only arguments. Note that this changes the arguments left /// Use a slash to separate positional only parameters. Note that this changes the parameters left
/// of the slash while the star change the arguments right of it: /// of the slash while the star change the parameters right of it:
/// ```text /// ```text
/// def f(a1, a2, /, a3, a4): pass /// def f(a1, a2, /, a3, a4): pass
/// ^^^^^^ positional only arguments (posonlyargs) /// ^^^^^^ positional only parameters (posonlyargs)
/// ^^^^^^ arguments (args) /// ^^^^^^ parameters (args)
/// ``` /// ```
/// You can combine both: /// You can combine both:
/// ```text /// ```text
/// def f(a1, a2, /, a3, a4, *, a5, a6): pass /// def f(a1, a2, /, a3, a4, *, a5, a6): pass
/// ^^^^^^ positional only arguments (posonlyargs) /// ^^^^^^ positional only parameters (posonlyargs)
/// ^^^^^^ arguments (args) /// ^^^^^^ parameters (args)
/// ^^^^^^ keyword only arguments (kwargs) /// ^^^^^^ keyword only parameters (kwargs)
/// ``` /// ```
/// They can all have defaults, meaning that the preceding node ends at the default instead of the /// They can all have defaults, meaning that the preceding node ends at the default instead of the
/// argument itself: /// argument itself:
/// ```text /// ```text
/// def f(a1=1, a2=2, /, a3=3, a4=4, *, a5=5, a6=6): pass /// def f(a1=1, a2=2, /, a3=3, a4=4, *, a5=5, a6=6): pass
/// ^ ^ ^ ^ ^ ^ defaults /// ^ ^ ^ ^ ^ ^ defaults
/// ^^^^^^^^^^ positional only arguments (posonlyargs) /// ^^^^^^^^^^ positional only parameters (posonlyargs)
/// ^^^^^^^^^^ arguments (args) /// ^^^^^^^^^^ parameters (args)
/// ^^^^^^^^^^ keyword only arguments (kwargs) /// ^^^^^^^^^^ keyword only parameters (kwargs)
/// ``` /// ```
/// An especially difficult case is having no regular arguments, so comments from both slash and /// An especially difficult case is having no regular parameters, so comments from both slash and
/// star will attach to either a2 or a3 and the next token is incorrect. /// star will attach to either a2 or a3 and the next token is incorrect.
/// ```text /// ```text
/// def f(a1, a2, /, *, a3, a4): pass /// def f(a1, a2, /, *, a3, a4): pass
/// ^^^^^^ positional only arguments (posonlyargs) /// ^^^^^^ positional only parameters (posonlyargs)
/// ^^^^^^ keyword only arguments (kwargs) /// ^^^^^^ keyword only parameters (kwargs)
/// ``` /// ```
pub(crate) fn assign_argument_separator_comment_placement( pub(crate) fn assign_argument_separator_comment_placement(
slash: Option<&ArgumentSeparator>, slash: Option<&ArgumentSeparator>,
@ -583,27 +583,31 @@ pub(crate) enum ArgumentSeparatorCommentLocation {
StarTrailing, StarTrailing,
} }
fn has_trailing_comma(arguments: &Arguments, last_node: Option<AnyNodeRef>, source: &str) -> bool { fn has_trailing_comma(
parameters: &Parameters,
last_node: Option<AnyNodeRef>,
source: &str,
) -> bool {
// No nodes, no trailing comma // No nodes, no trailing comma
let Some(last_node) = last_node else { let Some(last_node) = last_node else {
return false; return false;
}; };
let ends_with_pos_only_argument_separator = !arguments.posonlyargs.is_empty() let ends_with_pos_only_argument_separator = !parameters.posonlyargs.is_empty()
&& arguments.args.is_empty() && parameters.args.is_empty()
&& arguments.vararg.is_none() && parameters.vararg.is_none()
&& arguments.kwonlyargs.is_empty() && parameters.kwonlyargs.is_empty()
&& arguments.kwarg.is_none(); && parameters.kwarg.is_none();
let mut tokens = SimpleTokenizer::starts_at(last_node.end(), source).skip_trivia(); let mut tokens = SimpleTokenizer::starts_at(last_node.end(), source).skip_trivia();
// `def a(b, c, /): ... ` // `def a(b, c, /): ... `
// The slash lacks its own node // The slash lacks its own node
if ends_with_pos_only_argument_separator { if ends_with_pos_only_argument_separator {
let comma = tokens.next(); let comma = tokens.next();
assert!(matches!(comma, Some(SimpleToken { kind: SimpleTokenKind::Comma, .. })), "The last positional only argument must be separated by a `,` from the positional only arguments separator `/` but found '{comma:?}'."); assert!(matches!(comma, Some(SimpleToken { kind: SimpleTokenKind::Comma, .. })), "The last positional only argument must be separated by a `,` from the positional only parameters separator `/` but found '{comma:?}'.");
let slash = tokens.next(); let slash = tokens.next();
assert!(matches!(slash, Some(SimpleToken { kind: SimpleTokenKind::Slash, .. })), "The positional argument separator must be present for a function that has positional only arguments but found '{slash:?}'."); assert!(matches!(slash, Some(SimpleToken { kind: SimpleTokenKind::Slash, .. })), "The positional argument separator must be present for a function that has positional only parameters but found '{slash:?}'.");
} }
tokens tokens

View File

@ -12,7 +12,7 @@ pub(crate) struct ArgumentList {
} }
// Perform validation of function/lambda arguments in a function definition. // Perform validation of function/lambda arguments in a function definition.
pub(crate) fn validate_arguments(arguments: &ast::Arguments) -> Result<(), LexicalError> { pub(crate) fn validate_arguments(arguments: &ast::Parameters) -> Result<(), LexicalError> {
let mut all_arg_names = FxHashSet::with_capacity_and_hasher( let mut all_arg_names = FxHashSet::with_capacity_and_hasher(
arguments.posonlyargs.len() arguments.posonlyargs.len()
+ arguments.args.len() + arguments.args.len()
@ -26,8 +26,8 @@ pub(crate) fn validate_arguments(arguments: &ast::Arguments) -> Result<(), Lexic
let args = arguments.args.iter(); let args = arguments.args.iter();
let kwonlyargs = arguments.kwonlyargs.iter(); let kwonlyargs = arguments.kwonlyargs.iter();
let vararg: Option<&ast::Arg> = arguments.vararg.as_deref(); let vararg: Option<&ast::Parameter> = arguments.vararg.as_deref();
let kwarg: Option<&ast::Arg> = arguments.kwarg.as_deref(); let kwarg: Option<&ast::Parameter> = arguments.kwarg.as_deref();
for arg in posonlyargs for arg in posonlyargs
.chain(args) .chain(args)
@ -50,7 +50,10 @@ pub(crate) fn validate_arguments(arguments: &ast::Arguments) -> Result<(), Lexic
} }
pub(crate) fn validate_pos_params( pub(crate) fn validate_pos_params(
args: &(Vec<ast::ArgWithDefault>, Vec<ast::ArgWithDefault>), args: &(
Vec<ast::ParameterWithDefault>,
Vec<ast::ParameterWithDefault>,
),
) -> Result<(), LexicalError> { ) -> Result<(), LexicalError> {
let (posonlyargs, args) = args; let (posonlyargs, args) = args;
#[allow(clippy::skip_while_next)] #[allow(clippy::skip_while_next)]

View File

@ -1015,9 +1015,9 @@ FuncDef: ast::Stmt = {
let returns = r.map(Box::new); let returns = r.map(Box::new);
let end_location = body.last().unwrap().end(); let end_location = body.last().unwrap().end();
if is_async.is_some() { if is_async.is_some() {
ast::StmtAsyncFunctionDef { name, args, body, decorator_list, returns, type_params: type_params.unwrap_or_default(), range: (location..end_location).into() }.into() ast::StmtAsyncFunctionDef { name, parameters:args, body, decorator_list, returns, type_params: type_params.unwrap_or_default(), range: (location..end_location).into() }.into()
} else { } else {
ast::StmtFunctionDef { name, args, body, decorator_list, returns, type_params: type_params.unwrap_or_default(), range: (location..end_location).into() }.into() ast::StmtFunctionDef { name, parameters:args, body, decorator_list, returns, type_params: type_params.unwrap_or_default(), range: (location..end_location).into() }.into()
} }
}, },
}; };
@ -1041,13 +1041,13 @@ TypeAliasStatement: ast::Stmt = {
}, },
}; };
Parameters: ast::Arguments = { Parameters: ast::Parameters = {
<location:@L> "(" <a: (ParameterList<TypedParameter, StarTypedParameter, DoubleStarTypedParameter>)?> ")" <end_location:@R> =>? { <location:@L> "(" <a: (ParameterList<TypedParameter, StarTypedParameter, DoubleStarTypedParameter>)?> ")" <end_location:@R> =>? {
a.as_ref().map(validate_arguments).transpose()?; a.as_ref().map(validate_arguments).transpose()?;
let range = (location..end_location).into(); let range = (location..end_location).into();
let args = a let args = a
.map_or_else(|| ast::Arguments::empty(range), |mut arguments| { .map_or_else(|| ast::Parameters::empty(range), |mut arguments| {
arguments.range = range; arguments.range = range;
arguments arguments
}); });
@ -1058,15 +1058,15 @@ Parameters: ast::Arguments = {
// Note that this is a macro which is used once for function defs, and // Note that this is a macro which is used once for function defs, and
// once for lambda defs. // once for lambda defs.
ParameterList<ArgType, StarArgType, DoubleStarArgType>: ast::Arguments = { ParameterList<ParameterType, StarParameterType, DoubleStarParameterType>: ast::Parameters = {
<location:@L> <param1:ParameterDefs<ArgType>> <args2:("," <ParameterListStarArgs<ArgType, StarArgType, DoubleStarArgType>>)?> ","? <end_location:@R> =>? { <location:@L> <param1:ParameterDefs<ParameterType>> <args2:("," <ParameterListStarArgs<ParameterType, StarParameterType, DoubleStarParameterType>>)?> ","? <end_location:@R> =>? {
validate_pos_params(&param1)?; validate_pos_params(&param1)?;
let (posonlyargs, args) = param1; let (posonlyargs, args) = param1;
// Now gather rest of parameters: // Now gather rest of parameters:
let (vararg, kwonlyargs, kwarg) = args2.unwrap_or((None, vec![], None)); let (vararg, kwonlyargs, kwarg) = args2.unwrap_or((None, vec![], None));
Ok(ast::Arguments { Ok(ast::Parameters {
posonlyargs, posonlyargs,
args, args,
kwonlyargs, kwonlyargs,
@ -1075,7 +1075,7 @@ ParameterList<ArgType, StarArgType, DoubleStarArgType>: ast::Arguments = {
range: (location..end_location).into() range: (location..end_location).into()
}) })
}, },
<location:@L> <param1:ParameterDefs<ArgType>> <kw:("," <KwargParameter<DoubleStarArgType>>)> ","? <end_location:@R> =>? { <location:@L> <param1:ParameterDefs<ParameterType>> <kw:("," <KwargParameter<DoubleStarParameterType>>)> ","? <end_location:@R> =>? {
validate_pos_params(&param1)?; validate_pos_params(&param1)?;
let (posonlyargs, args) = param1; let (posonlyargs, args) = param1;
@ -1084,7 +1084,7 @@ ParameterList<ArgType, StarArgType, DoubleStarArgType>: ast::Arguments = {
let kwonlyargs = vec![]; let kwonlyargs = vec![];
let kwarg = kw; let kwarg = kw;
Ok(ast::Arguments { Ok(ast::Parameters {
posonlyargs, posonlyargs,
args, args,
kwonlyargs, kwonlyargs,
@ -1093,9 +1093,9 @@ ParameterList<ArgType, StarArgType, DoubleStarArgType>: ast::Arguments = {
range: (location..end_location).into() range: (location..end_location).into()
}) })
}, },
<location:@L> <params:ParameterListStarArgs<ArgType, StarArgType, DoubleStarArgType>> ","? <end_location:@R> => { <location:@L> <params:ParameterListStarArgs<ParameterType, StarParameterType, DoubleStarParameterType>> ","? <end_location:@R> => {
let (vararg, kwonlyargs, kwarg) = params; let (vararg, kwonlyargs, kwarg) = params;
ast::Arguments { ast::Parameters {
posonlyargs: vec![], posonlyargs: vec![],
args: vec![], args: vec![],
kwonlyargs, kwonlyargs,
@ -1104,8 +1104,8 @@ ParameterList<ArgType, StarArgType, DoubleStarArgType>: ast::Arguments = {
range: (location..end_location).into() range: (location..end_location).into()
} }
}, },
<location:@L> <kwarg:KwargParameter<DoubleStarArgType>> ","? <end_location:@R> => { <location:@L> <kwarg:KwargParameter<DoubleStarParameterType>> ","? <end_location:@R> => {
ast::Arguments { ast::Parameters {
posonlyargs: vec![], posonlyargs: vec![],
args: vec![], args: vec![],
kwonlyargs: vec![], kwonlyargs: vec![],
@ -1118,61 +1118,61 @@ ParameterList<ArgType, StarArgType, DoubleStarArgType>: ast::Arguments = {
// Use inline here to make sure the "," is not creating an ambiguity. // Use inline here to make sure the "," is not creating an ambiguity.
#[inline] #[inline]
ParameterDefs<ArgType>: (Vec<ast::ArgWithDefault>, Vec<ast::ArgWithDefault>) = { ParameterDefs<ParameterType>: (Vec<ast::ParameterWithDefault>, Vec<ast::ParameterWithDefault>) = {
<args:OneOrMore<ParameterDef<ArgType>>> => { <args:OneOrMore<ParameterDef<ParameterType>>> => {
(vec![], args) (vec![], args)
}, },
<posonlyargs:OneOrMore<ParameterDef<ArgType>>> "," "/" <args:("," <ParameterDef<ArgType>>)*> => { <posonlyargs:OneOrMore<ParameterDef<ParameterType>>> "," "/" <args:("," <ParameterDef<ParameterType>>)*> => {
(posonlyargs, args) (posonlyargs, args)
}, },
}; };
ParameterDef<ArgType>: ast::ArgWithDefault = { ParameterDef<ParameterType>: ast::ParameterWithDefault = {
<i:ArgType> => i, <i:ParameterType> => i,
<mut i:ArgType> "=" <e:Test<"all">> <end_location:@R> => { <mut i:ParameterType> "=" <e:Test<"all">> <end_location:@R> => {
i.default = Some(Box::new(e)); i.default = Some(Box::new(e));
i.range = (i.range.start()..end_location).into(); i.range = (i.range.start()..end_location).into();
i i
}, },
}; };
UntypedParameter: ast::ArgWithDefault = { UntypedParameter: ast::ParameterWithDefault = {
<location:@L> <arg:Identifier> <end_location:@R> => { <location:@L> <arg:Identifier> <end_location:@R> => {
let def = ast::Arg { arg, annotation: None, range: (location..end_location).into() }; let def = ast::Parameter { arg, annotation: None, range: (location..end_location).into() };
ast::ArgWithDefault { def, default: None, range: (location..end_location).into() } ast::ParameterWithDefault { def, default: None, range: (location..end_location).into() }
}, },
}; };
StarUntypedParameter: ast::Arg = { StarUntypedParameter: ast::Parameter = {
<location:@L> <arg:Identifier> <end_location:@R> => ast::Arg { arg, annotation: None, range: (location..end_location).into() }, <location:@L> <arg:Identifier> <end_location:@R> => ast::Parameter { arg, annotation: None, range: (location..end_location).into() },
}; };
TypedParameter: ast::ArgWithDefault = { TypedParameter: ast::ParameterWithDefault = {
<location:@L> <arg:Identifier> <a:(":" <Test<"all">>)?> <end_location:@R> => { <location:@L> <arg:Identifier> <a:(":" <Test<"all">>)?> <end_location:@R> => {
let annotation = a.map(Box::new); let annotation = a.map(Box::new);
let def = ast::Arg { arg, annotation, range: (location..end_location).into() }; let def = ast::Parameter { arg, annotation, range: (location..end_location).into() };
ast::ArgWithDefault { def, default: None, range: (location..end_location).into() } ast::ParameterWithDefault { def, default: None, range: (location..end_location).into() }
}, },
}; };
StarTypedParameter: ast::Arg = { StarTypedParameter: ast::Parameter = {
<location:@L> <arg:Identifier> <a:(":" <TestOrStarExpr>)?> <end_location:@R> => { <location:@L> <arg:Identifier> <a:(":" <TestOrStarExpr>)?> <end_location:@R> => {
let annotation = a.map(Box::new); let annotation = a.map(Box::new);
ast::Arg { arg, annotation, range: (location..end_location).into() } ast::Parameter { arg, annotation, range: (location..end_location).into() }
}, },
}; };
DoubleStarTypedParameter: ast::Arg = { DoubleStarTypedParameter: ast::Parameter = {
<location:@L> <arg:Identifier> <a:(":" <Test<"all">>)?> <end_location:@R> => { <location:@L> <arg:Identifier> <a:(":" <Test<"all">>)?> <end_location:@R> => {
let annotation = a.map(Box::new); let annotation = a.map(Box::new);
ast::Arg { arg, annotation, range: (location..end_location).into() } ast::Parameter { arg, annotation, range: (location..end_location).into() }
}, },
}; };
// Use inline here to make sure the "," is not creating an ambiguity. // Use inline here to make sure the "," is not creating an ambiguity.
// TODO: figure out another grammar that makes this inline no longer required. // TODO: figure out another grammar that makes this inline no longer required.
#[inline] #[inline]
ParameterListStarArgs<ArgType, StarArgType, DoubleStarArgType>: (Option<Box<ast::Arg>>, Vec<ast::ArgWithDefault>, Option<Box<ast::Arg>>) = { ParameterListStarArgs<ParameterType, StarParameterType, DoubleStarParameterType>: (Option<Box<ast::Parameter>>, Vec<ast::ParameterWithDefault>, Option<Box<ast::Parameter>>) = {
<location:@L> "*" <va:StarArgType?> <kwonlyargs:("," <ParameterDef<ArgType>>)*> <kwarg:("," <KwargParameter<DoubleStarArgType>>)?> =>? { <location:@L> "*" <va:StarParameterType?> <kwonlyargs:("," <ParameterDef<ParameterType>>)*> <kwarg:("," <KwargParameter<DoubleStarParameterType>>)?> =>? {
if va.is_none() && kwonlyargs.is_empty() && kwarg.is_none() { if va.is_none() && kwonlyargs.is_empty() && kwarg.is_none() {
return Err(LexicalError { return Err(LexicalError {
error: LexicalErrorType::OtherError("named arguments must follow bare *".to_string()), error: LexicalErrorType::OtherError("named arguments must follow bare *".to_string()),
@ -1187,8 +1187,8 @@ ParameterListStarArgs<ArgType, StarArgType, DoubleStarArgType>: (Option<Box<ast:
} }
}; };
KwargParameter<ArgType>: Option<Box<ast::Arg>> = { KwargParameter<ParameterType>: Option<Box<ast::Parameter>> = {
"**" <kwarg:ArgType?> => { "**" <kwarg:ParameterType?> => {
kwarg.map(Box::new) kwarg.map(Box::new)
} }
}; };
@ -1291,11 +1291,11 @@ LambdaDef: ast::Expr = {
<location:@L> "lambda" <location_args:@L> <p:ParameterList<UntypedParameter, StarUntypedParameter, StarUntypedParameter>?> <end_location_args:@R> ":" <body:Test<"all">> <end_location:@R> =>? { <location:@L> "lambda" <location_args:@L> <p:ParameterList<UntypedParameter, StarUntypedParameter, StarUntypedParameter>?> <end_location_args:@R> ":" <body:Test<"all">> <end_location:@R> =>? {
p.as_ref().map(validate_arguments).transpose()?; p.as_ref().map(validate_arguments).transpose()?;
let p = p let p = p
.unwrap_or_else(|| ast::Arguments::empty((location_args..end_location_args).into())); .unwrap_or_else(|| ast::Parameters::empty((location_args..end_location_args).into()));
Ok(ast::Expr::Lambda( Ok(ast::Expr::Lambda(
ast::ExprLambda { ast::ExprLambda {
args: Box::new(p), parameters: Box::new(p),
body: Box::new(body), body: Box::new(body),
range: (location..end_location).into() range: (location..end_location).into()
} }

File diff suppressed because it is too large Load Diff

View File

@ -11,15 +11,15 @@ Ok(
id: "f", id: "f",
range: 4..5, range: 4..5,
}, },
args: Arguments { parameters: Parameters {
range: 5..17, range: 5..17,
posonlyargs: [], posonlyargs: [],
args: [], args: [],
vararg: None, vararg: None,
kwonlyargs: [ kwonlyargs: [
ArgWithDefault { ParameterWithDefault {
range: 9..10, range: 9..10,
def: Arg { def: Parameter {
range: 9..10, range: 9..10,
arg: Identifier { arg: Identifier {
id: "a", id: "a",
@ -29,9 +29,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 12..13, range: 12..13,
def: Arg { def: Parameter {
range: 12..13, range: 12..13,
arg: Identifier { arg: Identifier {
id: "b", id: "b",
@ -41,9 +41,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 15..16, range: 15..16,
def: Arg { def: Parameter {
range: 15..16, range: 15..16,
arg: Identifier { arg: Identifier {
id: "c", id: "c",

View File

@ -11,15 +11,15 @@ Ok(
id: "f", id: "f",
range: 4..5, range: 4..5,
}, },
args: Arguments { parameters: Parameters {
range: 5..23, range: 5..23,
posonlyargs: [], posonlyargs: [],
args: [], args: [],
vararg: None, vararg: None,
kwonlyargs: [ kwonlyargs: [
ArgWithDefault { ParameterWithDefault {
range: 9..10, range: 9..10,
def: Arg { def: Parameter {
range: 9..10, range: 9..10,
arg: Identifier { arg: Identifier {
id: "a", id: "a",
@ -29,9 +29,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 12..16, range: 12..16,
def: Arg { def: Parameter {
range: 12..13, range: 12..13,
arg: Identifier { arg: Identifier {
id: "b", id: "b",
@ -51,9 +51,9 @@ Ok(
), ),
), ),
}, },
ArgWithDefault { ParameterWithDefault {
range: 18..22, range: 18..22,
def: Arg { def: Parameter {
range: 18..19, range: 18..19,
arg: Identifier { arg: Identifier {
id: "c", id: "c",

View File

@ -11,7 +11,7 @@ Ok(
id: "f", id: "f",
range: 4..5, range: 4..5,
}, },
args: Arguments { parameters: Parameters {
range: 5..7, range: 5..7,
posonlyargs: [], posonlyargs: [],
args: [], args: [],

View File

@ -11,7 +11,7 @@ Ok(
id: "f", id: "f",
range: 4..5, range: 4..5,
}, },
args: Arguments { parameters: Parameters {
range: 5..7, range: 5..7,
posonlyargs: [], posonlyargs: [],
args: [], args: [],

View File

@ -11,13 +11,13 @@ Ok(
id: "f", id: "f",
range: 4..5, range: 4..5,
}, },
args: Arguments { parameters: Parameters {
range: 5..26, range: 5..26,
posonlyargs: [], posonlyargs: [],
args: [ args: [
ArgWithDefault { ParameterWithDefault {
range: 6..7, range: 6..7,
def: Arg { def: Parameter {
range: 6..7, range: 6..7,
arg: Identifier { arg: Identifier {
id: "a", id: "a",
@ -27,9 +27,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 9..10, range: 9..10,
def: Arg { def: Parameter {
range: 9..10, range: 9..10,
arg: Identifier { arg: Identifier {
id: "b", id: "b",
@ -39,9 +39,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 12..13, range: 12..13,
def: Arg { def: Parameter {
range: 12..13, range: 12..13,
arg: Identifier { arg: Identifier {
id: "c", id: "c",
@ -54,9 +54,9 @@ Ok(
], ],
vararg: None, vararg: None,
kwonlyargs: [ kwonlyargs: [
ArgWithDefault { ParameterWithDefault {
range: 18..19, range: 18..19,
def: Arg { def: Parameter {
range: 18..19, range: 18..19,
arg: Identifier { arg: Identifier {
id: "d", id: "d",
@ -66,9 +66,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 21..22, range: 21..22,
def: Arg { def: Parameter {
range: 21..22, range: 21..22,
arg: Identifier { arg: Identifier {
id: "e", id: "e",
@ -78,9 +78,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 24..25, range: 24..25,
def: Arg { def: Parameter {
range: 24..25, range: 24..25,
arg: Identifier { arg: Identifier {
id: "f", id: "f",

View File

@ -11,13 +11,13 @@ Ok(
id: "f", id: "f",
range: 4..5, range: 4..5,
}, },
args: Arguments { parameters: Parameters {
range: 5..32, range: 5..32,
posonlyargs: [], posonlyargs: [],
args: [ args: [
ArgWithDefault { ParameterWithDefault {
range: 6..7, range: 6..7,
def: Arg { def: Parameter {
range: 6..7, range: 6..7,
arg: Identifier { arg: Identifier {
id: "a", id: "a",
@ -27,9 +27,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 9..10, range: 9..10,
def: Arg { def: Parameter {
range: 9..10, range: 9..10,
arg: Identifier { arg: Identifier {
id: "b", id: "b",
@ -39,9 +39,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 12..13, range: 12..13,
def: Arg { def: Parameter {
range: 12..13, range: 12..13,
arg: Identifier { arg: Identifier {
id: "c", id: "c",
@ -54,9 +54,9 @@ Ok(
], ],
vararg: None, vararg: None,
kwonlyargs: [ kwonlyargs: [
ArgWithDefault { ParameterWithDefault {
range: 18..19, range: 18..19,
def: Arg { def: Parameter {
range: 18..19, range: 18..19,
arg: Identifier { arg: Identifier {
id: "d", id: "d",
@ -66,9 +66,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 21..25, range: 21..25,
def: Arg { def: Parameter {
range: 21..22, range: 21..22,
arg: Identifier { arg: Identifier {
id: "e", id: "e",
@ -88,9 +88,9 @@ Ok(
), ),
), ),
}, },
ArgWithDefault { ParameterWithDefault {
range: 27..31, range: 27..31,
def: Arg { def: Parameter {
range: 27..28, range: 27..28,
arg: Identifier { arg: Identifier {
id: "f", id: "f",

View File

@ -11,13 +11,13 @@ Ok(
id: "f", id: "f",
range: 4..5, range: 4..5,
}, },
args: Arguments { parameters: Parameters {
range: 5..36, range: 5..36,
posonlyargs: [], posonlyargs: [],
args: [ args: [
ArgWithDefault { ParameterWithDefault {
range: 6..7, range: 6..7,
def: Arg { def: Parameter {
range: 6..7, range: 6..7,
arg: Identifier { arg: Identifier {
id: "a", id: "a",
@ -27,9 +27,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 9..10, range: 9..10,
def: Arg { def: Parameter {
range: 9..10, range: 9..10,
arg: Identifier { arg: Identifier {
id: "b", id: "b",
@ -39,9 +39,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 12..13, range: 12..13,
def: Arg { def: Parameter {
range: 12..13, range: 12..13,
arg: Identifier { arg: Identifier {
id: "c", id: "c",
@ -53,7 +53,7 @@ Ok(
}, },
], ],
vararg: Some( vararg: Some(
Arg { Parameter {
range: 16..20, range: 16..20,
arg: Identifier { arg: Identifier {
id: "args", id: "args",
@ -63,9 +63,9 @@ Ok(
}, },
), ),
kwonlyargs: [ kwonlyargs: [
ArgWithDefault { ParameterWithDefault {
range: 22..23, range: 22..23,
def: Arg { def: Parameter {
range: 22..23, range: 22..23,
arg: Identifier { arg: Identifier {
id: "d", id: "d",
@ -75,9 +75,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 25..29, range: 25..29,
def: Arg { def: Parameter {
range: 25..26, range: 25..26,
arg: Identifier { arg: Identifier {
id: "e", id: "e",
@ -97,9 +97,9 @@ Ok(
), ),
), ),
}, },
ArgWithDefault { ParameterWithDefault {
range: 31..35, range: 31..35,
def: Arg { def: Parameter {
range: 31..32, range: 31..32,
arg: Identifier { arg: Identifier {
id: "f", id: "f",

View File

@ -11,13 +11,13 @@ Ok(
id: "f", id: "f",
range: 4..5, range: 4..5,
}, },
args: Arguments { parameters: Parameters {
range: 5..46, range: 5..46,
posonlyargs: [], posonlyargs: [],
args: [ args: [
ArgWithDefault { ParameterWithDefault {
range: 6..7, range: 6..7,
def: Arg { def: Parameter {
range: 6..7, range: 6..7,
arg: Identifier { arg: Identifier {
id: "a", id: "a",
@ -27,9 +27,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 9..10, range: 9..10,
def: Arg { def: Parameter {
range: 9..10, range: 9..10,
arg: Identifier { arg: Identifier {
id: "b", id: "b",
@ -39,9 +39,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 12..13, range: 12..13,
def: Arg { def: Parameter {
range: 12..13, range: 12..13,
arg: Identifier { arg: Identifier {
id: "c", id: "c",
@ -53,7 +53,7 @@ Ok(
}, },
], ],
vararg: Some( vararg: Some(
Arg { Parameter {
range: 16..20, range: 16..20,
arg: Identifier { arg: Identifier {
id: "args", id: "args",
@ -63,9 +63,9 @@ Ok(
}, },
), ),
kwonlyargs: [ kwonlyargs: [
ArgWithDefault { ParameterWithDefault {
range: 22..23, range: 22..23,
def: Arg { def: Parameter {
range: 22..23, range: 22..23,
arg: Identifier { arg: Identifier {
id: "d", id: "d",
@ -75,9 +75,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 25..29, range: 25..29,
def: Arg { def: Parameter {
range: 25..26, range: 25..26,
arg: Identifier { arg: Identifier {
id: "e", id: "e",
@ -97,9 +97,9 @@ Ok(
), ),
), ),
}, },
ArgWithDefault { ParameterWithDefault {
range: 31..35, range: 31..35,
def: Arg { def: Parameter {
range: 31..32, range: 31..32,
arg: Identifier { arg: Identifier {
id: "f", id: "f",
@ -121,7 +121,7 @@ Ok(
}, },
], ],
kwarg: Some( kwarg: Some(
Arg { Parameter {
range: 39..45, range: 39..45,
arg: Identifier { arg: Identifier {
id: "kwargs", id: "kwargs",

View File

@ -11,13 +11,13 @@ Ok(
id: "f", id: "f",
range: 4..5, range: 4..5,
}, },
args: Arguments { parameters: Parameters {
range: 5..14, range: 5..14,
posonlyargs: [], posonlyargs: [],
args: [ args: [
ArgWithDefault { ParameterWithDefault {
range: 6..7, range: 6..7,
def: Arg { def: Parameter {
range: 6..7, range: 6..7,
arg: Identifier { arg: Identifier {
id: "a", id: "a",
@ -27,9 +27,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 9..10, range: 9..10,
def: Arg { def: Parameter {
range: 9..10, range: 9..10,
arg: Identifier { arg: Identifier {
id: "b", id: "b",
@ -39,9 +39,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 12..13, range: 12..13,
def: Arg { def: Parameter {
range: 12..13, range: 12..13,
arg: Identifier { arg: Identifier {
id: "c", id: "c",

View File

@ -11,13 +11,13 @@ Ok(
id: "f", id: "f",
range: 4..5, range: 4..5,
}, },
args: Arguments { parameters: Parameters {
range: 5..20, range: 5..20,
posonlyargs: [], posonlyargs: [],
args: [ args: [
ArgWithDefault { ParameterWithDefault {
range: 6..7, range: 6..7,
def: Arg { def: Parameter {
range: 6..7, range: 6..7,
arg: Identifier { arg: Identifier {
id: "a", id: "a",
@ -27,9 +27,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 9..13, range: 9..13,
def: Arg { def: Parameter {
range: 9..10, range: 9..10,
arg: Identifier { arg: Identifier {
id: "b", id: "b",
@ -49,9 +49,9 @@ Ok(
), ),
), ),
}, },
ArgWithDefault { ParameterWithDefault {
range: 15..19, range: 15..19,
def: Arg { def: Parameter {
range: 15..16, range: 15..16,
arg: Identifier { arg: Identifier {
id: "c", id: "c",

View File

@ -11,13 +11,13 @@ Ok(
id: "f", id: "f",
range: 4..5, range: 4..5,
}, },
args: Arguments { parameters: Parameters {
range: 5..14, range: 5..14,
posonlyargs: [], posonlyargs: [],
args: [ args: [
ArgWithDefault { ParameterWithDefault {
range: 6..7, range: 6..7,
def: Arg { def: Parameter {
range: 6..7, range: 6..7,
arg: Identifier { arg: Identifier {
id: "a", id: "a",
@ -27,9 +27,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 9..10, range: 9..10,
def: Arg { def: Parameter {
range: 9..10, range: 9..10,
arg: Identifier { arg: Identifier {
id: "b", id: "b",
@ -39,9 +39,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 12..13, range: 12..13,
def: Arg { def: Parameter {
range: 12..13, range: 12..13,
arg: Identifier { arg: Identifier {
id: "c", id: "c",

View File

@ -10,15 +10,15 @@ Ok(
value: Lambda( value: Lambda(
ExprLambda { ExprLambda {
range: 0..20, range: 0..20,
args: Arguments { parameters: Parameters {
range: 7..17, range: 7..17,
posonlyargs: [], posonlyargs: [],
args: [], args: [],
vararg: None, vararg: None,
kwonlyargs: [ kwonlyargs: [
ArgWithDefault { ParameterWithDefault {
range: 10..11, range: 10..11,
def: Arg { def: Parameter {
range: 10..11, range: 10..11,
arg: Identifier { arg: Identifier {
id: "a", id: "a",
@ -28,9 +28,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 13..14, range: 13..14,
def: Arg { def: Parameter {
range: 13..14, range: 13..14,
arg: Identifier { arg: Identifier {
id: "b", id: "b",
@ -40,9 +40,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 16..17, range: 16..17,
def: Arg { def: Parameter {
range: 16..17, range: 16..17,
arg: Identifier { arg: Identifier {
id: "c", id: "c",

View File

@ -10,15 +10,15 @@ Ok(
value: Lambda( value: Lambda(
ExprLambda { ExprLambda {
range: 0..26, range: 0..26,
args: Arguments { parameters: Parameters {
range: 7..23, range: 7..23,
posonlyargs: [], posonlyargs: [],
args: [], args: [],
vararg: None, vararg: None,
kwonlyargs: [ kwonlyargs: [
ArgWithDefault { ParameterWithDefault {
range: 10..11, range: 10..11,
def: Arg { def: Parameter {
range: 10..11, range: 10..11,
arg: Identifier { arg: Identifier {
id: "a", id: "a",
@ -28,9 +28,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 13..17, range: 13..17,
def: Arg { def: Parameter {
range: 13..14, range: 13..14,
arg: Identifier { arg: Identifier {
id: "b", id: "b",
@ -50,9 +50,9 @@ Ok(
), ),
), ),
}, },
ArgWithDefault { ParameterWithDefault {
range: 19..23, range: 19..23,
def: Arg { def: Parameter {
range: 19..20, range: 19..20,
arg: Identifier { arg: Identifier {
id: "c", id: "c",

View File

@ -10,7 +10,7 @@ Ok(
value: Lambda( value: Lambda(
ExprLambda { ExprLambda {
range: 0..9, range: 0..9,
args: Arguments { parameters: Parameters {
range: 6..6, range: 6..6,
posonlyargs: [], posonlyargs: [],
args: [], args: [],

View File

@ -10,13 +10,13 @@ Ok(
value: Lambda( value: Lambda(
ExprLambda { ExprLambda {
range: 0..26, range: 0..26,
args: Arguments { parameters: Parameters {
range: 7..23, range: 7..23,
posonlyargs: [], posonlyargs: [],
args: [ args: [
ArgWithDefault { ParameterWithDefault {
range: 7..8, range: 7..8,
def: Arg { def: Parameter {
range: 7..8, range: 7..8,
arg: Identifier { arg: Identifier {
id: "a", id: "a",
@ -26,9 +26,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 10..11, range: 10..11,
def: Arg { def: Parameter {
range: 10..11, range: 10..11,
arg: Identifier { arg: Identifier {
id: "b", id: "b",
@ -38,9 +38,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 13..14, range: 13..14,
def: Arg { def: Parameter {
range: 13..14, range: 13..14,
arg: Identifier { arg: Identifier {
id: "c", id: "c",
@ -53,9 +53,9 @@ Ok(
], ],
vararg: None, vararg: None,
kwonlyargs: [ kwonlyargs: [
ArgWithDefault { ParameterWithDefault {
range: 19..20, range: 19..20,
def: Arg { def: Parameter {
range: 19..20, range: 19..20,
arg: Identifier { arg: Identifier {
id: "d", id: "d",
@ -65,9 +65,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 22..23, range: 22..23,
def: Arg { def: Parameter {
range: 22..23, range: 22..23,
arg: Identifier { arg: Identifier {
id: "e", id: "e",

View File

@ -10,13 +10,13 @@ Ok(
value: Lambda( value: Lambda(
ExprLambda { ExprLambda {
range: 0..17, range: 0..17,
args: Arguments { parameters: Parameters {
range: 7..14, range: 7..14,
posonlyargs: [], posonlyargs: [],
args: [ args: [
ArgWithDefault { ParameterWithDefault {
range: 7..8, range: 7..8,
def: Arg { def: Parameter {
range: 7..8, range: 7..8,
arg: Identifier { arg: Identifier {
id: "a", id: "a",
@ -26,9 +26,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 10..11, range: 10..11,
def: Arg { def: Parameter {
range: 10..11, range: 10..11,
arg: Identifier { arg: Identifier {
id: "b", id: "b",
@ -38,9 +38,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 13..14, range: 13..14,
def: Arg { def: Parameter {
range: 13..14, range: 13..14,
arg: Identifier { arg: Identifier {
id: "c", id: "c",

View File

@ -10,13 +10,13 @@ Ok(
value: Lambda( value: Lambda(
ExprLambda { ExprLambda {
range: 0..23, range: 0..23,
args: Arguments { parameters: Parameters {
range: 7..20, range: 7..20,
posonlyargs: [], posonlyargs: [],
args: [ args: [
ArgWithDefault { ParameterWithDefault {
range: 7..8, range: 7..8,
def: Arg { def: Parameter {
range: 7..8, range: 7..8,
arg: Identifier { arg: Identifier {
id: "a", id: "a",
@ -26,9 +26,9 @@ Ok(
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 10..14, range: 10..14,
def: Arg { def: Parameter {
range: 10..11, range: 10..11,
arg: Identifier { arg: Identifier {
id: "b", id: "b",
@ -48,9 +48,9 @@ Ok(
), ),
), ),
}, },
ArgWithDefault { ParameterWithDefault {
range: 16..20, range: 16..20,
def: Arg { def: Parameter {
range: 16..17, range: 16..17,
arg: Identifier { arg: Identifier {
id: "c", id: "c",

View File

@ -10,7 +10,7 @@ expression: parse_ast
id: "test", id: "test",
range: 18..22, range: 18..22,
}, },
args: Arguments { parameters: Parameters {
range: 22..24, range: 22..24,
posonlyargs: [], posonlyargs: [],
args: [], args: [],

View File

@ -129,7 +129,7 @@ Module(
id: "foo", id: "foo",
range: 570..573, range: 570..573,
}, },
args: Arguments { parameters: Parameters {
range: 573..575, range: 573..575,
posonlyargs: [], posonlyargs: [],
args: [], args: [],

View File

@ -1,6 +1,6 @@
--- ---
source: crates/ruff_python_parser/src/parser.rs source: crates/ruff_python_parser/src/parser.rs
expression: "ast::Suite::parse(source, \"<test>\").unwrap()" expression: "parse_suite(source, \"<test>\").unwrap()"
--- ---
[ [
Expr( Expr(
@ -709,13 +709,13 @@ expression: "ast::Suite::parse(source, \"<test>\").unwrap()"
value: Lambda( value: Lambda(
ExprLambda { ExprLambda {
range: 591..619, range: 591..619,
args: Arguments { parameters: Parameters {
range: 598..603, range: 598..603,
posonlyargs: [], posonlyargs: [],
args: [ args: [
ArgWithDefault { ParameterWithDefault {
range: 598..603, range: 598..603,
def: Arg { def: Parameter {
range: 598..603, range: 598..603,
arg: Identifier { arg: Identifier {
id: "query", id: "query",

View File

@ -1,6 +1,6 @@
--- ---
source: crates/ruff_python_parser/src/parser.rs source: crates/ruff_python_parser/src/parser.rs
expression: "ast::Suite::parse(source, \"<test>\").unwrap()" expression: "parse_suite(source, \"<test>\").unwrap()"
--- ---
[ [
ClassDef( ClassDef(
@ -35,13 +35,13 @@ expression: "ast::Suite::parse(source, \"<test>\").unwrap()"
id: "__init__", id: "__init__",
range: 22..30, range: 22..30,
}, },
args: Arguments { parameters: Parameters {
range: 30..36, range: 30..36,
posonlyargs: [], posonlyargs: [],
args: [ args: [
ArgWithDefault { ParameterWithDefault {
range: 31..35, range: 31..35,
def: Arg { def: Parameter {
range: 31..35, range: 31..35,
arg: Identifier { arg: Identifier {
id: "self", id: "self",
@ -75,13 +75,13 @@ expression: "ast::Suite::parse(source, \"<test>\").unwrap()"
id: "method_with_default", id: "method_with_default",
range: 50..69, range: 50..69,
}, },
args: Arguments { parameters: Parameters {
range: 69..90, range: 69..90,
posonlyargs: [], posonlyargs: [],
args: [ args: [
ArgWithDefault { ParameterWithDefault {
range: 70..74, range: 70..74,
def: Arg { def: Parameter {
range: 70..74, range: 70..74,
arg: Identifier { arg: Identifier {
id: "self", id: "self",
@ -91,9 +91,9 @@ expression: "ast::Suite::parse(source, \"<test>\").unwrap()"
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 76..89, range: 76..89,
def: Arg { def: Parameter {
range: 76..79, range: 76..79,
arg: Identifier { arg: Identifier {
id: "arg", id: "arg",

View File

@ -1,6 +1,6 @@
--- ---
source: crates/ruff_python_parser/src/parser.rs source: crates/ruff_python_parser/src/parser.rs
expression: "ast::Suite::parse(source, \"<test>\").unwrap()" expression: "parse_suite(source, \"<test>\").unwrap()"
--- ---
[ [
FunctionDef( FunctionDef(
@ -10,13 +10,13 @@ expression: "ast::Suite::parse(source, \"<test>\").unwrap()"
id: "func", id: "func",
range: 4..8, range: 4..8,
}, },
args: Arguments { parameters: Parameters {
range: 8..11, range: 8..11,
posonlyargs: [], posonlyargs: [],
args: [ args: [
ArgWithDefault { ParameterWithDefault {
range: 9..10, range: 9..10,
def: Arg { def: Parameter {
range: 9..10, range: 9..10,
arg: Identifier { arg: Identifier {
id: "a", id: "a",
@ -57,13 +57,13 @@ expression: "ast::Suite::parse(source, \"<test>\").unwrap()"
id: "func", id: "func",
range: 26..30, range: 26..30,
}, },
args: Arguments { parameters: Parameters {
range: 33..39, range: 33..39,
posonlyargs: [], posonlyargs: [],
args: [ args: [
ArgWithDefault { ParameterWithDefault {
range: 34..38, range: 34..38,
def: Arg { def: Parameter {
range: 34..38, range: 34..38,
arg: Identifier { arg: Identifier {
id: "a", id: "a",
@ -131,13 +131,13 @@ expression: "ast::Suite::parse(source, \"<test>\").unwrap()"
id: "func", id: "func",
range: 59..63, range: 59..63,
}, },
args: Arguments { parameters: Parameters {
range: 71..77, range: 71..77,
posonlyargs: [], posonlyargs: [],
args: [ args: [
ArgWithDefault { ParameterWithDefault {
range: 72..76, range: 72..76,
def: Arg { def: Parameter {
range: 72..76, range: 72..76,
arg: Identifier { arg: Identifier {
id: "a", id: "a",
@ -213,13 +213,13 @@ expression: "ast::Suite::parse(source, \"<test>\").unwrap()"
id: "func", id: "func",
range: 97..101, range: 97..101,
}, },
args: Arguments { parameters: Parameters {
range: 118..124, range: 118..124,
posonlyargs: [], posonlyargs: [],
args: [ args: [
ArgWithDefault { ParameterWithDefault {
range: 119..123, range: 119..123,
def: Arg { def: Parameter {
range: 119..123, range: 119..123,
arg: Identifier { arg: Identifier {
id: "a", id: "a",
@ -310,12 +310,12 @@ expression: "ast::Suite::parse(source, \"<test>\").unwrap()"
id: "func", id: "func",
range: 144..148, range: 144..148,
}, },
args: Arguments { parameters: Parameters {
range: 153..162, range: 153..162,
posonlyargs: [], posonlyargs: [],
args: [], args: [],
vararg: Some( vararg: Some(
Arg { Parameter {
range: 155..161, range: 155..161,
arg: Identifier { arg: Identifier {
id: "a", id: "a",
@ -377,12 +377,12 @@ expression: "ast::Suite::parse(source, \"<test>\").unwrap()"
id: "func", id: "func",
range: 177..181, range: 177..181,
}, },
args: Arguments { parameters: Parameters {
range: 186..221, range: 186..221,
posonlyargs: [], posonlyargs: [],
args: [], args: [],
vararg: Some( vararg: Some(
Arg { Parameter {
range: 188..200, range: 188..200,
arg: Identifier { arg: Identifier {
id: "args", id: "args",
@ -411,7 +411,7 @@ expression: "ast::Suite::parse(source, \"<test>\").unwrap()"
), ),
kwonlyargs: [], kwonlyargs: [],
kwarg: Some( kwarg: Some(
Arg { Parameter {
range: 204..220, range: 204..220,
arg: Identifier { arg: Identifier {
id: "kwargs", id: "kwargs",
@ -475,7 +475,7 @@ expression: "ast::Suite::parse(source, \"<test>\").unwrap()"
id: "func", id: "func",
range: 236..240, range: 236..240,
}, },
args: Arguments { parameters: Parameters {
range: 261..263, range: 261..263,
posonlyargs: [], posonlyargs: [],
args: [], args: [],

View File

@ -9,13 +9,13 @@ expression: parse_ast
value: Lambda( value: Lambda(
ExprLambda { ExprLambda {
range: 0..18, range: 0..18,
args: Arguments { parameters: Parameters {
range: 7..11, range: 7..11,
posonlyargs: [], posonlyargs: [],
args: [ args: [
ArgWithDefault { ParameterWithDefault {
range: 7..8, range: 7..8,
def: Arg { def: Parameter {
range: 7..8, range: 7..8,
arg: Identifier { arg: Identifier {
id: "x", id: "x",
@ -25,9 +25,9 @@ expression: parse_ast
}, },
default: None, default: None,
}, },
ArgWithDefault { ParameterWithDefault {
range: 10..11, range: 10..11,
def: Arg { def: Parameter {
range: 10..11, range: 10..11,
arg: Identifier { arg: Identifier {
id: "y", id: "y",

View File

@ -9,7 +9,7 @@ expression: parse_ast
value: Lambda( value: Lambda(
ExprLambda { ExprLambda {
range: 0..9, range: 0..9,
args: Arguments { parameters: Parameters {
range: 6..6, range: 6..6,
posonlyargs: [], posonlyargs: [],
args: [], args: [],

Some files were not shown because too many files have changed in this diff Show More