From ff21256e355a86fc5064ea0f3648f98cdb5e4e23 Mon Sep 17 00:00:00 2001 From: Victorien Elvinger Date: Thu, 25 Jul 2024 17:33:20 +0200 Subject: [PATCH] refactor: consistently use `cast`, `cast_ref` and `try_cast` (#3520) --- .../biome_css_syntax/src/generated/nodes.rs | 18 +++++--- .../src/generated/nodes.rs | 15 +++---- .../biome_grit_syntax/src/generated/nodes.rs | 13 +++--- .../lint/a11y/no_noninteractive_tabindex.rs | 2 +- .../src/lint/a11y/no_positive_tabindex.rs | 9 ++-- .../src/lint/complexity/no_for_each.rs | 2 +- .../lint/complexity/no_useless_fragments.rs | 11 +++-- .../src/lint/complexity/use_flat_map.rs | 4 +- .../lint/correctness/no_constant_condition.rs | 20 ++++----- .../no_constant_math_min_max_clamp.rs | 2 +- .../lint/correctness/no_flat_map_identity.rs | 2 +- .../correctness/no_string_case_mismatch.rs | 2 +- .../no_unused_private_class_members.rs | 10 ++--- .../use_exhaustive_dependencies.rs | 21 +++++----- .../lint/correctness/use_hook_at_top_level.rs | 20 +++++---- .../src/lint/correctness/use_is_nan.rs | 2 +- .../correctness/use_jsx_key_in_iterable.rs | 6 +-- .../src/lint/nursery/no_console.rs | 2 +- .../lint/nursery/no_label_without_control.rs | 35 ++++++++-------- .../src/lint/nursery/use_date_now.rs | 13 +++--- .../src/lint/nursery/use_top_level_regex.rs | 41 +++++++++++-------- .../performance/no_accumulating_spread.rs | 2 +- .../src/lint/performance/no_barrel_file.rs | 8 ++-- .../lint/style/use_exponentiation_operator.rs | 2 +- .../src/lint/style/use_numeric_literals.rs | 2 +- .../src/lint/style/use_shorthand_assign.rs | 2 +- .../src/lint/suspicious/no_array_index_key.rs | 2 +- .../src/lint/suspicious/no_console_log.rs | 2 +- .../no_control_characters_in_regex.rs | 4 +- .../suspicious/no_duplicate_class_members.rs | 10 ++--- .../src/lint/suspicious/no_import_assign.rs | 2 +- .../no_misleading_character_class.rs | 8 ++-- .../no_misrefactored_shorthand_assign.rs | 2 +- .../lint/suspicious/no_prototype_builtins.rs | 2 +- .../suspicious/no_redundant_use_strict.rs | 21 ++++++---- .../src/lint/suspicious/use_getter_return.rs | 4 +- crates/biome_js_analyze/src/react/hooks.rs | 3 +- .../correctness/no_super_without_extends.rs | 26 +++++++----- .../expressions/arrow_function_expression.rs | 2 +- crates/biome_js_formatter/src/parentheses.rs | 2 +- .../src/utils/assignment_like.rs | 2 +- crates/biome_js_syntax/src/jsx_ext.rs | 8 ++-- crates/biome_rowan/src/ast/mod.rs | 9 ++-- xtask/codegen/src/generate_nodes.rs | 9 ++-- 44 files changed, 205 insertions(+), 179 deletions(-) diff --git a/crates/biome_css_syntax/src/generated/nodes.rs b/crates/biome_css_syntax/src/generated/nodes.rs index 8c6f3e42b8c8..4593d71c2f8e 100644 --- a/crates/biome_css_syntax/src/generated/nodes.rs +++ b/crates/biome_css_syntax/src/generated/nodes.rs @@ -20284,9 +20284,12 @@ impl AstNode for AnyCssQueryFeatureValue { CSS_NUMBER => AnyCssQueryFeatureValue::CssNumber(CssNumber { syntax }), CSS_RATIO => AnyCssQueryFeatureValue::CssRatio(CssRatio { syntax }), _ => { - if let Some(any_css_dimension) = AnyCssDimension::cast(syntax.clone()) { - return Some(AnyCssQueryFeatureValue::AnyCssDimension(any_css_dimension)); - } + let syntax = match AnyCssDimension::try_cast(syntax) { + Ok(any_css_dimension) => { + return Some(AnyCssQueryFeatureValue::AnyCssDimension(any_css_dimension)); + } + Err(syntax) => syntax, + }; if let Some(any_css_function) = AnyCssFunction::cast(syntax) { return Some(AnyCssQueryFeatureValue::AnyCssFunction(any_css_function)); } @@ -21682,9 +21685,12 @@ impl AstNode for AnyCssValue { CSS_STRING => AnyCssValue::CssString(CssString { syntax }), CSS_UNICODE_RANGE => AnyCssValue::CssUnicodeRange(CssUnicodeRange { syntax }), _ => { - if let Some(any_css_dimension) = AnyCssDimension::cast(syntax.clone()) { - return Some(AnyCssValue::AnyCssDimension(any_css_dimension)); - } + let syntax = match AnyCssDimension::try_cast(syntax) { + Ok(any_css_dimension) => { + return Some(AnyCssValue::AnyCssDimension(any_css_dimension)); + } + Err(syntax) => syntax, + }; if let Some(any_css_function) = AnyCssFunction::cast(syntax) { return Some(AnyCssValue::AnyCssFunction(any_css_function)); } diff --git a/crates/biome_graphql_syntax/src/generated/nodes.rs b/crates/biome_graphql_syntax/src/generated/nodes.rs index a1b0b3fbc95e..7f32332ebdcf 100644 --- a/crates/biome_graphql_syntax/src/generated/nodes.rs +++ b/crates/biome_graphql_syntax/src/generated/nodes.rs @@ -6044,13 +6044,14 @@ impl AstNode for AnyGraphqlDefinition { AnyGraphqlDefinition::GraphqlSelectionSet(GraphqlSelectionSet { syntax }) } _ => { - if let Some(any_graphql_type_definition) = - AnyGraphqlTypeDefinition::cast(syntax.clone()) - { - return Some(AnyGraphqlDefinition::AnyGraphqlTypeDefinition( - any_graphql_type_definition, - )); - } + let syntax = match AnyGraphqlTypeDefinition::try_cast(syntax) { + Ok(any_graphql_type_definition) => { + return Some(AnyGraphqlDefinition::AnyGraphqlTypeDefinition( + any_graphql_type_definition, + )); + } + Err(syntax) => syntax, + }; if let Some(any_graphql_type_extension) = AnyGraphqlTypeExtension::cast(syntax) { return Some(AnyGraphqlDefinition::AnyGraphqlTypeExtension( any_graphql_type_extension, diff --git a/crates/biome_grit_syntax/src/generated/nodes.rs b/crates/biome_grit_syntax/src/generated/nodes.rs index af8789f2ab28..66867c046092 100644 --- a/crates/biome_grit_syntax/src/generated/nodes.rs +++ b/crates/biome_grit_syntax/src/generated/nodes.rs @@ -11328,11 +11328,14 @@ impl AstNode for AnyGritPredicateMatchSubject { } } fn cast(syntax: SyntaxNode) -> Option { - if let Some(any_grit_container) = AnyGritContainer::cast(syntax.clone()) { - return Some(AnyGritPredicateMatchSubject::AnyGritContainer( - any_grit_container, - )); - } + let syntax = match AnyGritContainer::try_cast(syntax) { + Ok(any_grit_container) => { + return Some(AnyGritPredicateMatchSubject::AnyGritContainer( + any_grit_container, + )); + } + Err(syntax) => syntax, + }; if let Some(any_grit_literal) = AnyGritLiteral::cast(syntax) { return Some(AnyGritPredicateMatchSubject::AnyGritLiteral( any_grit_literal, diff --git a/crates/biome_js_analyze/src/lint/a11y/no_noninteractive_tabindex.rs b/crates/biome_js_analyze/src/lint/a11y/no_noninteractive_tabindex.rs index 311600757fe1..c61464e10867 100644 --- a/crates/biome_js_analyze/src/lint/a11y/no_noninteractive_tabindex.rs +++ b/crates/biome_js_analyze/src/lint/a11y/no_noninteractive_tabindex.rs @@ -195,7 +195,7 @@ fn attribute_has_negative_tabindex( AnyJsxAttributeValue::JsxExpressionAttributeValue(value) => { let expression = value.expression().ok()?; let expression_value = - AnyNumberLikeExpression::cast_ref(expression.syntax())?.value()?; + AnyNumberLikeExpression::cast(expression.into_syntax())?.value()?; Some(is_negative_tabindex(&expression_value)) } _ => None, diff --git a/crates/biome_js_analyze/src/lint/a11y/no_positive_tabindex.rs b/crates/biome_js_analyze/src/lint/a11y/no_positive_tabindex.rs index 9b127fa6409c..78a90facbc9e 100644 --- a/crates/biome_js_analyze/src/lint/a11y/no_positive_tabindex.rs +++ b/crates/biome_js_analyze/src/lint/a11y/no_positive_tabindex.rs @@ -138,12 +138,11 @@ impl Rule for NoPositiveTabindex { } TabindexProp::JsPropertyObjectMember(js_object_member) => { let expression = js_object_member.value().ok()?; - let expression_syntax_node = expression.syntax(); + let range = expression.range(); let expression_value = - AnyNumberLikeExpression::cast_ref(expression_syntax_node)?.value()?; - + AnyNumberLikeExpression::cast(expression.into_syntax())?.value()?; if !is_tabindex_valid(&expression_value) { - return Some(expression_syntax_node.text_trimmed_range()); + return Some(range); } } } @@ -214,7 +213,7 @@ fn attribute_has_valid_tabindex(jsx_any_attribute_value: &AnyJsxAttributeValue) AnyJsxAttributeValue::JsxExpressionAttributeValue(value) => { let expression = value.expression().ok()?; let expression_value = - AnyNumberLikeExpression::cast_ref(expression.syntax())?.value()?; + AnyNumberLikeExpression::cast(expression.into_syntax())?.value()?; Some(is_tabindex_valid(&expression_value)) } diff --git a/crates/biome_js_analyze/src/lint/complexity/no_for_each.rs b/crates/biome_js_analyze/src/lint/complexity/no_for_each.rs index 0d5095a66079..5a68f872ce93 100644 --- a/crates/biome_js_analyze/src/lint/complexity/no_for_each.rs +++ b/crates/biome_js_analyze/src/lint/complexity/no_for_each.rs @@ -81,7 +81,7 @@ impl Rule for NoForEach { fn run(ctx: &RuleContext) -> Self::Signals { let node = ctx.query(); let member_expression = - AnyJsMemberExpression::cast_ref(node.callee().ok()?.omit_parentheses().syntax())?; + AnyJsMemberExpression::cast(node.callee().ok()?.omit_parentheses().into_syntax())?; if member_expression.member_name()?.text() != "forEach" { return None; } diff --git a/crates/biome_js_analyze/src/lint/complexity/no_useless_fragments.rs b/crates/biome_js_analyze/src/lint/complexity/no_useless_fragments.rs index 0bec9b298651..a238dc06d0e5 100644 --- a/crates/biome_js_analyze/src/lint/complexity/no_useless_fragments.rs +++ b/crates/biome_js_analyze/src/lint/complexity/no_useless_fragments.rs @@ -135,12 +135,11 @@ impl Rule for NoUselessFragments { if JsxExpressionAttributeValue::can_cast(parent.kind()) { in_jsx_attr_expr = true; } - if let Some(parenthesized_expression) = - JsParenthesizedExpression::cast_ref(&parent) - { - parenthesized_expression.syntax().parent() - } else { - Some(parent) + match JsParenthesizedExpression::try_cast(parent) { + Ok(parenthesized_expression) => { + parenthesized_expression.syntax().parent() + } + Err(parent) => Some(parent), } }) .map_or(false, |parent| { diff --git a/crates/biome_js_analyze/src/lint/complexity/use_flat_map.rs b/crates/biome_js_analyze/src/lint/complexity/use_flat_map.rs index 780e8098a55e..ea10e9f464a2 100644 --- a/crates/biome_js_analyze/src/lint/complexity/use_flat_map.rs +++ b/crates/biome_js_analyze/src/lint/complexity/use_flat_map.rs @@ -70,7 +70,7 @@ impl Rule for UseFlatMap { } } let flat_member_expression = - AnyJsMemberExpression::cast_ref(flat_call.callee().ok()?.syntax())?; + AnyJsMemberExpression::cast(flat_call.callee().ok()?.into_syntax())?; if flat_member_expression.member_name()?.text() == "flat" { let Ok(AnyJsExpression::JsCallExpression(map_call)) = flat_member_expression.object() else { @@ -78,7 +78,7 @@ impl Rule for UseFlatMap { }; let map_call_arguments = map_call.arguments().ok()?.args(); let map_member_expression = - AnyJsMemberExpression::cast_ref(map_call.callee().ok()?.syntax())?; + AnyJsMemberExpression::cast(map_call.callee().ok()?.into_syntax())?; if map_member_expression.member_name()?.text() == "map" && map_call_arguments.len() == 1 { return Some(map_call); diff --git a/crates/biome_js_analyze/src/lint/correctness/no_constant_condition.rs b/crates/biome_js_analyze/src/lint/correctness/no_constant_condition.rs index 1d8852df7137..3a0eb139b7ec 100644 --- a/crates/biome_js_analyze/src/lint/correctness/no_constant_condition.rs +++ b/crates/biome_js_analyze/src/lint/correctness/no_constant_condition.rs @@ -106,7 +106,7 @@ impl Rule for NoConstantCondition { // If the statement contains a valid yield expression returned from a `while`, `for`, or `do...while` statement, // we don't need to examine the statement's `test`. if let Some(any_js_stmt) = conditional_stmt.body() { - if conditional_stmt.is_in_generator_function().unwrap_or(false) + if conditional_stmt.is_in_generator_function() && has_valid_yield_expression(&any_js_stmt).unwrap_or(false) { return None; @@ -158,15 +158,15 @@ impl ConditionalStatement { } } // Checks if the self statement is in a generator function - fn is_in_generator_function(&self) -> Option { - self.syntax().ancestors().find_map(|node| { - if let Some(func_decl) = JsFunctionDeclaration::cast_ref(&node) { - return Some(func_decl.star_token().is_some()); - }; - if let Some(func_expr) = JsFunctionExpression::cast(node) { - return Some(func_expr.star_token().is_some()); - }; - None + fn is_in_generator_function(&self) -> bool { + self.syntax().ancestors().any(|node| { + match JsFunctionDeclaration::try_cast(node) { + Ok(func_decl) => func_decl.star_token(), + Err(node) => { + JsFunctionExpression::cast(node).and_then(|func_expr| func_expr.star_token()) + } + } + .is_some() }) } } diff --git a/crates/biome_js_analyze/src/lint/correctness/no_constant_math_min_max_clamp.rs b/crates/biome_js_analyze/src/lint/correctness/no_constant_math_min_max_clamp.rs index 96d08836cfb4..8daa8bdea18a 100644 --- a/crates/biome_js_analyze/src/lint/correctness/no_constant_math_min_max_clamp.rs +++ b/crates/biome_js_analyze/src/lint/correctness/no_constant_math_min_max_clamp.rs @@ -147,7 +147,7 @@ fn get_math_min_or_max_call( model: &SemanticModel, ) -> Option { let callee = call_expression.callee().ok()?.omit_parentheses(); - let member_expr = AnyJsMemberExpression::cast_ref(callee.syntax())?; + let member_expr = AnyJsMemberExpression::cast(callee.into_syntax())?; let member_name = member_expr.member_name()?; let member_name = member_name.text(); diff --git a/crates/biome_js_analyze/src/lint/correctness/no_flat_map_identity.rs b/crates/biome_js_analyze/src/lint/correctness/no_flat_map_identity.rs index 64e69d6e0db2..f969760f9537 100644 --- a/crates/biome_js_analyze/src/lint/correctness/no_flat_map_identity.rs +++ b/crates/biome_js_analyze/src/lint/correctness/no_flat_map_identity.rs @@ -55,7 +55,7 @@ impl Rule for NoFlatMapIdentity { let flat_map_call = ctx.query(); let flat_map_expression = - AnyJsMemberExpression::cast_ref(flat_map_call.callee().ok()?.syntax())?; + AnyJsMemberExpression::cast(flat_map_call.callee().ok()?.into_syntax())?; if flat_map_expression.object().is_err() { return None; diff --git a/crates/biome_js_analyze/src/lint/correctness/no_string_case_mismatch.rs b/crates/biome_js_analyze/src/lint/correctness/no_string_case_mismatch.rs index a7b120fe0e2d..74299e5e3d8f 100644 --- a/crates/biome_js_analyze/src/lint/correctness/no_string_case_mismatch.rs +++ b/crates/biome_js_analyze/src/lint/correctness/no_string_case_mismatch.rs @@ -184,7 +184,7 @@ impl StringCase { return None; } let callee = call.callee().ok()?; - let member_expr = AnyJsMemberExpression::cast_ref(callee.syntax())?; + let member_expr = AnyJsMemberExpression::cast(callee.into_syntax())?; let member_name = member_expr.member_name()?; let member_name = member_name.text(); if member_name == "toLowerCase" { diff --git a/crates/biome_js_analyze/src/lint/correctness/no_unused_private_class_members.rs b/crates/biome_js_analyze/src/lint/correctness/no_unused_private_class_members.rs index 7074bec44f4c..2c501cd8ffc4 100644 --- a/crates/biome_js_analyze/src/lint/correctness/no_unused_private_class_members.rs +++ b/crates/biome_js_analyze/src/lint/correctness/no_unused_private_class_members.rs @@ -265,22 +265,22 @@ impl AnyMember { AnyJsClassMember::JsGetterClassMember(member) => member .modifiers() .iter() - .filter_map(|x| TsAccessibilityModifier::cast_ref(x.syntax())) + .filter_map(|x| TsAccessibilityModifier::cast(x.into_syntax())) .any(|accessibility| accessibility.is_private()), AnyJsClassMember::JsMethodClassMember(member) => member .modifiers() .iter() - .filter_map(|x| TsAccessibilityModifier::cast_ref(x.syntax())) + .filter_map(|x| TsAccessibilityModifier::cast(x.into_syntax())) .any(|accessibility| accessibility.is_private()), AnyJsClassMember::JsPropertyClassMember(member) => member .modifiers() .iter() - .filter_map(|x| TsAccessibilityModifier::cast_ref(x.syntax())) + .filter_map(|x| TsAccessibilityModifier::cast(x.into_syntax())) .any(|accessibility| accessibility.is_private()), AnyJsClassMember::JsSetterClassMember(member) => member .modifiers() .iter() - .filter_map(|x| TsAccessibilityModifier::cast_ref(x.syntax())) + .filter_map(|x| TsAccessibilityModifier::cast(x.into_syntax())) .any(|accessibility| accessibility.is_private()), _ => false, }; @@ -291,7 +291,7 @@ impl AnyMember { param .modifiers() .iter() - .filter_map(|x| TsAccessibilityModifier::cast_ref(x.syntax())) + .filter_map(|x| TsAccessibilityModifier::cast(x.into_syntax())) .any(|accessibility| accessibility.is_private()), ), } diff --git a/crates/biome_js_analyze/src/lint/correctness/use_exhaustive_dependencies.rs b/crates/biome_js_analyze/src/lint/correctness/use_exhaustive_dependencies.rs index 7158a021c324..27439c8ebfaf 100644 --- a/crates/biome_js_analyze/src/lint/correctness/use_exhaustive_dependencies.rs +++ b/crates/biome_js_analyze/src/lint/correctness/use_exhaustive_dependencies.rs @@ -657,34 +657,35 @@ fn determine_unstable_dependency( } } -fn into_member_vec(node: &JsSyntaxNode) -> Vec { +fn into_member_iter(node: &JsSyntaxNode) -> impl Iterator { let mut vec = vec![]; let mut next = Some(node.clone()); - while let Some(node) = &next { - match AnyJsMemberExpression::cast_ref(node) { - Some(member_expr) => { + while let Some(node) = next { + match AnyJsMemberExpression::try_cast(node) { + Ok(member_expr) => { let member_name = member_expr .member_name() .and_then(|it| it.as_string_constant().map(|it| it.to_owned())); if let Some(member_name) = member_name { - vec.insert(0, member_name); + vec.push(member_name); } next = member_expr.object().ok().map(AstNode::into_syntax); } - None => { - vec.insert(0, node.text_trimmed().to_string()); + Err(node) => { + vec.push(node.text_trimmed().to_string()); break; } } } - vec + // elemnsts are inserted in reverse, thus we have to reverse the iteration. + vec.into_iter().rev() } fn compare_member_depth(a: &JsSyntaxNode, b: &JsSyntaxNode) -> (bool, bool) { - let mut a_member_iter = into_member_vec(a).into_iter(); - let mut b_member_iter = into_member_vec(b).into_iter(); + let mut a_member_iter = into_member_iter(a); + let mut b_member_iter = into_member_iter(b); loop { let a_member = a_member_iter.next(); diff --git a/crates/biome_js_analyze/src/lint/correctness/use_hook_at_top_level.rs b/crates/biome_js_analyze/src/lint/correctness/use_hook_at_top_level.rs index 35064246dab1..c1b9de38967b 100644 --- a/crates/biome_js_analyze/src/lint/correctness/use_hook_at_top_level.rs +++ b/crates/biome_js_analyze/src/lint/correctness/use_hook_at_top_level.rs @@ -115,17 +115,19 @@ fn enclosing_function_if_call_is_at_top_level( let mut prev_node = None; for node in call.syntax().ancestors() { - if let Some(enclosing_function) = AnyJsFunctionOrMethod::cast_ref(&node) { - return Some(enclosing_function); - } - - if let Some(prev_node) = prev_node { - if is_conditional_expression(&node, &prev_node) { - return None; + match AnyJsFunctionOrMethod::try_cast(node) { + Ok(enclosing_function) => { + return Some(enclosing_function); + } + Err(node) => { + if let Some(prev_node) = prev_node { + if is_conditional_expression(&node, &prev_node) { + return None; + } + } + prev_node = Some(node); } } - - prev_node = Some(node); } None diff --git a/crates/biome_js_analyze/src/lint/correctness/use_is_nan.rs b/crates/biome_js_analyze/src/lint/correctness/use_is_nan.rs index c6e43f4ab51c..a83043a65317 100644 --- a/crates/biome_js_analyze/src/lint/correctness/use_is_nan.rs +++ b/crates/biome_js_analyze/src/lint/correctness/use_is_nan.rs @@ -296,7 +296,7 @@ fn has_nan(expr: AnyJsExpression, model: &SemanticModel) -> bool { } reference } else { - let member_expr = AnyJsMemberExpression::cast_ref(expr.syntax())?; + let member_expr = AnyJsMemberExpression::cast(expr.into_syntax())?; if member_expr.member_name()?.text() != "NaN" { return None; } diff --git a/crates/biome_js_analyze/src/lint/correctness/use_jsx_key_in_iterable.rs b/crates/biome_js_analyze/src/lint/correctness/use_jsx_key_in_iterable.rs index e90f3810b66e..b33c447fe54d 100644 --- a/crates/biome_js_analyze/src/lint/correctness/use_jsx_key_in_iterable.rs +++ b/crates/biome_js_analyze/src/lint/correctness/use_jsx_key_in_iterable.rs @@ -257,7 +257,7 @@ fn handle_potential_react_component( } if is_inside_jsx { - if let Some(node) = ReactComponentExpression::cast_ref(node.syntax()) { + if let Some(node) = ReactComponentExpression::cast(node.into_syntax()) { let range = handle_react_component(node, model)?; Some(range) } else { @@ -265,7 +265,7 @@ fn handle_potential_react_component( } } else { let range = - handle_react_component(ReactComponentExpression::cast_ref(node.syntax())?, model)?; + handle_react_component(ReactComponentExpression::cast(node.into_syntax())?, model)?; Some(range) } } @@ -291,7 +291,7 @@ fn handle_react_component( /// ``` fn handle_jsx_tag(node: &JsxTagExpression, model: &SemanticModel) -> Option> { let tag = node.tag().ok()?; - let tag = AnyJsxChild::cast_ref(tag.syntax())?; + let tag = AnyJsxChild::cast(tag.into_syntax())?; handle_jsx_child(&tag, model) } diff --git a/crates/biome_js_analyze/src/lint/nursery/no_console.rs b/crates/biome_js_analyze/src/lint/nursery/no_console.rs index c46cb0ae8125..7c7de34c3356 100644 --- a/crates/biome_js_analyze/src/lint/nursery/no_console.rs +++ b/crates/biome_js_analyze/src/lint/nursery/no_console.rs @@ -40,7 +40,7 @@ impl Rule for NoConsole { let call_expression = ctx.query(); let model = ctx.model(); let callee = call_expression.callee().ok()?; - let member_expression = AnyJsMemberExpression::cast_ref(callee.syntax())?; + let member_expression = AnyJsMemberExpression::cast(callee.into_syntax())?; let object = member_expression.object().ok()?; let (reference, name) = global_identifier(&object)?; if name.text() != "console" { diff --git a/crates/biome_js_analyze/src/lint/nursery/no_label_without_control.rs b/crates/biome_js_analyze/src/lint/nursery/no_label_without_control.rs index 947dc42a86a4..0b49d791fd2f 100644 --- a/crates/biome_js_analyze/src/lint/nursery/no_label_without_control.rs +++ b/crates/biome_js_analyze/src/lint/nursery/no_label_without_control.rs @@ -212,24 +212,25 @@ fn has_for_attribute(jsx_tag: &AnyJsxTag) -> Option { /// Returns whether the passed `AnyJsxTag` have a child that is considered an input component /// according to the passed `input_components` parameter fn has_nested_control(jsx_tag: &AnyJsxTag, input_components: &[String]) -> bool { - jsx_tag.syntax().descendants().any(|descendant| { - match ( - JsxName::cast(descendant.clone()), - JsxReferenceIdentifier::cast(descendant.clone()), - ) { - (Some(jsx_name), _) => { + jsx_tag + .syntax() + .descendants() + .any(|descendant| match JsxName::try_cast(descendant) { + Ok(jsx_name) => { let attribute_name = jsx_name.text(); input_components.contains(&attribute_name) || DEFAULT_INPUT_COMPONENTS.contains(&attribute_name.as_str()) } - (_, Some(jsx_reference_identifier)) => { - let attribute_name = jsx_reference_identifier.text(); - input_components.contains(&attribute_name) - || DEFAULT_INPUT_COMPONENTS.contains(&attribute_name.as_str()) + Err(descendant) => { + if let Some(jsx_reference_identifier) = JsxReferenceIdentifier::cast(descendant) { + let attribute_name = jsx_reference_identifier.text(); + input_components.contains(&attribute_name) + || DEFAULT_INPUT_COMPONENTS.contains(&attribute_name.as_str()) + } else { + false + } } - _ => false, - } - }) + }) } /// Returns whether the passed `AnyJsxTag` meets one of the following conditions: @@ -241,7 +242,9 @@ fn has_accessible_label(jsx_tag: &AnyJsxTag, label_attributes: &[String]) -> boo let mut has_accessible_attribute = false; for descendant in jsx_tag.syntax().descendants() { - if let Some(jsx_attribute) = JsxAttribute::cast(descendant.clone()) { + has_text = has_text || JsxText::can_cast(descendant.kind()); + + if let Some(jsx_attribute) = JsxAttribute::cast(descendant) { if let (Some(jsx_name), Some(jsx_attribute_value)) = ( jsx_attribute.name().ok(), jsx_attribute @@ -259,10 +262,6 @@ fn has_accessible_label(jsx_tag: &AnyJsxTag, label_attributes: &[String]) -> boo } } } - - if JsxText::cast(descendant.clone()).is_some() { - has_text = true; - } } has_accessible_attribute || has_text diff --git a/crates/biome_js_analyze/src/lint/nursery/use_date_now.rs b/crates/biome_js_analyze/src/lint/nursery/use_date_now.rs index 10494a6d1447..f924f41d916a 100644 --- a/crates/biome_js_analyze/src/lint/nursery/use_date_now.rs +++ b/crates/biome_js_analyze/src/lint/nursery/use_date_now.rs @@ -195,8 +195,7 @@ fn get_new_date_issue(expr: &JsNewExpression) -> Option<(AnyJsExpression, UseDat return None; } - let parent = &get_parent_without_parenthesis(expr.syntax())?; - + let parent = get_parent_without_parenthesis(expr.syntax())?; match parent { AnyJsExpression::JsBinaryExpression(binary_expr) => { let operator = binary_expr.operator().ok()?; @@ -224,7 +223,7 @@ fn get_new_date_issue(expr: &JsNewExpression) -> Option<(AnyJsExpression, UseDat | JsAssignmentOperator::RemainderAssign | JsAssignmentOperator::ExponentAssign ) { - let any_expr = AnyJsExpression::cast_ref(expr.right().ok()?.syntax())?; + let any_expr = AnyJsExpression::cast(expr.right().ok()?.into_syntax())?; return Some((any_expr, UseDateNowIssueKind::ReplaceConstructor)); } @@ -235,13 +234,13 @@ fn get_new_date_issue(expr: &JsNewExpression) -> Option<(AnyJsExpression, UseDat let operator = unary_expr.operator().ok()?; let syntax = match operator { - JsUnaryOperator::Plus => unary_expr.syntax(), - JsUnaryOperator::Minus => expr.syntax(), + JsUnaryOperator::Plus => unary_expr.into_syntax(), + JsUnaryOperator::Minus => expr.syntax().clone(), _ => return None, }; Some(( - AnyJsExpression::cast_ref(syntax)?, + AnyJsExpression::cast(syntax)?, UseDateNowIssueKind::ReplaceConstructor, )) } @@ -259,7 +258,7 @@ fn get_new_date_issue(expr: &JsNewExpression) -> Option<(AnyJsExpression, UseDat if call_name == "Number" || call_name == "BigInt" { return Some(( - AnyJsExpression::cast_ref(call_expr.syntax())?, + AnyJsExpression::cast(call_expr.into_syntax())?, UseDateNowIssueKind::ReplaceNumberConstructor, )); } diff --git a/crates/biome_js_analyze/src/lint/nursery/use_top_level_regex.rs b/crates/biome_js_analyze/src/lint/nursery/use_top_level_regex.rs index 7794e52bbb97..fed517ffc41a 100644 --- a/crates/biome_js_analyze/src/lint/nursery/use_top_level_regex.rs +++ b/crates/biome_js_analyze/src/lint/nursery/use_top_level_regex.rs @@ -64,23 +64,30 @@ impl Rule for UseTopLevelRegex { if flags.contains('g') || flags.contains('y') { return None; } - let found_all_allowed = regex.syntax().ancestors().all(|node| { - if let Some(node) = AnyJsControlFlowRoot::cast_ref(&node) { - matches!( - node, - AnyJsControlFlowRoot::JsStaticInitializationBlockClassMember(_) - | AnyJsControlFlowRoot::TsModuleDeclaration(_) - | AnyJsControlFlowRoot::JsModule(_) - | AnyJsControlFlowRoot::JsScript(_) - ) - } else if let Some(node) = JsPropertyClassMember::cast_ref(&node) { - node.modifiers() - .iter() - .any(|modifier| matches!(modifier, AnyJsPropertyModifier::JsStaticModifier(_))) - } else { - true - } - }); + let found_all_allowed = + regex + .syntax() + .ancestors() + .all(|node| match AnyJsControlFlowRoot::try_cast(node) { + Ok(node) => { + matches!( + node, + AnyJsControlFlowRoot::JsStaticInitializationBlockClassMember(_) + | AnyJsControlFlowRoot::TsModuleDeclaration(_) + | AnyJsControlFlowRoot::JsModule(_) + | AnyJsControlFlowRoot::JsScript(_) + ) + } + Err(node) => { + if let Some(node) = JsPropertyClassMember::cast(node) { + node.modifiers().iter().any(|modifier| { + matches!(modifier, AnyJsPropertyModifier::JsStaticModifier(_)) + }) + } else { + true + } + } + }); if found_all_allowed { None } else { diff --git a/crates/biome_js_analyze/src/lint/performance/no_accumulating_spread.rs b/crates/biome_js_analyze/src/lint/performance/no_accumulating_spread.rs index 8430c5c246c0..4005136b9abd 100644 --- a/crates/biome_js_analyze/src/lint/performance/no_accumulating_spread.rs +++ b/crates/biome_js_analyze/src/lint/performance/no_accumulating_spread.rs @@ -127,7 +127,7 @@ fn is_known_accumulator(node: &JsSpread, model: &SemanticModel) -> Option } let callee = call_expression.callee().ok()?; - let member_expression = AnyJsMemberExpression::cast_ref(callee.syntax())?; + let member_expression = AnyJsMemberExpression::cast(callee.into_syntax())?; // We only care about `.reduce` and `.reduceRight`. let member_name = member_expression.member_name()?; diff --git a/crates/biome_js_analyze/src/lint/performance/no_barrel_file.rs b/crates/biome_js_analyze/src/lint/performance/no_barrel_file.rs index f0817ae859ab..367515ba63ed 100644 --- a/crates/biome_js_analyze/src/lint/performance/no_barrel_file.rs +++ b/crates/biome_js_analyze/src/lint/performance/no_barrel_file.rs @@ -67,11 +67,11 @@ impl Rule for NoBarrelFile { } let items = ctx.query().items(); - for i in items { - if let Some(export) = JsExport::cast(i.into()) { + for item in items { + if let Some(export) = JsExport::cast(item.into()) { if let Ok(export_from_clause) = export.export_clause() { if let Some(export_from_clause) = - JsExportFromClause::cast(export_from_clause.clone().into()) + JsExportFromClause::cast_ref(export_from_clause.syntax()) { if export_from_clause.type_token().is_none() { return Some(export); @@ -79,7 +79,7 @@ impl Rule for NoBarrelFile { } if let Some(export_from_clause) = - JsExportNamedFromClause::cast(export_from_clause.into()) + JsExportNamedFromClause::cast(export_from_clause.into_syntax()) { if export_from_clause.type_token().is_some() { continue; diff --git a/crates/biome_js_analyze/src/lint/style/use_exponentiation_operator.rs b/crates/biome_js_analyze/src/lint/style/use_exponentiation_operator.rs index 94ce2b27b542..b1716434aecf 100644 --- a/crates/biome_js_analyze/src/lint/style/use_exponentiation_operator.rs +++ b/crates/biome_js_analyze/src/lint/style/use_exponentiation_operator.rs @@ -72,7 +72,7 @@ impl Rule for UseExponentiationOperator { let node = ctx.query(); let model = ctx.model(); let callee = node.callee().ok()?.omit_parentheses(); - let member_expr = AnyJsMemberExpression::cast_ref(callee.syntax())?; + let member_expr = AnyJsMemberExpression::cast(callee.into_syntax())?; if member_expr.member_name()?.text() != "pow" { return None; } diff --git a/crates/biome_js_analyze/src/lint/style/use_numeric_literals.rs b/crates/biome_js_analyze/src/lint/style/use_numeric_literals.rs index 242ee29b86d7..338d10ac2cdf 100644 --- a/crates/biome_js_analyze/src/lint/style/use_numeric_literals.rs +++ b/crates/biome_js_analyze/src/lint/style/use_numeric_literals.rs @@ -168,7 +168,7 @@ fn get_callee(expr: &JsCallExpression, model: &SemanticModel) -> Option<&'static } return None; } - let callee = AnyJsMemberExpression::cast_ref(callee.syntax())?; + let callee = AnyJsMemberExpression::cast(callee.into_syntax())?; if callee.member_name()?.text() != "parseInt" { return None; } diff --git a/crates/biome_js_analyze/src/lint/style/use_shorthand_assign.rs b/crates/biome_js_analyze/src/lint/style/use_shorthand_assign.rs index 27651435b112..f9a8b6b09361 100644 --- a/crates/biome_js_analyze/src/lint/style/use_shorthand_assign.rs +++ b/crates/biome_js_analyze/src/lint/style/use_shorthand_assign.rs @@ -90,7 +90,7 @@ impl Rule for UseShorthandAssign { let binary_expression = match right { AnyJsExpression::JsBinaryExpression(binary_expression) => binary_expression, AnyJsExpression::JsParenthesizedExpression(param) => { - JsBinaryExpression::cast_ref(param.expression().ok()?.syntax())? + JsBinaryExpression::cast(param.expression().ok()?.into_syntax())? } _ => return None, }; diff --git a/crates/biome_js_analyze/src/lint/suspicious/no_array_index_key.rs b/crates/biome_js_analyze/src/lint/suspicious/no_array_index_key.rs index 9743aab2ed36..50ba7d130b82 100644 --- a/crates/biome_js_analyze/src/lint/suspicious/no_array_index_key.rs +++ b/crates/biome_js_analyze/src/lint/suspicious/no_array_index_key.rs @@ -263,7 +263,7 @@ fn is_array_method_index( call_expression: &JsCallExpression, ) -> Option { let member_expression = - AnyJsMemberExpression::cast_ref(call_expression.callee().ok()?.syntax())?; + AnyJsMemberExpression::cast(call_expression.callee().ok()?.into_syntax())?; let name = member_expression.member_name()?; let name = name.text(); if matches!( diff --git a/crates/biome_js_analyze/src/lint/suspicious/no_console_log.rs b/crates/biome_js_analyze/src/lint/suspicious/no_console_log.rs index 7b483b7c74ed..39c8a32435ed 100644 --- a/crates/biome_js_analyze/src/lint/suspicious/no_console_log.rs +++ b/crates/biome_js_analyze/src/lint/suspicious/no_console_log.rs @@ -53,7 +53,7 @@ impl Rule for NoConsoleLog { let call_expression = ctx.query(); let model = ctx.model(); let callee = call_expression.callee().ok()?; - let member_expression = AnyJsMemberExpression::cast_ref(callee.syntax())?; + let member_expression = AnyJsMemberExpression::cast(callee.into_syntax())?; if member_expression.member_name()?.text() != "log" { return None; } diff --git a/crates/biome_js_analyze/src/lint/suspicious/no_control_characters_in_regex.rs b/crates/biome_js_analyze/src/lint/suspicious/no_control_characters_in_regex.rs index 98e59a2bffc4..5714eef3e779 100644 --- a/crates/biome_js_analyze/src/lint/suspicious/no_control_characters_in_regex.rs +++ b/crates/biome_js_analyze/src/lint/suspicious/no_control_characters_in_regex.rs @@ -182,7 +182,7 @@ fn collect_control_characters_from_expression( let raw_pattern = args .next() .and_then(|arg| arg.ok()) - .and_then(|arg| JsStringLiteralExpression::cast_ref(arg.syntax())) + .and_then(|arg| JsStringLiteralExpression::cast(arg.into_syntax())) .and_then(|js_string_literal| js_string_literal.inner_string_text().ok())? .to_string(); @@ -191,7 +191,7 @@ fn collect_control_characters_from_expression( let regexp_flags = args .next() .and_then(|arg| arg.ok()) - .and_then(|arg| JsStringLiteralExpression::cast_ref(arg.syntax())) + .and_then(|arg| JsStringLiteralExpression::cast(arg.into_syntax())) .map(|js_string_literal| js_string_literal.text()) .unwrap_or_default(); diff --git a/crates/biome_js_analyze/src/lint/suspicious/no_duplicate_class_members.rs b/crates/biome_js_analyze/src/lint/suspicious/no_duplicate_class_members.rs index 46fa794afb00..398c42ef346e 100644 --- a/crates/biome_js_analyze/src/lint/suspicious/no_duplicate_class_members.rs +++ b/crates/biome_js_analyze/src/lint/suspicious/no_duplicate_class_members.rs @@ -189,20 +189,20 @@ impl Rule for NoDuplicateClassMembers { let node = ctx.query(); node.into_iter() .filter_map(|member| { - let member_definition = AnyClassMemberDefinition::cast_ref(member.syntax())?; - let member_name_node = member_definition.name()?; + let member = AnyClassMemberDefinition::cast(member.into_syntax())?; + let member_name_node = member.name()?; let member_state = MemberState { name: get_member_name(&member_name_node)?.to_string(), - is_static: is_static_member(member_definition.modifiers_list()), + is_static: is_static_member(member.modifiers_list()), }; - let member_type = member_definition.member_type(); + let member_type = member.member_type(); if let Some(stored_members) = defined_members.get_mut(&member_state) { if stored_members.contains(&MemberType::Normal) || stored_members.contains(&member_type) || member_type == MemberType::Normal { - return Some(member_definition); + return Some(member); } else { stored_members.insert(member_type); } diff --git a/crates/biome_js_analyze/src/lint/suspicious/no_import_assign.rs b/crates/biome_js_analyze/src/lint/suspicious/no_import_assign.rs index bf3db96cc6ed..0b7239be08e4 100644 --- a/crates/biome_js_analyze/src/lint/suspicious/no_import_assign.rs +++ b/crates/biome_js_analyze/src/lint/suspicious/no_import_assign.rs @@ -95,7 +95,7 @@ impl Rule for NoImportAssign { let model = ctx.model(); for reference in ident_binding.all_writes(model) { invalid_assign_list.push(( - JsIdentifierAssignment::cast(reference.syntax().clone())?, + JsIdentifierAssignment::cast_ref(reference.syntax())?, ident_binding.clone(), )); } diff --git a/crates/biome_js_analyze/src/lint/suspicious/no_misleading_character_class.rs b/crates/biome_js_analyze/src/lint/suspicious/no_misleading_character_class.rs index a7dd98a232ce..5eed91bf9905 100644 --- a/crates/biome_js_analyze/src/lint/suspicious/no_misleading_character_class.rs +++ b/crates/biome_js_analyze/src/lint/suspicious/no_misleading_character_class.rs @@ -131,7 +131,7 @@ impl Rule for NoMisleadingCharacterClass { let raw_regex_pattern = args .next() .and_then(|arg| arg.ok()) - .and_then(|arg| JsStringLiteralExpression::cast_ref(arg.syntax())) + .and_then(|arg| JsStringLiteralExpression::cast(arg.into_syntax())) .and_then(|js_string_literal| js_string_literal.inner_string_text().ok())? .to_string(); @@ -139,7 +139,7 @@ impl Rule for NoMisleadingCharacterClass { let regexp_flags = args .next() .and_then(|arg| arg.ok()) - .and_then(|arg| JsStringLiteralExpression::cast_ref(arg.syntax())) + .and_then(|arg| JsStringLiteralExpression::cast(arg.into_syntax())) .map(|js_string_literal| js_string_literal.text()) .unwrap_or_default(); @@ -157,7 +157,7 @@ impl Rule for NoMisleadingCharacterClass { let raw_regex_pattern = args .next() .and_then(|arg| arg.ok()) - .and_then(|arg| JsStringLiteralExpression::cast_ref(arg.syntax())) + .and_then(|arg| JsStringLiteralExpression::cast(arg.into_syntax())) .and_then(|js_string_literal| js_string_literal.inner_string_text().ok())? .to_string(); @@ -166,7 +166,7 @@ impl Rule for NoMisleadingCharacterClass { let regexp_flags = args .next() .and_then(|arg| arg.ok()) - .and_then(|arg| JsStringLiteralExpression::cast_ref(arg.syntax())) + .and_then(|arg| JsStringLiteralExpression::cast(arg.into_syntax())) .map(|js_string_literal| js_string_literal.text()) .unwrap_or_default(); diff --git a/crates/biome_js_analyze/src/lint/suspicious/no_misrefactored_shorthand_assign.rs b/crates/biome_js_analyze/src/lint/suspicious/no_misrefactored_shorthand_assign.rs index 6eb8ff2afbcb..e1e85c1dcb7f 100644 --- a/crates/biome_js_analyze/src/lint/suspicious/no_misrefactored_shorthand_assign.rs +++ b/crates/biome_js_analyze/src/lint/suspicious/no_misrefactored_shorthand_assign.rs @@ -79,7 +79,7 @@ impl Rule for NoMisrefactoredShorthandAssign { let binary_expression = match right { AnyJsExpression::JsBinaryExpression(binary_expression) => binary_expression, AnyJsExpression::JsParenthesizedExpression(param) => { - JsBinaryExpression::cast_ref(param.expression().ok()?.syntax())? + JsBinaryExpression::cast(param.expression().ok()?.into_syntax())? } _ => return None, }; diff --git a/crates/biome_js_analyze/src/lint/suspicious/no_prototype_builtins.rs b/crates/biome_js_analyze/src/lint/suspicious/no_prototype_builtins.rs index 07bf8863ac9a..f7b0a3ce8be9 100644 --- a/crates/biome_js_analyze/src/lint/suspicious/no_prototype_builtins.rs +++ b/crates/biome_js_analyze/src/lint/suspicious/no_prototype_builtins.rs @@ -64,7 +64,7 @@ impl Rule for NoPrototypeBuiltins { fn run(ctx: &RuleContext) -> Self::Signals { let call_expr = ctx.query(); let callee = call_expr.callee().ok()?.omit_parentheses(); - if let Some(member_expr) = AnyJsMemberExpression::cast_ref(callee.syntax()) { + if let Some(member_expr) = AnyJsMemberExpression::cast(callee.into_syntax()) { let member_name = member_expr.member_name()?; let member_name_text = member_name.text(); return is_prototype_builtins(member_name_text).then_some(RuleState { diff --git a/crates/biome_js_analyze/src/lint/suspicious/no_redundant_use_strict.rs b/crates/biome_js_analyze/src/lint/suspicious/no_redundant_use_strict.rs index 0e759d94fd96..089d8fe6ad35 100644 --- a/crates/biome_js_analyze/src/lint/suspicious/no_redundant_use_strict.rs +++ b/crates/biome_js_analyze/src/lint/suspicious/no_redundant_use_strict.rs @@ -118,16 +118,21 @@ impl Rule for NoRedundantUseStrict { biome_js_syntax::AnyJsRoot::JsModule(js_module) => outer_most = Some(js_module.into()), _ => { for n in node.syntax().ancestors() { - if let Some(parent) = AnyNodeWithDirectives::cast_ref(&n) { - for directive in parent.directives() { - let directive_text = directive.inner_string_text().ok()?; - if directive_text == "use strict" { - outer_most = Some(directive.into()); - break; // continue with next parent + match AnyNodeWithDirectives::try_cast(n) { + Ok(parent) => { + for directive in parent.directives() { + let directive_text = directive.inner_string_text().ok()?; + if directive_text == "use strict" { + outer_most = Some(directive.into()); + break; // continue with next parent + } + } + } + Err(n) => { + if let Some(module_or_class) = AnyJsClass::cast(n) { + outer_most = Some(module_or_class.into()); } } - } else if let Some(module_or_class) = AnyJsClass::cast_ref(&n) { - outer_most = Some(module_or_class.into()); } } } diff --git a/crates/biome_js_analyze/src/lint/suspicious/use_getter_return.rs b/crates/biome_js_analyze/src/lint/suspicious/use_getter_return.rs index 65e3cbc064b3..2fc5fcdea990 100644 --- a/crates/biome_js_analyze/src/lint/suspicious/use_getter_return.rs +++ b/crates/biome_js_analyze/src/lint/suspicious/use_getter_return.rs @@ -113,8 +113,8 @@ impl Rule for UseGetterReturn { } } InstructionKind::Return => { - if let Some(NodeOrToken::Node(ref node)) = instruction.node { - if let Some(ref return_stmt) = JsReturnStatement::cast_ref(node) { + if let Some(NodeOrToken::Node(node)) = &instruction.node { + if let Some(return_stmt) = JsReturnStatement::cast_ref(node) { if return_stmt.argument().is_none() { invalid_returns.push(InvalidGetterReturn::EmptyReturn( return_stmt.range(), diff --git a/crates/biome_js_analyze/src/react/hooks.rs b/crates/biome_js_analyze/src/react/hooks.rs index 1bf1e38a3de6..513825d92515 100644 --- a/crates/biome_js_analyze/src/react/hooks.rs +++ b/crates/biome_js_analyze/src/react/hooks.rs @@ -501,8 +501,7 @@ mod test { .filter(|x| x.text_trimmed() == "useRef()") .last() .unwrap(); - let call = JsCallExpression::cast_ref(&node).unwrap(); - assert!(is_react_hook_call(&call)); + assert!(is_react_hook_call(&JsCallExpression::unwrap_cast(node))); } { diff --git a/crates/biome_js_analyze/src/syntax/correctness/no_super_without_extends.rs b/crates/biome_js_analyze/src/syntax/correctness/no_super_without_extends.rs index cace30e7182f..15efd82428b5 100644 --- a/crates/biome_js_analyze/src/syntax/correctness/no_super_without_extends.rs +++ b/crates/biome_js_analyze/src/syntax/correctness/no_super_without_extends.rs @@ -33,19 +33,23 @@ impl Rule for NoSuperWithoutExtends { let node = ctx.query(); for syntax in node.syntax().ancestors() { - // ancestor is class declaration - if let Some(class_declaration) = JsClassDeclaration::cast_ref(&syntax) { - if class_declaration.extends_clause().is_none() { - return Some(()); + match JsClassDeclaration::try_cast(syntax) { + Ok(class_declaration) => { + // ancestor is class declaration + if class_declaration.extends_clause().is_none() { + return Some(()); + } + return None; } - return None; - } - // ancestor is class expression - else if let Some(class_expression) = JsClassExpression::cast_ref(&syntax) { - if class_expression.extends_clause().is_none() { - return Some(()); + Err(syntax) => { + // ancestor is class expression + if let Some(class_expression) = JsClassExpression::cast(syntax) { + if class_expression.extends_clause().is_none() { + return Some(()); + } + return None; + } } - return None; } } diff --git a/crates/biome_js_formatter/src/js/expressions/arrow_function_expression.rs b/crates/biome_js_formatter/src/js/expressions/arrow_function_expression.rs index 1aaa58835c50..5fe698c9b770 100644 --- a/crates/biome_js_formatter/src/js/expressions/arrow_function_expression.rs +++ b/crates/biome_js_formatter/src/js/expressions/arrow_function_expression.rs @@ -420,7 +420,7 @@ pub fn can_avoid_parentheses(arrow: &JsArrowFunctionExpression, f: &mut JsFormat && !parameters .as_js_parameters() .and_then(|p| p.items().first()?.ok()) - .and_then(|p| JsFormalParameter::cast(p.syntax().clone())) + .and_then(|p| JsFormalParameter::cast(p.into_syntax())) .is_some_and(|p| { f.context().comments().has_comments(p.syntax()) || p.initializer().is_some() diff --git a/crates/biome_js_formatter/src/parentheses.rs b/crates/biome_js_formatter/src/parentheses.rs index 89f4c0dabacb..41b3d93a91a4 100644 --- a/crates/biome_js_formatter/src/parentheses.rs +++ b/crates/biome_js_formatter/src/parentheses.rs @@ -346,7 +346,7 @@ pub(crate) fn get_expression_left_side( }) } expression => { - return AnyJsBinaryLikeExpression::cast(expression.syntax().clone()).and_then( + return AnyJsBinaryLikeExpression::cast_ref(expression.syntax()).and_then( |binary_like| match binary_like.left().ok() { Some(AnyJsBinaryLikeLeftExpression::AnyJsExpression(expression)) => { Some(AnyJsExpressionLeftSide::from(expression)) diff --git a/crates/biome_js_formatter/src/utils/assignment_like.rs b/crates/biome_js_formatter/src/utils/assignment_like.rs index 9f96520c5e88..0177d298eecc 100644 --- a/crates/biome_js_formatter/src/utils/assignment_like.rs +++ b/crates/biome_js_formatter/src/utils/assignment_like.rs @@ -933,7 +933,7 @@ impl AnyJsAssignmentLike { let mut has_leading_comments = comments.has_leading_comments(union_type.syntax()); while is_nested_union_type(&union_type)? && !has_leading_comments { if let Some(Ok(inner_union_type)) = union_type.types().last() { - let inner_union_type = TsUnionType::cast_ref(inner_union_type.syntax()); + let inner_union_type = TsUnionType::cast(inner_union_type.into_syntax()); if let Some(inner_union_type) = inner_union_type { has_leading_comments = comments.has_leading_comments(inner_union_type.syntax()); diff --git a/crates/biome_js_syntax/src/jsx_ext.rs b/crates/biome_js_syntax/src/jsx_ext.rs index 6ceea176fb29..c19649637751 100644 --- a/crates/biome_js_syntax/src/jsx_ext.rs +++ b/crates/biome_js_syntax/src/jsx_ext.rs @@ -282,9 +282,9 @@ impl JsxAttributeList { pub fn find_by_name(&self, name_to_lookup: &str) -> SyntaxResult> { let attribute = self.iter().find_map(|attribute| { - let attribute = JsxAttribute::cast_ref(attribute.syntax())?; + let attribute = JsxAttribute::cast(attribute.into_syntax())?; let name = attribute.name().ok()?; - let name = JsxName::cast_ref(name.syntax())?; + let name = JsxName::cast(name.into_syntax())?; if name.value_token().ok()?.text_trimmed() == name_to_lookup { Some(attribute) } else { @@ -454,7 +454,7 @@ impl AnyJsxChild { } AnyJsxChild::JsxElement(element) => { let opening_element = element.opening_element().ok()?; - let jsx_element = AnyJsxElement::cast(opening_element.syntax().clone())?; + let jsx_element = AnyJsxElement::cast(opening_element.into_syntax())?; // We don't check if a component (e.g. ) is using the `aria-hidden` property, // since we don't have enough information about how the property is used. @@ -462,7 +462,7 @@ impl AnyJsxChild { || !jsx_element.has_truthy_attribute("aria-hidden") } AnyJsxChild::JsxSelfClosingElement(element) => { - let jsx_element = AnyJsxElement::cast(element.syntax().clone())?; + let jsx_element = AnyJsxElement::unwrap_cast(element.syntax().clone()); jsx_element.is_custom_component() || !jsx_element.has_truthy_attribute("aria-hidden") } diff --git a/crates/biome_rowan/src/ast/mod.rs b/crates/biome_rowan/src/ast/mod.rs index 2ffdf2fe745a..4e6a57e7aca9 100644 --- a/crates/biome_rowan/src/ast/mod.rs +++ b/crates/biome_rowan/src/ast/mod.rs @@ -169,7 +169,7 @@ pub trait AstNode: Clone { /// builder.finish_node(); /// /// let root_syntax = builder.finish(); - /// let root = RawLanguageRoot::cast(root_syntax.clone()).expect("Root to be a raw language root"); + /// let root = RawLanguageRoot::cast_ref(&root_syntax).expect("Root to be a raw language root"); /// /// // Returns `OK` because syntax is a `RawLanguageRoot` /// assert_eq!(RawLanguageRoot::try_cast(root.syntax().clone()), Ok(root.clone())); @@ -178,7 +178,7 @@ pub trait AstNode: Clone { /// ``` fn try_cast(syntax: SyntaxNode) -> Result> { if Self::can_cast(syntax.kind()) { - Ok(Self::cast(syntax).expect("Expected casted node because 'can_cast' returned true.")) + Ok(Self::unwrap_cast(syntax)) } else { Err(syntax) } @@ -202,7 +202,7 @@ pub trait AstNode: Clone { /// builder.finish_node(); /// /// let root_syntax = builder.finish(); - /// let root = RawLanguageRoot::cast(root_syntax.clone()).expect("Root to be a raw language root"); + /// let root = RawLanguageRoot::cast_ref(&root_syntax).expect("Root to be a raw language root"); /// /// // Returns `OK` because syntax is a `RawLanguageRoot` /// assert_eq!(RawLanguageRoot::try_cast_node(root.clone()), Ok(root.clone())); @@ -212,8 +212,7 @@ pub trait AstNode: Clone { /// ``` fn try_cast_node>(node: T) -> Result { if Self::can_cast(node.syntax().kind()) { - Ok(Self::cast(node.into_syntax()) - .expect("Expected casted node because 'can_cast' returned true.")) + Ok(Self::unwrap_cast(node.into_syntax())) } else { Err(node) } diff --git a/xtask/codegen/src/generate_nodes.rs b/xtask/codegen/src/generate_nodes.rs index 29b1cc57dc90..100039bdb611 100644 --- a/xtask/codegen/src/generate_nodes.rs +++ b/xtask/codegen/src/generate_nodes.rs @@ -416,12 +416,15 @@ pub fn generate_nodes(ast: &AstSrc, language_kind: LanguageKind) -> Result { return Some(#name::#variant_name(#variable_name)); - }} + } + Err(syntax) => syntax, + };} } else { // if this is the last variant, do not clone syntax quote! {