refactor(isolated_declarations, linter, minifier, prettier, semantic, transformer): remove unnecessary ref / ref mut syntax (#8643)

While working on #8641, I found a lot of places where we unnecessarily use `ref` / `ref mut` in match arms.

In many cases, we're creating double-references (turning a `&T` into a `&&T`). The compiler should be smart enough to remove them for us, but there doesn't seem much point in explicitly creating double-references when we don't actually want them, and relying on compiler to optimize them out again.
This commit is contained in:
overlookmotel 2025-01-21 14:20:07 +00:00
parent 54d0fac987
commit e66da9fe41
29 changed files with 63 additions and 67 deletions

View file

@ -368,7 +368,7 @@ impl<'a> IsolatedDeclarations<'a> {
for element in &decl.body.body {
match element {
ClassElement::StaticBlock(_) => {}
ClassElement::MethodDefinition(ref method) => {
ClassElement::MethodDefinition(method) => {
if self.has_internal_annotation(method.span) {
continue;
}

View file

@ -195,7 +195,7 @@ impl<'a> IsolatedDeclarations<'a> {
// 2. Transform export declarations
// 3. Collect all bindings / reference from module declarations
// 4. Collect transformed indexes
for stmt in &stmts {
for &stmt in &stmts {
match stmt {
match_declaration!(Statement) => {
if let Statement::TSModuleDeclaration(decl) = stmt {
@ -433,8 +433,8 @@ impl<'a> IsolatedDeclarations<'a> {
let mut last_function_name: Option<Atom<'a>> = None;
let mut is_export_default_function_overloads = false;
stmts.retain(move |stmt| match stmt {
Statement::FunctionDeclaration(ref func) => {
stmts.retain(move |&stmt| match stmt {
Statement::FunctionDeclaration(func) => {
let name = func
.id
.as_ref()
@ -454,8 +454,8 @@ impl<'a> IsolatedDeclarations<'a> {
}
true
}
Statement::ExportNamedDeclaration(ref decl) => {
if let Some(Declaration::FunctionDeclaration(ref func)) = decl.declaration {
Statement::ExportNamedDeclaration(decl) => {
if let Some(Declaration::FunctionDeclaration(func)) = &decl.declaration {
let name = func
.id
.as_ref()
@ -477,10 +477,8 @@ impl<'a> IsolatedDeclarations<'a> {
true
}
}
Statement::ExportDefaultDeclaration(ref decl) => {
if let ExportDefaultDeclarationKind::FunctionDeclaration(ref func) =
decl.declaration
{
Statement::ExportDefaultDeclaration(decl) => {
if let ExportDefaultDeclarationKind::FunctionDeclaration(func) = &decl.declaration {
if is_export_default_function_overloads && func.body.is_some() {
is_export_default_function_overloads = false;
return false;

View file

@ -51,7 +51,7 @@ impl IsolatedLintHandler {
// a diagnostics connected from related_info to original diagnostic
let mut inverted_diagnostics = vec![];
for d in &diagnostics {
let Some(ref related_info) = d.diagnostic.related_information else {
let Some(related_info) = &d.diagnostic.related_information else {
continue;
};
let related_information = Some(vec![DiagnosticRelatedInformation {

View file

@ -491,7 +491,7 @@ impl<'a> CompositeFix<'a> {
let mut output = String::new();
for fix in fixes {
let Fix { ref content, span } = fix;
let Fix { content, span } = fix;
// negative range or overlapping ranges is invalid
if span.start > span.end {
debug_assert!(false, "Negative range is invalid: {span:?}");
@ -513,7 +513,7 @@ impl<'a> CompositeFix<'a> {
output.reserve(before.len() + content.len());
output.push_str(before);
output.push_str(content);
output.push_str(&content);
last_pos = span.end;
}

View file

@ -227,7 +227,7 @@ impl GetterReturn {
// If the signature of function supports the return of the `undefined` value,
// you do not need to check this rule
if let AstKind::Function(func) = node.kind() {
if let Some(ref ret) = func.return_type {
if let Some(ret) = &func.return_type {
if ret.type_annotation.is_maybe_undefined() {
break 'returns true;
}

View file

@ -158,7 +158,7 @@ impl<'a> Visit<'a> for ConsecutiveSpaceFinder {
if ch.value != u32::from(b' ') {
return;
}
if let Some(ref mut space_span) = self.last_space_span {
if let Some(space_span) = &mut self.last_space_span {
// If this is consecutive with the last space, extend it
if space_span.end == ch.span.start {
space_span.end = ch.span.end;

View file

@ -45,7 +45,7 @@ where
IgnorePattern::Default => {
name.strip_prefix('_').map_or(".".into(), |name| format!(" to '{name}'."))
}
IgnorePattern::Some(ref r) => {
IgnorePattern::Some(r) => {
format!(" to match the pattern /{r}/.")
}
};

View file

@ -267,7 +267,7 @@ impl<R> IgnorePattern<R> {
match self {
Self::Default => IgnorePattern::Default,
Self::None => IgnorePattern::None,
Self::Some(ref r) => IgnorePattern::Some(r),
Self::Some(r) => IgnorePattern::Some(r),
}
}
}

View file

@ -266,7 +266,7 @@ impl SortImports {
let specifiers: Vec<_> = specifiers
.iter()
.filter_map(|specifier| {
if let ImportDeclarationSpecifier::ImportSpecifier(ref specifier) = specifier {
if let ImportDeclarationSpecifier::ImportSpecifier(specifier) = specifier {
Some(specifier)
} else {
None

View file

@ -121,8 +121,8 @@ impl Rule for First {
for statement in &program.body {
match statement {
Statement::TSImportEqualsDeclaration(decl) => match decl.module_reference {
TSModuleReference::ExternalModuleReference(ref mod_ref) => {
Statement::TSImportEqualsDeclaration(decl) => match &decl.module_reference {
TSModuleReference::ExternalModuleReference(mod_ref) => {
if matches!(self.absolute_first, AbsoluteFirst::AbsoluteFirst) {
if is_relative_path(mod_ref.expression.value.as_str()) {
any_relative = true;

View file

@ -56,7 +56,7 @@ impl Rule for NoAmd {
return;
}
if let AstKind::CallExpression(call_expr) = node.kind() {
if let Expression::Identifier(ref identifier) = &call_expr.callee {
if let Expression::Identifier(identifier) = &call_expr.callee {
if identifier.name != "define" && identifier.name != "require" {
return;
}

View file

@ -131,7 +131,7 @@ fn run<'a>(possible_jest_node: &PossibleJestNode<'a, '_>, ctx: &LintContext<'a>)
diagnostic(ctx, fn_expr.span, Message::UnexpectedDescribeArgument);
}
let Some(ref body) = fn_expr.body else {
let Some(body) = &fn_expr.body else {
return;
};
if let Some(span) = find_first_return_stmt_span(body) {

View file

@ -149,7 +149,7 @@ impl Rule for RequireReturns {
match parent_node.kind() {
AstKind::Function(_) | AstKind::ArrowFunctionExpression(_) => {
// Ignore `return;`
let Some(ref argument) = return_stmt.argument else {
let Some(argument) = &return_stmt.argument else {
continue 'visit_node;
};

View file

@ -69,7 +69,7 @@ impl Rule for NoTypos {
if let AstKind::ModuleDeclaration(ModuleDeclaration::ExportNamedDeclaration(en_decl)) =
node.kind()
{
if let Some(ref decl) = en_decl.declaration {
if let Some(decl) = &en_decl.declaration {
match decl {
Declaration::VariableDeclaration(decl) => {
for decl in &decl.declarations {

View file

@ -129,7 +129,7 @@ impl Rule for NoAccumulatingSpread {
let AstKind::SpreadElement(spread) = node.kind() else {
return;
};
let Expression::Identifier(ref ident) = spread.argument else {
let Expression::Identifier(ident) = &spread.argument else {
return;
};

View file

@ -41,7 +41,7 @@ fn get_resolvable_ident<'a>(node: &'a JSXElementName<'a>) -> Option<&'a Identifi
JSXElementName::Identifier(_)
| JSXElementName::NamespacedName(_)
| JSXElementName::ThisExpression(_) => None,
JSXElementName::IdentifierReference(ref ident) => Some(ident),
JSXElementName::IdentifierReference(ident) => Some(ident),
JSXElementName::MemberExpression(expr) => get_member_ident(expr),
}
}

View file

@ -202,7 +202,7 @@ impl Rule for BanTsComment {
));
}
if let DirectiveConfig::DescriptionFormat(Some(ref re)) = config {
if let DirectiveConfig::DescriptionFormat(Some(re)) = config {
if !re.is_match(description) {
ctx.diagnostic(comment_description_not_match_pattern(
directive,

View file

@ -193,8 +193,8 @@ impl Rule for NoRequireImports {
ctx.diagnostic(no_require_imports_diagnostic(call_expr.span));
}
AstKind::TSImportEqualsDeclaration(decl) => match decl.module_reference {
TSModuleReference::ExternalModuleReference(ref mod_ref) => {
AstKind::TSImportEqualsDeclaration(decl) => match &decl.module_reference {
TSModuleReference::ExternalModuleReference(mod_ref) => {
if self.allow_as_import {
return;
}

View file

@ -134,8 +134,8 @@ impl Rule for TripleSlashReference {
if !refs_for_import.is_empty() {
for stmt in &program.body {
match stmt {
Statement::TSImportEqualsDeclaration(decl) => match decl.module_reference {
TSModuleReference::ExternalModuleReference(ref mod_ref) => {
Statement::TSImportEqualsDeclaration(decl) => match &decl.module_reference {
TSModuleReference::ExternalModuleReference(mod_ref) => {
if let Some(v) = refs_for_import.get(mod_ref.expression.value.as_str())
{
ctx.diagnostic(triple_slash_reference_diagnostic(

View file

@ -84,7 +84,7 @@ impl Rule for NoThenable {
}
AstKind::ModuleDeclaration(ModuleDeclaration::ExportNamedDeclaration(decl)) => {
// check declaration
if let Some(ref decl) = decl.declaration {
if let Some(decl) = &decl.declaration {
match decl {
Declaration::VariableDeclaration(decl) => {
for decl in &decl.declarations {
@ -242,8 +242,8 @@ fn check_expression(expr: &Expression, ctx: &LintContext<'_>) -> Option<oxc_span
let decl = ctx.semantic().nodes().get_node(symbols.get_declaration(symbol_id));
let var_decl = decl.kind().as_variable_declarator()?;
match var_decl.init {
Some(Expression::StringLiteral(ref lit)) => {
match &var_decl.init {
Some(Expression::StringLiteral(lit)) => {
if lit.value == "then" {
Some(lit.span)
} else {

View file

@ -145,7 +145,7 @@ fn check_array_reduce_case<'a>(call_expr: &CallExpression<'a>, ctx: &LintContext
&first_argument.params.items[1].pattern.kind,
) {
(
BindingPatternKind::BindingIdentifier(ref first_param),
BindingPatternKind::BindingIdentifier(first_param),
BindingPatternKind::BindingIdentifier(second_param),
) => Some((&first_param.name, &second_param.name)),

View file

@ -339,7 +339,7 @@ impl<'a> PeepholeOptimizations {
if sequence_expr.expressions.len() > 1 {
let span = expr.span();
let mut sequence = ctx.ast.move_expression(&mut expr.test);
let Expression::SequenceExpression(ref mut sequence_expr) = &mut sequence else {
let Expression::SequenceExpression(sequence_expr) = &mut sequence else {
unreachable!()
};
let test = sequence_expr.expressions.pop().unwrap();
@ -587,15 +587,13 @@ impl<'a> PeepholeOptimizations {
{
let callee = ctx.ast.move_expression(&mut consequent.callee);
let consequent_first_arg = {
let Argument::SpreadElement(ref mut el) = &mut consequent.arguments[0]
else {
let Argument::SpreadElement(el) = &mut consequent.arguments[0] else {
unreachable!()
};
ctx.ast.move_expression(&mut el.argument)
};
let alternate_first_arg = {
let Argument::SpreadElement(ref mut el) = &mut alternate.arguments[0]
else {
let Argument::SpreadElement(el) = &mut alternate.arguments[0] else {
unreachable!()
};
ctx.ast.move_expression(&mut el.argument)

View file

@ -1558,11 +1558,11 @@ impl<'a> Format<'a> for PrivateIdentifier<'a> {
impl<'a> Format<'a> for BindingPattern<'a> {
fn format(&self, p: &mut Prettier<'a>) -> Doc<'a> {
let mut parts = Vec::new_in(p.allocator);
parts.push(match self.kind {
BindingPatternKind::BindingIdentifier(ref ident) => ident.format(p),
BindingPatternKind::ObjectPattern(ref pattern) => pattern.format(p),
BindingPatternKind::ArrayPattern(ref pattern) => pattern.format(p),
BindingPatternKind::AssignmentPattern(ref pattern) => pattern.format(p),
parts.push(match &self.kind {
BindingPatternKind::BindingIdentifier(ident) => ident.format(p),
BindingPatternKind::ObjectPattern(pattern) => pattern.format(p),
BindingPatternKind::ArrayPattern(pattern) => pattern.format(p),
BindingPatternKind::AssignmentPattern(pattern) => pattern.format(p),
});
if self.optional {

View file

@ -39,7 +39,7 @@ use crate::{
macro_rules! control_flow {
($self:ident, |$cfg:tt| $body:expr) => {
if let Some(ref mut $cfg) = $self.cfg {
if let Some($cfg) = &mut $self.cfg {
$body
} else {
Default::default()

View file

@ -124,7 +124,7 @@ impl DebugDot for BasicBlock {
impl DebugDot for Instruction {
fn debug_dot(&self, ctx: DebugDotContext) -> String {
match self.kind {
match &self.kind {
InstructionKind::Statement => {
self.node_id.map_or("None".to_string(), |id| ctx.debug_ast_kind(id))
}
@ -136,7 +136,7 @@ impl DebugDot for Instruction {
ctx.try_eval_literal(id).unwrap_or_else(|| ctx.debug_ast_kind(id))
)
}),
InstructionKind::Iteration(ref kind) => {
InstructionKind::Iteration(kind) => {
format!(
"Iteration({} {} {})",
self.node_id.map_or("None".to_string(), |id| ctx.debug_ast_kind(id)),

View file

@ -313,7 +313,7 @@ impl<'a> Traverse<'a> for ReactRefresh<'a, '_> {
let hook_name = match &call_expr.callee {
Expression::Identifier(ident) => ident.name,
Expression::StaticMemberExpression(ref member) => member.property.name,
Expression::StaticMemberExpression(member) => member.property.name,
_ => return,
};
@ -434,7 +434,7 @@ impl<'a> ReactRefresh<'a, '_> {
ctx: &mut TraverseCtx<'a>,
) -> bool {
match expr {
Expression::Identifier(ref ident) => {
Expression::Identifier(ident) => {
// For case like:
// export const Something = hoc(Foo)
// we don't want to wrap Foo inside the call.
@ -451,7 +451,7 @@ impl<'a> ReactRefresh<'a, '_> {
return false;
}
}
Expression::CallExpression(ref mut call_expr) => {
Expression::CallExpression(call_expr) => {
let allowed_callee = matches!(
call_expr.callee,
Expression::Identifier(_)
@ -660,7 +660,7 @@ impl<'a> ReactRefresh<'a, '_> {
None
}
}
Statement::ExportDefaultDeclaration(ref mut stmt_decl) => {
Statement::ExportDefaultDeclaration(stmt_decl) => {
match &mut stmt_decl.declaration {
declaration @ match_expression!(ExportDefaultDeclarationKind) => {
let expression = declaration.to_expression_mut();

View file

@ -33,14 +33,14 @@ impl BrowserslistQuery {
};
let result = match self {
BrowserslistQuery::Single(ref s) => {
BrowserslistQuery::Single(s) => {
if s.is_empty() {
browserslist::resolve(&["defaults"], &options)
} else {
browserslist::resolve(&[s], &options)
}
}
BrowserslistQuery::Multiple(ref s) => browserslist::resolve(s, &options),
BrowserslistQuery::Multiple(s) => browserslist::resolve(s, &options),
};
let result = match result {

View file

@ -359,10 +359,10 @@ impl<'a> ReplaceGlobalDefines<'a> {
.left
.as_simple_assignment_target_mut()
.and_then(|item| match item {
SimpleAssignmentTarget::ComputedMemberExpression(ref mut computed_member_expr) => {
SimpleAssignmentTarget::ComputedMemberExpression(computed_member_expr) => {
self.replace_dot_computed_member_expr(ctx, computed_member_expr)
}
SimpleAssignmentTarget::StaticMemberExpression(ref mut member) => {
SimpleAssignmentTarget::StaticMemberExpression(member) => {
self.replace_dot_static_member_expr(ctx, member)
}
SimpleAssignmentTarget::AssignmentTargetIdentifier(ident) => {
@ -387,10 +387,10 @@ impl<'a> ReplaceGlobalDefines<'a> {
Expression::ChainExpression(chain) => {
let Some(new_expr) =
chain.expression.as_member_expression_mut().and_then(|item| match item {
MemberExpression::ComputedMemberExpression(
ref mut computed_member_expr,
) => self.replace_dot_computed_member_expr(ctx, computed_member_expr),
MemberExpression::StaticMemberExpression(ref mut member) => {
MemberExpression::ComputedMemberExpression(computed_member_expr) => {
self.replace_dot_computed_member_expr(ctx, computed_member_expr)
}
MemberExpression::StaticMemberExpression(member) => {
self.replace_dot_static_member_expr(ctx, member)
}
MemberExpression::PrivateFieldExpression(_) => None,
@ -414,7 +414,7 @@ impl<'a> ReplaceGlobalDefines<'a> {
}
}
Expression::MetaProperty(meta_property) => {
if let Some(ref replacement) = self.config.0.import_meta {
if let Some(replacement) = &self.config.0.import_meta {
if meta_property.meta.name == "import" && meta_property.property.name == "meta"
{
let value = self.parse_value(replacement);
@ -476,8 +476,8 @@ impl<'a> ReplaceGlobalDefines<'a> {
member: &StaticMemberExpression<'a>,
) -> bool {
if meta_define.parts.is_empty() && meta_define.postfix_wildcard {
match member.object {
Expression::MetaProperty(ref meta) => {
match &member.object {
Expression::MetaProperty(meta) => {
return meta.meta.name == "import" && meta.property.name == "meta";
}
_ => return false,
@ -642,11 +642,11 @@ fn destructing_dot_define_optimizer<'ast>(
mut expr: Expression<'ast>,
ctx: &mut TraverseCtx<'ast>,
) -> Expression<'ast> {
let Expression::ObjectExpression(ref mut obj) = expr else { return expr };
let Expression::ObjectExpression(obj) = &mut expr else { return expr };
let parent = ctx.parent();
let destruct_obj_pat = match parent {
Ancestor::VariableDeclaratorInit(declarator) => match declarator.id().kind {
BindingPatternKind::ObjectPattern(ref pat) => pat,
Ancestor::VariableDeclaratorInit(declarator) => match &declarator.id().kind {
BindingPatternKind::ObjectPattern(pat) => pat,
_ => return expr,
},
_ => {

View file

@ -232,7 +232,7 @@ impl<'a> TypeScriptEnum<'a> {
};
init
} else if let Some(ref value) = prev_constant_value {
} else if let Some(value) = &prev_constant_value {
match value {
ConstantValue::Number(value) => {
let value = value + 1.0;