Skip to content

Commit

Permalink
Try boxing some node fields
Browse files Browse the repository at this point in the history
  • Loading branch information
dhruvmanila committed Dec 1, 2023
1 parent 613b68f commit b9aa0da
Show file tree
Hide file tree
Showing 37 changed files with 93 additions and 99 deletions.
2 changes: 1 addition & 1 deletion crates/ruff_linter/src/checkers/ast/analyze/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
decorator_list,
returns.as_ref().map(AsRef::as_ref),
parameters,
type_params.as_ref(),
type_params.as_deref(),
);
}
if checker.source_type.is_stub() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ pub(crate) fn assert_raises_exception(checker: &mut Checker, items: &[WithItem])
func,
arguments,
range: _,
}) = &item.context_expr
}) = item.context_expr.as_ref()
else {
return;
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,17 +84,17 @@ pub(crate) fn cached_instance_method(checker: &mut Checker, decorator_list: &[De
for decorator in decorator_list {
// TODO(charlie): This should take into account `classmethod-decorators` and
// `staticmethod-decorators`.
if let Expr::Name(ast::ExprName { id, .. }) = &decorator.expression {
if let Expr::Name(ast::ExprName { id, .. }) = decorator.expression.as_ref() {
if id == "classmethod" || id == "staticmethod" {
return;
}
}
}
for decorator in decorator_list {
if is_cache_func(
match &decorator.expression {
match decorator.expression.as_ref() {
Expr::Call(ast::ExprCall { func, .. }) => func,
_ => &decorator.expression,
expr => expr,
},
checker.semantic(),
) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ pub(crate) fn unnecessary_dict_comprehension(
if !generator.ifs.is_empty() || generator.is_async {
return;
}
let Expr::Tuple(ast::ExprTuple { elts, .. }) = &generator.target else {
let Expr::Tuple(ast::ExprTuple { elts, .. }) = generator.target.as_ref() else {
return;
};
let [target_key, target_value] = elts.as_slice() else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -687,7 +687,7 @@ fn pytest_fixture_parentheses(

/// PT001, PT002, PT003
fn check_fixture_decorator(checker: &mut Checker, func_name: &str, decorator: &Decorator) {
match &decorator.expression {
match decorator.expression.as_ref() {
Expr::Call(ast::ExprCall {
func,
arguments,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ fn pytest_mark_parentheses(
}

fn check_mark_parentheses(checker: &mut Checker, decorator: &Decorator, marker: &str) {
match &decorator.expression {
match decorator.expression.as_ref() {
Expr::Call(ast::ExprCall {
func,
arguments:
Expand Down Expand Up @@ -167,7 +167,7 @@ fn check_useless_usefixtures(checker: &mut Checker, decorator: &Decorator, marke
return;
}

match &decorator.expression {
match decorator.expression.as_ref() {
// @pytest.mark.usefixtures
Expr::Attribute(..) => {}
// @pytest.mark.usefixtures(...)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -628,7 +628,7 @@ pub(crate) fn parametrize(checker: &mut Checker, decorators: &[Decorator]) {
if let Expr::Call(ast::ExprCall {
arguments: Arguments { args, .. },
..
}) = &decorator.expression
}) = decorator.expression.as_ref()
{
if checker.enabled(Rule::PytestParametrizeNamesWrongType) {
if let [names, ..] = args.as_slice() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ pub(crate) fn complex_raises(
items: &[WithItem],
body: &[Stmt],
) {
let raises_called = items.iter().any(|item| match &item.context_expr {
let raises_called = items.iter().any(|item| match item.context_expr.as_ref() {
Expr::Call(ast::ExprCall { func, .. }) => is_pytest_raises(func, checker.semantic()),
_ => false,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ fn explicit_with_items(checker: &mut Checker, with_items: &[WithItem]) -> bool {
let [with_item] = with_items else {
return false;
};
let Expr::Call(expr_call) = &with_item.context_expr else {
let Expr::Call(expr_call) = with_item.context_expr.as_ref() else {
return false;
};
checker
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ fn nested_if_body(stmt_if: &ast::StmtIf) -> Option<NestedIf> {
// depends on the outer of the two conditions
let (test, nested_if) = if let Some(clause) = elif_else_clauses.last() {
if let Some(test) = &clause.test {
(test, NestedIf::Elif(clause))
(test.as_ref(), NestedIf::Elif(clause))
} else {
// The last condition is an `else` (different rule)
return None;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ pub(crate) fn if_else_block_instead_of_dict_lookup(checker: &mut Checker, stmt_i
return;
};

match test.as_ref() {
match test.as_deref() {
// `else`
None => {
// The else must also be a single effect-free return statement
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ pub(crate) fn needless_bool(checker: &mut Checker, stmt_if: &ast::StmtIf) {
test: None,
range: else_range,
}] => (
elif_test,
elif_test.as_ref(),
elif_body,
else_body,
TextRange::new(elif_range.start(), else_range.end()),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ fn match_async_exit_stack(semantic: &SemanticModel) -> bool {
for parent in semantic.current_statements() {
if let Stmt::With(ast::StmtWith { items, .. }) = parent {
for item in items {
if let Expr::Call(ast::ExprCall { func, .. }) = &item.context_expr {
if let Expr::Call(ast::ExprCall { func, .. }) = item.context_expr.as_ref() {
if semantic.resolve_call_path(func).is_some_and(|call_path| {
matches!(call_path.as_slice(), ["contextlib", "AsyncExitStack"])
}) {
Expand Down Expand Up @@ -93,7 +93,7 @@ fn match_exit_stack(semantic: &SemanticModel) -> bool {
for parent in semantic.current_statements() {
if let Stmt::With(ast::StmtWith { items, .. }) = parent {
for item in items {
if let Expr::Call(ast::ExprCall { func, .. }) = &item.context_expr {
if let Expr::Call(ast::ExprCall { func, .. }) = item.context_expr.as_ref() {
if semantic.resolve_call_path(func).is_some_and(|call_path| {
matches!(call_path.as_slice(), ["contextlib", "ExitStack"])
}) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -375,8 +375,8 @@ fn return_stmt(id: &str, test: &Expr, target: &Expr, iter: &Expr, generator: Gen
let node = ast::ExprGeneratorExp {
elt: Box::new(test.clone()),
generators: vec![Comprehension {
target: target.clone(),
iter: iter.clone(),
target: Box::new(target.clone()),
iter: Box::new(iter.clone()),
ifs: vec![],
is_async: false,
range: TextRange::default(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ pub(crate) fn is_singledispatch_implementation(
semantic: &SemanticModel,
) -> bool {
function_def.decorator_list.iter().any(|decorator| {
let Expr::Attribute(attribute) = &decorator.expression else {
let Expr::Attribute(attribute) = decorator.expression.as_ref() else {
return false;
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ fn function(
.iter()
.chain(&parameters.args)
.chain(&parameters.kwonlyargs)
.map(|parameter_with_default| &parameter_with_default.parameter)
.map(|parameter_with_default| parameter_with_default.parameter.as_ref())
.chain(
iter::once::<Option<&Parameter>>(parameters.vararg.as_deref())
.flatten()
Expand Down Expand Up @@ -265,7 +265,7 @@ fn method(
.chain(&parameters.args)
.chain(&parameters.kwonlyargs)
.skip(1)
.map(|parameter_with_default| &parameter_with_default.parameter)
.map(|parameter_with_default| parameter_with_default.parameter.as_ref())
.chain(
iter::once::<Option<&Parameter>>(parameters.vararg.as_deref())
.flatten()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,12 +198,12 @@ fn function(
.iter()
.enumerate()
.map(|(idx, parameter)| ParameterWithDefault {
parameter: Parameter {
parameter: Box::new(Parameter {
annotation: arg_types
.get(idx)
.map(|arg_type| Box::new(arg_type.clone())),
..parameter.parameter.clone()
},
..*parameter.parameter.clone()
}),
..parameter.clone()
})
.collect::<Vec<_>>();
Expand All @@ -212,12 +212,12 @@ fn function(
.iter()
.enumerate()
.map(|(idx, parameter)| ParameterWithDefault {
parameter: Parameter {
parameter: Box::new(Parameter {
annotation: arg_types
.get(idx + new_posonlyargs.len())
.map(|arg_type| Box::new(arg_type.clone())),
..parameter.parameter.clone()
},
..*parameter.parameter.clone()
}),
..parameter.clone()
})
.collect::<Vec<_>>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ fn get_undecorated_methods(

// if we find the decorator we're looking for, skip
if decorator_list.iter().any(|decorator| {
if let Expr::Name(ast::ExprName { id, .. }) = &decorator.expression {
if let Expr::Name(ast::ExprName { id, .. }) = decorator.expression.as_ref() {
if id == method_name && checker.semantic().is_builtin(method_name) {
return true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ pub(crate) fn property_with_parameters(
) {
if !decorator_list
.iter()
.any(|decorator| matches!(&decorator.expression, Expr::Name(ast::ExprName { id, .. }) if id == "property"))
.any(|decorator| matches!(decorator.expression.as_ref(), Expr::Name(ast::ExprName { id, .. }) if id == "property"))
{
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ pub(crate) fn too_many_boolean_expressions(checker: &mut Checker, stmt: &StmtIf)
}

for elif in &stmt.elif_else_clauses {
if let Some(bool_op) = elif.test.as_ref().and_then(Expr::as_bool_op_expr) {
if let Some(bool_op) = elif.test.as_deref().and_then(Expr::as_bool_op_expr) {
let expressions = count_bools(bool_op);
if expressions > checker.settings.pylint.max_bool_expr {
checker.diagnostics.push(Diagnostic::new(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ pub(crate) fn unnecessary_lambda(checker: &mut Checker, lambda: &ExprLambda) {
let lambda_posargs: Vec<&Parameter> = parameters
.args
.iter()
.map(|ParameterWithDefault { parameter, .. }| parameter)
.map(|ParameterWithDefault { parameter, .. }| parameter.as_ref())
.collect::<Vec<_>>();
if call_posargs.len() != lambda_posargs.len() {
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ pub(crate) fn lru_cache_with_maxsize_none(checker: &mut Checker, decorator_list:
range: _,
},
range: _,
}) = &decorator.expression
}) = decorator.expression.as_ref()
else {
continue;
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ pub(crate) fn lru_cache_without_parameters(checker: &mut Checker, decorator_list
func,
arguments,
range: _,
}) = &decorator.expression
}) = decorator.expression.as_ref()
else {
continue;
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{self as ast, Expr, Parameter, ParameterWithDefault, Stmt};
use ruff_python_ast::{self as ast, Expr, ParameterWithDefault, Stmt};
use ruff_text_size::{Ranged, TextSize};

use crate::checkers::ast::Checker;
Expand Down Expand Up @@ -90,15 +90,10 @@ pub(crate) fn super_call_with_parameters(checker: &mut Checker, call: &ast::Expr
};

// Extract the name of the first argument to the enclosing function.
let Some(ParameterWithDefault {
parameter: Parameter {
name: parent_arg, ..
},
..
}) = parent_parameters.args.first()
else {
let Some(ParameterWithDefault { parameter, .. }) = parent_parameters.args.first() else {
return;
};
let parent_arg = &parameter.name;

// Find the enclosing class definition (if any).
let Some(Stmt::ClassDef(ast::StmtClassDef {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ pub(crate) fn non_pep695_type_alias(checker: &mut Checker, stmt: &StmtAnnAssign)
checker.generator().stmt(&Stmt::from(StmtTypeAlias {
range: TextRange::default(),
name: target.clone(),
type_params,
type_params: type_params.map(Box::new),
value: value.clone(),
})),
stmt.range(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,7 @@ fn match_comprehension_target(comprehension: &ast::Comprehension) -> Option<Comp
if comprehension.is_async || !comprehension.ifs.is_empty() {
return None;
}
match &comprehension.target {
match comprehension.target.as_ref() {
Expr::Tuple(tuple) => Some(ComprehensionTarget::Tuple(tuple)),
Expr::Name(name) => Some(ComprehensionTarget::Name(name)),
_ => None,
Expand Down
2 changes: 1 addition & 1 deletion crates/ruff_linter/src/rules/ruff/rules/unreachable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,7 @@ fn match_case<'stmt>(
/// Returns true if `pattern` is a wildcard (`_`) pattern.
fn is_wildcard(pattern: &MatchCase) -> bool {
pattern.guard.is_none()
&& matches!(&pattern.pattern, Pattern::MatchAs(PatternMatchAs { pattern, name, .. }) if pattern.is_none() && name.is_none())
&& matches!(pattern.pattern.as_ref(), Pattern::MatchAs(PatternMatchAs { pattern, name, .. }) if pattern.is_none() && name.is_none())
}

#[derive(Debug, Default)]
Expand Down
4 changes: 2 additions & 2 deletions crates/ruff_python_ast/src/comparable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ impl<'a> From<&'a ast::PatternKeyword> for ComparablePatternKeyword<'a> {
fn from(keyword: &'a ast::PatternKeyword) -> Self {
Self {
attr: keyword.attr.as_str(),
pattern: (&keyword.pattern).into(),
pattern: (keyword.pattern.as_ref()).into(),
}
}
}
Expand Down Expand Up @@ -306,7 +306,7 @@ pub struct ComparableMatchCase<'a> {
impl<'a> From<&'a ast::MatchCase> for ComparableMatchCase<'a> {
fn from(match_case: &'a ast::MatchCase) -> Self {
Self {
pattern: (&match_case.pattern).into(),
pattern: (match_case.pattern.as_ref()).into(),
guard: match_case.guard.as_ref().map(Into::into),
body: match_case.body.iter().map(Into::into).collect(),
}
Expand Down
4 changes: 2 additions & 2 deletions crates/ruff_python_ast/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1433,10 +1433,10 @@ mod tests {
});
let type_alias = Stmt::TypeAlias(StmtTypeAlias {
name: Box::new(name.clone()),
type_params: Some(TypeParams {
type_params: Some(Box::new(TypeParams {
type_params: vec![type_var_one, type_var_two],
range: TextRange::default(),
}),
})),
value: Box::new(constant_three.clone()),
range: TextRange::default(),
});
Expand Down
Loading

0 comments on commit b9aa0da

Please sign in to comment.