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(
lambda @ ast::ExprLambda {
args: _,
parameters: _,
body: _,
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 comprehension::comprehension;
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 expression::expression;
pub(super) use module::module;
pub(super) use parameter::parameter;
pub(super) use parameters::parameters;
pub(super) use statement::statement;
pub(super) use suite::suite;
pub(super) use unresolved_references::unresolved_references;
mod argument;
mod arguments;
mod bindings;
mod comprehension;
mod deferred_for_loops;
@ -22,6 +20,8 @@ mod definitions;
mod except_handler;
mod expression;
mod module;
mod parameter;
mod parameters;
mod statement;
mod suite;
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::codes::Rule;
use crate::rules::{flake8_builtins, pep8_naming, pycodestyle};
/// Run lint rules over an [`Arg`] syntax node.
pub(crate) fn argument(arg: &Arg, checker: &mut Checker) {
/// Run lint rules over a [`Parameter`] syntax node.
pub(crate) fn parameter(parameter: &Parameter, checker: &mut Checker) {
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);
}
}
if checker.enabled(Rule::InvalidArgumentName) {
if let Some(diagnostic) = pep8_naming::rules::invalid_argument_name(
&arg.arg,
arg,
&parameter.arg,
parameter,
&checker.settings.pep8_naming.ignore_names,
) {
checker.diagnostics.push(diagnostic);
}
}
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::codes::Rule;
use crate::rules::{flake8_bugbear, flake8_pyi, ruff};
/// Run lint rules over a [`Arguments`] syntax node.
pub(crate) fn arguments(arguments: &Arguments, checker: &mut Checker) {
/// Run lint rules over a [`Parameters`] syntax node.
pub(crate) fn parameters(parameters: &Parameters, checker: &mut Checker) {
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) {
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) {
ruff::rules::implicit_optional(checker, arguments);
ruff::rules::implicit_optional(checker, parameters);
}
if checker.is_stub {
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) {
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,
decorator_list,
returns,
args,
parameters,
body,
..
})
@ -81,7 +81,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
name,
decorator_list,
returns,
args,
parameters,
body,
..
}) => {
@ -114,7 +114,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
checker.semantic.scope(),
name,
decorator_list,
args,
parameters,
)
{
checker.diagnostics.push(diagnostic);
@ -126,7 +126,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
checker.semantic.scope(),
name,
decorator_list,
args,
parameters,
) {
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);
}
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) {
flake8_pyi::rules::non_self_return_type(
@ -151,7 +151,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
name,
decorator_list,
returns.as_ref().map(AsRef::as_ref),
args,
parameters,
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);
}
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) {
flake8_pyi::rules::bad_exit_annotation(
checker,
stmt.is_async_function_def_stmt(),
name,
args,
parameters,
);
}
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) {
@ -230,13 +230,13 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
}
}
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) {
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) {
pylint::rules::too_many_arguments(checker, args, stmt);
pylint::rules::too_many_arguments(checker, parameters, stmt);
}
if checker.enabled(Rule::TooManyReturnStatements) {
if let Some(diagnostic) = pylint::rules::too_many_return_statements(
@ -282,7 +282,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
checker,
stmt,
name,
args,
parameters,
decorator_list,
body,
);
@ -304,7 +304,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
checker,
name,
decorator_list,
args,
parameters,
);
}
if checker.enabled(Rule::BooleanDefaultValueInFunctionDefinition) {
@ -312,7 +312,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
checker,
name,
decorator_list,
args,
parameters,
);
}
if checker.enabled(Rule::UnexpectedSpecialMethodSignature) {
@ -321,7 +321,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
stmt,
name,
decorator_list,
args,
parameters,
);
}
if checker.enabled(Rule::FStringDocstring) {

View file

@ -31,8 +31,8 @@ use std::path::Path;
use itertools::Itertools;
use log::error;
use ruff_python_ast::{
self as ast, Arg, ArgWithDefault, Arguments, Comprehension, Constant, ElifElseClause,
ExceptHandler, Expr, ExprContext, Keyword, Pattern, Ranged, Stmt, Suite, UnaryOp,
self as ast, Comprehension, Constant, ElifElseClause, ExceptHandler, Expr, ExprContext,
Keyword, Parameter, ParameterWithDefault, Parameters, Pattern, Ranged, Stmt, Suite, UnaryOp,
};
use ruff_text_size::{TextRange, TextSize};
@ -455,7 +455,7 @@ where
match stmt {
Stmt::FunctionDef(ast::StmtFunctionDef {
body,
args,
parameters,
decorator_list,
returns,
type_params,
@ -463,7 +463,7 @@ where
})
| Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef {
body,
args,
parameters,
decorator_list,
type_params,
returns,
@ -485,24 +485,24 @@ where
self.visit_type_param(type_param);
}
for arg_with_default in args
for parameter_with_default in parameters
.posonlyargs
.iter()
.chain(&args.args)
.chain(&args.kwonlyargs)
.chain(&parameters.args)
.chain(&parameters.kwonlyargs)
{
if let Some(expr) = &arg_with_default.def.annotation {
if let Some(expr) = &parameter_with_default.def.annotation {
if runtime_annotation {
self.visit_runtime_annotation(expr);
} else {
self.visit_annotation(expr);
};
}
if let Some(expr) = &arg_with_default.default {
if let Some(expr) = &parameter_with_default.default {
self.visit_expr(expr);
}
}
if let Some(arg) = &args.vararg {
if let Some(arg) = &parameters.vararg {
if let Some(expr) = &arg.annotation {
if runtime_annotation {
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 runtime_annotation {
self.visit_runtime_annotation(expr);
@ -888,21 +888,21 @@ where
}
Expr::Lambda(
lambda @ ast::ExprLambda {
args,
parameters,
body: _,
range: _,
},
) => {
// Visit the default arguments, but avoid the body, which will be deferred.
for ArgWithDefault {
for ParameterWithDefault {
default,
def: _,
range: _,
} in args
} in parameters
.posonlyargs
.iter()
.chain(&args.args)
.chain(&args.kwonlyargs)
.chain(&parameters.args)
.chain(&parameters.kwonlyargs)
{
if let Some(expr) = &default {
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.
// Bind, but intentionally avoid walking default expressions, as we handle them
// upstream.
for arg_with_default in &arguments.posonlyargs {
self.visit_arg(&arg_with_default.def);
for parameter_with_default in &parameters.posonlyargs {
self.visit_parameter(&parameter_with_default.def);
}
for arg_with_default in &arguments.args {
self.visit_arg(&arg_with_default.def);
for parameter_with_default in &parameters.args {
self.visit_parameter(&parameter_with_default.def);
}
if let Some(arg) = &arguments.vararg {
self.visit_arg(arg);
if let Some(arg) = &parameters.vararg {
self.visit_parameter(arg);
}
for arg_with_default in &arguments.kwonlyargs {
self.visit_arg(&arg_with_default.def);
for parameter_with_default in &parameters.kwonlyargs {
self.visit_parameter(&parameter_with_default.def);
}
if let Some(arg) = &arguments.kwarg {
self.visit_arg(arg);
if let Some(arg) = &parameters.kwarg {
self.visit_parameter(arg);
}
// 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.
// Bind, but intentionally avoid walking the annotation, as we handle it
// upstream.
self.add_binding(
&arg.arg,
arg.identifier(),
&parameter.arg,
parameter.identifier(),
BindingKind::Argument,
BindingFlags::empty(),
);
// Step 4: Analysis
analyze::argument(arg, self);
analyze::parameter(parameter, self);
}
fn visit_pattern(&mut self, pattern: &'b Pattern) {
@ -1824,9 +1824,13 @@ impl<'a> Checker<'a> {
self.semantic.restore(snapshot);
match &self.semantic.stmt() {
Stmt::FunctionDef(ast::StmtFunctionDef { body, args, .. })
| Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef { body, args, .. }) => {
self.visit_arguments(args);
Stmt::FunctionDef(ast::StmtFunctionDef {
body, parameters, ..
})
| Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef {
body, parameters, ..
}) => {
self.visit_parameters(parameters);
self.visit_body(body);
}
_ => {
@ -1846,12 +1850,12 @@ impl<'a> Checker<'a> {
self.semantic.restore(snapshot);
if let Expr::Lambda(ast::ExprLambda {
args,
parameters,
body,
range: _,
}) = expr
{
self.visit_arguments(args);
self.visit_parameters(parameters);
self.visit_expr(body);
} else {
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_semantic::analyze::visibility;
@ -6,11 +6,11 @@ use ruff_python_semantic::{Definition, Member, MemberKind, SemanticModel};
pub(super) fn match_function_def(
stmt: &Stmt,
) -> (&str, &Arguments, Option<&Expr>, &[Stmt], &[ast::Decorator]) {
) -> (&str, &Parameters, Option<&Expr>, &[Stmt], &[ast::Decorator]) {
match stmt {
Stmt::FunctionDef(ast::StmtFunctionDef {
name,
args,
parameters,
returns,
body,
decorator_list,
@ -18,14 +18,14 @@ pub(super) fn match_function_def(
})
| Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef {
name,
args,
parameters,
returns,
body,
decorator_list,
..
}) => (
name,
args,
parameters,
returns.as_ref().map(AsRef::as_ref),
body,
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_macros::{derive_message_formats, violation};
@ -524,7 +524,7 @@ pub(crate) fn definition(
let is_overridden = visibility::is_override(decorator_list, checker.semantic());
// ANN001, ANN401
for ArgWithDefault {
for ParameterWithDefault {
def,
default: _,
range: _,
@ -627,7 +627,7 @@ pub(crate) fn definition(
// ANN101, ANN102
if is_method && !visibility::is_staticmethod(cast::decorator_list(stmt), checker.semantic()) {
if let Some(ArgWithDefault {
if let Some(ParameterWithDefault {
def,
default: _,
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_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())?;
let kwarg_name = &arg.arg;
let kwarg_name = &parameter.arg;
if !matches_password_name(kwarg_name) {
return None;
}
@ -68,16 +68,16 @@ fn check_password_kwarg(arg: &Arg, default: &Expr) -> Option<Diagnostic> {
}
/// S107
pub(crate) fn hardcoded_password_default(checker: &mut Checker, arguments: &Arguments) {
for ArgWithDefault {
pub(crate) fn hardcoded_password_default(checker: &mut Checker, parameters: &Parameters) {
for ParameterWithDefault {
def,
default,
range: _,
} in arguments
} in parameters
.posonlyargs
.iter()
.chain(&arguments.args)
.chain(&arguments.kwonlyargs)
.chain(&parameters.args)
.chain(&parameters.kwonlyargs)
{
let Some(default) = default else {
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_macros::{derive_message_formats, violation};
@ -59,7 +59,7 @@ pub(crate) fn check_boolean_default_value_in_function_definition(
checker: &mut Checker,
name: &str,
decorator_list: &[Decorator],
arguments: &Arguments,
parameters: &Parameters,
) {
if is_allowed_func_def(name) {
return;
@ -72,11 +72,11 @@ pub(crate) fn check_boolean_default_value_in_function_definition(
return;
}
for ArgWithDefault {
for ParameterWithDefault {
def: _,
default,
range: _,
} in arguments.args.iter().chain(&arguments.posonlyargs)
} in parameters.args.iter().chain(&parameters.posonlyargs)
{
let Some(default) = default else {
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::Violation;
@ -80,7 +82,7 @@ pub(crate) fn check_positional_boolean_in_def(
checker: &mut Checker,
name: &str,
decorator_list: &[Decorator],
arguments: &Arguments,
parameters: &Parameters,
) {
if is_allowed_func_def(name) {
return;
@ -93,11 +95,11 @@ pub(crate) fn check_positional_boolean_in_def(
return;
}
for ArgWithDefault {
for ParameterWithDefault {
def,
default: _,
range: _,
} in arguments.posonlyargs.iter().chain(&arguments.args)
} in parameters.posonlyargs.iter().chain(&parameters.args)
{
if def.annotation.is_none() {
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_diagnostics::Violation;
@ -105,7 +105,7 @@ where
}
/// 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.
let extend_immutable_calls: Vec<CallPath> = checker
.settings
@ -116,15 +116,15 @@ pub(crate) fn function_call_in_argument_default(checker: &mut Checker, arguments
.collect();
let diagnostics = {
let mut visitor = ArgumentDefaultVisitor::new(checker.semantic(), extend_immutable_calls);
for ArgWithDefault {
for ParameterWithDefault {
default,
def: _,
range: _,
} in arguments
} in parameters
.posonlyargs
.iter()
.chain(&arguments.args)
.chain(&arguments.kwonlyargs)
.chain(&parameters.args)
.chain(&parameters.kwonlyargs)
{
if let Some(expr) = &default {
visitor.visit_expr(expr);

View file

@ -86,8 +86,12 @@ struct SuspiciousVariablesVisitor<'a> {
impl<'a> Visitor<'a> for SuspiciousVariablesVisitor<'a> {
fn visit_stmt(&mut self, stmt: &'a Stmt) {
match stmt {
Stmt::FunctionDef(ast::StmtFunctionDef { args, body, .. })
| Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef { args, body, .. }) => {
Stmt::FunctionDef(ast::StmtFunctionDef {
parameters, body, ..
})
| Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef {
parameters, body, ..
}) => {
// Collect all loaded variable names.
let mut visitor = LoadedNamesVisitor::default();
visitor.visit_body(body);
@ -99,7 +103,7 @@ impl<'a> Visitor<'a> for SuspiciousVariablesVisitor<'a> {
return false;
}
if includes_arg_name(&loaded.id, args) {
if includes_arg_name(&loaded.id, parameters) {
return false;
}
@ -165,7 +169,7 @@ impl<'a> Visitor<'a> for SuspiciousVariablesVisitor<'a> {
}
}
Expr::Lambda(ast::ExprLambda {
args,
parameters,
body,
range: _,
}) => {
@ -181,7 +185,7 @@ impl<'a> Visitor<'a> for SuspiciousVariablesVisitor<'a> {
return false;
}
if includes_arg_name(&loaded.id, args) {
if includes_arg_name(&loaded.id, parameters) {
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 ruff_diagnostics::{Diagnostic, Violation};
@ -71,20 +71,20 @@ where
}
}
Expr::Lambda(ast::ExprLambda {
args,
parameters,
body,
range: _,
}) => {
visitor::walk_expr(self, body);
for ArgWithDefault {
for ParameterWithDefault {
def,
default: _,
range: _,
} in args
} in parameters
.posonlyargs
.iter()
.chain(&args.args)
.chain(&args.kwonlyargs)
.chain(&parameters.args)
.chain(&parameters.kwonlyargs)
{
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_macros::{derive_message_formats, violation};
@ -57,17 +57,17 @@ impl Violation for MutableArgumentDefault {
}
/// 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().
for ArgWithDefault {
for ParameterWithDefault {
def,
default,
range: _,
} in arguments
} in parameters
.posonlyargs
.iter()
.chain(&arguments.args)
.chain(&arguments.kwonlyargs)
.chain(&parameters.args)
.chain(&parameters.kwonlyargs)
{
let Some(default) = default else {
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::Violation;
@ -62,16 +62,16 @@ impl Violation for BuiltinArgumentShadowing {
}
/// 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(
argument.arg.as_str(),
parameter.arg.as_str(),
&checker.settings.flake8_builtins.builtins_ignorelist,
) {
checker.diagnostics.push(Diagnostic::new(
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 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::{Diagnostic, Fix};
@ -98,11 +98,14 @@ pub(crate) fn unnecessary_map(
};
// 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;
};
if late_binding(args, body) {
if late_binding(parameters, body) {
return;
}
}
@ -121,11 +124,14 @@ pub(crate) fn unnecessary_map(
return;
};
let Expr::Lambda(ast::ExprLambda { args, body, .. }) = argument else {
let Expr::Lambda(ast::ExprLambda {
parameters, body, ..
}) = argument
else {
return;
};
if late_binding(args, body) {
if late_binding(parameters, body) {
return;
}
}
@ -140,7 +146,10 @@ pub(crate) fn unnecessary_map(
return;
};
let Expr::Lambda(ast::ExprLambda { args, body, .. }) = argument else {
let Expr::Lambda(ast::ExprLambda {
parameters, body, ..
}) = argument
else {
return;
};
@ -154,7 +163,7 @@ pub(crate) fn unnecessary_map(
return;
}
if late_binding(args, body) {
if late_binding(parameters, body) {
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.
///
/// 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
/// value of `x` in the comprehension.
fn late_binding(args: &Arguments, body: &Expr) -> bool {
let mut visitor = LateBindingVisitor::new(args);
fn late_binding(parameters: &Parameters, body: &Expr) -> bool {
let mut visitor = LateBindingVisitor::new(parameters);
visitor.visit_expr(body);
visitor.late_bound
}
@ -221,17 +230,17 @@ fn late_binding(args: &Arguments, body: &Expr) -> bool {
#[derive(Debug)]
struct LateBindingVisitor<'a> {
/// The arguments to the current lambda.
args: &'a Arguments,
parameters: &'a Parameters,
/// 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.
late_bound: bool,
}
impl<'a> LateBindingVisitor<'a> {
fn new(args: &'a Arguments) -> Self {
fn new(parameters: &'a Parameters) -> Self {
Self {
args,
parameters,
lambdas: Vec::new(),
late_bound: false,
}
@ -243,8 +252,8 @@ impl<'a> Visitor<'a> for LateBindingVisitor<'a> {
fn visit_expr(&mut self, expr: &'a Expr) {
match expr {
Expr::Lambda(ast::ExprLambda { args, .. }) => {
self.lambdas.push(args);
Expr::Lambda(ast::ExprLambda { parameters, .. }) => {
self.lambdas.push(parameters);
visitor::walk_expr(self, expr);
self.lambdas.pop();
}
@ -256,7 +265,7 @@ impl<'a> Visitor<'a> for LateBindingVisitor<'a> {
// If we're within a nested lambda...
if !self.lambdas.is_empty() {
// 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...
if !self.lambdas.iter().any(|args| includes_arg_name(id, args)) {
// Then it's late-bound.

View file

@ -54,16 +54,16 @@ impl Violation for ReimplementedListBuiltin {
/// PIE807
pub(crate) fn reimplemented_list_builtin(checker: &mut Checker, expr: &ExprLambda) {
let ExprLambda {
args,
parameters,
body,
range: _,
} = expr;
if args.args.is_empty()
&& args.kwonlyargs.is_empty()
&& args.posonlyargs.is_empty()
&& args.vararg.is_none()
&& args.kwarg.is_none()
if parameters.args.is_empty()
&& parameters.kwonlyargs.is_empty()
&& parameters.posonlyargs.is_empty()
&& parameters.vararg.is_none()
&& parameters.kwarg.is_none()
{
if let Expr::List(ast::ExprList { elts, .. }) = body.as_ref() {
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_macros::{derive_message_formats, violation};
@ -53,16 +53,16 @@ impl AlwaysAutofixableViolation for AnyEqNeAnnotation {
}
/// 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__") {
return;
}
if args.args.len() != 2 {
if parameters.args.len() != 2 {
return;
}
let Some(annotation) = &args.args[1].def.annotation else {
let Some(annotation) = &parameters.args[1].def.annotation else {
return;
};

View file

@ -1,8 +1,8 @@
use std::fmt::{Display, Formatter};
use ruff_python_ast::{
ArgWithDefault, Arguments, Expr, ExprBinOp, ExprSubscript, ExprTuple, Identifier, Operator,
Ranged,
Expr, ExprBinOp, ExprSubscript, ExprTuple, Identifier, Operator, ParameterWithDefault,
Parameters, Ranged,
};
use smallvec::SmallVec;
@ -104,7 +104,7 @@ pub(crate) fn bad_exit_annotation(
checker: &mut Checker,
is_async: bool,
name: &Identifier,
args: &Arguments,
parameters: &Parameters,
) {
let func_kind = match name.as_str() {
"__exit__" if !is_async => FuncKind::Sync,
@ -112,41 +112,45 @@ pub(crate) fn bad_exit_annotation(
_ => return,
};
let positional_args = args
let positional_args = parameters
.args
.iter()
.chain(args.posonlyargs.iter())
.collect::<SmallVec<[&ArgWithDefault; 4]>>();
.chain(parameters.posonlyargs.iter())
.collect::<SmallVec<[&ParameterWithDefault; 4]>>();
// 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`.
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.
for arg_with_default in positional_args
for parameter in positional_args
.iter()
.skip(4)
.filter(|arg_with_default| arg_with_default.default.is_none())
.filter(|parameter| parameter.default.is_none())
{
checker.diagnostics.push(Diagnostic::new(
BadExitAnnotation {
func_kind,
error_kind: ErrorKind::ArgsAfterFirstFourMustHaveDefault,
},
arg_with_default.range(),
parameter.range(),
));
}
// ...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(
BadExitAnnotation {
func_kind,
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)
/// 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) {
if let Some(varargs) = &args.vararg {
fn check_short_args_list(checker: &mut Checker, parameters: &Parameters, func_kind: FuncKind) {
if let Some(varargs) = &parameters.vararg {
if let Some(annotation) = varargs
.annotation
.as_ref()
@ -187,7 +191,7 @@ fn check_short_args_list(checker: &mut Checker, args: &Arguments, func_kind: Fun
func_kind,
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.
fn check_positional_args(
checker: &mut Checker,
positional_args: &[&ArgWithDefault],
positional_args: &[&ParameterWithDefault],
kind: FuncKind,
) {
// 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_macros::{derive_message_formats, violation};
use ruff_python_ast::Arguments;
use ruff_python_ast::Parameters;
use crate::checkers::ast::Checker;
use crate::settings::types::PythonVersion::Py311;
@ -47,12 +47,12 @@ impl Violation for NoReturnArgumentAnnotationInStub {
}
/// PYI050
pub(crate) fn no_return_argument_annotation(checker: &mut Checker, args: &Arguments) {
for annotation in args
pub(crate) fn no_return_argument_annotation(checker: &mut Checker, parameters: &Parameters) {
for annotation in parameters
.posonlyargs
.iter()
.chain(&args.args)
.chain(&args.kwonlyargs)
.chain(&parameters.args)
.chain(&parameters.kwonlyargs)
.filter_map(|arg| arg.def.annotation.as_ref())
{
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_macros::{derive_message_formats, violation};
@ -116,14 +116,14 @@ pub(crate) fn non_self_return_type(
name: &str,
decorator_list: &[Decorator],
returns: Option<&Expr>,
args: &Arguments,
parameters: &Parameters,
async_: bool,
) {
let ScopeKind::Class(class_def) = checker.semantic().scope().kind else {
return;
};
if args.args.is_empty() && args.posonlyargs.is_empty() {
if parameters.args.is_empty() && parameters.posonlyargs.is_empty() {
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_macros::{derive_message_formats, violation};
@ -53,12 +53,12 @@ impl Violation for RedundantNumericUnion {
}
/// PYI041
pub(crate) fn redundant_numeric_union(checker: &mut Checker, args: &Arguments) {
for annotation in args
pub(crate) fn redundant_numeric_union(checker: &mut Checker, parameters: &Parameters) {
for annotation in parameters
.args
.iter()
.chain(args.posonlyargs.iter())
.chain(args.kwonlyargs.iter())
.chain(parameters.posonlyargs.iter())
.chain(parameters.kwonlyargs.iter())
.filter_map(|arg| arg.def.annotation.as_ref())
{
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
// are not accurate, but check them anyway. It's possible that flagging them will help the user
// realize they're incorrect.
for annotation in args
for annotation in parameters
.vararg
.iter()
.chain(args.kwarg.iter())
.chain(parameters.kwarg.iter())
.filter_map(|arg| arg.annotation.as_ref())
{
check_annotation(checker, annotation);

View file

@ -1,5 +1,5 @@
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};
@ -400,16 +400,16 @@ fn is_annotatable_type_alias(value: &Expr, semantic: &SemanticModel) -> bool {
}
/// PYI011
pub(crate) fn typed_argument_simple_defaults(checker: &mut Checker, arguments: &Arguments) {
for ArgWithDefault {
pub(crate) fn typed_argument_simple_defaults(checker: &mut Checker, parameters: &Parameters) {
for ParameterWithDefault {
def,
default,
range: _,
} in arguments
} in parameters
.posonlyargs
.iter()
.chain(&arguments.args)
.chain(&arguments.kwonlyargs)
.chain(&parameters.args)
.chain(&parameters.kwonlyargs)
{
let Some(default) = default else {
continue;
@ -437,16 +437,16 @@ pub(crate) fn typed_argument_simple_defaults(checker: &mut Checker, arguments: &
}
/// PYI014
pub(crate) fn argument_simple_defaults(checker: &mut Checker, arguments: &Arguments) {
for ArgWithDefault {
pub(crate) fn argument_simple_defaults(checker: &mut Checker, parameters: &Parameters) {
for ParameterWithDefault {
def,
default,
range: _,
} in arguments
} in parameters
.posonlyargs
.iter()
.chain(&arguments.args)
.chain(&arguments.kwonlyargs)
.chain(&parameters.args)
.chain(&parameters.kwonlyargs)
{
let Some(default) = default else {
continue;

View file

@ -48,7 +48,7 @@ pub(crate) fn str_or_repr_defined_in_stub(checker: &mut Checker, stmt: &Stmt) {
name,
decorator_list,
returns,
args,
parameters,
..
}) = stmt
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__`
// 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;
}

View file

@ -1,7 +1,7 @@
use std::fmt;
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_diagnostics::{AlwaysAutofixableViolation, Violation};
@ -607,14 +607,14 @@ fn check_fixture_returns(checker: &mut Checker, stmt: &Stmt, name: &str, body: &
}
/// PT019
fn check_test_function_args(checker: &mut Checker, arguments: &Arguments) {
arguments
fn check_test_function_args(checker: &mut Checker, parameters: &Parameters) {
parameters
.posonlyargs
.iter()
.chain(&arguments.args)
.chain(&arguments.kwonlyargs)
.chain(&parameters.args)
.chain(&parameters.kwonlyargs)
.for_each(
|ArgWithDefault {
|ParameterWithDefault {
def,
default: _,
range: _,
@ -643,8 +643,8 @@ fn check_fixture_decorator_name(checker: &mut Checker, decorator: &Decorator) {
}
/// PT021
fn check_fixture_addfinalizer(checker: &mut Checker, args: &Arguments, body: &[Stmt]) {
if !includes_arg_name("request", args) {
fn check_fixture_addfinalizer(checker: &mut Checker, parameters: &Parameters, body: &[Stmt]) {
if !includes_arg_name("request", parameters) {
return;
}
@ -696,7 +696,7 @@ pub(crate) fn fixture(
checker: &mut Checker,
stmt: &Stmt,
name: &str,
args: &Arguments,
parameters: &Parameters,
decorators: &[Decorator],
body: &[Stmt],
) {
@ -724,7 +724,7 @@ pub(crate) fn fixture(
}
if checker.enabled(Rule::PytestFixtureFinalizerCallback) {
check_fixture_addfinalizer(checker, args, body);
check_fixture_addfinalizer(checker, parameters, body);
}
if checker.enabled(Rule::PytestUnnecessaryAsyncioMarkOnFixture)
@ -735,6 +735,6 @@ pub(crate) fn fixture(
}
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_macros::{derive_message_formats, violation};
@ -20,7 +20,7 @@ impl Violation for PytestPatchWithLambda {
/// Visitor that checks references the argument names in the lambda body.
#[derive(Debug)]
struct LambdaBodyVisitor<'a> {
arguments: &'a Arguments,
parameters: &'a Parameters,
uses_args: bool,
}
@ -31,7 +31,7 @@ where
fn visit_expr(&mut self, expr: &'b Expr) {
match expr {
Expr::Name(ast::ExprName { id, .. }) => {
if includes_arg_name(id, self.arguments) {
if includes_arg_name(id, self.parameters) {
self.uses_args = true;
}
}
@ -55,7 +55,7 @@ fn check_patch_call(
}
let ast::ExprLambda {
args,
parameters,
body,
range: _,
} = CallArguments::new(args, keywords)
@ -64,7 +64,7 @@ fn check_patch_call(
// Walk the lambda body.
let mut visitor = LambdaBodyVisitor {
arguments: args,
parameters,
uses_args: false,
};
visitor.visit_expr(body);

View file

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

View file

@ -2,7 +2,7 @@ use std::iter;
use regex::Regex;
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::{Diagnostic, Violation};
@ -215,26 +215,26 @@ impl Argumentable {
/// Check a plain function for unused arguments.
fn function(
argumentable: Argumentable,
args: &Arguments,
parameters: &Parameters,
values: &Scope,
semantic: &SemanticModel,
dummy_variable_rgx: &Regex,
ignore_variadic_names: bool,
diagnostics: &mut Vec<Diagnostic>,
) {
let args = args
let args = parameters
.posonlyargs
.iter()
.chain(&args.args)
.chain(&args.kwonlyargs)
.map(|arg_with_default| &arg_with_default.def)
.chain(&parameters.args)
.chain(&parameters.kwonlyargs)
.map(|parameter_with_default| &parameter_with_default.def)
.chain(
iter::once::<Option<&Arg>>(args.vararg.as_deref())
iter::once::<Option<&Parameter>>(parameters.vararg.as_deref())
.flatten()
.skip(usize::from(ignore_variadic_names)),
)
.chain(
iter::once::<Option<&Arg>>(args.kwarg.as_deref())
iter::once::<Option<&Parameter>>(parameters.kwarg.as_deref())
.flatten()
.skip(usize::from(ignore_variadic_names)),
);
@ -251,27 +251,27 @@ fn function(
/// Check a method for unused arguments.
fn method(
argumentable: Argumentable,
args: &Arguments,
parameters: &Parameters,
values: &Scope,
semantic: &SemanticModel,
dummy_variable_rgx: &Regex,
ignore_variadic_names: bool,
diagnostics: &mut Vec<Diagnostic>,
) {
let args = args
let args = parameters
.posonlyargs
.iter()
.chain(&args.args)
.chain(&args.kwonlyargs)
.chain(&parameters.args)
.chain(&parameters.kwonlyargs)
.skip(1)
.map(|arg_with_default| &arg_with_default.def)
.map(|parameter_with_default| &parameter_with_default.def)
.chain(
iter::once::<Option<&Arg>>(args.vararg.as_deref())
iter::once::<Option<&Parameter>>(parameters.vararg.as_deref())
.flatten()
.skip(usize::from(ignore_variadic_names)),
)
.chain(
iter::once::<Option<&Arg>>(args.kwarg.as_deref())
iter::once::<Option<&Parameter>>(parameters.kwarg.as_deref())
.flatten()
.skip(usize::from(ignore_variadic_names)),
);
@ -287,13 +287,13 @@ fn method(
fn call<'a>(
argumentable: Argumentable,
args: impl Iterator<Item = &'a Arg>,
parameters: impl Iterator<Item = &'a Parameter>,
values: &Scope,
semantic: &SemanticModel,
dummy_variable_rgx: &Regex,
diagnostics: &mut Vec<Diagnostic>,
) {
diagnostics.extend(args.filter_map(|arg| {
diagnostics.extend(parameters.filter_map(|arg| {
let binding = values
.get(arg.arg.as_str())
.map(|binding_id| semantic.binding(binding_id))?;
@ -324,14 +324,14 @@ pub(crate) fn unused_arguments(
match &scope.kind {
ScopeKind::Function(ast::StmtFunctionDef {
name,
args,
parameters,
body,
decorator_list,
..
})
| ScopeKind::AsyncFunction(ast::StmtAsyncFunctionDef {
name,
args,
parameters,
body,
decorator_list,
..
@ -350,7 +350,7 @@ pub(crate) fn unused_arguments(
{
function(
Argumentable::Function,
args,
parameters,
scope,
checker.semantic(),
&checker.settings.dummy_variable_rgx,
@ -375,7 +375,7 @@ pub(crate) fn unused_arguments(
{
method(
Argumentable::Method,
args,
parameters,
scope,
checker.semantic(),
&checker.settings.dummy_variable_rgx,
@ -400,7 +400,7 @@ pub(crate) fn unused_arguments(
{
method(
Argumentable::ClassMethod,
args,
parameters,
scope,
checker.semantic(),
&checker.settings.dummy_variable_rgx,
@ -425,7 +425,7 @@ pub(crate) fn unused_arguments(
{
function(
Argumentable::StaticMethod,
args,
parameters,
scope,
checker.semantic(),
&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()) {
function(
Argumentable::Lambda,
args,
parameters,
scope,
checker.semantic(),
&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_macros::{derive_message_formats, violation};
@ -50,7 +50,7 @@ impl Violation for InvalidArgumentName {
/// N803
pub(crate) fn invalid_argument_name(
name: &str,
arg: &Arg,
parameter: &Parameter,
ignore_names: &[IdentifierPattern],
) -> Option<Diagnostic> {
if ignore_names
@ -64,7 +64,7 @@ pub(crate) fn invalid_argument_name(
InvalidArgumentName {
name: name.to_string(),
},
arg.range(),
parameter.range(),
));
}
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_macros::{derive_message_formats, violation};
@ -59,7 +59,7 @@ pub(crate) fn invalid_first_argument_name_for_class_method(
scope: &Scope,
name: &str,
decorator_list: &[Decorator],
args: &Arguments,
parameters: &Parameters,
) -> Option<Diagnostic> {
if !matches!(
function_type::classify(
@ -74,11 +74,14 @@ pub(crate) fn invalid_first_argument_name_for_class_method(
) {
return None;
}
if let Some(ArgWithDefault {
if let Some(ParameterWithDefault {
def,
default: _,
range: _,
}) = args.posonlyargs.first().or_else(|| args.args.first())
}) = parameters
.posonlyargs
.first()
.or_else(|| parameters.args.first())
{
if &def.arg != "cls" {
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_macros::{derive_message_formats, violation};
@ -57,7 +57,7 @@ pub(crate) fn invalid_first_argument_name_for_method(
scope: &Scope,
name: &str,
decorator_list: &[Decorator],
args: &Arguments,
parameters: &Parameters,
) -> Option<Diagnostic> {
if !matches!(
function_type::classify(
@ -72,7 +72,10 @@ pub(crate) fn invalid_first_argument_name_for_method(
) {
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" {
return None;
}

View file

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

View file

@ -1,7 +1,7 @@
use itertools::Itertools;
use once_cell::sync::Lazy;
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 rustc_hash::FxHashSet;
@ -1726,27 +1726,23 @@ fn missing_args(checker: &mut Checker, docstring: &Docstring, docstrings_args: &
return;
};
let (Stmt::FunctionDef(ast::StmtFunctionDef {
args: arguments, ..
})
| Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef {
args: arguments, ..
})) = stmt
let (Stmt::FunctionDef(ast::StmtFunctionDef { parameters, .. })
| Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef { parameters, .. })) = stmt
else {
return;
};
// Look for arguments that weren't included in the docstring.
let mut missing_arg_names: FxHashSet<String> = FxHashSet::default();
for ArgWithDefault {
for ParameterWithDefault {
def,
default: _,
range: _,
} in arguments
} in parameters
.posonlyargs
.iter()
.chain(&arguments.args)
.chain(&arguments.kwonlyargs)
.chain(&parameters.args)
.chain(&parameters.kwonlyargs)
.skip(
// If this is a non-static method, skip `cls` or `self`.
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
// 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 starred_arg_name = format!("*{arg_name}");
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);
}
}
if let Some(arg) = &arguments.kwarg {
if let Some(arg) = &parameters.kwarg {
let arg_name = arg.arg.as_str();
let starred_arg_name = format!("**{arg_name}");
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_macros::{derive_message_formats, violation};
@ -51,7 +51,7 @@ pub(crate) fn property_with_parameters(
checker: &mut Checker,
stmt: &Stmt,
decorator_list: &[Decorator],
args: &Arguments,
parameters: &Parameters,
) {
if !decorator_list
.iter()
@ -59,11 +59,11 @@ pub(crate) fn property_with_parameters(
{
return;
}
if args
if parameters
.posonlyargs
.iter()
.chain(&args.args)
.chain(&args.kwonlyargs)
.chain(&parameters.args)
.chain(&parameters.kwonlyargs)
.count()
> 1
&& 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_macros::{derive_message_formats, violation};
@ -58,12 +58,12 @@ impl Violation for TooManyArguments {
}
/// PLR0913
pub(crate) fn too_many_arguments(checker: &mut Checker, arguments: &Arguments, stmt: &Stmt) {
let num_arguments = arguments
pub(crate) fn too_many_arguments(checker: &mut Checker, parameters: &Parameters, stmt: &Stmt) {
let num_arguments = parameters
.args
.iter()
.chain(&arguments.kwonlyargs)
.chain(&arguments.posonlyargs)
.chain(&parameters.kwonlyargs)
.chain(&parameters.posonlyargs)
.filter(|arg| !checker.settings.dummy_variable_rgx.is_match(&arg.def.arg))
.count();
if num_arguments > checker.settings.pylint.max_args {

View file

@ -1,6 +1,6 @@
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_macros::{derive_message_formats, violation};
@ -141,24 +141,31 @@ pub(crate) fn unexpected_special_method_signature(
stmt: &Stmt,
name: &str,
decorator_list: &[Decorator],
args: &Arguments,
parameters: &Parameters,
) {
if !checker.semantic().scope().kind.is_class() {
return;
}
// 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;
}
// 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;
}
let actual_params = args.args.len();
let mandatory_params = args.args.iter().filter(|arg| arg.default.is_none()).count();
let actual_params = parameters.args.len();
let mandatory_params = parameters
.args
.iter()
.filter(|arg| arg.default.is_none())
.count();
let Some(expected_params) =
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 {
mandatory_params <= max
} else {
args.vararg.is_some() || actual_params <= max
parameters.vararg.is_some() || actual_params <= max
}
}
ExpectedParams::Fixed(expected) => match expected.cmp(&mandatory_params) {
Ordering::Less => false,
Ordering::Greater => args.vararg.is_some() || actual_params >= expected,
Ordering::Greater => parameters.vararg.is_some() || actual_params >= expected,
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_macros::{derive_message_formats, violation};
@ -98,19 +98,20 @@ pub(crate) fn super_call_with_parameters(
// Find the enclosing function definition (if any).
let Some(Stmt::FunctionDef(ast::StmtFunctionDef {
args: parent_args, ..
parameters: parent_parameters,
..
})) = parents.find(|stmt| stmt.is_function_def_stmt())
else {
return;
};
// Extract the name of the first argument to the enclosing function.
let Some(ArgWithDefault {
def: Arg {
let Some(ParameterWithDefault {
def: Parameter {
arg: parent_arg, ..
},
..
}) = parent_args.args.first()
}) = parent_parameters.args.first()
else {
return;
};

View file

@ -1,7 +1,9 @@
use std::fmt;
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_diagnostics::{AutofixKind, Diagnostic, Edit, Fix, Violation};
@ -165,16 +167,16 @@ fn generate_fix(checker: &Checker, conversion_type: ConversionType, expr: &Expr)
}
/// RUF013
pub(crate) fn implicit_optional(checker: &mut Checker, arguments: &Arguments) {
for ArgWithDefault {
pub(crate) fn implicit_optional(checker: &mut Checker, parameters: &Parameters) {
for ParameterWithDefault {
def,
default,
range: _,
} in arguments
} in parameters
.posonlyargs
.iter()
.chain(&arguments.args)
.chain(&arguments.kwonlyargs)
.chain(&parameters.args)
.chain(&parameters.kwonlyargs)
{
let Some(default) = default else { continue };
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)]
pub struct ComparableArguments<'a> {
posonlyargs: Vec<ComparableArgWithDefault<'a>>,
args: Vec<ComparableArgWithDefault<'a>>,
vararg: Option<ComparableArg<'a>>,
kwonlyargs: Vec<ComparableArgWithDefault<'a>>,
kwarg: Option<ComparableArg<'a>>,
pub struct ComparableParameters<'a> {
posonlyargs: Vec<ComparableParameterWithDefault<'a>>,
args: Vec<ComparableParameterWithDefault<'a>>,
vararg: Option<ComparableParameter<'a>>,
kwonlyargs: Vec<ComparableParameterWithDefault<'a>>,
kwarg: Option<ComparableParameter<'a>>,
}
impl<'a> From<&'a ast::Arguments> for ComparableArguments<'a> {
fn from(arguments: &'a ast::Arguments) -> Self {
impl<'a> From<&'a ast::Parameters> for ComparableParameters<'a> {
fn from(parameters: &'a ast::Parameters) -> Self {
Self {
posonlyargs: arguments.posonlyargs.iter().map(Into::into).collect(),
args: arguments.args.iter().map(Into::into).collect(),
vararg: arguments.vararg.as_ref().map(Into::into),
kwonlyargs: arguments.kwonlyargs.iter().map(Into::into).collect(),
kwarg: arguments.kwarg.as_ref().map(Into::into),
posonlyargs: parameters.posonlyargs.iter().map(Into::into).collect(),
args: parameters.args.iter().map(Into::into).collect(),
vararg: parameters.vararg.as_ref().map(Into::into),
kwonlyargs: parameters.kwonlyargs.iter().map(Into::into).collect(),
kwarg: parameters.kwarg.as_ref().map(Into::into),
}
}
}
impl<'a> From<&'a Box<ast::Arguments>> for ComparableArguments<'a> {
fn from(arguments: &'a Box<ast::Arguments>) -> Self {
(arguments.as_ref()).into()
impl<'a> From<&'a Box<ast::Parameters>> for ComparableParameters<'a> {
fn from(parameters: &'a Box<ast::Parameters>) -> Self {
(parameters.as_ref()).into()
}
}
impl<'a> From<&'a Box<ast::Arg>> for ComparableArg<'a> {
fn from(arg: &'a Box<ast::Arg>) -> Self {
impl<'a> From<&'a Box<ast::Parameter>> for ComparableParameter<'a> {
fn from(arg: &'a Box<ast::Parameter>) -> Self {
(arg.as_ref()).into()
}
}
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct ComparableArg<'a> {
pub struct ComparableParameter<'a> {
arg: &'a str,
annotation: Option<Box<ComparableExpr<'a>>>,
}
impl<'a> From<&'a ast::Arg> for ComparableArg<'a> {
fn from(arg: &'a ast::Arg) -> Self {
impl<'a> From<&'a ast::Parameter> for ComparableParameter<'a> {
fn from(arg: &'a ast::Parameter) -> Self {
Self {
arg: arg.arg.as_str(),
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)]
pub struct ComparableArgWithDefault<'a> {
def: ComparableArg<'a>,
pub struct ComparableParameterWithDefault<'a> {
def: ComparableParameter<'a>,
default: Option<ComparableExpr<'a>>,
}
impl<'a> From<&'a ast::ArgWithDefault> for ComparableArgWithDefault<'a> {
fn from(arg: &'a ast::ArgWithDefault) -> Self {
impl<'a> From<&'a ast::ParameterWithDefault> for ComparableParameterWithDefault<'a> {
fn from(arg: &'a ast::ParameterWithDefault) -> Self {
Self {
def: (&arg.def).into(),
default: arg.default.as_ref().map(Into::into),
@ -511,7 +511,7 @@ pub struct ExprUnaryOp<'a> {
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct ExprLambda<'a> {
args: ComparableArguments<'a>,
parameters: ComparableParameters<'a>,
body: Box<ComparableExpr<'a>>,
}
@ -739,11 +739,11 @@ impl<'a> From<&'a ast::Expr> for ComparableExpr<'a> {
operand: operand.into(),
}),
ast::Expr::Lambda(ast::ExprLambda {
args,
parameters,
body,
range: _range,
}) => Self::Lambda(ExprLambda {
args: (args.as_ref()).into(),
parameters: (parameters.as_ref()).into(),
body: body.into(),
}),
ast::Expr::IfExp(ast::ExprIfExp {
@ -948,7 +948,7 @@ impl<'a> From<&'a ast::Expr> for ComparableExpr<'a> {
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct StmtFunctionDef<'a> {
name: &'a str,
args: ComparableArguments<'a>,
parameters: ComparableParameters<'a>,
body: Vec<ComparableStmt<'a>>,
decorator_list: Vec<ComparableDecorator<'a>>,
type_params: Vec<ComparableTypeParam<'a>>,
@ -958,7 +958,7 @@ pub struct StmtFunctionDef<'a> {
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct StmtAsyncFunctionDef<'a> {
name: &'a str,
args: ComparableArguments<'a>,
parameters: ComparableParameters<'a>,
body: Vec<ComparableStmt<'a>>,
decorator_list: Vec<ComparableDecorator<'a>>,
type_params: Vec<ComparableTypeParam<'a>>,
@ -1208,7 +1208,7 @@ impl<'a> From<&'a ast::Stmt> for ComparableStmt<'a> {
match stmt {
ast::Stmt::FunctionDef(ast::StmtFunctionDef {
name,
args,
parameters,
body,
decorator_list,
returns,
@ -1216,7 +1216,7 @@ impl<'a> From<&'a ast::Stmt> for ComparableStmt<'a> {
range: _range,
}) => Self::FunctionDef(StmtFunctionDef {
name: name.as_str(),
args: args.into(),
parameters: parameters.into(),
body: body.iter().map(Into::into).collect(),
decorator_list: decorator_list.iter().map(Into::into).collect(),
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 {
name,
args,
parameters,
body,
decorator_list,
returns,
@ -1232,7 +1232,7 @@ impl<'a> From<&'a ast::Stmt> for ComparableStmt<'a> {
range: _range,
}) => Self::AsyncFunctionDef(StmtAsyncFunctionDef {
name: name.as_str(),
args: args.into(),
parameters: parameters.into(),
body: body.iter().map(Into::into).collect(),
decorator_list: decorator_list.iter().map(Into::into).collect(),
returns: returns.as_ref().map(Into::into),

View file

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

View file

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

View file

@ -10,7 +10,7 @@
//!
//! 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_python_trivia::{is_python_whitespace, Cursor};
@ -38,8 +38,8 @@ impl Identifier for Stmt {
}
}
impl Identifier for Arg {
/// Return the [`TextRange`] for the identifier defining an [`Arg`].
impl Identifier for Parameter {
/// Return the [`TextRange`] for the identifier defining an [`Parameter`].
///
/// For example, return the range of `x` in:
/// ```python
@ -51,8 +51,8 @@ impl Identifier for Arg {
}
}
impl Identifier for ArgWithDefault {
/// Return the [`TextRange`] for the identifier defining an [`ArgWithDefault`].
impl Identifier for ParameterWithDefault {
/// Return the [`TextRange`] for the identifier defining an [`ParameterWithDefault`].
///
/// For example, return the range of `x` in:
/// ```python

View file

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

View file

@ -122,7 +122,7 @@ impl From<StmtLineMagic> for Stmt {
pub struct StmtFunctionDef {
pub range: TextRange,
pub name: Identifier,
pub args: Box<Arguments>,
pub parameters: Box<Parameters>,
pub body: Vec<Stmt>,
pub decorator_list: Vec<Decorator>,
pub returns: Option<Box<Expr>>,
@ -140,7 +140,7 @@ impl From<StmtFunctionDef> for Stmt {
pub struct StmtAsyncFunctionDef {
pub range: TextRange,
pub name: Identifier,
pub args: Box<Arguments>,
pub parameters: Box<Parameters>,
pub body: Vec<Stmt>,
pub decorator_list: Vec<Decorator>,
pub returns: Option<Box<Expr>>,
@ -668,7 +668,7 @@ impl From<ExprUnaryOp> for Expr {
#[derive(Clone, Debug, PartialEq)]
pub struct ExprLambda {
pub range: TextRange,
pub args: Box<Arguments>,
pub parameters: Box<Parameters>,
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)
#[derive(Clone, Debug, PartialEq)]
pub struct Arg {
pub struct Parameter {
pub range: TextRange,
pub arg: Identifier,
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.
/// 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.
///
/// The matching Python style AST type is [`PythonArguments`]. While [`PythonArguments`] has ordered `kwonlyargs` fields by
/// default existence, [Arguments] has location-ordered kwonlyargs fields.
/// The original Python-style AST type orders `kwonlyargs` fields by default existence; [Parameters] 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)]
pub struct Arguments {
pub struct Parameters {
pub range: TextRange,
pub posonlyargs: Vec<ArgWithDefault>,
pub args: Vec<ArgWithDefault>,
pub vararg: Option<Box<Arg>>,
pub kwonlyargs: Vec<ArgWithDefault>,
pub kwarg: Option<Box<Arg>>,
pub posonlyargs: Vec<ParameterWithDefault>,
pub args: Vec<ParameterWithDefault>,
pub vararg: Option<Box<Parameter>>,
pub kwonlyargs: Vec<ParameterWithDefault>,
pub kwarg: Option<Box<Parameter>>,
}
/// 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.
#[derive(Clone, Debug, PartialEq)]
pub struct ArgWithDefault {
pub struct ParameterWithDefault {
pub range: TextRange,
pub def: Arg,
pub def: Parameter,
pub default: Option<Box<Expr>>,
}
@ -2105,7 +2092,7 @@ impl CmpOp {
}
}
impl Arguments {
impl Parameters {
pub fn empty(range: TextRange) -> Self {
Self {
range,
@ -2124,21 +2111,21 @@ fn clone_boxed_expr(expr: &Box<Expr>) -> Box<Expr> {
Box::new(expr.clone())
}
impl ArgWithDefault {
pub fn as_arg(&self) -> &Arg {
impl ParameterWithDefault {
pub fn as_parameter(&self) -> &Parameter {
&self.def
}
pub fn to_arg(&self) -> (Arg, Option<Box<Expr>>) {
let ArgWithDefault {
pub fn to_parameter(&self) -> (Parameter, Option<Box<Expr>>) {
let ParameterWithDefault {
range: _,
def,
default,
} = self;
(def.clone(), default.as_ref().map(clone_boxed_expr))
}
pub fn into_arg(self) -> (Arg, Option<Box<Expr>>) {
let ArgWithDefault {
pub fn into_parameter(self) -> (Parameter, Option<Box<Expr>>) {
let ParameterWithDefault {
range: _,
def,
default,
@ -2147,7 +2134,7 @@ impl ArgWithDefault {
}
}
impl Arguments {
impl Parameters {
pub fn defaults(&self) -> impl std::iter::Iterator<Item = &Expr> {
self.posonlyargs
.iter()
@ -2156,14 +2143,14 @@ impl Arguments {
}
#[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 with_defaults = Vec::new();
for arg in &self.kwonlyargs {
if let Some(ref default) = arg.default {
with_defaults.push((arg.as_arg(), &**default));
with_defaults.push((arg.as_parameter(), &**default));
} else {
args.push(arg.as_arg());
args.push(arg.as_parameter());
}
}
(args, with_defaults)
@ -2838,12 +2825,7 @@ impl Ranged for crate::ExceptHandler {
}
}
impl Ranged for crate::nodes::PythonArguments {
fn range(&self) -> TextRange {
self.range
}
}
impl Ranged for crate::nodes::Arg {
impl Ranged for crate::nodes::Parameter {
fn range(&self) -> TextRange {
self.range
}
@ -2952,12 +2934,12 @@ impl Ranged for crate::nodes::Decorator {
self.range
}
}
impl Ranged for crate::nodes::Arguments {
impl Ranged for crate::nodes::Parameters {
fn range(&self) -> TextRange {
self.range
}
}
impl Ranged for crate::nodes::ArgWithDefault {
impl Ranged for crate::nodes::ParameterWithDefault {
fn range(&self) -> TextRange {
self.range
}

View file

@ -3,9 +3,9 @@
pub mod preorder;
use crate::{
self as ast, Alias, Arg, Arguments, BoolOp, CmpOp, Comprehension, Decorator, ElifElseClause,
ExceptHandler, Expr, ExprContext, Keyword, MatchCase, Operator, Pattern, Stmt, TypeParam,
TypeParamTypeVar, UnaryOp, WithItem,
self as ast, Alias, BoolOp, CmpOp, Comprehension, Decorator, ElifElseClause, ExceptHandler,
Expr, ExprContext, Keyword, MatchCase, Operator, Parameter, Parameters, Pattern, Stmt,
TypeParam, TypeParamTypeVar, UnaryOp, WithItem,
};
/// 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) {
walk_format_spec(self, format_spec);
}
fn visit_arguments(&mut self, arguments: &'a Arguments) {
walk_arguments(self, arguments);
fn visit_parameters(&mut self, parameters: &'a Parameters) {
walk_parameters(self, parameters);
}
fn visit_arg(&mut self, arg: &'a Arg) {
walk_arg(self, arg);
fn visit_parameter(&mut self, parameter: &'a Parameter) {
walk_parameter(self, parameter);
}
fn visit_keyword(&mut self, keyword: &'a 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) {
match stmt {
Stmt::FunctionDef(ast::StmtFunctionDef {
args,
parameters,
body,
decorator_list,
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 {
visitor.visit_type_param(type_param);
}
visitor.visit_arguments(args);
visitor.visit_parameters(parameters);
for expr in returns {
visitor.visit_annotation(expr);
}
visitor.visit_body(body);
}
Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef {
args,
parameters,
body,
decorator_list,
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 {
visitor.visit_type_param(type_param);
}
visitor.visit_arguments(args);
visitor.visit_parameters(parameters);
for expr in returns {
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);
}
Expr::Lambda(ast::ExprLambda {
args,
parameters,
body,
range: _range,
}) => {
visitor.visit_arguments(args);
visitor.visit_parameters(parameters);
visitor.visit_expr(body);
}
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);
}
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.
for arg in &arguments.posonlyargs {
for arg in &parameters.posonlyargs {
if let Some(default) = &arg.default {
visitor.visit_expr(default);
}
}
for arg in &arguments.args {
for arg in &parameters.args {
if let Some(default) = &arg.default {
visitor.visit_expr(default);
}
}
for arg in &arguments.kwonlyargs {
for arg in &parameters.kwonlyargs {
if let Some(default) = &arg.default {
visitor.visit_expr(default);
}
}
for arg in &arguments.posonlyargs {
visitor.visit_arg(&arg.def);
for arg in &parameters.posonlyargs {
visitor.visit_parameter(&arg.def);
}
for arg in &arguments.args {
visitor.visit_arg(&arg.def);
for arg in &parameters.args {
visitor.visit_parameter(&arg.def);
}
if let Some(arg) = &arguments.vararg {
visitor.visit_arg(arg);
if let Some(arg) = &parameters.vararg {
visitor.visit_parameter(arg);
}
for arg in &arguments.kwonlyargs {
visitor.visit_arg(&arg.def);
for arg in &parameters.kwonlyargs {
visitor.visit_parameter(&arg.def);
}
if let Some(arg) = &arguments.kwarg {
visitor.visit_arg(arg);
if let Some(arg) = &parameters.kwarg {
visitor.visit_parameter(arg);
}
}
pub fn walk_arg<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, arg: &'a Arg) {
if let Some(expr) = &arg.annotation {
pub fn walk_parameter<'a, V: Visitor<'a> + ?Sized>(visitor: &mut V, parameter: &'a Parameter) {
if let Some(expr) = &parameter.annotation {
visitor.visit_annotation(expr);
}
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,12 +1,12 @@
//! 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 ruff_python_ast::{
self as ast, Alias, Arg, Arguments, BoolOp, CmpOp, Comprehension, Constant, ConversionFlag,
DebugText, ExceptHandler, Expr, Identifier, MatchCase, Operator, Pattern, Stmt, Suite,
TypeParam, TypeParamParamSpec, TypeParamTypeVar, TypeParamTypeVarTuple, WithItem,
self as ast, Alias, BoolOp, CmpOp, Comprehension, Constant, ConversionFlag, DebugText,
ExceptHandler, Expr, Identifier, MatchCase, Operator, Parameter, Parameters, Pattern, Stmt,
Suite, TypeParam, TypeParamParamSpec, TypeParamTypeVar, TypeParamTypeVarTuple, WithItem,
};
use ruff_python_literal::escape::{AsciiEscape, Escape, UnicodeEscape};
@ -205,7 +205,7 @@ impl<'a> Generator<'a> {
match ast {
Stmt::FunctionDef(ast::StmtFunctionDef {
name,
args,
parameters,
body,
returns,
decorator_list,
@ -224,7 +224,7 @@ impl<'a> Generator<'a> {
self.p_id(name);
self.unparse_type_params(type_params);
self.p("(");
self.unparse_args(args);
self.unparse_parameters(parameters);
self.p(")");
if let Some(returns) = returns {
self.p(" -> ");
@ -239,7 +239,7 @@ impl<'a> Generator<'a> {
}
Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef {
name,
args,
parameters,
body,
returns,
decorator_list,
@ -258,7 +258,7 @@ impl<'a> Generator<'a> {
self.p_id(name);
self.unparse_type_params(type_params);
self.p("(");
self.unparse_args(args);
self.unparse_parameters(parameters);
self.p(")");
if let Some(returns) = returns {
self.p(" -> ");
@ -985,14 +985,14 @@ impl<'a> Generator<'a> {
});
}
Expr::Lambda(ast::ExprLambda {
args,
parameters,
body,
range: _range,
}) => {
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.unparse_args(args);
self.unparse_parameters(parameters);
self.p(": ");
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;
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.unparse_arg_with_default(arg_with_default);
self.p_if(i + 1 == args.posonlyargs.len(), ", /");
self.unparse_parameter_with_default(parameter_with_default);
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("*");
}
if let Some(vararg) = &args.vararg {
self.unparse_arg(vararg);
if let Some(vararg) = &parameters.vararg {
self.unparse_parameter(vararg);
}
for kwarg in &args.kwonlyargs {
for kwarg in &parameters.kwonlyargs {
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("**");
self.unparse_arg(kwarg);
self.unparse_parameter(kwarg);
}
}
fn unparse_arg(&mut self, arg: &Arg) {
self.p_id(&arg.arg);
if let Some(ann) = &arg.annotation {
fn unparse_parameter(&mut self, parameter: &Parameter) {
self.p_id(&parameter.arg);
if let Some(ann) = &parameter.annotation {
self.p(": ");
self.unparse_expr(ann, precedence::COMMA);
}
}
fn unparse_arg_with_default(&mut self, arg_with_default: &ArgWithDefault) {
self.unparse_arg(&arg_with_default.def);
if let Some(default) = &arg_with_default.default {
fn unparse_parameter_with_default(&mut self, parameter_with_default: &ParameterWithDefault) {
self.unparse_parameter(&parameter_with_default.def);
if let Some(default) = &parameter_with_default.default {
self.p("=");
self.unparse_expr(default, precedence::COMMA);
}

View file

@ -1,8 +1,8 @@
use std::cmp::Ordering;
use ruff_python_ast::{
self as ast, Arguments, Comprehension, Expr, ExprAttribute, ExprBinOp, ExprIfExp, ExprSlice,
ExprStarred, MatchCase, Ranged,
self as ast, Comprehension, Expr, ExprAttribute, ExprBinOp, ExprIfExp, ExprSlice, ExprStarred,
MatchCase, Parameters, Ranged,
};
use ruff_text_size::TextRange;
@ -15,7 +15,7 @@ use ruff_source_file::{Locator, UniversalNewlines};
use crate::comments::visitor::{CommentPlacement, DecoratedComment};
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,
};
@ -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
// fixups.
match comment.enclosing_node() {
AnyNodeRef::Arguments(arguments) => {
handle_arguments_separator_comment(comment, arguments, locator)
AnyNodeRef::Parameters(arguments) => {
handle_parameters_separator_comment(comment, arguments, locator)
}
AnyNodeRef::Comprehension(comprehension) => {
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
/// separator `*` as dangling comments to the enclosing [`Arguments`] node.
/// Attaches comments for the positional-only parameters separator `/` or the keywords-only
/// parameters separator `*` as dangling comments to the enclosing [`Parameters`] node.
///
/// See [`assign_argument_separator_comment_placement`]
fn handle_arguments_separator_comment<'a>(
fn handle_parameters_separator_comment<'a>(
comment: DecoratedComment<'a>,
arguments: &Arguments,
parameters: &Parameters,
locator: &Locator,
) -> 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 placement = assign_argument_separator_comment_placement(
slash.as_ref(),
@ -832,11 +832,11 @@ fn handle_leading_function_with_decorators_comment(comment: DecoratedComment) ->
.preceding_node()
.is_some_and(|node| node.is_decorator());
let is_following_arguments = comment
let is_following_parameters = comment
.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)
} else {
CommentPlacement::Default(comment)

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,7 +1,7 @@
use crate::comments::dangling_node_comments;
use crate::context::PyFormatContext;
use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses};
use crate::other::arguments::ArgumentsParentheses;
use crate::other::parameters::ParametersParentheses;
use crate::AsFormat;
use crate::{FormatNodeRule, PyFormatter};
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<()> {
let ExprLambda {
range: _,
args,
parameters,
body,
} = item;
write!(f, [text("lambda")])?;
if !args.args.is_empty() {
if !parameters.args.is_empty() {
write!(
f,
[
space(),
args.format().with_options(ArgumentsParentheses::Never),
parameters
.format()
.with_options(ParametersParentheses::Never),
]
)?;
}
@ -44,7 +46,7 @@ impl FormatNodeRule<ExprLambda> for FormatExprLambda {
// lambda # Dangling
// : 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 {
#[inline]
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
impl FormatRule<ast::Parameters, PyFormatContext<'_>>
for crate::other::parameters::FormatParameters
{
#[inline]
fn fmt(
&self,
node: &ast::ArgWithDefault,
node: &ast::Parameters,
f: &mut Formatter<PyFormatContext<'_>>,
) -> 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<
'a,
ast::ArgWithDefault,
crate::other::arg_with_default::FormatArgWithDefault,
ast::Parameters,
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>,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(
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<
ast::ArgWithDefault,
crate::other::arg_with_default::FormatArgWithDefault,
ast::ParameterWithDefault,
crate::other::parameter_with_default::FormatParameterWithDefault,
PyFormatContext<'ast>,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(
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 arg;
pub(crate) mod arg_with_default;
pub(crate) mod arguments;
pub(crate) mod comprehension;
pub(crate) mod decorator;
pub(crate) mod elif_else_clause;
@ -9,4 +6,7 @@ pub(crate) mod except_handler_except_handler;
pub(crate) mod identifier;
pub(crate) mod keyword;
pub(crate) mod match_case;
pub(crate) mod parameter;
pub(crate) mod parameter_with_default;
pub(crate) mod parameters;
pub(crate) mod with_item;

View file

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

View file

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

View file

@ -1,6 +1,6 @@
use std::usize;
use ruff_python_ast::{Arguments, Ranged};
use ruff_python_ast::{Parameters, Ranged};
use ruff_text_size::{TextRange, TextSize};
use ruff_formatter::{format_args, write, FormatRuleWithOptions};
@ -17,14 +17,14 @@ use crate::prelude::*;
use crate::FormatNodeRule;
#[derive(Eq, PartialEq, Debug, Default)]
pub enum ArgumentsParentheses {
/// By default, arguments will always preserve their surrounding parentheses.
pub enum ParametersParentheses {
/// By default, parameters will always preserve their surrounding parentheses.
#[default]
Preserve,
/// 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:
/// ```python
/// lambda (x, y, z): ...
@ -37,12 +37,12 @@ pub enum ArgumentsParentheses {
}
#[derive(Default)]
pub struct FormatArguments {
parentheses: ArgumentsParentheses,
pub struct FormatParameters {
parentheses: ParametersParentheses,
}
impl FormatRuleWithOptions<Arguments, PyFormatContext<'_>> for FormatArguments {
type Options = ArgumentsParentheses;
impl FormatRuleWithOptions<Parameters, PyFormatContext<'_>> for FormatParameters {
type Options = ParametersParentheses;
fn with_options(mut self, options: Self::Options) -> Self {
self.parentheses = options;
@ -50,9 +50,9 @@ impl FormatRuleWithOptions<Arguments, PyFormatContext<'_>> for FormatArguments {
}
}
impl FormatNodeRule<Arguments> for FormatArguments {
fn fmt_fields(&self, item: &Arguments, f: &mut PyFormatter) -> FormatResult<()> {
let Arguments {
impl FormatNodeRule<Parameters> for FormatParameters {
fn fmt_fields(&self, item: &Parameters, f: &mut PyFormatter) -> FormatResult<()> {
let Parameters {
range: _,
posonlyargs,
args,
@ -70,10 +70,10 @@ impl FormatNodeRule<Arguments> for FormatArguments {
let mut joiner = f.join_with(separator);
let mut last_node: Option<AnyNodeRef> = None;
for arg_with_default in posonlyargs {
joiner.entry(&arg_with_default.format());
for parameter_with_default in posonlyargs {
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() {
@ -86,7 +86,7 @@ impl FormatNodeRule<Arguments> for FormatArguments {
comment.slice().range(),
comment.line_position(),
)
.expect("Unexpected dangling comment type in function arguments");
.expect("Unexpected dangling comment type in function parameters");
matches!(
assignment,
ArgumentSeparatorCommentLocation::SlashLeading
@ -100,10 +100,10 @@ impl FormatNodeRule<Arguments> for FormatArguments {
slash_comments_end
};
for arg_with_default in args {
joiner.entry(&arg_with_default.format());
for parameter_with_default in args {
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 `*`
@ -139,10 +139,10 @@ impl FormatNodeRule<Arguments> for FormatArguments {
});
}
for arg_with_default in kwonlyargs {
joiner.entry(&arg_with_default.format());
for parameter_with_default in kwonlyargs {
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 {
@ -168,7 +168,7 @@ impl FormatNodeRule<Arguments> for FormatArguments {
// # Never expands, the comma is always preserved
// 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
// behave like a magic trailing comma, it's just preserved
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 num_arguments = posonlyargs.len()
let num_parameters = posonlyargs.len()
+ args.len()
+ usize::from(vararg.is_some())
+ kwonlyargs.len()
+ usize::from(kwarg.is_some());
if self.parentheses == ArgumentsParentheses::Never {
if self.parentheses == ParametersParentheses::Never {
write!(f, [group(&format_inner)])
} else if num_arguments == 0 {
// No arguments, format any dangling comments between `()`
} else if num_parameters == 0 {
// No parameters, format any dangling comments between `()`
write!(
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`
Ok(())
}
@ -283,18 +283,18 @@ pub(crate) struct ArgumentSeparator {
/// Returns slash and star
pub(crate) fn find_argument_separators(
contents: &str,
arguments: &Arguments,
parameters: &Parameters,
) -> (Option<ArgumentSeparator>, Option<ArgumentSeparator>) {
// 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
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
// def f(a1=1, a2=2, /, a3, a4): pass
// ^^^^^^^^^^^ the range (defaults)
// def f(a1, a2, /, a3, a4): pass
// ^^^^^^^^^^^^ 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 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
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
// formatting
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:
// * `f(a, /, b, *, c)` and `f(a=1, /, b=2, *, c)`
// * `f(a, /, *, b)`
// * `f(*, b)` (else branch)
let after_arguments = arguments
let after_parameters = parameters
.args
.last()
.map(|arg| arg.range.end())
.or(slash.map(|(_, slash)| slash.end()));
if let Some(preceding_end) = after_arguments {
let range = TextRange::new(preceding_end, arguments.end());
if let Some(preceding_end) = after_parameters {
let range = TextRange::new(preceding_end, parameters.end());
let mut tokens = SimpleTokenizer::new(contents, range).skip_trivia();
let comma = tokens
@ -345,7 +345,7 @@ pub(crate) fn find_argument_separators(
following_start: first_keyword_argument.start(),
})
} else {
let mut tokens = SimpleTokenizer::new(contents, arguments.range).skip_trivia();
let mut tokens = SimpleTokenizer::new(contents, parameters.range).skip_trivia();
let lparen = tokens
.next()
@ -356,7 +356,7 @@ pub(crate) fn find_argument_separators(
.expect("The function definition can't end here");
debug_assert!(star.kind() == SimpleTokenKind::Star, "{star:?}");
Some(ArgumentSeparator {
preceding_end: arguments.range.start(),
preceding_end: parameters.range.start(),
separator: star.range,
following_start: first_keyword_argument.start(),
})
@ -371,13 +371,13 @@ pub(crate) fn find_argument_separators(
// * `f(a, /, *b)`
// * `f(a, /, *, b)`
// * `f(a, /)`
let slash_following_start = arguments
let slash_following_start = parameters
.args
.first()
.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()))
.unwrap_or(arguments.end());
.unwrap_or(parameters.end());
let slash = slash.map(|(preceding_end, slash)| ArgumentSeparator {
preceding_end,
separator: slash,
@ -387,13 +387,13 @@ pub(crate) fn find_argument_separators(
(slash, star)
}
/// Locates positional only arguments separator `/` or the keywords only arguments
/// Locates positional only parameters separator `/` or the keywords only parameters
/// separator `*` comments.
///
/// ```python
/// def test(
/// a,
/// # Positional only arguments after here
/// # Positional only parameters after here
/// /, # trailing positional argument comment.
/// b,
/// ):
@ -403,7 +403,7 @@ pub(crate) fn find_argument_separators(
/// ```python
/// def f(
/// a="",
/// # Keyword only arguments only after here
/// # Keyword only parameters only after here
/// *, # trailing keyword argument comment.
/// b="",
/// ):
@ -439,43 +439,43 @@ pub(crate) fn find_argument_separators(
///
/// ```text
/// 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
/// def f(a1, a2, *, a3, a4): pass
/// ^^^^^^ arguments (args)
/// ^^^^^^ keyword only arguments (kwargs)
/// ^^^^^^ parameters (args)
/// ^^^^^^ keyword only parameters (kwargs)
/// ```
/// Use a slash to separate positional only arguments. Note that this changes the arguments left
/// of the slash while the star change the arguments right of it:
/// Use a slash to separate positional only parameters. Note that this changes the parameters left
/// of the slash while the star change the parameters right of it:
/// ```text
/// def f(a1, a2, /, a3, a4): pass
/// ^^^^^^ positional only arguments (posonlyargs)
/// ^^^^^^ arguments (args)
/// ^^^^^^ positional only parameters (posonlyargs)
/// ^^^^^^ parameters (args)
/// ```
/// You can combine both:
/// ```text
/// def f(a1, a2, /, a3, a4, *, a5, a6): pass
/// ^^^^^^ positional only arguments (posonlyargs)
/// ^^^^^^ arguments (args)
/// ^^^^^^ keyword only arguments (kwargs)
/// ^^^^^^ positional only parameters (posonlyargs)
/// ^^^^^^ parameters (args)
/// ^^^^^^ keyword only parameters (kwargs)
/// ```
/// They can all have defaults, meaning that the preceding node ends at the default instead of the
/// argument itself:
/// ```text
/// def f(a1=1, a2=2, /, a3=3, a4=4, *, a5=5, a6=6): pass
/// ^ ^ ^ ^ ^ ^ defaults
/// ^^^^^^^^^^ positional only arguments (posonlyargs)
/// ^^^^^^^^^^ arguments (args)
/// ^^^^^^^^^^ keyword only arguments (kwargs)
/// ^^^^^^^^^^ positional only parameters (posonlyargs)
/// ^^^^^^^^^^ parameters (args)
/// ^^^^^^^^^^ 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.
/// ```text
/// def f(a1, a2, /, *, a3, a4): pass
/// ^^^^^^ positional only arguments (posonlyargs)
/// ^^^^^^ keyword only arguments (kwargs)
/// ^^^^^^ positional only parameters (posonlyargs)
/// ^^^^^^ keyword only parameters (kwargs)
/// ```
pub(crate) fn assign_argument_separator_comment_placement(
slash: Option<&ArgumentSeparator>,
@ -583,27 +583,31 @@ pub(crate) enum ArgumentSeparatorCommentLocation {
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
let Some(last_node) = last_node else {
return false;
};
let ends_with_pos_only_argument_separator = !arguments.posonlyargs.is_empty()
&& arguments.args.is_empty()
&& arguments.vararg.is_none()
&& arguments.kwonlyargs.is_empty()
&& arguments.kwarg.is_none();
let ends_with_pos_only_argument_separator = !parameters.posonlyargs.is_empty()
&& parameters.args.is_empty()
&& parameters.vararg.is_none()
&& parameters.kwonlyargs.is_empty()
&& parameters.kwarg.is_none();
let mut tokens = SimpleTokenizer::starts_at(last_node.end(), source).skip_trivia();
// `def a(b, c, /): ... `
// The slash lacks its own node
if ends_with_pos_only_argument_separator {
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();
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

View file

@ -12,7 +12,7 @@ pub(crate) struct ArgumentList {
}
// 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(
arguments.posonlyargs.len()
+ arguments.args.len()
@ -26,8 +26,8 @@ pub(crate) fn validate_arguments(arguments: &ast::Arguments) -> Result<(), Lexic
let args = arguments.args.iter();
let kwonlyargs = arguments.kwonlyargs.iter();
let vararg: Option<&ast::Arg> = arguments.vararg.as_deref();
let kwarg: Option<&ast::Arg> = arguments.kwarg.as_deref();
let vararg: Option<&ast::Parameter> = arguments.vararg.as_deref();
let kwarg: Option<&ast::Parameter> = arguments.kwarg.as_deref();
for arg in posonlyargs
.chain(args)
@ -50,7 +50,10 @@ pub(crate) fn validate_arguments(arguments: &ast::Arguments) -> Result<(), Lexic
}
pub(crate) fn validate_pos_params(
args: &(Vec<ast::ArgWithDefault>, Vec<ast::ArgWithDefault>),
args: &(
Vec<ast::ParameterWithDefault>,
Vec<ast::ParameterWithDefault>,
),
) -> Result<(), LexicalError> {
let (posonlyargs, args) = args;
#[allow(clippy::skip_while_next)]

View file

@ -1015,9 +1015,9 @@ FuncDef: ast::Stmt = {
let returns = r.map(Box::new);
let end_location = body.last().unwrap().end();
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 {
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> =>? {
a.as_ref().map(validate_arguments).transpose()?;
let range = (location..end_location).into();
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
});
@ -1058,15 +1058,15 @@ Parameters: ast::Arguments = {
// Note that this is a macro which is used once for function defs, and
// once for lambda defs.
ParameterList<ArgType, StarArgType, DoubleStarArgType>: ast::Arguments = {
<location:@L> <param1:ParameterDefs<ArgType>> <args2:("," <ParameterListStarArgs<ArgType, StarArgType, DoubleStarArgType>>)?> ","? <end_location:@R> =>? {
ParameterList<ParameterType, StarParameterType, DoubleStarParameterType>: ast::Parameters = {
<location:@L> <param1:ParameterDefs<ParameterType>> <args2:("," <ParameterListStarArgs<ParameterType, StarParameterType, DoubleStarParameterType>>)?> ","? <end_location:@R> =>? {
validate_pos_params(&param1)?;
let (posonlyargs, args) = param1;
// Now gather rest of parameters:
let (vararg, kwonlyargs, kwarg) = args2.unwrap_or((None, vec![], None));
Ok(ast::Arguments {
Ok(ast::Parameters {
posonlyargs,
args,
kwonlyargs,
@ -1075,7 +1075,7 @@ ParameterList<ArgType, StarArgType, DoubleStarArgType>: ast::Arguments = {
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)?;
let (posonlyargs, args) = param1;
@ -1084,7 +1084,7 @@ ParameterList<ArgType, StarArgType, DoubleStarArgType>: ast::Arguments = {
let kwonlyargs = vec![];
let kwarg = kw;
Ok(ast::Arguments {
Ok(ast::Parameters {
posonlyargs,
args,
kwonlyargs,
@ -1093,9 +1093,9 @@ ParameterList<ArgType, StarArgType, DoubleStarArgType>: ast::Arguments = {
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;
ast::Arguments {
ast::Parameters {
posonlyargs: vec![],
args: vec![],
kwonlyargs,
@ -1104,8 +1104,8 @@ ParameterList<ArgType, StarArgType, DoubleStarArgType>: ast::Arguments = {
range: (location..end_location).into()
}
},
<location:@L> <kwarg:KwargParameter<DoubleStarArgType>> ","? <end_location:@R> => {
ast::Arguments {
<location:@L> <kwarg:KwargParameter<DoubleStarParameterType>> ","? <end_location:@R> => {
ast::Parameters {
posonlyargs: vec![],
args: 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.
#[inline]
ParameterDefs<ArgType>: (Vec<ast::ArgWithDefault>, Vec<ast::ArgWithDefault>) = {
<args:OneOrMore<ParameterDef<ArgType>>> => {
ParameterDefs<ParameterType>: (Vec<ast::ParameterWithDefault>, Vec<ast::ParameterWithDefault>) = {
<args:OneOrMore<ParameterDef<ParameterType>>> => {
(vec![], args)
},
<posonlyargs:OneOrMore<ParameterDef<ArgType>>> "," "/" <args:("," <ParameterDef<ArgType>>)*> => {
<posonlyargs:OneOrMore<ParameterDef<ParameterType>>> "," "/" <args:("," <ParameterDef<ParameterType>>)*> => {
(posonlyargs, args)
},
};
ParameterDef<ArgType>: ast::ArgWithDefault = {
<i:ArgType> => i,
<mut i:ArgType> "=" <e:Test<"all">> <end_location:@R> => {
ParameterDef<ParameterType>: ast::ParameterWithDefault = {
<i:ParameterType> => i,
<mut i:ParameterType> "=" <e:Test<"all">> <end_location:@R> => {
i.default = Some(Box::new(e));
i.range = (i.range.start()..end_location).into();
i
},
};
UntypedParameter: ast::ArgWithDefault = {
UntypedParameter: ast::ParameterWithDefault = {
<location:@L> <arg:Identifier> <end_location:@R> => {
let def = ast::Arg { arg, annotation: None, range: (location..end_location).into() };
ast::ArgWithDefault { def, default: None, range: (location..end_location).into() }
let def = ast::Parameter { arg, annotation: None, range: (location..end_location).into() };
ast::ParameterWithDefault { def, default: None, range: (location..end_location).into() }
},
};
StarUntypedParameter: ast::Arg = {
<location:@L> <arg:Identifier> <end_location:@R> => ast::Arg { arg, annotation: None, range: (location..end_location).into() },
StarUntypedParameter: ast::Parameter = {
<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> => {
let annotation = a.map(Box::new);
let def = ast::Arg { arg, annotation, range: (location..end_location).into() };
ast::ArgWithDefault { def, default: None, range: (location..end_location).into() }
let def = ast::Parameter { arg, annotation, 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> => {
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> => {
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.
// TODO: figure out another grammar that makes this inline no longer required.
#[inline]
ParameterListStarArgs<ArgType, StarArgType, DoubleStarArgType>: (Option<Box<ast::Arg>>, Vec<ast::ArgWithDefault>, Option<Box<ast::Arg>>) = {
<location:@L> "*" <va:StarArgType?> <kwonlyargs:("," <ParameterDef<ArgType>>)*> <kwarg:("," <KwargParameter<DoubleStarArgType>>)?> =>? {
ParameterListStarArgs<ParameterType, StarParameterType, DoubleStarParameterType>: (Option<Box<ast::Parameter>>, Vec<ast::ParameterWithDefault>, Option<Box<ast::Parameter>>) = {
<location:@L> "*" <va:StarParameterType?> <kwonlyargs:("," <ParameterDef<ParameterType>>)*> <kwarg:("," <KwargParameter<DoubleStarParameterType>>)?> =>? {
if va.is_none() && kwonlyargs.is_empty() && kwarg.is_none() {
return Err(LexicalError {
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>> = {
"**" <kwarg:ArgType?> => {
KwargParameter<ParameterType>: Option<Box<ast::Parameter>> = {
"**" <kwarg:ParameterType?> => {
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> =>? {
p.as_ref().map(validate_arguments).transpose()?;
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(
ast::ExprLambda {
args: Box::new(p),
parameters: Box::new(p),
body: Box::new(body),
range: (location..end_location).into()
}

File diff suppressed because it is too large Load diff

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

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