repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/correctness/no_const_assign.rs | crates/rome_js_analyze/src/semantic_analyzers/correctness/no_const_assign.rs | use crate::semantic_services::Semantic;
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{
AnyJsArrayBindingPatternElement, AnyJsObjectBindingPatternMember,
JsArrayBindingPatternElementList, JsForVariableDeclaration, JsIdentifierAssignment,
JsIdentifierBinding, JsObjectBindingPatternPropertyList, JsVariableDeclaration,
JsVariableDeclarator, JsVariableDeclaratorList,
};
use rome_rowan::{AstNode, TextRange};
declare_rule! {
/// Prevents from having `const` variables being re-assigned.
///
/// Trying to assign a value to a `const` will cause an `TypeError` when the code is executed.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// const a = 1;
/// a = 4;
/// ```
///
/// ```js,expect_diagnostic
/// const a = 2;
/// a += 1;
/// ```
///
/// ```js,expect_diagnostic
/// const a = 1;
/// ++a;
/// ```
///
/// ```js,expect_diagnostic
/// const a = 1, b = 2;
///
/// a = 2;
/// ```
///
/// ### Valid
///
/// ```js
/// const a = 10;
/// let b = 10;
/// b = 20;
/// ```
///
pub(crate) NoConstAssign {
version: "10.0.0",
name: "noConstAssign",
recommended: true,
}
}
impl Rule for NoConstAssign {
type Query = Semantic<JsIdentifierAssignment>;
type State = TextRange;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let model = ctx.model();
let declared_binding = model.binding(node)?;
if let Some(possible_declarator) = declared_binding.syntax().ancestors().find(|node| {
!AnyJsObjectBindingPatternMember::can_cast(node.kind())
&& !JsObjectBindingPatternPropertyList::can_cast(node.kind())
&& !AnyJsArrayBindingPatternElement::can_cast(node.kind())
&& !JsArrayBindingPatternElementList::can_cast(node.kind())
&& !JsIdentifierBinding::can_cast(node.kind())
}) {
if JsVariableDeclarator::can_cast(possible_declarator.kind()) {
let possible_declaration = possible_declarator.parent()?;
if let Some(js_for_variable_declaration) =
JsForVariableDeclaration::cast_ref(&possible_declaration)
{
if js_for_variable_declaration.is_const() {
return Some(declared_binding.syntax().text_trimmed_range());
}
} else if let Some(js_variable_declaration) =
JsVariableDeclaratorList::cast_ref(&possible_declaration)
.and_then(|declaration| declaration.syntax().parent())
.and_then(JsVariableDeclaration::cast)
{
if js_variable_declaration.is_const() {
return Some(declared_binding.syntax().text_trimmed_range());
}
}
}
}
None
}
fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
let name = node.name_token().ok()?;
let name = name.text_trimmed();
Some(
RuleDiagnostic::new(
rule_category!(),
node.syntax().text_trimmed_range(),
markup! {"Can't assign "<Emphasis>{name}</Emphasis>" because it's a constant"},
)
.detail(
state,
markup! {"This is where the variable is defined as constant"},
),
)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/correctness/no_void_elements_with_children.rs | crates/rome_js_analyze/src/semantic_analyzers/correctness/no_void_elements_with_children.rs | use crate::react::{ReactApiCall, ReactCreateElementCall};
use crate::semantic_services::Semantic;
use crate::JsRuleAction;
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, ActionCategory, Rule, RuleDiagnostic};
use rome_console::{markup, MarkupBuf};
use rome_diagnostics::Applicability;
use rome_js_factory::make::{jsx_attribute_list, jsx_self_closing_element};
use rome_js_syntax::{
AnyJsxAttribute, JsCallExpression, JsPropertyObjectMember, JsxAttribute, JsxElement,
JsxSelfClosingElement,
};
use rome_rowan::{declare_node_union, AstNode, AstNodeList, BatchMutationExt};
declare_rule! {
/// This rules prevents void elements (AKA self-closing elements) from having children.
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// <br>invalid child</br>
/// ```
///
/// ```jsx,expect_diagnostic
/// <img alt="some text" children={"some child"} />
/// ```
///
/// ```js,expect_diagnostic
/// React.createElement('img', {}, 'child')
/// ```
pub(crate) NoVoidElementsWithChildren {
version: "0.10.0",
name: "noVoidElementsWithChildren",
recommended: true,
}
}
declare_node_union! {
pub(crate) NoVoidElementsWithChildrenQuery = JsxElement | JsCallExpression | JsxSelfClosingElement
}
/// Returns true if the name of the element belong to a self-closing element
fn is_void_dom_element(element_name: &str) -> bool {
matches!(
element_name,
"area"
| "base"
| "br"
| "col"
| "embed"
| "hr"
| "img"
| "input"
| "keygen"
| "link"
| "menuitem"
| "meta"
| "param"
| "source"
| "track"
| "wbr"
)
}
pub(crate) enum NoVoidElementsWithChildrenCause {
/// The cause affects React using JSX code
Jsx {
/// If the current element has children props in style
///
/// ```jsx
/// <img>
/// Some child
/// </img>
/// ```
children_cause: bool,
/// If the current element has the prop `dangerouslySetInnerHTML`
dangerous_prop_cause: Option<JsxAttribute>,
/// If the current element has the prop `children`
children_prop: Option<JsxAttribute>,
},
/// The cause affects React using `React` object APIs
ReactCreateElement {
/// If the current element has children props in style:
///
/// ```js
/// React.createElement('img', {}, 'child')
/// ```
children_cause: bool,
/// If the current element has the prop `dangerouslySetInnerHTML`
dangerous_prop_cause: Option<JsPropertyObjectMember>,
/// If the current element has the prop `children`
children_prop: Option<JsPropertyObjectMember>,
/// An instance of [ReactCreateElementCall]
react_create_element: ReactCreateElementCall,
},
}
pub(crate) struct NoVoidElementsWithChildrenState {
/// The name of the element that triggered the rule
element_name: String,
/// It tracks the causes that triggers the rule
cause: NoVoidElementsWithChildrenCause,
}
impl NoVoidElementsWithChildrenState {
fn new(element_name: impl Into<String>, cause: NoVoidElementsWithChildrenCause) -> Self {
Self {
element_name: element_name.into(),
cause,
}
}
fn has_children_cause(&self) -> bool {
match &self.cause {
NoVoidElementsWithChildrenCause::Jsx {
children_prop,
children_cause,
..
} => *children_cause || children_prop.is_some(),
NoVoidElementsWithChildrenCause::ReactCreateElement {
children_prop,
children_cause,
..
} => *children_cause || children_prop.is_some(),
}
}
fn has_dangerous_prop_cause(&self) -> bool {
match &self.cause {
NoVoidElementsWithChildrenCause::Jsx {
dangerous_prop_cause,
..
} => dangerous_prop_cause.is_some(),
NoVoidElementsWithChildrenCause::ReactCreateElement {
dangerous_prop_cause,
..
} => dangerous_prop_cause.is_some(),
}
}
fn diagnostic_message(&self) -> MarkupBuf {
let has_children_cause = self.has_children_cause();
let has_dangerous_cause = self.has_dangerous_prop_cause();
match (has_children_cause, has_dangerous_cause) {
(true, true) => {
(markup! {
<Emphasis>{self.element_name}</Emphasis>" is a void element tag and must not have "<Emphasis>"children"</Emphasis>
", or the "<Emphasis>"dangerouslySetInnerHTML"</Emphasis>" prop."
}).to_owned()
}
(true, false) => {
(markup! {
<Emphasis>{self.element_name}</Emphasis>" is a void element tag and must not have "<Emphasis>"children"</Emphasis>"."
}).to_owned()
}
(false, true) => {
(markup! {
<Emphasis>{self.element_name}</Emphasis>" is a void element tag and must not have the "<Emphasis>"dangerouslySetInnerHTML"</Emphasis>" prop."
}).to_owned()
},
_ => unreachable!("At least a cause must be set")
}
}
fn action_message(&self) -> MarkupBuf {
let has_children_cause = self.has_children_cause();
let has_dangerous_cause = self.has_dangerous_prop_cause();
match (has_children_cause, has_dangerous_cause) {
(true, true) => {
(markup! {
"Remove the "<Emphasis>"children"</Emphasis>" and the "<Emphasis>"dangerouslySetInnerHTML"</Emphasis>" prop."
}).to_owned()
}
(true, false) => {
(markup! {
"Remove the "<Emphasis>"children"</Emphasis>"."
}).to_owned()
}
(false, true) => {
(markup! {
"Remove the "<Emphasis>"dangerouslySetInnerHTML"</Emphasis>" prop."
}).to_owned()
},
_ => unreachable!("At least a cause must be set")
}
}
}
impl Rule for NoVoidElementsWithChildren {
type Query = Semantic<NoVoidElementsWithChildrenQuery>;
type State = NoVoidElementsWithChildrenState;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let model = ctx.model();
match node {
NoVoidElementsWithChildrenQuery::JsxElement(element) => {
let opening_element = element.opening_element().ok()?;
let name = opening_element.name().ok()?;
let name = name.as_jsx_name()?.value_token().ok()?;
let name = name.text_trimmed();
if is_void_dom_element(name) {
let dangerous_prop = opening_element
.find_attribute_by_name("dangerouslySetInnerHTML")
.ok()?;
let has_children = !element.children().is_empty();
let children_prop = opening_element.find_attribute_by_name("children").ok()?;
if dangerous_prop.is_some() || has_children || children_prop.is_some() {
let cause = NoVoidElementsWithChildrenCause::Jsx {
children_prop,
dangerous_prop_cause: dangerous_prop,
children_cause: has_children,
};
return Some(NoVoidElementsWithChildrenState::new(name, cause));
}
}
}
NoVoidElementsWithChildrenQuery::JsxSelfClosingElement(element) => {
let name = element.name().ok()?;
let name = name.as_jsx_name()?.value_token().ok()?;
let name = name.text_trimmed();
if is_void_dom_element(name) {
let dangerous_prop = element
.find_attribute_by_name("dangerouslySetInnerHTML")
.ok()?;
let children_prop = element.find_attribute_by_name("children").ok()?;
if dangerous_prop.is_some() || children_prop.is_some() {
let cause = NoVoidElementsWithChildrenCause::Jsx {
children_prop,
dangerous_prop_cause: dangerous_prop,
children_cause: false,
};
return Some(NoVoidElementsWithChildrenState::new(name, cause));
}
}
}
NoVoidElementsWithChildrenQuery::JsCallExpression(call_expression) => {
let react_create_element =
ReactCreateElementCall::from_call_expression(call_expression, model)?;
let element_type = react_create_element
.element_type
.as_any_js_expression()?
.as_any_js_literal_expression()?
.as_js_string_literal_expression()?;
let element_name = element_type.inner_string_text().ok()?;
let element_name = element_name.text();
if is_void_dom_element(element_name) {
let has_children = react_create_element.children.is_some();
let dangerous_prop =
react_create_element.find_prop_by_name("dangerouslySetInnerHTML");
let children_prop = react_create_element.find_prop_by_name("children");
if dangerous_prop.is_some() || has_children || children_prop.is_some() {
let cause = NoVoidElementsWithChildrenCause::ReactCreateElement {
children_prop,
dangerous_prop_cause: dangerous_prop,
children_cause: has_children,
react_create_element,
};
return Some(NoVoidElementsWithChildrenState::new(element_name, cause));
}
}
}
}
None
}
fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
let range = match node {
NoVoidElementsWithChildrenQuery::JsxElement(element) => {
element.syntax().text_trimmed_range()
}
NoVoidElementsWithChildrenQuery::JsCallExpression(expression) => {
expression.syntax().text_trimmed_range()
}
NoVoidElementsWithChildrenQuery::JsxSelfClosingElement(element) => {
element.syntax().text_trimmed_range()
}
};
Some(RuleDiagnostic::new(
rule_category!(),
range,
state.diagnostic_message(),
))
}
fn action(ctx: &RuleContext<Self>, state: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
match node {
NoVoidElementsWithChildrenQuery::JsxElement(element) => {
if let NoVoidElementsWithChildrenCause::Jsx {
children_prop,
dangerous_prop_cause,
..
} = &state.cause
{
let opening_element = element.opening_element().ok()?;
let closing_element = element.closing_element().ok()?;
// here we create a new list of attributes, ignoring the ones that needs to be
// removed
let new_attribute_list: Vec<_> = opening_element
.attributes()
.into_iter()
.filter_map(|attribute| {
if let AnyJsxAttribute::JsxAttribute(attribute) = &attribute {
if let Some(children_prop) = children_prop {
if children_prop == attribute {
return None;
}
}
if let Some(dangerous_prop_cause) = dangerous_prop_cause {
if dangerous_prop_cause == attribute {
return None;
}
}
}
Some(attribute)
})
.collect();
let new_attribute_list = jsx_attribute_list(new_attribute_list);
let new_node = jsx_self_closing_element(
opening_element.l_angle_token().ok()?,
opening_element.name().ok()?,
new_attribute_list,
closing_element.slash_token().ok()?,
opening_element.r_angle_token().ok()?,
)
.build();
mutation.replace_element(
element.clone().into_syntax().into(),
new_node.into_syntax().into(),
);
}
}
NoVoidElementsWithChildrenQuery::JsCallExpression(_) => {
if let NoVoidElementsWithChildrenCause::ReactCreateElement {
children_prop,
dangerous_prop_cause,
react_create_element,
children_cause,
} = &state.cause
{
if *children_cause {
if let Some(children) = react_create_element.children.as_ref() {
mutation.remove_node(children.clone());
}
}
if let Some(children_prop) = children_prop.as_ref() {
mutation.remove_node(children_prop.clone());
}
if let Some(dangerous_prop_case) = dangerous_prop_cause.as_ref() {
mutation.remove_node(dangerous_prop_case.clone());
}
}
}
// self closing elements don't have inner children so we can safely remove the props
// that we don't need
NoVoidElementsWithChildrenQuery::JsxSelfClosingElement(_) => {
if let NoVoidElementsWithChildrenCause::Jsx {
children_prop,
dangerous_prop_cause,
..
} = &state.cause
{
if let Some(children_prop) = children_prop.as_ref() {
mutation.remove_node(children_prop.clone());
}
if let Some(dangerous_prop_case) = dangerous_prop_cause.as_ref() {
mutation.remove_node(dangerous_prop_case.clone());
}
}
}
}
Some(JsRuleAction {
mutation,
message: state.action_message(),
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/correctness/no_new_symbol.rs | crates/rome_js_analyze/src/semantic_analyzers/correctness/no_new_symbol.rs | use crate::{semantic_services::Semantic, JsRuleAction};
use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{global_identifier, AnyJsExpression, JsCallExpression, JsNewExpression};
use rome_rowan::{chain_trivia_pieces, AstNode, BatchMutationExt};
declare_rule! {
/// Disallow `new` operators with the `Symbol` object.
///
/// `Symbol` cannot be instantiated. This results in throwing a `TypeError`.
///
/// Source: https://eslint.org/docs/latest/rules/no-new-symbol
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// var foo = new Symbol('foo');
/// ```
///
/// ### Valid
///
/// ```js
/// var bar = Symbol('bar');
/// function baz() {
/// function Symbol() { }
/// new Symbol();
/// }
/// ```
pub(crate) NoNewSymbol {
version: "0.10.0",
name: "noNewSymbol",
recommended: true,
}
}
impl Rule for NoNewSymbol {
type Query = Semantic<JsNewExpression>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let callee = ctx.query().callee().ok()?;
let (reference, name) = global_identifier(&callee)?;
if name.text() != "Symbol" {
return None;
}
ctx.model().binding(&reference).is_none().then_some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
ctx.query().range(),
markup! {
<Emphasis>"Symbol"</Emphasis>" cannot be called as a constructor."
},
))
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let call_expression = convert_new_expression_to_call_expression(node)?;
let mut mutation = ctx.root().begin();
mutation.replace_node_discard_trivia::<AnyJsExpression>(
node.clone().into(),
call_expression.into(),
);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Remove "<Emphasis>"new"</Emphasis>"." }.to_owned(),
mutation,
})
}
}
fn convert_new_expression_to_call_expression(expr: &JsNewExpression) -> Option<JsCallExpression> {
let new_token = expr.new_token().ok()?;
let mut callee = expr.callee().ok()?;
if new_token.has_leading_comments() || new_token.has_trailing_comments() {
callee = callee.prepend_trivia_pieces(chain_trivia_pieces(
new_token.leading_trivia().pieces(),
new_token.trailing_trivia().pieces(),
))?;
}
Some(make::js_call_expression(callee, expr.arguments()?).build())
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/correctness/no_children_prop.rs | crates/rome_js_analyze/src/semantic_analyzers/correctness/no_children_prop.rs | use crate::react::{ReactApiCall, ReactCreateElementCall};
use crate::semantic_services::Semantic;
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{JsCallExpression, JsPropertyObjectMember, JsxAttribute, JsxName};
use rome_rowan::{declare_node_union, AstNode};
declare_rule! {
/// Prevent passing of **children** as props.
///
/// When using JSX, the children should be nested between the opening and closing tags.
/// When not using JSX, the children should be passed as additional arguments to `React.createElement`.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// <FirstComponent children={'foo'} />
/// ```
///
/// ```js,expect_diagnostic
/// React.createElement('div', { children: 'foo' });
/// ```
pub(crate) NoChildrenProp {
version: "0.10.0",
name: "noChildrenProp",
recommended: true,
}
}
declare_node_union! {
pub(crate) NoChildrenPropQuery = JsxAttribute | JsCallExpression
}
pub(crate) enum NoChildrenPropState {
JsxProp(JsxName),
MemberProp(JsPropertyObjectMember),
}
impl Rule for NoChildrenProp {
type Query = Semantic<NoChildrenPropQuery>;
type State = NoChildrenPropState;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
match node {
NoChildrenPropQuery::JsxAttribute(attribute) => {
let name = attribute.name().ok()?;
let name = name.as_jsx_name()?;
if name.value_token().ok()?.text() == "children" {
return Some(NoChildrenPropState::JsxProp(name.clone()));
}
None
}
NoChildrenPropQuery::JsCallExpression(call_expression) => {
let model = ctx.model();
if let Some(react_create_element) =
ReactCreateElementCall::from_call_expression(call_expression, model)
{
let children_prop = react_create_element.find_prop_by_name("children");
if let Some(children_prop) = children_prop {
return Some(NoChildrenPropState::MemberProp(children_prop));
}
}
None
}
}
}
fn diagnostic(_ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let (range, footer_help) = match state {
NoChildrenPropState::JsxProp(name) => {
(
name.syntax().text_trimmed_range(),
(markup! {
"The canonical way to pass children in React is to use JSX elements"
}).to_owned()
)
}
NoChildrenPropState::MemberProp(children_prop) => (
children_prop.name().ok()?.syntax().text_trimmed_range(),
(markup! {
"The canonical way to pass children in React is to use additional arguments to React.createElement"
}).to_owned()
),
};
Some(
RuleDiagnostic::new(
rule_category!(),
range,
markup! {
"Avoid passing "<Emphasis>"children"</Emphasis>" using a prop"
},
)
.note(footer_help),
)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/correctness/no_undeclared_variables.rs | crates/rome_js_analyze/src/semantic_analyzers/correctness/no_undeclared_variables.rs | use crate::globals::browser::BROWSER;
use crate::globals::node::NODE;
use crate::globals::runtime::{BUILTIN, ES_2021};
use crate::globals::typescript::TYPESCRIPT_BUILTIN;
use crate::semantic_services::SemanticServices;
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{JsFileSource, Language, TextRange, TsAsExpression, TsReferenceType};
use rome_rowan::AstNode;
declare_rule! {
/// Prevents the usage of variables that haven't been declared inside the document.
///
/// If you need to allow-list some global bindings, you can use the [`javascript.globals`](/configuration/#javascriptglobals) configuration.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// foobar;
/// ```
///
/// ```js,expect_diagnostic
/// // throw diagnostic for JavaScript files
/// PromiseLike;
/// ```
/// ### Valid
///
/// ```ts
/// type B<T> = PromiseLike<T>
/// ```
pub(crate) NoUndeclaredVariables {
version: "0.10.0",
name: "noUndeclaredVariables",
recommended: false,
}
}
impl Rule for NoUndeclaredVariables {
type Query = SemanticServices;
type State = (TextRange, String);
type Signals = Vec<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
ctx.query()
.all_unresolved_references()
.filter_map(|reference| {
let identifier = reference.tree();
let under_as_expression = identifier
.parent::<TsReferenceType>()
.and_then(|ty| ty.parent::<TsAsExpression>())
.is_some();
let token = identifier.value_token().ok()?;
let text = token.text_trimmed();
let source_type = ctx.source_type::<JsFileSource>();
if ctx.is_global(text) {
return None;
}
// Typescript Const Assertion
if text == "const" && under_as_expression {
return None;
}
if is_global(text, source_type) {
return None;
}
let span = token.text_trimmed_range();
let text = text.to_string();
Some((span, text))
})
.collect()
}
fn diagnostic(_ctx: &RuleContext<Self>, (span, name): &Self::State) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
*span,
markup! {
"The "<Emphasis>{name}</Emphasis>" variable is undeclared"
},
))
}
}
fn is_global(reference_name: &str, source_type: &JsFileSource) -> bool {
ES_2021.binary_search(&reference_name).is_ok()
|| BROWSER.binary_search(&reference_name).is_ok()
|| NODE.binary_search(&reference_name).is_ok()
|| match source_type.language() {
Language::JavaScript => BUILTIN.binary_search(&reference_name).is_ok(),
Language::TypeScript { .. } => {
BUILTIN.binary_search(&reference_name).is_ok()
|| TYPESCRIPT_BUILTIN.binary_search(&reference_name).is_ok()
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/correctness/no_global_object_calls.rs | crates/rome_js_analyze/src/semantic_analyzers/correctness/no_global_object_calls.rs | use crate::semantic_services::Semantic;
use rome_analyze::{context::RuleContext, declare_rule, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{global_identifier, AnyJsExpression, JsCallExpression, JsNewExpression};
use rome_rowan::{declare_node_union, SyntaxResult, TextRange};
use std::{fmt::Display, str::FromStr};
declare_rule! {
/// Disallow calling global object properties as functions
///
/// ECMAScript provides several global objects that are intended to be used as-is.
/// Some of these objects look as if they could be constructors due their capitalization (such as Math and JSON) but will throw an error if you try to execute them as functions.
///
/// The ECMAScript 5 specification makes it clear that both Math and JSON cannot be invoked:
/// The Math object does not have a [[Call]] internal property; it is not possible to invoke the Math object as a function.
///
/// The ECMAScript 2015 specification makes it clear that Reflect cannot be invoked:
/// The Reflect object also does not have a [[Call]] internal method; it is not possible to invoke the Reflect object as a function.
///
/// The ECMAScript 2017 specification makes it clear that Atomics cannot be invoked:
/// The Atomics object does not have a [[Call]] internal method; it is not possible to invoke the Atomics object as a function.
///
/// And the ECMAScript Internationalization API Specification makes it clear that Intl cannot be invoked:
/// The Intl object does not have a [[Call]] internal method; it is not possible to invoke the Intl object as a function.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// var math = Math();
/// ```
///
/// ```js,expect_diagnostic
/// var newMath = new Math();
/// ```
///
/// ```js,expect_diagnostic
/// var json = JSON();
/// ```
///
/// ```js,expect_diagnostic
/// var newJSON = new JSON();
/// ```
///
/// ```js,expect_diagnostic
/// var reflect = Reflect();
/// ```
///
/// ```js,expect_diagnostic
/// var newReflect = new Reflect();
/// ```
///
/// ```js,expect_diagnostic
/// var atomics = Atomics();
/// ```
///
/// ```js,expect_diagnostic
/// var newAtomics = new Atomics();
/// ```
///
/// ```js,expect_diagnostic
/// var intl = Intl();
/// ```
///
/// ```js,expect_diagnostic
/// var newIntl = new Intl();
/// ```
///
/// ## Valid
///
/// ```js
/// function area(r) {
/// return Math.PI * r * r;
/// }
///
/// var object = JSON.parse("{}");
///
/// var value = Reflect.get({ x: 1, y: 2 }, "x");
///
/// var first = Atomics.load(foo, 0);
///
/// var segmenterFr = new Intl.Segmenter("fr", { granularity: "word" });
/// ```
///
pub(crate) NoGlobalObjectCalls {
version: "12.0.0",
name: "noGlobalObjectCalls",
recommended: true,
}
}
impl Rule for NoGlobalObjectCalls {
type Query = Semantic<QueryNode>;
type State = (NonCallableGlobals, TextRange);
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let model = ctx.model();
let callee = node.callee().ok()?.omit_parentheses();
let (reference, name) = global_identifier(&callee)?;
let non_callable = NonCallableGlobals::from_str(name.text()).ok()?;
model
.binding(&reference)
.is_none()
.then_some((non_callable, name.range()))
}
fn diagnostic(
_: &RuleContext<Self>,
(non_callable, range): &Self::State,
) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
range,
markup! {
<Emphasis>{non_callable.to_string()}</Emphasis>" is not a function."
},
))
}
}
declare_node_union! {
/// Enum for [JsCallExpression] and [JsNewExpression]
pub(crate) QueryNode = JsNewExpression | JsCallExpression
}
impl QueryNode {
fn callee(&self) -> SyntaxResult<AnyJsExpression> {
match self {
QueryNode::JsNewExpression(expression) => expression.callee(),
QueryNode::JsCallExpression(expression) => expression.callee(),
}
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub(crate) enum NonCallableGlobals {
Atomics,
Json,
Math,
Reflect,
Intl,
}
impl FromStr for NonCallableGlobals {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"Atomics" => Ok(NonCallableGlobals::Atomics),
"JSON" => Ok(NonCallableGlobals::Json),
"Math" => Ok(NonCallableGlobals::Math),
"Reflect" => Ok(NonCallableGlobals::Reflect),
"Intl" => Ok(NonCallableGlobals::Intl),
_ => Err("non callable globals not implemented".to_string()),
}
}
}
impl Display for NonCallableGlobals {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let repr = match self {
NonCallableGlobals::Atomics => "Atomics",
NonCallableGlobals::Json => "Json",
NonCallableGlobals::Math => "Math",
NonCallableGlobals::Reflect => "Reflect",
NonCallableGlobals::Intl => "Intl",
};
write!(f, "{}", repr)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/nursery/use_is_array.rs | crates/rome_js_analyze/src/semantic_analyzers/nursery/use_is_array.rs | use crate::{semantic_services::Semantic, JsRuleAction};
use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{
global_identifier, AnyJsCallArgument, AnyJsExpression, JsInstanceofExpression, T,
};
use rome_rowan::{trim_leading_trivia_pieces, AstNode, BatchMutationExt};
declare_rule! {
/// Use `Array.isArray()` instead of `instanceof Array`.
///
/// In _JavaScript_ some array-like objects such as _arguments_ are not instances of the `Array` class. ///
/// Moreover, the global `Array` class can be different between two execution contexts.
/// For instance, two frames in a web browser have a distinct `Array` class.
/// Passing arrays across these contexts, results in arrays that are not instances of the contextual global `Array` class.
/// To avoid these issues, use `Array.isArray()` instead of `instanceof Array`.
/// See the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray) for more details.
///
/// Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-instanceof-array.md
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// const xs = [];
/// if (xs instanceof Array) {}
/// ```
///
/// ## Valid
///
/// ```js
/// const xs = [];
/// if (Array.isArray(xs)) {}
/// ```
///
pub(crate) UseIsArray {
version: "next",
name: "useIsArray",
recommended: true,
}
}
impl Rule for UseIsArray {
type Query = Semantic<JsInstanceofExpression>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let model = ctx.model();
let right = node.right().ok()?.omit_parentheses();
let (reference, name) = global_identifier(&right)?;
if name.text() != "Array" {
return None;
}
model.binding(&reference).is_none().then_some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
Some(
RuleDiagnostic::new(
rule_category!(),
ctx.query().range(),
markup! {
"Use "<Emphasis>"Array.isArray()"</Emphasis>" instead of "<Emphasis>"instanceof Array"</Emphasis>"."
},
)
.note(markup! {
<Emphasis>"instanceof Array"</Emphasis>" returns false for array-like objects and arrays from other execution contexts."
}),
)
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let array = node.right().ok()?;
let array_trailing_trivia = array.syntax().last_trailing_trivia()?.pieces();
let mut mutation = ctx.root().begin();
let is_array = make::js_static_member_expression(
array.with_trailing_trivia_pieces([])?,
make::token(T![.]),
make::js_name(make::ident("isArray")).into(),
);
let arg = AnyJsCallArgument::AnyJsExpression(node.left().ok()?.trim()?);
let instanceof_trailing_trivia = node.instanceof_token().ok()?.trailing_trivia().pieces();
let args = make::js_call_arguments(
make::token(T!['(']).with_trailing_trivia_pieces(trim_leading_trivia_pieces(
instanceof_trailing_trivia,
)),
make::js_call_argument_list([arg], []),
make::token(T![')']).with_trailing_trivia_pieces(array_trailing_trivia),
);
let call = make::js_call_expression(is_array.into(), args).build();
mutation.replace_node_discard_trivia(
AnyJsExpression::JsInstanceofExpression(node.clone()),
call.into(),
);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! {
"Use "<Emphasis>"Array.isArray()"</Emphasis>" instead."
}
.to_owned(),
mutation,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/nursery/no_accumulating_spread.rs | crates/rome_js_analyze/src/semantic_analyzers/nursery/no_accumulating_spread.rs | use rome_analyze::{context::RuleContext, declare_rule, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_semantic::SemanticModel;
use rome_js_syntax::{
AnyJsFunction, AnyJsMemberExpression, JsCallArgumentList, JsCallArguments, JsCallExpression,
JsFormalParameter, JsParameterList, JsParameters, JsSpread,
};
use rome_rowan::AstNode;
use crate::semantic_services::Semantic;
declare_rule! {
/// Disallow the use of spread (`...`) syntax on accumulators.
///
/// Spread syntax allows an iterable to be expanded into its individual elements.
///
/// Spread syntax should be avoided on accumulators (like those in `.reduce`)
/// because it causes a time complexity of `O(n^2)` instead of `O(n)`.
///
/// Source: https://prateeksurana.me/blog/why-using-object-spread-with-reduce-bad-idea/
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// var a = ['a', 'b', 'c'];
/// a.reduce((acc, val) => [...acc, val], []);
/// ```
///
/// ```js,expect_diagnostic
/// var a = ['a', 'b', 'c'];
/// a.reduce((acc, val) => {return [...acc, val];}, []);
/// ```
///
/// ```js,expect_diagnostic
/// var a = ['a', 'b', 'c'];
/// a.reduce((acc, val) => ({...acc, [val]: val}), {});
/// ```
///
/// ## Valid
///
/// ```js
/// var a = ['a', 'b', 'c'];
/// a.reduce((acc, val) => {acc.push(val); return acc}, []);
/// ```
///
pub(crate) NoAccumulatingSpread {
version: "12.1.0",
name: "noAccumulatingSpread",
recommended: false,
}
}
impl Rule for NoAccumulatingSpread {
type Query = Semantic<JsSpread>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let model = ctx.model();
is_known_accumulator(node, model)?.then_some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(
RuleDiagnostic::new(
rule_category!(),
node.range(),
markup! {
"Avoid the use of spread (`...`) syntax on accumulators."
},
)
.note(markup! {
"Spread syntax should be avoided on accumulators (like those in `.reduce`) because it causes a time complexity of `O(n^2)`."
}),
)
}
}
fn is_known_accumulator(node: &JsSpread, model: &SemanticModel) -> Option<bool> {
let reference = node
.argument()
.ok()?
.as_js_identifier_expression()?
.name()
.ok()?;
let parameter = model
.binding(&reference)
.and_then(|declaration| declaration.syntax().parent())
.and_then(JsFormalParameter::cast)?;
let function = parameter
.parent::<JsParameterList>()
.and_then(|list| list.parent::<JsParameters>())
.and_then(|parameters| parameters.parent::<AnyJsFunction>())?;
let call_expression = function
.parent::<JsCallArgumentList>()
.and_then(|arguments| arguments.parent::<JsCallArguments>())
.and_then(|arguments| arguments.parent::<JsCallExpression>())?;
let callee = call_expression.callee().ok()?;
let member_expression = AnyJsMemberExpression::cast_ref(callee.syntax())?;
let member_name = member_expression.member_name()?;
if !matches!(member_name.text(), "reduce" | "reduceRight") {
return None;
}
Some(parameter.syntax().index() == 0)
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/nursery/no_global_is_finite.rs | crates/rome_js_analyze/src/semantic_analyzers/nursery/no_global_is_finite.rs | use crate::{semantic_services::Semantic, JsRuleAction};
use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{global_identifier, AnyJsExpression, T};
use rome_rowan::{AstNode, BatchMutationExt};
declare_rule! {
/// Use `Number.isFinite` instead of global `isFinite`.
///
/// `Number.isFinite()` and `isFinite()` [have not the same behavior](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#difference_between_number.isfinite_and_global_isfinite).
/// When the argument to `isFinite()` is not a number, the value is first coerced to a number.
/// `Number.isFinite()` does not perform this coercion.
/// Therefore, it is a more reliable way to test whether a number is finite.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// isFinite(false); // true
/// ```
///
/// ## Valid
///
/// ```js
/// Number.isFinite(false); // false
/// ```
pub(crate) NoGlobalIsFinite {
version: "next",
name: "noGlobalIsFinite",
recommended: true,
}
}
impl Rule for NoGlobalIsFinite {
type Query = Semantic<AnyJsExpression>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let model = ctx.model();
let (reference, name) = global_identifier(node)?;
if name.text() != "isFinite" {
return None;
}
model.binding(&reference).is_none().then_some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(
RuleDiagnostic::new(
rule_category!(),
node.range(),
markup! {
<Emphasis>"isFinite"</Emphasis>" is unsafe. It attempts a type coercion. Use "<Emphasis>"Number.isFinite"</Emphasis>" instead."
},
)
.note(markup! {
"See "<Hyperlink href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite#description">"the MDN documentation"</Hyperlink>" for more details."
}),
)
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
let (old, new) = match node {
AnyJsExpression::JsIdentifierExpression(expression) => (
node.clone(),
make::js_static_member_expression(
make::js_identifier_expression(make::js_reference_identifier(make::ident(
"Number",
)))
.into(),
make::token(T![.]),
make::js_name(expression.name().ok()?.value_token().ok()?).into(),
),
),
AnyJsExpression::JsStaticMemberExpression(expression) => (
node.clone(),
make::js_static_member_expression(
make::js_static_member_expression(
expression.object().ok()?,
make::token(T![.]),
make::js_name(make::ident("Number")).into(),
)
.into(),
expression.operator_token().ok()?,
expression.member().ok()?,
),
),
AnyJsExpression::JsComputedMemberExpression(expression) => {
let object = expression.object().ok()?;
(
object.clone(),
make::js_static_member_expression(
object,
make::token(T![.]),
make::js_name(make::ident("Number")).into(),
),
)
}
_ => return None,
};
mutation.replace_node(old, new.into());
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! {
"Use "<Emphasis>"Number.isFinite"</Emphasis>" instead."
}
.to_owned(),
mutation,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/nursery/no_unsafe_declaration_merging.rs | crates/rome_js_analyze/src/semantic_analyzers/nursery/no_unsafe_declaration_merging.rs | use crate::semantic_services::Semantic;
use rome_analyze::{context::RuleContext, declare_rule, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{
binding_ext::AnyJsBindingDeclaration, TsDeclareStatement, TsExportDeclareClause,
TsInterfaceDeclaration,
};
use rome_rowan::{AstNode, TextRange};
declare_rule! {
/// Disallow unsafe declaration merging between interfaces and classes.
///
/// _TypeScript_'s [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) supports merging separate declarations with the same name.
///
/// _Declaration merging_ between classes and interfaces is unsafe.
/// The _TypeScript Compiler_ doesn't check whether properties defined in the interface are initialized in the class.
/// This can cause lead to _TypeScript_ not detecting code that will cause runtime errors.
///
/// Source: https://typescript-eslint.io/rules/no-unsafe-declaration-merging/
///
/// ## Examples
///
/// ### Invalid
///
/// ```ts,expect_diagnostic
/// interface Foo {
/// f(): void
/// }
///
/// class Foo {}
///
/// const foo = new Foo();
/// foo.f(); // Runtime Error: Cannot read properties of undefined.
/// ```
///
/// ## Valid
///
/// ```ts
/// interface Foo {}
/// class Bar implements Foo {}
/// ```
///
/// ```ts
/// namespace Baz {}
/// namespace Baz {}
/// enum Baz {}
/// ```
pub(crate) NoUnsafeDeclarationMerging {
version: "next",
name: "noUnsafeDeclarationMerging",
recommended: true,
}
}
impl Rule for NoUnsafeDeclarationMerging {
type Query = Semantic<TsInterfaceDeclaration>;
type State = TextRange;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let ts_interface = ctx.query();
let model = ctx.model();
let interface_binding = ts_interface.id().ok()?;
let interface_name = interface_binding.name_token().ok()?;
let scope = model.scope(ts_interface.syntax()).parent()?;
for binding in scope.bindings() {
if let Some(AnyJsBindingDeclaration::JsClassDeclaration(class)) =
binding.tree().declaration()
{
// This is not unsafe of merging an interface and an ambient class.
if class.parent::<TsDeclareStatement>().is_none()
&& class.parent::<TsExportDeclareClause>().is_none()
{
if let Ok(id) = class.id() {
if let Some(id) = id.as_js_identifier_binding() {
if let Ok(name) = id.name_token() {
if name.text() == interface_name.text() {
return Some(name.text_trimmed_range());
}
}
}
}
}
}
}
None
}
fn diagnostic(ctx: &RuleContext<Self>, class_range: &Self::State) -> Option<RuleDiagnostic> {
let ts_interface = ctx.query();
Some(
RuleDiagnostic::new(
rule_category!(),
class_range,
markup! {
"This "<Emphasis>"class"</Emphasis>" is unsafely merged with an "<Emphasis>"interface"</Emphasis>"."
},
)
.detail(ts_interface.id().ok()?.range(), markup! {
"The "<Emphasis>"interface"</Emphasis>" is declared here."
})
.note(markup! {
"The TypeScript compiler doesn't check whether properties defined in the interface are initialized in the class."
}),
)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/nursery/no_global_is_nan.rs | crates/rome_js_analyze/src/semantic_analyzers/nursery/no_global_is_nan.rs | use crate::{semantic_services::Semantic, JsRuleAction};
use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{global_identifier, AnyJsExpression, T};
use rome_rowan::{AstNode, BatchMutationExt};
declare_rule! {
/// Use `Number.isNaN` instead of global `isNaN`.
///
/// `Number.isNaN()` and `isNaN()` [have not the same behavior](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN#description).
/// When the argument to `isNaN()` is not a number, the value is first coerced to a number.
/// `Number.isNaN()` does not perform this coercion.
/// Therefore, it is a more reliable way to test whether a value is `NaN`.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// isNaN({}); // true
/// ```
///
/// ## Valid
///
/// ```js
/// Number.isNaN({}); // false
/// ```
///
pub(crate) NoGlobalIsNan {
version: "next",
name: "noGlobalIsNan",
recommended: true,
}
}
impl Rule for NoGlobalIsNan {
type Query = Semantic<AnyJsExpression>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let model = ctx.model();
let (reference, name) = global_identifier(node)?;
if name.text() != "isNaN" {
return None;
}
model.binding(&reference).is_none().then_some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(
RuleDiagnostic::new(
rule_category!(),
node.range(),
markup! {
<Emphasis>"isNaN"</Emphasis>" is unsafe. It attempts a type coercion. Use "<Emphasis>"Number.isNaN"</Emphasis>" instead."
},
)
.note(markup! {
"See "<Hyperlink href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN#description">"the MDN documentation"</Hyperlink>" for more details."
}),
)
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
let (old, new) = match node {
AnyJsExpression::JsIdentifierExpression(expression) => (
node.clone(),
make::js_static_member_expression(
make::js_identifier_expression(make::js_reference_identifier(make::ident(
"Number",
)))
.into(),
make::token(T![.]),
make::js_name(expression.name().ok()?.value_token().ok()?).into(),
),
),
AnyJsExpression::JsStaticMemberExpression(expression) => (
node.clone(),
make::js_static_member_expression(
make::js_static_member_expression(
expression.object().ok()?,
make::token(T![.]),
make::js_name(make::ident("Number")).into(),
)
.into(),
expression.operator_token().ok()?,
expression.member().ok()?,
),
),
AnyJsExpression::JsComputedMemberExpression(expression) => {
let object = expression.object().ok()?;
(
object.clone(),
make::js_static_member_expression(
object,
make::token(T![.]),
make::js_name(make::ident("Number")).into(),
),
)
}
_ => return None,
};
mutation.replace_node(old, new.into());
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! {
"Use "<Emphasis>"Number.isNaN"</Emphasis>" instead."
}
.to_owned(),
mutation,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/nursery/no_banned_types.rs | crates/rome_js_analyze/src/semantic_analyzers/nursery/no_banned_types.rs | use std::fmt::Display;
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, ActionCategory, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{
JsReferenceIdentifier, JsSyntaxKind, TextRange, TsIntersectionTypeElementList, TsObjectType,
TsReferenceType, TsTypeConstraintClause,
};
use rome_rowan::{declare_node_union, AstNode, AstNodeList, BatchMutationExt};
use crate::semantic_services::Semantic;
use crate::JsRuleAction;
declare_rule! {
/// Disallow primitive type aliases and misleading types.
///
/// - Enforce consistent names for primitive types
///
/// Primitive types have aliases.
/// For example, `Number` is an alias of `number`.
/// The rule recommends the lowercase primitive type names.
///
/// - Disallow the `Function` type
///
/// The `Function` type is loosely typed and is thus considered dangerous or harmful.
/// `Function` is equivalent to the type `(...rest: any[]) => any` that uses the unsafe `any` type.
///
/// - Disallow the misleading non-nullable type `{}`
///
/// In TypeScript, the type `{}` doesn't represent an empty object.
/// It represents any value except `null` and `undefined`.
/// The following TypeScript example is perfectly valid:
///
/// ```ts,expect_diagnostic
/// const n: {} = 0
/// ```
///
/// To represent an empty object, you should use `{ [k: string]: never }` or `Record<string, never>`.
///
/// To avoid any confusion, the rule forbids the use of the type `{}`,e except in two situation.
/// In type constraints to restrict a generic type to non-nullable types:
///
/// ```ts
/// function f<T extends {}>(x: T) {
/// assert(x != null);
/// }
/// ```
///
/// And in a type intersection to narrow a type to its non-nullable equivalent type:
///
/// ```ts
/// type NonNullableMyType = MyType & {};
/// ```
///
/// In this last case, you can also use the `NonNullable` utility type:
///
/// ```ts
/// type NonNullableMyType = NonNullable<MyType>;
/// ```
///
/// Source: https://typescript-eslint.io/rules/ban-types
///
/// ## Examples
///
/// ### Invalid
///
/// ```ts,expect_diagnostic
/// let foo: String = "bar";
/// ```
///
/// ```ts,expect_diagnostic
/// let bool = true as Boolean;
/// ```
///
/// ```ts,expect_diagnostic
/// let invalidTuple: [string, Boolean] = ["foo", false];
/// ```
///
/// ### Valid
///
/// ```ts
/// let foo: string = "bar";
/// ```
///
/// ```ts
/// let tuple: [boolean, string] = [false, "foo"];
/// ```
///
/// ```
pub(crate) NoBannedTypes {
version: "10.0.0",
name: "noBannedTypes",
recommended: true,
}
}
impl Rule for NoBannedTypes {
type Query = Semantic<TsBannedType>;
type State = State;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let query = ctx.query();
let model = ctx.model();
match query {
TsBannedType::TsObjectType(ts_object_type) => {
// Allow empty object type for type constraint and intersections.
// ```js
// type AssertNonNullGeneric<T extends {}> = T
// type NonNull<T> = T & {}
// ```
if ts_object_type.members().is_empty()
&& (ts_object_type.parent::<TsTypeConstraintClause>().is_none()
&& ts_object_type
.parent::<TsIntersectionTypeElementList>()
.is_none())
{
return Some(State {
banned_type: BannedType::EmptyObject,
banned_type_range: ts_object_type.range(),
reference_identifier: None,
});
}
}
TsBannedType::TsReferenceType(ts_reference_type) => {
let ts_any_name = ts_reference_type.name().ok()?;
let reference_identifier = ts_any_name.as_js_reference_identifier()?;
if model.binding(reference_identifier).is_none() {
// if the dientifier is global
let identifier_token = reference_identifier.value_token().ok()?;
if let Some(banned_type) = BannedType::from_str(identifier_token.text_trimmed())
{
return Some(State {
banned_type,
banned_type_range: identifier_token.text_trimmed_range(),
reference_identifier: Some(reference_identifier.clone()),
});
}
}
}
}
None
}
fn diagnostic(
_ctx: &RuleContext<Self>,
State {
banned_type,
banned_type_range,
..
}: &Self::State,
) -> Option<RuleDiagnostic> {
let diagnostic = RuleDiagnostic::new(
rule_category!(),
banned_type_range,
markup! {"Don't use '"{banned_type.to_string()}"' as a type."}.to_owned(),
)
.note(markup! { {banned_type.message()} }.to_owned());
Some(diagnostic)
}
fn action(
ctx: &RuleContext<Self>,
State {
banned_type,
reference_identifier,
..
}: &Self::State,
) -> Option<JsRuleAction> {
let mut mutation = ctx.root().begin();
let suggested_type = banned_type.as_js_syntax_kind()?.to_string()?;
mutation.replace_node(reference_identifier.clone()?, banned_type.fix_with()?);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::Always,
message: markup! { "Use '"{suggested_type}"' instead" }.to_owned(),
mutation,
})
}
}
declare_node_union! {
pub(crate) TsBannedType = TsReferenceType | TsObjectType
}
pub struct State {
/// Reference to the enum item containing the banned type.
/// Used for both diagnostic and action.
banned_type: BannedType,
/// Text range used to diagnostic the banned type.
banned_type_range: TextRange,
/// Reference to the node to be replaced in the action.
/// This is optional because we don't replace empty objects references.
reference_identifier: Option<JsReferenceIdentifier>,
}
#[derive(Debug)]
pub enum BannedType {
BigInt,
Boolean,
Function,
Number,
Object,
String,
Symbol,
/// {}
EmptyObject,
}
impl BannedType {
/// construct a [BannedType] from the textual name of a JavaScript type
fn from_str(s: &str) -> Option<Self> {
Some(match s {
"BigInt" => Self::BigInt,
"Boolean" => Self::Boolean,
"Function" => Self::Function,
"Number" => Self::Number,
"Object" => Self::Object,
"String" => Self::String,
"Symbol" => Self::Symbol,
"{}" => Self::EmptyObject,
_ => return None,
})
}
/// Retrieves a diagnostic message from a [BannedType]
fn message(&self) -> &str {
match *self {
| Self::BigInt
| Self::Boolean
| Self::Number
| Self::String
| Self::Symbol => "Use lowercase primitives for consistency.",
Self::Function =>
"Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.",
Self::Object =>
"Prefer explicitly define the object shape. This type means \"any non-nullable value\", which is slightly better than 'unknown', but it's still a broad type.",
Self::EmptyObject => "Prefer explicitly define the object shape. '{}' means \"any non-nullable value\".",
}
}
/// Converts a [BannedType] to a [JsSyntaxKind]
fn as_js_syntax_kind(&self) -> Option<JsSyntaxKind> {
Some(match *self {
Self::BigInt => JsSyntaxKind::BIGINT_KW,
Self::Boolean => JsSyntaxKind::BOOLEAN_KW,
Self::Number => JsSyntaxKind::NUMBER_KW,
Self::String => JsSyntaxKind::STRING_KW,
Self::Symbol => JsSyntaxKind::SYMBOL_KW,
_ => return None,
})
}
/// Retrieves a [JsReferenceIdentifier] from a [BannedType] that will be used to
/// replace it on the rule action
fn fix_with(&self) -> Option<JsReferenceIdentifier> {
Some(match *self {
Self::BigInt | Self::Boolean | Self::Number | Self::String | Self::Symbol => {
make::js_reference_identifier(make::token(Self::as_js_syntax_kind(self)?))
}
_ => return None,
})
}
}
impl Display for BannedType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let representation = match self {
Self::BigInt => "BigInt",
Self::Boolean => "Boolean",
Self::Function => "Function",
Self::Number => "Number",
Self::Object => "Object",
Self::String => "String",
Self::Symbol => "Symbol",
Self::EmptyObject => "{}",
};
write!(f, "{}", representation)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/nursery/no_constant_condition.rs | crates/rome_js_analyze/src/semantic_analyzers/nursery/no_constant_condition.rs | use crate::{semantic_services::Semantic, utils::rename::RenamableNode};
use rome_analyze::{context::RuleContext, declare_rule, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_semantic::SemanticModel;
use rome_js_syntax::{
AnyJsArrayElement, AnyJsExpression, AnyJsLiteralExpression, AnyJsStatement,
AnyJsTemplateElement, JsAssignmentOperator, JsConditionalExpression, JsDoWhileStatement,
JsForStatement, JsFunctionDeclaration, JsFunctionExpression, JsIfStatement, JsLogicalOperator,
JsStatementList, JsUnaryOperator, JsWhileStatement, JsYieldExpression, TextRange,
};
use rome_rowan::{declare_node_union, AstNode, AstSeparatedList};
declare_rule! {
/// Disallow constant expressions in conditions
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// if (false) {
/// doSomethingUnfinished();
/// }
/// ```
///
/// ```js,expect_diagnostic
/// if (Boolean(1)) {
/// doSomethingAlways();
/// }
/// ```
///
/// ```js,expect_diagnostic
/// if (undefined) {
/// doSomethingUnfinished();
/// }
/// ```
///
/// ```js,expect_diagnostic
/// for (;-2;) {
/// doSomethingForever();
/// }
/// ```
///
/// ```js,expect_diagnostic
/// while (typeof x) {
/// doSomethingForever();
/// }
/// ```
///
/// ```js,expect_diagnostic
/// var result = 0 ? a : b;
/// ```
///
/// ### Valid
///
/// ```js
/// if (x === 0) {
/// doSomething();
/// }
///
/// for (;;) {
/// doSomethingForever();
/// }
///
/// while (typeof x === "undefined") {
/// doSomething();
/// }
///
/// do {
/// doSomething();
/// } while (x);
///
/// var result = x !== 0 ? a : b;
/// ```
///
pub(crate) NoConstantCondition {
version: "12.1.0",
name: "noConstantCondition",
recommended: true,
}
}
declare_node_union! {
pub(crate) ConditionalStatement = JsConditionalExpression | JsWhileStatement | JsDoWhileStatement | JsIfStatement | JsForStatement
}
impl Rule for NoConstantCondition {
type Query = Semantic<ConditionalStatement>;
type State = TextRange;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let conditional_stmt = ctx.query();
let model = ctx.model();
// We must verify that the conditional statement is within a generator function.
// 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)
&& has_valid_yield_expression(&any_js_stmt).unwrap_or(false)
{
return None;
}
}
let test = conditional_stmt.test()?;
is_constant_condition(&test, true, model).map(|_| Some(test.range()))?
}
fn diagnostic(_ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
state,
markup! {
"Unexpected constant condition."
},
))
}
}
impl ConditionalStatement {
fn test(&self) -> Option<AnyJsExpression> {
match self {
Self::JsConditionalExpression(it) => it.test().ok(),
Self::JsWhileStatement(it) => it.test().ok(),
Self::JsDoWhileStatement(it) => it.test().ok(),
Self::JsIfStatement(it) => it.test().ok(),
Self::JsForStatement(it) => it.test(),
}
}
fn body(&self) -> Option<AnyJsStatement> {
match self {
Self::JsWhileStatement(it) => it.body().ok(),
Self::JsDoWhileStatement(it) => it.body().ok(),
Self::JsForStatement(it) => it.body().ok(),
_ => None,
}
}
// Checks if the self statement is in a generator function
fn is_in_generator_function(&self) -> Option<bool> {
self.syntax().ancestors().find_map(|node| {
if let Some(func_decl) = JsFunctionDeclaration::cast(node.clone()) {
return Some(func_decl.as_fields().star_token.is_some());
};
if let Some(func_expr) = JsFunctionExpression::cast(node) {
return Some(func_expr.as_fields().star_token.is_some());
};
None
})
}
}
impl From<AnyJsStatement> for ConditionalStatement {
fn from(node: AnyJsStatement) -> Self {
match node {
AnyJsStatement::JsWhileStatement(it) => Self::JsWhileStatement(it),
AnyJsStatement::JsDoWhileStatement(it) => Self::JsDoWhileStatement(it),
AnyJsStatement::JsIfStatement(it) => Self::JsIfStatement(it),
AnyJsStatement::JsForStatement(it) => Self::JsForStatement(it),
_ => unreachable!(),
}
}
}
// Gets a yield expression from the given statement
fn get_yield_expression(stmt: &AnyJsStatement) -> Option<JsYieldExpression> {
let stmt = stmt.as_js_expression_statement()?;
let expr = stmt.as_fields().expression.ok()?;
let expr = expr.as_js_yield_expression()?;
Some(expr.clone())
}
fn get_statement_list(stmt: &AnyJsStatement) -> Option<JsStatementList> {
Some(stmt.as_js_block_statement()?.as_fields().statements)
}
/// Checks if a given statement can return valid yield expression
fn has_valid_yield_expression(stmt: &AnyJsStatement) -> Option<bool> {
let mut stmt_list = get_statement_list(stmt)?.into_iter();
loop {
match stmt_list.next() {
Some(first_stmt) => {
if get_yield_expression(&first_stmt).is_some()
|| stmt_list.any(|stmt| get_yield_expression(&stmt).is_some())
{
return Some(true);
} else {
// We need to examine `while`, `do...while`, and `for` statements more closely,
// as there are cases where a yield expression is correctly returned even with nested loops.
match first_stmt {
AnyJsStatement::JsWhileStatement(stmt) => {
stmt_list = get_statement_list(&stmt.body().ok()?)?.into_iter();
}
AnyJsStatement::JsDoWhileStatement(stmt) => {
stmt_list = get_statement_list(&stmt.body().ok()?)?.into_iter();
}
AnyJsStatement::JsForStatement(stmt) => {
stmt_list = get_statement_list(&stmt.body().ok()?)?.into_iter();
}
_ => return None,
}
}
}
None => return None,
}
}
}
fn is_constant_condition(
test: &AnyJsExpression,
in_boolean_position: bool,
model: &SemanticModel,
) -> Option<()> {
use AnyJsExpression::*;
match test.clone().omit_parentheses() {
AnyJsLiteralExpression(_)
| JsObjectExpression(_)
| JsFunctionExpression(_)
| JsArrowFunctionExpression(_)
| JsClassExpression(_) => Some(()),
JsUnaryExpression(node) => {
use JsUnaryOperator::*;
let op = node.operator().ok()?;
if op == Void || op == Typeof && in_boolean_position {
return Some(());
}
if op == LogicalNot {
return is_constant_condition(&node.argument().ok()?, true, model);
}
is_constant_condition(&node.argument().ok()?, false, model)
}
JsBinaryExpression(node) => is_constant_condition(&node.left().ok()?, false, model)
.and_then(|_| is_constant_condition(&node.right().ok()?, false, model)),
JsLogicalExpression(node) => {
let left = node.left().ok()?;
let right = node.right().ok()?;
let op = node.operator().ok()?;
let is_left_constant =
is_constant_condition(&left, in_boolean_position, model).is_some();
let is_right_constant =
is_constant_condition(&right, in_boolean_position, model).is_some();
let is_left_short_circuit = is_left_constant && is_logical_identity(left, op);
let is_right_short_circuit =
in_boolean_position && is_right_constant && is_logical_identity(right, op);
if (is_left_constant && is_right_constant)
|| is_left_short_circuit
|| is_right_short_circuit
{
Some(())
} else {
None
}
}
JsSequenceExpression(node) => {
is_constant_condition(&node.right().ok()?, in_boolean_position, model)
}
JsIdentifierExpression(node) => {
if node.name().ok()?.binding(model).is_some() {
// This is any_js_stmt edge case. Mordern browser doesn't allow to redeclare `undefined` but ESLint handle this so we do
return None;
}
let is_named_undefined = node.name().ok()?.is_undefined();
is_named_undefined.then_some(())
}
JsArrayExpression(node) => {
if !in_boolean_position {
node.elements()
.into_iter()
.all(|js_statement| {
if let Ok(element) = js_statement {
match element {
AnyJsArrayElement::JsArrayHole(_) => true,
AnyJsArrayElement::JsSpread(node) => {
if let Ok(argument) = node.argument() {
is_constant_condition(&argument, in_boolean_position, model)
.is_some()
} else {
false
}
}
_ => element
.as_any_js_expression()
.and_then(|node| is_constant_condition(node, false, model))
.is_some(),
}
} else {
false
}
})
.then_some(())
} else {
Some(())
}
}
JsNewExpression(_) => in_boolean_position.then_some(()),
JsCallExpression(node) => {
if node.has_callee("Boolean") {
let callee = node.callee().ok()?;
let ident = callee.as_js_identifier_expression()?.name().ok()?;
let binding = ident.binding(model);
if binding.is_some() {
return None;
}
let args = node.arguments().ok()?.args();
if args.is_empty() {
return Some(());
}
return is_constant_condition(
args.first()?.ok()?.as_any_js_expression()?,
true,
model,
);
}
None
}
JsAssignmentExpression(node) => {
use JsAssignmentOperator::*;
let operator = node.operator().ok()?;
if operator == Assign {
return is_constant_condition(&node.right().ok()?, in_boolean_position, model);
}
if matches!(operator, LogicalOrAssign | LogicalAndAssign) && in_boolean_position {
let new_op = match operator {
LogicalAndAssign => JsLogicalOperator::LogicalAnd,
LogicalOrAssign => JsLogicalOperator::LogicalOr,
_ => unreachable!(),
};
return is_logical_identity(node.right().ok()?, new_op).then_some(());
}
None
}
JsTemplateExpression(node) => {
let is_tag = node.tag().is_some();
let elements = node.elements();
let has_truthy_quasi = !is_tag
&& elements.clone().into_iter().any(|element| match element {
AnyJsTemplateElement::JsTemplateChunkElement(element) => {
if let Ok(quasi) = element.template_chunk_token() {
!quasi.text_trimmed().is_empty()
} else {
false
}
}
AnyJsTemplateElement::JsTemplateElement(_) => false,
});
if has_truthy_quasi && in_boolean_position {
return Some(());
}
elements
.into_iter()
.all(|element| match element {
AnyJsTemplateElement::JsTemplateChunkElement(_) => !is_tag,
AnyJsTemplateElement::JsTemplateElement(element) => {
if let Ok(expr) = element.expression() {
is_constant_condition(&expr, false, model).is_some()
} else {
false
}
}
})
.then_some(())
}
_ => None,
}
}
fn is_logical_identity(node: AnyJsExpression, operator: JsLogicalOperator) -> bool {
use AnyJsExpression::*;
use JsLogicalOperator::*;
match node.omit_parentheses() {
AnyJsLiteralExpression(node) => {
let boolean_value = get_boolean_value(node);
operator == LogicalOr && boolean_value || (operator == LogicalAnd && !boolean_value)
}
JsUnaryExpression(node) => {
if operator != LogicalAnd {
return false;
}
if let Ok(node_operator) = node.operator() {
node_operator == JsUnaryOperator::Void
} else {
false
}
}
JsLogicalExpression(node) => {
if let Ok(node_operator) = node.operator() {
// handles `any_js_stmt && false || b`
// `false` is an identity element of `&&` but not `||`
// so the logical identity of the whole expression can not be defined.
if operator != node_operator {
return false;
}
let is_left_logical_identify = node
.left()
.ok()
.map_or(false, |left| is_logical_identity(left, operator));
if is_left_logical_identify {
return true;
}
node.right()
.ok()
.map_or(false, |right| is_logical_identity(right, operator))
} else {
false
}
}
JsAssignmentExpression(node) => {
if let Ok(node_operator) = node.operator() {
if let Ok(right) = node.right() {
let is_valid_logical_assignment = match node_operator {
JsAssignmentOperator::LogicalAndAssign
if operator == JsLogicalOperator::LogicalAnd =>
{
true
}
JsAssignmentOperator::LogicalOrAssign
if operator == JsLogicalOperator::LogicalOr =>
{
true
}
_ => false,
};
is_valid_logical_assignment && is_logical_identity(right, operator)
} else {
false
}
} else {
false
}
}
_ => false,
}
}
fn get_boolean_value(node: AnyJsLiteralExpression) -> bool {
use AnyJsLiteralExpression::*;
match node {
JsRegexLiteralExpression(_) => true,
_ => node
.as_static_value()
.map_or(false, |value| !value.is_falsy()),
}
}
#[cfg(test)]
mod tests {
use rome_js_parser::JsParserOptions;
use rome_js_syntax::{AnyJsLiteralExpression, JsFileSource};
use rome_rowan::SyntaxNodeCast;
use super::get_boolean_value;
fn assert_boolean_value(code: &str, value: bool) {
let source = rome_js_parser::parse(code, JsFileSource::tsx(), JsParserOptions::default());
if source.has_errors() {
panic!("syntax error")
}
let literal_expression = source
.syntax()
.descendants()
.find_map(|js_statement| js_statement.cast::<AnyJsLiteralExpression>());
assert_eq!(
get_boolean_value(literal_expression.expect("Not found AnyLiteralExpression.")),
value
);
}
#[test]
fn test_get_boolean_value() {
assert_boolean_value("false", false);
assert_boolean_value("0", false);
assert_boolean_value("-0", false);
assert_boolean_value("0n", false);
assert_boolean_value("let any_js_stmt =\"\"", false);
assert_boolean_value("let any_js_stmt = ''", false);
assert_boolean_value("null", false);
assert_boolean_value("true", true);
assert_boolean_value("let any_js_stmt = \"0\"", true);
assert_boolean_value("let any_js_stmt = \"false\"", true);
assert_boolean_value("-42", true);
assert_boolean_value("12n", true);
assert_boolean_value("3.14", true);
assert_boolean_value("-3.14", true);
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/nursery/use_exhaustive_dependencies.rs | crates/rome_js_analyze/src/semantic_analyzers/nursery/use_exhaustive_dependencies.rs | use crate::react::hooks::*;
use crate::semantic_services::Semantic;
use bpaf::Bpaf;
use rome_analyze::{context::RuleContext, declare_rule, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_deserialize::json::{has_only_known_keys, VisitJsonNode};
use rome_deserialize::{DeserializationDiagnostic, VisitNode};
use rome_js_semantic::{Capture, SemanticModel};
use rome_js_syntax::{
binding_ext::AnyJsBindingDeclaration, JsCallExpression, JsStaticMemberExpression, JsSyntaxKind,
JsSyntaxNode, JsVariableDeclaration, TextRange,
};
use rome_json_syntax::{AnyJsonValue, JsonLanguage, JsonSyntaxNode};
use rome_rowan::{AstNode, AstSeparatedList, SyntaxNode, SyntaxNodeCast};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::str::FromStr;
#[cfg(feature = "schemars")]
use schemars::JsonSchema;
declare_rule! {
/// Enforce all dependencies are correctly specified.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// import { useEffect } from "react";
///
/// function component() {
/// let a = 1;
/// useEffect(() => {
/// console.log(a);
/// });
/// }
/// ```
///
/// ```js,expect_diagnostic
/// import { useEffect } from "react";
///
/// function component() {
/// let b = 1;
/// useEffect(() => {
/// }, [b]);
/// }
/// ```
///
/// ```js,expect_diagnostic
/// import { useEffect, useState } from "react";
///
/// function component() {
/// const [name, setName] = useState();
/// useEffect(() => {
/// console.log(name);
/// setName("");
/// }, [name, setName]);
/// }
/// ```
///
/// ```js,expect_diagnostic
/// import { useEffect } from "react";
///
/// function component() {
/// let a = 1;
/// const b = a + 1;
/// useEffect(() => {
/// console.log(b);
/// });
/// }
/// ```
///
/// ## Valid
///
/// ```js
/// import { useEffect } from "react";
///
/// function component() {
/// let a = 1;
/// useEffect(() => {
/// console.log(a);
/// }, [a]);
/// }
/// ```
///
/// ```js
/// import { useEffect } from "react";
///
/// function component() {
/// const a = 1;
/// useEffect(() => {
/// console.log(a);
/// });
/// }
/// ```
///
/// ```js
/// import { useEffect } from "react";
///
/// function component() {
/// const [name, setName] = useState();
/// useEffect(() => {
/// console.log(name);
/// setName("");
/// }, [name]);
/// }
/// ```
///
/// ## Options
///
/// Allows to specify custom hooks - from libraries or internal projects - that can be considered stable.
///
/// ```json
/// {
/// "//": "...",
/// "options": {
/// "hooks": [
/// { "name": "useLocation", "closureIndex": 0, "dependenciesIndex": 1},
/// { "name": "useQuery", "closureIndex": 1, "dependenciesIndex": 0}
/// ]
/// }
/// }
/// ```
///
/// Given the previous example, your hooks be used like this:
///
/// ```js
/// function Foo() {
/// const location = useLocation(() => {}, []);
/// const query = useQuery([], () => {});
/// }
/// ```
///
pub(crate) UseExhaustiveDependencies {
version: "10.0.0",
name: "useExhaustiveDependencies",
recommended: true,
}
}
#[derive(Debug, Clone)]
pub struct ReactExtensiveDependenciesOptions {
pub(crate) hooks_config: HashMap<String, ReactHookConfiguration>,
pub(crate) stable_config: HashSet<StableReactHookConfiguration>,
}
impl Default for ReactExtensiveDependenciesOptions {
fn default() -> Self {
let hooks_config = HashMap::from_iter([
("useEffect".to_string(), (0, 1).into()),
("useLayoutEffect".to_string(), (0, 1).into()),
("useInsertionEffect".to_string(), (0, 1).into()),
("useCallback".to_string(), (0, 1).into()),
("useMemo".to_string(), (0, 1).into()),
("useImperativeHandle".to_string(), (1, 2).into()),
("useState".to_string(), ReactHookConfiguration::default()),
("useContext".to_string(), ReactHookConfiguration::default()),
("useReducer".to_string(), ReactHookConfiguration::default()),
("useRef".to_string(), ReactHookConfiguration::default()),
(
"useDebugValue".to_string(),
ReactHookConfiguration::default(),
),
(
"useDeferredValue".to_string(),
ReactHookConfiguration::default(),
),
(
"useTransition".to_string(),
ReactHookConfiguration::default(),
),
("useId".to_string(), ReactHookConfiguration::default()),
(
"useSyncExternalStore".to_string(),
ReactHookConfiguration::default(),
),
]);
let stable_config: HashSet<StableReactHookConfiguration> = HashSet::from_iter([
StableReactHookConfiguration::new("useState", Some(1)),
StableReactHookConfiguration::new("useReducer", Some(1)),
StableReactHookConfiguration::new("useTransition", Some(1)),
StableReactHookConfiguration::new("useRef", None),
StableReactHookConfiguration::new("useContext", None),
StableReactHookConfiguration::new("useId", None),
StableReactHookConfiguration::new("useSyncExternalStore", None),
]);
Self {
hooks_config,
stable_config,
}
}
}
/// Options for the rule `useExhaustiveDependencies` and `useHookAtTopLevel`
#[derive(Default, Deserialize, Serialize, Debug, Clone, Bpaf)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct HooksOptions {
#[bpaf(external, hide, many)]
/// List of safe hooks
pub hooks: Vec<Hooks>,
}
impl FromStr for HooksOptions {
type Err = ();
fn from_str(_s: &str) -> Result<Self, Self::Err> {
Ok(HooksOptions::default())
}
}
#[derive(Default, Deserialize, Serialize, Debug, Clone, Bpaf)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Hooks {
#[bpaf(hide)]
/// The name of the hook
pub name: String,
#[bpaf(hide)]
/// The "position" of the closure function, starting from zero.
///
/// ### Example
pub closure_index: Option<usize>,
#[bpaf(hide)]
/// The "position" of the array of dependencies, starting from zero.
pub dependencies_index: Option<usize>,
}
impl Hooks {
const KNOWN_KEYS: &'static [&'static str] = &["name", "closureIndex", "dependenciesIndex"];
}
impl VisitJsonNode for Hooks {}
impl VisitNode<JsonLanguage> for Hooks {
fn visit_member_name(
&mut self,
node: &JsonSyntaxNode,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
has_only_known_keys(node, Hooks::KNOWN_KEYS, diagnostics)
}
fn visit_map(
&mut self,
key: &JsonSyntaxNode,
value: &JsonSyntaxNode,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
let (name, value) = self.get_key_and_value(key, value, diagnostics)?;
let name_text = name.text();
match name_text {
"name" => {
self.name = self.map_to_string(&value, name_text, diagnostics)?;
}
"closureIndex" => {
self.closure_index = self.map_to_usize(&value, name_text, usize::MAX, diagnostics);
}
"dependenciesIndex" => {
self.dependencies_index =
self.map_to_usize(&value, name_text, usize::MAX, diagnostics);
}
_ => {}
}
Some(())
}
}
impl FromStr for Hooks {
type Err = ();
fn from_str(_s: &str) -> Result<Self, Self::Err> {
Ok(Hooks::default())
}
}
impl VisitJsonNode for HooksOptions {}
impl VisitNode<JsonLanguage> for HooksOptions {
fn visit_member_name(
&mut self,
node: &JsonSyntaxNode,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
has_only_known_keys(node, &["hooks"], diagnostics)
}
fn visit_array_member(
&mut self,
element: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
let mut hook = Hooks::default();
let element = AnyJsonValue::cast(element.clone())?;
self.map_to_object(&element, "hooks", &mut hook, diagnostics)?;
if hook.name.is_empty() {
diagnostics.push(
DeserializationDiagnostic::new(markup!(
"The field "<Emphasis>"name"</Emphasis>" is mandatory"
))
.with_range(element.range()),
)
} else {
self.hooks.push(hook);
}
Some(())
}
fn visit_map(
&mut self,
key: &JsonSyntaxNode,
value: &JsonSyntaxNode,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
let (name, value) = self.get_key_and_value(key, value, diagnostics)?;
let name_text = name.text();
if name_text == "hooks" {
let array = value.as_json_array_value()?;
for element in array.elements() {
let element = element.ok()?;
let hook_array = element.as_json_array_value()?;
let len = hook_array.elements().len();
if len < 1 {
diagnostics.push(
DeserializationDiagnostic::new("At least one element is needed")
.with_range(hook_array.range()),
);
return Some(());
}
if len > 3 {
diagnostics.push(
DeserializationDiagnostic::new(
"Too many elements, maximum three are expected",
)
.with_range(hook_array.range()),
);
return Some(());
}
let mut elements = hook_array.elements().iter();
let hook_name = elements.next()?.ok()?;
let hook_name = hook_name
.as_json_string_value()
.ok_or_else(|| {
DeserializationDiagnostic::new_incorrect_type("string", hook_name.range())
})
.ok()?
.inner_string_text()
.ok()?
.to_string();
let closure_index = if let Some(element) = elements.next() {
let element = element.ok()?;
Some(self.map_to_u8(&element, name_text, u8::MAX, diagnostics)? as usize)
} else {
None
};
let dependencies_index = if let Some(element) = elements.next() {
let element = element.ok()?;
Some(self.map_to_u8(&element, name_text, u8::MAX, diagnostics)? as usize)
} else {
None
};
self.hooks.push(Hooks {
name: hook_name,
closure_index,
dependencies_index,
});
}
}
Some(())
}
}
impl ReactExtensiveDependenciesOptions {
pub fn new(hooks: HooksOptions) -> Self {
let mut default = ReactExtensiveDependenciesOptions::default();
for hook in hooks.hooks.into_iter() {
default.hooks_config.insert(
hook.name,
ReactHookConfiguration {
closure_index: hook.closure_index,
dependencies_index: hook.dependencies_index,
},
);
}
default
}
}
/// Flags the possible fixes that were found
pub enum Fix {
/// When a dependency needs to be added.
AddDependency(TextRange, Vec<TextRange>),
/// When a dependency needs to be removed.
RemoveDependency(TextRange, Vec<TextRange>),
/// When a dependency is more deep than the capture
DependencyTooDeep {
function_name_range: TextRange,
capture_range: TextRange,
dependency_range: TextRange,
},
}
fn get_whole_static_member_expression(
reference: &JsSyntaxNode,
) -> Option<JsStaticMemberExpression> {
let root = reference
.ancestors()
.skip(2) //IDENT and JS_REFERENCE_IDENTIFIER
.take_while(|x| x.kind() == JsSyntaxKind::JS_STATIC_MEMBER_EXPRESSION)
.last()?;
root.cast()
}
// Test if a capture needs to be in the dependency list
// of a react hook call
fn capture_needs_to_be_in_the_dependency_list(
capture: Capture,
component_function_range: &TextRange,
model: &SemanticModel,
options: &ReactExtensiveDependenciesOptions,
) -> Option<Capture> {
let binding = capture.binding();
// Ignore if imported
if binding.is_imported() {
return None;
}
match binding.tree().declaration()? {
// These declarations are always stable
AnyJsBindingDeclaration::JsFunctionDeclaration(_)
| AnyJsBindingDeclaration::JsClassDeclaration(_)
| AnyJsBindingDeclaration::TsEnumDeclaration(_)
| AnyJsBindingDeclaration::TsTypeAliasDeclaration(_)
| AnyJsBindingDeclaration::TsInterfaceDeclaration(_)
| AnyJsBindingDeclaration::TsModuleDeclaration(_) => None,
// Variable declarators are stable if ...
AnyJsBindingDeclaration::JsVariableDeclarator(declarator) => {
let declaration = declarator
.syntax()
.ancestors()
.filter_map(JsVariableDeclaration::cast)
.next()?;
let declaration_range = declaration.syntax().text_range();
if declaration.is_const() {
// ... they are `const` and declared outside of the component function
let _ = component_function_range.intersect(declaration_range)?;
// ... they are `const` and their initializer is constant
let initializer = declarator.initializer()?;
let expr = initializer.expression().ok()?;
if model.is_constant(&expr) {
return None;
}
}
// ... they are assign to stable returns of another React function
let not_stable = !is_binding_react_stable(&binding.tree(), &options.stable_config);
not_stable.then_some(capture)
}
// all others need to be in the dependency list
AnyJsBindingDeclaration::JsFormalParameter(_)
| AnyJsBindingDeclaration::JsRestParameter(_)
| AnyJsBindingDeclaration::JsBogusParameter(_)
| AnyJsBindingDeclaration::TsIndexSignatureParameter(_)
| AnyJsBindingDeclaration::TsPropertyParameter(_)
| AnyJsBindingDeclaration::JsFunctionExpression(_)
| AnyJsBindingDeclaration::TsDeclareFunctionDeclaration(_)
| AnyJsBindingDeclaration::JsClassExpression(_)
| AnyJsBindingDeclaration::JsClassExportDefaultDeclaration(_)
| AnyJsBindingDeclaration::JsFunctionExportDefaultDeclaration(_)
| AnyJsBindingDeclaration::TsDeclareFunctionExportDefaultDeclaration(_)
| AnyJsBindingDeclaration::JsCatchDeclaration(_) => Some(capture),
// This should not be unreachable because of the test
// if the capture is imported
AnyJsBindingDeclaration::JsImportDefaultClause(_)
| AnyJsBindingDeclaration::JsImportNamespaceClause(_)
| AnyJsBindingDeclaration::JsShorthandNamedImportSpecifier(_)
| AnyJsBindingDeclaration::JsNamedImportSpecifier(_)
| AnyJsBindingDeclaration::JsBogusNamedImportSpecifier(_)
| AnyJsBindingDeclaration::JsDefaultImportSpecifier(_)
| AnyJsBindingDeclaration::JsNamespaceImportSpecifier(_)
| AnyJsBindingDeclaration::TsImportEqualsDeclaration(_) => {
unreachable!()
}
}
}
// Find the function that is calling the hook
fn function_of_hook_call(call: &JsCallExpression) -> Option<JsSyntaxNode> {
call.syntax().ancestors().find(|x| {
matches!(
x.kind(),
JsSyntaxKind::JS_FUNCTION_DECLARATION
| JsSyntaxKind::JS_FUNCTION_EXPORT_DEFAULT_DECLARATION
| JsSyntaxKind::JS_FUNCTION_EXPRESSION
| JsSyntaxKind::JS_ARROW_FUNCTION_EXPRESSION
)
})
}
impl Rule for UseExhaustiveDependencies {
type Query = Semantic<JsCallExpression>;
type State = Fix;
type Signals = Vec<Self::State>;
type Options = HooksOptions;
fn run(ctx: &RuleContext<Self>) -> Vec<Self::State> {
let options = ctx.options();
let options = ReactExtensiveDependenciesOptions::new(options.clone());
let mut signals = vec![];
let call = ctx.query();
let model = ctx.model();
if let Some(result) = react_hook_with_dependency(call, &options.hooks_config, model) {
let Some(component_function) = function_of_hook_call(call) else {
return vec![]
};
let component_function_range = component_function.text_range();
let captures: Vec<_> = result
.all_captures(model)
.filter_map(|capture| {
capture_needs_to_be_in_the_dependency_list(
capture,
&component_function_range,
model,
&options,
)
})
.map(|capture| {
let path = get_whole_static_member_expression(capture.node());
let (text, range) = if let Some(path) = path {
(
path.syntax().text_trimmed().to_string(),
path.syntax().text_trimmed_range(),
)
} else {
(
capture.node().text_trimmed().to_string(),
capture.node().text_trimmed_range(),
)
};
(text, range, capture)
})
.collect();
let deps: Vec<(String, TextRange)> = result
.all_dependencies()
.map(|dep| {
(
dep.syntax().text_trimmed().to_string(),
dep.syntax().text_trimmed_range(),
)
})
.collect();
let mut add_deps: BTreeMap<String, Vec<TextRange>> = BTreeMap::new();
let mut remove_deps: Vec<TextRange> = vec![];
// Evaluate all the captures
for (capture_text, capture_range, _) in captures.iter() {
let mut suggested_fix = None;
let mut is_captured_covered = false;
for (dependency_text, dependency_range) in deps.iter() {
let capture_deeper_than_dependency = capture_text.starts_with(dependency_text);
let dependency_deeper_than_capture = dependency_text.starts_with(capture_text);
match (
capture_deeper_than_dependency,
dependency_deeper_than_capture,
) {
// capture == dependency
(true, true) => {
suggested_fix = None;
is_captured_covered = true;
break;
}
// example
// capture: a.b.c
// dependency: a
// this is ok, but we may suggest performance improvements
// in the future
(true, false) => {
// We need to continue, because it may still have a perfect match
// in the dependency list
is_captured_covered = true;
}
// example
// capture: a.b
// dependency: a.b.c
// This can be valid in some cases. We will flag an error nonetheless.
(false, true) => {
// We need to continue, because it may still have a perfect match
// in the dependency list
suggested_fix = Some(Fix::DependencyTooDeep {
function_name_range: result.function_name_range,
capture_range: *capture_range,
dependency_range: *dependency_range,
});
}
_ => {}
}
}
if let Some(fix) = suggested_fix {
signals.push(fix);
}
if !is_captured_covered {
let captures = add_deps.entry(capture_text.clone()).or_default();
captures.push(*capture_range);
}
}
// Search for dependencies not captured
for (dependency_text, dep_range) in deps {
let mut covers_any_capture = false;
for (capture_text, _, _) in captures.iter() {
let capture_deeper_dependency = capture_text.starts_with(&dependency_text);
let dependency_deeper_capture = dependency_text.starts_with(capture_text);
if capture_deeper_dependency || dependency_deeper_capture {
covers_any_capture = true;
break;
}
}
if !covers_any_capture {
remove_deps.push(dep_range);
}
}
// Generate signals
for (_, captures) in add_deps {
signals.push(Fix::AddDependency(result.function_name_range, captures));
}
if !remove_deps.is_empty() {
signals.push(Fix::RemoveDependency(
result.function_name_range,
remove_deps,
));
}
}
signals
}
fn diagnostic(_: &RuleContext<Self>, dep: &Self::State) -> Option<RuleDiagnostic> {
match dep {
Fix::AddDependency(use_effect_range, captures) => {
let mut diag = RuleDiagnostic::new(
rule_category!(),
use_effect_range,
markup! {
"This hook do not specify all of its dependencies."
},
);
for range in captures.iter() {
diag = diag.detail(
range,
"This dependency is not specified in the hook dependency list.",
);
}
Some(diag)
}
Fix::RemoveDependency(use_effect_range, ranges) => {
let mut diag = RuleDiagnostic::new(
rule_category!(),
use_effect_range,
markup! {
"This hook specifies more dependencies than necessary."
},
);
for range in ranges.iter() {
diag = diag.detail(range, "This dependency can be removed from the list.");
}
Some(diag)
}
Fix::DependencyTooDeep {
function_name_range,
capture_range,
dependency_range,
} => {
let diag = RuleDiagnostic::new(
rule_category!(),
function_name_range,
markup! {
"This hook specifies a dependency more specific that its captures"
},
)
.detail(capture_range, "This capture is more generic than...")
.detail(dependency_range, "...this dependency.");
Some(diag)
}
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/nursery/use_hook_at_top_level.rs | crates/rome_js_analyze/src/semantic_analyzers/nursery/use_hook_at_top_level.rs | use super::use_exhaustive_dependencies::ReactExtensiveDependenciesOptions;
use crate::semantic_analyzers::nursery::use_exhaustive_dependencies::HooksOptions;
use crate::{react::hooks::react_hook_configuration, semantic_services::Semantic};
use rome_analyze::{context::RuleContext, declare_rule, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_semantic::CallsExtensions;
use rome_js_syntax::{AnyJsFunction, JsCallExpression, JsFunctionBody, JsSyntaxKind, TextRange};
use rome_rowan::AstNode;
declare_rule! {
/// Enforce that all React hooks are being called from the Top Level
/// component functions.
///
/// To understand why this required see https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// function Component1({ a }) {
/// if (a == 1) {
/// useEffect();
/// }
/// }
/// ```
///
/// ## Valid
///
/// ```js
/// function Component1() {
/// useEffect();
/// }
/// ```
///
/// ## Options
///
/// Allows to specify custom hooks - from libraries or internal projects - that can be considered stable.
///
/// ```json
/// {
/// "//": "...",
/// "options": {
/// "hooks": [
/// { "name": "useLocation", "closureIndex": 0, "dependenciesIndex": 1},
/// { "name": "useQuery", "closureIndex": 1, "dependenciesIndex": 0}
/// ]
/// }
/// }
/// ```
///
/// Given the previous example, your hooks be used like this:
///
/// ```js
/// function Foo() {
/// const location = useLocation(() => {}, []);
/// const query = useQuery([], () => {});
/// }
/// ```
///
pub(crate) UseHookAtTopLevel {
version: "12.0.0",
name: "useHookAtTopLevel",
recommended: false,
}
}
pub enum Suggestion {
None {
hook_name_range: TextRange,
path: Vec<TextRange>,
},
}
// Verify if the call expression is at the top level
// of the component
fn enclosing_function_if_call_is_at_top_level(call: &JsCallExpression) -> Option<AnyJsFunction> {
let next = call.syntax().ancestors().find(|x| {
!matches!(
x.kind(),
JsSyntaxKind::JS_STATEMENT_LIST
| JsSyntaxKind::JS_BLOCK_STATEMENT
| JsSyntaxKind::JS_VARIABLE_STATEMENT
| JsSyntaxKind::JS_EXPRESSION_STATEMENT
| JsSyntaxKind::JS_RETURN_STATEMENT
| JsSyntaxKind::JS_CALL_EXPRESSION
| JsSyntaxKind::JS_CALL_ARGUMENT_LIST
| JsSyntaxKind::JS_CALL_ARGUMENTS
| JsSyntaxKind::JS_STATIC_MEMBER_EXPRESSION
| JsSyntaxKind::JS_INITIALIZER_CLAUSE
| JsSyntaxKind::JS_VARIABLE_DECLARATOR
| JsSyntaxKind::JS_VARIABLE_DECLARATOR_LIST
| JsSyntaxKind::JS_VARIABLE_DECLARATION
| JsSyntaxKind::TS_AS_EXPRESSION
| JsSyntaxKind::TS_SATISFIES_EXPRESSION
)
});
next.and_then(JsFunctionBody::cast)
.and_then(|body| body.parent::<AnyJsFunction>())
}
#[derive(Debug)]
pub struct CallPath {
call: JsCallExpression,
path: Vec<TextRange>,
}
impl Rule for UseHookAtTopLevel {
type Query = Semantic<JsCallExpression>;
type State = Suggestion;
type Signals = Option<Self::State>;
type Options = HooksOptions;
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let options = ctx.options();
let options = ReactExtensiveDependenciesOptions::new(options.clone());
let call = ctx.query();
let hook_name_range = call.callee().ok()?.syntax().text_trimmed_range();
if react_hook_configuration(call, &options.hooks_config).is_some() {
let model = ctx.model();
let root = CallPath {
call: call.clone(),
path: vec![],
};
let mut calls = vec![root];
while let Some(CallPath { call, path }) = calls.pop() {
let range = call.syntax().text_range();
let mut path = path.clone();
path.push(range);
if let Some(enclosing_function) = enclosing_function_if_call_is_at_top_level(&call)
{
if let Some(calls_iter) = enclosing_function.all_calls(model) {
for call in calls_iter {
calls.push(CallPath {
call: call.tree(),
path: path.clone(),
});
}
}
} else {
return Some(Suggestion::None {
hook_name_range,
path,
});
}
}
}
None
}
fn diagnostic(_: &RuleContext<Self>, suggestion: &Self::State) -> Option<RuleDiagnostic> {
match suggestion {
Suggestion::None {
hook_name_range,
path,
} => {
let call_deep = path.len() - 1;
let mut diag = if call_deep == 0 {
RuleDiagnostic::new(
rule_category!(),
hook_name_range,
markup! {
"This hook is being called conditionally, but all hooks must be called in the exact same order in every component render."
},
)
} else {
RuleDiagnostic::new(
rule_category!(),
hook_name_range,
markup! {
"This hook is being called indirectly and conditionally, but all hooks must be called in the exact same order in every component render."
},
)
};
for (i, range) in path.iter().skip(1).enumerate() {
let msg = if i == 0 {
markup! {
"This is the call path until the hook."
}
} else {
markup! {}
};
diag = diag.detail(range, msg);
}
let diag = diag.note(
markup! {
"For React to preserve state between calls, hooks needs to be called unconditionally and always in the same order."
},
).note(
markup! {
"See https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level"
},
);
Some(diag)
}
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/nursery/use_naming_convention.rs | crates/rome_js_analyze/src/semantic_analyzers/nursery/use_naming_convention.rs | use std::str::FromStr;
use crate::{
control_flow::AnyJsControlFlowRoot,
semantic_services::Semantic,
utils::case::Case,
utils::rename::{AnyJsRenamableDeclaration, RenameSymbolExtensions},
JsRuleAction,
};
use bpaf::Bpaf;
use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_deserialize::{
json::{has_only_known_keys, with_only_known_variants, VisitJsonNode},
DeserializationDiagnostic, VisitNode,
};
use rome_diagnostics::Applicability;
use rome_js_semantic::CanBeImportedExported;
use rome_js_syntax::{
binding_ext::AnyJsBindingDeclaration, inner_string_text, AnyJsClassMember, AnyJsObjectMember,
AnyJsVariableDeclaration, AnyTsTypeMember, JsIdentifierBinding, JsLiteralExportName,
JsLiteralMemberName, JsPrivateClassMemberName, JsSyntaxKind, JsSyntaxToken,
JsVariableDeclarator, JsVariableKind, TsEnumMember, TsIdentifierBinding, TsTypeParameterName,
};
use rome_js_unicode_table::is_js_ident;
use rome_json_syntax::JsonLanguage;
use rome_rowan::{
declare_node_union, AstNode, AstNodeList, BatchMutationExt, SyntaxNode, SyntaxResult, TokenText,
};
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
#[cfg(feature = "schemars")]
use schemars::JsonSchema;
declare_rule! {
/// Enforce naming conventions for everything across a codebase.
///
/// Enforcing [naming conventions](https://en.wikipedia.org/wiki/Naming_convention_(programming)) helps to keep the codebase consistent,
/// and reduces overhead when thinking about the name [case] of a variable.
///
/// ## Naming conventions
///
/// All names can be prefixed and suffixed by underscores `_` and dollar signs `$`.
///
/// ### Variable names
///
/// All variables, including function parameters and catch parameters, are in [`camelCase`].
///
/// Additionally, top-level variables declared as `const` or `var` may be in [`CONSTANT_CASE`] or [`PascalCase`].
/// Top-level variables are declared at module or script level.
/// Variables declared in a TypeScript `module` or `namespace` are also considered top-level.
///
/// ```js
/// function f(param, _unusedParam) {
/// let localValue = 0;
/// try {
/// /* ... */
/// } catch (customError) {
/// /* ... */
/// }
/// }
///
/// export const A_CONSTANT = 5;
///
/// export const Person = class {}
///
/// let aVariable = 0;
///
/// export namespace ns {
/// export const ANOTHER_CONSTANT = "";
/// }
/// ```
///
/// Examples of incorrect names:
///
/// ```js,expect_diagnostic
/// let a_value = 0;
/// ```
///
/// ```js,expect_diagnostic
/// function f(FirstParam) {}
/// ```
///
/// ### Function names
///
/// A `function` name is in [`camelCase`] or [`PascalCase`].
///
/// ```jsx
/// function trimString(s) { /*...*/ }
///
/// function Component() {
/// return <div></div>;
/// }
/// ```
///
/// ### TypeScript `enum` names
///
/// A _TypeScript_ `enum` name is in [`PascalCase`].
///
/// `enum` members are by default in [`PascalCase`].
/// However, you can configure the [case] of `enum` members.
/// See [options](#options) for more details.
///
/// ```ts
/// enum Status {
/// Open,
/// Close,
/// }
/// ```
///
/// ### Classes
///
/// - A class name is in [`PascalCase`].
///
/// - A static property name and a static getter name are in [`camelCase`] or [`CONSTANT_CASE`].
///
/// - A class property name and a class method name are in [`camelCase`].
///
/// ```js
/// class Person {
/// static MAX_FRIEND_COUNT = 256;
///
/// static get SPECIAL_PERSON_INSTANCE() { /*...*/ }
///
/// initializedProperty = 0;
///
/// specialMethod() {}
/// }
/// ```
///
/// ### TypeScript `type` aliases and `interface`
///
/// - A `type` alias and an interface name are in [`PascalCase`].
///
/// - A property name and a method name in a type or interface are in [`camelCase`] or [`CONSTANT_CASE`].
///
/// - A `readonly` property name and a getter name can also be in [`CONSTANT_CASE`].
///
/// ```ts
/// type Named = {
/// readonly fullName: string;
///
/// specialMethod(): void;
/// };
///
/// interface Named {
/// readonly fullName: string;
///
/// specialMethod(): void;
/// }
///
/// interface PersonConstructor {
/// readonly MAX_FRIEND_COUNT: number;
///
/// get SPECIAL_PERSON_INSTANCE(): Person;
///
/// new(): Person;
/// }
/// ```
///
/// Examples of an incorrect type alias:
///
/// ```ts,expect_diagnostic
/// type person = { fullName: string };
/// ```
///
/// ### Literal object property and method names
///
/// Literal object property and method names are in [`camelCase`].
///
/// ```js
/// const alice = {
/// fullName: "Alice",
/// }
/// ```
///
/// Example of an incorrect name:
///
/// ```js,expect_diagnostic
/// const alice = {
/// FULL_NAME: "Alice",
/// }
/// ```
///
/// ### Imported and exported module aliases
///
/// Imported and exported module aliases are in [`camelCase`].
///
/// ```js
/// import * as myLib from "my-lib";
///
/// export * as myLib from "my-lib";
/// ```
///
/// `import` and `export` aliases are in [`camelCase`], [`PascalCase`], or [`CONSTANT_CASE`]:
///
/// ```js
/// import assert, {
/// deepStrictEqual as deepEqual,
/// AssertionError as AssertError
/// } from "node:assert";
/// ```
///
/// Examples of an incorrect name:
///
/// ```ts,expect_diagnostic
/// import * as MyLib from "my-lib";
/// ```
///
/// ### TypeScript type parameter names
///
/// A _TypeScript_ type parameter name is in [`PascalCase`].
///
/// ```ts
/// function id<Val>(value: Val): Val { /* ... */}
/// ```
///
/// ### TypeScript `namespace` names
///
/// A _TypeScript_ `namespace` name is in [`camelCase`] or in [`PascalCase`].
///
/// ```ts
/// namespace mathExtra {
/// /*...*/
/// }
///
/// namespace MathExtra {
/// /*...*/
/// }
/// ```
///
/// ## Options
///
/// The rule provides two options that are detailed in the following subsections.
///
/// ```json
/// {
/// "//": "...",
/// "options": {
/// "strictCase": false,
/// "enumMemberCase": "CONSTANT_CASE"
/// }
/// }
/// ```
///
/// ### strictCase
///
/// When this option is set to `true`, it forbids consecutive uppercase characters in [`camelCase`] and [`PascalCase`].
/// For instance, when the option is set to `true`, `HTTPServer` or `aHTTPServer` will throw an error.
/// These names should be renamed to `HttpServer` and `aHttpServer`
///
/// When the option is set to `false`, consecutive uppercase characters are allowed.
/// `HTTPServer` and `aHTTPServer` are so valid.
///
/// Default: `true`
///
/// ### enumMemberCase
///
/// By default, the rule enforces the naming convention followed by the [TypeScript Compiler team](https://www.typescriptlang.org/docs/handbook/enums.html):
/// an `enum` member has to be in [`PascalCase`].
///
/// You can enforce another convention by setting `enumMemberCase` option.
/// The supported cases are: [`PascalCase`], [`CONSTANT_CASE`], and [`camelCase`].
///
/// [case]: https://en.wikipedia.org/wiki/Naming_convention_(programming)#Examples_of_multiple-word_identifier_formats
/// [`camelCase`]: https://en.wikipedia.org/wiki/Camel_case
/// [`PascalCase`]: https://en.wikipedia.org/wiki/Camel_case
/// [`CONSTANT_CASE`]: https://en.wikipedia.org/wiki/Snake_case
pub(crate) UseNamingConvention {
version: "next",
name: "useNamingConvention",
recommended: false,
}
}
impl Rule for UseNamingConvention {
type Query = Semantic<AnyIdentifierBindingLike>;
type State = State;
type Signals = Option<Self::State>;
type Options = NamingConventionOptions;
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let options = ctx.options();
let element = Named::from_name(node)?;
let allowed_cases = element.allowed_cases(options);
if allowed_cases.is_empty() {
// No naming convention to verify.
return None;
}
let name = node.name().ok()?;
let name = name.text();
if !is_js_ident(name) {
// ignore non-identifier strings
return None;
}
let trimmed_name = trim_underscore_dollar(name);
let actual_case = Case::identify(trimmed_name, options.strict_case);
if trimmed_name.is_empty()
|| allowed_cases
.iter()
.any(|&expected_style| actual_case.is_compatible_with(expected_style))
{
// Valid case
return None;
}
let preferred_case = element.allowed_cases(ctx.options())[0];
let new_trimmed_name = preferred_case.convert(trimmed_name);
let suggested_name = name.replace(trimmed_name, &new_trimmed_name);
Some(State {
element,
suggested_name,
})
}
fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let State {
element,
suggested_name,
} = state;
let name = ctx.query().name().ok()?;
let name = name.text();
let trimmed_name = trim_underscore_dollar(name);
let allowed_cases = element.allowed_cases(ctx.options());
let allowed_case_names = allowed_cases
.iter()
.map(|style| style.to_string())
.collect::<SmallVec<[_; 3]>>()
.join(" or ");
let trimmed_info = if name != trimmed_name {
markup! {" trimmed as `"{trimmed_name}"`"}.to_owned()
} else {
markup! {""}.to_owned()
};
Some(RuleDiagnostic::new(
rule_category!(),
ctx.query().syntax().text_trimmed_range(),
markup! {
"This "<Emphasis>{element.to_string()}</Emphasis>" name"{trimmed_info}" should be in "<Emphasis>{allowed_case_names}</Emphasis>"."
},
).note(markup! {
"The name could be renamed to `"{suggested_name}"`."
}))
}
fn action(ctx: &RuleContext<Self>, state: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let model = ctx.model();
let mut mutation = ctx.root().begin();
let State {
element,
suggested_name,
} = state;
let renamable = match node {
AnyIdentifierBindingLike::JsIdentifierBinding(binding) => {
if binding.is_exported(model) {
return None;
}
if let Some(AnyJsBindingDeclaration::TsPropertyParameter(_)) = binding.declaration()
{
// Property parameters are also class properties.
return None;
}
Some(AnyJsRenamableDeclaration::JsIdentifierBinding(
binding.clone(),
))
}
AnyIdentifierBindingLike::TsIdentifierBinding(binding) => {
if binding.is_exported(model) {
return None;
}
Some(AnyJsRenamableDeclaration::TsIdentifierBinding(
binding.clone(),
))
}
_ => None,
};
if let Some(renamable) = renamable {
let preferred_case = element.allowed_cases(ctx.options())[0];
let renamed = mutation.rename_any_renamable_node(model, renamable, &suggested_name[..]);
if renamed {
return Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::Always,
message: markup! { "Rename this symbol in "<Emphasis>{preferred_case.to_string()}</Emphasis>"." }.to_owned(),
mutation,
});
}
}
None
}
}
declare_node_union! {
/// Ast nodes that defines a name.
pub(crate) AnyIdentifierBindingLike =
JsIdentifierBinding |
JsLiteralMemberName |
JsPrivateClassMemberName |
JsLiteralExportName |
TsIdentifierBinding |
TsTypeParameterName
}
impl AnyIdentifierBindingLike {
fn name_token(&self) -> SyntaxResult<JsSyntaxToken> {
match self {
AnyIdentifierBindingLike::JsIdentifierBinding(binding) => binding.name_token(),
AnyIdentifierBindingLike::JsLiteralMemberName(member_name) => member_name.value(),
AnyIdentifierBindingLike::JsPrivateClassMemberName(member_name) => {
member_name.id_token()
}
AnyIdentifierBindingLike::JsLiteralExportName(export_name) => export_name.value(),
AnyIdentifierBindingLike::TsIdentifierBinding(binding) => binding.name_token(),
AnyIdentifierBindingLike::TsTypeParameterName(type_parameter) => {
type_parameter.ident_token()
}
}
}
fn name(&self) -> SyntaxResult<TokenText> {
Ok(inner_string_text(&self.name_token()?))
}
}
#[derive(Debug)]
pub(crate) struct State {
element: Named,
suggested_name: String,
}
/// Rule's options.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, Bpaf)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct NamingConventionOptions {
/// If `false`, then consecutive uppercase are allowed in _camel_ and _pascal_ cases.
/// This does not affect other [Case].
#[bpaf(hide)]
#[serde(
default = "default_strict_case",
skip_serializing_if = "is_default_strict_case"
)]
pub strict_case: bool,
/// Allowed cases for _TypeScript_ `enum` member names.
#[bpaf(hide)]
#[serde(default, skip_serializing_if = "is_default")]
pub enum_member_case: EnumMemberCase,
}
const fn default_strict_case() -> bool {
true
}
const fn is_default_strict_case(strict_case: &bool) -> bool {
*strict_case == default_strict_case()
}
fn is_default<T: Default + Eq>(value: &T) -> bool {
value == &T::default()
}
impl NamingConventionOptions {
pub(crate) const KNOWN_KEYS: &'static [&'static str] = &["strictCase", "enumMemberCase"];
}
impl Default for NamingConventionOptions {
fn default() -> Self {
Self {
strict_case: default_strict_case(),
enum_member_case: EnumMemberCase::default(),
}
}
}
// Required by [Bpaf].
impl FromStr for NamingConventionOptions {
type Err = &'static str;
fn from_str(_s: &str) -> Result<Self, Self::Err> {
// WARNING: should not be used.
Ok(Self::default())
}
}
impl VisitJsonNode for NamingConventionOptions {}
impl VisitNode<JsonLanguage> for NamingConventionOptions {
fn visit_member_name(
&mut self,
node: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
has_only_known_keys(node, Self::KNOWN_KEYS, diagnostics)
}
fn visit_map(
&mut self,
key: &SyntaxNode<JsonLanguage>,
value: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
let (name, value) = self.get_key_and_value(key, value, diagnostics)?;
let name_text = name.text();
match name_text {
"strictCase" => {
self.strict_case = self.map_to_boolean(&value, name_text, diagnostics)?
}
"enumMemberCase" => {
let mut enum_member_case = EnumMemberCase::default();
self.map_to_known_string(&value, name_text, &mut enum_member_case, diagnostics)?;
self.enum_member_case = enum_member_case;
}
_ => (),
}
Some(())
}
}
/// Supported cases for TypeScript `enum` member names.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum EnumMemberCase {
/// PascalCase
#[serde(rename = "PascalCase")]
#[default]
Pascal,
/// CONSTANT_CASE
#[serde(rename = "CONSTANT_CASE")]
Constant,
/// camelCase
#[serde(rename = "camelCase")]
Camel,
}
impl EnumMemberCase {
pub const KNOWN_VALUES: &'static [&'static str] = &["camelCase", "CONSTANT_CASE", "PascalCase"];
}
/// Required by [Bpaf].
impl FromStr for EnumMemberCase {
type Err = &'static str;
fn from_str(_s: &str) -> Result<Self, Self::Err> {
// WARNING: should not be used.
Ok(EnumMemberCase::default())
}
}
impl VisitNode<JsonLanguage> for EnumMemberCase {
fn visit_member_value(
&mut self,
node: &SyntaxNode<JsonLanguage>,
diagnostics: &mut Vec<DeserializationDiagnostic>,
) -> Option<()> {
let node = with_only_known_variants(node, Self::KNOWN_VALUES, diagnostics)?;
match node.inner_string_text().ok()?.text() {
"PascalCase" => *self = Self::Pascal,
"CONSTANT_CASE" => *self = Self::Constant,
"camelCase" => *self = Self::Camel,
_ => (),
}
Some(())
}
}
impl From<EnumMemberCase> for Case {
fn from(case: EnumMemberCase) -> Case {
match case {
EnumMemberCase::Pascal => Case::Pascal,
EnumMemberCase::Constant => Case::Constant,
EnumMemberCase::Camel => Case::Camel,
}
}
}
/// Named elements with an attached naming convention.
///
/// [Named::from_name] enables to get the element from an [AnyName].
/// [Named::allowed_cases] enables to get a list of allowed cases for a given element.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
enum Named {
CatchParameter,
Class,
ClassGetter,
ClassMethod,
ClassProperty,
ClassSetter,
ClassStaticGetter,
ClassStaticMethod,
ClassStaticProperty,
ClassStaticSetter,
Enum,
EnumMember,
ExportAlias,
ExportSource,
Function,
FunctionParameter,
ImportAlias,
ImportNamespace,
ImportSource,
IndexParameter,
Interface,
LocalConst,
LocalLet,
LocalVar,
LocalUsing,
Namespace,
ObjectGetter,
ObjectMethod,
ObjectProperty,
ObjectSetter,
ParameterProperty,
TopLevelConst,
TopLevelLet,
TopLevelVar,
TypeAlias,
TypeGetter,
TypeMethod,
TypeProperty,
TypeReadonlyProperty,
TypeSetter,
TypeParameter,
}
impl Named {
fn from_name(js_name: &AnyIdentifierBindingLike) -> Option<Named> {
match js_name {
AnyIdentifierBindingLike::JsIdentifierBinding(binding) => {
Named::from_binding_declaration(&binding.declaration()?)
}
AnyIdentifierBindingLike::TsIdentifierBinding(binding) => {
Named::from_binding_declaration(&binding.declaration()?)
}
AnyIdentifierBindingLike::JsLiteralMemberName(member_name) => {
if let Some(member) = member_name.parent::<AnyJsClassMember>() {
Named::from_class_member(&member)
} else if let Some(member) = member_name.parent::<AnyTsTypeMember>() {
Named::from_type_member(&member)
} else if let Some(member) = member_name.parent::<AnyJsObjectMember>() {
Named::from_object_member(&member)
} else if member_name.parent::<TsEnumMember>().is_some() {
Some(Named::EnumMember)
} else {
None
}
}
AnyIdentifierBindingLike::JsPrivateClassMemberName(member_name) => {
Named::from_class_member(&member_name.parent::<AnyJsClassMember>()?)
}
AnyIdentifierBindingLike::JsLiteralExportName(export_name) => {
match export_name.syntax().parent()?.kind() {
JsSyntaxKind::JS_NAMED_IMPORT_SPECIFIER => Some(Named::ImportSource),
JsSyntaxKind::JS_EXPORT_NAMED_FROM_SPECIFIER => Some(Named::ExportSource),
JsSyntaxKind::JS_EXPORT_NAMED_SPECIFIER | JsSyntaxKind::JS_EXPORT_AS_CLAUSE => {
Some(Named::ExportAlias)
}
_ => None,
}
}
AnyIdentifierBindingLike::TsTypeParameterName(_) => Some(Named::TypeParameter),
}
}
fn from_class_member(member: &AnyJsClassMember) -> Option<Named> {
match member {
AnyJsClassMember::JsBogusMember(_)
| AnyJsClassMember::JsConstructorClassMember(_)
| AnyJsClassMember::TsConstructorSignatureClassMember(_)
| AnyJsClassMember::JsEmptyClassMember(_)
| AnyJsClassMember::JsStaticInitializationBlockClassMember(_) => None,
AnyJsClassMember::TsIndexSignatureClassMember(_) => Some(Named::IndexParameter),
AnyJsClassMember::JsGetterClassMember(getter) => {
let is_static = getter
.modifiers()
.iter()
.any(|modifier| modifier.as_js_static_modifier().is_some());
Some(if is_static {
Named::ClassStaticGetter
} else {
Named::ClassGetter
})
}
AnyJsClassMember::TsGetterSignatureClassMember(getter) => {
let is_static = getter
.modifiers()
.iter()
.any(|modifier| modifier.as_js_static_modifier().is_some());
Some(if is_static {
Named::ClassStaticGetter
} else {
Named::ClassGetter
})
}
AnyJsClassMember::JsMethodClassMember(method) => {
let is_static = method
.modifiers()
.iter()
.any(|modifier| modifier.as_js_static_modifier().is_some());
Some(if is_static {
Named::ClassStaticMethod
} else {
Named::ClassMethod
})
}
AnyJsClassMember::TsMethodSignatureClassMember(method) => {
let is_static = method
.modifiers()
.iter()
.any(|modifier| modifier.as_js_static_modifier().is_some());
Some(if is_static {
Named::ClassStaticMethod
} else {
Named::ClassMethod
})
}
AnyJsClassMember::JsPropertyClassMember(property) => {
let is_static = property
.modifiers()
.iter()
.any(|modifier| modifier.as_js_static_modifier().is_some());
Some(if is_static {
Named::ClassStaticProperty
} else {
Named::ClassProperty
})
}
AnyJsClassMember::TsPropertySignatureClassMember(property) => {
let is_static = property
.modifiers()
.iter()
.any(|modifier| modifier.as_js_static_modifier().is_some());
Some(if is_static {
Named::ClassStaticProperty
} else {
Named::ClassProperty
})
}
AnyJsClassMember::TsInitializedPropertySignatureClassMember(property) => {
let is_static = property
.modifiers()
.iter()
.any(|modifier| modifier.as_js_static_modifier().is_some());
Some(if is_static {
Named::ClassStaticProperty
} else {
Named::ClassProperty
})
}
AnyJsClassMember::JsSetterClassMember(setter) => {
let is_static = setter
.modifiers()
.iter()
.any(|modifier| modifier.as_js_static_modifier().is_some());
Some(if is_static {
Named::ClassStaticSetter
} else {
Named::ClassSetter
})
}
AnyJsClassMember::TsSetterSignatureClassMember(setter) => {
let is_static = setter
.modifiers()
.iter()
.any(|modifier| modifier.as_js_static_modifier().is_some());
Some(if is_static {
Named::ClassStaticSetter
} else {
Named::ClassSetter
})
}
}
}
fn from_binding_declaration(decl: &AnyJsBindingDeclaration) -> Option<Named> {
match decl {
AnyJsBindingDeclaration::JsVariableDeclarator(var) => {
Named::from_variable_declarator(var)
}
AnyJsBindingDeclaration::JsBogusParameter(_)
| AnyJsBindingDeclaration::JsFormalParameter(_)
| AnyJsBindingDeclaration::JsRestParameter(_) => Some(Named::FunctionParameter),
AnyJsBindingDeclaration::JsCatchDeclaration(_) => Some(Named::CatchParameter),
AnyJsBindingDeclaration::TsPropertyParameter(_) => Some(Named::ParameterProperty),
AnyJsBindingDeclaration::TsIndexSignatureParameter(_) => Some(Named::IndexParameter),
AnyJsBindingDeclaration::JsNamespaceImportSpecifier(_)
| AnyJsBindingDeclaration::JsImportNamespaceClause(_) => Some(Named::ImportNamespace),
AnyJsBindingDeclaration::JsFunctionDeclaration(_)
| AnyJsBindingDeclaration::JsFunctionExpression(_)
| AnyJsBindingDeclaration::JsFunctionExportDefaultDeclaration(_)
| AnyJsBindingDeclaration::TsDeclareFunctionDeclaration(_)
| AnyJsBindingDeclaration::TsDeclareFunctionExportDefaultDeclaration(_) => {
Some(Named::Function)
}
AnyJsBindingDeclaration::JsImportDefaultClause(_)
| AnyJsBindingDeclaration::TsImportEqualsDeclaration(_)
| AnyJsBindingDeclaration::JsDefaultImportSpecifier(_)
| AnyJsBindingDeclaration::JsNamedImportSpecifier(_) => Some(Named::ImportAlias),
AnyJsBindingDeclaration::TsModuleDeclaration(_) => Some(Named::Namespace),
AnyJsBindingDeclaration::TsTypeAliasDeclaration(_) => Some(Named::TypeAlias),
AnyJsBindingDeclaration::JsClassDeclaration(_)
| AnyJsBindingDeclaration::JsClassExpression(_)
| AnyJsBindingDeclaration::JsClassExportDefaultDeclaration(_) => Some(Named::Class),
AnyJsBindingDeclaration::TsInterfaceDeclaration(_) => Some(Named::Interface),
AnyJsBindingDeclaration::TsEnumDeclaration(_) => Some(Named::Enum),
AnyJsBindingDeclaration::JsShorthandNamedImportSpecifier(_) => {
Some(Named::ImportSource)
}
AnyJsBindingDeclaration::JsBogusNamedImportSpecifier(_) => None,
}
}
fn from_variable_declarator(var: &JsVariableDeclarator) -> Option<Named> {
let is_top_level_level = matches!(
var.syntax()
.ancestors()
.find_map(AnyJsControlFlowRoot::cast),
Some(AnyJsControlFlowRoot::JsModule(_)) | Some(AnyJsControlFlowRoot::JsScript(_))
);
let var_declaration = var
.syntax()
.ancestors()
.find_map(AnyJsVariableDeclaration::cast)?;
let var_kind = var_declaration.variable_kind().ok()?;
Some(match (var_kind, is_top_level_level) {
(JsVariableKind::Const, false) => Named::LocalConst,
(JsVariableKind::Let, false) => Named::LocalLet,
(JsVariableKind::Var, false) => Named::LocalVar,
(JsVariableKind::Using, false) => Named::LocalUsing,
(JsVariableKind::Const, true) => Named::TopLevelConst,
(JsVariableKind::Let, true) => Named::TopLevelLet,
(JsVariableKind::Var, true) => Named::TopLevelVar,
(JsVariableKind::Using, true) => Named::LocalUsing,
})
}
fn from_object_member(member: &AnyJsObjectMember) -> Option<Named> {
match member {
AnyJsObjectMember::JsBogusMember(_) | AnyJsObjectMember::JsSpread(_) => None,
AnyJsObjectMember::JsGetterObjectMember(_) => Some(Named::ObjectGetter),
AnyJsObjectMember::JsMethodObjectMember(_) => Some(Named::ObjectMethod),
AnyJsObjectMember::JsPropertyObjectMember(_)
| AnyJsObjectMember::JsShorthandPropertyObjectMember(_) => Some(Named::ObjectProperty),
AnyJsObjectMember::JsSetterObjectMember(_) => Some(Named::ObjectSetter),
}
}
fn from_type_member(member: &AnyTsTypeMember) -> Option<Named> {
match member {
AnyTsTypeMember::JsBogusMember(_)
| AnyTsTypeMember::TsCallSignatureTypeMember(_)
| AnyTsTypeMember::TsConstructSignatureTypeMember(_) => None,
AnyTsTypeMember::TsIndexSignatureTypeMember(_) => Some(Named::IndexParameter),
AnyTsTypeMember::TsGetterSignatureTypeMember(_) => Some(Named::TypeGetter),
AnyTsTypeMember::TsMethodSignatureTypeMember(_) => Some(Named::TypeMethod),
AnyTsTypeMember::TsPropertySignatureTypeMember(property) => {
Some(if property.readonly_token().is_some() {
Named::TypeReadonlyProperty
} else {
Named::TypeProperty
})
}
AnyTsTypeMember::TsSetterSignatureTypeMember(_) => Some(Named::TypeSetter),
}
}
/// Returns the list of allowed [Case] for `self`.
/// The preferred case comes first in the list.
fn allowed_cases(self, options: &NamingConventionOptions) -> SmallVec<[Case; 3]> {
match self {
Named::CatchParameter
| Named::ClassGetter
| Named::ClassMethod
| Named::ClassProperty
| Named::ClassSetter
| Named::ClassStaticMethod
| Named::ClassStaticSetter
| Named::FunctionParameter
| Named::ImportNamespace
| Named::IndexParameter
| Named::LocalConst
| Named::LocalLet
| Named::LocalVar
| Named::LocalUsing
| Named::ObjectGetter
| Named::ObjectMethod
| Named::ObjectProperty
| Named::ObjectSetter
| Named::ParameterProperty
| Named::TopLevelLet
| Named::TypeMethod
| Named::TypeProperty
| Named::TypeSetter => SmallVec::from_slice(&[Case::Camel]),
Named::Class
| Named::Enum
| Named::Interface
| Named::TypeAlias
| Named::TypeParameter => SmallVec::from_slice(&[Case::Pascal]),
Named::ClassStaticGetter
| Named::ClassStaticProperty
| Named::TypeReadonlyProperty
| Named::TypeGetter => SmallVec::from_slice(&[Case::Camel, Case::Constant]),
Named::EnumMember => SmallVec::from_slice(&[options.enum_member_case.into()]),
Named::ExportAlias | Named::ImportAlias | Named::TopLevelConst | Named::TopLevelVar => {
SmallVec::from_slice(&[Case::Camel, Case::Pascal, Case::Constant])
}
Named::ExportSource | Named::ImportSource => SmallVec::new(),
Named::Function | Named::Namespace => {
SmallVec::from_slice(&[Case::Camel, Case::Pascal])
}
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/security/no_dangerously_set_inner_html_with_children.rs | crates/rome_js_analyze/src/semantic_analyzers/security/no_dangerously_set_inner_html_with_children.rs | use crate::react::{ReactApiCall, ReactCreateElementCall};
use crate::semantic_services::Semantic;
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_semantic::SemanticModel;
use rome_js_syntax::{
JsCallExpression, JsPropertyObjectMember, JsSyntaxNode, JsxAttribute, JsxElement,
JsxSelfClosingElement,
};
use rome_rowan::{declare_node_union, AstNode, AstNodeList, TextRange};
declare_rule! {
/// Report when a DOM element or a component uses both `children` and `dangerouslySetInnerHTML` prop.
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// function createMarkup() {
/// return { __html: 'child' }
/// }
/// <Component dangerouslySetInnerHTML={createMarkup()}>"child1"</Component>
/// ```
///
/// ```jsx,expect_diagnostic
/// function createMarkup() {
/// return { __html: 'child' }
/// }
/// <Component dangerouslySetInnerHTML={createMarkup()} children="child1" />
/// ```
///
/// ```js,expect_diagnostic
/// React.createElement('div', { dangerouslySetInnerHTML: { __html: 'HTML' } }, 'children')
/// ```
pub(crate) NoDangerouslySetInnerHtmlWithChildren {
version: "0.10.0",
name: "noDangerouslySetInnerHtmlWithChildren",
recommended: true,
}
}
declare_node_union! {
pub(crate) DangerousProp = JsxAttribute | JsPropertyObjectMember
}
/// The kind of children
enum ChildrenKind {
/// As prop, e.g.
/// ```jsx
/// <Component children="child" />
/// ```
Prop(DangerousProp),
/// As direct descendent, e.g.
/// ```jsx
/// <ComponentA><ComponentB /> </ComponentA>
/// ```
Direct(JsSyntaxNode),
}
impl ChildrenKind {
fn text_trimmed_range(&self) -> TextRange {
match self {
ChildrenKind::Prop(prop) => prop.syntax().text_trimmed_range(),
ChildrenKind::Direct(node) => node.text_trimmed_range(),
}
}
}
pub(crate) struct RuleState {
/// The `dangerouslySetInnerHTML` prop
dangerous_prop: DangerousProp,
/// The kind of `children` found
children_kind: ChildrenKind,
}
declare_node_union! {
pub(crate) AnyJsCreateElement = JsxElement | JsxSelfClosingElement | JsCallExpression
}
impl AnyJsCreateElement {
/// If checks if the element has direct children (no children prop)
fn has_children(&self, model: &SemanticModel) -> Option<JsSyntaxNode> {
match self {
AnyJsCreateElement::JsxElement(element) => {
if !element.children().is_empty() {
Some(element.children().syntax().clone())
} else {
None
}
}
AnyJsCreateElement::JsxSelfClosingElement(_) => None,
AnyJsCreateElement::JsCallExpression(expression) => {
let react_create_element =
ReactCreateElementCall::from_call_expression(expression, model)?;
react_create_element
.children
.map(|children| children.syntax().clone())
}
}
}
fn find_dangerous_prop(&self, model: &SemanticModel) -> Option<DangerousProp> {
match self {
AnyJsCreateElement::JsxElement(element) => {
let opening_element = element.opening_element().ok()?;
opening_element
.find_attribute_by_name("dangerouslySetInnerHTML")
.ok()?
.map(DangerousProp::from)
}
AnyJsCreateElement::JsxSelfClosingElement(element) => element
.find_attribute_by_name("dangerouslySetInnerHTML")
.ok()?
.map(DangerousProp::from),
AnyJsCreateElement::JsCallExpression(call_expression) => {
let react_create_element =
ReactCreateElementCall::from_call_expression(call_expression, model)?;
react_create_element
.find_prop_by_name("dangerouslySetInnerHTML")
.map(DangerousProp::from)
}
}
}
fn find_children_prop(&self, model: &SemanticModel) -> Option<DangerousProp> {
match self {
AnyJsCreateElement::JsxElement(element) => {
let opening_element = element.opening_element().ok()?;
opening_element
.find_attribute_by_name("children")
.ok()?
.map(DangerousProp::from)
}
AnyJsCreateElement::JsxSelfClosingElement(element) => element
.find_attribute_by_name("children")
.ok()?
.map(DangerousProp::from),
AnyJsCreateElement::JsCallExpression(call_expression) => {
let react_create_element =
ReactCreateElementCall::from_call_expression(call_expression, model)?;
react_create_element
.find_prop_by_name("children")
.map(DangerousProp::from)
}
}
}
}
impl Rule for NoDangerouslySetInnerHtmlWithChildren {
type Query = Semantic<AnyJsCreateElement>;
type State = RuleState;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let model = ctx.model();
if let Some(dangerous_prop) = node.find_dangerous_prop(model) {
if let Some(children_node) = node.has_children(model) {
return Some(RuleState {
children_kind: ChildrenKind::Direct(children_node),
dangerous_prop,
});
} else if let Some(children_prop) = node.find_children_prop(model) {
return Some(RuleState {
children_kind: ChildrenKind::Prop(children_prop),
dangerous_prop,
});
}
}
None
}
fn diagnostic(_ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
state.dangerous_prop.syntax().text_trimmed_range(),
markup! {
"Avoid passing both "<Emphasis>"children"</Emphasis>" and the "<Emphasis>"dangerouslySetInnerHTML"</Emphasis>" prop."
},
).detail(state.children_kind.text_trimmed_range(), markup! {
"This is the source of the children prop"
}).note(
markup! {
"Setting HTML content will inadvertently override any passed children in React"
}
))
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/semantic_analyzers/security/no_dangerously_set_inner_html.rs | crates/rome_js_analyze/src/semantic_analyzers/security/no_dangerously_set_inner_html.rs | use crate::react::ReactCreateElementCall;
use crate::semantic_services::Semantic;
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{AnyJsxAttributeName, JsCallExpression, JsLiteralMemberName, JsxAttribute};
use rome_rowan::{declare_node_union, AstNode};
declare_rule! {
/// Prevent the usage of dangerous JSX props
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// function createMarkup() {
/// return { __html: 'child' }
/// }
/// <div dangerouslySetInnerHTML={createMarkup()}></div>
/// ```
///
/// ```js,expect_diagnostic
/// React.createElement('div', {
/// dangerouslySetInnerHTML: { __html: 'child' }
/// });
/// ```
pub(crate) NoDangerouslySetInnerHtml {
version: "0.10.0",
name: "noDangerouslySetInnerHtml",
recommended: true,
}
}
declare_node_union! {
pub(crate) AnyJsCreateElement = JsxAttribute | JsCallExpression
}
pub(crate) enum NoDangerState {
Attribute(JsxAttribute),
Property(JsLiteralMemberName),
}
impl Rule for NoDangerouslySetInnerHtml {
type Query = Semantic<AnyJsCreateElement>;
type State = NoDangerState;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let model = ctx.model();
match node {
AnyJsCreateElement::JsxAttribute(jsx_attribute) => {
let name = jsx_attribute.name().ok()?;
match name {
AnyJsxAttributeName::JsxName(jsx_name) => {
if jsx_name.syntax().text_trimmed() == "dangerouslySetInnerHTML" {
return Some(NoDangerState::Attribute(jsx_attribute.clone()));
}
}
AnyJsxAttributeName::JsxNamespaceName(_) => return None,
}
}
AnyJsCreateElement::JsCallExpression(call_expression) => {
if let Some(react_create_element) =
ReactCreateElementCall::from_call_expression(call_expression, model)
{
let ReactCreateElementCall { props, .. } = react_create_element;
// if we are inside a create element call, we inspect the second argument, which
// should be an object expression. We look for a member that has as name
// "dangerouslySetInnerHTML"
if let Some(props) = props {
let members = props.members();
for member in members {
let member = member.ok()?;
let property_member =
member.as_js_property_object_member()?.name().ok()?;
let name = property_member.as_js_literal_member_name()?;
if name.syntax().text_trimmed() == "dangerouslySetInnerHTML" {
return Some(NoDangerState::Property(name.clone()));
}
}
}
}
}
}
None
}
fn diagnostic(_ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let text_range = match state {
NoDangerState::Attribute(jsx_attribute) => {
let name = jsx_attribute.name().ok()?;
name.syntax().text_trimmed_range()
}
NoDangerState::Property(property) => property.syntax().text_trimmed_range(),
};
let diagnostic = RuleDiagnostic::new(rule_category!(),
text_range,
markup! {
"Avoid passing content using the "<Emphasis>"dangerouslySetInnerHTML"</Emphasis>" prop."
}
.to_owned(),
).warning(
"Setting content using code can expose users to cross-site scripting (XSS) attacks",
);
Some(diagnostic)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/complexity.rs | crates/rome_js_analyze/src/analyzers/complexity.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
use rome_analyze::declare_group;
pub(crate) mod no_extra_boolean_cast;
pub(crate) mod no_for_each;
pub(crate) mod no_multiple_spaces_in_regular_expression_literals;
pub(crate) mod no_useless_catch;
pub(crate) mod no_useless_constructor;
pub(crate) mod no_useless_label;
pub(crate) mod no_useless_rename;
pub(crate) mod no_useless_switch_case;
pub(crate) mod no_useless_type_constraint;
pub(crate) mod no_with;
pub(crate) mod use_flat_map;
pub(crate) mod use_literal_keys;
pub(crate) mod use_optional_chain;
pub(crate) mod use_simple_number_keys;
pub(crate) mod use_simplified_logic_expression;
declare_group! {
pub (crate) Complexity {
name : "complexity" ,
rules : [
self :: no_extra_boolean_cast :: NoExtraBooleanCast ,
self :: no_for_each :: NoForEach ,
self :: no_multiple_spaces_in_regular_expression_literals :: NoMultipleSpacesInRegularExpressionLiterals ,
self :: no_useless_catch :: NoUselessCatch ,
self :: no_useless_constructor :: NoUselessConstructor ,
self :: no_useless_label :: NoUselessLabel ,
self :: no_useless_rename :: NoUselessRename ,
self :: no_useless_switch_case :: NoUselessSwitchCase ,
self :: no_useless_type_constraint :: NoUselessTypeConstraint ,
self :: no_with :: NoWith ,
self :: use_flat_map :: UseFlatMap ,
self :: use_literal_keys :: UseLiteralKeys ,
self :: use_optional_chain :: UseOptionalChain ,
self :: use_simple_number_keys :: UseSimpleNumberKeys ,
self :: use_simplified_logic_expression :: UseSimplifiedLogicExpression ,
]
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/a11y.rs | crates/rome_js_analyze/src/analyzers/a11y.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
use rome_analyze::declare_group;
pub(crate) mod no_access_key;
pub(crate) mod no_auto_focus;
pub(crate) mod no_blank_target;
pub(crate) mod no_distracting_elements;
pub(crate) mod no_header_scope;
pub(crate) mod no_redundant_alt;
pub(crate) mod no_svg_without_title;
pub(crate) mod use_alt_text;
pub(crate) mod use_anchor_content;
pub(crate) mod use_heading_content;
pub(crate) mod use_html_lang;
pub(crate) mod use_iframe_title;
pub(crate) mod use_key_with_click_events;
pub(crate) mod use_key_with_mouse_events;
pub(crate) mod use_media_caption;
pub(crate) mod use_valid_anchor;
declare_group! {
pub (crate) A11y {
name : "a11y" ,
rules : [
self :: no_access_key :: NoAccessKey ,
self :: no_auto_focus :: NoAutoFocus ,
self :: no_blank_target :: NoBlankTarget ,
self :: no_distracting_elements :: NoDistractingElements ,
self :: no_header_scope :: NoHeaderScope ,
self :: no_redundant_alt :: NoRedundantAlt ,
self :: no_svg_without_title :: NoSvgWithoutTitle ,
self :: use_alt_text :: UseAltText ,
self :: use_anchor_content :: UseAnchorContent ,
self :: use_heading_content :: UseHeadingContent ,
self :: use_html_lang :: UseHtmlLang ,
self :: use_iframe_title :: UseIframeTitle ,
self :: use_key_with_click_events :: UseKeyWithClickEvents ,
self :: use_key_with_mouse_events :: UseKeyWithMouseEvents ,
self :: use_media_caption :: UseMediaCaption ,
self :: use_valid_anchor :: UseValidAnchor ,
]
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/correctness.rs | crates/rome_js_analyze/src/analyzers/correctness.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
use rome_analyze::declare_group;
pub(crate) mod no_constructor_return;
pub(crate) mod no_empty_pattern;
pub(crate) mod no_inner_declarations;
pub(crate) mod no_invalid_constructor_super;
pub(crate) mod no_precision_loss;
pub(crate) mod no_setter_return;
pub(crate) mod no_string_case_mismatch;
pub(crate) mod no_switch_declarations;
pub(crate) mod no_unnecessary_continue;
pub(crate) mod no_unreachable;
pub(crate) mod no_unreachable_super;
pub(crate) mod no_unsafe_finally;
pub(crate) mod no_unsafe_optional_chaining;
pub(crate) mod no_unused_labels;
pub(crate) mod no_void_type_return;
pub(crate) mod use_valid_for_direction;
pub(crate) mod use_yield;
declare_group! {
pub (crate) Correctness {
name : "correctness" ,
rules : [
self :: no_constructor_return :: NoConstructorReturn ,
self :: no_empty_pattern :: NoEmptyPattern ,
self :: no_inner_declarations :: NoInnerDeclarations ,
self :: no_invalid_constructor_super :: NoInvalidConstructorSuper ,
self :: no_precision_loss :: NoPrecisionLoss ,
self :: no_setter_return :: NoSetterReturn ,
self :: no_string_case_mismatch :: NoStringCaseMismatch ,
self :: no_switch_declarations :: NoSwitchDeclarations ,
self :: no_unnecessary_continue :: NoUnnecessaryContinue ,
self :: no_unreachable :: NoUnreachable ,
self :: no_unreachable_super :: NoUnreachableSuper ,
self :: no_unsafe_finally :: NoUnsafeFinally ,
self :: no_unsafe_optional_chaining :: NoUnsafeOptionalChaining ,
self :: no_unused_labels :: NoUnusedLabels ,
self :: no_void_type_return :: NoVoidTypeReturn ,
self :: use_valid_for_direction :: UseValidForDirection ,
self :: use_yield :: UseYield ,
]
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/style.rs | crates/rome_js_analyze/src/analyzers/style.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
use rome_analyze::declare_group;
pub(crate) mod no_comma_operator;
pub(crate) mod no_implicit_boolean;
pub(crate) mod no_inferrable_types;
pub(crate) mod no_namespace;
pub(crate) mod no_negation_else;
pub(crate) mod no_non_null_assertion;
pub(crate) mod no_parameter_properties;
pub(crate) mod no_unused_template_literal;
pub(crate) mod use_block_statements;
pub(crate) mod use_default_parameter_last;
pub(crate) mod use_enum_initializers;
pub(crate) mod use_exponentiation_operator;
pub(crate) mod use_numeric_literals;
pub(crate) mod use_self_closing_elements;
pub(crate) mod use_shorthand_array_type;
pub(crate) mod use_single_case_statement;
pub(crate) mod use_single_var_declarator;
pub(crate) mod use_template;
pub(crate) mod use_while;
declare_group! {
pub (crate) Style {
name : "style" ,
rules : [
self :: no_comma_operator :: NoCommaOperator ,
self :: no_implicit_boolean :: NoImplicitBoolean ,
self :: no_inferrable_types :: NoInferrableTypes ,
self :: no_namespace :: NoNamespace ,
self :: no_negation_else :: NoNegationElse ,
self :: no_non_null_assertion :: NoNonNullAssertion ,
self :: no_parameter_properties :: NoParameterProperties ,
self :: no_unused_template_literal :: NoUnusedTemplateLiteral ,
self :: use_block_statements :: UseBlockStatements ,
self :: use_default_parameter_last :: UseDefaultParameterLast ,
self :: use_enum_initializers :: UseEnumInitializers ,
self :: use_exponentiation_operator :: UseExponentiationOperator ,
self :: use_numeric_literals :: UseNumericLiterals ,
self :: use_self_closing_elements :: UseSelfClosingElements ,
self :: use_shorthand_array_type :: UseShorthandArrayType ,
self :: use_single_case_statement :: UseSingleCaseStatement ,
self :: use_single_var_declarator :: UseSingleVarDeclarator ,
self :: use_template :: UseTemplate ,
self :: use_while :: UseWhile ,
]
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/nursery.rs | crates/rome_js_analyze/src/analyzers/nursery.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
use rome_analyze::declare_group;
pub(crate) mod no_confusing_arrow;
pub(crate) mod no_control_characters_in_regex;
pub(crate) mod no_excessive_complexity;
pub(crate) mod no_fallthrough_switch_clause;
pub(crate) mod no_nonoctal_decimal_escape;
pub(crate) mod no_self_assign;
pub(crate) mod no_static_only_class;
pub(crate) mod no_useless_empty_export;
pub(crate) mod no_void;
pub(crate) mod use_arrow_function;
pub(crate) mod use_grouped_type_import;
pub(crate) mod use_import_restrictions;
pub(crate) mod use_literal_enum_members;
declare_group! {
pub (crate) Nursery {
name : "nursery" ,
rules : [
self :: no_confusing_arrow :: NoConfusingArrow ,
self :: no_control_characters_in_regex :: NoControlCharactersInRegex ,
self :: no_excessive_complexity :: NoExcessiveComplexity ,
self :: no_fallthrough_switch_clause :: NoFallthroughSwitchClause ,
self :: no_nonoctal_decimal_escape :: NoNonoctalDecimalEscape ,
self :: no_self_assign :: NoSelfAssign ,
self :: no_static_only_class :: NoStaticOnlyClass ,
self :: no_useless_empty_export :: NoUselessEmptyExport ,
self :: no_void :: NoVoid ,
self :: use_arrow_function :: UseArrowFunction ,
self :: use_grouped_type_import :: UseGroupedTypeImport ,
self :: use_import_restrictions :: UseImportRestrictions ,
self :: use_literal_enum_members :: UseLiteralEnumMembers ,
]
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/performance.rs | crates/rome_js_analyze/src/analyzers/performance.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
use rome_analyze::declare_group;
pub(crate) mod no_delete;
declare_group! {
pub (crate) Performance {
name : "performance" ,
rules : [
self :: no_delete :: NoDelete ,
]
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious.rs | crates/rome_js_analyze/src/analyzers/suspicious.rs | //! Generated file, do not edit by hand, see `xtask/codegen`
use rome_analyze::declare_group;
pub(crate) mod no_assign_in_expressions;
pub(crate) mod no_async_promise_executor;
pub(crate) mod no_comment_text;
pub(crate) mod no_compare_neg_zero;
pub(crate) mod no_confusing_labels;
pub(crate) mod no_const_enum;
pub(crate) mod no_debugger;
pub(crate) mod no_double_equals;
pub(crate) mod no_duplicate_case;
pub(crate) mod no_duplicate_class_members;
pub(crate) mod no_duplicate_jsx_props;
pub(crate) mod no_duplicate_object_keys;
pub(crate) mod no_empty_interface;
pub(crate) mod no_explicit_any;
pub(crate) mod no_extra_non_null_assertion;
pub(crate) mod no_prototype_builtins;
pub(crate) mod no_redundant_use_strict;
pub(crate) mod no_self_compare;
pub(crate) mod no_shadow_restricted_names;
pub(crate) mod no_sparse_array;
pub(crate) mod no_unsafe_negation;
pub(crate) mod use_default_switch_clause_last;
pub(crate) mod use_namespace_keyword;
pub(crate) mod use_valid_typeof;
declare_group! {
pub (crate) Suspicious {
name : "suspicious" ,
rules : [
self :: no_assign_in_expressions :: NoAssignInExpressions ,
self :: no_async_promise_executor :: NoAsyncPromiseExecutor ,
self :: no_comment_text :: NoCommentText ,
self :: no_compare_neg_zero :: NoCompareNegZero ,
self :: no_confusing_labels :: NoConfusingLabels ,
self :: no_const_enum :: NoConstEnum ,
self :: no_debugger :: NoDebugger ,
self :: no_double_equals :: NoDoubleEquals ,
self :: no_duplicate_case :: NoDuplicateCase ,
self :: no_duplicate_class_members :: NoDuplicateClassMembers ,
self :: no_duplicate_jsx_props :: NoDuplicateJsxProps ,
self :: no_duplicate_object_keys :: NoDuplicateObjectKeys ,
self :: no_empty_interface :: NoEmptyInterface ,
self :: no_explicit_any :: NoExplicitAny ,
self :: no_extra_non_null_assertion :: NoExtraNonNullAssertion ,
self :: no_prototype_builtins :: NoPrototypeBuiltins ,
self :: no_redundant_use_strict :: NoRedundantUseStrict ,
self :: no_self_compare :: NoSelfCompare ,
self :: no_shadow_restricted_names :: NoShadowRestrictedNames ,
self :: no_sparse_array :: NoSparseArray ,
self :: no_unsafe_negation :: NoUnsafeNegation ,
self :: use_default_switch_clause_last :: UseDefaultSwitchClauseLast ,
self :: use_namespace_keyword :: UseNamespaceKeyword ,
self :: use_valid_typeof :: UseValidTypeof ,
]
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/a11y/use_key_with_click_events.rs | crates/rome_js_analyze/src/analyzers/a11y/use_key_with_click_events.rs | use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{jsx_ext::AnyJsxElement, AnyJsxAttribute, AnyJsxElementName};
use rome_rowan::AstNode;
declare_rule! {
/// Enforce onClick is accompanied by at least one of the following: `onKeyUp`, `onKeyDown`, `onKeyPress`.
///
/// Coding for the keyboard is important for users with physical disabilities who cannot use a mouse, AT compatibility, and screenreader users.
/// This does not apply for interactive or hidden elements.
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// <div onClick={() => {}} />
/// ```
///
/// ```jsx,expect_diagnostic
/// <div onClick={() => {}} ></div>
/// ```
///
/// ### Valid
///
/// ```jsx
/// <div onClick={() => {}} onKeyDown={handleKeyDown} />
///```
///
/// ```jsx
/// <div onClick={() => {}} onKeyUp={handleKeyUp} />
///```
///
/// ```jsx
/// <div onClick={() => {}} onKeyPress={handleKeyPress} />
///```
///
/// ```jsx
/// // this rule doesn't apply to user created component
/// <MyComponent onClick={() => {}} />
///```
///
/// ```jsx,
/// <div onClick={() => {}} {...spread}></div>
/// ```
///
/// ```jsx
/// <div {...spread} onClick={() => {}} ></div>
/// ```
///
/// ```jsx
/// <button onClick={() => console.log("test")}>Submit</button>
/// ```
///
/// ## Accessibility guidelines
///
/// - [WCAG 2.1.1](https://www.w3.org/WAI/WCAG21/Understanding/keyboard)
///
pub(crate) UseKeyWithClickEvents {
version: "10.0.0",
name: "useKeyWithClickEvents",
recommended: true,
}
}
impl Rule for UseKeyWithClickEvents {
type Query = Ast<AnyJsxElement>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let element = ctx.query();
match element.name() {
Ok(AnyJsxElementName::JsxName(name)) => {
let element_name = name.value_token().ok()?.text_trimmed().to_lowercase();
// Don't handle interactive roles
// TODO Support aria roles https://github.com/rome/tools/issues/3640
if matches!(
element_name.as_str(),
"button" | "checkbox" | "combobox" | "a" | "input"
) {
return None;
}
}
_ => {
return None;
}
}
let attributes = element.attributes();
let on_click_attribute = attributes.find_by_name("onClick").ok()?;
#[allow(clippy::question_mark)]
if on_click_attribute.is_none() {
return None;
}
for attribute in attributes {
match attribute {
AnyJsxAttribute::JsxAttribute(attribute) => {
let attribute_name = attribute.name().ok()?;
let name = attribute_name.as_jsx_name()?;
let name_token = name.value_token().ok()?;
if matches!(
name_token.text_trimmed(),
"onKeyDown" | "onKeyUp" | "onKeyPress"
) {
return None;
}
}
AnyJsxAttribute::JsxSpreadAttribute(_) => {
return None;
}
}
}
Some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
node.range(),
markup! {
"Enforce to have the "<Emphasis>"onClick"</Emphasis>" mouse event with the "<Emphasis>"onKeyUp"</Emphasis>", the "<Emphasis>"onKeyDown"</Emphasis>", or the "<Emphasis>"onKeyPress"</Emphasis>" keyboard event."
},
).note(markup! {
"Actions triggered using mouse events should have corresponding keyboard events to account for keyboard-only navigation."
}))
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/a11y/use_heading_content.rs | crates/rome_js_analyze/src/analyzers/a11y/use_heading_content.rs | use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{jsx_ext::AnyJsxElement, JsxElement};
use rome_rowan::AstNode;
declare_rule! {
/// Enforce that heading elements (h1, h2, etc.) have content and that the content is accessible to screen readers.
/// Accessible means that it is not hidden using the aria-hidden prop.
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// <h1 />
/// ```
///
/// ```jsx,expect_diagnostic
/// <h1><div aria-hidden /></h1>
/// ```
///
/// ```jsx,expect_diagnostic
/// <h1></h1>
/// ```
///
/// ## Valid
///
/// ```jsx
/// <h1>heading</h1>
/// ```
///
/// ```jsx
/// <h1><div aria-hidden="true"></div>visible content</h1>
/// ```
///
/// ```jsx
/// <h1 dangerouslySetInnerHTML={{ __html: "heading" }} />
/// ```
///
/// ```jsx
/// <h1><div aria-hidden />visible content</h1>
/// ```
///
/// ## Accessibility guidelines
///
/// - [WCAG 2.4.6](https://www.w3.org/TR/UNDERSTANDING-WCAG20/navigation-mechanisms-descriptive.html)
///
pub(crate) UseHeadingContent {
version: "12.1.0",
name: "useHeadingContent",
recommended: false,
}
}
const HEADING_ELEMENTS: [&str; 6] = ["h1", "h2", "h3", "h4", "h5", "h6"];
impl Rule for UseHeadingContent {
type Query = Ast<AnyJsxElement>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let name = node.name().ok()?.name_value_token()?;
if HEADING_ELEMENTS.contains(&name.text_trimmed()) {
if node.has_truthy_attribute("aria-hidden") {
return Some(());
}
if has_valid_heading_content(node) {
return None;
}
match node {
AnyJsxElement::JsxOpeningElement(opening_element) => {
if !opening_element.has_accessible_child() {
return Some(());
}
}
AnyJsxElement::JsxSelfClosingElement(_) => return Some(()),
}
}
None
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let range = match ctx.query() {
AnyJsxElement::JsxOpeningElement(node) => {
node.parent::<JsxElement>()?.syntax().text_range()
}
AnyJsxElement::JsxSelfClosingElement(node) => node.syntax().text_trimmed_range(),
};
Some(RuleDiagnostic::new(
rule_category!(),
range,
markup! {
"Provide screen reader accessible content when using "<Emphasis>"heading"</Emphasis>" elements."
},
).note(
"All headings on a page should have content that is accessible to screen readers."
))
}
}
/// check if the node has a valid heading attribute
fn has_valid_heading_content(node: &AnyJsxElement) -> bool {
node.find_attribute_by_name("dangerouslySetInnerHTML")
.is_some()
|| node
.find_attribute_by_name("children")
.map_or(false, |attribute| {
if attribute.initializer().is_none() {
return false;
}
attribute
.as_static_value()
.map_or(true, |attribute| !attribute.is_falsy())
})
|| node.has_spread_prop()
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/a11y/no_redundant_alt.rs | crates/rome_js_analyze/src/analyzers/a11y/no_redundant_alt.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::jsx_ext::AnyJsxElement;
use rome_js_syntax::{
AnyJsExpression, AnyJsLiteralExpression, AnyJsTemplateElement, AnyJsxAttributeValue,
};
use rome_rowan::AstNode;
declare_rule! {
/// Enforce `img` alt prop does not contain the word "image", "picture", or "photo".
///
/// The rule will first check if `aria-hidden` is truthy to determine whether to enforce the rule. If the image is
/// hidden, then the rule will always succeed.
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// <img src="src" alt="photo content" />;
/// ```
///
/// ```jsx,expect_diagnostic
/// <img alt={`picture doing ${things}`} {...this.props} />;
/// ```
///
/// ```jsx,expect_diagnostic
/// <img alt="picture of cool person" aria-hidden={false} />;
/// ```
///
/// ### Valid
///
/// ```jsx
/// <>
/// <img src="src" alt="alt" />
/// <img src="src" alt={photo} />
/// <img src="bar" aria-hidden alt="Picture of me taking a photo of an image" />
/// </>
/// ```
///
pub(crate) NoRedundantAlt {
version: "12.0.0",
name: "noRedundantAlt",
recommended: true,
}
}
impl Rule for NoRedundantAlt {
type Query = Ast<AnyJsxElement>;
type State = AnyJsxAttributeValue;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
if node.name_value_token()?.text_trimmed() != "img" {
return None;
}
let aria_hidden_attribute = node.find_attribute_by_name("aria-hidden");
if let Some(aria_hidden) = aria_hidden_attribute {
let is_false = match aria_hidden.initializer()?.value().ok()? {
AnyJsxAttributeValue::AnyJsxTag(_) => false,
AnyJsxAttributeValue::JsxExpressionAttributeValue(aria_hidden) => {
aria_hidden
.expression()
.ok()?
.as_any_js_literal_expression()?
.as_js_boolean_literal_expression()?
.value_token()
.ok()?
.text_trimmed()
== "false"
}
AnyJsxAttributeValue::JsxString(aria_hidden) => {
aria_hidden.inner_string_text().ok()?.text() == "false"
}
};
if !is_false {
return None;
}
}
let alt = node
.find_attribute_by_name("alt")?
.initializer()?
.value()
.ok()?;
match alt {
AnyJsxAttributeValue::AnyJsxTag(_) => None,
AnyJsxAttributeValue::JsxExpressionAttributeValue(ref value) => {
match value.expression().ok()? {
AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsStringLiteralExpression(expr),
) => {
is_redundant_alt(expr.inner_string_text().ok()?.to_string()).then_some(alt)
}
AnyJsExpression::JsTemplateExpression(expr) => {
let contain_redundant_alt =
expr.elements().into_iter().any(|template_element| {
match template_element {
AnyJsTemplateElement::JsTemplateChunkElement(node) => {
node.template_chunk_token().ok().map_or(false, |token| {
is_redundant_alt(token.text_trimmed().to_string())
})
}
AnyJsTemplateElement::JsTemplateElement(_) => false,
}
});
contain_redundant_alt.then_some(alt)
}
_ => None,
}
}
AnyJsxAttributeValue::JsxString(ref value) => {
let text = value.inner_string_text().ok()?.to_string();
is_redundant_alt(text).then_some(alt)
}
}
}
fn diagnostic(_ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
Some(
RuleDiagnostic::new(
rule_category!(),
state.range(),
markup! {
"Avoid the words \"image\", \"picture\", or \"photo\" in " <Emphasis>"img"</Emphasis>" element alt text."
},
)
.note(markup! {
"Screen readers announce img elements as \"images\", so it is not necessary to redeclare this in alternative text."
}),
)
}
}
const REDUNDANT_WORDS: [&str; 3] = ["image", "photo", "picture"];
fn is_redundant_alt(alt: String) -> bool {
REDUNDANT_WORDS
.into_iter()
.any(|word| alt.split_whitespace().any(|x| x.to_lowercase() == word))
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/a11y/use_html_lang.rs | crates/rome_js_analyze/src/analyzers/a11y/use_html_lang.rs | use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{jsx_ext::AnyJsxElement, TextRange};
use rome_rowan::AstNode;
declare_rule! {
/// Enforce that `html` element has `lang` attribute.
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// <html></html>
/// ```
///
/// ```jsx,expect_diagnostic
/// <html lang={""}></html>
/// ```
///
/// ```jsx,expect_diagnostic
/// <html lang={null}></html>
/// ```
///
/// ```jsx,expect_diagnostic
/// <html lang={undefined}></html>
/// ```
///
/// ```jsx,expect_diagnostic
/// <html lang={true}></html>
/// ```
///
/// ### Valid
///
/// ```jsx
/// <html lang="en"></html>
/// ```
///
/// ```jsx
/// <html lang={language}></html>
/// ```
///
/// ```jsx
/// <html {...props}></html>
/// ```
///
/// ```jsx
/// <html lang={""} {...props}></html>
/// ```
///
/// ## Accessibility guidelines
///
/// - [WCAG 3.1.1](https://www.w3.org/WAI/WCAG21/Understanding/language-of-page)
///
pub(crate) UseHtmlLang {
version: "12.0.0",
name: "useHtmlLang",
recommended: true,
}
}
impl Rule for UseHtmlLang {
type Query = Ast<AnyJsxElement>;
type State = TextRange;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let element = ctx.query();
let name = element.name().ok()?.name_value_token()?;
if name.text_trimmed() == "html" {
if let Some(lang_attribute) = element.find_attribute_by_name("lang") {
if !lang_attribute
.as_static_value()
.map_or(true, |attribute| attribute.is_not_string_constant(""))
&& !element.has_trailing_spread_prop(lang_attribute)
{
return Some(element.syntax().text_trimmed_range());
}
} else if !element.has_spread_prop() {
return Some(element.syntax().text_trimmed_range());
}
}
None
}
fn diagnostic(_ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
state,
markup! {
"Provide a "<Emphasis>"lang"</Emphasis>" attribute when using the "<Emphasis>"html"</Emphasis>" element."
}
).note(
markup! {
"Setting a "<Emphasis>"lang"</Emphasis>" attribute on HTML document elements configures the language"
"used by screen readers when no user default is specified."
}
))
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/a11y/use_anchor_content.rs | crates/rome_js_analyze/src/analyzers/a11y/use_anchor_content.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::jsx_ext::AnyJsxElement;
use rome_js_syntax::JsxElement;
use rome_rowan::AstNode;
declare_rule! {
/// Enforce that anchors have content and that the content is accessible to screen readers.
///
/// Accessible means the content is not hidden using the `aria-hidden` attribute.
/// Refer to the references to learn about why this is important.
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// <a />
/// ```
///
/// ```jsx,expect_diagnostic
/// <a></a>
/// ```
///
/// ```jsx,expect_diagnostic
/// <a> </a>
/// ```
///
/// ```jsx,expect_diagnostic
/// <a aria-hidden>content</a>
/// ```
///
/// ```jsx,expect_diagnostic
/// <a><span aria-hidden="true">content</span></a>
/// ```
///
/// ## Valid
///
/// ```jsx
/// <a>content</a>
/// ```
///
/// ```jsx
/// function html() {
/// return { __html: "foo" }
/// }
/// <a dangerouslySetInnerHTML={html()} />
/// ```
///
/// ```jsx
/// <a><TextWrapper aria-hidden={true} />content</a>
/// ```
///
/// ```jsx
/// <a><div aria-hidden="true"></div>content</a>
/// ```
///
/// ## Accessibility guidelines
///
/// - [WCAG 2.4.4](https://www.w3.org/WAI/WCAG21/Understanding/link-purpose-in-context)
/// - [WCAG 4.1.2](https://www.w3.org/WAI/WCAG21/Understanding/name-role-value)
///
pub(crate) UseAnchorContent {
version: "10.0.0",
name: "useAnchorContent",
recommended: true,
}
}
impl Rule for UseAnchorContent {
type Query = Ast<AnyJsxElement>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let name = node.name().ok()?.name_value_token()?;
if name.text_trimmed() == "a" {
if node.has_truthy_attribute("aria-hidden") {
return Some(());
}
if has_valid_anchor_content(node) {
return None;
}
match node {
AnyJsxElement::JsxOpeningElement(opening_element) => {
if !opening_element.has_accessible_child() {
return Some(());
}
}
AnyJsxElement::JsxSelfClosingElement(_) => return Some(()),
}
}
None
}
fn diagnostic(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<RuleDiagnostic> {
let range = match ctx.query() {
AnyJsxElement::JsxOpeningElement(node) => {
node.parent::<JsxElement>()?.syntax().text_range()
}
AnyJsxElement::JsxSelfClosingElement(node) => node.syntax().text_trimmed_range(),
};
Some(RuleDiagnostic::new(
rule_category!(),
range,
markup! {
"Provide screen reader accessible content when using "<Emphasis>"`a`"</Emphasis>" elements."
}
).note(
markup! {
"All links on a page should have content that is accessible to screen readers."
}
))
}
}
/// check if the node has a valid anchor attribute
fn has_valid_anchor_content(node: &AnyJsxElement) -> bool {
node.find_attribute_by_name("dangerouslySetInnerHTML")
.is_some()
|| node
.find_attribute_by_name("children")
.map_or(false, |attribute| {
if attribute.initializer().is_none() {
return false;
}
attribute
.as_static_value()
.map_or(true, |attribute| !attribute.is_falsy())
})
|| node.has_spread_prop()
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/a11y/use_media_caption.rs | crates/rome_js_analyze/src/analyzers/a11y/use_media_caption.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::jsx_ext::AnyJsxElement;
use rome_js_syntax::{AnyJsxChild, JsxElement, TextRange};
use rome_rowan::AstNode;
declare_rule! {
/// Enforces that `audio` and `video` elements must have a `track` for captions.
///
/// **ESLint Equivalent:** [media-has-caption](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/main/docs/rules/media-has-caption.md)
///
/// ## Examples
///
/// ### Invalid
/// ```jsx,expect_diagnostic
/// <video />
/// ```
///
/// ```jsx,expect_diagnostic
/// <audio>child</audio>
/// ```
///
/// ### Valid
///
/// ```jsx
/// <audio>
/// <track kind="captions" {...props} />
/// </audio>
/// ```
///
/// ```jsx
/// <video muted {...props}></video>
/// ```
pub(crate) UseMediaCaption {
version: "12.0.0",
name: "useMediaCaption",
recommended: true,
}
}
impl Rule for UseMediaCaption {
type Query = Ast<AnyJsxElement>;
type State = TextRange;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let has_audio_or_video =
matches!(node.name_value_token()?.text_trimmed(), "video" | "audio");
let has_muted = node.find_attribute_by_name("muted").is_some();
let has_spread_prop = node
.attributes()
.into_iter()
.any(|attr| attr.as_jsx_spread_attribute().is_some());
if !has_audio_or_video || has_muted || has_spread_prop {
return None;
}
match node {
AnyJsxElement::JsxOpeningElement(_) => {
let jsx_element = node.parent::<JsxElement>()?;
let has_track = jsx_element
.children()
.into_iter()
.filter_map(|child| {
let any_jsx = match child {
AnyJsxChild::JsxElement(element) => {
Some(AnyJsxElement::from(element.opening_element().ok()?))
}
AnyJsxChild::JsxSelfClosingElement(element) => {
Some(AnyJsxElement::from(element))
}
_ => None,
}?;
let has_track = any_jsx.name_value_token()?.text_trimmed() == "track";
let has_valid_kind = &any_jsx
.find_attribute_by_name("kind")?
.initializer()?
.value()
.ok()?
.as_jsx_string()?
.inner_string_text()
.ok()?
.to_lowercase()
== "captions";
Some(has_track && has_valid_kind)
})
.any(|is_valid| is_valid);
if !has_track {
return Some(jsx_element.range());
}
}
_ => return Some(node.range()),
}
None
}
fn diagnostic(_: &RuleContext<Self>, range: &Self::State) -> Option<RuleDiagnostic> {
let diagnostic = RuleDiagnostic::new(
rule_category!(),
range,
markup! {"Provide a "<Emphasis>"track"</Emphasis>" for captions when using "<Emphasis>"audio"</Emphasis>" or "<Emphasis>"video"</Emphasis>" elements."}.to_owned(),
)
.note("Captions support users with hearing-impairments. They should be a transcription or translation of the dialogue, sound effects, musical cues, and other relevant audio information.");
Some(diagnostic)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/a11y/use_iframe_title.rs | crates/rome_js_analyze/src/analyzers/a11y/use_iframe_title.rs | use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::jsx_ext::AnyJsxElement;
use rome_rowan::AstNode;
declare_rule! {
/// Enforces the usage of the attribute `title` for the element `iframe`.
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// <iframe />
/// ```
///
/// ```jsx,expect_diagnostic
/// <iframe></iframe>
/// ```
///
/// ```jsx,expect_diagnostic
/// <iframe title="" />
/// ```
///
/// ```jsx,expect_diagnostic
/// <iframe title={""} />
/// ```
///
/// ```jsx,expect_diagnostic
/// <iframe title={undefined} />
/// ```
///
/// ```jsx,expect_diagnostic
/// <iframe title={false} />
/// ```
///
/// ```jsx,expect_diagnostic
/// <iframe title={true} />
/// ```
///
/// ```jsx,expect_diagnostic
/// <iframe title={42} />
/// ```
///
///
/// ### Valid
///
/// ```jsx
/// <>
/// <iframe title="This is a unique title" />
/// <iframe title={uniqueTitle} />
/// <iframe {...props} />
/// </>
/// ```
///
/// ## Accessibility guidelines
///
/// - [WCAG 2.4.1](https://www.w3.org/WAI/WCAG21/Understanding/bypass-blocks)
/// - [WCAG 4.1.2](https://www.w3.org/WAI/WCAG21/Understanding/name-role-value)
///
pub(crate) UseIframeTitle {
version: "12.0.0",
name: "useIframeTitle",
recommended: true,
}
}
impl Rule for UseIframeTitle {
type Query = Ast<AnyJsxElement>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let element = ctx.query();
let name = element.name().ok()?.name_value_token()?;
if name.text_trimmed() == "iframe" {
if let Some(lang_attribute) = element.find_attribute_by_name("title") {
if !lang_attribute
.as_static_value()
.map_or(true, |attribute| attribute.is_not_string_constant(""))
&& !element.has_trailing_spread_prop(lang_attribute)
{
return Some(());
}
} else if !element.has_spread_prop() {
return Some(());
}
}
None
}
fn diagnostic(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(
RuleDiagnostic::new(
rule_category!(),
node.syntax().text_trimmed_range(),
markup! {
"Provide a "<Emphasis>"title"</Emphasis>" attribute when using "<Emphasis>"iframe"</Emphasis>" elements."
}
)
.note(markup! {
"Screen readers rely on the title set on an iframe to describe the content being displayed."
}),
)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/a11y/no_blank_target.rs | crates/rome_js_analyze/src/analyzers/a11y/no_blank_target.rs | use crate::JsRuleAction;
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make::{
jsx_attribute, jsx_attribute_initializer_clause, jsx_attribute_list, jsx_ident, jsx_name,
jsx_string, token,
};
use rome_js_syntax::jsx_ext::AnyJsxElement;
use rome_js_syntax::{
AnyJsxAttribute, AnyJsxAttributeName, AnyJsxAttributeValue, JsxAttribute, JsxAttributeList, T,
};
use rome_rowan::{AstNode, AstNodeList, BatchMutationExt, TriviaPieceKind};
declare_rule! {
/// Disallow `target="_blank"` attribute without `rel="noreferrer"`
///
/// When creating anchor `a` element, there are times when its link has to be opened in a new browser tab
/// via `target="_blank"` attribute. This attribute has to paired with `rel="noreferrer"` or you're incur
/// in a security issue.
///
/// Refer to [the noreferrer documentation](https://html.spec.whatwg.org/multipage/links.html#link-type-noreferrer)
/// and the [the noopener documentation](https://html.spec.whatwg.org/multipage/links.html#link-type-noopener)
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// <a href='http://external.link' target='_blank'>child</a>
/// ```
///
/// ```jsx,expect_diagnostic
/// <a href='http://external.link' target='_blank' rel="noopener">child</a>
/// ```
///
/// ```jsx,expect_diagnostic
/// <a {...props} href='http://external.link' target='_blank' rel="noopener">child</a>
/// ```
///
/// ### Valid
///
/// ```jsx
/// <a href='http://external.link' rel='noreferrer' target='_blank'>child</a>
/// ```
///
/// ```jsx
/// <a href='http://external.link' target='_blank' rel="noopener" {...props}>child</a>
/// ```
pub(crate) NoBlankTarget {
version: "10.0.0",
name: "noBlankTarget",
recommended: true,
}
}
impl Rule for NoBlankTarget {
type Query = Ast<AnyJsxElement>;
/// Two attributes:
/// 1. The attribute `target=`
/// 2. The attribute `rel=`, if present
type State = (JsxAttribute, Option<JsxAttribute>);
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
if node.name_value_token()?.text_trimmed() != "a"
|| node.find_attribute_by_name("href").is_none()
{
return None;
}
let target_attribute = node.find_attribute_by_name("target")?;
let rel_attribute = node.find_attribute_by_name("rel");
if target_attribute.as_static_value()?.text() == "_blank" {
match rel_attribute {
None => {
if !node.has_trailing_spread_prop(target_attribute.clone()) {
return Some((target_attribute, None));
}
}
Some(rel_attribute) => {
if rel_attribute.initializer().is_none()
|| (!rel_attribute
.as_static_value()?
.text()
.split_ascii_whitespace()
.any(|f| f == "noreferrer")
&& !node.has_trailing_spread_prop(target_attribute.clone())
&& !node.has_trailing_spread_prop(rel_attribute.clone()))
{
return Some((target_attribute, Some(rel_attribute)));
}
}
}
}
None
}
fn action(
ctx: &RuleContext<Self>,
(target_attribute, rel_attribute): &Self::State,
) -> Option<JsRuleAction> {
let mut mutation = ctx.root().begin();
let message = if let Some(rel_attribute) = rel_attribute {
let prev_jsx_attribute = rel_attribute.initializer()?.value().ok()?;
let prev_jsx_string = prev_jsx_attribute.as_jsx_string()?;
let new_text = format!(
"\"noreferrer {}\"",
prev_jsx_string.inner_string_text().ok()?.text()
);
mutation.replace_node(prev_jsx_string.clone(), jsx_string(jsx_ident(&new_text)));
(markup! {
"Add the "<Emphasis>"\"noreferrer\""</Emphasis>" to the existing attribute."
})
.to_owned()
} else {
let old_attribute_list = target_attribute
.syntax()
.ancestors()
.find_map(JsxAttributeList::cast)?;
let mut new_attribute_list: Vec<_> = old_attribute_list.iter().collect();
let new_attribute = jsx_attribute(AnyJsxAttributeName::JsxName(jsx_name(
jsx_ident("rel").with_leading_trivia([(TriviaPieceKind::Whitespace, " ")]),
)))
.with_initializer(jsx_attribute_initializer_clause(
token(T![=]),
AnyJsxAttributeValue::JsxString(jsx_string(jsx_ident("\"noreferrer\""))),
))
.build();
new_attribute_list.push(AnyJsxAttribute::JsxAttribute(new_attribute));
mutation.replace_node(old_attribute_list, jsx_attribute_list(new_attribute_list));
(markup! {
"Add the "<Emphasis>"rel=\"noreferrer\""</Emphasis>" attribute."
})
.to_owned()
};
Some(JsRuleAction {
mutation,
message,
category: ActionCategory::QuickFix,
applicability: Applicability::Always,
})
}
fn diagnostic(
_ctx: &RuleContext<Self>,
(target_attribute, _): &Self::State,
) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
target_attribute.syntax().text_trimmed_range(),
markup! {
"Avoid using "<Emphasis>"target=\"_blank\""</Emphasis>" without "<Emphasis>"rel=\"noreferrer\""</Emphasis>"."
},
).note(
markup!{
"Opening external links in new tabs without rel=\"noreferrer\" is a security risk. See \
"<Hyperlink href="https://html.spec.whatwg.org/multipage/links.html#link-type-noopener">"the explanation"</Hyperlink>" for more details."
}
))
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/a11y/no_header_scope.rs | crates/rome_js_analyze/src/analyzers/a11y/no_header_scope.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_syntax::jsx_ext::AnyJsxElement;
use rome_rowan::{AstNode, BatchMutationExt};
use crate::JsRuleAction;
declare_rule! {
/// The scope prop should be used only on `<th>` elements.
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// <div scope={scope} />
/// ```
///
/// ```jsx,expect_diagnostic
/// <div scope="col" />
/// ```
///
/// ### Valid
///
/// ```jsx
/// <th scope={scope}></th>
/// ```
///
/// ```jsx
/// <th scope="col"></th>
/// ```
///
/// ## Accessibility guidelines
///
/// - [WCAG 1.3.1](https://www.w3.org/WAI/WCAG21/Understanding/info-and-relationships)
/// - [WCAG 4.1.1](https://www.w3.org/WAI/WCAG21/Understanding/parsing)
///
pub(crate) NoHeaderScope {
version: "11.0.0",
name: "noHeaderScope",
recommended: true,
}
}
impl Rule for NoHeaderScope {
type Query = Ast<AnyJsxElement>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let element = ctx.query();
if element.is_element()
&& element.name_value_token()?.text_trimmed() != "th"
&& element.has_truthy_attribute("scope")
{
return Some(());
}
None
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let element = ctx.query();
let scope_node = element.find_attribute_by_name("scope")?;
let diagnostic = RuleDiagnostic::new(
rule_category!(),
scope_node.range(),
markup! {"Avoid using the "<Emphasis>"scope"</Emphasis>" attribute on elements other than "<Emphasis>"th"</Emphasis>" elements."}
.to_owned(),
);
Some(diagnostic)
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let element = ctx.query();
let scope_node = element.find_attribute_by_name("scope")?;
let mut mutation = ctx.root().begin();
mutation.remove_node(scope_node);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Remove the "<Emphasis>"scope"</Emphasis>" attribute." }.to_owned(),
mutation,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/a11y/use_key_with_mouse_events.rs | crates/rome_js_analyze/src/analyzers/a11y/use_key_with_mouse_events.rs | use crate::semantic_services::Semantic;
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Rule, RuleDiagnostic};
use rome_console::{markup, MarkupBuf};
use rome_js_syntax::jsx_ext::AnyJsxElement;
use rome_rowan::AstNode;
declare_rule! {
/// Enforce `onMouseOver` / `onMouseOut` are accompanied by `onFocus` / `onBlur`.
///
/// Coding for the keyboard is important for users with physical disabilities who cannot use a mouse, AT compatibility, and screenreader users.
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// <div onMouseOver={() => {}} />
/// ```
///
/// ```jsx,expect_diagnostic
/// <div onMouseOut={() => {}} />
/// ```
///
/// ### Valid
///
/// ```jsx
/// <>
/// <div onMouseOver={() => {}} onFocus={() => {}} />
/// <div onMouseOut={() => {}} onBlur={() => {}} />
/// <div onMouseOver={() => {}} {...otherProps} />
/// <div onMouseOut={() => {}} {...otherProps} />
/// <div onMouseOver={() => {}} onFocus={() => {}} {...otherProps} />
/// <div onMouseOut={() => {}} onBlur={() => {}} {...otherProps} />
/// </>
/// ```
///
/// ## Accessibility guidelines
///
/// - [WCAG 2.1.1](https://www.w3.org/WAI/WCAG21/Understanding/keyboard)
///
pub(crate) UseKeyWithMouseEvents {
version: "10.0.0",
name: "useKeyWithMouseEvents",
recommended: true,
}
}
pub(crate) enum UseKeyWithMouseEventsState {
MissingOnFocus,
MissingOnBlur,
}
impl UseKeyWithMouseEventsState {
fn message(&self) -> MarkupBuf {
match self {
UseKeyWithMouseEventsState::MissingOnBlur => {
markup! {"onMouseOut must be accompanied by onBlur for accessibility."}.to_owned()
}
UseKeyWithMouseEventsState::MissingOnFocus => {
markup! {"onMouseOver must be accompanied by onFocus for accessibility."}.to_owned()
}
}
}
}
impl Rule for UseKeyWithMouseEvents {
type Query = Semantic<AnyJsxElement>;
type State = UseKeyWithMouseEventsState;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
if !node.is_custom_component() {
if !has_valid_focus_attributes(node) {
return Some(UseKeyWithMouseEventsState::MissingOnFocus);
}
if !has_valid_blur_attributes(node) {
return Some(UseKeyWithMouseEventsState::MissingOnBlur);
}
}
None
}
fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
let footer_note_text = markup! {"Actions triggered using mouse events should have corresponding events to account for keyboard-only navigation."};
Some(
RuleDiagnostic::new(
rule_category!(),
node.syntax().text_trimmed_range(),
state.message(),
)
.note(footer_note_text),
)
}
}
fn has_valid_focus_attributes(elem: &AnyJsxElement) -> bool {
if let Some(on_mouse_over_attribute) = elem.find_attribute_by_name("onMouseOver") {
if !elem.has_trailing_spread_prop(on_mouse_over_attribute) {
return elem.find_attribute_by_name("onFocus").map_or(false, |it| {
!it.as_static_value()
.map_or(false, |value| value.is_null_or_undefined())
});
}
}
true
}
fn has_valid_blur_attributes(elem: &AnyJsxElement) -> bool {
if let Some(on_mouse_attribute) = elem.find_attribute_by_name("onMouseOut") {
if !elem.has_trailing_spread_prop(on_mouse_attribute) {
return elem.find_attribute_by_name("onBlur").map_or(false, |it| {
!it.as_static_value()
.map_or(false, |value| value.is_null_or_undefined())
});
}
}
true
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/a11y/no_svg_without_title.rs | crates/rome_js_analyze/src/analyzers/a11y/no_svg_without_title.rs | use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{jsx_ext::AnyJsxElement, JsxAttribute, JsxChildList, JsxElement};
use rome_rowan::{AstNode, AstNodeList};
declare_rule! {
/// Enforces the usage of the `title` element for the `svg` element.
///
/// It is not possible to specify the `alt` attribute for the `svg` as for the `img`.
/// To make svg accessible, the following methods are available:
/// - provide the `title` element as the first child to `svg`
/// - provide `role="img"` and `aria-label` or `aria-labelledby` to `svg`
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// <svg>foo</svg>
/// ```
///
/// ```js,expect_diagnostic
/// <svg>
/// <title></title>
/// <circle />
/// </svg>
/// ``
///
/// ```js,expect_diagnostic
/// <svg>foo</svg>
/// ```
///
/// ```js
/// <svg role="img" aria-label="">
/// <span id="">Pass</span>
/// </svg>
/// ```
///
/// ## Valid
///
/// ```js
/// <svg>
/// <rect />
/// <rect />
/// <g>
/// <circle />
/// <circle />
/// <g>
/// <title>Pass</title>
/// <circle />
/// <circle />
/// </g>
/// </g>
/// </svg>
/// ```
///
/// ```js
/// <svg>
/// <title>Pass</title>
/// <circle />
/// </svg>
/// ```
///
/// ```js
/// <svg role="img" aria-label="title">
/// <span id="title">Pass</span>
/// </svg>
/// ```
///
/// ## Accessibility guidelines
/// [Document Structure – SVG 1.1 (Second Edition)](https://www.w3.org/TR/SVG11/struct.html#DescriptionAndTitleElements)
/// [ARIA: img role - Accessibility | MDN](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/img_role)
/// [Accessible SVGs | CSS-Tricks - CSS-Tricks](https://css-tricks.com/accessible-svgs/)
/// [Contextually Marking up accessible images and SVGs | scottohara.me](https://www.scottohara.me/blog/2019/05/22/contextual-images-svgs-and-a11y.html)
///
pub(crate) NoSvgWithoutTitle {
version: "12.0.0",
name: "noSvgWithoutTitle",
recommended: true,
}
}
impl Rule for NoSvgWithoutTitle {
type Query = Ast<AnyJsxElement>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
if node.name_value_token()?.text_trimmed() != "svg" {
return None;
}
// Checks if a `svg` element has a valid `title` element is in a childlist
let jsx_element = node.parent::<JsxElement>()?;
if let AnyJsxElement::JsxOpeningElement(_) = node {
let has_valid_title = has_valid_title_element(&jsx_element.children());
if has_valid_title.map_or(false, |bool| bool) {
return None;
}
}
// Checks if a `svg` element has role='img' and title/aria-label/aria-labelledby attrigbute
let Some(role_attribute) = node.find_attribute_by_name("role") else {
return Some(())
};
let role_attribute_value = role_attribute.initializer()?.value().ok()?;
let Some(text) = role_attribute_value.as_jsx_string()?.inner_string_text().ok() else {
return Some(())
};
if text.to_lowercase() == "img" {
let [aria_label, aria_labelledby] = node
.attributes()
.find_by_names(["aria-label", "aria-labelledby"]);
let jsx_child_list = jsx_element.children();
let is_valid = is_valid_attribute_value(aria_label, &jsx_child_list).unwrap_or(false)
|| is_valid_attribute_value(aria_labelledby, &jsx_child_list).unwrap_or(false);
if !is_valid {
return Some(());
}
};
None
}
fn diagnostic(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
let diagnostic = RuleDiagnostic::new(
rule_category!(),
node.syntax().text_trimmed_range(),
markup! {
"Alternative text "<Emphasis>"title"</Emphasis>" element cannot be empty"
},
)
.note(markup! {
"For accessibility purposes, "<Emphasis>"SVGs"</Emphasis>" should have an alternative text,
provided via "<Emphasis>"title"</Emphasis>" element. If the svg element has role=\"img\", you should add the "<Emphasis>"aria-label"</Emphasis>" or "<Emphasis>"aria-labelledby"</Emphasis>" attribute."
});
Some(diagnostic)
}
}
/// Checks if the given attribute is attached to the `svg` element and the attribute value is used by the `id` of the childs element.
fn is_valid_attribute_value(
attribute: Option<JsxAttribute>,
jsx_child_list: &JsxChildList,
) -> Option<bool> {
let attribute_value = attribute?.initializer()?.value().ok()?;
let is_used_attribute = jsx_child_list
.iter()
.filter_map(|child| {
let jsx_element = child.as_jsx_element()?;
let opening_element = jsx_element.opening_element().ok()?;
let maybe_attribute = opening_element.find_attribute_by_name("id").ok()?;
let child_attribute_value = maybe_attribute?.initializer()?.value().ok()?;
let is_valid = attribute_value.as_static_value()?.text()
== child_attribute_value.as_static_value()?.text();
Some(is_valid)
})
.any(|x| x);
Some(is_used_attribute)
}
/// Checks if the given `JsxChildList` has a valid `title` element.
fn has_valid_title_element(jsx_child_list: &JsxChildList) -> Option<bool> {
jsx_child_list
.iter()
.filter_map(|child| {
let jsx_element = child.as_jsx_element()?;
let opening_element = jsx_element.opening_element().ok()?;
let name = opening_element.name().ok()?;
let name = name.as_jsx_name()?.value_token().ok()?;
let has_title_name = name.text_trimmed() == "title";
if !has_title_name {
return has_valid_title_element(&jsx_element.children());
}
let is_empty_child = jsx_element.children().is_empty();
Some(has_title_name && !is_empty_child)
})
.next()
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/a11y/no_access_key.rs | crates/rome_js_analyze/src/analyzers/a11y/no_access_key.rs | use crate::JsRuleAction;
use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_syntax::{jsx_ext::AnyJsxElement, JsxAttribute, JsxAttributeList};
use rome_rowan::{AstNode, BatchMutationExt};
declare_rule! {
/// Enforce that the `accessKey` attribute is not used on any HTML element.
///
/// The `accessKey` assigns a keyboard shortcut to the current element. However, the `accessKey` value
/// can conflict with keyboard commands used by screen readers and keyboard-only users, which leads to
/// inconsistent keyboard actions across applications. To avoid accessibility complications,
/// this rule suggests users remove the `accessKey` attribute on elements.
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// <input type="submit" accessKey="s" value="Submit" />
/// ```
///
/// ```jsx,expect_diagnostic
/// <a href="https://webaim.org/" accessKey="w">WebAIM.org</a>
/// ```
///
/// ```jsx,expect_diagnostic
/// <button accessKey="n">Next</button>
/// ```
///
/// ## Resources
///
/// - [WebAIM: Keyboard Accessibility - Accesskey](https://webaim.org/techniques/keyboard/accesskey#spec)
/// - [MDN `accesskey` documentation](https://developer.mozilla.org/docs/Web/HTML/Global_attributes/accesskey)
///
pub(crate) NoAccessKey {
version: "11.0.0",
name: "noAccessKey",
recommended: false,
}
}
impl Rule for NoAccessKey {
type Query = Ast<JsxAttribute>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
if node.name_value_token()?.text_trimmed() != "accessKey" {
return None;
}
let element = node
.parent::<JsxAttributeList>()
.and_then(|list| list.parent::<AnyJsxElement>())?;
// We do not know if the `accessKey` prop is used for HTML elements
// or for user-created React components
if element.is_custom_component() {
return None;
}
let attribute_value = node.initializer()?.value().ok()?;
if attribute_value.is_value_null_or_undefined() {
return None;
}
Some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(
RuleDiagnostic::new(
rule_category!(),
node.syntax().text_trimmed_range(),
markup! {
"Avoid the "<Emphasis>"accessKey"</Emphasis>" attribute to reduce inconsistencies between \
keyboard shortcuts and screen reader keyboard comments."
},
).note(
markup! {
"Assigning keyboard shortcuts using the "<Emphasis>"accessKey"</Emphasis>" attribute leads to \
inconsistent keyboard actions across applications."
},
)
)
}
fn action(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
mutation.remove_node(node.clone());
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Remove the "<Emphasis>"accessKey"</Emphasis>" attribute." }
.to_owned(),
mutation,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/a11y/no_distracting_elements.rs | crates/rome_js_analyze/src/analyzers/a11y/no_distracting_elements.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_syntax::jsx_ext::AnyJsxElement;
use rome_js_syntax::*;
use rome_rowan::{AstNode, BatchMutationExt};
use crate::JsRuleAction;
declare_rule! {
/// Enforces that no distracting elements are used.
///
/// Elements that can be visually distracting can cause accessibility issues with visually impaired users.
/// Such elements are most likely deprecated, and should be avoided.
/// By default, the following elements are visually distracting: `<marquee>` and `<blink>`.
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// <marquee />
/// ```
///
/// ```jsx,expect_diagnostic
/// <blink />
/// ```
///
/// ### Valid
///
/// ```jsx
/// <div />
/// ```
///
/// ## Accessibility guidelines
///
/// - [WCAG 2.2.2](https://www.w3.org/WAI/WCAG21/Understanding/pause-stop-hide)
///
pub(crate) NoDistractingElements {
version: "11.0.0",
name: "noDistractingElements",
recommended: true,
}
}
impl Rule for NoDistractingElements {
type Query = Ast<AnyJsxElement>;
type State = JsSyntaxToken;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let element = ctx.query();
let name = element.name_value_token()?;
match name.text_trimmed() {
"marquee" | "blink" => Some(name),
_ => None,
}
}
fn diagnostic(ctx: &RuleContext<Self>, name: &Self::State) -> Option<RuleDiagnostic> {
let element = ctx.query();
let diagnostic = RuleDiagnostic::new(
rule_category!(),
element.range(),
markup! {"Don't use the '"{name.text_trimmed()}"' element."}.to_owned(),
)
.note(markup! {
"Visually distracting elements can cause accessibility issues and should be avoided."
});
Some(diagnostic)
}
fn action(ctx: &RuleContext<Self>, name: &Self::State) -> Option<JsRuleAction> {
let element = ctx.query();
let mut mutation = ctx.root().begin();
mutation.remove_node(element.clone());
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Remove the '"{name.text_trimmed()}"' element." }.to_owned(),
mutation,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/a11y/use_valid_anchor.rs | crates/rome_js_analyze/src/analyzers/a11y/use_valid_anchor.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::{markup, MarkupBuf};
use rome_js_syntax::jsx_ext::AnyJsxElement;
use rome_rowan::{AstNode, TextRange};
declare_rule! {
/// Enforce that all anchors are valid, and they are navigable elements.
///
/// The anchor element (`<a></a>`) - also called **hyperlink** - is an important element
/// that allows users to navigate pages, in the same page, same website or on another website.
///
/// While before it was possible to attach logic to an anchor element, with the advent of JSX libraries,
/// it's now easier to attach logic to any HTML element, anchors included.
///
/// This rule is designed to prevent users to attach logic at the click of anchors, and also makes
/// sure that the `href` provided to the anchor element is valid. If the anchor has logic attached to it,
/// the rules suggests to turn it to a `button`, because that's likely what the user wants.
///
/// Anchor `<a></a>` elements should be used for navigation, while `<button></button>` should be
/// used for user interaction.
///
/// There are **many reasons** why an anchor should not have a logic and have a correct `href` attribute:
/// - it can disrupt the correct flow of the user navigation e.g. a user that wants to open the link
/// in another tab, but the default "click" behaviour is prevented
/// - it can source of invalid links, and crawlers can't navigate the website, risking to penalise
/// SEO ranking
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// <a href={null}>navigate here</a>
/// ```
/// ```jsx,expect_diagnostic
/// <a href={undefined}>navigate here</a>
/// ```
/// ```jsx,expect_diagnostic
/// <a href>navigate here</a>
/// ```
/// ```jsx,expect_diagnostic
/// <a href="javascript:void(0)">navigate here</a>
/// ```
/// ```jsx,expect_diagnostic
/// <a href="https://example.com" onClick={something}>navigate here</a>
/// ```
/// ### Valid
///
/// ```jsx
/// <a href={`https://www.javascript.com`}>navigate here</a>
/// ```
///
/// ```jsx
/// <a href={somewhere}>navigate here</a>
/// ```
///
/// ```jsx
/// <a {...spread}>navigate here</a>
/// ```
///
/// ## Accessibility guidelines
///
/// - [WCAG 2.1.1](https://www.w3.org/WAI/WCAG21/Understanding/keyboard)
///
pub(crate) UseValidAnchor {
version: "10.0.0",
name: "useValidAnchor",
recommended: true,
}
}
/// Representation of the various states
///
/// The `TextRange` of each variant represents the range of where the issue is found.
pub(crate) enum UseValidAnchorState {
/// The anchor element has not `href` attribute
MissingHrefAttribute(TextRange),
/// The value assigned to attribute `href` is not valid
IncorrectHref(TextRange),
/// The element has `href` and `onClick`
CantBeAnchor(TextRange),
}
impl UseValidAnchorState {
fn message(&self) -> MarkupBuf {
match self {
UseValidAnchorState::MissingHrefAttribute(_) => {
(markup! {
"Provide a "<Emphasis>"href"</Emphasis>" attribute for the "<Emphasis>"a"</Emphasis>" element."
}).to_owned()
},
UseValidAnchorState::IncorrectHref(_) => {
(markup! {
"Provide a valid value for the attribute "<Emphasis>"href"</Emphasis>"."
}).to_owned()
}
UseValidAnchorState::CantBeAnchor(_) => {
(markup! {
"Use a "<Emphasis>"button"</Emphasis>" element instead of an "<Emphasis>"a"</Emphasis>" element."
}).to_owned()
}
}
}
fn note(&self) -> MarkupBuf {
match self {
UseValidAnchorState::MissingHrefAttribute(_) => (markup! {
"An anchor element should always have a "<Emphasis>"href"</Emphasis>""
})
.to_owned(),
UseValidAnchorState::IncorrectHref(_) => (markup! {
"The href attribute should be a valid a URL"
})
.to_owned(),
UseValidAnchorState::CantBeAnchor(_) => (markup! {
"Anchor elements should only be used for default sections or page navigation"
})
.to_owned(),
}
}
fn range(&self) -> &TextRange {
match self {
UseValidAnchorState::MissingHrefAttribute(range)
| UseValidAnchorState::CantBeAnchor(range)
| UseValidAnchorState::IncorrectHref(range) => range,
}
}
}
impl Rule for UseValidAnchor {
type Query = Ast<AnyJsxElement>;
type State = UseValidAnchorState;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let name = node.name().ok()?.name_value_token()?;
if name.text_trimmed() == "a" {
let anchor_attribute = node.find_attribute_by_name("href");
let on_click_attribute = node.find_attribute_by_name("onClick");
match (anchor_attribute, on_click_attribute) {
(Some(_), Some(_)) => {
return Some(UseValidAnchorState::CantBeAnchor(
node.syntax().text_trimmed_range(),
))
}
(Some(anchor_attribute), _) => {
if anchor_attribute.initializer().is_none() {
return Some(UseValidAnchorState::IncorrectHref(
anchor_attribute.syntax().text_trimmed_range(),
));
}
let static_value = anchor_attribute.as_static_value()?;
if static_value.as_string_constant().map_or(true, |const_str| {
const_str.is_empty()
|| const_str == "#"
|| const_str.contains("javascript:")
}) {
return Some(UseValidAnchorState::IncorrectHref(
anchor_attribute.syntax().text_trimmed_range(),
));
}
}
(None, Some(on_click_attribute)) => {
return Some(UseValidAnchorState::CantBeAnchor(
on_click_attribute.syntax().text_trimmed_range(),
))
}
(None, None) => {
if !node.has_spread_prop() {
return Some(UseValidAnchorState::MissingHrefAttribute(
node.syntax().text_trimmed_range(),
));
}
}
};
}
None
}
fn diagnostic(_ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let diagnostic = RuleDiagnostic::new(rule_category!(), state.range(), state.message())
.note(state.note())
.note(
markup! {
"Check "<Hyperlink href="https://marcysutton.com/links-vs-buttons-in-modern-web-applications">"this thorough explanation"</Hyperlink>" to better understand the context."
}
);
Some(diagnostic)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/a11y/use_alt_text.rs | crates/rome_js_analyze/src/analyzers/a11y/use_alt_text.rs | use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::{fmt::Display, fmt::Formatter, markup};
use rome_js_syntax::{jsx_ext::AnyJsxElement, TextRange};
use rome_rowan::AstNode;
declare_rule! {
/// Enforce that all elements that require alternative text have meaningful information to relay back to the end user.
///
/// This is a critical component of accessibility for screen reader users in order for them to understand the content's purpose on the page.
/// By default, this rule checks for alternative text on the following elements: `<img>`, `<area>`, `<input type="image">`, and `<object>`.
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// <img src="image.png" />
/// ```
///
/// ```jsx,expect_diagnostic
/// <input type="image" src="image.png" />
/// ```
///
/// ### Valid
///
/// ```jsx
/// <img src="image.png" alt="image alt" />
/// ```
///
/// ```jsx
/// <input type="image" src="image.png" alt="alt text" />
/// ```
///
/// ```jsx
/// <input type="image" src="image.png" aria-label="alt text" />
/// ```
///
/// ```jsx
/// <input type="image" src="image.png" aria-labelledby="someId" />
/// ```
///
/// ## Accessibility guidelines
///
/// - [WCAG 1.1.1](https://www.w3.org/WAI/WCAG21/Understanding/non-text-content.html)
///
pub(crate) UseAltText {
version: "10.0.0",
name: "useAltText",
recommended: true,
}
}
pub enum ValidatedElement {
Object,
Img,
Area,
Input,
}
impl Display for ValidatedElement {
fn fmt(&self, fmt: &mut Formatter) -> std::io::Result<()> {
match self {
ValidatedElement::Object => fmt.write_markup(markup!(<Emphasis>"title"</Emphasis>)),
_ => fmt.write_markup(markup!(<Emphasis>"alt"</Emphasis>)),
}
}
}
impl Rule for UseAltText {
type Query = Ast<AnyJsxElement>;
type State = (ValidatedElement, TextRange);
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let element = ctx.query();
if element.is_custom_component() {
return None;
}
let has_alt = has_valid_alt_text(element);
let has_aria_label = has_valid_label(element, "aria-label");
let has_aria_labelledby = has_valid_label(element, "aria-labelledby");
match element.name_value_token()?.text_trimmed() {
"object" => {
let has_title = has_valid_label(element, "title");
if !has_title && !has_aria_label && !has_aria_labelledby {
match element {
AnyJsxElement::JsxOpeningElement(opening_element) => {
if !opening_element.has_accessible_child() {
return Some((
ValidatedElement::Object,
element.syntax().text_range(),
));
}
}
AnyJsxElement::JsxSelfClosingElement(_) => {
return Some((ValidatedElement::Object, element.syntax().text_range()));
}
}
}
}
"img" => {
if !has_alt && !has_aria_label && !has_aria_labelledby {
return Some((ValidatedElement::Img, element.syntax().text_range()));
}
}
"area" => {
if !has_alt && !has_aria_label && !has_aria_labelledby {
return Some((ValidatedElement::Area, element.syntax().text_range()));
}
}
"input" => {
if has_type_image_attribute(element)
&& !has_alt
&& !has_aria_label
&& !has_aria_labelledby
{
return Some((ValidatedElement::Input, element.syntax().text_range()));
}
}
_ => {}
}
None
}
fn diagnostic(_ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let (validate_element, range) = state;
let message = markup!(
"Provide a text alternative through the "{{validate_element}}", "<Emphasis>"aria-label"</Emphasis>" or "<Emphasis>"aria-labelledby"</Emphasis>" attribute"
).to_owned();
Some(
RuleDiagnostic::new(rule_category!(), range, message).note(markup! {
"Meaningful alternative text on elements helps users relying on screen readers to understand content's purpose within a page."
}),
)
}
}
fn has_type_image_attribute(element: &AnyJsxElement) -> bool {
element
.find_attribute_by_name("type")
.map_or(false, |attribute| {
attribute
.as_static_value()
.map_or(false, |value| value.text() == "image")
})
}
fn has_valid_alt_text(element: &AnyJsxElement) -> bool {
element
.find_attribute_by_name("alt")
.map_or(false, |attribute| {
if attribute.initializer().is_none() {
return false;
}
attribute
.as_static_value()
.map_or(true, |value| !value.is_null_or_undefined())
&& !element.has_trailing_spread_prop(attribute)
})
}
fn has_valid_label(element: &AnyJsxElement, name_to_lookup: &str) -> bool {
element
.find_attribute_by_name(name_to_lookup)
.map_or(false, |attribute| {
if attribute.initializer().is_none() {
return false;
}
attribute.as_static_value().map_or(true, |value| {
!value.is_null_or_undefined() && value.is_not_string_constant("")
}) && !element.has_trailing_spread_prop(attribute)
})
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/a11y/no_auto_focus.rs | crates/rome_js_analyze/src/analyzers/a11y/no_auto_focus.rs | use crate::JsRuleAction;
use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_syntax::{jsx_ext::AnyJsxElement, JsxAttribute};
use rome_rowan::{AstNode, BatchMutationExt};
declare_rule! {
/// Enforce that autoFocus prop is not used on elements.
///
/// Autofocusing elements can cause usability issues for sighted and non-sighted users, alike.
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// <input autoFocus />
/// ```
///
/// ```jsx,expect_diagnostic
/// <input autoFocus="true" />
/// ```
///
/// ```jsx,expect_diagnostic
/// <input autoFocus={"false"} />
/// ```
///
/// ```jsx,expect_diagnostic
/// <input autoFocus={undefined} />
/// ```
///
/// ### Valid
///
/// ```jsx
/// <input />
///```
///
/// ```jsx
/// <div />
///```
///
/// ```jsx
/// <button />
///```
///
/// ```jsx
/// // `autoFocus` prop in user created component is valid
/// <MyComponent autoFocus={true} />
///```
///
/// ## Resources
///
/// - [WHATWG HTML Standard, The autofocus attribute](https://html.spec.whatwg.org/multipage/interaction.html#attr-fe-autofocus)
/// - [The accessibility of HTML 5 autofocus](https://brucelawson.co.uk/2009/the-accessibility-of-html-5-autofocus/)
///
pub(crate) NoAutoFocus {
version: "10.0.0",
name: "noAutofocus",
recommended: true,
}
}
impl Rule for NoAutoFocus {
type Query = Ast<AnyJsxElement>;
type State = JsxAttribute;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
if node.is_custom_component() {
return None;
}
node.find_attribute_by_name("autoFocus")
}
fn diagnostic(_ctx: &RuleContext<Self>, attr: &Self::State) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
attr.syntax().text_trimmed_range(),
markup! {
"Avoid the "<Emphasis>"autoFocus"</Emphasis>" attribute."
},
))
}
fn action(ctx: &RuleContext<Self>, attr: &Self::State) -> Option<JsRuleAction> {
let mut mutation = ctx.root().begin();
if attr.syntax().has_trailing_comments() {
let prev_token = attr.syntax().first_token()?.prev_token()?;
let new_token =
prev_token.append_trivia_pieces(attr.syntax().last_trailing_trivia()?.pieces());
mutation.replace_token_discard_trivia(prev_token, new_token);
}
mutation.remove_node(attr.clone());
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Remove the "<Emphasis>"autoFocus"</Emphasis>" attribute." }
.to_owned(),
mutation,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/no_extra_non_null_assertion.rs | crates/rome_js_analyze/src/analyzers/suspicious/no_extra_non_null_assertion.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_syntax::{
AnyJsAssignment, AnyJsExpression, TsNonNullAssertionAssignment, TsNonNullAssertionExpression,
};
use rome_rowan::{declare_node_union, AstNode, BatchMutationExt};
use crate::JsRuleAction;
declare_rule! {
/// Prevents the wrong usage of the non-null assertion operator (`!`) in TypeScript files.
///
/// > The `!` non-null assertion operator in TypeScript is used to assert that a value's type does not include `null` or `undefined`. Using the operator any more than once on a single value does nothing.
///
/// Source: https://typescript-eslint.io/rules/no-extra-non-null-assertion
///
/// ## Examples
///
/// ### Invalid
/// ```ts,expect_diagnostic
/// const bar = foo!!.bar;
/// ```
///
/// ```ts,expect_diagnostic
/// function fn(bar?: { n: number }) {
/// return bar!?.n;
/// }
/// ```
///
/// ```ts,expect_diagnostic
/// function fn(bar?: { n: number }) {
/// return ((bar!))?.();
/// }
/// ```
///
/// ### Valid
/// ```ts
/// const bar = foo!.bar;
///
/// obj?.string!.trim();
///
/// function fn(key: string | null) {
/// const obj = {};
/// return obj?.[key!];
/// }
/// ```
///
pub(crate) NoExtraNonNullAssertion {
version: "11.0.0",
name: "noExtraNonNullAssertion",
recommended: true,
}
}
declare_node_union! {
pub(crate) AnyTsNonNullAssertion = TsNonNullAssertionAssignment | TsNonNullAssertionExpression
}
impl Rule for NoExtraNonNullAssertion {
type Query = Ast<AnyTsNonNullAssertion>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
match node {
AnyTsNonNullAssertion::TsNonNullAssertionAssignment(_) => {
let parent = node.parent::<AnyJsAssignment>()?;
// Cases considered as invalid:
// - TsNonNullAssertionAssignment > TsNonNullAssertionAssignment
if matches!(parent, AnyJsAssignment::TsNonNullAssertionAssignment(_)) {
return Some(());
}
}
AnyTsNonNullAssertion::TsNonNullAssertionExpression(_) => {
let parent = node.parent::<AnyJsExpression>()?;
// Cases considered as invalid:
// - TsNonNullAssertionAssignment > TsNonNullAssertionExpression
// - TsNonNullAssertionExpression > TsNonNullAssertionExpression
// - JsCallExpression[optional] > TsNonNullAssertionExpression
// - JsStaticMemberExpression[optional] > TsNonNullAssertionExpression
let has_extra_non_assertion = match parent.omit_parentheses() {
AnyJsExpression::JsAssignmentExpression(expr) => expr
.left()
.ok()?
.as_any_js_assignment()?
.as_ts_non_null_assertion_assignment()
.is_some(),
AnyJsExpression::TsNonNullAssertionExpression(_) => true,
AnyJsExpression::JsStaticMemberExpression(expr) => expr.is_optional(),
AnyJsExpression::JsCallExpression(expr) => expr.is_optional(),
_ => false,
};
if has_extra_non_assertion {
return Some(());
}
}
}
None
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let diagnostic = RuleDiagnostic::new(
rule_category!(),
ctx.query().range(),
"Forbidden extra non-null assertion.",
);
Some(diagnostic)
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let mut mutation = ctx.root().begin();
let node = ctx.query();
let excl_token = match node {
AnyTsNonNullAssertion::TsNonNullAssertionAssignment(assignment) => {
assignment.excl_token().ok()?
}
AnyTsNonNullAssertion::TsNonNullAssertionExpression(expression) => {
expression.excl_token().ok()?
}
};
mutation.remove_token(excl_token);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::Always,
message: markup! { "Remove extra non-null assertion." }.to_owned(),
mutation,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/no_comment_text.rs | crates/rome_js_analyze/src/analyzers/suspicious/no_comment_text.rs | use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{AnyJsxChild, JsxText, TriviaPieceKind, T};
use rome_rowan::{AstNode, BatchMutationExt};
use crate::JsRuleAction;
declare_rule! {
/// Prevent comments from being inserted as text nodes
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// const a3 = <div>// comment</div>;
/// ```
///
/// ```js,expect_diagnostic
/// const a4 = <div>/* comment */</div>;
/// ```
///
/// ```js,expect_diagnostic
/// const a5 = <div>/** comment */</div>;
/// ```
///
/// ### Valid
///
/// ```js
/// const a = <div>{/* comment */}</div>;
/// const a1 = <div>{/** comment */}</div>;
/// const a2 = <div className={"cls" /* comment */}></div>;
/// ```
pub(crate) NoCommentText {
version: "0.7.0",
name: "noCommentText",
recommended: true,
}
}
impl Rule for NoCommentText {
type Query = Ast<JsxText>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let n = ctx.query();
let jsx_value = n.text();
let is_single_line_comment = jsx_value.starts_with("//");
let is_multi_line_comment = jsx_value.starts_with("/*") && jsx_value.ends_with("*/");
if is_single_line_comment || is_multi_line_comment {
Some(())
} else {
None
}
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
node.range(),
markup! {
"Wrap "<Emphasis>"comments"</Emphasis>" inside children within "<Emphasis>"braces"</Emphasis>"."
},
))
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
let normalized_comment = format!(
"/*{}*/",
node.text()
.trim_start_matches("/**")
.trim_start_matches("//")
.trim_start_matches("/*")
.trim_end_matches("*/")
);
mutation.replace_node(
AnyJsxChild::JsxText(node.clone()),
AnyJsxChild::JsxExpressionChild(
make::jsx_expression_child(
make::token(T!['{']).with_trailing_trivia([(
TriviaPieceKind::MultiLineComment,
normalized_comment.as_str(),
)]),
make::token(T!['}']),
)
.build(),
),
);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Wrap the comments with braces" }.to_owned(),
mutation,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/no_debugger.rs | crates/rome_js_analyze/src/analyzers/suspicious/no_debugger.rs | use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_syntax::JsDebuggerStatement;
use rome_rowan::{AstNode, BatchMutationExt};
use crate::{utils, JsRuleAction};
declare_rule! {
/// Disallow the use of `debugger`
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// debugger;
/// ```
///
/// ### Valid
///
/// ```js
/// const test = { debugger: 1 };
/// test.debugger;
///```
pub(crate) NoDebugger {
version: "0.7.0",
name: "noDebugger",
recommended: true,
}
}
impl Rule for NoDebugger {
type Query = Ast<JsDebuggerStatement>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(_: &RuleContext<Self>) -> Option<Self::State> {
Some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
node.syntax().text_trimmed_range(),
markup! {
"This is an unexpected use of the "<Emphasis>"debugger"</Emphasis>" statement."
}
.to_owned(),
))
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
utils::remove_statement(&mut mutation, node)?;
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Remove debugger statement" }.to_owned(),
mutation,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/no_double_equals.rs | crates/rome_js_analyze/src/analyzers/suspicious/no_double_equals.rs | use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{AnyJsExpression, AnyJsLiteralExpression, JsBinaryExpression, T};
use rome_js_syntax::{JsSyntaxKind::*, JsSyntaxToken};
use rome_rowan::{BatchMutationExt, SyntaxResult};
use crate::JsRuleAction;
declare_rule! {
/// Require the use of `===` and `!==`
///
/// It is generally bad practice to use `==` for comparison instead of
/// `===`. Double operators will triger implicit [type coercion](https://developer.mozilla.org/en-US/docs/Glossary/Type_coercion)
/// and are thus not prefered. Using strict equality operators is almost
/// always best practice.
///
/// For ergonomic reasons, this rule makes an exception for `== null` for
/// comparing to both `null` and `undefined`.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// foo == bar
/// ```
///
/// ### Valid
///
/// ```js
/// foo == null
///```
///
/// ```js
/// foo != null
///```
///
/// ```js
/// null == foo
///```
///
/// ```js
/// null != foo
///```
pub(crate) NoDoubleEquals {
version: "0.7.0",
name: "noDoubleEquals",
recommended: true,
}
}
impl Rule for NoDoubleEquals {
type Query = Ast<JsBinaryExpression>;
type State = JsSyntaxToken;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let n = ctx.query();
let op = n.operator_token().ok()?;
if !matches!(op.kind(), EQ2 | NEQ) {
return None;
}
// TODO: Implement SyntaxResult helpers to make this cleaner
if is_null_literal(n.left()) || is_null_literal(n.right()) {
return None;
}
Some(op)
}
fn diagnostic(_ctx: &RuleContext<Self>, op: &Self::State) -> Option<RuleDiagnostic> {
let text_trimmed = op.text_trimmed();
let suggestion = if op.kind() == EQ2 { "===" } else { "!==" };
let description = format!(
"Use {} instead of {}.\n{} is only allowed when comparing against `null`",
suggestion, text_trimmed, text_trimmed
);
Some(RuleDiagnostic::new(
rule_category!(),
op.text_trimmed_range(),
markup! {
"Use "<Emphasis>{suggestion}</Emphasis>" instead of "<Emphasis>{text_trimmed}</Emphasis>
},
)
.detail(op.text_trimmed_range(), markup! {
<Emphasis>{text_trimmed}</Emphasis>" is only allowed when comparing against "<Emphasis>"null"</Emphasis>
}).note(markup! {
"Using "<Emphasis>{suggestion}</Emphasis>" may be unsafe if you are relying on type coercion"
})
.description(description))
}
fn action(ctx: &RuleContext<Self>, op: &Self::State) -> Option<JsRuleAction> {
let mut mutation = ctx.root().begin();
let suggestion = if op.kind() == EQ2 { T![===] } else { T![!==] };
mutation.replace_token(op.clone(), make::token(suggestion));
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
// SAFETY: `suggestion` can only be JsSyntaxKind::EQ3 or JsSyntaxKind::NEQ2,
// the implementation of `to_string` for these two variants always returns Some
message: markup! { "Use "<Emphasis>{suggestion.to_string().unwrap()}</Emphasis> }
.to_owned(),
mutation,
})
}
}
fn is_null_literal(res: SyntaxResult<AnyJsExpression>) -> bool {
matches!(
res,
Ok(AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsNullLiteralExpression(_)
))
)
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/no_async_promise_executor.rs | crates/rome_js_analyze/src/analyzers/suspicious/no_async_promise_executor.rs | use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{AnyJsExpression, AnyJsFunction, JsNewExpression, JsNewExpressionFields};
use rome_rowan::{AstNode, AstSeparatedList};
declare_rule! {
/// Disallows using an async function as a Promise executor.
///
/// The executor function can also be an async function. However, this is usually a mistake, for a few reasons:
/// 1. If an async executor function throws an error, the error will be lost and won't cause the newly-constructed `Promise` to reject. This could make it difficult to debug and handle some errors.
/// 2. If a Promise executor function is using `await`, this is usually a sign that it is not actually necessary to use the `new Promise` constructor, or the scope of the `new Promise` constructor can be reduced.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// new Promise(async function foo(resolve, reject) {})
/// ```
///
/// ```js,expect_diagnostic
/// new Promise(async (resolve, reject) => {})
/// ```
///
/// ```js,expect_diagnostic
/// new Promise(((((async () => {})))))
/// ```
///
/// ### Valid
///
/// ```js
/// new Promise((resolve, reject) => {})
/// new Promise((resolve, reject) => {}, async function unrelated() {})
/// new Foo(async (resolve, reject) => {})
/// new Foo((( (resolve, reject) => {} )))
/// ```
pub(crate) NoAsyncPromiseExecutor {
version: "0.7.0",
name: "noAsyncPromiseExecutor",
recommended: true,
}
}
impl Rule for NoAsyncPromiseExecutor {
type Query = Ast<JsNewExpression>;
type State = AnyJsFunction;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let node = ctx.query();
let JsNewExpressionFields {
new_token: _,
callee,
type_arguments: _,
arguments,
} = node.as_fields();
let callee = callee.ok()?;
let is_promise_constructor = callee
.as_js_identifier_expression()
.and_then(|ident| ident.name().ok())
.map_or(false, |name| name.syntax().text_trimmed() == "Promise");
if !is_promise_constructor {
return None;
}
// get first argument of the `Promise` constructor
let first_arg = arguments?.args().iter().next()?.ok()?;
if let Some(expr) = first_arg.as_any_js_expression() {
get_async_function_expression_like(expr)
} else {
None
}
}
fn diagnostic(_: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
state.range(),
markup! {
"Promise executor functions should not be `async`."
},
))
}
}
/// Check if the expression is async function expression like, include the edge case
/// ```js
/// ((((((async function () {}))))))
/// ```
fn get_async_function_expression_like(expr: &AnyJsExpression) -> Option<AnyJsFunction> {
match expr.clone().omit_parentheses() {
AnyJsExpression::JsFunctionExpression(func) => func
.async_token()
.map(|_| AnyJsFunction::JsFunctionExpression(func.clone())),
AnyJsExpression::JsArrowFunctionExpression(func) => func
.async_token()
.map(|_| AnyJsFunction::JsArrowFunctionExpression(func.clone())),
_ => None,
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/no_redundant_use_strict.rs | crates/rome_js_analyze/src/analyzers/suspicious/no_redundant_use_strict.rs | use crate::JsRuleAction;
use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_syntax::{
AnyJsClass, JsDirective, JsDirectiveList, JsFunctionBody, JsModule, JsScript,
};
use rome_rowan::{declare_node_union, AstNode, BatchMutationExt};
declare_rule! {
/// Prevents from having redundant `"use strict"`.
///
/// ## Examples
///
/// ### Invalid
/// ```cjs,expect_diagnostic
/// "use strict";
/// function foo() {
/// "use strict";
/// }
/// ```
/// ```cjs,expect_diagnostic
/// "use strict";
/// "use strict";
///
/// function foo() {
///
/// }
/// ```
/// ```cjs,expect_diagnostic
/// function foo() {
/// "use strict";
/// "use strict";
/// }
/// ```
/// ```cjs,expect_diagnostic
/// class C1 {
/// test() {
/// "use strict";
/// }
/// }
/// ```
/// ```cjs,expect_diagnostic
/// const C2 = class {
/// test() {
/// "use strict";
/// }
/// };
///
/// ```
/// ### Valid
/// ```cjs
/// function foo() {
///
/// }
///```
/// ```cjs
/// function foo() {
/// "use strict";
/// }
/// function bar() {
/// "use strict";
/// }
///```
///
pub(crate) NoRedundantUseStrict {
version: "11.0.0",
name: "noRedundantUseStrict",
recommended: true,
}
}
declare_node_union! { AnyNodeWithDirectives = JsFunctionBody | JsScript }
impl AnyNodeWithDirectives {
fn directives(&self) -> JsDirectiveList {
match self {
AnyNodeWithDirectives::JsFunctionBody(node) => node.directives(),
AnyNodeWithDirectives::JsScript(script) => script.directives(),
}
}
}
declare_node_union! { pub(crate) AnyJsStrictModeNode = AnyJsClass| JsModule | JsDirective }
impl Rule for NoRedundantUseStrict {
type Query = Ast<JsDirective>;
type State = AnyJsStrictModeNode;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
if node.inner_string_text().ok()? != "use strict" {
return None;
}
let mut outer_most: Option<AnyJsStrictModeNode> = None;
let root = ctx.root();
match root {
rome_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
}
}
} else if let Some(module_or_class) = AnyJsClass::cast_ref(&n) {
outer_most = Some(module_or_class.into());
}
}
}
}
if let Some(outer_most) = outer_most {
// skip itself
if outer_most.syntax() == node.syntax() {
return None;
}
return Some(outer_most);
}
None
}
fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let mut diag = RuleDiagnostic::new(
rule_category!(),
ctx.query().range(),
markup! {
"Redundant "<Emphasis>{"use strict"}</Emphasis>" directive."
},
);
match state {
AnyJsStrictModeNode::AnyJsClass(js_class) => diag = diag.detail(
js_class.range(),
markup! {"All parts of a class's body are already in strict mode."},
) ,
AnyJsStrictModeNode::JsModule(_js_module) => diag= diag.note(
markup! {"The entire contents of "<Emphasis>{"JavaScript modules"}</Emphasis>" are automatically in strict mode, with no statement needed to initiate it."},
),
AnyJsStrictModeNode::JsDirective(js_directive) => diag= diag.detail(
js_directive.range(),
markup! {"This outer "<Emphasis>{"use strict"}</Emphasis>" directive already enables strict mode."},
),
}
Some(diag)
}
fn action(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<JsRuleAction> {
let root = ctx.root();
let mut batch = root.begin();
batch.remove_node(ctx.query().clone());
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::Always,
message: markup! { "Remove the redundant \"use strict\" directive" }.to_owned(),
mutation: batch,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/no_self_compare.rs | crates/rome_js_analyze/src/analyzers/suspicious/no_self_compare.rs | use crate::utils::is_node_equal;
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Ast, Rule, RuleDiagnostic};
use rome_js_syntax::JsBinaryExpression;
use rome_rowan::AstNode;
declare_rule! {
/// Disallow comparisons where both sides are exactly the same.
///
/// > Comparing a variable against itself is usually an error, either a typo or refactoring error. It is confusing to the reader and may potentially introduce a runtime error.
///
/// > The only time you would compare a variable against itself is when you are testing for `NaN`.
/// However, it is far more appropriate to use `typeof x === 'number' && Number.isNaN(x)` for that use case rather than leaving the reader of the code to determine the intent of self comparison.
///
/// Source: [no-self-compare](https://eslint.org/docs/latest/rules/no-self-compare).
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// if (x === x) {}
/// ```
///
/// ```js,expect_diagnostic
/// if (a.b.c() !== a.b .c()) {}
/// ```
///
pub(crate) NoSelfCompare {
version: "12.0.0",
name: "noSelfCompare",
recommended: true,
}
}
impl Rule for NoSelfCompare {
type Query = Ast<JsBinaryExpression>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
if !node.is_comparison_operator() {
return None;
}
let left = node.left().ok()?;
let right = node.right().ok()?;
if is_node_equal(left.syntax(), right.syntax()) {
return Some(());
}
None
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
ctx.query().range(),
"Comparing to itself is potentially pointless.",
))
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/no_const_enum.rs | crates/rome_js_analyze/src/analyzers/suspicious/no_const_enum.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_syntax::TsEnumDeclaration;
use rome_rowan::{chain_trivia_pieces, trim_leading_trivia_pieces, AstNode, BatchMutationExt};
use crate::JsRuleAction;
declare_rule! {
/// Disallow TypeScript `const enum`
///
/// Const enums are enums that should be inlined at use sites.
/// Const enums are not supported by bundlers and are incompatible with the `isolatedModules` mode.
/// Their use can lead to import nonexistent values (because const enums are erased).
///
/// Thus, library authors and bundler users should not use const enums.
///
/// ## Examples
///
/// ### Invalid
///
/// ```ts,expect_diagnostic
/// const enum Status {
/// Open,
/// Close,
/// }
/// ```
///
/// ### Valid
///
/// ```ts
/// enum Status {
/// Open,
/// Close,
/// }
/// ```
pub(crate) NoConstEnum {
version: "11.0.0",
name: "noConstEnum",
recommended: true,
}
}
impl Rule for NoConstEnum {
type Query = Ast<TsEnumDeclaration>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let enum_decl = ctx.query();
enum_decl.const_token().and(Some(()))
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let enum_decl = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
enum_decl.range(),
markup! {
"The "<Emphasis>"enum declaration"</Emphasis>" should not be "<Emphasis>"const"</Emphasis>
},
).note(
"Const enums are not supported by bundlers and are incompatible with the 'isolatedModules' mode. Their use can lead to import inexistent values."
).note(markup! {
"See "<Hyperlink href="https://www.typescriptlang.org/docs/handbook/enums.html#const-enum-pitfalls">"TypeScript Docs"</Hyperlink>" for more details."
}))
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let enum_decl = ctx.query();
let mut mutation = ctx.root().begin();
let const_token = enum_decl.const_token()?;
let enum_token = enum_decl.enum_token().ok()?;
let new_enum_token = enum_token.prepend_trivia_pieces(chain_trivia_pieces(
const_token.leading_trivia().pieces(),
trim_leading_trivia_pieces(const_token.trailing_trivia().pieces()),
));
mutation.remove_token(const_token);
mutation.replace_token_discard_trivia(enum_token, new_enum_token);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::Always,
message: markup! {
"Turn the "<Emphasis>"const enum"</Emphasis>" into a regular "<Emphasis>"enum"</Emphasis>"."
}.to_owned(),
mutation,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/no_duplicate_class_members.rs | crates/rome_js_analyze/src/analyzers/suspicious/no_duplicate_class_members.rs | use std::collections::{HashMap, HashSet};
use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_js_syntax::{
AnyJsClassMemberName, JsClassMemberList, JsGetterClassMember, JsMethodClassMember,
JsPropertyClassMember, JsSetterClassMember, JsStaticModifier, JsSyntaxList, TextRange,
};
use rome_rowan::{declare_node_union, AstNode};
use rome_rowan::{AstNodeList, TokenText};
declare_rule! {
/// Disallow duplicate class members.
///
/// If there are declarations of the same name among class members,
/// the last declaration overwrites other declarations silently.
/// It can cause unexpected behaviours.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// class Foo {
/// bar() { }
/// bar() { }
/// }
/// ```
///
/// ```js,expect_diagnostic
/// class Foo {
/// bar() { }
/// get bar() { }
/// }
/// ```
///
/// ```js,expect_diagnostic
/// class Foo {
/// bar;
/// bar() { }
/// }
/// ```
///
/// ```js,expect_diagnostic
/// class Foo {
/// static bar() { }
/// static bar() { }
/// }
/// ```
///
/// ## Valid
///
/// ```js
/// class Foo {
/// bar() { }
/// qux() { }
/// }
/// ```
///
/// ```js
/// class Foo {
/// set bar(value) { }
/// get bar() { }
/// }
/// ```
///
/// ```js
/// class Foo {
/// bar;
/// qux;
/// }
/// ```
///
/// ```js
/// class Foo {
/// bar;
/// qux() { }
/// }
/// ```
///
/// ```js
/// class Foo {
/// static bar() { }
/// bar() { }
/// }
/// ```
///
pub(crate) NoDuplicateClassMembers {
version: "12.0.0",
name: "noDuplicateClassMembers",
recommended: true,
}
}
fn get_member_name(node: &AnyJsClassMemberName) -> Option<TokenText> {
match node {
AnyJsClassMemberName::JsLiteralMemberName(node) => node.name().ok(),
_ => None,
}
}
fn is_static_member(node: JsSyntaxList) -> bool {
node.into_iter().any(|m| {
if let rome_rowan::SyntaxSlot::Node(node) = m {
JsStaticModifier::can_cast(node.kind())
} else {
false
}
})
}
declare_node_union! {
pub(crate) AnyClassMemberDefinition = JsGetterClassMember | JsMethodClassMember | JsPropertyClassMember | JsSetterClassMember
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum MemberType {
Normal,
Getter,
Setter,
}
impl AnyClassMemberDefinition {
fn name(&self) -> Option<AnyJsClassMemberName> {
match self {
AnyClassMemberDefinition::JsGetterClassMember(node) => node.name().ok(),
AnyClassMemberDefinition::JsMethodClassMember(node) => node.name().ok(),
AnyClassMemberDefinition::JsPropertyClassMember(node) => node.name().ok(),
AnyClassMemberDefinition::JsSetterClassMember(node) => node.name().ok(),
}
}
fn modifiers_list(&self) -> JsSyntaxList {
match self {
AnyClassMemberDefinition::JsGetterClassMember(node) => {
node.modifiers().syntax_list().clone()
}
AnyClassMemberDefinition::JsMethodClassMember(node) => {
node.modifiers().syntax_list().clone()
}
AnyClassMemberDefinition::JsPropertyClassMember(node) => {
node.modifiers().syntax_list().clone()
}
AnyClassMemberDefinition::JsSetterClassMember(node) => {
node.modifiers().syntax_list().clone()
}
}
}
fn range(&self) -> TextRange {
match self {
AnyClassMemberDefinition::JsGetterClassMember(node) => node.range(),
AnyClassMemberDefinition::JsMethodClassMember(node) => node.range(),
AnyClassMemberDefinition::JsPropertyClassMember(node) => node.range(),
AnyClassMemberDefinition::JsSetterClassMember(node) => node.range(),
}
}
fn member_type(&self) -> MemberType {
match self {
AnyClassMemberDefinition::JsGetterClassMember(_) => MemberType::Getter,
AnyClassMemberDefinition::JsMethodClassMember(_) => MemberType::Normal,
AnyClassMemberDefinition::JsPropertyClassMember(_) => MemberType::Normal,
AnyClassMemberDefinition::JsSetterClassMember(_) => MemberType::Setter,
}
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct MemberState {
name: String,
is_static: bool,
}
impl Rule for NoDuplicateClassMembers {
type Query = Ast<JsClassMemberList>;
type State = AnyClassMemberDefinition;
type Signals = Vec<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let mut defined_members: HashMap<MemberState, HashSet<MemberType>> = HashMap::new();
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_state = MemberState {
name: get_member_name(&member_name_node)?.to_string(),
is_static: is_static_member(member_definition.modifiers_list()),
};
let member_type = member_definition.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);
} else {
stored_members.insert(member_type);
}
} else {
defined_members.insert(member_state, HashSet::from([member_type]));
}
None
})
.collect()
}
fn diagnostic(_: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let diagnostic = RuleDiagnostic::new(
rule_category!(),
state.range(),
format!(
"Duplicate class member name {:?}",
get_member_name(&state.name()?)?.text()
),
);
Some(diagnostic)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/no_explicit_any.rs | crates/rome_js_analyze/src/analyzers/suspicious/no_explicit_any.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::TsAnyType;
use rome_rowan::AstNode;
declare_rule! {
/// Disallow the `any` type usage.
///
/// The `any` type in TypeScript is a dangerous "escape hatch" from the type system.
/// Using `any` disables many type checking rules and is generally best used only as a last resort or when prototyping code.
///
/// TypeScript's `--noImplicitAny` compiler option prevents an implied `any`,
/// but doesn't prevent `any` from being explicitly used the way this rule does.
///
/// Source: https://typescript-eslint.io/rules/no-explicit-any
///
/// ## Examples
///
/// ### Invalid
///
/// ```ts,expect_diagnostic
/// let variable: any = 1;
/// ```
///
/// ```ts,expect_diagnostic
/// class SomeClass {
/// message: Array<Array<any>>;
/// }
/// ```
///
/// ```ts,expect_diagnostic
/// function fn(param: Array<any>): void {}
/// ```
///
/// ### Valid
///
/// ```ts
/// let variable: number = 1;
/// let variable2 = 1;
/// ```
///
/// ```ts
/// class SomeClass {
/// message: Array<Array<unknown>>;
/// }
/// ```
///
/// ```ts
/// function fn(param: Array<Array<unknown>>): Array<unknown> {}
/// ```
///
/// ```
pub(crate) NoExplicitAny {
version: "10.0.0",
name: "noExplicitAny",
recommended: true,
}
}
impl Rule for NoExplicitAny {
type Query = Ast<TsAnyType>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(_: &RuleContext<Self>) -> Self::Signals {
Some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let diagnostic = RuleDiagnostic::new(
rule_category!(),
ctx.query().range(),
markup! {"Unexpected "<Emphasis>"any"</Emphasis>". Specify a different type."}
.to_owned(),
).note(markup! {
<Emphasis>"any"</Emphasis>" disables many type checking rules. Its use should be avoided."
});
Some(diagnostic)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/no_duplicate_object_keys.rs | crates/rome_js_analyze/src/analyzers/suspicious/no_duplicate_object_keys.rs | use crate::utils::batch::JsBatchMutation;
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{
AnyJsObjectMember, JsGetterObjectMember, JsObjectExpression, JsSetterObjectMember,
};
use rome_js_syntax::{
JsMethodObjectMember, JsPropertyObjectMember, JsShorthandPropertyObjectMember, TextRange,
};
use rome_rowan::{AstNode, BatchMutationExt, TokenText};
use std::cmp::Ordering;
use std::collections::HashMap;
use std::fmt::Display;
use crate::JsRuleAction;
declare_rule! {
/// Prevents object literals having more than one property declaration for the same name.
/// If an object property with the same name is defined multiple times (except when combining a getter with a setter), only the last definition makes it into the object and previous definitions are ignored, which is likely a mistake.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// const obj = {
/// a: 1,
/// a: 2,
/// }
/// ```
///
/// ```js,expect_diagnostic
/// const obj = {
/// set a(v) {},
/// a: 2,
/// }
/// ```
///
/// ### Valid
///
/// ```js
/// const obj = {
/// a: 1,
/// b: 2,
/// }
/// ```
///
/// ```js
/// const obj = {
/// get a() { return 1; },
/// set a(v) {},
/// }
/// ```
///
pub(crate) NoDuplicateObjectKeys {
version: "11.0.0",
name: "noDuplicateObjectKeys",
recommended: true,
}
}
/// An object member defining a single object property.
enum MemberDefinition {
Getter(JsGetterObjectMember),
Setter(JsSetterObjectMember),
Method(JsMethodObjectMember),
Property(JsPropertyObjectMember),
ShorthandProperty(JsShorthandPropertyObjectMember),
}
impl MemberDefinition {
fn name(&self) -> Option<TokenText> {
match self {
MemberDefinition::Getter(getter) => {
getter.name().ok()?.as_js_literal_member_name()?.name().ok()
}
MemberDefinition::Setter(setter) => {
setter.name().ok()?.as_js_literal_member_name()?.name().ok()
}
MemberDefinition::Method(method) => {
method.name().ok()?.as_js_literal_member_name()?.name().ok()
}
MemberDefinition::Property(property) => property
.name()
.ok()?
.as_js_literal_member_name()?
.name()
.ok(),
MemberDefinition::ShorthandProperty(shorthand_property) => Some(
shorthand_property
.name()
.ok()?
.value_token()
.ok()?
.token_text_trimmed(),
),
}
}
fn range(&self) -> TextRange {
match self {
MemberDefinition::Getter(getter) => getter.range(),
MemberDefinition::Setter(setter) => setter.range(),
MemberDefinition::Method(method) => method.range(),
MemberDefinition::Property(property) => property.range(),
MemberDefinition::ShorthandProperty(shorthand_property) => shorthand_property.range(),
}
}
fn node(&self) -> AnyJsObjectMember {
match self {
MemberDefinition::Getter(getter) => AnyJsObjectMember::from(getter.clone()),
MemberDefinition::Setter(setter) => AnyJsObjectMember::from(setter.clone()),
MemberDefinition::Method(method) => AnyJsObjectMember::from(method.clone()),
MemberDefinition::Property(property) => AnyJsObjectMember::from(property.clone()),
MemberDefinition::ShorthandProperty(shorthand_property) => {
AnyJsObjectMember::from(shorthand_property.clone())
}
}
}
}
impl Display for MemberDefinition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Getter(_) => "getter",
Self::Setter(_) => "setter",
Self::Method(_) => "method",
Self::Property(_) => "property value",
Self::ShorthandProperty(_) => "shorthand property",
})?;
if let Some(name) = self.name() {
f.write_str(" named ")?;
f.write_str(&name)?;
}
Ok(())
}
}
enum MemberDefinitionError {
NotASinglePropertyMember,
BogusMemberType,
}
impl TryFrom<AnyJsObjectMember> for MemberDefinition {
type Error = MemberDefinitionError;
fn try_from(member: AnyJsObjectMember) -> Result<Self, Self::Error> {
match member {
AnyJsObjectMember::JsGetterObjectMember(member) => Ok(MemberDefinition::Getter(member)),
AnyJsObjectMember::JsSetterObjectMember(member) => Ok(MemberDefinition::Setter(member)),
AnyJsObjectMember::JsMethodObjectMember(member) => Ok(MemberDefinition::Method(member)),
AnyJsObjectMember::JsPropertyObjectMember(member) => {
Ok(MemberDefinition::Property(member))
}
AnyJsObjectMember::JsShorthandPropertyObjectMember(member) => {
Ok(MemberDefinition::ShorthandProperty(member))
}
AnyJsObjectMember::JsSpread(_) => Err(MemberDefinitionError::NotASinglePropertyMember),
AnyJsObjectMember::JsBogusMember(_) => Err(MemberDefinitionError::BogusMemberType),
}
}
}
/// A descriptor for a property that is, as far as we can tell from statically analyzing the object expression,
/// not overwritten by another object member and will make it into the object.
#[derive(Clone)]
enum DefinedProperty {
Get(TextRange),
Set(TextRange),
GetSet(TextRange, TextRange),
Value(TextRange),
}
impl From<MemberDefinition> for DefinedProperty {
fn from(definition: MemberDefinition) -> Self {
match definition {
MemberDefinition::Getter(getter) => DefinedProperty::Get(getter.range()),
MemberDefinition::Setter(setter) => DefinedProperty::Set(setter.range()),
MemberDefinition::Method(method) => DefinedProperty::Value(method.range()),
MemberDefinition::Property(property) => DefinedProperty::Value(property.range()),
MemberDefinition::ShorthandProperty(shorthand_property) => {
DefinedProperty::Value(shorthand_property.range())
}
}
}
}
pub(crate) struct PropertyConflict(DefinedProperty, MemberDefinition);
impl DefinedProperty {
fn extend_with(
&self,
member_definition: MemberDefinition,
) -> Result<DefinedProperty, PropertyConflict> {
match (self, member_definition) {
// Add missing get/set counterpart
(DefinedProperty::Set(set_range), MemberDefinition::Getter(getter)) => {
Ok(DefinedProperty::GetSet(getter.range(), *set_range))
}
(DefinedProperty::Get(get_range), MemberDefinition::Setter(setter)) => {
Ok(DefinedProperty::GetSet(*get_range, setter.range()))
}
// Else conflict
(defined_property, member_definition) => Err(PropertyConflict(
defined_property.clone(),
member_definition,
)),
}
}
}
impl Rule for NoDuplicateObjectKeys {
type Query = Ast<JsObjectExpression>;
type State = PropertyConflict;
type Signals = Vec<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let mut defined_properties: HashMap<TokenText, DefinedProperty> = HashMap::new();
let mut signals: Self::Signals = Vec::new();
for member_definition in node
.members()
.into_iter()
.flatten()
.filter_map(|member| MemberDefinition::try_from(member).ok())
// Note that we iterate from last to first property, so that we highlight properties being overwritten as problems and not those that take effect.
.rev()
{
if let Some(member_name) = member_definition.name() {
match defined_properties.remove(&member_name) {
None => {
defined_properties
.insert(member_name, DefinedProperty::from(member_definition));
}
Some(defined_property) => {
match defined_property.extend_with(member_definition) {
Ok(new_defined_property) => {
defined_properties.insert(member_name, new_defined_property);
}
Err(conflict) => {
signals.push(conflict);
defined_properties.insert(member_name, defined_property);
}
}
}
}
}
}
signals
}
fn diagnostic(
_ctx: &RuleContext<Self>,
PropertyConflict(defined_property, member_definition): &Self::State,
) -> Option<RuleDiagnostic> {
let mut diagnostic = RuleDiagnostic::new(
rule_category!(),
member_definition.range(),
format!(
"This {} is later overwritten by an object member with the same name.",
member_definition
),
);
diagnostic = match defined_property {
DefinedProperty::Get(range) => {
diagnostic.detail(range, "Overwritten with this getter.")
}
DefinedProperty::Set(range) => {
diagnostic.detail(range, "Overwritten with this setter.")
}
DefinedProperty::Value(range) => {
diagnostic.detail(range, "Overwritten with this value.")
}
DefinedProperty::GetSet(get_range, set_range) => match member_definition {
MemberDefinition::Getter(_) => {
diagnostic.detail(get_range, "Overwritten with this getter.")
}
MemberDefinition::Setter(_) => {
diagnostic.detail(set_range, "Overwritten with this setter.")
}
MemberDefinition::Method(_)
| MemberDefinition::Property(_)
| MemberDefinition::ShorthandProperty(_) => match get_range.ordering(*set_range) {
Ordering::Less => diagnostic.detail(set_range, "Overwritten with this setter."),
Ordering::Greater => {
diagnostic.detail(get_range, "Overwritten with this getter.")
}
Ordering::Equal => {
panic!(
"The ranges of the property getter and property setter cannot overlap."
)
}
},
},
};
diagnostic = diagnostic.note("If an object property with the same name is defined multiple times (except when combining a getter with a setter), only the last definition makes it into the object and previous definitions are ignored.");
Some(diagnostic)
}
fn action(
ctx: &RuleContext<Self>,
PropertyConflict(_, member_definition): &Self::State,
) -> Option<JsRuleAction> {
let mut batch = ctx.root().begin();
batch.remove_js_object_member(&member_definition.node());
Some(JsRuleAction {
category: rome_analyze::ActionCategory::QuickFix,
// The property initialization could contain side effects
applicability: rome_diagnostics::Applicability::MaybeIncorrect,
message: markup!("Remove this " {member_definition.to_string()}).to_owned(),
mutation: batch,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/no_unsafe_negation.rs | crates/rome_js_analyze/src/analyzers/suspicious/no_unsafe_negation.rs | use crate::JsRuleAction;
use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{AnyJsExpression, JsInExpression, JsInstanceofExpression, T};
use rome_rowan::{declare_node_union, AstNode, AstNodeExt, BatchMutationExt};
declare_rule! {
/// Disallow using unsafe negation.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// !1 in [1,2];
/// ```
///
/// ```js,expect_diagnostic
/// /**test*/!/** test*/1 instanceof [1,2];
/// ```
///
/// ### Valid
/// ```js
/// -1 in [1,2];
/// ~1 in [1,2];
/// typeof 1 in [1,2];
/// void 1 in [1,2];
/// delete 1 in [1,2];
/// +1 instanceof [1,2];
/// ```
pub(crate) NoUnsafeNegation {
version: "0.7.0",
name: "noUnsafeNegation",
recommended: true,
}
}
impl Rule for NoUnsafeNegation {
type Query = Ast<JsInOrInstanceOfExpression>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let node = ctx.query();
match node {
JsInOrInstanceOfExpression::JsInstanceofExpression(expr) => {
let left = expr.left().ok()?;
if let Some(unary) = left.as_js_unary_expression() {
match unary.operator().ok()? {
rome_js_syntax::JsUnaryOperator::LogicalNot => Some(()),
_ => None,
}
} else {
None
}
}
JsInOrInstanceOfExpression::JsInExpression(expr) => {
let left = expr.property().ok()?;
if let Some(rome_js_syntax::AnyJsExpression::JsUnaryExpression(unary)) =
left.as_any_js_expression()
{
match unary.operator().ok()? {
rome_js_syntax::JsUnaryOperator::LogicalNot => Some(()),
_ => None,
}
} else {
None
}
}
}
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
node.range(),
markup! {
"The negation operator is used unsafely on the left side of this binary expression."
},
))
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
// The action could be splitted to three steps
// 1. Remove `!` operator of unary expression
// 2. Wrap the expression with `()`, convert the expression to a `JsParenthesizedExpression`
// 3. Replace the `JsParenthesizedExpression` to `JsUnaryExpression` by adding a `JsUnaryOperator::LogicalNot`
match node {
JsInOrInstanceOfExpression::JsInstanceofExpression(expr) => {
let left = expr.left().ok()?;
let unary_expression = left.as_js_unary_expression()?;
let argument = unary_expression.argument().ok()?;
let next_expr = expr
.clone()
.replace_node_discard_trivia(left.clone(), argument)?;
let next_parenthesis_expression = make::js_parenthesized_expression(
make::token(T!['(']),
rome_js_syntax::AnyJsExpression::JsInstanceofExpression(next_expr),
make::token(T![')']),
);
let next_unary_expression = make::js_unary_expression(
unary_expression.operator_token().ok()?,
AnyJsExpression::JsParenthesizedExpression(next_parenthesis_expression),
);
mutation.replace_node(
AnyJsExpression::JsInstanceofExpression(expr.clone()),
AnyJsExpression::JsUnaryExpression(next_unary_expression),
);
}
JsInOrInstanceOfExpression::JsInExpression(expr) => {
let left = expr.property().ok()?;
let unary_expression = left.as_any_js_expression()?.as_js_unary_expression()?;
let argument = unary_expression.argument().ok()?;
let next_expr = expr.clone().replace_node_discard_trivia(
left.clone(),
rome_js_syntax::AnyJsInProperty::AnyJsExpression(argument),
)?;
let next_parenthesis_expression = make::js_parenthesized_expression(
make::token(T!['(']),
rome_js_syntax::AnyJsExpression::JsInExpression(next_expr),
make::token(T![')']),
);
let next_unary_expression = make::js_unary_expression(
unary_expression.operator_token().ok()?,
AnyJsExpression::JsParenthesizedExpression(next_parenthesis_expression),
);
mutation.replace_node(
AnyJsExpression::JsInExpression(expr.clone()),
AnyJsExpression::JsUnaryExpression(next_unary_expression),
);
}
}
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Wrap the expression with a parenthesis" }.to_owned(),
mutation,
})
}
}
declare_node_union! {
/// Enum for [JsInstanceofExpression] and [JsInExpression]
#[allow(dead_code)]
pub(crate) JsInOrInstanceOfExpression = JsInstanceofExpression | JsInExpression
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/use_valid_typeof.rs | crates/rome_js_analyze/src/analyzers/suspicious/use_valid_typeof.rs | use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{
AnyJsExpression, AnyJsLiteralExpression, JsBinaryExpression, JsBinaryExpressionFields,
JsBinaryOperator, JsUnaryOperator, TextRange,
};
use rome_rowan::{AstNode, BatchMutationExt};
use crate::JsRuleAction;
declare_rule! {
/// This rule verifies the result of `typeof $expr` unary expressions is being
/// compared to valid values, either string literals containing valid type
/// names or other `typeof` expressions
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// typeof foo === "strnig"
/// ```
///
/// ```js,expect_diagnostic
/// typeof foo == "undefimed"
/// ```
///
/// ```js,expect_diagnostic
/// typeof bar != "nunber"
/// ```
///
/// ```js,expect_diagnostic
/// typeof bar !== "fucntion"
/// ```
///
/// ```js,expect_diagnostic
/// typeof foo === undefined
/// ```
///
/// ```js,expect_diagnostic
/// typeof bar == Object
/// ```
///
/// ```js,expect_diagnostic
/// typeof foo === baz
/// ```
///
/// ```js,expect_diagnostic
/// typeof foo == 5
/// ```
///
/// ```js,expect_diagnostic
/// typeof foo == -5
/// ```
///
/// ### Valid
///
/// ```js
/// typeof foo === "string"
/// ```
///
/// ```js
/// typeof bar == "undefined"
/// ```
///
/// ```js
/// typeof bar === typeof qux
/// ```
pub(crate) UseValidTypeof {
version: "0.7.0",
name: "useValidTypeof",
recommended: true,
}
}
impl Rule for UseValidTypeof {
type Query = Ast<JsBinaryExpression>;
type State = (TypeofError, Option<(AnyJsExpression, JsTypeName)>);
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let n = ctx.query();
let JsBinaryExpressionFields {
left,
operator_token: _,
right,
} = n.as_fields();
if !matches!(
n.operator().ok()?,
JsBinaryOperator::Equality
| JsBinaryOperator::StrictEquality
| JsBinaryOperator::Inequality
| JsBinaryOperator::StrictInequality
) {
return None;
}
let left = left.ok()?;
let right = right.ok()?;
let range = match (&left, &right) {
// Check for `typeof $expr == $lit` and `$lit == typeof $expr`
(
AnyJsExpression::JsUnaryExpression(unary),
lit @ AnyJsExpression::AnyJsLiteralExpression(literal),
)
| (
lit @ AnyJsExpression::AnyJsLiteralExpression(literal),
AnyJsExpression::JsUnaryExpression(unary),
) => {
if unary.operator().ok()? != JsUnaryOperator::Typeof {
return None;
}
if let AnyJsLiteralExpression::JsStringLiteralExpression(literal) = literal {
let literal = literal.value_token().ok()?;
let range = literal.text_trimmed_range();
let literal = literal
.text_trimmed()
.trim_start_matches(['"', '\''])
.trim_end_matches(['"', '\''])
.to_lowercase();
if JsTypeName::from_str(&literal).is_some() {
return None;
}
// Try to fix the casing of the literal eg. "String" -> "string"
let suggestion = literal.to_lowercase();
return Some((
TypeofError::InvalidLiteral(range, literal),
JsTypeName::from_str(&suggestion).map(|type_name| (lit.clone(), type_name)),
));
}
lit.range()
}
// Check for `typeof $expr == typeof $expr`
(
AnyJsExpression::JsUnaryExpression(left),
AnyJsExpression::JsUnaryExpression(right),
) => {
let is_typeof_left = left.operator().ok()? == JsUnaryOperator::Typeof;
let is_typeof_right = right.operator().ok()? == JsUnaryOperator::Typeof;
if is_typeof_left && !is_typeof_right {
right.range()
} else if is_typeof_right && !is_typeof_left {
left.range()
} else {
return None;
}
}
// Check for `typeof $expr == $ident`
(
AnyJsExpression::JsUnaryExpression(unary),
id @ AnyJsExpression::JsIdentifierExpression(ident),
)
| (
AnyJsExpression::JsIdentifierExpression(ident),
id @ AnyJsExpression::JsUnaryExpression(unary),
) => {
if unary.operator().ok()? != JsUnaryOperator::Typeof {
return None;
}
// Try to convert the identifier to a string literal eg. String -> "string"
let suggestion = ident.name().ok().and_then(|name| {
let value = name.value_token().ok()?;
let to_lower = value.text_trimmed().to_lowercase();
let as_type = JsTypeName::from_str(&to_lower)?;
Some((id.clone(), as_type))
});
return Some((TypeofError::InvalidExpression(ident.range()), suggestion));
}
// Check for `typeof $expr == $expr`
(AnyJsExpression::JsUnaryExpression(unary), expr)
| (expr, AnyJsExpression::JsUnaryExpression(unary)) => {
if unary.operator().ok()? != JsUnaryOperator::Typeof {
return None;
}
expr.range()
}
_ => return None,
};
Some((TypeofError::InvalidExpression(range), None))
}
fn diagnostic(_: &RuleContext<Self>, (err, _): &Self::State) -> Option<RuleDiagnostic> {
const TITLE: &str = "Invalid `typeof` comparison value";
Some(match err {
TypeofError::InvalidLiteral(range, literal) => {
RuleDiagnostic::new(rule_category!(), range, TITLE)
.note("not a valid type name")
.description(format!("{TITLE}: \"{literal}\" is not a valid type name"))
}
TypeofError::InvalidExpression(range) => {
RuleDiagnostic::new(rule_category!(), range, TITLE)
.note("not a string literal")
.description(format!("{TITLE}: this expression is not a string literal",))
}
})
}
fn action(ctx: &RuleContext<Self>, (_, suggestion): &Self::State) -> Option<JsRuleAction> {
let mut mutation = ctx.root().begin();
let (expr, type_name) = suggestion.as_ref()?;
mutation.replace_node(
expr.clone(),
AnyJsExpression::AnyJsLiteralExpression(AnyJsLiteralExpression::from(
make::js_string_literal_expression(make::js_string_literal(type_name.as_str())),
)),
);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Compare the result of `typeof` with a valid type name" }.to_owned(),
mutation,
})
}
}
pub enum TypeofError {
InvalidLiteral(TextRange, String),
InvalidExpression(TextRange),
}
pub enum JsTypeName {
Undefined,
Object,
Boolean,
Number,
String,
Function,
Symbol,
BigInt,
}
impl JsTypeName {
/// construct a [JsTypeName] from the textual name of a JavaScript type
fn from_str(s: &str) -> Option<Self> {
Some(match s {
"undefined" => Self::Undefined,
"object" => Self::Object,
"boolean" => Self::Boolean,
"number" => Self::Number,
"string" => Self::String,
"function" => Self::Function,
"symbol" => Self::Symbol,
"bigint" => Self::BigInt,
_ => return None,
})
}
/// Convert a [JsTypeName] to a JS string literal
const fn as_str(&self) -> &'static str {
match self {
Self::Undefined => "undefined",
Self::Object => "object",
Self::Boolean => "boolean",
Self::Number => "number",
Self::String => "string",
Self::Function => "function",
Self::Symbol => "symbol",
Self::BigInt => "bigint",
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/no_compare_neg_zero.rs | crates/rome_js_analyze/src/analyzers/suspicious/no_compare_neg_zero.rs | use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{
AnyJsExpression, AnyJsLiteralExpression, JsBinaryExpression, JsSyntaxKind, JsUnaryOperator,
};
use rome_rowan::{AstNode, BatchMutationExt, SyntaxToken};
use crate::JsRuleAction;
pub struct NoCompareNegZeroState {
operator_kind: &'static str,
left_need_replaced: bool,
right_need_replaced: bool,
}
declare_rule! {
/// Disallow comparing against `-0`
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// (1 >= -0)
/// ```
///
/// ### Valid
///
/// ```js
/// (1 >= 0)
///```
pub(crate) NoCompareNegZero {
version: "0.7.0",
name: "noCompareNegZero",
recommended: true,
}
}
impl Rule for NoCompareNegZero {
type Query = Ast<JsBinaryExpression>;
type State = NoCompareNegZeroState;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let node = ctx.query();
if !node.is_comparison_operator() {
return None;
}
let op = node.operator_token().ok()?;
let left = node.left().ok()?;
let right = node.right().ok()?;
let is_left_neg_zero = is_neg_zero(&left).unwrap_or(false);
let is_right_neg_zero = is_neg_zero(&right).unwrap_or(false);
if is_left_neg_zero || is_right_neg_zero {
// SAFETY: Because we know those T![>] | T![>=] | T![<] | T![<=] | T![==] | T![===] | T![!=] | T![!==] SyntaxKind will
// always success in to_string, you could look at our test case `noCompareNegZero.js`
let operator_kind = op.kind().to_string().unwrap();
Some(NoCompareNegZeroState {
operator_kind,
left_need_replaced: is_left_neg_zero,
right_need_replaced: is_right_neg_zero,
})
} else {
None
}
}
fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
node.range(),
markup! {
"Do not use the "{state.operator_kind}" operator to compare against -0."
},
))
}
fn action(ctx: &RuleContext<Self>, state: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
if state.left_need_replaced {
mutation.replace_node(
node.left().ok()?,
AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsNumberLiteralExpression(
make::js_number_literal_expression(SyntaxToken::new_detached(
JsSyntaxKind::JS_NUMBER_LITERAL,
"0",
[],
[],
)),
),
),
);
}
if state.right_need_replaced {
mutation.replace_node(
node.right().ok()?,
AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsNumberLiteralExpression(
make::js_number_literal_expression(SyntaxToken::new_detached(
JsSyntaxKind::JS_NUMBER_LITERAL,
"0",
[],
[],
)),
),
),
);
}
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::Always,
message: markup! { "Replace -0 with 0" }.to_owned(),
mutation,
})
}
}
fn is_neg_zero(node: &AnyJsExpression) -> Option<bool> {
match node {
AnyJsExpression::JsUnaryExpression(expr) => {
if !matches!(expr.operator().ok()?, JsUnaryOperator::Minus) {
return Some(false);
}
let argument = expr.argument().ok()?;
if let AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsNumberLiteralExpression(expr),
) = argument
{
Some(expr.value_token().ok()?.text_trimmed() == "0")
} else {
Some(false)
}
}
_ => Some(false),
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/no_sparse_array.rs | crates/rome_js_analyze/src/analyzers/suspicious/no_sparse_array.rs | use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{AnyJsArrayElement, AnyJsExpression, JsArrayExpression, TriviaPieceKind};
use rome_rowan::{AstNode, AstNodeExt, AstSeparatedList, BatchMutationExt};
use crate::JsRuleAction;
declare_rule! {
/// Disallow sparse arrays
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// [1,,2]
/// ```
pub(crate) NoSparseArray {
version: "0.7.0",
name: "noSparseArray",
recommended: true,
}
}
impl Rule for NoSparseArray {
type Query = Ast<JsArrayExpression>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let node = ctx.query();
// We defer collect `JsHole` index until user want to apply code action.
node.elements().iter().find_map(|element| {
if matches!(element.ok()?, AnyJsArrayElement::JsArrayHole(_),) {
Some(())
} else {
None
}
})
}
fn diagnostic(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(RuleDiagnostic::new(rule_category!(),
node.syntax().text_trimmed_range(),
markup! {
"This "<Emphasis>"array"</Emphasis>" contains an "<Emphasis>"empty slot"</Emphasis>"."
}
.to_owned()
))
}
fn action(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
let mut final_array_element_list = node.elements();
for (i, item) in final_array_element_list.iter().enumerate() {
if matches!(item, Ok(AnyJsArrayElement::JsArrayHole(_))) {
let undefine_indent = if i == 0 {
make::ident("undefined")
} else {
make::ident("undefined")
.with_leading_trivia([(TriviaPieceKind::Whitespace, " ")])
};
let ident_expr =
make::js_identifier_expression(make::js_reference_identifier(undefine_indent));
// Why we need to use `final_array_element_list.iter().nth(i)` instead of `item`, because every time we
// call `replace_node` the previous iteration `item` is not the descent child of current `final_array_element_list` any more.
let n_element = final_array_element_list.iter().nth(i)?.ok()?;
final_array_element_list = final_array_element_list.replace_node(
n_element,
AnyJsArrayElement::AnyJsExpression(AnyJsExpression::JsIdentifierExpression(
ident_expr,
)),
)?;
}
}
mutation.replace_node(
node.clone(),
make::js_array_expression(
node.l_brack_token().ok()?,
final_array_element_list,
node.r_brack_token().ok()?,
),
);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Replace hole with undefined" }.to_owned(),
mutation,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/use_namespace_keyword.rs | crates/rome_js_analyze/src/analyzers/suspicious/use_namespace_keyword.rs | use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{JsSyntaxToken, TsModuleDeclaration, T};
use rome_rowan::BatchMutationExt;
use crate::JsRuleAction;
declare_rule! {
/// Require using the `namespace` keyword over the `module` keyword to declare TypeScript namespaces.
///
/// TypeScript historically allowed a code organization called _namespace_.
/// [_ECMAScript modules_ are preferred](https://www.typescriptlang.org/docs/handbook/2/modules.html#typescript-namespaces) (`import` / `export`).
///
/// For projects still using _namespaces_, it's preferred to use the `namespace` keyword instead of the `module` keyword.
/// The `module` keyword is deprecated to avoid any confusion with the _ECMAScript modules_ which are often called _modules_.
///
/// Note that TypeScript `module` declarations to describe external APIs (`declare module "foo" {}`) are still allowed.
///
/// Source: https://typescript-eslint.io/rules/prefer-namespace-keyword
///
/// See also: https://www.typescriptlang.org/docs/handbook/namespaces-and-modules.html
///
/// ## Examples
///
/// ### Invalid
///
/// ```ts,expect_diagnostic
/// module Example {}
/// ```
///
/// ## Valid
///
/// ```ts
/// namespace Example {}
/// ```
///
/// ```ts
/// declare module "foo" {}
/// ```
///
pub(crate) UseNamespaceKeyword {
version: "12.0.0",
name: "useNamespaceKeyword",
recommended: true,
}
}
impl Rule for UseNamespaceKeyword {
type Query = Ast<TsModuleDeclaration>;
type State = JsSyntaxToken;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let ts_module = ctx.query();
let token = ts_module.module_or_namespace().ok()?;
ts_module.is_module().ok()?.then_some(token)
}
fn diagnostic(_: &RuleContext<Self>, module_token: &Self::State) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
module_token.text_trimmed_range(),
markup! {
"Use the "<Emphasis>"namespace"</Emphasis>" keyword instead of the outdated "<Emphasis>"module"</Emphasis>" keyword."
},
).note(markup! {
"The "<Emphasis>"module"</Emphasis>" keyword is deprecated to avoid any confusion with the "<Emphasis>"ECMAScript modules"</Emphasis>" which are often called "<Emphasis>"modules"</Emphasis>"."
}))
}
fn action(ctx: &RuleContext<Self>, module_token: &Self::State) -> Option<JsRuleAction> {
let mut mutation = ctx.root().begin();
mutation.replace_token_transfer_trivia(module_token.clone(), make::token(T![namespace]));
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::Always,
message: markup! {"Use "<Emphasis>"namespace"</Emphasis>" instead."}.to_owned(),
mutation,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/no_prototype_builtins.rs | crates/rome_js_analyze/src/analyzers/suspicious/no_prototype_builtins.rs | use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{AnyJsMemberExpression, JsCallExpression, TextRange};
use rome_rowan::AstNode;
declare_rule! {
/// Disallow direct use of `Object.prototype` builtins.
///
/// ECMAScript 5.1 added `Object.create` which allows the creation of an object with a custom prototype.
/// This pattern is often used for objects used as Maps. However, this pattern can lead to errors
/// if something else relies on prototype properties/methods.
/// Moreover, the methods could be shadowed, this can lead to random bugs and denial of service
/// vulnerabilities. For example, calling `hasOwnProperty` directly on parsed JSON like `{"hasOwnProperty": 1}` could lead to vulnerabilities.
/// To avoid subtle bugs like this, you should call these methods from `Object.prototype`.
/// For example, `foo.isPrototypeof(bar)` should be replaced with `Object.prototype.isPrototypeof.call(foo, "bar")`
/// As for the `hasOwn` method, `foo.hasOwn("bar")` should be replaced with `Object.hasOwn(foo, "bar")`.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// var invalid = foo.hasOwnProperty("bar");
/// ```
///
/// ```js,expect_diagnostic
/// var invalid = foo.isPrototypeOf(bar);
/// ```
///
/// ```js,expect_diagnostic
/// var invalid = foo.propertyIsEnumerable("bar");
/// ```
///
/// ## Valid
///
/// ```js
/// var valid = Object.hasOwn(foo, "bar");
/// var valid = Object.prototype.isPrototypeOf.call(foo, bar);
/// var valid = {}.propertyIsEnumerable.call(foo, "bar");
/// ```
///
pub(crate) NoPrototypeBuiltins {
version: "12.0.0",
name: "noPrototypeBuiltins",
recommended: true,
}
}
pub(crate) struct RuleState {
prototype_builtins_method_name: String,
text_range: TextRange,
}
impl Rule for NoPrototypeBuiltins {
type Query = Ast<JsCallExpression>;
type State = RuleState;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> 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()) {
let member_name = member_expr.member_name()?;
let member_name_text = member_name.text();
return is_prototype_builtins(member_name_text).then_some(RuleState {
prototype_builtins_method_name: member_name_text.to_string(),
text_range: member_name.range(),
});
}
None
}
fn diagnostic(_ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let diag = RuleDiagnostic::new(
rule_category!(),
state.text_range,
markup! {
"Do not access Object.prototype method '"{&state.prototype_builtins_method_name}"' from target object."
},
);
if state.prototype_builtins_method_name == "hasOwnProperty" {
Some(
diag.note(markup! {
"It's recommended using "<Emphasis>"Object.hasOwn()"</Emphasis>" instead of using "<Emphasis>"Object.hasOwnProperty()"</Emphasis>"."
})
.note(markup! {
"See "<Hyperlink href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn">"MDN web docs"</Hyperlink>" for more details."
}),
)
} else {
Some(diag)
}
}
}
/// Chekcks if the `Object.prototype` builtins called directly.
fn is_prototype_builtins(token_text: &str) -> bool {
matches!(
token_text,
"hasOwnProperty" | "isPrototypeOf" | "propertyIsEnumerable"
)
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/no_duplicate_jsx_props.rs | crates/rome_js_analyze/src/analyzers/suspicious/no_duplicate_jsx_props.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::jsx_ext::AnyJsxElement;
use rome_js_syntax::{AnyJsxAttribute, JsxAttribute};
use rome_rowan::AstNode;
use std::collections::HashMap;
declare_rule! {
/// Prevents JSX properties to be assigned multiple times.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// <Hello name="John" name="John" />
/// ```
///
/// ```js,expect_diagnostic
/// <label xml:lang="en-US" xml:lang="en-US"></label>
/// ```
///
/// ### Valid
///
/// ```js
/// <Hello firstname="John" lastname="Doe" />
/// ```
///
/// ```js
/// <label xml:lang="en-US" lang="en-US"></label>
/// ```
pub(crate) NoDuplicateJsxProps {
version: "12.1.0",
name: "noDuplicateJsxProps",
recommended: true,
}
}
fn push_attribute(
attr: JsxAttribute,
attributes: &mut HashMap<String, Vec<JsxAttribute>>,
) -> Option<()> {
let name = attr.name().ok()?.syntax().text_trimmed();
let name = name.to_string().to_lowercase();
attributes.entry(name).or_default().push(attr);
Some(())
}
impl Rule for NoDuplicateJsxProps {
type Query = Ast<AnyJsxElement>;
type State = (String, Vec<JsxAttribute>);
type Signals = HashMap<String, Vec<JsxAttribute>>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let mut defined_attributes: HashMap<String, Vec<JsxAttribute>> = HashMap::new();
for attribute in node.attributes() {
if let AnyJsxAttribute::JsxAttribute(attr) = attribute {
let _ = push_attribute(attr, &mut defined_attributes);
}
}
defined_attributes.retain(|_, val| val.len() > 1);
defined_attributes
}
fn diagnostic(_: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let mut attributes = state.1.iter();
let mut diagnostic = RuleDiagnostic::new(
rule_category!(),
attributes.next()?.syntax().text_trimmed_range(),
markup!("This JSX property is assigned multiple times."),
);
for attr in attributes {
diagnostic = diagnostic.detail(
attr.syntax().text_trimmed_range(),
"This attribute is assigned again here.",
)
}
Some(diagnostic)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/no_duplicate_case.rs | crates/rome_js_analyze/src/analyzers/suspicious/no_duplicate_case.rs | use crate::utils::is_node_equal;
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Ast, Rule, RuleDiagnostic};
use rome_js_syntax::{AnyJsExpression, AnyJsSwitchClause, JsCaseClause, JsSwitchStatement};
use rome_rowan::{AstNode, TextRange};
declare_rule! {
/// Disallow duplicate case labels.
/// If a switch statement has duplicate test expressions in case clauses, it is likely that a programmer copied a case clause but forgot to change the test expression.
///
/// Source: https://eslint.org/docs/latest/rules/no-duplicate-case
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// switch (a) {
/// case 1:
/// break;
/// case 1:
/// break;
/// default:
/// break;
/// }
/// ```
///
/// ```js,expect_diagnostic
/// switch (a) {
/// case one:
/// break;
/// case one:
/// break;
/// default:
/// break;
/// }
/// ```
///
/// ```js,expect_diagnostic
/// switch (a) {
/// case "1":
/// break;
/// case "1":
/// break;
/// default:
/// break;
/// }
/// ```
///
/// ### Valid
///
/// ```js
/// switch (a) {
/// case 1:
/// break;
/// case 2:
/// break;
/// default:
/// break;
/// }
/// ```
///
/// ```js
/// switch (a) {
/// case one:
/// break;
/// case two:
/// break;
/// default:
/// break;
/// }
/// ```
///
/// ```js
/// switch (a) {
/// case "1":
/// break;
/// case "2":
/// break;
/// default:
/// break;
/// }
/// ```
pub(crate) NoDuplicateCase {
version: "12.0.0",
name: "noDuplicateCase",
recommended: true,
}
}
impl Rule for NoDuplicateCase {
type Query = Ast<JsSwitchStatement>;
type State = (TextRange, JsCaseClause);
type Signals = Vec<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let mut defined_tests: Vec<AnyJsExpression> = Vec::new();
let mut signals = Vec::new();
for case in node.cases() {
if let AnyJsSwitchClause::JsCaseClause(case) = case {
if let Ok(test) = case.test() {
let define_test = defined_tests
.iter()
.find(|define_test| is_node_equal(define_test.syntax(), test.syntax()));
match define_test {
Some(define_test) => {
signals.push((define_test.range(), case));
}
None => {
defined_tests.push(test);
}
}
}
}
}
signals
}
fn diagnostic(_: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let (first_label_range, case) = state;
case.test().ok().map(|test| {
RuleDiagnostic::new(rule_category!(), test.range(), "Duplicate case label.")
.detail(first_label_range, "The first similar label is here:")
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/no_confusing_labels.rs | crates/rome_js_analyze/src/analyzers/suspicious/no_confusing_labels.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{AnyJsStatement, JsLabeledStatement};
declare_rule! {
/// Disallow labeled statements that are not loops.
///
/// Labeled statements in JavaScript are used in conjunction with `break` and `continue` to control flow around multiple loops.
/// Their use for other statements is suspicious and unfamiliar.
///
/// Source: https://eslint.org/docs/latest/rules/no-labels
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// label: f();
/// ```
///
/// ```js,expect_diagnostic
/// label: {
/// f();
/// break label;
/// }
/// ```
///
/// ```js,expect_diagnostic
/// label: if (a) {
/// f()
/// break label;
/// }
/// ```
///
/// ```js,expect_diagnostic
/// label: switch (a) {
/// case 0:
/// break label;
/// }
/// ```
///
/// ### Valid
///
/// ```js
/// outer: while (a) {
/// while(b) {
/// break outer;
/// }
/// }
/// ```
pub(crate) NoConfusingLabels {
version: "12.0.0",
name: "noConfusingLabels",
recommended: true,
}
}
impl Rule for NoConfusingLabels {
type Query = Ast<JsLabeledStatement>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let labeled_stmt = ctx.query();
match labeled_stmt.body().ok()? {
AnyJsStatement::JsDoWhileStatement(_)
| AnyJsStatement::JsForInStatement(_)
| AnyJsStatement::JsForOfStatement(_)
| AnyJsStatement::JsForStatement(_)
| AnyJsStatement::JsWhileStatement(_) => None,
_ => Some(()),
}
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let labeled_stmt = ctx.query();
Some(
RuleDiagnostic::new(
rule_category!(),
labeled_stmt.label_token().ok()?.text_trimmed_range(),
markup! {
"Unexpected "<Emphasis>"label"</Emphasis>"."
},
)
.note("Only loops should be labeled.\nThe use of labels for other statements is suspicious and unfamiliar."),
)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/use_default_switch_clause_last.rs | crates/rome_js_analyze/src/analyzers/suspicious/use_default_switch_clause_last.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{JsCaseClause, JsDefaultClause};
use rome_rowan::{AstNode, Direction};
declare_rule! {
/// Enforce default clauses in switch statements to be last
///
/// A switch statement can optionally have a default clause.
///
/// If present, it’s usually the last clause, but it doesn’t need to be. It is also allowed to put the default clause before all case clauses, or anywhere between.
/// The behavior is mostly the same as if it was the last clause.
///
/// The default block will be still executed only if there is no match in the case clauses (including those defined after the default),
/// but there is also the ability to “fall through” from the default clause to the following clause in the list.
/// However, such flow is not common and it would be confusing to the readers.
///
/// Even if there is no "fall through" logic, it’s still unexpected to see the default clause before or between the case clauses. By convention, it is expected to be the last clause.
///
/// Source: https://eslint.org/docs/latest/rules/default-case-last
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// switch (foo) {
/// default:
/// break;
/// case 0:
/// break;
/// }
/// ```
///
/// ```js,expect_diagnostic
/// switch (foo) {
/// default:
/// f();
/// case 0:
/// break;
/// }
/// ```
///
/// ```js,expect_diagnostic
/// switch (foo) {
/// case 0:
/// break;
/// default:
/// case 1:
/// break;
/// }
/// ```
///
/// ### Valid
///
/// ```js
/// switch (foo) {
/// case 0:
/// break;
/// case 1:
/// default:
/// break;
/// }
/// ```
///
/// ```js
/// switch (foo) {
/// case 0:
/// break;
/// }
/// ```
///
pub(crate) UseDefaultSwitchClauseLast {
version: "11.0.0",
name: "useDefaultSwitchClauseLast",
recommended: true,
}
}
impl Rule for UseDefaultSwitchClauseLast {
type Query = Ast<JsDefaultClause>;
type State = JsCaseClause;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let default_clause = ctx.query();
let next_case = default_clause
.syntax()
.siblings(Direction::Next)
.find_map(JsCaseClause::cast);
next_case
}
fn diagnostic(ctx: &RuleContext<Self>, next_case: &Self::State) -> Option<RuleDiagnostic> {
let default_clause = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
default_clause.range(),
markup! {
"The "<Emphasis>"default"</Emphasis>" clause should be the last "<Emphasis>"switch"</Emphasis>" clause."
},
).detail(
next_case.range(),
markup! {
"The following "<Emphasis>"case"</Emphasis>" clause is here:"
},
).note(
markup! {
"Regardless its position, the "<Emphasis>"default"</Emphasis>" clause is always executed when there is no match. To avoid confusion, the "<Emphasis>"default"</Emphasis>" clause should be the last "<Emphasis>"switch"</Emphasis>" clause."
}
))
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/no_shadow_restricted_names.rs | crates/rome_js_analyze/src/analyzers/suspicious/no_shadow_restricted_names.rs | use crate::globals::runtime::BUILTIN;
use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::JsIdentifierBinding;
use rome_rowan::AstNode;
declare_rule! {
/// Disallow identifiers from shadowing restricted names.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// function NaN() {}
/// ```
///
/// ```js,expect_diagnostic
/// let Set;
/// ```
///
/// ```js,expect_diagnostic
/// try { } catch(Object) {}
/// ```
///
/// ```js,expect_diagnostic
/// function Array() {}
/// ```
///
/// ```js,expect_diagnostic
/// function test(JSON) {console.log(JSON)}
/// ```
pub(crate) NoShadowRestrictedNames {
version: "0.9.0",
name: "noShadowRestrictedNames",
recommended: true,
}
}
pub struct State {
shadowed_name: String,
}
impl Rule for NoShadowRestrictedNames {
type Query = Ast<JsIdentifierBinding>;
type State = State;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let binding = ctx.query();
let name = binding.name_token().ok()?;
let name = name.text_trimmed();
if BUILTIN.contains(&name) {
Some(State {
shadowed_name: name.to_string(),
})
} else {
None
}
}
fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let binding = ctx.query();
let diag = RuleDiagnostic::new(rule_category!(),
binding.syntax().text_trimmed_range(),
markup! {
"Do not shadow the global \"" {state.shadowed_name} "\" property."
},
)
.note(
markup! {"Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global."},
);
Some(diag)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/no_assign_in_expressions.rs | crates/rome_js_analyze/src/analyzers/suspicious/no_assign_in_expressions.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{
AnyJsArrayAssignmentPatternElement, AnyJsArrayElement, AnyJsAssignment, AnyJsAssignmentPattern,
AnyJsExpression, AnyJsObjectAssignmentPatternMember, AnyJsObjectMember,
JsArrayAssignmentPattern, JsArrayAssignmentPatternRestElement,
JsArrayAssignmentPatternRestElementFields, JsArrayExpression, JsAssignmentExpression,
JsAssignmentOperator, JsAssignmentWithDefault, JsAssignmentWithDefaultFields,
JsBogusAssignment, JsBogusExpression, JsComputedMemberAssignment,
JsComputedMemberAssignmentFields, JsComputedMemberExpression, JsExpressionStatement,
JsForStatement, JsIdentifierAssignment, JsIdentifierExpression, JsObjectAssignmentPattern,
JsObjectAssignmentPatternFields, JsObjectAssignmentPatternPropertyFields, JsObjectExpression,
JsParenthesizedAssignment, JsParenthesizedAssignmentFields, JsParenthesizedExpression,
JsSequenceExpression, JsSpread, JsStaticMemberAssignment, JsStaticMemberAssignmentFields,
JsStaticMemberExpression, JsSyntaxElement, JsSyntaxKind, TsAsAssignment, TsAsAssignmentFields,
TsAsExpression, TsNonNullAssertionAssignment, TsNonNullAssertionAssignmentFields,
TsNonNullAssertionExpression, TsSatisfiesAssignment, TsSatisfiesAssignmentFields,
TsSatisfiesExpression, TsTypeAssertionAssignment, TsTypeAssertionAssignmentFields,
TsTypeAssertionExpression,
};
use rome_rowan::{AstNode, AstSeparatedList, BatchMutationExt, SyntaxError, SyntaxResult};
use crate::JsRuleAction;
declare_rule! {
/// Disallow assignments in expressions.
///
/// In expressions, it is common to mistype a comparison operator (such as `==`) as an assignment operator (such as `=`).
/// Moreover, the use of assignments in expressions is confusing.
/// Indeed, expressions are often considered as side-effect free.
///
/// ## Examples
///
/// ### Invalid
///
/// ```ts,expect_diagnostic
/// let a, b;
/// a = (b = 1) + 1;
/// ```
///
/// ```ts,expect_diagnostic
/// let a;
/// if (a = 1) {
/// }
/// ```
///
/// ```ts,expect_diagnostic
/// function f(a) {
/// return a = 1;
/// }
/// ```
///
/// ### Valid
///
/// ```ts
/// let a;
/// a = 1;
/// ```
pub(crate) NoAssignInExpressions {
version: "12.0.0",
name: "noAssignInExpressions",
recommended: true,
}
}
impl Rule for NoAssignInExpressions {
type Query = Ast<JsAssignmentExpression>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let assign = ctx.query();
let mut ancestor = assign
.syntax()
.ancestors()
.take_while(|x| {
// Allow parens and multiple assign such as `a = b = (c = d)`
JsAssignmentExpression::can_cast(x.kind())
|| JsParenthesizedExpression::can_cast(x.kind())
})
.last()?;
let mut prev_ancestor = ancestor;
ancestor = prev_ancestor.parent()?;
while JsSequenceExpression::can_cast(ancestor.kind()) {
// Allow statements separated by sequences such as `a = 1, b = 2`
prev_ancestor = ancestor;
ancestor = prev_ancestor.parent()?;
}
if JsExpressionStatement::can_cast(ancestor.kind()) {
None
} else if let Some(for_stmt) = JsForStatement::cast(ancestor) {
if let Some(for_test) = for_stmt.test() {
// Disallow assignment in test part of a `for`
(for_test.syntax() == &prev_ancestor).then_some(())
} else {
// Allow assignment in initializer and update parts of a `for`
None
}
} else {
Some(())
}
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let assign = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
assign.range(),
markup! {
"The "<Emphasis>"assignment"</Emphasis>" should not be in an "<Emphasis>"expression"</Emphasis>"."
},
).note(
"The use of assignments in expressions is confusing.\nExpressions are often considered as side-effect free."
))
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let assign = ctx.query();
let op = assign.operator().ok()?;
if let JsAssignmentOperator::Assign = op {
let mut mutation = ctx.root().begin();
let token = assign.operator_token().ok()?;
let binary_expression = make::js_binary_expression(
assign.left().ok()?.try_into_expression().ok()?,
make::token(JsSyntaxKind::EQ3)
.with_leading_trivia_pieces(token.leading_trivia().pieces())
.with_trailing_trivia_pieces(token.trailing_trivia().pieces()),
assign.right().ok()?,
);
mutation.replace_element(
JsSyntaxElement::Node(assign.syntax().clone()),
JsSyntaxElement::Node(binary_expression.into_syntax()),
);
Some(JsRuleAction {
mutation,
applicability: Applicability::MaybeIncorrect,
category: ActionCategory::QuickFix,
message: markup!("Did you mean '==='?").to_owned(),
})
} else {
None
}
}
}
trait TryFromAssignment<T>: Sized {
fn try_from_assignment(value: T) -> SyntaxResult<Self>;
}
pub trait TryIntoExpression<T>: Sized {
fn try_into_expression(self) -> SyntaxResult<T>;
}
impl<T, U> TryIntoExpression<U> for T
where
U: TryFromAssignment<T>,
{
fn try_into_expression(self) -> SyntaxResult<U> {
U::try_from_assignment(self)
}
}
impl TryFromAssignment<AnyJsAssignment> for AnyJsExpression {
fn try_from_assignment(value: AnyJsAssignment) -> SyntaxResult<AnyJsExpression> {
let expression = match value {
AnyJsAssignment::JsBogusAssignment(assigment) => {
AnyJsExpression::JsBogusExpression(assigment.try_into_expression()?)
}
AnyJsAssignment::JsComputedMemberAssignment(assigment) => {
AnyJsExpression::JsComputedMemberExpression(assigment.try_into_expression()?)
}
AnyJsAssignment::JsIdentifierAssignment(assigment) => {
AnyJsExpression::JsIdentifierExpression(assigment.try_into_expression()?)
}
AnyJsAssignment::JsParenthesizedAssignment(assigment) => {
AnyJsExpression::JsParenthesizedExpression(assigment.try_into_expression()?)
}
AnyJsAssignment::JsStaticMemberAssignment(assigment) => {
AnyJsExpression::JsStaticMemberExpression(assigment.try_into_expression()?)
}
AnyJsAssignment::TsAsAssignment(assigment) => {
AnyJsExpression::TsAsExpression(assigment.try_into_expression()?)
}
AnyJsAssignment::TsNonNullAssertionAssignment(assigment) => {
AnyJsExpression::TsNonNullAssertionExpression(assigment.try_into_expression()?)
}
AnyJsAssignment::TsSatisfiesAssignment(assigment) => {
AnyJsExpression::TsSatisfiesExpression(assigment.try_into_expression()?)
}
AnyJsAssignment::TsTypeAssertionAssignment(assigment) => {
AnyJsExpression::TsTypeAssertionExpression(assigment.try_into_expression()?)
}
};
Ok(expression)
}
}
impl TryFromAssignment<JsArrayAssignmentPattern> for JsArrayExpression {
fn try_from_assignment(value: JsArrayAssignmentPattern) -> SyntaxResult<Self> {
let mut elements = Vec::new();
let mut separators = Vec::new();
for element in value.elements().elements() {
if let Ok(Some(separator)) = element.trailing_separator {
separators.push(separator);
}
let element = match element.node? {
AnyJsArrayAssignmentPatternElement::AnyJsAssignmentPattern(assignment) => {
AnyJsArrayElement::AnyJsExpression(assignment.try_into_expression()?)
}
AnyJsArrayAssignmentPatternElement::JsArrayAssignmentPatternRestElement(
assignment,
) => AnyJsArrayElement::JsSpread(assignment.try_into_expression()?),
AnyJsArrayAssignmentPatternElement::JsArrayHole(hole) => {
AnyJsArrayElement::JsArrayHole(hole)
}
AnyJsArrayAssignmentPatternElement::JsAssignmentWithDefault(assignment) => {
AnyJsArrayElement::AnyJsExpression(AnyJsExpression::JsAssignmentExpression(
assignment.try_into_expression()?,
))
}
};
elements.push(element);
}
let elements = make::js_array_element_list(elements.into_iter(), separators.into_iter());
let expression =
make::js_array_expression(value.l_brack_token()?, elements, value.r_brack_token()?);
Ok(expression)
}
}
impl TryFromAssignment<JsArrayAssignmentPatternRestElement> for JsSpread {
fn try_from_assignment(value: JsArrayAssignmentPatternRestElement) -> SyntaxResult<JsSpread> {
let JsArrayAssignmentPatternRestElementFields {
dotdotdot_token,
pattern,
} = value.as_fields();
Ok(make::js_spread(
dotdotdot_token?,
pattern?.try_into_expression()?,
))
}
}
impl TryFromAssignment<JsObjectAssignmentPattern> for JsObjectExpression {
fn try_from_assignment(value: JsObjectAssignmentPattern) -> SyntaxResult<JsObjectExpression> {
let JsObjectAssignmentPatternFields {
l_curly_token,
properties,
r_curly_token,
} = value.as_fields();
let mut members = Vec::new();
let mut separators = Vec::new();
for property in properties.elements() {
if let Ok(Some(separator)) = property.trailing_separator {
separators.push(separator);
}
let member = match property.node? {
AnyJsObjectAssignmentPatternMember::JsBogusAssignment(assigment) => {
AnyJsObjectMember::JsBogusMember(make::js_bogus_member([Some(
JsSyntaxElement::Node(assigment.into_syntax()),
)]))
}
AnyJsObjectAssignmentPatternMember::JsObjectAssignmentPatternProperty(
assigment,
) => {
let JsObjectAssignmentPatternPropertyFields {
member,
colon_token,
pattern,
init,
} = assigment.as_fields();
if init.is_some() {
return Err(SyntaxError::MissingRequiredChild);
} else {
let member = make::js_property_object_member(
member?,
colon_token?,
pattern?.try_into_expression()?,
);
AnyJsObjectMember::JsPropertyObjectMember(member)
}
}
AnyJsObjectAssignmentPatternMember::JsObjectAssignmentPatternRest(assigment) => {
let spread = make::js_spread(
assigment.dotdotdot_token()?,
assigment.target()?.try_into_expression()?,
);
AnyJsObjectMember::JsSpread(spread)
}
AnyJsObjectAssignmentPatternMember::JsObjectAssignmentPatternShorthandProperty(
assigment,
) => {
if assigment.init().is_some() {
return Err(SyntaxError::MissingRequiredChild);
} else {
let member = make::js_shorthand_property_object_member(
make::js_reference_identifier(assigment.identifier()?.name_token()?),
);
AnyJsObjectMember::JsShorthandPropertyObjectMember(member)
}
}
};
members.push(member);
}
let member_list = make::js_object_member_list(members.into_iter(), separators.into_iter());
let expression = make::js_object_expression(l_curly_token?, member_list, r_curly_token?);
Ok(expression)
}
}
impl TryFromAssignment<JsAssignmentWithDefault> for JsAssignmentExpression {
fn try_from_assignment(value: JsAssignmentWithDefault) -> SyntaxResult<JsAssignmentExpression> {
let JsAssignmentWithDefaultFields {
pattern,
eq_token,
default,
} = value.as_fields();
Ok(make::js_assignment_expression(
pattern?, eq_token?, default?,
))
}
}
impl TryFromAssignment<AnyJsAssignmentPattern> for AnyJsExpression {
fn try_from_assignment(value: AnyJsAssignmentPattern) -> SyntaxResult<AnyJsExpression> {
let expression = match value {
AnyJsAssignmentPattern::AnyJsAssignment(assigment) => {
assigment.try_into_expression()?
}
AnyJsAssignmentPattern::JsArrayAssignmentPattern(assigment) => {
AnyJsExpression::JsArrayExpression(assigment.try_into_expression()?)
}
AnyJsAssignmentPattern::JsObjectAssignmentPattern(assigment) => {
AnyJsExpression::JsObjectExpression(assigment.try_into_expression()?)
}
};
Ok(expression)
}
}
impl TryFromAssignment<JsBogusAssignment> for JsBogusExpression {
fn try_from_assignment(value: JsBogusAssignment) -> SyntaxResult<JsBogusExpression> {
Ok(make::js_bogus_expression([Some(JsSyntaxElement::Node(
value.into_syntax(),
))]))
}
}
impl TryFromAssignment<JsComputedMemberAssignment> for JsComputedMemberExpression {
fn try_from_assignment(
value: JsComputedMemberAssignment,
) -> SyntaxResult<JsComputedMemberExpression> {
let JsComputedMemberAssignmentFields {
object,
l_brack_token,
member,
r_brack_token,
} = value.as_fields();
Ok(
make::js_computed_member_expression(object?, l_brack_token?, member?, r_brack_token?)
.build(),
)
}
}
impl TryFromAssignment<JsIdentifierAssignment> for JsIdentifierExpression {
fn try_from_assignment(value: JsIdentifierAssignment) -> SyntaxResult<JsIdentifierExpression> {
Ok(make::js_identifier_expression(
make::js_reference_identifier(value.name_token()?),
))
}
}
impl TryFromAssignment<JsParenthesizedAssignment> for JsParenthesizedExpression {
fn try_from_assignment(
value: JsParenthesizedAssignment,
) -> SyntaxResult<JsParenthesizedExpression> {
let JsParenthesizedAssignmentFields {
l_paren_token,
assignment,
r_paren_token,
} = value.as_fields();
Ok(make::js_parenthesized_expression(
l_paren_token?,
assignment?.try_into_expression()?,
r_paren_token?,
))
}
}
impl TryFromAssignment<JsStaticMemberAssignment> for JsStaticMemberExpression {
fn try_from_assignment(
value: JsStaticMemberAssignment,
) -> SyntaxResult<JsStaticMemberExpression> {
let JsStaticMemberAssignmentFields {
object,
dot_token,
member,
} = value.as_fields();
Ok(make::js_static_member_expression(
object?, dot_token?, member?,
))
}
}
impl TryFromAssignment<TsAsAssignment> for TsAsExpression {
fn try_from_assignment(value: TsAsAssignment) -> SyntaxResult<TsAsExpression> {
let TsAsAssignmentFields {
assignment,
as_token,
ty,
} = value.as_fields();
Ok(make::ts_as_expression(
assignment?.try_into_expression()?,
as_token?,
ty?,
))
}
}
impl TryFromAssignment<TsNonNullAssertionAssignment> for TsNonNullAssertionExpression {
fn try_from_assignment(
value: TsNonNullAssertionAssignment,
) -> SyntaxResult<TsNonNullAssertionExpression> {
let TsNonNullAssertionAssignmentFields {
assignment,
excl_token,
} = value.as_fields();
Ok(make::ts_non_null_assertion_expression(
assignment?.try_into_expression()?,
excl_token?,
))
}
}
impl TryFromAssignment<TsSatisfiesAssignment> for TsSatisfiesExpression {
fn try_from_assignment(value: TsSatisfiesAssignment) -> SyntaxResult<TsSatisfiesExpression> {
let TsSatisfiesAssignmentFields {
assignment,
satisfies_token,
ty,
} = value.as_fields();
Ok(make::ts_satisfies_expression(
assignment?.try_into_expression()?,
satisfies_token?,
ty?,
))
}
}
impl TryFromAssignment<TsTypeAssertionAssignment> for TsTypeAssertionExpression {
fn try_from_assignment(
value: TsTypeAssertionAssignment,
) -> SyntaxResult<TsTypeAssertionExpression> {
let TsTypeAssertionAssignmentFields {
l_angle_token,
ty,
r_angle_token,
assignment,
} = value.as_fields();
Ok(make::ts_type_assertion_expression(
l_angle_token?,
ty?,
r_angle_token?,
assignment?.try_into_expression()?,
))
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/suspicious/no_empty_interface.rs | crates/rome_js_analyze/src/analyzers/suspicious/no_empty_interface.rs | use crate::JsRuleAction;
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::{
make,
syntax::{AnyTsType, T},
};
use rome_js_syntax::{
AnyJsDeclarationClause, TriviaPieceKind, TsInterfaceDeclaration, TsTypeAliasDeclaration,
};
use rome_rowan::{AstNode, AstNodeList, BatchMutationExt};
declare_rule! {
/// Disallow the declaration of empty interfaces.
///
/// > An empty interface in TypeScript does very little: any non-nullable value is assignable to `{}`. Using an empty interface is often a sign of programmer error, such as misunderstanding the concept of `{}` or forgetting to fill in fields.
///
/// Source: https://typescript-eslint.io/rules/no-empty-interface
///
/// ## Examples
///
/// ### Invalid
/// ```ts,expect_diagnostic
/// interface A {}
/// ```
///
/// ```ts,expect_diagnostic
/// // A === B
/// interface A extends B {}
/// ```
///
/// ### Valid
/// ```ts
/// interface A {
/// prop: string;
/// }
///
/// // The interface can be used as an union type.
/// interface A extends B, C {}
/// ```
///
pub(crate) NoEmptyInterface {
version: "11.0.0",
name: "noEmptyInterface",
recommended: true,
}
}
pub enum DiagnosticMessage {
NoEmptyInterface,
NoEmptyInterfaceWithSuper,
}
impl DiagnosticMessage {
/// Convert a [DiagnosticMessage] to a string
fn as_str(&self) -> &'static str {
match self {
Self::NoEmptyInterface => "An empty interface is equivalent to '{}'.",
Self::NoEmptyInterfaceWithSuper => {
"An interface declaring no members is equivalent to its supertype."
}
}
}
/// Retrieves a [TsTypeAliasDeclaration] from a [DiagnosticMessage] that will be used to
/// replace it on the rule action
fn fix_with(&self, node: &TsInterfaceDeclaration) -> Option<TsTypeAliasDeclaration> {
match self {
Self::NoEmptyInterface => make_type_alias_from_interface(
node,
AnyTsType::from(make::ts_object_type(
make::token(T!['{']),
make::ts_type_member_list([]),
make::token(T!['}']),
)),
),
Self::NoEmptyInterfaceWithSuper => {
let super_interface = node.extends_clause()?.types().into_iter().next()?.ok()?;
let type_arguments = super_interface.type_arguments();
let ts_reference_type = make::ts_reference_type(super_interface.name().ok()?);
let ts_reference_type = if type_arguments.is_some() {
ts_reference_type
.with_type_arguments(type_arguments?)
.build()
} else {
ts_reference_type.build()
};
make_type_alias_from_interface(node, AnyTsType::from(ts_reference_type))
}
}
}
}
impl Rule for NoEmptyInterface {
type Query = Ast<TsInterfaceDeclaration>;
type State = DiagnosticMessage;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let has_no_members = node.members().is_empty();
let extends_clause_count = if let Some(extends_clause) = node.extends_clause() {
extends_clause.types().into_iter().count()
} else {
0
};
if extends_clause_count == 0 && has_no_members {
return Some(DiagnosticMessage::NoEmptyInterface);
}
if extends_clause_count == 1 && has_no_members {
return Some(DiagnosticMessage::NoEmptyInterfaceWithSuper);
}
None
}
fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let diagnostic = RuleDiagnostic::new(rule_category!(), ctx.query().range(), state.as_str());
Some(diagnostic)
}
fn action(ctx: &RuleContext<Self>, state: &Self::State) -> Option<JsRuleAction> {
let mut mutation = ctx.root().begin();
let node = ctx.query();
mutation.replace_node(
AnyJsDeclarationClause::from(node.clone()),
AnyJsDeclarationClause::from(state.fix_with(node)?),
);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::Always,
message: markup! { "Convert empty interface to type alias." }.to_owned(),
mutation,
})
}
}
/// Builds a [TsTypeAliasDeclaration] from an [TsInterfaceDeclaration].
fn make_type_alias_from_interface(
node: &TsInterfaceDeclaration,
ts_type: AnyTsType,
) -> Option<TsTypeAliasDeclaration> {
let type_params = node.type_parameters();
let new_node = make::ts_type_alias_declaration(
make::token(T![type]).with_trailing_trivia([(TriviaPieceKind::Whitespace, " ")]),
node.id().ok()?,
make::token(T![=]).with_trailing_trivia([(TriviaPieceKind::Whitespace, " ")]),
ts_type,
);
let new_node = if type_params.is_some() {
new_node.with_type_parameters(type_params?).build()
} else {
new_node.build()
};
Some(new_node)
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/style/no_negation_else.rs | crates/rome_js_analyze/src/analyzers/style/no_negation_else.rs | use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{
AnyJsExpression, AnyJsStatement, JsConditionalExpression, JsIfStatement, JsUnaryExpression,
JsUnaryOperator,
};
use rome_rowan::{declare_node_union, AstNode, AstNodeExt, BatchMutationExt};
use crate::JsRuleAction;
declare_rule! {
/// Disallow negation in the condition of an `if` statement if it has an `else` clause
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// if (!true) {consequent;} else {alternate;}
/// ```
///
/// ```js,expect_diagnostic
/// !true ? consequent : alternate
///```
///
/// ### Valid
///
/// ```js
/// if (!true) {consequent;}
///```
///
/// ```js
/// true ? consequent : alternate
///```
pub(crate) NoNegationElse {
version: "0.7.0",
name: "noNegationElse",
recommended: false,
}
}
impl Rule for NoNegationElse {
type Query = Ast<AnyJsCondition>;
type State = JsUnaryExpression;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let n = ctx.query();
match n {
AnyJsCondition::JsConditionalExpression(expr) => {
if is_negation(&expr.test().ok()?).unwrap_or(false) {
Some(expr.test().ok()?.as_js_unary_expression().unwrap().clone())
} else {
None
}
}
AnyJsCondition::JsIfStatement(stmt) => {
if is_negation(&stmt.test().ok()?).unwrap_or(false)
&& !matches!(
stmt.else_clause()?.alternate().ok()?,
AnyJsStatement::JsIfStatement(_)
)
{
Some(stmt.test().ok()?.as_js_unary_expression().unwrap().clone())
} else {
None
}
}
}
}
fn diagnostic(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
node.range(),
markup! {
"Invert blocks when performing a negation test."
},
))
}
fn action(ctx: &RuleContext<Self>, state: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
match node {
AnyJsCondition::JsConditionalExpression(expr) => {
let mut next_expr = expr
.clone()
.replace_node(expr.test().ok()?, state.argument().ok()?)?;
next_expr = next_expr
.clone()
.replace_node(next_expr.alternate().ok()?, expr.consequent().ok()?)?;
next_expr = next_expr
.clone()
.replace_node(next_expr.consequent().ok()?, expr.alternate().ok()?)?;
mutation.replace_node(
node.clone(),
AnyJsCondition::JsConditionalExpression(next_expr),
);
}
AnyJsCondition::JsIfStatement(stmt) => {
let next_stmt = stmt
.clone()
.replace_node(stmt.test().ok()?, state.argument().ok()?)?;
let next_stmt = next_stmt.clone().replace_node(
next_stmt.else_clause()?,
make::js_else_clause(
stmt.else_clause()?.else_token().ok()?,
stmt.consequent().ok()?,
),
)?;
let next_stmt = next_stmt.clone().replace_node(
next_stmt.consequent().ok()?,
stmt.else_clause()?.alternate().ok()?,
)?;
mutation.replace_node(node.clone(), AnyJsCondition::JsIfStatement(next_stmt));
}
}
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Exchange alternate and consequent of the node" }.to_owned(),
mutation,
})
}
}
fn is_negation(node: &AnyJsExpression) -> Option<bool> {
match node {
AnyJsExpression::JsUnaryExpression(expr) => {
match (expr.operator().ok(), expr.argument().ok()) {
(
Some(JsUnaryOperator::LogicalNot),
Some(AnyJsExpression::JsUnaryExpression(inner_unary)),
) => Some(inner_unary.operator().ok()? != JsUnaryOperator::LogicalNot),
_ => Some(true),
}
}
_ => Some(false),
}
}
declare_node_union! {
pub AnyJsCondition = JsConditionalExpression | JsIfStatement
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/style/no_parameter_properties.rs | crates/rome_js_analyze/src/analyzers/style/no_parameter_properties.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::TsPropertyParameter;
use rome_rowan::AstNode;
declare_rule! {
/// Disallow the use of parameter properties in class constructors.
///
/// TypeScript includes a "parameter properties" shorthand for declaring a class constructor parameter and class property in one location.
/// Parameter properties can confuse those new to TypeScript as they are less explicit than other ways of declaring and initializing class members.
/// Moreover, private class properties, starting with `#`, cannot be turned into "parameter properties".
/// This questions the future of this feature.
///
/// Source: https://typescript-eslint.io/rules/parameter-properties
///
/// ## Examples
///
/// ### Invalid
///
/// ```ts,expect_diagnostic
/// class A {
/// constructor(readonly name: string) {}
/// }
/// ```
///
/// ### Valid
///
/// ```ts
/// class A {
/// constructor(name: string) {}
/// }
/// ```
///
pub(crate) NoParameterProperties {
version: "12.0.0",
name: "noParameterProperties",
recommended: false,
}
}
impl Rule for NoParameterProperties {
type Query = Ast<TsPropertyParameter>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(_: &RuleContext<Self>) -> Self::Signals {
Some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let param_prop = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
param_prop.range(),
markup! {
"Use a more explicit "<Emphasis>"class property"</Emphasis>" instead of a "<Emphasis>"parameter property"</Emphasis>"."
},
).note(
markup! {
<Emphasis>"Parameter properties"</Emphasis>" are less explicit than other ways of declaring and initializing "<Emphasis>"class properties"</Emphasis>"."
}
))
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/style/no_non_null_assertion.rs | crates/rome_js_analyze/src/analyzers/style/no_non_null_assertion.rs | use crate::JsRuleAction;
use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{
AnyJsExpression, TsNonNullAssertionAssignment, TsNonNullAssertionExpression, T,
};
use rome_rowan::{declare_node_union, AstNode, BatchMutationExt};
declare_rule! {
/// Disallow non-null assertions using the `!` postfix operator.
///
/// TypeScript's `!` non-null assertion operator asserts to the type system that an expression is non-nullable, as
/// in not `null` or `undefined`. Using assertions to tell the type system new information is often a sign that
/// code is not fully type-safe. It's generally better to structure program logic so that TypeScript understands
/// when values may be nullable.
///
/// ## Examples
///
/// ### Invalid
///
/// ```ts,expect_diagnostic
/// interface Example {
/// property?: string;
/// }
/// declare const example: Example;
/// const includesBaz = foo.property!.includes('baz');
/// ```
/// ```ts,expect_diagnostic
/// (b!! as number) = "test";
/// ```
///
/// ### Valid
///
/// ```ts
/// interface Example {
/// property?: string;
/// }
///
/// declare const example: Example;
/// const includesBaz = foo.property?.includes('baz') ?? false;
/// ```
///
pub(crate) NoNonNullAssertion {
version: "11.0.0",
name: "noNonNullAssertion",
recommended: true,
}
}
declare_node_union! {
pub(crate) AnyTsNonNullAssertion = TsNonNullAssertionExpression | TsNonNullAssertionAssignment
}
impl Rule for NoNonNullAssertion {
type Query = Ast<AnyTsNonNullAssertion>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
match ctx.query() {
AnyTsNonNullAssertion::TsNonNullAssertionExpression(node) => node
.parent::<TsNonNullAssertionExpression>()
.map_or(Some(()), |_| None),
AnyTsNonNullAssertion::TsNonNullAssertionAssignment(node) => node
.parent::<TsNonNullAssertionAssignment>()
.map_or(Some(()), |_| None),
}
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
ctx.query().range(),
markup! {
"Forbidden non-null assertion."
},
))
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
match node {
AnyTsNonNullAssertion::TsNonNullAssertionAssignment(_) => None,
AnyTsNonNullAssertion::TsNonNullAssertionExpression(node) => {
let mut mutation = ctx.root().begin();
// get the expression without assertion marker
// the loop handles repetitive (useless) assertion marker such as `expr!!!`.
let mut expr = node.expression();
while let Ok(AnyJsExpression::TsNonNullAssertionExpression(assertion)) = expr {
expr = assertion.expression()
}
let assertion_less_expr = expr.ok()?;
let old_node = AnyJsExpression::TsNonNullAssertionExpression(node.clone());
match node.parent::<AnyJsExpression>()? {
AnyJsExpression::JsComputedMemberExpression(parent) => {
if parent.is_optional() {
// object!?["prop"] --> object?.["prop"]
mutation.replace_node(old_node, assertion_less_expr);
} else {
// object!["prop"] --> object?["prop"]
let new_parent = parent
.clone()
.with_optional_chain_token(Some(make::token(T![?.])))
.with_object(assertion_less_expr);
mutation.replace_node(parent, new_parent);
}
}
AnyJsExpression::JsCallExpression(parent) => {
if parent.is_optional() {
// f!?() --> f?()
mutation.replace_node(old_node, assertion_less_expr);
} else {
// f!() --> f?.()
let new_parent = parent
.clone()
.with_optional_chain_token(Some(make::token(T![?.])))
.with_callee(assertion_less_expr);
mutation.replace_node(parent, new_parent);
}
}
AnyJsExpression::JsStaticMemberExpression(parent) => {
if parent.is_optional() {
// object!?.prop --> object?.prop
mutation.replace_node(old_node, assertion_less_expr);
} else {
// object!.prop --> object?.prop
let new_parent = parent
.clone()
.with_operator_token_token(make::token(T![?.]))
.with_object(assertion_less_expr);
mutation.replace_node(parent, new_parent);
}
}
_ => {
// unsupported
return None;
}
};
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Replace with optional chain operator "<Emphasis>"?."</Emphasis>" This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator" }
.to_owned(),
mutation,
})
}
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/style/no_namespace.rs | crates/rome_js_analyze/src/analyzers/style/no_namespace.rs | use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::TsModuleDeclaration;
use rome_rowan::AstNode;
declare_rule! {
/// Disallow the use of TypeScript's `namespace`s.
///
/// Namespaces are an old way to organize your code in TypeScript.
/// They are not recommended anymore and should be replaced by ES6 modules
/// (the `import`/`export` syntax).
///
/// Source: https://typescript-eslint.io/rules/no-namespace
///
/// ## Examples
///
/// ### Invalid
///
/// ```ts,expect_diagnostic
/// module foo {}
/// ```
///
/// ```ts,expect_diagnostic
/// declare module foo {}
/// ```
///
/// ```ts,expect_diagnostic
/// namespace foo {}
/// ```
///
/// ```ts,expect_diagnostic
/// declare namespace foo {}
/// ```
///
/// ## Valid
///
/// ```ts
/// import foo from 'foo';
/// export { bar };
/// ```
///
/// ```ts
/// declare global {}
/// ```
///
/// ```ts
/// declare module 'foo' {}
/// ```
///
pub(crate) NoNamespace {
version: "12.0.0",
name: "noNamespace",
recommended: false,
}
}
impl Rule for NoNamespace {
type Query = Ast<TsModuleDeclaration>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(_: &RuleContext<Self>) -> Self::Signals {
Some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(
RuleDiagnostic::new(
rule_category!(),
node.syntax().text_trimmed_range(),
markup! {
"TypeScript's namespaces are an oudated way to organize code."
},
)
.note(markup! {
"Prefer the ES6 modules (import/export) over namespaces."
}),
)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/style/use_shorthand_array_type.rs | crates/rome_js_analyze/src/analyzers/style/use_shorthand_array_type.rs | use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{
AnyTsType, JsSyntaxKind, JsSyntaxToken, TriviaPieceKind, TsReferenceType, TsTypeArguments, T,
};
use rome_rowan::{AstNode, AstSeparatedList, BatchMutationExt, TriviaPiece};
use crate::JsRuleAction;
declare_rule! {
/// When expressing array types, this rule promotes the usage of `T[]` shorthand instead of `Array<T>`.
///
/// ESLint (typescript-eslint) equivalent: [array-type/array-simple](https://typescript-eslint.io/rules/array-type/#array-simple)
///
/// ## Examples
///
/// ### Invalid
/// ```ts,expect_diagnostic
/// let invalid: Array<foo>;
/// ```
///
/// ```ts,expect_diagnostic
/// let invalid: Promise<Array<string>>;
/// ```
///
/// ```ts,expect_diagnostic
/// let invalid: Array<Foo<Bar>>;
/// ```
///
/// ```ts,expect_diagnostic
/// let invalid: Array<[number, number]>;
/// ```
///
/// ```ts,expect_diagnostic
/// let invalid: Array<[number, number]>;
/// ```
///
/// ```ts,expect_diagnostic
/// let invalid: ReadonlyArray<string>;
/// ```
///
/// ### Valid
///
/// ```ts
/// let valid: Array<Foo | Bar>;
/// let valid: Array<keyof Bar>;
/// let valid: Array<foo | bar>;
/// ```
pub(crate) UseShorthandArrayType {
version: "0.7.0",
name: "useShorthandArrayType",
recommended: false,
}
}
#[derive(Debug)]
enum TsArrayKind {
/// `Array<T>`
Simple,
/// `ReadonlyArray<T>`
Readonly,
}
impl Rule for UseShorthandArrayType {
type Query = Ast<TsReferenceType>;
type State = AnyTsType;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let node = ctx.query();
let type_arguments = node.type_arguments()?;
match get_array_kind_by_reference(node) {
Some(array_kind) => convert_to_array_type(type_arguments, array_kind),
None => None,
}
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
if let Some(kind) = get_array_kind_by_reference(node) {
return Some(RuleDiagnostic::new(
rule_category!(),
node.range(),
match kind {
TsArrayKind::Simple => {
markup! {"Use "<Emphasis>"shorthand T[] syntax"</Emphasis>" instead of "<Emphasis>"Array<T> syntax."</Emphasis>}
}
TsArrayKind::Readonly => {
markup! {"Use "<Emphasis>"shorthand readonly T[] syntax"</Emphasis>" instead of "<Emphasis>"ReadonlyArray<T> syntax."</Emphasis>}
}
},
));
};
None
}
fn action(ctx: &RuleContext<Self>, state: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
mutation.replace_node(AnyTsType::TsReferenceType(node.clone()), state.clone());
if let Some(kind) = get_array_kind_by_reference(node) {
let message = match kind {
TsArrayKind::Simple => {
markup! { "Use "<Emphasis>"shorthand T[] syntax"</Emphasis>" to replace" }
.to_owned()
}
TsArrayKind::Readonly => {
markup! { "Use "<Emphasis>"shorthand readonly T[] syntax"</Emphasis>" to replace" }
.to_owned()
}
};
return Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message,
mutation,
});
};
None
}
}
fn get_array_kind_by_reference(ty: &TsReferenceType) -> Option<TsArrayKind> {
let name = ty.name().ok()?;
name.as_js_reference_identifier().and_then(|identifier| {
let name = identifier.value_token().ok()?;
match name.text_trimmed() {
"Array" => Some(TsArrayKind::Simple),
"ReadonlyArray" => Some(TsArrayKind::Readonly),
_ => None,
}
})
}
fn convert_to_array_type(
type_arguments: TsTypeArguments,
array_kind: TsArrayKind,
) -> Option<AnyTsType> {
if type_arguments.ts_type_argument_list().len() > 0 {
let types_array = type_arguments
.ts_type_argument_list()
.into_iter()
.filter_map(|param| {
let param = param.ok()?;
let element_type = match ¶m {
// Intersection or higher types
AnyTsType::TsUnionType(_)
| AnyTsType::TsIntersectionType(_)
| AnyTsType::TsFunctionType(_)
| AnyTsType::TsConstructorType(_)
| AnyTsType::TsConditionalType(_)
| AnyTsType::TsTypeOperatorType(_)
| AnyTsType::TsInferType(_)
| AnyTsType::TsObjectType(_)
| AnyTsType::TsMappedType(_) => None,
AnyTsType::TsReferenceType(ty) => match get_array_kind_by_reference(ty) {
Some(array_kind) => {
if let Some(type_arguments) = ty.type_arguments() {
convert_to_array_type(type_arguments, array_kind)
} else {
Some(param)
}
}
None => Some(param),
},
_ => Some(param),
};
element_type.map(|element_type| match array_kind {
TsArrayKind::Simple => AnyTsType::TsArrayType(make::ts_array_type(
element_type,
make::token(T!['[']),
make::token(T![']']),
)),
TsArrayKind::Readonly => {
let readonly_token = JsSyntaxToken::new_detached(
JsSyntaxKind::TS_READONLY_MODIFIER,
"readonly ",
[],
[TriviaPiece::new(TriviaPieceKind::Whitespace, 1)],
);
// Modify `ReadonlyArray<ReadonlyArray<T>>` to `readonly (readonly T[])[]`
if let AnyTsType::TsTypeOperatorType(op) = &element_type {
if let Ok(op) = op.operator_token() {
if op.text_trimmed() == "readonly" {
return AnyTsType::TsTypeOperatorType(
make::ts_type_operator_type(
readonly_token,
// wrap ArrayType
AnyTsType::TsArrayType(make::ts_array_type(
AnyTsType::TsParenthesizedType(
make::ts_parenthesized_type(
make::token(T!['(']),
element_type,
make::token(T![')']),
),
),
make::token(T!['[']),
make::token(T![']']),
)),
),
);
}
}
}
AnyTsType::TsTypeOperatorType(make::ts_type_operator_type(
readonly_token,
AnyTsType::TsArrayType(make::ts_array_type(
element_type,
make::token(T!['[']),
make::token(T![']']),
)),
))
}
})
})
.collect::<Vec<_>>();
match types_array.len() {
0 => {}
1 => {
// SAFETY: We know that `length` of `array_types` is 1, so unwrap the first element should be safe.
let first_type = types_array.into_iter().next().unwrap();
return Some(first_type);
}
length => {
let ts_union_type_builder = make::ts_union_type(make::ts_union_type_variant_list(
types_array.into_iter(),
(0..length - 1).map(|_| {
make::token(T![|])
.with_leading_trivia([(TriviaPieceKind::Whitespace, " ")])
.with_trailing_trivia([(TriviaPieceKind::Whitespace, " ")])
}),
));
return Some(AnyTsType::TsUnionType(ts_union_type_builder.build()));
}
}
}
None
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/style/use_enum_initializers.rs | crates/rome_js_analyze/src/analyzers/style/use_enum_initializers.rs | use crate::JsRuleAction;
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{
AnyJsExpression, AnyJsLiteralExpression, JsSyntaxKind, TsDeclareStatement, TsEnumDeclaration,
TsExportDeclareClause,
};
use rome_rowan::{AstNode, BatchMutationExt};
declare_rule! {
/// Require that each enum member value be explicitly initialized.
///
/// _TypeScript_ enums are a practical way to organize semantically related constant values.
/// Members of enums that don't have explicit values are by default given sequentially increasing numbers.
///
/// When the value of enum members are important,
/// allowing implicit values for enum members can cause bugs if enum declarations are modified over time.
///
/// Source: https://typescript-eslint.io/rules/prefer-enum-initializers
///
/// ## Examples
///
/// ### Invalid
///
/// ```ts,expect_diagnostic
/// enum Version {
/// V1,
/// }
/// ```
///
/// ```ts,expect_diagnostic
/// enum Status {
/// Open = 1,
/// Close,
/// }
/// ```
///
/// ```ts,expect_diagnostic
/// enum Color {
/// Red = "Red",
/// Green = "Green",
/// Blue,
/// }
/// ```
///
/// ### Valid
///
/// ```ts
/// enum Status {
/// Open = 1,
/// Close = 2,
/// }
/// ```
///
/// ```ts
/// enum Color {
/// Red = "Red",
/// Green = "Green",
/// Blue = "Blue",
/// }
/// ```
///
/// ```ts
/// declare enum Weather {
/// Rainy,
/// Sunny,
/// }
/// ```
pub(crate) UseEnumInitializers {
version: "11.0.0",
name: "useEnumInitializers",
recommended: true,
}
}
impl Rule for UseEnumInitializers {
// We apply the rule on an entire enum declaration to avoid reporting
// a diagnostic for every enum members without initializers.
type Query = Ast<TsEnumDeclaration>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let enum_declaration = ctx.query();
if enum_declaration.parent::<TsDeclareStatement>().is_some()
|| enum_declaration.parent::<TsExportDeclareClause>().is_some()
{
// In ambient declarations, enum members without initializers are opaque types.
// They generally represent an enum with complex initializers.
return None;
}
for enum_member in enum_declaration.members() {
let enum_member = enum_member.ok()?;
if enum_member.initializer().is_none() {
return Some(());
}
}
None
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let enum_declaration = ctx.query();
let mut diagnostic = RuleDiagnostic::new(
rule_category!(),
enum_declaration.id().ok()?.range(),
markup! {
"This "<Emphasis>"enum declaration"</Emphasis>" contains members that are implicitly initialized."
},
);
for enum_member in enum_declaration.members() {
let enum_member = enum_member.ok()?;
if enum_member.initializer().is_none() {
diagnostic = diagnostic.detail(enum_member.range(), markup! {
"This "<Emphasis>"enum member"</Emphasis>" should be explicitly initialized."
});
}
}
Some(diagnostic.note(
"Allowing implicit initializations for enum members can cause bugs if enum declarations are modified over time."
))
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let enum_declaration = ctx.query();
let mut mutation = ctx.root().begin();
let mut has_mutations = false;
let mut next_member_value = EnumInitializer::Integer(0);
for enum_member in enum_declaration.members() {
let enum_member = enum_member.ok()?;
if let Some(initializer) = enum_member.initializer() {
next_member_value = EnumInitializer::Other;
let expr = initializer.expression().ok()?.omit_parentheses();
if let Some(expr) = expr.as_any_js_literal_expression() {
match expr {
AnyJsLiteralExpression::JsNumberLiteralExpression(expr) => {
let n = expr.value_token().ok()?;
let n = n.text_trimmed();
if let Ok(n) = n.parse::<i64>() {
next_member_value = EnumInitializer::Integer(n + 1);
}
}
AnyJsLiteralExpression::JsStringLiteralExpression(expr) => {
if enum_member.name().ok()?.name() == expr.inner_string_text().ok() {
next_member_value = EnumInitializer::EnumName;
}
}
_ => {}
}
}
} else {
let x = match next_member_value {
EnumInitializer::Integer(n) => {
next_member_value = EnumInitializer::Integer(n + 1);
Some(AnyJsLiteralExpression::JsNumberLiteralExpression(
make::js_number_literal_expression(make::js_number_literal(n)),
))
}
EnumInitializer::EnumName => {
let enum_name = enum_member.name().ok()?.name()?;
let enum_name = enum_name.text();
Some(AnyJsLiteralExpression::JsStringLiteralExpression(
make::js_string_literal_expression(make::js_string_literal(enum_name)),
))
}
EnumInitializer::Other => None,
};
if let Some(x) = x {
has_mutations = true;
let new_enum_member =
enum_member
.clone()
.with_initializer(Some(make::js_initializer_clause(
make::token_decorated_with_space(JsSyntaxKind::EQ),
AnyJsExpression::AnyJsLiteralExpression(x),
)));
mutation.replace_node_discard_trivia(enum_member, new_enum_member);
}
}
}
if has_mutations {
return Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Initialize all enum members." }.to_owned(),
mutation,
});
}
None
}
}
enum EnumInitializer {
// The member is initialized with an integer
Integer(i64),
/// The member name is equal to the member value
EnumName,
Other,
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/style/use_while.rs | crates/rome_js_analyze/src/analyzers/style/use_while.rs | use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{AnyJsStatement, JsForStatement, JsForStatementFields, T};
use rome_rowan::BatchMutationExt;
use crate::JsRuleAction;
declare_rule! {
/// Enforce the use of `while` loops instead of `for` loops when the
/// initializer and update expressions are not needed
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// for (; x.running;) {
/// x.step();
/// }
/// ```
pub(crate) UseWhile {
version: "0.7.0",
name: "useWhile",
recommended: true,
}
}
impl Rule for UseWhile {
type Query = Ast<JsForStatement>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let n = ctx.query();
let JsForStatementFields {
for_token: _,
l_paren_token,
initializer,
first_semi_token: _,
test,
second_semi_token: _,
update,
r_paren_token,
body,
} = n.as_fields();
if l_paren_token.is_err()
|| initializer.is_some()
|| test.is_none()
|| update.is_some()
|| r_paren_token.is_err()
|| body.is_err()
{
None
} else {
Some(())
}
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
// SAFETY: These tokens have been checked for errors in `run` already
let for_range = node.for_token().unwrap().text_trimmed_range();
let r_paren_range = node.r_paren_token().unwrap().text_trimmed_range();
Some(RuleDiagnostic::new(
rule_category!(),
for_range.cover(r_paren_range),
markup! {
"Use "<Emphasis>"while"</Emphasis>" loops instead of "<Emphasis>"for"</Emphasis>" loops."
},
))
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
let JsForStatementFields {
for_token: _,
l_paren_token,
initializer: _,
first_semi_token: _,
test,
second_semi_token: _,
update: _,
r_paren_token,
body,
} = node.as_fields();
mutation.replace_node(
AnyJsStatement::from(node.clone()),
AnyJsStatement::from(make::js_while_statement(
make::token_decorated_with_space(T![while]),
l_paren_token.ok()?,
test?,
r_paren_token.ok()?,
body.ok()?,
)),
);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Use a while loop" }.to_owned(),
mutation,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/style/use_self_closing_elements.rs | crates/rome_js_analyze/src/analyzers/style/use_self_closing_elements.rs | use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{AnyJsxTag, JsSyntaxToken, JsxElement, JsxOpeningElementFields, T};
use rome_rowan::{AstNode, AstNodeList, BatchMutationExt, TriviaPiece};
use crate::JsRuleAction;
declare_rule! {
/// Prevent extra closing tags for components without children
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// <div></div>
/// ```
///
/// ```js,expect_diagnostic
/// <Component></Component>
/// ```
///
/// ```js,expect_diagnostic
/// <Foo.bar></Foo.bar>
/// ```
///
/// ### Valid
///
/// ```js
/// <div />
///```
///
/// ```js
/// <div>child</div>
///```
///
/// ```js
/// <Component />
///```
///
/// ```js
/// <Component>child</Component>
///```
///
/// ```js
/// <Foo.bar />
///```
///
/// ```js
/// <Foo.bar>child</Foo.bar>
///```
pub(crate) UseSelfClosingElements {
version: "0.7.0",
name: "useSelfClosingElements",
recommended: true,
}
}
impl Rule for UseSelfClosingElements {
type Query = Ast<JsxElement>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
if ctx.query().children().is_empty() {
Some(())
} else {
None
}
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
ctx.query().range(),
markup! {
"JSX elements without children should be marked as self-closing. In JSX, it is valid for any element to be self-closing."
},
))
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let mut mutation = ctx.root().begin();
let open_element = ctx.query().opening_element().ok()?;
let JsxOpeningElementFields {
l_angle_token,
name,
type_arguments,
attributes,
r_angle_token,
} = open_element.as_fields();
let mut r_angle_token = r_angle_token.ok()?;
let mut leading_trivia = vec![];
let mut slash_token = String::new();
for trivia in r_angle_token.leading_trivia().pieces() {
leading_trivia.push(TriviaPiece::new(trivia.kind(), trivia.text_len()));
slash_token.push_str(trivia.text());
}
// check if previous `open_element` have a whitespace before `>`
// this step make sure we could convert <div></div> -> <div />
// <div test="some""></div> -> <div test="some" />
let prev_token = r_angle_token.prev_token();
let need_extra_whitespace = prev_token
.as_ref()
.map_or(true, |token| !token.trailing_trivia().text().ends_with(' '));
// drop the leading trivia of `r_angle_token`
r_angle_token = r_angle_token.with_leading_trivia([]);
if leading_trivia.is_empty() && need_extra_whitespace {
slash_token.push(' ');
leading_trivia.push(TriviaPiece::whitespace(1));
}
slash_token += "/";
let mut self_closing_element_builder = make::jsx_self_closing_element(
l_angle_token.ok()?,
name.ok()?,
attributes,
JsSyntaxToken::new_detached(T![/], &slash_token, leading_trivia, []),
r_angle_token,
);
if let Some(type_arguments) = type_arguments {
self_closing_element_builder =
self_closing_element_builder.with_type_arguments(type_arguments);
}
let self_closing_element = self_closing_element_builder.build();
mutation.replace_node(
AnyJsxTag::JsxElement(ctx.query().clone()),
AnyJsxTag::JsxSelfClosingElement(self_closing_element),
);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Use a SelfClosingElement instead" }.to_owned(),
mutation,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/style/no_inferrable_types.rs | crates/rome_js_analyze/src/analyzers/style/no_inferrable_types.rs | use crate::JsRuleAction;
use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_syntax::{
AnyJsExpression, AnyTsPropertyAnnotation, AnyTsVariableAnnotation, JsFormalParameter,
JsInitializerClause, JsPropertyClassMember, JsSyntaxKind, JsVariableDeclaration,
JsVariableDeclarator, JsVariableDeclaratorList, TsPropertyParameter, TsReadonlyModifier,
TsTypeAnnotation,
};
use rome_rowan::AstNode;
use rome_rowan::BatchMutationExt;
declare_rule! {
/// Disallow type annotations for variables, parameters, and class properties initialized with a literal expression.
///
/// TypeScript is able to infer the types of parameters, properties, and variables from their default or initial values.
/// There is no need to use an explicit `:` type annotation for trivially inferred types (boolean, bigint, number, regex, string).
/// Doing so adds unnecessary verbosity to code making it harder to read.
///
/// In contrast to ESLint's rule, this rule allows to use a wide type for `const` declarations.
/// Moreover, the rule does not recognize `undefined` values, primitive type constructors (String, Number, ...), and `RegExp` type.
/// These global variables could be shadowed by local ones.
///
/// Source: https://typescript-eslint.io/rules/no-inferrable-types
///
/// ## Examples
///
/// ### Invalid
///
/// ```ts,expect_diagnostic
/// const variable: 1 = 1;
/// ```
///
/// ```ts,expect_diagnostic
/// let variable: number = 1;
/// ```
///
/// ```ts,expect_diagnostic
/// class SomeClass {
/// readonly field: 1 = 1;
/// }
/// ```
///
/// ```ts,expect_diagnostic
/// class SomeClass {
/// field: number = 1;
/// }
/// ```
///
/// ```ts,expect_diagnostic
/// function f(param: number = 1): void {}
/// ```
///
/// ### Valid
///
/// ```ts
/// const variable: number = 1;
/// ```
///
/// ```ts
/// let variable: 1 | 2 = 1;
/// ```
///
/// ```ts
/// class SomeClass {
/// readonly field: number = 1;
/// }
/// ```
///
/// ```ts
/// // `undefined` could be shadowed
/// const variable: undefined = undefined;
/// ```
///
/// ```ts
/// // `RegExp` could be shadowed
/// const variable: RegExp = /a/;
/// ```
///
/// ```ts
/// // `String` could be shadowed
/// let variable: string = String(5);
/// ```
///
/// ```ts
/// class SomeClass {
/// field: 1 | 2 = 1;
/// }
/// ```
///
/// ```ts
/// function f(param: 1 | 2 = 1): void {}
/// ```
///
pub(crate) NoInferrableTypes {
version: "12.0.0",
name: "noInferrableTypes",
recommended: true,
}
}
impl Rule for NoInferrableTypes {
type Query = Ast<JsInitializerClause>;
type State = TsTypeAnnotation;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let init = ctx.query();
let init_expr = init.expression().ok()?.omit_parentheses();
if has_trivially_inferrable_type(&init_expr).is_some() {
// `is_const` signals a const context (const declarations, readonly properties)
// non const contexts are other situations (let/var declarations, mutable properties, formal parameters)
let mut is_const = false;
let mut type_annotation = None;
if let Some(param) = init.parent::<JsFormalParameter>() {
if let Some(prop_param) = param.parent::<TsPropertyParameter>() {
is_const = prop_param
.modifiers()
.into_iter()
.any(|x| TsReadonlyModifier::can_cast(x.syntax().kind()));
}
type_annotation = param.type_annotation();
} else if let Some(prop) = init.parent::<JsPropertyClassMember>() {
is_const = prop
.modifiers()
.into_iter()
.any(|x| TsReadonlyModifier::can_cast(x.syntax().kind()));
type_annotation = match prop.property_annotation()? {
AnyTsPropertyAnnotation::TsTypeAnnotation(annotation) => Some(annotation),
_ => None,
};
} else if let Some(declarator) = init.parent::<JsVariableDeclarator>() {
is_const = declarator
.parent::<JsVariableDeclaratorList>()?
.parent::<JsVariableDeclaration>()?
.is_const();
type_annotation = match declarator.variable_annotation()? {
AnyTsVariableAnnotation::TsTypeAnnotation(annotation) => Some(annotation),
_ => None,
};
}
if let Some(type_annotation) = type_annotation {
let ty = type_annotation.ty().ok()?.omit_parentheses();
// In const contexts, literal type annotations are rejected.
// e.g. `const x: 1 = <literal>`
//
// In non-const contexts, wide type annotation are rejected.
// e.g. `let x: number = <literal>`
if (is_const && ty.is_literal_type()) || (!is_const && ty.is_primitive_type()) {
return Some(type_annotation);
}
}
}
None
}
fn diagnostic(_: &RuleContext<Self>, annotation: &Self::State) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
annotation.range(),
markup! {
"This type annotation is trivially inferred from its initialization."
},
))
}
fn action(ctx: &RuleContext<Self>, annotation: &Self::State) -> Option<JsRuleAction> {
let mut mutation = ctx.root().begin();
let first_token = annotation.syntax().first_token()?;
let prev_token = first_token.prev_token()?;
let new_prev_token = prev_token.append_trivia_pieces(first_token.leading_trivia().pieces());
let last_token = annotation.syntax().last_token()?;
let next_token = last_token.next_token()?;
let new_next_token =
next_token.prepend_trivia_pieces(last_token.trailing_trivia().pieces());
mutation.replace_token_discard_trivia(prev_token, new_prev_token);
mutation.replace_token_discard_trivia(next_token, new_next_token);
mutation.remove_node(annotation.clone());
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::Always,
message: markup! { "Remove the type annotation." }.to_owned(),
mutation,
})
}
}
fn has_trivially_inferrable_type(expr: &AnyJsExpression) -> Option<()> {
match expr {
AnyJsExpression::AnyJsLiteralExpression(_) => Some(()),
AnyJsExpression::JsTemplateExpression(tpl_expr) => tpl_expr.tag().is_none().then_some(()),
AnyJsExpression::JsUnaryExpression(unary_exp) => {
match unary_exp.operator_token().ok()?.kind() {
JsSyntaxKind::BANG
| JsSyntaxKind::MINUS
| JsSyntaxKind::PLUS
| JsSyntaxKind::VOID_KW => Some(()),
_ => None,
}
}
_ => None,
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/style/use_single_var_declarator.rs | crates/rome_js_analyze/src/analyzers/style/use_single_var_declarator.rs | use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{
JsModuleItemList, JsStatementList, JsSyntaxToken, JsVariableDeclarationFields,
JsVariableDeclaratorList, JsVariableStatement, JsVariableStatementFields, TextSize,
TriviaPieceKind, T,
};
use rome_rowan::{AstNode, AstNodeExt, AstSeparatedList, BatchMutationExt, TriviaPiece};
use crate::JsRuleAction;
declare_rule! {
/// Disallow multiple variable declarations in the same variable statement
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// let foo, bar;
/// ```
///
/// ### Valid
///
/// ```js
/// for (let i = 0, x = 1; i < arr.length; i++) {}
/// ```
pub(crate) UseSingleVarDeclarator {
version: "0.7.0",
name: "useSingleVarDeclarator",
recommended: true,
}
}
impl Rule for UseSingleVarDeclarator {
type Query = Ast<JsVariableStatement>;
type State = (
Option<JsSyntaxToken>,
JsSyntaxToken,
JsVariableDeclaratorList,
Option<JsSyntaxToken>,
);
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let node = ctx.query();
let JsVariableStatementFields {
declaration,
semicolon_token,
} = node.as_fields();
let JsVariableDeclarationFields {
await_token,
kind,
declarators,
} = declaration.ok()?.as_fields();
let kind = kind.ok()?;
if declarators.len() < 2 {
return None;
}
Some((await_token, kind, declarators, semicolon_token))
}
fn diagnostic(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
node.range(),
"Declare variables separately",
))
}
fn action(ctx: &RuleContext<Self>, state: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let prev_parent = node.syntax().parent()?;
if !JsStatementList::can_cast(prev_parent.kind())
&& !JsModuleItemList::can_cast(prev_parent.kind())
{
return None;
}
let (await_token, kind, declarators, semicolon_token) = state;
let index = prev_parent
.children()
.position(|slot| &slot == node.syntax())?;
// Extract the indentation part from the leading trivia of the kind
// token, defined as all whitespace and newline trivia pieces starting
// from the token going backwards up to the first newline (included).
// If the leading trivia for the token is empty, a single newline trivia
// piece is created. For efficiency, the trivia pieces are stored in
// reverse order (the vector is then reversed again on iteration)
let mut has_newline = false;
let leading_trivia: Vec<_> = kind
.leading_trivia()
.pieces()
.rev()
.take_while(|piece| {
let has_previous_newline = has_newline;
has_newline |= piece.is_newline();
!has_previous_newline
})
.filter_map(|piece| {
if piece.is_whitespace() || piece.is_newline() {
Some((piece.kind(), piece.text().to_string()))
} else {
None
}
})
.collect();
let kind_indent = if !leading_trivia.is_empty() {
leading_trivia
} else {
vec![(TriviaPieceKind::Newline, String::from("\n"))]
};
let last_semicolon_token = semicolon_token.as_ref();
let remaining_semicolon_token = semicolon_token.clone().map(|_| make::token(T![;]));
let declarators_len = declarators.len();
let next_parent = prev_parent.clone().splice_slots(
index..=index,
declarators
.iter()
.enumerate()
.filter_map(|(index, declarator)| {
let mut declarator = declarator.ok()?;
// Remove the leading trivia for the declarators
let first_token = declarator.syntax().first_token()?;
let first_token_leading_trivia = first_token.leading_trivia();
declarator = declarator
.replace_token_discard_trivia(
first_token.clone(),
first_token.with_leading_trivia([]),
)
// SAFETY: first_token is a known child of declarator
.unwrap();
let kind = if index == 0 {
// Clone the kind token with its entire leading trivia
// for the first statement
kind.clone()
} else {
// For the remaining statements, clone the kind token
// with the leading trivia pieces previously removed
// from the first token of the declarator node, with
// the indentation fixed up to match the original kind
// token
let indent: &[(TriviaPieceKind, String)] = &kind_indent;
let mut trivia_pieces = Vec::new();
let mut token_text = String::new();
for piece in first_token_leading_trivia.pieces() {
if !piece.is_comments() {
continue;
}
for (kind, text) in indent.iter().rev() {
trivia_pieces.push(TriviaPiece::new(*kind, TextSize::of(text)));
token_text.push_str(text);
}
trivia_pieces.push(TriviaPiece::new(piece.kind(), piece.text_len()));
token_text.push_str(piece.text());
}
for (kind, text) in indent.iter().rev() {
trivia_pieces.push(TriviaPiece::new(*kind, TextSize::of(text)));
token_text.push_str(text);
}
token_text.push_str(kind.text_trimmed());
for piece in kind.trailing_trivia().pieces() {
token_text.push_str(piece.text());
}
JsSyntaxToken::new_detached(
kind.kind(),
&token_text,
trivia_pieces,
kind.trailing_trivia().pieces().map(|piece| {
TriviaPiece::new(piece.kind(), TextSize::of(piece.text()))
}),
)
};
let mut variable_declaration = make::js_variable_declaration(
kind,
make::js_variable_declarator_list([declarator], []),
);
if let Some(await_token) = await_token {
variable_declaration =
variable_declaration.with_await_token(await_token.clone());
}
let mut builder = make::js_variable_statement(variable_declaration.build());
let semicolon_token = if index + 1 == declarators_len {
last_semicolon_token
} else {
remaining_semicolon_token.as_ref()
};
if let Some(semicolon_token) = semicolon_token {
builder = builder.with_semicolon_token(semicolon_token.clone());
}
Some(Some(builder.build().into_syntax().into()))
}),
);
let mut mutation = ctx.root().begin();
mutation.replace_element(prev_parent.into(), next_parent.into());
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Break out into multiple declarations" }.to_owned(),
mutation,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/style/use_single_case_statement.rs | crates/rome_js_analyze/src/analyzers/style/use_single_case_statement.rs | use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{AnyJsStatement, AnyJsSwitchClause, TriviaPieceKind, T};
use rome_rowan::{AstNode, AstNodeList, BatchMutationExt};
use crate::JsRuleAction;
declare_rule! {
/// Enforces switch clauses have a single statement, emits a quick fix wrapping
/// the statements in a block.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// switch (foo) {
/// case true:
/// case false:
/// let foo = '';
/// foo;
/// }
/// ```
///
/// ### Valid
///
/// ```js
/// switch (foo) {
/// case true:
/// case false: {
/// let foo = '';
/// foo;
/// }
/// }
/// ```
pub(crate) UseSingleCaseStatement {
version: "0.7.0",
name: "useSingleCaseStatement",
recommended: false,
}
}
impl Rule for UseSingleCaseStatement {
type Query = Ast<AnyJsSwitchClause>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let switch_clause = ctx.query();
if switch_clause.consequent().len() > 1 {
Some(())
} else {
None
}
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let switch_clause = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
switch_clause.consequent().range(),
markup! {
"A "<Emphasis>"switch clause"</Emphasis>" should only have a single statement."
},
))
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let switch_clause = ctx.query();
let clause_token = switch_clause.clause_token().ok()?;
let colon_token = switch_clause.colon_token().ok()?;
let consequent = switch_clause.consequent();
let new_colon_token = colon_token.with_trailing_trivia([]);
let new_consequent = make::js_statement_list(Some(AnyJsStatement::JsBlockStatement(
make::js_block_statement(
make::token(T!['{'])
.with_leading_trivia([(TriviaPieceKind::Whitespace, " ")])
.with_trailing_trivia_pieces(colon_token.trailing_trivia().pieces()),
consequent.clone(),
make::token(T!['}'])
.with_leading_trivia_pieces(clause_token.indentation_trivia_pieces()),
),
)));
let mut mutation = ctx.root().begin();
mutation.replace_token_discard_trivia(colon_token, new_colon_token);
mutation.replace_node_discard_trivia(consequent, new_consequent);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Wrap the statements in a block." }.to_owned(),
mutation,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/style/use_template.rs | crates/rome_js_analyze/src/analyzers/style/use_template.rs | use rome_analyze::RuleSuppressions;
use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::AnyJsTemplateElement::{self, JsTemplateElement};
use rome_js_syntax::{
AnyJsExpression, AnyJsLiteralExpression, JsBinaryExpression, JsBinaryOperator, JsLanguage,
JsSyntaxKind, JsSyntaxToken, JsTemplateElementList, JsTemplateExpression, WalkEvent, T,
};
use rome_rowan::{AstNode, AstNodeList, BatchMutationExt, SyntaxToken};
use crate::{utils::escape::escape, utils::escape_string, JsRuleAction};
declare_rule! {
/// Template literals are preferred over string concatenation.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// console.log(foo + "baz");
/// ```
///
/// ```js,expect_diagnostic
/// console.log(1 * 2 + "foo");
/// ```
///
/// ```js,expect_diagnostic
/// console.log(1 + "foo" + 2 + "bar" + "baz" + 3);
/// ```
///
/// ```js,expect_diagnostic
/// console.log((1 + "foo") * 2);
/// ```
///
/// ```js,expect_diagnostic
/// console.log("foo" + 1);
/// ```
///
/// ### Valid
///
/// ```js
/// console.log("foo" + "bar");
/// console.log(foo() + "\n");
/// ```
pub(crate) UseTemplate {
version: "0.7.0",
name: "useTemplate",
recommended: true,
}
}
impl Rule for UseTemplate {
type Query = Ast<JsBinaryExpression>;
type State = Vec<AnyJsExpression>;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let binary_expr = ctx.query();
let need_process = is_unnecessary_string_concat_expression(binary_expr)?;
if !need_process {
return None;
}
let collections = collect_binary_add_expression(binary_expr)?;
collections
.iter()
.any(|expr| {
!matches!(
expr,
AnyJsExpression::AnyJsLiteralExpression(
rome_js_syntax::AnyJsLiteralExpression::JsStringLiteralExpression(_)
)
)
})
.then_some(collections)
}
fn suppressed_nodes(
ctx: &RuleContext<Self>,
_state: &Self::State,
suppressions: &mut RuleSuppressions<JsLanguage>,
) {
let mut iter = ctx.query().syntax().preorder();
while let Some(node) = iter.next() {
if let WalkEvent::Enter(node) = node {
if node.kind() == JsSyntaxKind::JS_BINARY_EXPRESSION {
suppressions.suppress_node(node);
} else {
iter.skip_subtree();
}
}
}
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
node.range(),
markup! {
""<Emphasis>"Template"</Emphasis>" literals are preferred over "<Emphasis>"string concatenation."</Emphasis>""
},
))
}
fn action(ctx: &RuleContext<Self>, state: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
let template = convert_expressions_to_js_template(state)?;
mutation.replace_node(
AnyJsExpression::JsBinaryExpression(node.clone()),
AnyJsExpression::JsTemplateExpression(template),
);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Use a "<Emphasis>"TemplateLiteral"</Emphasis>"." }.to_owned(),
mutation,
})
}
}
/// Merge `Vec<JsAnyExpression>` into a `JsTemplate`
fn convert_expressions_to_js_template(
exprs: &Vec<AnyJsExpression>,
) -> Option<JsTemplateExpression> {
let mut reduced_exprs = Vec::with_capacity(exprs.len());
for expr in exprs.iter() {
match expr {
AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsStringLiteralExpression(string),
) => {
let trimmed_string = string.syntax().text_trimmed().to_string();
let string_without_quotes = &trimmed_string[1..trimmed_string.len() - 1];
let chunk_element = AnyJsTemplateElement::JsTemplateChunkElement(
make::js_template_chunk_element(JsSyntaxToken::new_detached(
JsSyntaxKind::TEMPLATE_CHUNK,
&escape(string_without_quotes, &["${", "`"], '\\'),
[],
[],
)),
);
reduced_exprs.push(chunk_element);
}
AnyJsExpression::JsTemplateExpression(template) => {
reduced_exprs.extend(flatten_template_element_list(template.elements())?);
}
_ => {
let template_element =
AnyJsTemplateElement::JsTemplateElement(make::js_template_element(
SyntaxToken::new_detached(JsSyntaxKind::DOLLAR_CURLY, "${", [], []),
// Trim spaces to make the generated `JsTemplate` a little nicer,
// if we don't do this the `1 * (2 + "foo") + "bar"` will become:
// ```js
// `${1 * (2 + "foo") }bar`
// ```
expr.clone().trim()?,
SyntaxToken::new_detached(JsSyntaxKind::DOLLAR_CURLY, "}", [], []),
));
reduced_exprs.push(template_element);
}
}
}
Some(
make::js_template_expression(
make::token(T!['`']),
make::js_template_element_list(reduced_exprs),
make::token(T!['`']),
)
.build(),
)
}
/// Flatten a [JsTemplateElementList] of [JsTemplate] which could possibly be recursive, into a `Vec<JsAnyTemplateElement>`
/// ## Example
/// flatten
/// ```js
/// `${1 + 2 + `${a}test` }bar`
/// ```
/// into
/// `[1, 2, a, "test", "bar"]`
fn flatten_template_element_list(list: JsTemplateElementList) -> Option<Vec<AnyJsTemplateElement>> {
let mut ret = Vec::with_capacity(list.len());
for element in list {
match element {
AnyJsTemplateElement::JsTemplateChunkElement(_) => ret.push(element),
JsTemplateElement(ref ele) => {
let expr = ele.expression().ok()?;
match expr {
AnyJsExpression::JsTemplateExpression(template) => {
ret.extend(flatten_template_element_list(template.elements())?);
}
_ => {
ret.push(element);
}
}
}
}
}
Some(ret)
}
fn is_unnecessary_string_concat_expression(node: &JsBinaryExpression) -> Option<bool> {
if node.operator().ok()? != JsBinaryOperator::Plus {
return None;
}
match node.left().ok()? {
rome_js_syntax::AnyJsExpression::JsBinaryExpression(binary) => {
if is_unnecessary_string_concat_expression(&binary) == Some(true) {
return Some(true);
}
}
rome_js_syntax::AnyJsExpression::JsTemplateExpression(_) => return Some(true),
rome_js_syntax::AnyJsExpression::AnyJsLiteralExpression(
rome_js_syntax::AnyJsLiteralExpression::JsStringLiteralExpression(string_literal),
) => {
if has_new_line_or_tick(string_literal).is_none() {
return Some(true);
}
}
_ => (),
}
match node.right().ok()? {
rome_js_syntax::AnyJsExpression::JsBinaryExpression(binary) => {
if is_unnecessary_string_concat_expression(&binary) == Some(true) {
return Some(true);
}
}
rome_js_syntax::AnyJsExpression::JsTemplateExpression(_) => return Some(true),
rome_js_syntax::AnyJsExpression::AnyJsLiteralExpression(
rome_js_syntax::AnyJsLiteralExpression::JsStringLiteralExpression(string_literal),
) => {
if has_new_line_or_tick(string_literal).is_none() {
return Some(true);
}
}
_ => (),
}
None
}
/// Check if the string literal has new line or tick
fn has_new_line_or_tick(
string_literal: rome_js_syntax::JsStringLiteralExpression,
) -> Option<usize> {
escape_string(string_literal.value_token().ok()?.text_trimmed())
.ok()?
.find(|ch| matches!(ch, '\n' | '`'))
}
/// Convert [JsBinaryExpression] recursively only if the `operator` is `+` into Vec<[JsAnyExpression]>
/// ## Example
/// - from: `1 + 2 + 3 + (1 * 2)`
/// - to: `[1, 2, 3, (1 * 2)]`
fn collect_binary_add_expression(node: &JsBinaryExpression) -> Option<Vec<AnyJsExpression>> {
let mut result = vec![];
match node.left().ok()? {
AnyJsExpression::JsBinaryExpression(left)
if matches!(left.operator().ok()?, JsBinaryOperator::Plus) =>
{
result.append(&mut collect_binary_add_expression(&left)?);
}
left => {
result.push(left);
}
};
match node.right().ok()? {
AnyJsExpression::JsBinaryExpression(right)
if matches!(right.operator().ok()?, JsBinaryOperator::Plus) =>
{
result.append(&mut collect_binary_add_expression(&right)?);
}
right => {
result.push(right);
}
};
Some(result)
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/style/no_comma_operator.rs | crates/rome_js_analyze/src/analyzers/style/no_comma_operator.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Ast, Rule, RuleDiagnostic};
use rome_js_syntax::{JsForStatement, JsSequenceExpression};
use rome_rowan::AstNode;
declare_rule! {
/// Disallow comma operator.
///
/// The comma operator includes multiple expressions where only one is expected.
/// It evaluates every operand from left to right and returns the value of the last operand.
/// It frequently obscures side effects, and its use is often an accident.
///
/// The use of the comma operator in the initialization and update parts of a `for` is still allowed.
///
/// Source: https://eslint.org/docs/latest/rules/no-sequences
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// const foo = (doSomething(), 0);
/// ```
///
/// ```js,expect_diagnostic
/// for (; doSomething(), !!test; ) {}
/// ```
///
/// ```js,expect_diagnostic
/// // Use a semicolon instead.
/// let a, b;
/// a = 1, b = 2;
/// ```
///
/// ### Valid
///
/// ```js
/// for(a = 0, b = 0; (a + b) < 10; a++, b += 2) {}
/// ```
///
pub(crate) NoCommaOperator {
version: "12.0.0",
name: "noCommaOperator",
recommended: true,
}
}
impl Rule for NoCommaOperator {
type Query = Ast<JsSequenceExpression>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let seq = ctx.query();
if let Some(for_stmt) = seq.parent::<JsForStatement>() {
// Allow comma operator in initializer and update parts of a `for`
if for_stmt.test().map(AstNode::into_syntax).as_ref() != Some(seq.syntax()) {
return None;
}
}
Some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let seq = ctx.query();
Some(
RuleDiagnostic::new(
rule_category!(),
seq.comma_token().ok()?.text_trimmed_range(),
"The comma operator is disallowed.",
)
.note("Its use is often confusing and obscures side effects."),
)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/style/no_unused_template_literal.rs | crates/rome_js_analyze/src/analyzers/style/no_unused_template_literal.rs | use crate::JsRuleAction;
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{
AnyJsExpression, AnyJsLiteralExpression, AnyJsTemplateElement, JsTemplateExpression,
};
use rome_rowan::{AstNode, AstNodeList, BatchMutationExt};
declare_rule! {
/// Disallow template literals if interpolation and special-character handling are not needed
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// const foo = `bar`
/// ```
///
/// ```js,expect_diagnostic
/// const foo = `bar `
/// ```
///
/// ### Valid
///
/// ```js
/// const foo = `bar
/// has newline`;
/// ```
///
/// ```js
/// const foo = `"bar"`
/// ```
///
/// ```js
/// const foo = `'bar'`
/// ```
pub(crate) NoUnusedTemplateLiteral {
version: "0.7.0",
name: "noUnusedTemplateLiteral",
recommended: true,
}
}
impl Rule for NoUnusedTemplateLiteral {
type Query = Ast<JsTemplateExpression>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let node = ctx.query();
if node.tag().is_none() && can_convert_to_string_literal(node) {
Some(())
} else {
None
}
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(RuleDiagnostic::new(rule_category!(),node.range(), markup! {
"Do not use template literals if interpolation and special-character handling are not needed."
}
.to_owned() ) )
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
// join all template content
let inner_content = node
.elements()
.iter()
.fold(String::from(""), |mut acc, cur| {
match cur {
AnyJsTemplateElement::JsTemplateChunkElement(ele) => {
// Safety: if `ele.template_chunk_token()` is `Err` variant, [can_convert_to_string_lit] should return false,
// thus `run` will return None
acc += ele.template_chunk_token().unwrap().text();
acc
}
AnyJsTemplateElement::JsTemplateElement(_) => {
// Because we know if TemplateLit has any `JsTemplateElement` will return `None` in `run` function
unreachable!()
}
}
});
mutation.replace_node(
AnyJsExpression::JsTemplateExpression(node.clone()),
AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsStringLiteralExpression(
make::js_string_literal_expression(make::js_string_literal(&inner_content)),
),
),
);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Replace with string literal" }.to_owned(),
mutation,
})
}
}
fn can_convert_to_string_literal(node: &JsTemplateExpression) -> bool {
!node.elements().iter().any(|element| {
// We want to test if any templateElement has violated rule that can convert to string literal, rules are listed below
// 1. Variant of element is `JsTemplateElement`
// 2. Content of `ChunkElement` has any special characters, any of `\n`, `'`, `"`
match element {
AnyJsTemplateElement::JsTemplateElement(_) => true,
AnyJsTemplateElement::JsTemplateChunkElement(chunk) => {
match chunk.template_chunk_token() {
Ok(token) => {
// if token text has any special character
token
.text()
.chars()
.any(|ch| matches!(ch, '\n' | '\'' | '"'))
}
Err(_) => {
// if we found an error, then just return `true`, which means that this template literal can't be converted to
// a string literal
true
}
}
}
}
})
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/style/use_exponentiation_operator.rs | crates/rome_js_analyze/src/analyzers/style/use_exponentiation_operator.rs | use crate::semantic_services::Semantic;
use crate::JsRuleAction;
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, ActionCategory, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::{make, syntax::T};
use rome_js_syntax::{
global_identifier, AnyJsExpression, AnyJsMemberExpression, JsBinaryOperator, JsCallExpression,
JsClassDeclaration, JsClassExpression, JsExtendsClause, JsInExpression, OperatorPrecedence,
};
use rome_rowan::{AstNode, AstSeparatedList, BatchMutationExt};
declare_rule! {
/// Disallow the use of `Math.pow` in favor of the `**` operator.
///
/// > Introduced in ES2016, the infix exponentiation operator ** is an alternative for the standard Math.pow function.
/// > Infix notation is considered to be more readable and thus more preferable than the function notation.
///
/// Source: https://eslint.org/docs/latest/rules/prefer-exponentiation-operator
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// const foo = Math.pow(2, 8);
/// ```
///
/// ```js,expect_diagnostic
/// const bar = Math.pow(a, b);
/// ```
///
/// ```js,expect_diagnostic
/// let baz = Math.pow(a + b, c + d);
/// ```
///
/// ```js,expect_diagnostic
/// let quux = Math.pow(-1, n);
/// ```
///
/// ### Valid
///
/// ```js
/// const foo = 2 ** 8;
///
/// const bar = a ** b;
///
/// let baz = (a + b) ** (c + d);
///
/// let quux = (-1) ** n;
/// ```
///
pub(crate) UseExponentiationOperator {
version: "11.0.0",
name: "useExponentiationOperator",
recommended: true,
}
}
pub struct MathPowCall {
base: AnyJsExpression,
exponent: AnyJsExpression,
}
impl MathPowCall {
fn make_base(&self) -> Option<AnyJsExpression> {
Some(if self.does_base_need_parens()? {
parenthesize_any_js_expression(&self.base)
} else {
self.base.clone()
})
}
fn make_exponent(&self) -> Option<AnyJsExpression> {
Some(if self.does_exponent_need_parens()? {
parenthesize_any_js_expression(&self.exponent)
} else {
self.exponent.clone()
})
}
/// Determines whether the base expression needs parens in an exponentiation binary expression.
fn does_base_need_parens(&self) -> Option<bool> {
Some(
// '**' is right-associative, parens are needed when Math.pow(a ** b, c) is converted to (a ** b) ** c
self.base.precedence().ok()? <= OperatorPrecedence::Exponential
// An unary operator cannot be used immediately before an exponentiation expression
|| self.base.as_js_unary_expression().is_some()
|| self.base.as_js_await_expression().is_some(),
)
}
/// Determines whether the exponent expression needs parens in an exponentiation binary expression.
fn does_exponent_need_parens(&self) -> Option<bool> {
Some(self.exponent.precedence().ok()? < OperatorPrecedence::Exponential)
}
}
impl Rule for UseExponentiationOperator {
type Query = Semantic<JsCallExpression>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let model = ctx.model();
let callee = node.callee().ok()?.omit_parentheses();
let member_expr = AnyJsMemberExpression::cast_ref(callee.syntax())?;
if member_expr.member_name()?.text() != "pow" {
return None;
}
let object = member_expr.object().ok()?.omit_parentheses();
let (reference, name) = global_identifier(&object)?;
if name.text() != "Math" {
return None;
}
model.binding(&reference).is_none().then_some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let diagnostic = RuleDiagnostic::new(
rule_category!(),
ctx.query().range(),
"Use the '**' operator instead of 'Math.pow'.",
);
Some(diagnostic)
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
if !should_suggest_fix(node)? {
return None;
}
let mut mutation = ctx.root().begin();
let [base, exponent] = node.get_arguments_by_index([0, 1]);
let math_pow_call = MathPowCall {
base: base?.as_any_js_expression()?.clone().omit_parentheses(),
exponent: exponent?.as_any_js_expression()?.clone().omit_parentheses(),
};
let new_node = make::js_binary_expression(
math_pow_call.make_base()?,
make::token(T![**]),
math_pow_call.make_exponent()?,
);
if let Some((needs_parens, parent)) = does_exponentiation_expression_need_parens(node) {
if needs_parens && parent.is_some() {
mutation.replace_node(parent.clone()?, parenthesize_any_js_expression(&parent?));
}
mutation.replace_node(
AnyJsExpression::from(node.clone()),
parenthesize_any_js_expression(&AnyJsExpression::from(new_node)),
);
} else {
mutation.replace_node(
AnyJsExpression::from(node.clone()),
AnyJsExpression::from(new_node),
);
}
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Use the '**' operator instead of 'Math.pow'." }.to_owned(),
mutation,
})
}
}
/// Verify if the autofix is safe to be applied and won't remove comments.
/// Argument list is considered valid if there's no spread arg and leading/trailing comments.
fn should_suggest_fix(node: &JsCallExpression) -> Option<bool> {
let arguments = node.arguments().ok()?;
let args_count = arguments.args().len();
Some(
args_count == 2
&& !arguments.l_paren_token().ok()?.has_leading_comments()
&& !arguments.l_paren_token().ok()?.has_trailing_comments()
&& !arguments.r_paren_token().ok()?.has_leading_comments()
&& !arguments.r_paren_token().ok()?.has_trailing_comments()
&& arguments.args().into_iter().flatten().all(|arg| {
!arg.syntax().has_leading_comments()
&& !arg.syntax().has_trailing_comments()
&& arg.as_js_spread().is_none()
}),
)
}
/// Wraps a [AnyJsExpression] in paretheses
fn parenthesize_any_js_expression(expr: &AnyJsExpression) -> AnyJsExpression {
AnyJsExpression::from(make::js_parenthesized_expression(
make::token(T!['(']),
expr.clone(),
make::token(T![')']),
))
}
/// Determines whether the given parent node needs parens if used as the exponent in an exponentiation binary expression.
fn does_exponentiation_expression_need_parens(
node: &JsCallExpression,
) -> Option<(bool, Option<AnyJsExpression>)> {
if let Some(parent) = node.parent::<AnyJsExpression>() {
if does_expression_need_parens(node, &parent)? {
return Some((true, Some(parent)));
}
} else if let Some(extends_clause) = node.parent::<JsExtendsClause>() {
if extends_clause.parent::<JsClassDeclaration>().is_some() {
return Some((true, None));
}
if let Some(class_expr) = extends_clause.parent::<JsClassExpression>() {
let class_expr = AnyJsExpression::from(class_expr);
if does_expression_need_parens(node, &class_expr)? {
return Some((true, Some(class_expr)));
}
}
}
None
}
/// Determines whether the given expression needs parens when used in an exponentiation binary expression.
fn does_expression_need_parens(
node: &JsCallExpression,
expression: &AnyJsExpression,
) -> Option<bool> {
let needs_parentheses = match &expression {
// Skips already parenthesized expressions
AnyJsExpression::JsParenthesizedExpression(_) => return None,
AnyJsExpression::JsBinaryExpression(bin_expr) => {
if bin_expr.parent::<JsInExpression>().is_some() {
return Some(true);
}
let binding = bin_expr.right().ok()?;
let call_expr = binding.as_js_call_expression();
bin_expr.operator().ok()? != JsBinaryOperator::Exponent
|| call_expr.is_none()
|| call_expr? != node
}
AnyJsExpression::JsCallExpression(call_expr) => !call_expr
.arguments()
.ok()?
.args()
.iter()
.filter_map(|arg| {
let binding = arg.ok()?;
return binding
.as_any_js_expression()?
.as_js_call_expression()
.cloned();
})
.any(|arg| &arg == node),
AnyJsExpression::JsNewExpression(new_expr) => !new_expr
.arguments()?
.args()
.iter()
.filter_map(|arg| {
let binding = arg.ok()?;
return binding
.as_any_js_expression()?
.as_js_call_expression()
.cloned();
})
.any(|arg| &arg == node),
AnyJsExpression::JsComputedMemberExpression(member_expr) => {
let binding = member_expr.member().ok()?;
let call_expr = binding.as_js_call_expression();
call_expr.is_none() || call_expr? != node
}
AnyJsExpression::JsInExpression(_) => return Some(true),
AnyJsExpression::JsClassExpression(_)
| AnyJsExpression::JsStaticMemberExpression(_)
| AnyJsExpression::JsUnaryExpression(_)
| AnyJsExpression::JsTemplateExpression(_) => true,
_ => false,
};
Some(needs_parentheses && expression.precedence().ok()? >= OperatorPrecedence::Exponential)
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/style/no_implicit_boolean.rs | crates/rome_js_analyze/src/analyzers/style/no_implicit_boolean.rs | use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{
AnyJsLiteralExpression, AnyJsxAttributeValue, JsSyntaxKind, JsxAttribute, JsxAttributeFields, T,
};
use rome_rowan::{AstNode, AstNodeExt, BatchMutationExt};
use crate::JsRuleAction;
declare_rule! {
/// Disallow implicit `true` values on JSX boolean attributes
///
/// ## Examples
///
/// ### Invalid
///
/// ```jsx,expect_diagnostic
/// <input disabled />
/// ```
///
/// ### Valid
///
/// ```jsx
/// <input disabled={false} />
///```
///
/// ```jsx
/// <input disabled={''} />
///```
///
/// ```jsx
/// <input disabled={0} />
///```
///
/// ```jsx
/// <input disabled={undefined} />
///```
///
/// ```jsx
/// <input disabled='false' />
///```
pub(crate) NoImplicitBoolean {
version: "0.7.0",
name: "noImplicitBoolean",
recommended: false,
}
}
impl Rule for NoImplicitBoolean {
type Query = Ast<JsxAttribute>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let n = ctx.query();
match n.initializer() {
Some(_) => None,
None => Some(()),
}
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let n = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
n.range(),
markup! {
"Use explicit boolean values for boolean JSX props."
}
.to_owned(),
))
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let n = ctx.query();
let mut mutation = ctx.root().begin();
let JsxAttributeFields {
name,
initializer: _,
} = n.as_fields();
let name = name.ok()?;
// we use this variable for constructing `JsxAnyAttributeName` without clone the name, so we pre compute the type here.
let name_syntax = name.syntax();
// we need to move trailing_trivia of name_syntax to close_curly_token
// <div disabled /**test*/ /> -> <div disabled={true}/**test*/ />
let last_token_of_name_syntax = name_syntax.last_token()?;
// drop the trailing trivia of name_syntax, at CST level it means
// clean the trailing trivia of last token of name_syntax
let next_last_token_of_name_syntax = last_token_of_name_syntax.with_trailing_trivia([]);
let next_name = name.replace_token_discard_trivia(
last_token_of_name_syntax,
next_last_token_of_name_syntax,
)?;
let attr_value = make::jsx_expression_attribute_value(
make::token(JsSyntaxKind::L_CURLY),
rome_js_syntax::AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsBooleanLiteralExpression(
make::js_boolean_literal_expression(make::token(T![true])),
),
),
make::token(JsSyntaxKind::R_CURLY),
);
let next_attr = make::jsx_attribute(next_name).with_initializer(
make::jsx_attribute_initializer_clause(
make::token(T![=]),
AnyJsxAttributeValue::JsxExpressionAttributeValue(attr_value),
),
);
let next_attr = next_attr.build();
mutation.replace_node(n.clone(), next_attr);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::Always,
message: markup! { "Add explicit `true` literal for this attribute" }.to_owned(),
mutation,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/style/use_block_statements.rs | crates/rome_js_analyze/src/analyzers/style/use_block_statements.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, ActionCategory, Ast, Rule, RuleAction, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{
AnyJsStatement, JsDoWhileStatement, JsElseClause, JsForInStatement, JsForOfStatement,
JsForStatement, JsIfStatement, JsLanguage, JsSyntaxTrivia, JsWhileStatement, JsWithStatement,
TriviaPieceKind, T,
};
use rome_rowan::{declare_node_union, AstNode, BatchMutationExt, SyntaxTriviaPiece};
use crate::JsRuleAction;
use crate::{use_block_statements_diagnostic, use_block_statements_replace_body};
declare_rule! {
/// Requires following curly brace conventions.
/// JavaScript allows the omission of curly braces when a block contains only one statement. However, it is considered by many to be best practice to never omit curly braces around blocks, even when they are optional, because it can lead to bugs and reduces code clarity.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// if (x) x;
/// ```
///
/// ```js,expect_diagnostic
/// if (x) {
/// x;
/// } else y;
/// ```
///
/// ```js,expect_diagnostic
/// if (x) {
/// x;
/// } else if (y) y;
/// ```
///
/// ```js,expect_diagnostic
/// for (;;);
/// ```
///
/// ```js,expect_diagnostic
/// for (p in obj);
/// ```
///
/// ```js,expect_diagnostic
/// for (x of xs);
/// ```
///
/// ```js,expect_diagnostic
/// do;
/// while (x);
/// ```
///
/// ```js,expect_diagnostic
/// while (x);
/// ```
///
/// ```js,expect_diagnostic
/// with (x);
/// ```
pub(crate) UseBlockStatements {
version: "0.7.0",
name: "useBlockStatements",
recommended: false,
}
}
declare_node_union! {
pub(crate) AnyJsBlockStatement = JsIfStatement | JsElseClause | JsDoWhileStatement | JsForInStatement | JsForOfStatement | JsForStatement | JsWhileStatement | JsWithStatement
}
impl Rule for UseBlockStatements {
type Query = Ast<AnyJsBlockStatement>;
type State = UseBlockStatementsOperationType;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let node = ctx.query();
match node {
AnyJsBlockStatement::JsIfStatement(stmt) => {
use_block_statements_diagnostic!(stmt, consequent)
}
AnyJsBlockStatement::JsDoWhileStatement(stmt) => {
use_block_statements_diagnostic!(stmt)
}
AnyJsBlockStatement::JsForInStatement(stmt) => {
use_block_statements_diagnostic!(stmt)
}
AnyJsBlockStatement::JsForOfStatement(stmt) => {
use_block_statements_diagnostic!(stmt)
}
AnyJsBlockStatement::JsForStatement(stmt) => {
use_block_statements_diagnostic!(stmt)
}
AnyJsBlockStatement::JsWhileStatement(stmt) => {
use_block_statements_diagnostic!(stmt)
}
AnyJsBlockStatement::JsWithStatement(stmt) => {
use_block_statements_diagnostic!(stmt)
}
AnyJsBlockStatement::JsElseClause(stmt) => {
let body = stmt.alternate().ok()?;
if matches!(body, AnyJsStatement::JsEmptyStatement(_)) {
return Some(UseBlockStatementsOperationType::ReplaceBody);
}
let is_block = matches!(
body,
AnyJsStatement::JsBlockStatement(_) | AnyJsStatement::JsIfStatement(_)
);
if !is_block {
return Some(UseBlockStatementsOperationType::Wrap(body));
}
None
}
}
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
node.range(),
markup! {
"Block statements are preferred in this position."
},
))
}
fn action(
ctx: &RuleContext<Self>,
nodes_need_to_replaced: &Self::State,
) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
match nodes_need_to_replaced {
UseBlockStatementsOperationType::Wrap(stmt) => {
let mut l_curly_token = make::token(T!['{']);
let r_curly_token = make::token(T!['}']);
// Ensure the opening curly token is separated from the previous token by at least one space
let has_previous_space = stmt
.syntax()
.first_token()
.and_then(|token| token.prev_token())
.map(|token| {
token
.trailing_trivia()
.pieces()
.rev()
.take_while(|piece| !piece.is_newline())
.any(|piece| piece.is_whitespace())
})
.unwrap_or(false);
if !has_previous_space {
l_curly_token =
l_curly_token.with_leading_trivia([(TriviaPieceKind::Whitespace, " ")]);
}
// Clone the leading trivia of the single statement as the
// leading trivia of the closing curly token
let mut leading_trivia = stmt
.syntax()
.first_leading_trivia()
.map(collect_to_first_newline)
.unwrap_or_else(Vec::new);
// If the statement has no leading trivia, add a space after
// the opening curly token
if leading_trivia.is_empty() {
l_curly_token =
l_curly_token.with_trailing_trivia([(TriviaPieceKind::Whitespace, " ")]);
}
// If the leading trivia for the statement contains any newline,
// then the indentation is probably one level too deep for the
// closing curly token, clone the leading trivia from the
// parent node instead
if leading_trivia.iter().any(|piece| piece.is_newline()) {
// Find the parent block statement node, skipping over
// else-clause nodes if this statement is part of an
// else-if chain
let mut node = node.clone();
while let Some(parent) = node.parent::<AnyJsBlockStatement>() {
if !matches!(parent, AnyJsBlockStatement::JsElseClause(_)) {
break;
}
node = parent;
}
leading_trivia = node
.syntax()
.first_leading_trivia()
.map(collect_to_first_newline)
.unwrap_or_else(Vec::new);
}
// Apply the cloned trivia to the closing curly token, or
// fallback to a single space if it's still empty
let r_curly_token = if !leading_trivia.is_empty() {
let leading_trivia = leading_trivia
.iter()
.rev()
.map(|piece| (piece.kind(), piece.text()));
r_curly_token.with_leading_trivia(leading_trivia)
} else {
let has_trailing_single_line_comments = stmt
.syntax()
.last_trailing_trivia()
.map(|trivia| {
trivia
.pieces()
.any(|trivia| trivia.kind() == TriviaPieceKind::SingleLineComment)
})
.unwrap_or(false);
// if the node we have to enclose has some trailing comments, then we add a new line
// to the leading trivia of the right curly brace
if !has_trailing_single_line_comments {
r_curly_token.with_leading_trivia([(TriviaPieceKind::Whitespace, " ")])
} else {
r_curly_token.with_leading_trivia([(TriviaPieceKind::Newline, "\n")])
}
};
mutation.replace_node_discard_trivia(
stmt.clone(),
AnyJsStatement::JsBlockStatement(make::js_block_statement(
l_curly_token,
make::js_statement_list([stmt.clone()]),
r_curly_token,
)),
);
}
UseBlockStatementsOperationType::ReplaceBody => match node {
AnyJsBlockStatement::JsIfStatement(stmt) => {
use_block_statements_replace_body!(
JsIfStatement,
with_consequent,
mutation,
node,
stmt
)
}
AnyJsBlockStatement::JsElseClause(stmt) => {
use_block_statements_replace_body!(
JsElseClause,
with_alternate,
mutation,
node,
stmt
)
}
AnyJsBlockStatement::JsDoWhileStatement(stmt) => {
use_block_statements_replace_body!(JsDoWhileStatement, mutation, node, stmt)
}
AnyJsBlockStatement::JsForInStatement(stmt) => {
use_block_statements_replace_body!(JsForInStatement, mutation, node, stmt)
}
AnyJsBlockStatement::JsForOfStatement(stmt) => {
use_block_statements_replace_body!(JsForOfStatement, mutation, node, stmt)
}
AnyJsBlockStatement::JsForStatement(stmt) => {
use_block_statements_replace_body!(JsForStatement, mutation, node, stmt)
}
AnyJsBlockStatement::JsWhileStatement(stmt) => {
use_block_statements_replace_body!(JsWhileStatement, mutation, node, stmt)
}
AnyJsBlockStatement::JsWithStatement(stmt) => {
use_block_statements_replace_body!(JsWithStatement, mutation, node, stmt)
}
},
};
Some(RuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Wrap the statement with a `JsBlockStatement`" }.to_owned(),
mutation,
})
}
}
/// Collect newline and comment trivia pieces in reverse order up to the first newline included
fn collect_to_first_newline(trivia: JsSyntaxTrivia) -> Vec<SyntaxTriviaPiece<JsLanguage>> {
let mut has_newline = false;
trivia
.pieces()
.rev()
.filter(|piece| piece.is_newline() || piece.is_whitespace())
.take_while(|piece| {
let had_newline = has_newline;
has_newline |= piece.is_newline();
!had_newline
})
.collect()
}
pub enum UseBlockStatementsOperationType {
Wrap(AnyJsStatement),
ReplaceBody,
}
#[macro_export]
macro_rules! use_block_statements_diagnostic {
($id:ident, $field:ident) => {{
let body = $id.$field().ok()?;
if matches!(body, AnyJsStatement::JsEmptyStatement(_)) {
Some(UseBlockStatementsOperationType::ReplaceBody)
} else if !matches!(body, AnyJsStatement::JsBlockStatement(_)) {
Some(UseBlockStatementsOperationType::Wrap(body))
} else {
None
}
}};
($id:ident) => {
use_block_statements_diagnostic!($id, body)
};
}
#[macro_export]
macro_rules! use_block_statements_replace_body {
($stmt_type:ident, $builder_method:ident, $mutation:ident, $node:ident, $stmt:ident) => {
$mutation.replace_node(
$node.clone(),
AnyJsBlockStatement::$stmt_type($stmt.clone().$builder_method(
AnyJsStatement::JsBlockStatement(make::js_block_statement(
make::token(T!['{']).with_leading_trivia([(TriviaPieceKind::Whitespace, " ")]),
make::js_statement_list([]),
make::token(T!['}']),
)),
)),
)
};
($stmt_type:ident, $mutation:ident, $node:ident, $stmt:ident) => {
use_block_statements_replace_body!($stmt_type, with_body, $mutation, $node, $stmt)
};
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/style/use_default_parameter_last.rs | crates/rome_js_analyze/src/analyzers/style/use_default_parameter_last.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_syntax::{JsFormalParameter, JsInitializerClause, JsSyntaxToken, TsPropertyParameter};
use rome_rowan::{declare_node_union, AstNode, BatchMutationExt, Direction};
use crate::JsRuleAction;
declare_rule! {
/// Enforce default function parameters and optional function parameters to be last.
///
/// Default and optional parameters that precede a required parameter cannot be omitted at call site.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// function f(a = 0, b) {}
/// ```
///
/// ```js,expect_diagnostic
/// function f(a, b = 0, c) {}
/// ```
///
/// ```ts,expect_diagnostic
/// function f(a: number, b?: number, c: number) {}
/// ```
///
/// ```ts,expect_diagnostic
/// class Foo {
/// constructor(readonly a = 10, readonly b: number) {}
/// }
/// ```
///
/// ### Valid
///
/// ```js
/// function f(a, b = 0) {}
/// ```
///
/// ```ts
/// function f(a: number, b?: number, c = 0) {}
/// ```
///
/// ```ts
/// function f(a: number, b = 0, c?: number) {}
/// ```
///
pub(crate) UseDefaultParameterLast {
version: "11.0.0",
name: "useDefaultParameterLast",
recommended: true,
}
}
declare_node_union! {
pub(crate) AnyFormalParameter = JsFormalParameter | TsPropertyParameter
}
impl AnyFormalParameter {
pub(crate) fn is_required(&self) -> bool {
self.question_mark_token().is_none() && self.initializer().is_none()
}
pub(crate) fn initializer(&self) -> Option<JsInitializerClause> {
match self {
AnyFormalParameter::JsFormalParameter(x) => x.initializer(),
AnyFormalParameter::TsPropertyParameter(x) => x
.formal_parameter()
.ok()?
.as_js_formal_parameter()?
.initializer(),
}
}
pub(crate) fn question_mark_token(&self) -> Option<JsSyntaxToken> {
match self {
AnyFormalParameter::JsFormalParameter(x) => x.question_mark_token(),
AnyFormalParameter::TsPropertyParameter(x) => x
.formal_parameter()
.ok()?
.as_js_formal_parameter()?
.question_mark_token(),
}
}
}
impl Rule for UseDefaultParameterLast {
type Query = Ast<AnyFormalParameter>;
type State = AnyFormalParameter;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let formal_param = ctx.query();
if formal_param.is_required() {
return None;
}
let last_required_param = formal_param
.syntax()
.siblings(Direction::Next)
.filter_map(AnyFormalParameter::cast)
.filter(|x| x.is_required())
.last();
last_required_param
}
fn diagnostic(
ctx: &RuleContext<Self>,
last_required_param: &Self::State,
) -> Option<RuleDiagnostic> {
let formal_param = ctx.query();
let param_kind = if formal_param.question_mark_token().is_some() {
"optional"
} else {
"default"
};
Some(RuleDiagnostic::new(
rule_category!(),
formal_param.range(),
markup! {
"This "<Emphasis>{param_kind}" parameter"</Emphasis>" should follow the last "<Emphasis>"required parameter"</Emphasis>" or should be a "<Emphasis>"required parameter"</Emphasis>"."
},
).detail(
last_required_param.range(),
markup! {
"The last "<Emphasis>"required parameter"</Emphasis>" is here:"
},
).note(
markup! {
"A "<Emphasis>{param_kind}" parameter"</Emphasis>" that precedes a "<Emphasis>"required parameter"</Emphasis>" cannot be omitted at call site."
}
))
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let opt_param = ctx.query();
let mut mutation = ctx.root().begin();
if opt_param.question_mark_token().is_some() {
let question_mark = opt_param.question_mark_token()?;
let prev_token = question_mark.prev_token()?;
let new_token =
prev_token.append_trivia_pieces(question_mark.trailing_trivia().pieces());
mutation.replace_token_discard_trivia(prev_token, new_token);
mutation.remove_token(question_mark);
} else {
let initializer = opt_param.initializer()?;
let prev_token = initializer.syntax().prev_sibling()?.last_token()?;
let new_token = prev_token
.trim_trailing_trivia()
.append_trivia_pieces(initializer.syntax().last_trailing_trivia()?.pieces());
mutation.replace_token_discard_trivia(prev_token, new_token);
mutation.remove_node(initializer);
}
Some(JsRuleAction {
mutation,
message:
markup! {"Turn the parameter into a "<Emphasis>"required parameter"</Emphasis>"."}
.to_owned(),
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/style/use_numeric_literals.rs | crates/rome_js_analyze/src/analyzers/style/use_numeric_literals.rs | use crate::semantic_services::Semantic;
use crate::{ast_utils, JsRuleAction};
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, ActionCategory, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_semantic::SemanticModel;
use rome_js_syntax::{
global_identifier, AnyJsExpression, AnyJsLiteralExpression, AnyJsMemberExpression,
JsCallExpression, JsSyntaxToken,
};
use rome_rowan::{AstNode, AstSeparatedList, BatchMutationExt};
declare_rule! {
/// Disallow `parseInt()` and `Number.parseInt()` in favor of binary, octal, and hexadecimal literals
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// parseInt("111110111", 2) === 503;
/// ```
///
/// ```js,expect_diagnostic
/// Number.parseInt("767", 8) === 503;
/// ```
/// ### Valid
///
/// ```js
/// parseInt(1);
/// parseInt(1, 3);
/// Number.parseInt(1);
/// Number.parseInt(1, 3);
///
/// 0b111110111 === 503;
/// 0o767 === 503;
/// 0x1F7 === 503;
///
/// a[parseInt](1,2);
///
/// parseInt(foo);
/// parseInt(foo, 2);
/// Number.parseInt(foo);
/// Number.parseInt(foo, 2);
/// ```
pub(crate) UseNumericLiterals {
version: "11.0.0",
name: "useNumericLiterals",
recommended: true,
}
}
pub struct CallInfo {
callee: &'static str,
text: String,
radix: Radix,
}
impl Rule for UseNumericLiterals {
type Query = Semantic<JsCallExpression>;
type State = CallInfo;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let expr = ctx.query();
let model = ctx.model();
CallInfo::try_from_expr(expr, model)
}
fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
node.range(),
markup! { "Use "{state.radix.description()}" literals instead of "{state.callee} }
.to_owned(),
))
}
fn action(ctx: &RuleContext<Self>, call: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
let number = call.to_numeric_literal()?;
let number = ast_utils::token_with_source_trivia(number, node);
mutation.replace_node_discard_trivia(
AnyJsExpression::JsCallExpression(node.clone()),
AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsNumberLiteralExpression(
make::js_number_literal_expression(number),
),
),
);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Replace with "{call.radix.description()}" literals" }.to_owned(),
mutation,
})
}
}
impl CallInfo {
fn try_from_expr(expr: &JsCallExpression, model: &SemanticModel) -> Option<CallInfo> {
let args = expr.arguments().ok()?.args();
if args.len() != 2 {
return None;
}
let mut args = args.into_iter();
let text = args
.next()?
.ok()?
.as_any_js_expression()?
.as_static_value()?
.as_string_constant()?
.to_string();
let radix = args
.next()?
.ok()?
.as_any_js_expression()?
.as_any_js_literal_expression()?
.as_js_number_literal_expression()?
.as_number()?;
let callee = get_callee(expr, model)?;
Some(CallInfo {
callee,
text,
radix: Radix::from_f64(radix)?,
})
}
fn to_numeric_literal(&self) -> Option<JsSyntaxToken> {
i128::from_str_radix(&self.text, self.radix as u32).ok()?;
let number = format!("{}{}", self.radix.prefix(), self.text);
let number = make::js_number_literal(&number);
Some(number)
}
}
fn get_callee(expr: &JsCallExpression, model: &SemanticModel) -> Option<&'static str> {
let callee = expr.callee().ok()?.omit_parentheses();
if let Some((reference, name)) = global_identifier(&callee) {
if name.text() == "parseInt" && model.binding(&reference).is_none() {
return Some("parseInt()");
}
return None;
}
let callee = AnyJsMemberExpression::cast_ref(callee.syntax())?;
if callee.member_name()?.text() != "parseInt" {
return None;
}
let object = callee.object().ok()?.omit_parentheses();
let (reference, name) = global_identifier(&object)?;
if name.text() == "Number" && model.binding(&reference).is_none() {
return Some("Number.parseInt()");
}
None
}
#[derive(Copy, Clone)]
enum Radix {
Binary = 2,
Octal = 8,
Hexadecimal = 16,
}
impl Radix {
fn from_f64(v: f64) -> Option<Self> {
Some(if v == 2.0 {
Self::Binary
} else if v == 8.0 {
Self::Octal
} else if v == 16.0 {
Self::Hexadecimal
} else {
return None;
})
}
fn prefix(&self) -> &'static str {
match self {
Radix::Binary => "0b",
Radix::Octal => "0o",
Radix::Hexadecimal => "0x",
}
}
fn description(&self) -> &'static str {
match self {
Radix::Binary => "binary",
Radix::Octal => "octal",
Radix::Hexadecimal => "hexadecimal",
}
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/performance/no_delete.rs | crates/rome_js_analyze/src/analyzers/performance/no_delete.rs | use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{
AnyJsAssignment, AnyJsAssignmentPattern, AnyJsExpression, JsComputedMemberExpressionFields,
JsStaticMemberExpressionFields, JsUnaryExpression, JsUnaryOperator, T,
};
use rome_rowan::{AstNode, BatchMutationExt};
use crate::JsRuleAction;
declare_rule! {
/// Disallow the use of the `delete` operator.
///
/// The `delete` operator enables the removal of a property from an object.
///
/// The `delete` operator should be avoided because it [can prevent some optimizations of _JavaScript_ engines](https://webkit.org/blog/10298/inline-caching-delete/).
/// Moreover, it can lead to unexpected results.
/// For instance, deleting an array element [does not change the length of the array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#deleting_array_elements).
///
/// The only legitimate use of `delete` is on an object that behaves like a _map_.
/// To allow this pattern, this rule does not report `delete` on computed properties that are not literal values.
/// Consider using [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instead of an object.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// const arr = [1, 2, 3];
/// delete arr[0];
/// ```
///
/// ```js,expect_diagnostic
/// const obj = {a: {b: {c: 123}}};
/// delete obj.a.b.c;
/// ```
///
/// ### Valid
///
/// ```js
/// const foo = new Set([1,2,3]);
/// foo.delete(1);
///```
///
/// ```js
/// const map = Object.create(null);
/// const key = "key"
/// map[key] = "value"
/// delete map[key];
///```
///
/// ```js
/// let x = 5;
/// delete f(); // uncovered by this rule.
///```
///
pub(crate) NoDelete {
version: "0.7.0",
name: "noDelete",
recommended: true,
}
}
impl Rule for NoDelete {
type Query = Ast<JsUnaryExpression>;
type State = AnyJsExpression;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let op = node.operator().ok()?;
if op != JsUnaryOperator::Delete {
return None;
}
let argument = node.argument().ok()?;
let should_report = if let Some(computed) = argument.as_js_computed_member_expression() {
// `delete record[x]` is allowed, but if `x` is a literal value.
computed
.member()
.ok()?
.as_any_js_literal_expression()
.is_some()
} else {
// if `argument` is not a computed or static member,
// then `delete` has either no effect or an undefined behavior.
// This should be rejected by another rule.
argument.as_js_static_member_expression().is_some()
};
should_report.then_some(argument)
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
node.range(),
markup! {
"Avoid the "<Emphasis>"delete"</Emphasis>" operator which can impact performance."
},
))
}
fn action(ctx: &RuleContext<Self>, argument: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let assignment = to_assignment(argument).ok()?;
let mut mutation = ctx.root().begin();
mutation.replace_node(
AnyJsExpression::from(node.clone()),
AnyJsExpression::from(make::js_assignment_expression(
AnyJsAssignmentPattern::AnyJsAssignment(assignment),
make::token_decorated_with_space(T![=]),
AnyJsExpression::from(make::js_identifier_expression(
make::js_reference_identifier(make::ident("undefined")),
)),
)),
);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Use an "<Emphasis>"undefined"</Emphasis>" assignment instead." }
.to_owned(),
mutation,
})
}
}
fn to_assignment(expr: &AnyJsExpression) -> Result<AnyJsAssignment, ()> {
match expr {
AnyJsExpression::JsStaticMemberExpression(expr) if !expr.is_optional_chain() => {
let JsStaticMemberExpressionFields {
object,
operator_token,
member,
} = expr.as_fields();
Ok(AnyJsAssignment::from(make::js_static_member_assignment(
object.map_err(drop)?,
operator_token.map_err(drop)?,
member.map_err(drop)?,
)))
}
AnyJsExpression::JsComputedMemberExpression(expr) if !expr.is_optional_chain() => {
let JsComputedMemberExpressionFields {
object,
optional_chain_token: _,
l_brack_token,
member,
r_brack_token,
} = expr.as_fields();
Ok(AnyJsAssignment::from(make::js_computed_member_assignment(
object.map_err(drop)?,
l_brack_token.map_err(drop)?,
member.map_err(drop)?,
r_brack_token.map_err(drop)?,
)))
}
_ => Err(()),
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/complexity/no_useless_label.rs | crates/rome_js_analyze/src/analyzers/complexity/no_useless_label.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_syntax::{
AnyJsStatement, JsDoWhileStatement, JsForInStatement, JsForOfStatement, JsForStatement,
JsLabeledStatement, JsSwitchStatement, JsWhileStatement,
};
use crate::JsRuleAction;
use rome_rowan::{declare_node_union, AstNode, BatchMutationExt};
declare_rule! {
/// Disallow unnecessary labels.
///
/// If a loop contains no nested loops or switches, labeling the loop is unnecessary.
///
/// Source: https://eslint.org/docs/latest/rules/no-extra-label
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// loop: while(a) {
/// break loop;
/// }
/// ```
///
/// ### Valid
///
/// ```js
/// outer: while(a) {
/// while(b) {
/// break outer;
/// }
/// }
/// ```
///
pub(crate) NoUselessLabel {
version: "12.0.0",
name: "noUselessLabel",
recommended: true,
}
}
declare_node_union! {
pub(crate) JsBreakableStatement =
JsDoWhileStatement |
JsForInStatement |
JsForOfStatement |
JsForStatement |
JsSwitchStatement |
JsWhileStatement
}
impl Rule for NoUselessLabel {
type Query = Ast<AnyJsStatement>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let stmt = ctx.query();
let label_token = match stmt {
AnyJsStatement::JsBreakStatement(x) => x.label_token(),
AnyJsStatement::JsContinueStatement(x) => x.label_token(),
_ => None,
}?;
let label = label_token.text_trimmed();
for parent in stmt.syntax().ancestors() {
if JsBreakableStatement::can_cast(parent.kind()) {
if let Some(labeled_stmt) = JsLabeledStatement::cast(parent.parent()?) {
if labeled_stmt.label_token().ok()?.text_trimmed() == label {
return Some(());
}
}
break;
} else if let Some(labeled_stmt) = JsLabeledStatement::cast(parent) {
if labeled_stmt.label_token().ok()?.text_trimmed() == label {
break;
}
}
}
None
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let stmt = ctx.query();
let label_token = match stmt {
AnyJsStatement::JsBreakStatement(x) => x.label_token(),
AnyJsStatement::JsContinueStatement(x) => x.label_token(),
_ => None,
}?;
Some(RuleDiagnostic::new(
rule_category!(),
label_token.text_trimmed_range(),
markup! {
"Unnecessary "<Emphasis>"label"</Emphasis>"."
},
))
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let stmt = ctx.query();
let (stmt_token, label_token) = match stmt {
AnyJsStatement::JsBreakStatement(x) => (x.break_token().ok()?, x.label_token()?),
AnyJsStatement::JsContinueStatement(x) => (x.continue_token().ok()?, x.label_token()?),
_ => return None,
};
// We want to remove trailing spaces and keep all comments that follows `stmt_token`
// e.g. `break /* a comment */ ` to `break /* a comment */`.
// This requires to traverse the trailing trivia in reverse order.
// We keep trailing trivia of `label_stmt`
// e.g. `break label // a comment` -> `break // a comment`
// We do not keep leading trivia of `label_stmt` because we assume that they are associated to the label.
let new_stmt_token = stmt_token
.trim_trailing_trivia()
.append_trivia_pieces(label_token.trailing_trivia().pieces());
let mut mutation = ctx.root().begin();
mutation.remove_token(label_token);
mutation.replace_token_discard_trivia(stmt_token, new_stmt_token);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! {"Remove the unnecessary "<Emphasis>"label"</Emphasis>".\nYou can achieve the same result without the label."}.to_owned(),
mutation,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/complexity/no_useless_type_constraint.rs | crates/rome_js_analyze/src/analyzers/complexity/no_useless_type_constraint.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_syntax::TsTypeConstraintClause;
use rome_rowan::{AstNode, BatchMutationExt};
use crate::JsRuleAction;
declare_rule! {
/// Disallow using `any` or `unknown` as type constraint.
///
/// Generic type parameters (`<T>`) in TypeScript may be **constrained** with [`extends`](https://www.typescriptlang.org/docs/handbook/generics.html#generic-constraints).
/// A supplied type must then be a subtype of the supplied constraint.
/// All types are subtypes of `any` and `unknown`.
/// It is thus useless to extend from `any` or `unknown`.
///
/// Source: https://typescript-eslint.io/rules/no-unnecessary-type-constraint/
///
/// ## Examples
///
/// ### Invalid
///
/// ```ts,expect_diagnostic
/// interface FooAny<T extends any> {}
/// ```
/// ```ts,expect_diagnostic
/// type BarAny<T extends any> = {};
/// ```
/// ```ts,expect_diagnostic
/// class BazAny<T extends any> {
/// }
/// ```
/// ```ts,expect_diagnostic
/// class BazAny {
/// quxAny<U extends any>() {}
/// }
/// ```
/// ```ts,expect_diagnostic
/// const QuuxAny = <T extends any>() => {};
/// ```
/// ```ts,expect_diagnostic
/// function QuuzAny<T extends any>() {}
/// ```
///
/// ```ts,expect_diagnostic
/// interface FooUnknown<T extends unknown> {}
/// ```
/// ```ts,expect_diagnostic
/// type BarUnknown<T extends unknown> = {};
/// ```
/// ```ts,expect_diagnostic
/// class BazUnknown<T extends unknown> {
/// }
/// ```ts,expect_diagnostic
/// class BazUnknown {
/// quxUnknown<U extends unknown>() {}
/// }
/// ```
/// ```ts,expect_diagnostic
/// const QuuxUnknown = <T extends unknown>() => {};
/// ```
/// ```ts,expect_diagnostic
/// function QuuzUnknown<T extends unknown>() {}
/// ```
///
/// ### Valid
///
/// ```ts
/// interface Foo<T> {}
///
/// type Bar<T> = {};
///```
pub(crate) NoUselessTypeConstraint {
version: "next",
name: "noUselessTypeConstraint",
recommended: true,
}
}
impl Rule for NoUselessTypeConstraint {
type Query = Ast<TsTypeConstraintClause>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let node = ctx.query();
let ty = node.ty().ok()?;
if ty.as_ts_any_type().is_some() || ty.as_ts_unknown_type().is_some() {
Some(())
} else {
None
}
}
fn diagnostic(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(
RuleDiagnostic::new(
rule_category!(),
node.syntax().text_trimmed_range(),
markup! {
"Constraining a type parameter to "<Emphasis>"any"</Emphasis>" or "<Emphasis>"unknown"</Emphasis>" is useless."
},
)
.note(markup! {
"All types are subtypes of "<Emphasis>"any"</Emphasis>" and "<Emphasis>"unknown"</Emphasis>"."
}),
)
}
fn action(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
mutation.remove_node(node.clone());
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Remove the constraint." }.to_owned(),
mutation,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/complexity/no_useless_constructor.rs | crates/rome_js_analyze/src/analyzers/complexity/no_useless_constructor.rs | use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_syntax::{
AnyJsCallArgument, AnyJsClass, AnyJsConstructorParameter, JsCallExpression,
JsConstructorClassMember, TsPropertyParameter,
};
use rome_rowan::{AstNode, AstNodeList, AstSeparatedList, BatchMutationExt};
use crate::JsRuleAction;
declare_rule! {
/// Disallow unnecessary constructors.
///
/// _ES2015_ provides a default class constructor if one is not specified.
/// As such, providing an empty constructor or one that delegates into its parent is unnecessary.
///
/// Source: https://typescript-eslint.io/rules/no-useless-constructor
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// class A {
/// constructor (a) {}
/// }
/// ```
///
/// ```js,expect_diagnostic
/// class B extends A {
/// constructor (a) {
/// super(a);
/// }
/// }
/// ```
///
/// ```js,expect_diagnostic
/// class C {
/// /**
/// * Documented constructor.
/// */
/// constructor () {}
/// }
/// ```
///
/// ## Valid
///
/// ```js
/// class A {
/// constructor (prop) {
/// this.prop = prop;
/// }
/// }
/// ```
///
/// ```js
/// class B extends A {
/// constructor () {
/// super(5);
/// }
/// }
/// ```
///
/// ```ts
/// class C {
/// // Empty constructor with parameter properties are allowed.
/// constructor (private prop: number) {}
/// }
/// ```
pub(crate) NoUselessConstructor {
version: "12.1.0",
name: "noUselessConstructor",
recommended: true,
}
}
impl Rule for NoUselessConstructor {
type Query = Ast<JsConstructorClassMember>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let constructor = ctx.query();
let is_not_public = constructor
.modifiers()
.iter()
.any(|modifier| !modifier.is_public());
if is_not_public {
return None;
}
let has_parameter_property = constructor
.parameters()
.ok()?
.parameters()
.iter()
.filter_map(|x| x.ok())
.any(|x| TsPropertyParameter::can_cast(x.syntax().kind()));
if has_parameter_property {
return None;
}
let has_parent_class = constructor
.syntax()
.ancestors()
.find_map(AnyJsClass::cast)
.filter(|x| x.extends_clause().is_some())
.is_some();
let mut body_statements = constructor.body().ok()?.statements().iter();
let Some(first) = body_statements.next() else {
if has_parent_class {
// A `super` call is missing.
// Do not report as useless constructor.
return None;
}
// empty body and no parent class
return Some(());
};
if body_statements.count() != 0 {
// There are more than one statement.
return None;
}
let Some(js_expr) = first.as_js_expression_statement()?.expression().ok() else {
return None;
};
let Some(js_call) = js_expr.as_js_call_expression() else {
return None;
};
let is_super_call = js_call.callee().ok()?.as_js_super_expression().is_some();
if !is_super_call {
return None;
}
if !is_delegating_initialization(constructor, js_call) {
return None;
}
// The constructor has a single statement:
// a `super()` call that delegates initialization to the parent class
Some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let constructor = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
constructor.range(),
markup! {
"This constructor is unnecessary."
},
))
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let constructor = ctx.query();
let mut mutation = ctx.root().begin();
mutation.remove_node(constructor.clone());
// Safely remove the constructor whether there is no comments.
let applicability = if constructor.syntax().has_comments_descendants() {
Applicability::MaybeIncorrect
} else {
Applicability::Always
};
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability,
message: markup! { "Remove the unnecessary constructor." }.to_owned(),
mutation,
})
}
}
/// Is `constructor` delegating initialization via `super_call`?
///
/// This checks that constructors' **all** parameters are passed to the super-call in the same order.
fn is_delegating_initialization(
constructor: &JsConstructorClassMember,
super_call: &JsCallExpression,
) -> bool {
let result = || {
let parameters = constructor.parameters().ok()?.parameters().iter();
let arguments = super_call.arguments().ok()?.args().iter();
if parameters.clone().count() != arguments.clone().count() {
return None;
}
let zipped = parameters.zip(arguments);
for (param, arg) in zipped {
let param = param.ok()?;
let arg = arg.ok()?;
match (param, arg) {
(
AnyJsConstructorParameter::JsRestParameter(param),
AnyJsCallArgument::JsSpread(arg),
) => {
let param_name = param
.binding()
.ok()?
.as_any_js_binding()?
.as_js_identifier_binding()?
.name_token()
.ok()?;
let arg_name = arg
.argument()
.ok()?
.as_js_identifier_expression()?
.name()
.ok()?
.value_token()
.ok()?;
if param_name.text_trimmed() != arg_name.text_trimmed() {
return Some(false);
}
}
(
AnyJsConstructorParameter::AnyJsFormalParameter(param),
AnyJsCallArgument::AnyJsExpression(expr),
) => {
let param_name = param
.as_js_formal_parameter()?
.binding()
.ok()?
.as_any_js_binding()?
.as_js_identifier_binding()?
.name_token()
.ok()?;
let arg_name = expr
.as_js_identifier_expression()?
.name()
.ok()?
.value_token()
.ok()?;
if param_name.text_trimmed() != arg_name.text_trimmed() {
return Some(false);
}
}
(_, _) => {
return Some(false);
}
}
}
Some(true)
};
result().unwrap_or(false)
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/complexity/no_useless_switch_case.rs | crates/rome_js_analyze/src/analyzers/complexity/no_useless_switch_case.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_syntax::{JsCaseClause, JsDefaultClause};
use rome_rowan::{AstNode, AstNodeList, BatchMutationExt, Direction, SyntaxElement};
use crate::JsRuleAction;
declare_rule! {
/// Disallow useless `case` in `switch` statements.
///
/// A `switch` statement can optionally have a `default` clause.
///
/// The `default` clause will be still executed only if there is no match in the `case` clauses.
/// An empty `case` clause that precedes the `default` clause is thus useless.
///
/// Source: https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-useless-switch-case.md
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// switch (foo) {
/// case 0:
/// default:
/// break;
/// case 1:
/// break;
/// }
/// ```
///
/// ```js,expect_diagnostic
/// switch (foo) {
/// default:
/// case 0:
/// break;
/// case 1:
/// break;
/// }
/// ```
///
/// ### Valid
///
/// ```js
/// switch (foo) {
/// case 0:
/// break;
/// default:
/// break;
/// }
/// ```
///
/// ```js
/// switch (foo) {
/// case 0:
/// break;
/// }
/// ```
///
pub(crate) NoUselessSwitchCase {
version: "12.0.0",
name: "noUselessSwitchCase",
recommended: true,
}
}
impl Rule for NoUselessSwitchCase {
type Query = Ast<JsDefaultClause>;
type State = JsCaseClause;
type Signals = Vec<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let default_clause = ctx.query();
let it = default_clause
.syntax()
.siblings(Direction::Prev)
.filter_map(JsCaseClause::cast)
.take_while(|case| case.consequent().is_empty());
if default_clause.consequent().is_empty() {
// The default clause is directly followed by at least a case. e.g.
//
// ```js
// switch (foo) {
// default:
// case 1:
// case 2:
// break;
// }
// ```
//
it.chain(
default_clause
.syntax()
.siblings(Direction::Next)
.filter_map(JsCaseClause::cast)
.take_while(|case| case.consequent().is_empty()),
)
.chain(
default_clause
.syntax()
.siblings(Direction::Next)
.filter_map(JsCaseClause::cast)
.find(|case| !case.consequent().is_empty()),
)
.collect()
} else {
it.collect()
}
}
fn diagnostic(ctx: &RuleContext<Self>, useless_case: &Self::State) -> Option<RuleDiagnostic> {
let default_clause = ctx.query();
Some(
RuleDiagnostic::new(
rule_category!(),
useless_case.range(),
markup! {
"Useless "<Emphasis>"case clause"</Emphasis>"."
},
)
.detail(
default_clause.range(),
markup! {
"because the "<Emphasis>"default clause"</Emphasis>" is present:"
},
),
)
}
fn action(ctx: &RuleContext<Self>, useless_case: &Self::State) -> Option<JsRuleAction> {
let default_clause = ctx.query();
let mut mutation = ctx.root().begin();
let consequent = useless_case.consequent();
if consequent.len() > 0 {
let default_clause_colon_token = default_clause.colon_token().ok()?;
let new_default_clause = default_clause
.to_owned()
.with_consequent(consequent)
.with_colon_token(default_clause_colon_token.append_trivia_pieces(
useless_case.colon_token().ok()?.trailing_trivia().pieces(),
));
mutation.remove_node(default_clause.to_owned());
mutation.replace_element(
SyntaxElement::Node(useless_case.syntax().to_owned()),
SyntaxElement::Node(new_default_clause.syntax().to_owned()),
);
} else {
mutation.remove_node(useless_case.to_owned());
}
Some(JsRuleAction {
mutation,
message: markup! {"Remove the useless "<Emphasis>"case"</Emphasis>"."}.to_owned(),
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/complexity/no_for_each.rs | crates/rome_js_analyze/src/analyzers/complexity/no_for_each.rs | use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{AnyJsMemberExpression, JsCallExpression};
use rome_rowan::AstNode;
declare_rule! {
/// Prefer `for...of` statement instead of `Array.forEach`.
///
/// Here's a summary of why `forEach` may be disallowed, and why `for...of` is preferred for almost any use-case of `forEach`:
/// - Performance: Using `forEach` can lead to performance issues, especially when working with large arrays.
/// When more requirements are added on, `forEach` typically gets chained with other methods like `filter` or `map`, causing multiple iterations over the same Array.
/// Encouraging for loops discourages chaining and encourages single-iteration logic (e.g. using a continue instead of `filter`).
///
/// - Readability: While `forEach` is a simple and concise way to iterate over an array, it can make the code less readable, especially when the callback function is complex.
/// In contrast, using a for loop or a `for...of` loop can make the code more explicit and easier to read.
///
/// - Debugging: `forEach` can make debugging more difficult, because it hides the iteration process.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// els.forEach(el => {
/// el
/// })
/// ```
///
/// ```js,expect_diagnostic
/// els['forEach'](el => {
/// el
/// })
/// ```
///
/// ## Valid
///
/// ```js
/// for (const el of els) {
/// el
/// }
/// ```
///
pub(crate) NoForEach {
version: "12.1.0",
name: "noForEach",
recommended: false,
}
}
impl Rule for NoForEach {
type Query = Ast<JsCallExpression>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let member_expression =
AnyJsMemberExpression::cast_ref(node.callee().ok()?.omit_parentheses().syntax())?;
(member_expression.member_name()?.text() == "forEach").then_some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
node.syntax().text_trimmed_range(),
markup! {
"Prefer for...of instead of Array.forEach"
},
))
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/complexity/no_extra_boolean_cast.rs | crates/rome_js_analyze/src/analyzers/complexity/no_extra_boolean_cast.rs | use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_syntax::{
AnyJsExpression, JsCallArgumentList, JsCallArguments, JsCallExpression,
JsConditionalExpression, JsDoWhileStatement, JsForStatement, JsIfStatement, JsNewExpression,
JsSyntaxKind, JsSyntaxNode, JsUnaryExpression, JsUnaryOperator, JsWhileStatement,
};
use rome_rowan::{AstNode, AstSeparatedList, BatchMutationExt, SyntaxNodeCast};
use crate::JsRuleAction;
pub enum ExtraBooleanCastType {
/// !!x
DoubleNegation,
/// Boolean(x)
BooleanCall,
}
declare_rule! {
/// Disallow unnecessary boolean casts
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// if (!Boolean(foo)) {
/// }
/// ```
///
/// ```js,expect_diagnostic
/// while (!!foo) {}
/// ```
///
/// ```js,expect_diagnostic
/// let x = 1;
/// do {
/// 1 + 1;
/// } while (Boolean(x));
/// ```
///
/// ```js,expect_diagnostic
/// for (; !!foo; ) {}
/// ```
///
/// ```js,expect_diagnostic
/// new Boolean(!!x);
/// ```
///
/// ### Valid
/// ```js
/// Boolean(!x);
/// !x;
/// !!x;
/// ```
pub(crate) NoExtraBooleanCast {
version: "0.9.0",
name: "noExtraBooleanCast",
recommended: true,
}
}
/// Check if this node is in the position of `test` slot of parent syntax node.
/// ## Example
/// ```js
/// if (!!x) {
/// ^^^ this is a boolean context
/// }
/// ```
fn is_in_boolean_context(node: &JsSyntaxNode) -> Option<bool> {
let parent = node.parent()?;
match parent.kind() {
JsSyntaxKind::JS_IF_STATEMENT => {
Some(parent.cast::<JsIfStatement>()?.test().ok()?.syntax() == node)
}
JsSyntaxKind::JS_DO_WHILE_STATEMENT => {
Some(parent.cast::<JsDoWhileStatement>()?.test().ok()?.syntax() == node)
}
JsSyntaxKind::JS_WHILE_STATEMENT => {
Some(parent.cast::<JsWhileStatement>()?.test().ok()?.syntax() == node)
}
JsSyntaxKind::JS_FOR_STATEMENT => {
Some(parent.cast::<JsForStatement>()?.test()?.syntax() == node)
}
JsSyntaxKind::JS_CONDITIONAL_EXPRESSION => Some(
parent
.cast::<JsConditionalExpression>()?
.test()
.ok()?
.syntax()
== node,
),
_ => None,
}
}
/// Checks if the node is a `Boolean` Constructor Call
/// # Example
/// ```js
/// new Boolean(x);
/// ```
/// The checking algorithm of [JsNewExpression] is a little different from [JsCallExpression] due to
/// two nodes have different shapes
fn is_boolean_constructor_call(node: &JsSyntaxNode) -> Option<bool> {
let expr = JsCallArgumentList::cast(node.clone())?
.parent::<JsCallArguments>()?
.parent::<JsNewExpression>()?;
Some(expr.has_callee("Boolean"))
}
/// Check if the SyntaxNode is a `Boolean` Call Expression
/// ## Example
/// ```js
/// Boolean(x)
/// ```
fn is_boolean_call(node: &JsSyntaxNode) -> Option<bool> {
let expr = JsCallExpression::cast(node.clone())?;
Some(expr.has_callee("Boolean"))
}
/// Check if the SyntaxNode is a Negate Unary Expression
/// ## Example
/// ```js
/// !!x
/// ```
fn is_negation(node: &JsSyntaxNode) -> Option<JsUnaryExpression> {
let unary_expr = JsUnaryExpression::cast(node.clone())?;
if unary_expr.operator().ok()? == JsUnaryOperator::LogicalNot {
Some(unary_expr)
} else {
None
}
}
impl Rule for NoExtraBooleanCast {
type Query = Ast<AnyJsExpression>;
type State = (AnyJsExpression, ExtraBooleanCastType);
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let n = ctx.query();
let syntax = n.syntax().clone();
let parent_syntax = syntax.parent()?;
// Check if parent `SyntaxNode` in any boolean `Type Coercion` context,
// reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean
let parent_node_in_boolean_cast_context = is_in_boolean_context(&syntax).unwrap_or(false)
|| is_boolean_constructor_call(&parent_syntax).unwrap_or(false)
|| is_negation(&parent_syntax).is_some()
|| is_boolean_call(&parent_syntax).unwrap_or(false);
// Convert `!!x` -> `x` if parent `SyntaxNode` in any boolean `Type Coercion` context
if parent_node_in_boolean_cast_context {
if let Some(result) = is_double_negation_ignore_parenthesis(&syntax) {
return Some(result);
};
// Convert `Boolean(x)` -> `x` if parent `SyntaxNode` in any boolean `Type Coercion` context
// Only if `Boolean` Call Expression have one `JsAnyExpression` argument
if let Some(expr) = JsCallExpression::cast(syntax.clone()) {
if expr.has_callee("Boolean") {
let arguments = expr.arguments().ok()?;
let len = arguments.args().len();
if len == 1 {
return arguments
.args()
.into_iter()
.next()?
.ok()
.map(|item| item.into_syntax())
.and_then(AnyJsExpression::cast)
.map(|expr| (expr, ExtraBooleanCastType::BooleanCall));
}
}
return None;
}
// Convert `new Boolean(x)` -> `x` if parent `SyntaxNode` in any boolean `Type Coercion` context
// Only if `Boolean` Call Expression have one `JsAnyExpression` argument
return JsNewExpression::cast(syntax).and_then(|expr| {
if expr.has_callee("Boolean") {
let arguments = expr.arguments()?;
let len = arguments.args().len();
if len == 1 {
return arguments
.args()
.into_iter()
.next()?
.ok()
.map(|item| item.into_syntax())
.and_then(AnyJsExpression::cast)
.map(|expr| (expr, ExtraBooleanCastType::BooleanCall));
}
}
None
});
}
None
}
fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
let (_, extra_boolean_cast_type) = state;
let (title, note) = match extra_boolean_cast_type {
ExtraBooleanCastType::DoubleNegation => ("Avoid redundant double-negation.", "It is not necessary to use double-negation when a value will already be coerced to a boolean."),
ExtraBooleanCastType::BooleanCall => ("Avoid redundant `Boolean` call", "It is not necessary to use `Boolean` call when a value will already be coerced to a boolean."),
};
Some(
RuleDiagnostic::new(
rule_category!(),
node.range(),
markup! {
{title}
},
)
.note(note),
)
}
fn action(ctx: &RuleContext<Self>, state: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
let (node_to_replace, extra_boolean_cast_type) = state;
let message = match extra_boolean_cast_type {
ExtraBooleanCastType::DoubleNegation => "Remove redundant double-negation",
ExtraBooleanCastType::BooleanCall => "Remove redundant `Boolean` call",
};
mutation.replace_node(node.clone(), node_to_replace.clone());
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { {message} }.to_owned(),
mutation,
})
}
}
/// Check if the SyntaxNode is a Double Negation. Including the edge case
/// ```js
/// !(!x)
/// ```
/// Return [Rule::State] `(JsAnyExpression, ExtraBooleanCastType)` if it is a DoubleNegation Expression
///
fn is_double_negation_ignore_parenthesis(
syntax: &rome_rowan::SyntaxNode<rome_js_syntax::JsLanguage>,
) -> Option<(AnyJsExpression, ExtraBooleanCastType)> {
if let Some(negation_expr) = is_negation(syntax) {
let argument = negation_expr.argument().ok()?;
match argument {
AnyJsExpression::JsUnaryExpression(expr)
if expr.operator().ok()? == JsUnaryOperator::LogicalNot =>
{
expr.argument()
.ok()
.map(|argument| (argument, ExtraBooleanCastType::DoubleNegation))
}
// Check edge case `!(!xxx)`
AnyJsExpression::JsParenthesizedExpression(expr) => {
expr.expression().ok().and_then(|expr| {
is_negation(expr.syntax()).and_then(|negation| {
Some((
negation.argument().ok()?,
ExtraBooleanCastType::DoubleNegation,
))
})
})
}
_ => None,
}
} else {
None
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/complexity/use_simplified_logic_expression.rs | crates/rome_js_analyze/src/analyzers/complexity/use_simplified_logic_expression.rs | use crate::JsRuleAction;
use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{
AnyJsExpression, AnyJsLiteralExpression, JsBooleanLiteralExpression, JsLogicalExpression,
JsUnaryExpression, JsUnaryOperator, T,
};
use rome_rowan::{AstNode, AstNodeExt, BatchMutationExt};
declare_rule! {
/// Discard redundant terms from logical expressions.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// const boolExp = true;
/// const r = true && boolExp;
/// ```
///
/// ```js,expect_diagnostic
/// const boolExp2 = true;
/// const r2 = boolExp || true;
/// ```
///
/// ```js,expect_diagnostic
/// const nonNullExp = 123;
/// const r3 = null ?? nonNullExp;
/// ```
///
/// ```js,expect_diagnostic
/// const boolExpr1 = true;
/// const boolExpr2 = false;
/// const r4 = !boolExpr1 || !boolExpr2;
/// ```
///
/// ### Valid
/// ```js
/// const boolExpr3 = true;
/// const boolExpr4 = false;
/// const r5 = !(boolExpr1 && boolExpr2);
/// const boolExpr5 = true;
/// const boolExpr6 = false;
/// ```
///
pub(crate) UseSimplifiedLogicExpression {
version: "0.7.0",
name: "useSimplifiedLogicExpression",
recommended: false,
}
}
impl Rule for UseSimplifiedLogicExpression {
type Query = Ast<JsLogicalExpression>;
/// First element of tuple is if the expression is simplified by [De Morgan's Law](https://en.wikipedia.org/wiki/De_Morgan%27s_laws) rule, the second element is the expression to replace.
type State = (bool, AnyJsExpression);
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let node = ctx.query();
let left = node.left().ok()?;
let right = node.right().ok()?;
match node.operator().ok()? {
rome_js_syntax::JsLogicalOperator::NullishCoalescing
if matches!(
left,
AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsNullLiteralExpression(_)
)
) =>
{
return Some((false, right));
}
rome_js_syntax::JsLogicalOperator::LogicalOr => {
if let AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsBooleanLiteralExpression(literal),
) = left
{
return simplify_or_expression(literal, right).map(|expr| (false, expr));
}
if let AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsBooleanLiteralExpression(literal),
) = right
{
return simplify_or_expression(literal, left).map(|expr| (false, expr));
}
if could_apply_de_morgan(node).unwrap_or(false) {
return simplify_de_morgan(node)
.map(|expr| (true, AnyJsExpression::JsUnaryExpression(expr)));
}
}
rome_js_syntax::JsLogicalOperator::LogicalAnd => {
if let AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsBooleanLiteralExpression(literal),
) = left
{
return simplify_and_expression(literal, right).map(|expr| (false, expr));
}
if let AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsBooleanLiteralExpression(literal),
) = right
{
return simplify_and_expression(literal, left).map(|expr| (false, expr));
}
if could_apply_de_morgan(node).unwrap_or(false) {
return simplify_de_morgan(node)
.map(|expr| (true, AnyJsExpression::JsUnaryExpression(expr)));
}
}
_ => return None,
}
None
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
node.range(),
markup! {
"Logical expression contains unnecessary complexity."
},
))
}
fn action(ctx: &RuleContext<Self>, state: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
let (is_simplified_by_de_morgan, expr) = state;
mutation.replace_node(
AnyJsExpression::JsLogicalExpression(node.clone()),
expr.clone(),
);
let message = if *is_simplified_by_de_morgan {
"Reduce the complexity of the logical expression."
} else {
"Discard redundant terms from the logical expression."
};
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { ""{message}"" }.to_owned(),
mutation,
})
}
}
/// https://en.wikipedia.org/wiki/De_Morgan%27s_laws
fn could_apply_de_morgan(node: &JsLogicalExpression) -> Option<bool> {
let left = node.left().ok()?;
let right = node.right().ok()?;
match (left, right) {
(AnyJsExpression::JsUnaryExpression(left), AnyJsExpression::JsUnaryExpression(right)) => {
Some(
matches!(left.operator().ok()?, JsUnaryOperator::LogicalNot)
&& matches!(right.operator().ok()?, JsUnaryOperator::LogicalNot)
&& !matches!(left.argument().ok()?, AnyJsExpression::JsUnaryExpression(_))
&& !matches!(
right.argument().ok()?,
AnyJsExpression::JsUnaryExpression(_)
),
)
}
_ => Some(false),
}
}
fn simplify_and_expression(
literal: JsBooleanLiteralExpression,
expression: AnyJsExpression,
) -> Option<AnyJsExpression> {
keep_expression_if_literal(literal, expression, true)
}
fn simplify_or_expression(
literal: JsBooleanLiteralExpression,
expression: AnyJsExpression,
) -> Option<AnyJsExpression> {
keep_expression_if_literal(literal, expression, false)
}
fn keep_expression_if_literal(
literal: JsBooleanLiteralExpression,
expression: AnyJsExpression,
expected_value: bool,
) -> Option<AnyJsExpression> {
let eval_value = match literal.value_token().ok()?.kind() {
T![true] => true,
T![false] => false,
_ => return None,
};
if eval_value == expected_value {
Some(expression)
} else {
Some(AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsBooleanLiteralExpression(literal),
))
}
}
fn simplify_de_morgan(node: &JsLogicalExpression) -> Option<JsUnaryExpression> {
let left = node.left().ok()?;
let right = node.right().ok()?;
let operator_token = node.operator_token().ok()?;
match (left, right) {
(AnyJsExpression::JsUnaryExpression(left), AnyJsExpression::JsUnaryExpression(right)) => {
let mut next_logic_expression = match operator_token.kind() {
T![||] => node
.clone()
.replace_token(operator_token, make::token(T![&&])),
T![&&] => node
.clone()
.replace_token(operator_token, make::token(T![||])),
_ => return None,
}?;
next_logic_expression = next_logic_expression.with_left(left.argument().ok()?);
next_logic_expression = next_logic_expression.with_right(right.argument().ok()?);
Some(make::js_unary_expression(
make::token(T![!]),
AnyJsExpression::JsParenthesizedExpression(make::js_parenthesized_expression(
make::token(T!['(']),
AnyJsExpression::JsLogicalExpression(next_logic_expression),
make::token(T![')']),
)),
))
}
_ => None,
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/complexity/no_useless_rename.rs | crates/rome_js_analyze/src/analyzers/complexity/no_useless_rename.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{
JsExportNamedFromSpecifier, JsExportNamedSpecifier, JsNamedImportSpecifier,
JsObjectBindingPatternProperty, JsSyntaxElement,
};
use rome_rowan::{declare_node_union, trim_leading_trivia_pieces, AstNode, BatchMutationExt};
use crate::JsRuleAction;
declare_rule! {
/// Disallow renaming import, export, and destructured assignments to the same name.
///
/// ES2015 allows for the renaming of references in import and export statements as well as destructuring assignments.
/// This gives programmers a concise syntax for performing these operations while renaming these references:
///
/// ```js
/// import { foo as bar } from "baz";
/// export { foo as bar };
/// let { foo: bar } = baz;
/// ```
///
/// With this syntax, it is possible to rename a reference to the same name.
/// This is a completely redundant operation, as this is the same as not renaming at all.
///
/// Source: https://eslint.org/docs/latest/rules/no-useless-rename
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// import { foo as foo } from "bar";
/// ```
///
/// ```js,expect_diagnostic
/// export { foo as foo };
/// ```
///
/// ```js,expect_diagnostic
/// let { foo: foo } = bar;
/// ```
///
/// ### Valid
///
/// ```js
/// import { foo as bar } from "baz";
/// ```
///
/// ```js
/// export { foo as bar };
/// ```
///
/// ```js
/// let { foo: bar } = baz;
/// ```
///
pub(crate) NoUselessRename {
version: "12.0.0",
name: "noUselessRename",
recommended: true,
}
}
declare_node_union! {
pub(crate) JsRenaming = JsExportNamedFromSpecifier | JsExportNamedSpecifier | JsNamedImportSpecifier | JsObjectBindingPatternProperty
}
impl Rule for NoUselessRename {
type Query = Ast<JsRenaming>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let renaming = ctx.query();
let (old_name, new_name) = match renaming {
JsRenaming::JsExportNamedFromSpecifier(x) => (
x.source_name().ok()?.value().ok()?,
x.export_as()?.exported_name().ok()?.value().ok()?,
),
JsRenaming::JsExportNamedSpecifier(x) => (
x.local_name().ok()?.value_token().ok()?,
x.exported_name().ok()?.value().ok()?,
),
JsRenaming::JsNamedImportSpecifier(x) => (
x.name().ok()?.value().ok()?,
x.local_name()
.ok()?
.as_js_identifier_binding()?
.name_token()
.ok()?,
),
JsRenaming::JsObjectBindingPatternProperty(x) => (
x.member().ok()?.as_js_literal_member_name()?.value().ok()?,
x.pattern()
.ok()?
.as_any_js_binding()?
.as_js_identifier_binding()?
.name_token()
.ok()?,
),
};
(old_name.text_trimmed() == new_name.text_trimmed()).then_some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let renaming = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
renaming.syntax().text_trimmed_range(),
markup! {
"Useless rename."
},
))
}
fn action(ctx: &RuleContext<Self>, _: &Self::State) -> Option<JsRuleAction> {
let renaming = ctx.query();
let mut mutation = ctx.root().begin();
match renaming {
JsRenaming::JsExportNamedFromSpecifier(x) => {
let last_token = x.source_name().ok()?.value().ok()?;
let export_as = x.export_as()?;
let export_as_last_token = export_as.exported_name().ok()?.value().ok()?;
let replacing_token = last_token.append_trivia_pieces(trim_leading_trivia_pieces(
export_as_last_token.trailing_trivia().pieces(),
));
mutation.remove_node(export_as);
mutation.replace_token_discard_trivia(last_token, replacing_token);
}
JsRenaming::JsExportNamedSpecifier(x) => {
let replacing =
make::js_export_named_shorthand_specifier(x.local_name().ok()?).build();
mutation.replace_element(
JsSyntaxElement::Node(x.syntax().clone()),
JsSyntaxElement::Node(replacing.syntax().clone()),
);
}
JsRenaming::JsNamedImportSpecifier(x) => {
let replacing =
make::js_shorthand_named_import_specifier(x.local_name().ok()?).build();
mutation.replace_element(
JsSyntaxElement::Node(x.syntax().clone()),
JsSyntaxElement::Node(replacing.syntax().clone()),
);
}
JsRenaming::JsObjectBindingPatternProperty(x) => {
let mut replacing_builder = make::js_object_binding_pattern_shorthand_property(
x.pattern().ok()?.as_any_js_binding()?.clone(),
);
if let Some(init) = x.init() {
replacing_builder = replacing_builder.with_init(init);
}
mutation.replace_element(
JsSyntaxElement::Node(x.syntax().clone()),
JsSyntaxElement::Node(replacing_builder.build().syntax().clone()),
);
}
}
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::Always,
message: markup! { "Remove the renaming." }.to_owned(),
mutation,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/complexity/no_useless_catch.rs | crates/rome_js_analyze/src/analyzers/complexity/no_useless_catch.rs | use rome_analyze::{context::RuleContext, declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::{JsCatchClause, TextRange};
use rome_rowan::{AstNode, AstNodeList};
declare_rule! {
/// Disallow unnecessary `catch` clauses.
///
/// A `catch` clause that only rethrows the original error is redundant,
/// and has no effect on the runtime behavior of the program.
/// These redundant clauses can be a source of confusion and code bloat,
/// so it’s better to disallow these unnecessary `catch` clauses.
///
/// Source: https://eslint.org/docs/latest/rules/no-useless-catch
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// try {
/// doSomething();
/// } catch(e) {
/// throw e;
/// }
/// ```
/// ```js,expect_diagnostic
/// try {
/// doSomething();
/// } catch(e) {
/// throw e;
/// } finally {
/// doCleanUp();
/// }
/// ```
/// ## Valid
///
/// ```js
/// try {
/// doSomething();
/// } catch(e) {
/// doSomethingWhenCatch();
/// throw e;
/// }
/// ```
///
/// ```js
/// try {
/// doSomething();
/// } catch(e) {
/// handleError(e);
/// }
/// ```
///
pub(crate) NoUselessCatch {
version: "12.0.0",
name: "noUselessCatch",
recommended: true,
}
}
impl Rule for NoUselessCatch {
type Query = Ast<JsCatchClause>;
type State = TextRange;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let binding = ctx.query();
let catch_body = binding.body().ok()?;
let body_statements = catch_body.statements();
// We need guarantees that body_statements has only one `throw` statement.
if body_statements.len() != 1 {
return None;
}
let catch_declaration = binding.declaration()?;
let catch_binding_err = catch_declaration
.binding()
.ok()?
.as_any_js_binding()?
.as_js_identifier_binding()?
.name_token()
.ok()?;
let catch_err_name = catch_binding_err.text();
let first_statement = body_statements.first()?;
let js_throw_statement = first_statement.as_js_throw_statement()?;
let throw_ident = js_throw_statement
.argument()
.ok()?
.as_js_identifier_expression()?
.text();
if throw_ident.eq(catch_err_name) {
Some(js_throw_statement.syntax().text_trimmed_range())
} else {
None
}
}
fn diagnostic(_: &RuleContext<Self>, text_range: &Self::State) -> Option<RuleDiagnostic> {
Some(
RuleDiagnostic::new(
rule_category!(),
text_range,
markup!("The "<Emphasis>"catch"</Emphasis>" clause that only rethrows the original error is redundant."),
)
.note(markup!(
"These unnecessary "<Emphasis>"catch"</Emphasis>" clauses can be confusing. It is recommended to remove them."
)),
)
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/complexity/use_literal_keys.rs | crates/rome_js_analyze/src/analyzers/complexity/use_literal_keys.rs | use crate::JsRuleAction;
use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make::{
self, ident, js_literal_member_name, js_name, js_static_member_expression, token,
};
use rome_js_syntax::{
AnyJsComputedMember, AnyJsExpression, AnyJsLiteralExpression, AnyJsName, JsComputedMemberName,
JsLiteralMemberName, JsSyntaxKind, T,
};
use rome_js_unicode_table::is_js_ident;
use rome_rowan::{declare_node_union, AstNode, BatchMutationExt, TextRange};
declare_rule! {
/// Enforce the usage of a literal access to properties over computed property access.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// a.b["c"];
/// ```
///
/// ```js,expect_diagnostic
/// a.c[`d`]
/// ```
///
/// ```js,expect_diagnostic
/// a.c[`d`] = "something"
/// ```
///
/// ```js,expect_diagnostic
/// a = {
/// ['b']: d
/// }
/// ```
///
/// ## Valid
///
/// ```js
/// a["c" + "d"];
/// a[d.c];
/// ```
///
pub(crate) UseLiteralKeys {
version: "12.1.0",
name: "useLiteralKeys",
recommended: true,
}
}
impl Rule for UseLiteralKeys {
type Query = Ast<AnyJsMember>;
type State = (TextRange, String);
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();
let inner_expression = match node {
AnyJsMember::AnyJsComputedMember(computed_member) => computed_member.member().ok()?,
AnyJsMember::JsLiteralMemberName(member) => {
if member.value().ok()?.kind() == JsSyntaxKind::JS_STRING_LITERAL {
let name = member.name().ok()?;
if is_js_ident(&name) {
return Some((member.range(), name.to_string()));
}
}
return None;
}
AnyJsMember::JsComputedMemberName(member) => member.expression().ok()?,
};
match inner_expression {
AnyJsExpression::AnyJsLiteralExpression(
AnyJsLiteralExpression::JsStringLiteralExpression(string_literal),
) => {
let value = string_literal.inner_string_text().ok()?;
// A computed property `["something"]` can always be simplified to a string literal "something".
if matches!(node, AnyJsMember::JsComputedMemberName(_)) || is_js_ident(&value) {
return Some((string_literal.range(), value.to_string()));
}
}
AnyJsExpression::JsTemplateExpression(template_expression) => {
let mut value = String::new();
for element in template_expression.elements() {
let chunk = element.as_js_template_chunk_element()?;
value.push_str(chunk.template_chunk_token().ok()?.text_trimmed());
}
// A computed property ``[`something`]`` can always be simplified to a string literal "something".
if matches!(node, AnyJsMember::JsComputedMemberName(_)) || is_js_ident(&value) {
return Some((template_expression.range(), value));
}
}
_ => {}
}
None
}
fn diagnostic(_ctx: &RuleContext<Self>, (range, _): &Self::State) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
range,
markup! {
"The computed expression can be simplified without the use of a string literal."
},
))
}
fn action(ctx: &RuleContext<Self>, (_, identifier): &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
match node {
AnyJsMember::AnyJsComputedMember(node) => {
let object = node.object().ok()?;
let member = js_name(ident(identifier));
let static_expression =
js_static_member_expression(object, token(T![.]), AnyJsName::JsName(member));
mutation.replace_element(
node.clone().into_syntax().into(),
static_expression.into_syntax().into(),
);
}
AnyJsMember::JsLiteralMemberName(node) => {
mutation.replace_token(node.value().ok()?, make::ident(identifier));
}
AnyJsMember::JsComputedMemberName(member) => {
let name_token = if is_js_ident(identifier) {
make::ident(identifier)
} else {
make::js_string_literal(identifier)
};
let literal_member_name = js_literal_member_name(name_token);
mutation.replace_element(
member.clone().into_syntax().into(),
literal_member_name.into_syntax().into(),
);
}
}
Some(JsRuleAction {
mutation,
applicability: Applicability::MaybeIncorrect,
category: ActionCategory::QuickFix,
message: markup! {
"Use a literal key instead."
}
.to_owned(),
})
}
}
declare_node_union! {
pub(crate) AnyJsMember = AnyJsComputedMember | JsLiteralMemberName | JsComputedMemberName
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/complexity/no_multiple_spaces_in_regular_expression_literals.rs | crates/rome_js_analyze/src/analyzers/complexity/no_multiple_spaces_in_regular_expression_literals.rs | use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_syntax::{JsRegexLiteralExpression, JsSyntaxKind, JsSyntaxToken, TextRange, TextSize};
use rome_rowan::BatchMutationExt;
use std::fmt::Write;
use crate::JsRuleAction;
declare_rule! {
/// Disallow unclear usage of multiple space characters in regular expression literals
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// / /
/// ```
///
/// ```js,expect_diagnostic
/// / foo/
/// ```
///
/// ```js,expect_diagnostic
/// /foo /
/// ```
///
/// ```js,expect_diagnostic
/// /foo bar/
/// ```
///
/// ```js,expect_diagnostic
/// /foo bar baz/
/// ```
///
/// ```js,expect_diagnostic
/// /foo [ba]r b(a|z)/
/// ```
///
/// ### Valid
///
/// ```js
/// /foo {2}bar/
///```
///
/// ```js
/// /foo bar baz/
///```
///
/// ```js
/// /foo bar baz/
///```
///
/// ```js
/// /foo /
///```
pub(crate) NoMultipleSpacesInRegularExpressionLiterals {
version: "0.7.0",
name: "noMultipleSpacesInRegularExpressionLiterals",
recommended: true,
}
}
impl Rule for NoMultipleSpacesInRegularExpressionLiterals {
type Query = Ast<JsRegexLiteralExpression>;
type State = Vec<(usize, usize)>;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let value_token = ctx.query().value_token().ok()?;
let trimmed_text = value_token.text_trimmed();
let mut range_list = vec![];
let mut continue_white_space = false;
let mut last_white_index = 0;
for (i, ch) in trimmed_text.chars().enumerate() {
if ch == ' ' {
if !continue_white_space {
continue_white_space = true;
last_white_index = i;
} else {
}
} else if continue_white_space {
if i - last_white_index > 1 {
range_list.push((last_white_index, i));
}
continue_white_space = false;
}
}
if !range_list.is_empty() {
Some(range_list)
} else {
None
}
}
fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let value_token = ctx.query().value_token().ok()?;
let value_token_range = value_token.text_trimmed_range();
// SAFETY: We know diagnostic will be sended only if the `range_list` is not empty
// first and last continuous whitespace range of `range_list`
let (first_start, _) = state[0];
let (_, last_end) = state[state.len() - 1];
Some(RuleDiagnostic::new(
rule_category!(),
TextRange::new(
value_token_range.start() + TextSize::from(first_start as u32),
value_token_range.start() + TextSize::from(last_end as u32),
),
markup! {
"This regular expression contains unclear uses of multiple spaces."
},
))
}
fn action(ctx: &RuleContext<Self>, state: &Self::State) -> Option<JsRuleAction> {
let mut mutation = ctx.root().begin();
let trimmed_token = ctx.query().value_token().ok()?;
let trimmed_token_string = trimmed_token.text_trimmed();
let mut normalized_string_token = String::new();
let mut previous_start = 0;
let mut eg_length = 0;
for (start, end) in state.iter() {
normalized_string_token += &trimmed_token_string[previous_start..*start];
write!(normalized_string_token, " {{{}}}", *end - *start).unwrap();
previous_start = *end;
eg_length += *end - *start;
}
normalized_string_token += &trimmed_token_string[previous_start..];
let next_trimmed_token = JsSyntaxToken::new_detached(
JsSyntaxKind::JS_REGEX_LITERAL,
&normalized_string_token,
[],
[],
);
mutation.replace_token(trimmed_token, next_trimmed_token);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "It's hard to visually count the amount of spaces, it's clearer if you use a quantifier instead. eg / {"{eg_length}"}/" }.to_owned(),
mutation,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/complexity/no_with.rs | crates/rome_js_analyze/src/analyzers/complexity/no_with.rs | use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_js_syntax::JsWithStatement;
use rome_rowan::AstNode;
declare_rule! {
/// Disallow `with` statements in non-strict contexts.
///
/// The `with` statement is potentially problematic because it adds members of an object to the current
/// scope, making it impossible to tell what a variable inside the block actually refers to.
///
/// ## Examples
///
/// ### Invalid
///
/// ```cjs,expect_diagnostic
/// function f() {
/// with (point) {
/// r = Math.sqrt(x * x + y * y); // is r a member of point?
/// }
/// }
/// ```
pub(crate) NoWith {
version: "12.0.0",
name: "noWith",
recommended: true,
}
}
impl Rule for NoWith {
type Query = Ast<JsWithStatement>;
type State = ();
type Signals = Option<Self::State>;
type Options = ();
fn run(_ctx: &RuleContext<Self>) -> Option<Self::State> {
Some(())
}
fn diagnostic(ctx: &RuleContext<Self>, _: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
node.range(),
markup! {
"Unexpected use of "<Emphasis>"with"</Emphasis>" statement."
},
).note(
"The with statement is potentially problematic because it adds members of an object to the current\nscope, making it impossible to tell what a variable inside the block actually refers to."
))
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/complexity/use_flat_map.rs | crates/rome_js_analyze/src/analyzers/complexity/use_flat_map.rs | use crate::JsRuleAction;
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make::{ident, js_name};
use rome_js_syntax::{AnyJsExpression, AnyJsMemberExpression, AnyJsName, JsCallExpression};
use rome_rowan::{AstNode, AstSeparatedList, BatchMutationExt};
declare_rule! {
/// Promotes the use of `.flatMap()` when `map().flat()` are used together.
///
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// const array = ["split", "the text", "into words"];
/// array.map(sentence => sentence.split(' ')).flat();
/// ```
///
/// ```js,expect_diagnostic
/// const array = ["split", "the text", "into words"];
/// array.map(sentence => sentence.split(' ')).flat(1);
/// ```
///
/// ### Valid
///
/// ```js
/// const array = ["split", "the text", "into words"];
/// array.map(sentence => sentence.split(' ')).flat(2);
/// ```
///
pub(crate) UseFlatMap {
version: "10.0.0",
name: "useFlatMap",
recommended: true,
}
}
impl Rule for UseFlatMap {
type Query = Ast<JsCallExpression>;
type State = JsCallExpression;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let flat_call = ctx.query();
let arguments = flat_call.arguments().ok()?.args();
// Probably not a `flat` call.
if arguments.len() > 1 {
return None;
}
if let Some(first_argument) = arguments.first() {
let first_argument = first_argument.ok()?;
let first_argument = first_argument
.as_any_js_expression()?
.as_any_js_literal_expression()?
.as_js_number_literal_expression()?;
if first_argument.value_token().ok()?.text_trimmed() != "1" {
return None;
}
}
let flat_member_expression =
AnyJsMemberExpression::cast_ref(flat_call.callee().ok()?.syntax())?;
if flat_member_expression.member_name()?.text() == "flat" {
let object = flat_member_expression.object().ok()?;
let map_call = object.as_js_call_expression()?;
let map_call_arguments = map_call.arguments().ok()?.args();
let map_member_expression =
AnyJsMemberExpression::cast_ref(map_call.callee().ok()?.syntax())?;
if map_member_expression.member_name()?.text() == "map" && map_call_arguments.len() == 1
{
return Some(map_call.clone());
}
}
None
}
fn diagnostic(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<RuleDiagnostic> {
let node = ctx.query();
Some(RuleDiagnostic::new(
rule_category!(),
node.syntax().text_trimmed_range(),
markup! {
"The call chain "<Emphasis>".map().flat()"</Emphasis>" can be replaced with a single "<Emphasis>".flatMap()"</Emphasis>" call."
},
))
}
fn action(ctx: &RuleContext<Self>, flat_call: &Self::State) -> Option<JsRuleAction> {
let node = ctx.query();
let mut mutation = ctx.root().begin();
let flat_call = flat_call.clone();
let old_static_member_expression = flat_call.callee().ok()?;
let old_static_member_expression =
old_static_member_expression.as_js_static_member_expression()?;
let member = js_name(ident("flatMap"));
let flat_map_member_expression = old_static_member_expression
.clone()
.with_member(AnyJsName::JsName(member));
let flat_map_call = flat_call.with_callee(AnyJsExpression::JsStaticMemberExpression(
flat_map_member_expression,
));
mutation.replace_node(node.clone(), flat_map_call);
Some(JsRuleAction {
mutation,
message: markup! {"Replace the chain with "<Emphasis>".flatMap()"</Emphasis>"."}
.to_owned(),
category: ActionCategory::QuickFix,
applicability: Applicability::Always,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/complexity/use_simple_number_keys.rs | crates/rome_js_analyze/src/analyzers/complexity/use_simple_number_keys.rs | use crate::JsRuleAction;
use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{
AnyJsObjectMember, JsLiteralMemberName, JsObjectExpression, JsSyntaxKind, TextRange,
};
use rome_rowan::{AstNode, BatchMutationExt};
use std::str::FromStr;
declare_rule! {
/// Disallow number literal object member names which are not base10 or uses underscore as separator
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// ({ 0x1: 1 });
/// ```
/// ```js,expect_diagnostic
/// ({ 11_1.11: "ee" });
/// ```
/// ```js,expect_diagnostic
/// ({ 0o1: 1 });
/// ```
/// ```js,expect_diagnostic
/// ({ 1n: 1 });
/// ```
/// ```js,expect_diagnostic
/// ({ 11_1.11: "ee" });
/// ```
///
/// ## Valid
///
/// ```js
/// ({ 0: "zero" });
/// ({ 122: "integer" });
/// ({ 1.22: "floating point" });
/// ({ 3.1e12: "floating point with e" });
/// ```
///
pub(crate) UseSimpleNumberKeys {
version: "12.1.0",
name: "useSimpleNumberKeys",
recommended: false,
}
}
#[derive(Clone)]
pub enum NumberLiteral {
Binary {
node: JsLiteralMemberName,
value: String,
big_int: bool,
},
Decimal {
node: JsLiteralMemberName,
value: String,
big_int: bool,
underscore: bool,
},
Octal {
node: JsLiteralMemberName,
value: String,
big_int: bool,
},
Hexadecimal {
node: JsLiteralMemberName,
value: String,
big_int: bool,
},
FloatingPoint {
node: JsLiteralMemberName,
value: String,
exponent: bool,
underscore: bool,
},
}
pub struct NumberLiteralError;
impl TryFrom<AnyJsObjectMember> for NumberLiteral {
type Error = NumberLiteralError;
fn try_from(any_member: AnyJsObjectMember) -> Result<Self, Self::Error> {
let Some(literal_member_name_syntax) = any_member
.syntax()
.children()
.find(|x| JsLiteralMemberName::can_cast(x.kind())) else {
return Err(NumberLiteralError)
};
let literal_member_name = JsLiteralMemberName::cast(literal_member_name_syntax).unwrap();
let token = literal_member_name.value().unwrap();
match token.kind() {
JsSyntaxKind::JS_NUMBER_LITERAL | JsSyntaxKind::JS_BIGINT_LITERAL => {
let chars: Vec<char> = token.to_string().chars().collect();
let mut value = String::new();
let mut is_first_char_zero: bool = false;
let mut is_second_char_a_letter: Option<char> = None;
let mut contains_dot: bool = false;
let mut exponent: bool = false;
let mut largest_digit: char = '0';
let mut underscore: bool = false;
let mut big_int: bool = false;
for i in 0..chars.len() {
if i == 0 && chars[i] == '0' && chars.len() > 1 {
is_first_char_zero = true;
continue;
}
if chars[i] == 'n' {
big_int = true;
break;
}
if chars[i] == 'e' || chars[i] == 'E' {
exponent = true;
}
if i == 1 && chars[i].is_alphabetic() && !exponent {
is_second_char_a_letter = Some(chars[i]);
continue;
}
if chars[i] == '_' {
underscore = true;
continue;
}
if chars[i] == '.' {
contains_dot = true;
}
if largest_digit < chars[i] {
largest_digit = chars[i];
}
value.push(chars[i])
}
if contains_dot {
return Ok(Self::FloatingPoint {
node: literal_member_name,
value,
exponent,
underscore,
});
};
if !is_first_char_zero {
return Ok(Self::Decimal {
node: literal_member_name,
value,
big_int,
underscore,
});
};
match is_second_char_a_letter {
Some('b' | 'B') => {
return Ok(Self::Binary {
node: literal_member_name,
value,
big_int,
})
}
Some('o' | 'O') => {
return Ok(Self::Octal {
node: literal_member_name,
value,
big_int,
})
}
Some('x' | 'X') => {
return Ok(Self::Hexadecimal {
node: literal_member_name,
value,
big_int,
})
}
_ => (),
}
if largest_digit < '8' {
return Ok(Self::Octal {
node: literal_member_name,
value,
big_int,
});
}
Ok(Self::Decimal {
node: literal_member_name,
value,
big_int,
underscore,
})
}
_ => Err(NumberLiteralError),
}
}
}
impl NumberLiteral {
fn node(&self) -> JsLiteralMemberName {
match self {
Self::Decimal { node, .. } => node.clone(),
Self::Binary { node, .. } => node.clone(),
Self::FloatingPoint { node, .. } => node.clone(),
Self::Octal { node, .. } => node.clone(),
Self::Hexadecimal { node, .. } => node.clone(),
}
}
fn range(&self) -> TextRange {
match self {
Self::Decimal { node, .. } => node.range(),
Self::Binary { node, .. } => node.range(),
Self::FloatingPoint { node, .. } => node.range(),
Self::Octal { node, .. } => node.range(),
Self::Hexadecimal { node, .. } => node.range(),
}
}
fn value(&self) -> &String {
match self {
Self::Decimal { value, .. } => value,
Self::Binary { value, .. } => value,
Self::FloatingPoint { value, .. } => value,
Self::Octal { value, .. } => value,
Self::Hexadecimal { value, .. } => value,
}
}
}
impl NumberLiteral {
fn to_base_ten(&self) -> Option<f64> {
match self {
Self::Binary { value, .. } => i64::from_str_radix(value, 2).map(|num| num as f64).ok(),
Self::Decimal { value, .. } | Self::FloatingPoint { value, .. } => {
f64::from_str(value).ok()
}
Self::Octal { value, .. } => i64::from_str_radix(value, 7).map(|num| num as f64).ok(),
Self::Hexadecimal { value, .. } => {
i64::from_str_radix(value, 16).map(|num| num as f64).ok()
}
}
}
}
enum WrongNumberLiteralName {
Binary,
Hexadecimal,
Octal,
BigInt,
WithUnderscore,
}
pub struct RuleState(WrongNumberLiteralName, NumberLiteral);
impl Rule for UseSimpleNumberKeys {
type Query = Ast<JsObjectExpression>;
type State = RuleState;
type Signals = Vec<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let mut signals: Self::Signals = Vec::new();
let node = ctx.query();
for number_literal in node
.members()
.into_iter()
.flatten()
.filter_map(|member| NumberLiteral::try_from(member).ok())
{
match number_literal {
NumberLiteral::Decimal { big_int: true, .. } => {
signals.push(RuleState(WrongNumberLiteralName::BigInt, number_literal))
}
NumberLiteral::FloatingPoint {
underscore: true, ..
}
| NumberLiteral::Decimal {
underscore: true, ..
} => signals.push(RuleState(
WrongNumberLiteralName::WithUnderscore,
number_literal,
)),
NumberLiteral::Binary { .. } => {
signals.push(RuleState(WrongNumberLiteralName::Binary, number_literal))
}
NumberLiteral::Hexadecimal { .. } => signals.push(RuleState(
WrongNumberLiteralName::Hexadecimal,
number_literal,
)),
NumberLiteral::Octal { .. } => {
signals.push(RuleState(WrongNumberLiteralName::Octal, number_literal))
}
_ => (),
}
}
signals
}
fn diagnostic(
_ctx: &RuleContext<Self>,
RuleState(reason, literal): &Self::State,
) -> Option<RuleDiagnostic> {
let title = match reason {
WrongNumberLiteralName::BigInt => "Bigint is not allowed here.",
WrongNumberLiteralName::WithUnderscore => {
"Number literal with underscore is not allowed here."
}
WrongNumberLiteralName::Binary => "Binary number literal in is not allowed here.",
WrongNumberLiteralName::Hexadecimal => {
"Hexadecimal number literal is not allowed here."
}
WrongNumberLiteralName::Octal => "Octal number literal is not allowed here.",
};
let diagnostic = RuleDiagnostic::new(rule_category!(), literal.range(), title.to_string());
Some(diagnostic)
}
fn action(
ctx: &RuleContext<Self>,
RuleState(reason, literal): &Self::State,
) -> Option<JsRuleAction> {
let mut mutation = ctx.root().begin();
let node = literal.node();
let token = node.value().ok()?;
let message = match reason {
WrongNumberLiteralName::Binary
| WrongNumberLiteralName::Octal
| WrongNumberLiteralName::Hexadecimal => {
let text = literal.to_base_ten()?;
mutation.replace_token(token, make::js_number_literal(text));
markup! ("Replace "{ node.to_string() } " with "{text.to_string()}).to_owned()
}
WrongNumberLiteralName::WithUnderscore | WrongNumberLiteralName::BigInt => {
let text = literal.value();
mutation.replace_token(token, make::js_number_literal(text));
markup! ("Replace "{ node.to_string() } " with "{text}).to_owned()
}
};
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::Always,
message,
mutation,
})
}
}
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | false |
rome/tools | https://github.com/rome/tools/blob/392d188a49d70e495f13b1bb08cd7d9c43690f9b/crates/rome_js_analyze/src/analyzers/complexity/use_optional_chain.rs | crates/rome_js_analyze/src/analyzers/complexity/use_optional_chain.rs | use rome_analyze::{context::RuleContext, declare_rule, ActionCategory, Ast, Rule, RuleDiagnostic};
use rome_console::markup;
use rome_diagnostics::Applicability;
use rome_js_factory::make;
use rome_js_syntax::{
AnyJsExpression, AnyJsMemberExpression, AnyJsName, JsLogicalExpression, JsLogicalOperator,
OperatorPrecedence, T,
};
use rome_rowan::{AstNode, AstNodeExt, BatchMutationExt, SyntaxResult};
use std::cmp::Ordering;
use std::collections::VecDeque;
use std::iter;
use crate::JsRuleAction;
declare_rule! {
/// Enforce using concise optional chain instead of chained logical expressions.
///
/// TypeScript 3.7 added support for the optional chain operator.
/// This operator allows you to safely access properties and methods on objects when they are potentially `null` or `undefined`.
/// The optional chain operator only chains when the property value is `null` or `undefined`.
/// It is much safer than relying upon logical operator chaining; which chains on any truthy value.
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// foo && foo.bar && foo.bar.baz && foo.bar.baz.buzz
/// ```
///
/// ```js,expect_diagnostic
/// foo.bar && foo.bar.baz.buzz
/// ```
///
/// ```js,expect_diagnostic
/// foo !== undefined && foo.bar != undefined && foo.bar.baz !== null && foo.bar.baz.buzz
/// ```
///
/// ```js,expect_diagnostic
/// ((foo || {}).bar || {}).baz;
/// ```
///
/// ```js,expect_diagnostic
/// (await (foo1 || {}).foo2 || {}).foo3;
/// ```
///
/// ```ts,expect_diagnostic
/// (((typeof x) as string) || {}).bar;
/// ```
///
/// ### Valid
///
/// ```js
/// foo && bar;
///```
/// ```js
/// foo || {};
///```
///
/// ```js
/// (foo = 2 || {}).bar;
///```
///
/// ```js
/// foo || foo.bar;
///```
///
/// ```js
/// foo["some long"] && foo["some long string"].baz
///```
///
pub(crate) UseOptionalChain {
version: "0.10.0",
name: "useOptionalChain",
recommended: true,
}
}
pub(crate) enum UseOptionalChainState {
LogicalAnd(VecDeque<AnyJsExpression>),
LogicalOrLike(LogicalOrLikeChain),
}
impl Rule for UseOptionalChain {
type Query = Ast<JsLogicalExpression>;
type State = UseOptionalChainState;
type Signals = Option<Self::State>;
type Options = ();
fn run(ctx: &RuleContext<Self>) -> Option<Self::State> {
let logical = ctx.query();
let operator = logical.operator().ok()?;
match operator {
JsLogicalOperator::LogicalAnd => {
let head = logical.right().ok()?;
let chain = LogicalAndChain::from_expression(head).ok()?;
if chain.is_inside_another_chain().ok()? {
return None;
}
let optional_chain_expression_nodes = chain.optional_chain_expression_nodes()?;
Some(UseOptionalChainState::LogicalAnd(
optional_chain_expression_nodes,
))
}
JsLogicalOperator::NullishCoalescing | JsLogicalOperator::LogicalOr => {
let chain = LogicalOrLikeChain::from_expression(logical)?;
if chain.is_inside_another_chain() {
return None;
}
Some(UseOptionalChainState::LogicalOrLike(chain))
}
}
}
fn diagnostic(ctx: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
let range = match state {
UseOptionalChainState::LogicalAnd(_) => ctx.query().range(),
UseOptionalChainState::LogicalOrLike(state) => state.member.range(),
};
Some(RuleDiagnostic::new(
rule_category!(),
range,
markup! {
"Change to an optional chain."
}
.to_owned(),
))
}
fn action(ctx: &RuleContext<Self>, state: &Self::State) -> Option<JsRuleAction> {
match state {
UseOptionalChainState::LogicalAnd(optional_chain_expression_nodes) => {
let mut prev_expression = None;
for expression in optional_chain_expression_nodes {
let next_expression = prev_expression
.take()
.and_then(|(prev_expression, new_expression)| {
expression
.clone()
.replace_node(prev_expression, new_expression)
})
.unwrap_or_else(|| expression.clone());
let next_expression = match next_expression {
AnyJsExpression::JsCallExpression(call_expression) => {
let optional_chain_token = call_expression
.optional_chain_token()
.unwrap_or_else(|| make::token(T![?.]));
call_expression
.with_optional_chain_token(Some(optional_chain_token))
.into()
}
AnyJsExpression::JsStaticMemberExpression(member_expression) => {
let operator = member_expression.operator_token().ok()?;
AnyJsExpression::from(make::js_static_member_expression(
member_expression.object().ok()?,
make::token(T![?.])
.with_leading_trivia_pieces(operator.leading_trivia().pieces())
.with_trailing_trivia_pieces(
operator.trailing_trivia().pieces(),
),
member_expression.member().ok()?,
))
}
AnyJsExpression::JsComputedMemberExpression(member_expression) => {
let optional_chain_token = member_expression
.optional_chain_token()
.unwrap_or_else(|| make::token(T![?.]));
member_expression
.with_optional_chain_token(Some(optional_chain_token))
.into()
}
_ => return None,
};
prev_expression = Some((expression.clone(), next_expression));
}
let (prev_expression, new_expression) = prev_expression?;
let logical = ctx.query();
let next_right = logical
.right()
.ok()?
.replace_node(prev_expression, new_expression.clone())
.unwrap_or(new_expression);
let mut mutation = ctx.root().begin();
mutation.replace_node(AnyJsExpression::from(logical.clone()), next_right);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Change to an optional chain." }.to_owned(),
mutation,
})
}
UseOptionalChainState::LogicalOrLike(chain) => {
let chain = chain.optional_chain_expression_nodes();
let mut prev_chain: Option<(AnyJsMemberExpression, AnyJsMemberExpression)> = None;
for (mut left, member) in chain {
if let Some((prev_member, next_member)) = prev_chain.take() {
left = left
.replace_node(prev_member, next_member.clone())
.unwrap_or_else(|| next_member.into());
}
left = trim_trailing_space(left)?;
let need_parenthesis =
left.precedence().ok()? < OperatorPrecedence::LeftHandSide;
if need_parenthesis {
left = make::js_parenthesized_expression(
make::token(T!['(']),
left,
make::token(T![')']),
)
.into();
}
let next_member = match member.clone() {
AnyJsMemberExpression::JsStaticMemberExpression(expression) => {
let static_member_expression = make::js_static_member_expression(
left,
make::token(T![?.]),
expression.member().ok()?,
);
AnyJsMemberExpression::from(static_member_expression)
}
AnyJsMemberExpression::JsComputedMemberExpression(expression) => {
let computed_member_expression = make::js_computed_member_expression(
left,
expression.l_brack_token().ok()?,
expression.member().ok()?,
expression.r_brack_token().ok()?,
)
.with_optional_chain_token(make::token(T![?.]))
.build();
computed_member_expression.into()
}
};
prev_chain = Some((member, next_member));
}
let (prev_member, new_member) = prev_chain?;
let mut mutation = ctx.root().begin();
mutation.replace_node(prev_member, new_member);
Some(JsRuleAction {
category: ActionCategory::QuickFix,
applicability: Applicability::MaybeIncorrect,
message: markup! { "Change to an optional chain." }.to_owned(),
mutation,
})
}
}
}
}
/// Normalize optional chain like.
/// E.g. `foo != null` is normalized to `foo`
fn normalized_optional_chain_like(expression: AnyJsExpression) -> SyntaxResult<AnyJsExpression> {
if let AnyJsExpression::JsBinaryExpression(expression) = &expression {
if expression.is_optional_chain_like()? {
return expression.left();
}
}
Ok(expression)
}
/// `LogicalAndChainOrdering` is the result of a comparison between two logical and chain.
enum LogicalAndChainOrdering {
/// An ordering where a chain is a sub-chain of another.
/// ```js
/// (foo && foo.bar) /* is sub-chain of */ (foo && foo.bar && foo.bar.baz)
/// ```
SubChain,
/// An ordering where a chain is equal to another.
/// ```js
/// (foo && foo.bar) /* is equal */ (foo && foo.bar)
/// ```
Equal,
/// An ordering where a chain is different to another.
/// ```js
/// (foo && foo.bar) /* is different */ (bar && bar.bar && bar.bar.baz)
/// ```
Different,
}
/// `LogicalAndChain` handles cases with `JsLogicalExpression` which has `JsLogicalOperator::LogicalAnd` operator:
/// ```js
/// foo && foo.bar && foo.bar.baz && foo.bar.baz.buzz;
///
/// foo.bar && foo.bar.baz && foo.bar.baz.buzz;
///
/// foo !== undefined && foo.bar;
/// ```
/// The main idea of the `LogicalAndChain`:
/// 1. Check that the current chain isn't in another `LogicalAndChain`. We need to find the topmost logical expression which will be the head of the first current chain.
/// 2. Go down thought logical expressions and collect other chains and compare them with the current one.
/// 3. If a chain is a sub-chain of the current chain, we assign that sub-chain to new current one. Difference between current chain and sub-chain is a tail.
/// 4. Save the first tail `JsAnyExpression` to the buffer.
/// 5. Transform every `JsAnyExpression` from the buffer to optional expression.
///
/// E.g. `foo && foo.bar.baz && foo.bar.baz.zoo;`.
/// The logical expression `foo && foo.bar.baz` isn't the topmost. We skip it.
/// `foo && foo.bar.baz && foo.bar.baz.zoo;` is the topmost and it'll be a start point.
/// We start collecting a chain. We collect `JsAnyExpression` but for clarity let's use string identifiers.
/// `foo.bar.baz.zoo;` -> `[foo, bar, baz, zoo]`
/// Next step we take a next chain and also collect it.
/// `foo.bar.baz` -> `[foo, bar, baz]`
/// By comparing them we understand that one is a sub-chain of the other. `[foo, bar, baz]` is new current chain. `[zoo]` is a tail.
/// We save `zoo` expression to the buffer.
/// Next step we take a next chain and also collect it.
/// `foo` -> `[foo]`
/// By comparing them we understand that one is a sub-chain of the other. `[foo]` is new current chain. `[bar, baz]` is a tail.
/// We save `bar` expression to the buffer.
/// Iterate buffer `[bar, zoo]` we need to make every `JsAnyExpression` optional: `foo?.bar.baz?.zoo;`
///
#[derive(Debug)]
pub(crate) struct LogicalAndChain {
head: AnyJsExpression,
/// The buffer of `JsAnyExpression` which need to make optional chain.
buf: VecDeque<AnyJsExpression>,
}
impl LogicalAndChain {
fn from_expression(head: AnyJsExpression) -> SyntaxResult<LogicalAndChain> {
/// Iterate over `JsAnyExpression` and collect every expression which is a part of the chain:
/// ```js
/// foo.bar[baz];
/// ```
/// `[JsReferenceIdentifier, JsStaticMemberExpression, JsComputedMemberExpression]`
fn collect_chain(expression: AnyJsExpression) -> SyntaxResult<VecDeque<AnyJsExpression>> {
let mut buf = VecDeque::new();
let mut current_expression = Some(expression);
while let Some(expression) = current_expression.take() {
current_expression = match &expression {
AnyJsExpression::JsStaticMemberExpression(member_expression) => {
let object = member_expression.object()?;
buf.push_front(expression);
Some(object)
}
AnyJsExpression::JsComputedMemberExpression(member_expression) => {
let object = member_expression.object()?;
buf.push_front(expression);
Some(object)
}
AnyJsExpression::JsCallExpression(call_expression) => {
let callee = call_expression.callee()?;
buf.push_front(expression);
Some(callee)
}
AnyJsExpression::JsIdentifierExpression(_) => {
buf.push_front(expression);
return Ok(buf);
}
_ => return Ok(buf),
};
}
Ok(buf)
}
let buf = collect_chain(head.clone())?;
Ok(LogicalAndChain { head, buf })
}
/// This function checks if `LogicalAndChain` is inside another parent `LogicalAndChain`
/// and the chain is sub-chain of parent chain.
fn is_inside_another_chain(&self) -> SyntaxResult<bool> {
// Because head of the chain is right expression of logical expression we need to take a parent and a grand-parent.
// E.g. `foo && foo.bar && foo.bar.baz`
// The head of the sub-chain is `foo.bar`.
// The parent of the head is logical expression `foo && foo.bar`
// The grand-parent of the head is logical expression `foo && foo.bar && foo.bar.baz`
if let Some(parent) = self.head.parent::<JsLogicalExpression>() {
if let Some(grand_parent) = parent.parent::<JsLogicalExpression>() {
let grand_parent_operator = grand_parent.operator()?;
if !matches!(grand_parent_operator, JsLogicalOperator::LogicalAnd) {
return Ok(false);
}
let grand_parent_logical_left = grand_parent.left()?;
// Here we check that we came from the left side of the logical expression.
// Because only the left-hand parts can be sub-chains.
if grand_parent_logical_left.as_js_logical_expression() == Some(&parent) {
let grand_parent_right_chain = LogicalAndChain::from_expression(
normalized_optional_chain_like(grand_parent.right()?)?,
)?;
let result = grand_parent_right_chain.cmp_chain(self)?;
return match result {
LogicalAndChainOrdering::SubChain | LogicalAndChainOrdering::Equal => {
Ok(true)
}
LogicalAndChainOrdering::Different => Ok(false),
};
}
}
}
Ok(false)
}
/// This function compares two `LogicalAndChain` and returns `LogicalAndChainOrdering`
/// by comparing their `token_text_trimmed` for every `JsAnyExpression` node.
fn cmp_chain(&self, other: &LogicalAndChain) -> SyntaxResult<LogicalAndChainOrdering> {
let chain_ordering = match self.buf.len().cmp(&other.buf.len()) {
Ordering::Less => return Ok(LogicalAndChainOrdering::Different),
Ordering::Equal => LogicalAndChainOrdering::Equal,
Ordering::Greater => LogicalAndChainOrdering::SubChain,
};
for (main_expression, branch_expression) in self.buf.iter().zip(&other.buf) {
let (main_expression, branch_expression) = match (&main_expression, &branch_expression)
{
(
AnyJsExpression::JsCallExpression(main_expression),
AnyJsExpression::JsCallExpression(branch_expression),
) => (main_expression.callee()?, branch_expression.callee()?),
_ => (main_expression.clone(), branch_expression.clone()),
};
let (main_value_token, branch_value_token) = match (main_expression, branch_expression)
{
(
AnyJsExpression::JsComputedMemberExpression(main_expression),
AnyJsExpression::JsComputedMemberExpression(branch_expression),
) => match (main_expression.member()?, branch_expression.member()?) {
(
AnyJsExpression::JsIdentifierExpression(main_identifier),
AnyJsExpression::JsIdentifierExpression(branch_identifier),
) => (
main_identifier.name()?.value_token()?,
branch_identifier.name()?.value_token()?,
),
(
AnyJsExpression::AnyJsLiteralExpression(main_expression),
AnyJsExpression::AnyJsLiteralExpression(branch_expression),
) => (
main_expression.value_token()?,
branch_expression.value_token()?,
),
_ => return Ok(LogicalAndChainOrdering::Different),
},
(
AnyJsExpression::JsStaticMemberExpression(main_expression),
AnyJsExpression::JsStaticMemberExpression(branch_expression),
) => match (main_expression.member()?, branch_expression.member()?) {
(AnyJsName::JsName(main_name), AnyJsName::JsName(branch_name)) => {
(main_name.value_token()?, branch_name.value_token()?)
}
(
AnyJsName::JsPrivateName(main_name),
AnyJsName::JsPrivateName(branch_name),
) => (main_name.value_token()?, branch_name.value_token()?),
_ => return Ok(LogicalAndChainOrdering::Different),
},
(
AnyJsExpression::JsIdentifierExpression(main_expression),
AnyJsExpression::JsIdentifierExpression(branch_expression),
) => (
main_expression.name()?.value_token()?,
branch_expression.name()?.value_token()?,
),
_ => return Ok(LogicalAndChainOrdering::Different),
};
if main_value_token.token_text_trimmed() != branch_value_token.token_text_trimmed() {
return Ok(LogicalAndChainOrdering::Different);
}
}
Ok(chain_ordering)
}
/// This function returns a list of `JsAnyExpression` which we need to transform into an option chain expression.
fn optional_chain_expression_nodes(mut self) -> Option<VecDeque<AnyJsExpression>> {
let mut optional_chain_expression_nodes = VecDeque::with_capacity(self.buf.len());
// Take a head of a next sub-chain
// E.g. `foo && foo.bar && foo.bar.baz`
// The head is `foo.bar.baz` expression.
// The parent of the head is a logical expression `foo && foo.bar && foo.bar.baz`.
// The next chain head is a left part of the logical expression `foo && foo.bar`
let mut next_chain_head = self.head.parent::<JsLogicalExpression>()?.left().ok();
while let Some(expression) = next_chain_head.take() {
let expression = match expression {
// Extract a left `JsAnyExpression` from `JsBinaryExpression` if it's optional chain like
// ```js
// (foo === undefined) && foo.bar;
// ```
// is roughly equivalent to
// ```js
// foo && foo.bar;
// ```
AnyJsExpression::JsBinaryExpression(expression) => expression
.is_optional_chain_like()
.ok()?
.then_some(expression.left().ok()?)?,
expression => expression,
};
let head = match expression {
AnyJsExpression::JsLogicalExpression(logical) => {
if matches!(logical.operator().ok()?, JsLogicalOperator::LogicalAnd) {
// Here we move our sub-chain head over the chains of logical expression
next_chain_head = logical.left().ok();
logical.right().ok()?
} else {
return None;
}
}
AnyJsExpression::JsIdentifierExpression(_)
| AnyJsExpression::JsStaticMemberExpression(_)
| AnyJsExpression::JsComputedMemberExpression(_)
| AnyJsExpression::JsCallExpression(_) => expression,
_ => return None,
};
let branch =
LogicalAndChain::from_expression(normalized_optional_chain_like(head).ok()?)
.ok()?;
match self.cmp_chain(&branch).ok()? {
LogicalAndChainOrdering::SubChain => {
// Here we reduce our main `JsAnyExpression` buffer by splitting the main buffer.
// Let's say that we have two buffers:
// The main is `[foo, bar, baz]` and a branch is `[foo]`
// After splitting the main buffer will be `[foo]` and the tail will be `[bar, baz]`.
// It means that we need to transform `bar` (first tail expression) into the optional one.
let mut tail = self.buf.split_off(branch.buf.len());
if let Some(part) = tail.pop_front() {
optional_chain_expression_nodes.push_front(part)
};
}
LogicalAndChainOrdering::Equal => continue,
LogicalAndChainOrdering::Different => return None,
}
}
if optional_chain_expression_nodes.is_empty() {
return None;
}
Some(optional_chain_expression_nodes)
}
}
/// `LogicalOrLikeChain` handles cases with `JsLogicalExpression` which has `JsLogicalOperator::NullishCoalescing` or `JsLogicalOperator::LogicalOr` operator:
/// ```js
/// (foo || {}).bar;
/// (foo ?? {}).bar;
/// ((foo ?? {}).bar || {}).baz;
/// ```
/// The main idea of the `LogicalOrLikeChain`:
/// 1. Check that the current member expressions isn't in another `LogicalOrLikeChain`. We need to find the topmost member expression.
/// 2. Go down thought logical expressions and collect left and member expressions to buffer.
/// 3. Transform every left `JsAnyExpression` and member `JsAnyMemberExpression` expressions into optional `JsAnyMemberExpression`.
///
/// E.g. `((foo ?? {}).bar || {}).baz;`.
/// The member expression `(foo ?? {}).bar` isn't the topmost. We skip it.
/// `((foo ?? {}).bar || {}).baz;` is the topmost and it'll be a start point.
/// We start collecting pairs of a left and member expressions to buffer.
/// First expression is `((foo ?? {}).bar || {}).baz;`:
/// Buffer is `[((foo ?? {}).bar, ((foo ?? {}).bar || {}).baz;)]`
/// Next expressions is `((foo ?? {}).bar || {}).baz;`:
/// Buffer is `[(foo, (foo ?? {}).bar), ((foo ?? {}).bar, ((foo ?? {}).bar || {}).baz;)]`
/// Iterate buffer, take member expressions and replace object with left parts and make the expression optional chain:
/// `foo?.bar?.baz;`
///
#[derive(Debug)]
pub(crate) struct LogicalOrLikeChain {
member: AnyJsMemberExpression,
}
impl LogicalOrLikeChain {
/// Create a `LogicalOrLikeChain` if `JsLogicalExpression` is optional chain like and the `JsLogicalExpression` is inside member expression.
/// ```js
/// (foo || {}).bar;
/// ```
fn from_expression(logical: &JsLogicalExpression) -> Option<LogicalOrLikeChain> {
let is_right_empty_object = logical
.right()
.ok()?
// Handle case when a right expression is inside parentheses
// E.g. (foo || (({}))).bar;
.omit_parentheses()
.as_js_object_expression()?
.is_empty();
if !is_right_empty_object {
return None;
}
let member =
LogicalOrLikeChain::get_chain_parent_member(AnyJsExpression::from(logical.clone()))?;
Some(LogicalOrLikeChain { member })
}
/// This function checks if `LogicalOrLikeChain` is inside another parent `LogicalOrLikeChain`.
/// E.g.
/// `(foo ?? {}).bar` is inside `((foo ?? {}).bar || {}).baz;`
fn is_inside_another_chain(&self) -> bool {
LogicalOrLikeChain::get_chain_parent(self.member.clone()).map_or(false, |parent| {
parent
.as_js_logical_expression()
.filter(|parent_expression| {
matches!(
parent_expression.operator(),
Ok(JsLogicalOperator::NullishCoalescing | JsLogicalOperator::LogicalOr)
)
})
.and_then(LogicalOrLikeChain::from_expression)
.is_some()
})
}
/// This function returns a list of pairs `(JsAnyExpression, JsAnyMemberExpression)` which we need to transform into an option chain expression.
fn optional_chain_expression_nodes(
&self,
) -> VecDeque<(AnyJsExpression, AnyJsMemberExpression)> {
let mut chain = VecDeque::new();
// Start from the topmost member expression
let mut next_member_chain = Some(self.member.clone());
while let Some(member) = next_member_chain.take() {
let object = match member.object() {
Ok(object) => object,
_ => return chain,
};
// Handle case when a object expression is inside parentheses
// E.g. (((foo || {}))).bar;
let object = object.omit_parentheses();
if let AnyJsExpression::JsLogicalExpression(logical) = object {
let is_valid_operator = logical.operator().map_or(false, |operator| {
matches!(
operator,
JsLogicalOperator::NullishCoalescing | JsLogicalOperator::LogicalOr
)
});
if !is_valid_operator {
return chain;
}
let is_right_empty_object = logical
.right()
.ok()
.and_then(|right| {
right
// Handle case when a right expression is inside parentheses
// E.g. (foo || (({}))).bar;
.omit_parentheses()
.as_js_object_expression()
.map(|object| object.is_empty())
})
.unwrap_or(false);
if !is_right_empty_object {
return chain;
}
let left = match logical.left() {
Ok(left) => left,
Err(_) => return chain,
};
// Set next member expression from the left part
// Find next member expression
// E.g. `((foo || {}).baz() || {}).bar`
// If current member chain is `bar` the next member chain is baz.
// Need to downward traversal to find first `JsAnyExpression` which we can't include in chain
next_member_chain = LogicalOrLikeChain::get_member(left.clone());
chain.push_front((left, member))
}
}
chain
}
/// Traversal by parent to find the parent member of a chain.
fn get_chain_parent_member(expression: AnyJsExpression) -> Option<AnyJsMemberExpression> {
iter::successors(expression.parent::<AnyJsExpression>(), |expression| {
if matches!(expression, AnyJsExpression::JsParenthesizedExpression(_)) {
expression.parent::<AnyJsExpression>()
} else {
None
}
})
.last()
.and_then(|parent| {
let member = match parent {
AnyJsExpression::JsComputedMemberExpression(expression) => {
AnyJsMemberExpression::from(expression)
}
AnyJsExpression::JsStaticMemberExpression(expression) => {
AnyJsMemberExpression::from(expression)
}
_ => return None,
};
Some(member)
})
}
/// Traversal by parent to find the parent of a chain.
/// This function is opposite to the `get_member` function.
fn get_chain_parent(expression: AnyJsMemberExpression) -> Option<AnyJsExpression> {
iter::successors(expression.parent::<AnyJsExpression>(), |expression| {
if matches!(
expression,
AnyJsExpression::JsParenthesizedExpression(_)
| AnyJsExpression::JsAwaitExpression(_)
| AnyJsExpression::JsCallExpression(_)
| AnyJsExpression::JsNewExpression(_)
| AnyJsExpression::TsAsExpression(_)
| AnyJsExpression::TsSatisfiesExpression(_)
| AnyJsExpression::TsNonNullAssertionExpression(_)
| AnyJsExpression::TsTypeAssertionExpression(_)
) {
expression.parent::<AnyJsExpression>()
} else {
None
}
})
.last()
}
/// Downward traversal to find the member.
/// E.g. `((foo || {}).baz() || {}).bar`
/// If current member chain is `bar` the next member chain is baz.
/// Need to downward traversal to find first `JsAnyExpression` which we can't include in chain.
fn get_member(expression: AnyJsExpression) -> Option<AnyJsMemberExpression> {
let expression = iter::successors(Some(expression), |expression| match expression {
AnyJsExpression::JsParenthesizedExpression(expression) => expression.expression().ok(),
AnyJsExpression::JsAwaitExpression(expression) => expression.argument().ok(),
AnyJsExpression::JsCallExpression(expression) => expression.callee().ok(),
| rust | MIT | 392d188a49d70e495f13b1bb08cd7d9c43690f9b | 2026-01-04T15:38:12.578592Z | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.